]> git.ipfire.org Git - thirdparty/man-pages.git/blob - man2/futex.2
futex.2: Minor wording fixes
[thirdparty/man-pages.git] / man2 / futex.2
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 .\" at http://thread.gmane.org/gmane.linux.kernel/1703405/focus=1873242
21 .\"
22 .TH FUTEX 2 2014-05-21 "Linux" "Linux Programmer's Manual"
23 .SH NAME
24 futex \- fast user-space locking
25 .SH SYNOPSIS
26 .nf
27 .sp
28 .B "#include <linux/futex.h>"
29 .B "#include <sys/time.h>"
30 .sp
31 .BI "int futex(int *" uaddr ", int " futex_op ", int " val ,
32 .BI " const struct timespec *" timeout , \
33 " \fR /* or: \fBuint32_t \fIval2\fP */
34 .BI " int *" uaddr2 ", int " val3 );
35 .fi
36
37 .IR Note :
38 There is no glibc wrapper for this system call; see NOTES.
39 .SH DESCRIPTION
40 .PP
41 The
42 .BR futex ()
43 system call provides a method for waiting until a certain condition becomes
44 true.
45 It is typically used as a blocking construct in the context of
46 shared-memory synchronization.
47 When using futexes, the majority of
48 the synchronization operations are performed in user space.
49 The user-space program employs
50 .BR futex ()
51 operations only when it is likely that the program has to block for
52 a longer time until the condition becomes true.
53 The program uses another
54 .BR futex ()
55 operation to wake anyone waiting for a particular condition.
56
57 A futex is a 32-bit value\(emreferred to below as a
58 .IR "futex word" \(emwhose
59 address is supplied to the
60 .BR futex ()
61 system call.
62 (Futexes are 32-bits in size on all platforms, including 64-bit systems.)
63 All futex operations are governed by this value.
64 In order to share a futex between processes,
65 the futex is placed in a region of shared memory,
66 created using (for example)
67 .BR mmap (2)
68 or
69 .BR shmat (2).
70 (Thus the futex word may have different
71 virtual addresses in different processes,
72 but these addresses all refer to the same location in physical memory.)
73
74 When executing a futex operation that requests to block a thread,
75 the kernel will block only if the futex word has the value that the
76 calling thread supplied (as one of the arguments of the
77 .BR futex ()
78 call) as the expected value of the futex word.
79 The loading of the futex word's value,
80 the comparison of that value with the expected value,
81 and the actual blocking will happen atomically and totally
82 ordered with respect to concurrently executing futex
83 operations on the same futex word.
84 Thus, the futex word is used to connect the synchronization in user space
85 with the implementation of blocking by the kernel.
86 Analogously to an atomic
87 compare-and-exchange operation that potentially changes shared memory,
88 blocking via a futex is an atomic compare-and-block operation.
89 .\" FIXME(Torvald Riegel):
90 .\" Eventually we want to have some text in NOTES to satisfy
91 .\" the reference in the following sentence
92 .\" See NOTES for
93 .\" a detailed specification of the synchronization semantics.
94
95 One example use of futexes is for implementing locks.
96 The state of the lock (i.e., acquired or not acquired)
97 can be represented as an atomically accessed flag in shared memory.
98 In the uncontended case,
99 a thread can access or modify the lock state with atomic instructions
100 for example atomically changing it from not acquired to acquired
101 using an atomic compare-and-exchange instruction.
102 (Such instructions are performed entirely in user mode,
103 and the kernel maintains no information about the lock state.)
104 On the other hand, a thread may be unable to acquire a lock because
105 it is already acquired by another thread.
106 It then may pass the lock's flag as a futex word and the value
107 representing the acquired state as the expected value to a
108 .BR futex ()
109 wait operation.
110 This
111 .BR futex ()
112 call will block if and only if the lock is still acquired.
113 When releasing the lock, a thread has to first reset the
114 lock state to not acquired and then execute a futex
115 operation that wakes threads blocked on the lock flag used as a futex word
116 (this can be be further optimized to avoid unnecessary wake-ups).
117 See
118 .BR futex (7)
119 for more detail on how to use futexes.
120
121 Besides the basic wait and wake-up futex functionality, there are further
122 futex operations aimed at supporting more complex use cases.
123 Also note that
124 no explicit initialization or destruction are necessary to use futexes;
125 the kernel maintains a futex
126 (i.e., the kernel-internal implementation artifact)
127 only while operations such as
128 .BR FUTEX_WAIT ,
129 described below, are being performed on a particular futex word.
130 .\"
131 .SS Arguments
132 The
133 .I uaddr
134 argument points to the futex word.
135 On all platforms, futexes are four-byte
136 integers that must be aligned on a four-byte boundary.
137 The operation to perform on the futex is specified in the
138 .I futex_op
139 argument;
140 .IR val
141 is a value whose meaning and purpose depends on
142 .IR futex_op .
143
144 The remaining arguments
145 .RI ( timeout ,
146 .IR uaddr2 ,
147 and
148 .IR val3 )
149 are required only for certain of the futex operations described below.
150 Where one of these arguments is not required, it is ignored.
151
152 For several blocking operations, the
153 .I timeout
154 argument is a pointer to a
155 .IR timespec
156 structure that specifies a timeout for the operation.
157 However, notwithstanding the prototype shown above, for some operations,
158 the least significant four bytes are used as an integer whose meaning
159 is determined by the operation.
160 For these operations, the kernel casts the
161 .I timeout
162 value first to
163 .IR "unsigned long",
164 then to
165 .IR uint32_t ,
166 and in the remainder of this page, this argument is referred to as
167 .I val2
168 when interpreted in this fashion.
169
170 Where it is required, the
171 .IR uaddr2
172 argument is a pointer to a second futex word that is employed
173 by the operation.
174 The interpretation of the final integer argument,
175 .IR val3 ,
176 depends on the operation.
177 .\"
178 .\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
179 .\"
180 .SS Futex operations
181 The
182 .I futex_op
183 argument consists of two parts:
184 a command that specifies the operation to be performed,
185 bit-wise ORed with zero or or more options that
186 modify the behaviour of the operation.
187 The options that may be included in
188 .I futex_op
189 are as follows:
190 .TP
191 .BR FUTEX_PRIVATE_FLAG " (since Linux 2.6.22)"
192 .\" commit 34f01cc1f512fa783302982776895c73714ebbc2
193 This option bit can be employed with all futex operations.
194 It tells the kernel that the futex is process-private and not shared
195 with another process (i.e., it is being used for synchronization
196 only between threads of the same process).
197 This allows the kernel to make some additional performance optimizations.
198 .\" I.e., It allows the kernel choose the fast path for validating
199 .\" the user-space address and avoids expensive VMA lookups,
200 .\" taking reference counts on file backing store, and so on.
201
202 As a convenience,
203 .IR <linux/futex.h>
204 defines a set of constants with the suffix
205 .BR _PRIVATE
206 that are equivalents of all of the operations listed below,
207 .\" except the obsolete FUTEX_FD, for which the "private" flag was
208 .\" meaningless
209 but with the
210 .BR FUTEX_PRIVATE_FLAG
211 ORed into the constant value.
212 Thus, there are
213 .BR FUTEX_WAIT_PRIVATE ,
214 .BR FUTEX_WAKE_PRIVATE ,
215 and so on.
216 .TP
217 .BR FUTEX_CLOCK_REALTIME " (since Linux 2.6.28)"
218 .\" commit 1acdac104668a0834cfa267de9946fac7764d486
219 This option bit can be employed only with the
220 .BR FUTEX_WAIT_BITSET
221 and
222 .BR FUTEX_WAIT_REQUEUE_PI
223 operations.
224
225 If this option is set, the kernel treats
226 .I timeout
227 as an absolute time based on
228 .BR CLOCK_REALTIME .
229
230 If this option is not set, the kernel treats
231 .I timeout
232 as relative time,
233 .\" FIXME XXX I added CLOCK_MONOTONIC below. Okay?
234 measured against the
235 .BR CLOCK_MONOTONIC
236 clock.
237 .PP
238 The operation specified in
239 .I futex_op
240 is one of the following:
241 .\"
242 .\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
243 .\"
244 .TP
245 .BR FUTEX_WAIT " (since Linux 2.6.0)"
246 .\" Strictly speaking, since some time in 2.5.x
247 This operation tests that the value at the
248 futex word pointed to by the address
249 .I uaddr
250 still contains the expected value
251 .IR val ,
252 and if so, then sleeps waiting for a
253 .B FUTEX_WAKE
254 operation on the futex word.
255 The load of the value of the futex word is an atomic memory
256 access (i.e., using atomic machine instructions of the respective
257 architecture).
258 This load, the comparison with the expected value, and
259 starting to sleep are performed atomically
260 .\" FIXME: Torvald, what do you mean by "totally odered" here?
261 .\" (Also used at various other points in the page.)
262 and totally ordered
263 with respect to other futex operations on the same futex word.
264 If the thread starts to sleep,
265 it is considered a waiter on this futex word.
266 If the futex value does not match
267 .IR val ,
268 then the call fails immediately with the error
269 .BR EAGAIN .
270
271 The purpose of the comparison with the expected value is to prevent lost
272 wake-ups.
273 If another thread changed the value of the futex word after the
274 calling thread decided to block based on the prior value,
275 and if the other thread executed a
276 .BR FUTEX_WAKE
277 operation (or similar wake-up) after the value change and before this
278 .BR FUTEX_WAIT
279 operation, then the latter will observe the value change and will not start
280 to sleep.
281
282 If the
283 .I timeout
284 argument is non-NULL, its contents specify a relative timeout for the wait,
285 .\" FIXME XXX I added CLOCK_MONOTONIC below. Okay?
286 measured according to the
287 .BR CLOCK_MONOTONIC
288 clock.
289 (This interval will be rounded up to the system clock granularity,
290 and kernel scheduling delays mean that the
291 blocking interval may overrun by a small amount.)
292 If
293 .I timeout
294 is NULL, the call blocks indefinitely.
295
296 The arguments
297 .I uaddr2
298 and
299 .I val3
300 are ignored.
301
302 .\" FIXME(Torvald) I think we should remove this. Or maybe adapt to a
303 .\" different example.
304 .\" For
305 .\" .BR futex (7),
306 .\" this call is executed if decrementing the count gave a negative value
307 .\" (indicating contention),
308 .\" and will sleep until another process or thread releases
309 .\" the futex and executes the
310 .\" .B FUTEX_WAKE
311 .\" operation.
312 .\"
313 .\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
314 .\"
315 .TP
316 .BR FUTEX_WAKE " (since Linux 2.6.0)"
317 .\" Strictly speaking, since Linux 2.5.x
318 This operation wakes at most
319 .I val
320 of the waiters that are waiting (e.g., inside
321 .BR FUTEX_WAIT )
322 on the futex word at the address
323 .IR uaddr .
324 Most commonly,
325 .I val
326 is specified as either 1 (wake up a single waiter) or
327 .BR INT_MAX
328 (wake up all waiters).
329 No guarantee is provided about which waiters are awoken
330 (e.g., a waiter with a higher scheduling priority is not guaranteed
331 to be awoken in preference to a waiter with a lower priority).
332
333 The arguments
334 .IR timeout ,
335 .IR uaddr2 ,
336 and
337 .I val3
338 are ignored.
339
340 .\" FIXME(Torvald) I think we should remove this. Or maybe adapt to
341 .\" a different example.
342 .\" For
343 .\" .BR futex (7),
344 .\" this is executed if incrementing the count showed that
345 .\" there were waiters,
346 .\" once the futex value has been set to 1
347 .\" (indicating that it is available).
348 .\"
349 .\" FIXME How does "incrementing the count show that there were waiters"?
350 .\"
351 .\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
352 .\"
353 .TP
354 .BR FUTEX_FD " (from Linux 2.6.0 up to and including Linux 2.6.25)"
355 .\" Strictly speaking, from Linux 2.5.x to 2.6.25
356 This operation creates a file descriptor that is associated with
357 the futex at
358 .IR uaddr .
359 The caller must close the returned file descriptor after use.
360 When another process or thread performs a
361 .BR FUTEX_WAKE
362 on the futex word, the file descriptor indicates as being readable with
363 .BR select (2),
364 .BR poll (2),
365 and
366 .BR epoll (7)
367
368 The file descriptor can be used to obtain asynchronous notifications: if
369 .I val
370 is nonzero, then when another process or thread executes a
371 .BR FUTEX_WAKE ,
372 the caller will receive the signal number that was passed in
373 .IR val .
374
375 The arguments
376 .IR timeout ,
377 .I uaddr2
378 and
379 .I val3
380 are ignored.
381
382 .\" FIXME(Torvald) We never define "upped". Maybe just remove the
383 .\" following sentence?
384 To prevent race conditions, the caller should test if the futex has
385 been upped after
386 .B FUTEX_FD
387 returns.
388
389 Because it was inherently racy,
390 .B FUTEX_FD
391 has been removed
392 .\" commit 82af7aca56c67061420d618cc5a30f0fd4106b80
393 from Linux 2.6.26 onward.
394 .\"
395 .\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
396 .\"
397 .TP
398 .BR FUTEX_REQUEUE " (since Linux 2.6.0)"
399 .\" Strictly speaking: from Linux 2.5.70
400 .\" FIXME(Torvald) Is there some indication that FUTEX_REQUEUE is broken
401 .\" in general, or is this comment implicitly speaking about the
402 .\" condvar (?) use case? If the latter we might want to weaken the
403 .\" advice below a little.
404 .\" [Anyone else have input on this?]
405 .\"
406 .IR "Avoid using this operation" .
407 It is broken for its intended purpose.
408 Use
409 .BR FUTEX_CMP_REQUEUE
410 instead.
411
412 This operation performs the same task as
413 .BR FUTEX_CMP_REQUEUE ,
414 except that no check is made using the value in
415 .IR val3 .
416 (The argument
417 .I val3
418 is ignored.)
419 .\"
420 .\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
421 .\"
422 .TP
423 .BR FUTEX_CMP_REQUEUE " (since Linux 2.6.7)"
424 This operation first checks whether the location
425 .I uaddr
426 still contains the value
427 .IR val3 .
428 If not, the operation fails with the error
429 .BR EAGAIN .
430 Otherwise, the operation wakes up a maximum of
431 .I val
432 waiters that are waiting on the futex at
433 .IR uaddr .
434 If there are more than
435 .I val
436 waiters, then the remaining waiters are removed
437 from the wait queue of the source futex at
438 .I uaddr
439 and added to the wait queue of the target futex at
440 .IR uaddr2 .
441 The
442 .I val2
443 argument specifies an upper limit on the number of waiters
444 that are requeued to the futex at
445 .IR uaddr2 .
446
447 .\" FIXME(Torvald) Is the following correct? Or is just the decision
448 .\" which threads to wake or requeue part of the atomic operation?
449 The load from
450 .I uaddr
451 is an atomic memory access (i.e., using atomic machine instructions of
452 the respective architecture).
453 This load, the comparison with
454 .IR val3 ,
455 and the requeueing of any waiters are performed atomically and totally
456 ordered with respect to other operations on the same futex word.
457
458 This operation was added as a replacement for the earlier
459 .BR FUTEX_REQUEUE .
460 The difference is that the check of the value at
461 .I uaddr
462 can be used to ensure that requeueing happens only under certain
463 conditions.
464 Both operations can be used to avoid a "thundering herd" effect when
465 .B FUTEX_WAKE
466 is used and all of the waiters that are woken need to acquire
467 another futex.
468
469 .\" FIXME Please review the following new paragraph to see if it is
470 .\" accurate.
471 Typical values to specify for
472 .I val
473 are 0 or or 1.
474 (Specifying
475 .BR INT_MAX
476 is not useful, because it would make the
477 .BR FUTEX_CMP_REQUEUE
478 operation equivalent to
479 .BR FUTEX_WAKE .)
480 The limit value specified via
481 .I val2
482 is typically either 1 or
483 .BR INT_MAX .
484 (Specifying the argument as 0 is not useful, because it would make the
485 .BR FUTEX_CMP_REQUEUE
486 operation equivalent to
487 .BR FUTEX_WAIT .)
488 .\"
489 .\" FIXME Here, it would be helpful to have an example of how
490 .\" FUTEX_CMP_REQUEUE might be used, at the same time illustrating
491 .\" why FUTEX_WAKE is unsuitable for the same use case.
492 .\"
493 .\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
494 .\"
495 .\" FIXME I added a lengthy piece of text on FUTEX_WAKE_OP text,
496 .\" and I'd be happy if someone checked it.
497 .TP
498 .BR FUTEX_WAKE_OP " (since Linux 2.6.14)"
499 .\" commit 4732efbeb997189d9f9b04708dc26bf8613ed721
500 .\" Author: Jakub Jelinek <jakub@redhat.com>
501 .\" Date: Tue Sep 6 15:16:25 2005 -0700
502 .\" FIXME(Torvald) The glibc condvar implementation is currently being
503 .\" revised (e.g., to not use an internal lock anymore).
504 .\" It is probably more future-proof to remove this paragraph.
505 .\" [Torvald, do you have an update here?]
506 This operation was added to support some user-space use cases
507 where more than one futex must be handled at the same time.
508 The most notable example is the implementation of
509 .BR pthread_cond_signal (3),
510 which requires operations on two futexes,
511 the one used to implement the mutex and the one used in the implementation
512 of the wait queue associated with the condition variable.
513 .BR FUTEX_WAKE_OP
514 allows such cases to be implemented without leading to
515 high rates of contention and context switching.
516
517 The
518 .BR FUTEX_WAIT_OP
519 operation is equivalent to executing the following code atomically
520 and totally ordered with respect to other futex operations on
521 any of the two supplied futex words:
522
523 .in +4n
524 .nf
525 int oldval = *(int *) uaddr2;
526 *(int *) uaddr2 = oldval \fIop\fP \fIoparg\fP;
527 futex(uaddr, FUTEX_WAKE, val, 0, 0, 0);
528 if (oldval \fIcmp\fP \fIcmparg\fP)
529 futex(uaddr2, FUTEX_WAKE, val2, 0, 0, 0);
530 .fi
531 .in
532
533 In other words,
534 .BR FUTEX_WAIT_OP
535 does the following:
536 .RS
537 .IP * 3
538 saves the original value of the futex word at
539 .IR uaddr2
540 and performs an operation to modify the value of the futex at
541 .IR uaddr2 ;
542 this is an atomic read-modify-write memory access (i.e., using atomic
543 machine instructions of the respective architecture)
544 .IP *
545 wakes up a maximum of
546 .I val
547 waiters on the futex for the futex word at
548 .IR uaddr ;
549 and
550 .IP *
551 dependent on the results of a test of the original value of the
552 futex word at
553 .IR uaddr2 ,
554 wakes up a maximum of
555 .I val2
556 waiters on the futex for the futex word at
557 .IR uaddr2 .
558 .RE
559 .IP
560 The operation and comparison that are to be performed are encoded
561 in the bits of the argument
562 .IR val3 .
563 Pictorially, the encoding is:
564
565 .in +8n
566 .nf
567 +---+---+-----------+-----------+
568 |op |cmp| oparg | cmparg |
569 +---+---+-----------+-----------+
570 4 4 12 12 <== # of bits
571 .fi
572 .in
573
574 Expressed in code, the encoding is:
575
576 .in +4n
577 .nf
578 #define FUTEX_OP(op, oparg, cmp, cmparg) \\
579 (((op & 0xf) << 28) | \\
580 ((cmp & 0xf) << 24) | \\
581 ((oparg & 0xfff) << 12) | \\
582 (cmparg & 0xfff))
583 .fi
584 .in
585
586 In the above,
587 .I op
588 and
589 .I cmp
590 are each one of the codes listed below.
591 The
592 .I oparg
593 and
594 .I cmparg
595 components are literal numeric values, except as noted below.
596
597 The
598 .I op
599 component has one of the following values:
600
601 .in +4n
602 .nf
603 FUTEX_OP_SET 0 /* uaddr2 = oparg; */
604 FUTEX_OP_ADD 1 /* uaddr2 += oparg; */
605 FUTEX_OP_OR 2 /* uaddr2 |= oparg; */
606 FUTEX_OP_ANDN 3 /* uaddr2 &= ~oparg; */
607 FUTEX_OP_XOR 4 /* uaddr2 ^= oparg; */
608 .fi
609 .in
610
611 In addition, bit-wise ORing the following value into
612 .I op
613 causes
614 .IR "(1\ <<\ oparg)"
615 to be used as the operand:
616
617 .in +4n
618 .nf
619 FUTEX_OP_ARG_SHIFT 8 /* Use (1 << oparg) as operand */
620 .fi
621 .in
622
623 The
624 .I cmp
625 field is one of the following:
626
627 .in +4n
628 .nf
629 FUTEX_OP_CMP_EQ 0 /* if (oldval == cmparg) wake */
630 FUTEX_OP_CMP_NE 1 /* if (oldval != cmparg) wake */
631 FUTEX_OP_CMP_LT 2 /* if (oldval < cmparg) wake */
632 FUTEX_OP_CMP_LE 3 /* if (oldval <= cmparg) wake */
633 FUTEX_OP_CMP_GT 4 /* if (oldval > cmparg) wake */
634 FUTEX_OP_CMP_GE 5 /* if (oldval >= cmparg) wake */
635 .fi
636 .in
637
638 The return value of
639 .BR FUTEX_WAKE_OP
640 is the sum of the number of waiters woken on the futex
641 .IR uaddr
642 plus the number of waiters woken on the futex
643 .IR uaddr2 .
644 .\"
645 .\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
646 .\"
647 .TP
648 .BR FUTEX_WAIT_BITSET " (since Linux 2.6.25)"
649 .\" commit cd689985cf49f6ff5c8eddc48d98b9d581d9475d
650 This operation is like
651 .BR FUTEX_WAIT
652 except that
653 .I val3
654 is used to provide a 32-bit bitset to the kernel.
655 This bitset is stored in the kernel-internal state of the waiter.
656 See the description of
657 .BR FUTEX_WAKE_BITSET
658 for further details.
659
660 The
661 .BR FUTEX_WAIT_BITSET
662 operation also interprets the
663 .I timeout
664 argument differently from
665 .BR FUTEX_WAIT .
666 See the discussion of
667 .BR FUTEX_CLOCK_REALTIME ,
668 above.
669
670 The
671 .I uaddr2
672 argument is ignored.
673 .\"
674 .\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
675 .\"
676 .TP
677 .BR FUTEX_WAKE_BITSET " (since Linux 2.6.25)"
678 .\" commit cd689985cf49f6ff5c8eddc48d98b9d581d9475d
679 This operation is the same as
680 .BR FUTEX_WAKE
681 except that the
682 .I val3
683 argument is used to provide a 32-bit bitset to the kernel.
684 This bitset is used to select which waiters should be woken up.
685 The selection is done by a bit-wise AND of the "wake" bitset
686 (i.e., the value in
687 .IR val3 )
688 and the bitset which is stored in the kernel-internal
689 state of the waiter (the "wait" bitset that is set using
690 .BR FUTEX_WAIT_BITSET ).
691 All of the waiters for which the result of the AND is nonzero are woken up;
692 the remaining waiters are left sleeping.
693
694 .\" FIXME XXX Is this next paragraph that I added okay?
695 The effect of
696 .BR FUTEX_WAIT_BITSET
697 and
698 .BR FUTEX_WAKE_BITSET
699 is to allow selective wake-ups among multiple waiters that are blocked
700 on the same futex.
701 Note, however, that using this bitset multiplexing feature on a
702 futex is less efficient than simply using multiple futexes,
703 because employing bitset multiplexing requires the kernel
704 to check all waiters on a futex,
705 including those that are not interested in being woken up
706 (i.e., they do not have the relevant bit set in their "wait" bitset).
707 .\" According to http://locklessinc.com/articles/futex_cheat_sheet/:
708 .\"
709 .\" "The original reason for the addition of these extensions
710 .\" was to improve the performance of pthread read-write locks
711 .\" in glibc. However, the pthreads library no longer uses the
712 .\" same locking algorithm, and these extensions are not used
713 .\" without the bitset parameter being all ones.
714 .\"
715 .\" The page goes on to note that the FUTEX_WAIT_BITSET operation
716 .\" is nevertheless used (with a bitset of all ones) in order to
717 .\" obtain the absolute timeout functionality that is useful
718 .\" for efficiently implementing Pthreads APIs (which use absolute
719 .\" timeouts); FUTEX_WAIT provides only relative timeouts.
720
721 The
722 .I uaddr2
723 and
724 .I timeout
725 arguments are ignored.
726
727 The
728 .BR FUTEX_WAIT
729 and
730 .BR FUTEX_WAKE
731 operations correspond to
732 .BR FUTEX_WAIT_BITSET
733 and
734 .BR FUTEX_WAKE_BITSET
735 operations where the bitsets are all ones.
736 .\"
737 .\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
738 .\"
739 .SS Priority-inheritance futexes
740 Linux supports priority-inheritance (PI) futexes in order to handle
741 priority-inversion problems that can be encountered with
742 normal futex locks.
743 Priority inversion is the problem that occurs when a high-priority
744 task is blocked waiting to acquire a lock held by a low-priority task,
745 while tasks at an intermediate priority continuously preempt
746 the low-priority task from the CPU.
747 Consequently, the low-priority task makes no progress toward
748 releasing the lock, and the high-priority task remains blocked.
749
750 Priority inheritance is a mechanism for dealing with
751 the priority-inversion problem.
752 With this mechanism, when a high-priority task becomes blocked
753 by a lock held by a low-priority task,
754 the latter's priority is temporarily raised to that of the former,
755 so that it is not preempted by any intermediate level tasks,
756 and can thus make progress toward releasing the lock.
757 To be effective, priority inheritance must be transitive,
758 meaning that if a high-priority task blocks on a lock
759 held by a lower-priority task that is itself blocked by lock
760 held by another intermediate-priority task
761 (and so on, for chains of arbitrary length),
762 then both of those tasks
763 (or more generally, all of the tasks in a lock chain)
764 have their priorities raised to be the same as the high-priority task.
765
766 .\" FIXME XXX The following is my attempt at a definition of PI futexes,
767 .\" based on mail discussions with Darren Hart. Does it seem okay?
768 From a user-space perspective,
769 what makes a futex PI-aware is a policy agreement between user space
770 and the kernel about the value of the futex word (described in a moment),
771 coupled with the use of the PI futex operations described below
772 (in particular,
773 .BR FUTEX_LOCK_PI ,
774 .BR FUTEX_TRYLOCK_PI ,
775 and
776 .BR FUTEX_CMP_REQUEUE_PI ).
777 .\" Quoting Darren Hart:
778 .\" These opcodes paired with the PI futex value policy (described below)
779 .\" defines a "futex" as PI aware. These were created very specifically
780 .\" in support of PI pthread_mutexes, so it makes a lot more sense to
781 .\" talk about a PI aware pthread_mutex, than a PI aware futex, since
782 .\" there is a lot of policy and scaffolding that has to be built up
783 .\" around it to use it properly (this is what a PI pthread_mutex is).
784
785 .\" FIXME XXX ===== Start of adapted Hart/Guniguntala text =====
786 .\" The following text is drawn from the Hart/Guniguntala paper
787 .\" (listed in SEE ALSO), but I have reworded some pieces
788 .\" significantly. Please check it.
789 .\"
790 The PI futex operations described below differ from the other
791 futex operations in that they impose policy on the use of the value of the
792 futex word:
793 .IP * 3
794 If the lock is not acquired, the futex word's value shall be 0.
795 .IP *
796 If the lock is acquired, the futex word's value shall
797 be the thread ID (TID;
798 see
799 .BR gettid (2))
800 of the owning thread.
801 .IP *
802 .\" FIXME XXX In the following line, I added "the lock is owned and". Okay?
803 If the lock is owned and there are threads contending for the lock,
804 then the
805 .B FUTEX_WAITERS
806 bit shall be set in the futex word's value; in other words, this value is:
807
808 FUTEX_WAITERS | TID
809
810 .PP
811 Note that a PI futex word never just has the value
812 .BR FUTEX_WAITERS ,
813 which is a permissible state for non-PI futexes.
814
815 With this policy in place,
816 a user-space application can acquire an unacquired
817 lock or release a lock that no other threads try to acquire using atomic
818 instructions executed in user mode
819 (e.g., a compare-and-swap operation such as
820 .I cmpxchg
821 on the x86 architecture).
822 Acquiring a lock simply consists of using compare-and-swap to atomically
823 set the futex word's value to the caller's TID if its previous value was 0.
824 Releasing a lock requires using compare-and-swap to set the futex word's
825 value to 0 if the previous value was the expected TID.
826
827 If a futex is already acquired (i.e., has a nonzero value),
828 waiters must employ the
829 .B FUTEX_LOCK_PI
830 operation to acquire the lock.
831 If other threads are waiting for the lock, then the
832 .B FUTEX_WAITERS
833 bit is set in the futex value;
834 in this case, the lock owner must employ the
835 .B FUTEX_UNLOCK_PI
836 operation to release the lock.
837
838 In the cases where callers are forced into the kernel
839 (i.e., required to perform a
840 .BR futex ()
841 call),
842 they then deal directly with a so-called RT-mutex,
843 a kernel locking mechanism which implements the required
844 priority-inheritance semantics.
845 After the RT-mutex is acquired, the futex value is updated accordingly,
846 before the calling thread returns to user space.
847 .\" FIXME ===== End of adapted Hart/Guniguntala text =====
848
849 It is important to note
850 .\" FIXME We need some explanation in the following paragraph of *why*
851 .\" it is important to note that "the kernel will update the
852 .\" futex word's value prior to returning to user space".
853 .\" Can someone explain?
854 that the kernel will update the futex word's value prior
855 to returning to user space.
856 Unlike the other futex operations described above,
857 the PI futex operations are designed
858 for the implementation of very specific IPC mechanisms.
859 .\"
860 .\" FIXME XXX In discussing errors for FUTEX_CMP_REQUEUE_PI, Darren Hart
861 .\" made the observation that "EINVAL is returned if the non-pi
862 .\" to pi or op pairing semantics are violated."
863 .\" Probably there needs to be a general statement about this
864 .\" requirement, probably located at about this point in the page.
865 .\" Darren (or someone else), care to take a shot at this?
866 .\"
867 .\" FIXME Somewhere on this page (I guess under the discussion of PI
868 .\" futexes) we need a discussion of the FUTEX_OWNER_DIED bit.
869 .\" Can someone propose a text?
870
871 PI futexes are operated on by specifying one of the following values in
872 .IR futex_op :
873 .\"
874 .\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
875 .\"
876 .TP
877 .BR FUTEX_LOCK_PI " (since Linux 2.6.18)"
878 .\" commit c87e2837be82df479a6bae9f155c43516d2feebc
879 .\"
880 .\" FIXME I did some significant rewording of tglx's text to create
881 .\" the text below.
882 .\" Please check the following paragraph, in case I injected
883 .\" errors.
884 .\"
885 This operation is used after after an attempt to acquire
886 the lock via an atomic user-mode instruction failed
887 because the futex word has a nonzero value\(emspecifically,
888 because it contained the namespace-specific TID of the lock owner.
889 .\" FIXME In the preceding line, what does "namespace-specific" mean?
890 .\" (I kept those words from tglx.)
891 .\" That is, what kind of namespace are we talking about?
892 .\" (I suppose we are talking PID namespaces here, but I want to
893 .\" be sure.)
894
895 The operation checks the value of the futex word at the address
896 .IR uaddr .
897 If the value is 0, then the kernel tries to atomically set
898 the futex value to the caller's TID.
899 .\" FIXME What would be the cause(s) of failure referred to
900 .\" in the following sentence?
901 If that fails,
902 or the futex word's value is nonzero,
903 the kernel atomically sets the
904 .B FUTEX_WAITERS
905 bit, which signals the futex owner that it cannot unlock the futex in
906 user space atomically by setting the futex value to 0.
907 After that, the kernel tries to find the thread which is
908 associated with the owner TID,
909 .\" FIXME Could I get a bit more detail on the next two lines?
910 .\" What is "creates or reuses kernel state" about?
911 .\" (I think this needs to be clearer in the page)
912 creates or reuses kernel state on behalf of the owner
913 and attaches the waiter to it.
914 .\" FIXME In the next line, what type of "priority" are we talking about?
915 .\" Realtime priorities for SCHED_FIFO and SCHED_RR?
916 .\" Or something else?
917 The enqueueing of the waiter is in descending priority order if more
918 than one waiter exists.
919 .\" FIXME What does "bandwidth" refer to in the next line?
920 The owner inherits either the priority or the bandwidth of the waiter.
921 .\" FIXME In the preceding line, what determines whether the
922 .\" owner inherits the priority versus the bandwidth?
923 .\"
924 .\" FIXME Could I get some help translating the next sentence into
925 .\" something that user-space developers (and I) can understand?
926 .\" In particular, what are "nested locks" in this context?
927 This inheritance follows the lock chain in the case of
928 nested locking and performs deadlock detection.
929
930 .\" FIXME tglx said "The timeout argument is handled as described in
931 .\" FUTEX_WAIT." However, it appears to me that this is not right.
932 .\" Is the following formulation correct?
933 The
934 .I timeout
935 argument provides a timeout for the lock attempt.
936 It is interpreted as an absolute time, measured against the
937 .BR CLOCK_REALTIME
938 clock.
939 If
940 .I timeout
941 is NULL, the operation will block indefinitely.
942
943 The
944 .IR uaddr2 ,
945 .IR val ,
946 and
947 .IR val3
948 arguments are ignored.
949 .\"
950 .\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
951 .\"
952 .TP
953 .BR FUTEX_TRYLOCK_PI " (since Linux 2.6.18)"
954 .\" commit c87e2837be82df479a6bae9f155c43516d2feebc
955 This operation tries to acquire the futex at
956 .IR uaddr .
957 .\" FIXME I think it would be helpful here to say a few more words about
958 .\" the difference(s) between FUTEX_LOCK_PI and FUTEX_TRYLOCK_PI.
959 .\" Can someone propose something?
960 .\"
961 .\" FIXME(Torvald) Additionally, we claim above that just FUTEX_WAITERS
962 .\" is never an allowed state.
963 It deals with the situation where the TID value at
964 .I uaddr
965 is 0, but the
966 .B FUTEX_WAITERS
967 bit is set.
968 .\" FIXME How does the situation in the previous sentence come about?
969 .\" Probably it would be helpful to say something about that in
970 .\" the man page.
971 .\" FIXME And *how* does FUTEX_TRYLOCK_PI deal with this situation?
972 User space cannot handle this condition in a race-free manner
973
974 The
975 .IR uaddr2 ,
976 .IR val ,
977 .IR timeout ,
978 and
979 .IR val3
980 arguments are ignored.
981 .\"
982 .\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
983 .\"
984 .TP
985 .BR FUTEX_UNLOCK_PI " (since Linux 2.6.18)"
986 .\" commit c87e2837be82df479a6bae9f155c43516d2feebc
987 This operation wakes the top priority waiter that is waiting in
988 .B FUTEX_LOCK_PI
989 on the futex address provided by the
990 .I uaddr
991 argument.
992
993 This is called when the user space value at
994 .I uaddr
995 cannot be changed atomically from a TID (of the owner) to 0.
996
997 The
998 .IR uaddr2 ,
999 .IR val ,
1000 .IR timeout ,
1001 and
1002 .IR val3
1003 arguments are ignored.
1004 .\"
1005 .\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
1006 .\"
1007 .TP
1008 .BR FUTEX_CMP_REQUEUE_PI " (since Linux 2.6.31)"
1009 .\" commit 52400ba946759af28442dee6265c5c0180ac7122
1010 This operation is a PI-aware variant of
1011 .BR FUTEX_CMP_REQUEUE .
1012 It requeues waiters that are blocked via
1013 .B FUTEX_WAIT_REQUEUE_PI
1014 on
1015 .I uaddr
1016 from a non-PI source futex
1017 .RI ( uaddr )
1018 to a PI target futex
1019 .RI ( uaddr2 ).
1020
1021 As with
1022 .BR FUTEX_CMP_REQUEUE ,
1023 this operation wakes up a maximum of
1024 .I val
1025 waiters that are waiting on the futex at
1026 .IR uaddr .
1027 However, for
1028 .BR FUTEX_CMP_REQUEUE_PI ,
1029 .I val
1030 is required to be 1
1031 (since the main point is to avoid a thundering herd).
1032 The remaining waiters are removed from the wait queue of the source futex at
1033 .I uaddr
1034 and added to the wait queue of the target futex at
1035 .IR uaddr2 .
1036
1037 The
1038 .I val2
1039 .\" val2 is the cap on the number of requeued waiters.
1040 .\" In the glibc pthread_cond_broadcast() implementation, this argument
1041 .\" is specified as INT_MAX, and for pthread_cond_signal() it is 0.
1042 and
1043 .I val3
1044 arguments serve the same purposes as for
1045 .BR FUTEX_CMP_REQUEUE .
1046 .\"
1047 .\" FIXME The page at http://locklessinc.com/articles/futex_cheat_sheet/
1048 .\" notes that "priority-inheritance Futex to priority-inheritance
1049 .\" Futex requeues are currently unsupported". Do we need to say
1050 .\" something in the man page about that?
1051 .\"
1052 .\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
1053 .\"
1054 .TP
1055 .BR FUTEX_WAIT_REQUEUE_PI " (since Linux 2.6.31)"
1056 .\" commit 52400ba946759af28442dee6265c5c0180ac7122
1057 .\"
1058 .\" FIXME I find the next sentence (from tglx) pretty hard to grok.
1059 .\" Could someone explain it a bit more?
1060 Wait operation to wait on a non-PI futex at
1061 .I uaddr
1062 and potentially be requeued onto a PI futex at
1063 .IR uaddr2 .
1064 The wait operation on
1065 .I uaddr
1066 is the same as
1067 .BR FUTEX_WAIT .
1068 .\"
1069 .\" FIXME I'm not quite clear on the meaning of the following sentence.
1070 .\" Is this trying to say that while blocked in a
1071 .\" FUTEX_WAIT_REQUEUE_PI, it could happen that another
1072 .\" task does a FUTEX_WAKE on uaddr that simply causes
1073 .\" a normal wake, with the result that the FUTEX_WAIT_REQUEUE_PI
1074 .\" does not complete? What happens then to the FUTEX_WAIT_REQUEUE_PI
1075 .\" opertion? Does it remain blocked, or does it unblock
1076 .\" In which case, what does user space see?
1077 The waiter can be removed from the wait on
1078 .I uaddr
1079 via
1080 .BR FUTEX_WAKE
1081 without requeueing on
1082 .IR uaddr2 .
1083
1084 .\" FIXME Please check the following. tglx said "The timeout argument
1085 .\" is handled as described in FUTEX_WAIT.", but the truth is
1086 .\" as below, AFAICS
1087 If
1088 .I timeout
1089 is not NULL, it specifies a timeout for the wait operation;
1090 this timeout is interpreted as outlined above in the description of the
1091 .BR FUTEX_CLOCK_REALTIME
1092 option.
1093 If
1094 .I timeout
1095 is NULL, the operation can block indefinitely.
1096
1097 The
1098 .I val3
1099 argument is ignored.
1100 .\" FIXME Re the preceding sentence... Actually 'val3' is internally set to
1101 .\" FUTEX_BITSET_MATCH_ANY before calling futex_wait_requeue_pi().
1102 .\" I'm not sure we need to say anything about this though.
1103 .\" Comments?
1104
1105 The
1106 .BR FUTEX_WAIT_REQUEUE_PI
1107 and
1108 .BR FUTEX_CMP_REQUEUE_PI
1109 were added to support a fairly specific use case:
1110 support for priority-inheritance-aware POSIX threads condition variables.
1111 The idea is that these operations should always be paired,
1112 in order to ensure that user space and the kernel remain in sync.
1113 Thus, in the
1114 .BR FUTEX_WAIT_REQUEUE_PI
1115 operation, the user-space application pre-specifies the target
1116 of the requeue that takes place in the
1117 .BR FUTEX_CMP_REQUEUE_PI
1118 operation.
1119 .\"
1120 .\" Darren Hart notes that a patch to allow glibc to fully support
1121 .\" PI-aware pthreads condition variables has not yet been accepted into
1122 .\" glibc. The story is complex, and can be found at
1123 .\" https://sourceware.org/bugzilla/show_bug.cgi?id=11588
1124 .\" Darren notes that in the meantime, the patch is shipped with various
1125 .\" PREEMPT_RT-enabled Linux systems.
1126 .\"
1127 .\" Related to the preceding, Darren proposed that somewhere, man-pages
1128 .\" should document the following point:
1129 .\"
1130 .\" While the Linux kernel, since 2.6.31, supports requeueing of
1131 .\" priority-inheritance (PI) aware mutexes via the
1132 .\" FUTEX_WAIT_REQUEUE_PI and FUTEX_CMP_REQUEUE_PI futex operations,
1133 .\" the glibc implementation does not yet take full advantage of this.
1134 .\" Specifically, the condvar internal data lock remains a non-PI aware
1135 .\" mutex, regardless of the type of the pthread_mutex associated with
1136 .\" the condvar. This can lead to an unbounded priority inversion on
1137 .\" the internal data lock even when associating a PI aware
1138 .\" pthread_mutex with a condvar during a pthread_cond*_wait
1139 .\" operation. For this reason, it is not recommended to rely on
1140 .\" priority inheritance when using pthread condition variables.
1141 .\"
1142 .\" The problem is that the obvious location for this text is
1143 .\" the pthread_cond*wait(3) man page. However, such a man page
1144 .\" does not currently exist.
1145 .\"
1146 .\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
1147 .\"
1148 .SH RETURN VALUE
1149 .PP
1150 In the event of an error (and assuming that
1151 .BR futex ()
1152 was invoked via
1153 .BR syscall (2)),
1154 all operations return \-1 and set
1155 .I errno
1156 to indicate the cause of the error.
1157 The return value on success depends on the operation,
1158 as described in the following list:
1159 .TP
1160 .B FUTEX_WAIT
1161 Returns 0 if the caller was woken up.
1162 Note that a wake-up can also be caused by common futex usage patterns
1163 in unrelated code that happened to have previously used the futex word's
1164 memory location (e.g., typical futex-based implementations of
1165 Pthreads mutexes can cause this under some conditions).
1166 Therefore, callers should always conservatively assume that a return
1167 value of 0 can mean a spurious wake-up, and use the futex word's value
1168 (i.e., the user space synchronization scheme)
1169 to decide whether to continue to block or not.
1170 .TP
1171 .B FUTEX_WAKE
1172 Returns the number of waiters that were woken up.
1173 .TP
1174 .B FUTEX_FD
1175 Returns the new file descriptor associated with the futex.
1176 .TP
1177 .B FUTEX_REQUEUE
1178 Returns the number of waiters that were woken up.
1179 .TP
1180 .B FUTEX_CMP_REQUEUE
1181 Returns the total number of waiters that were woken up or
1182 requeued to the futex for the futex word at
1183 .IR uaddr2 .
1184 If this value is greater than
1185 .IR val ,
1186 then the difference is the number of waiters requeued to the futex for the
1187 futex word at
1188 .IR uaddr2 .
1189 .TP
1190 .B FUTEX_WAKE_OP
1191 Returns the total number of waiters that were woken up.
1192 This is the sum of the woken waiters on the two futexes for
1193 the futex words at
1194 .I uaddr
1195 and
1196 .IR uaddr2 .
1197 .TP
1198 .B FUTEX_WAIT_BITSET
1199 Returns 0 if the caller was woken up.
1200 See
1201 .B FUTEX_WAIT
1202 for how to interpret this correctly in practice.
1203 .TP
1204 .B FUTEX_WAKE_BITSET
1205 Returns the number of waiters that were woken up.
1206 .TP
1207 .B FUTEX_LOCK_PI
1208 Returns 0 if the futex was successfully locked.
1209 .TP
1210 .B FUTEX_TRYLOCK_PI
1211 Returns 0 if the futex was successfully locked.
1212 .TP
1213 .B FUTEX_UNLOCK_PI
1214 Returns 0 if the futex was successfully unlocked.
1215 .TP
1216 .B FUTEX_CMP_REQUEUE_PI
1217 Returns the total number of waiters that were woken up or
1218 requeued to the futex for the futex word at
1219 .IR uaddr2 .
1220 If this value is greater than
1221 .IR val ,
1222 then difference is the number of waiters requeued to the futex for
1223 the futex word at
1224 .IR uaddr2 .
1225 .TP
1226 .B FUTEX_WAIT_REQUEUE_PI
1227 Returns 0 if the caller was successfully requeued to the futex for
1228 the futex word at
1229 .IR uaddr2 .
1230 .\"
1231 .\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
1232 .\"
1233 .SH ERRORS
1234 .TP
1235 .B EACCES
1236 No read access to the memory of a futex word.
1237 .TP
1238 .B EAGAIN
1239 .RB ( FUTEX_WAIT ,
1240 .BR FUTEX_WAIT_BITSET ,
1241 .BR FUTEX_WAIT_REQUEUE_PI )
1242 The value pointed to by
1243 .I uaddr
1244 was not equal to the expected value
1245 .I val
1246 at the time of the call.
1247
1248 .BR Note :
1249 on Linux, the symbolic names
1250 .B EAGAIN
1251 and
1252 .B EWOULDBLOCK
1253 (both of which appear in different parts of the kernel futex code)
1254 have the same value.
1255 .TP
1256 .B EAGAIN
1257 .RB ( FUTEX_CMP_REQUEUE ,
1258 .BR FUTEX_CMP_REQUEUE_PI )
1259 The value pointed to by
1260 .I uaddr
1261 is not equal to the expected value
1262 .IR val3 .
1263 .\" FIXME: Is the following sentence correct?
1264 .\" [I would prefer to remove this sentence. --triegel@redhat.com]
1265 (This probably indicates a race;
1266 use the safe
1267 .B FUTEX_WAKE
1268 now.)
1269 .\"
1270 .\" FIXME XXX Should there be an EAGAIN case for FUTEX_TRYLOCK_PI?
1271 .\" It seems so, looking at the handling of the rt_mutex_trylock()
1272 .\" call in futex_lock_pi()
1273 .\" (Davidlohr also thinks so.)
1274 .\"
1275 .TP
1276 .BR EAGAIN
1277 .RB ( FUTEX_LOCK_PI ,
1278 .BR FUTEX_TRYLOCK_PI ,
1279 .BR FUTEX_CMP_REQUEUE_PI )
1280 The futex owner thread ID of
1281 .I uaddr
1282 (for
1283 .BR FUTEX_CMP_REQUEUE_PI :
1284 .IR uaddr2 )
1285 is about to exit,
1286 but has not yet handled the internal state cleanup.
1287 Try again.
1288 .TP
1289 .BR EDEADLK
1290 .RB ( FUTEX_LOCK_PI ,
1291 .BR FUTEX_TRYLOCK_PI ,
1292 .BR FUTEX_CMP_REQUEUE_PI )
1293 The futex word at
1294 .I uaddr
1295 is already locked by the caller.
1296 .TP
1297 .BR EDEADLK
1298 .\" FIXME XXX I see that kernel/locking/rtmutex.c uses EDEADLK in some
1299 .\" places, and EDEADLOCK in others. On almost all architectures
1300 .\" these constants are synonymous. Is there a reason that both
1301 .\" names are used?
1302 .\" FIXME I reworded tglx's text somewhat; is the following okay?
1303 .RB ( FUTEX_CMP_REQUEUE_PI )
1304 While requeueing a waiter to the PI futex for the futex word at
1305 .IR uaddr2 ,
1306 the kernel detected a deadlock.
1307 .TP
1308 .B EFAULT
1309 A required pointer argument (i.e.,
1310 .IR uaddr ,
1311 .IR uaddr2 ,
1312 or
1313 .IR timeout )
1314 did not point to a valid user-space address.
1315 .TP
1316 .B EINTR
1317 A
1318 .B FUTEX_WAIT
1319 or
1320 .B FUTEX_WAIT_BITSET
1321 operation was interrupted by a signal (see
1322 .BR signal (7)).
1323 In kernels before Linux 2.6.22, this error could also be returned for
1324 on a spurious wakeup; since Linux 2.6.22, this no longer happens.
1325 .TP
1326 .B EINVAL
1327 The operation in
1328 .IR futex_op
1329 is one of those that employs a timeout, but the supplied
1330 .I timeout
1331 argument was invalid
1332 .RI ( tv_sec
1333 was less than zero, or
1334 .IR tv_nsec
1335 was not less than 1,000,000,000).
1336 .TP
1337 .B EINVAL
1338 The operation specified in
1339 .IR futex_op
1340 employs one or both of the pointers
1341 .I uaddr
1342 and
1343 .IR uaddr2 ,
1344 but one of these does not point to a valid object\(emthat is,
1345 the address is not four-byte-aligned.
1346 .TP
1347 .B EINVAL
1348 .RB ( FUTEX_WAIT_BITSET ,
1349 .BR FUTEX_WAKE_BITSET )
1350 The bitset supplied in
1351 .IR val3
1352 is zero.
1353 .TP
1354 .B EINVAL
1355 .RB ( FUTEX_CMP_REQUEUE_PI )
1356 .I uaddr
1357 equals
1358 .IR uaddr2
1359 (i.e., an attempt was made to requeue to the same futex).
1360 .TP
1361 .BR EINVAL
1362 .RB ( FUTEX_FD )
1363 The signal number supplied in
1364 .I val
1365 is invalid.
1366 .TP
1367 .B EINVAL
1368 .RB ( FUTEX_WAKE ,
1369 .BR FUTEX_WAKE_OP ,
1370 .BR FUTEX_WAKE_BITSET ,
1371 .BR FUTEX_REQUEUE ,
1372 .BR FUTEX_CMP_REQUEUE )
1373 The kernel detected an inconsistency between the user-space state at
1374 .I uaddr
1375 and the kernel state\(emthat is, it detected a waiter which waits in
1376 .BR FUTEX_LOCK_PI
1377 on
1378 .IR uaddr .
1379 .TP
1380 .B EINVAL
1381 .RB ( FUTEX_LOCK_PI ,
1382 .BR FUTEX_TRYLOCK_PI ,
1383 .BR FUTEX_UNLOCK_PI )
1384 The kernel detected an inconsistency between the user-space state at
1385 .I uaddr
1386 and the kernel state.
1387 This indicates either state corruption
1388 .\" FIXME tglx did not mention the "state corruption" case for
1389 .\" FUTEX_UNLOCK_PI, but I have added it, since I'm estimating
1390 .\" that it also applied for FUTEX_UNLOCK_PI.
1391 .\" So, does that case also apply for FUTEX_UNLOCK_PI?
1392 or that the kernel found a waiter on
1393 .I uaddr
1394 which is waiting via
1395 .BR FUTEX_WAIT
1396 or
1397 .BR FUTEX_WAIT_BITSET .
1398 .TP
1399 .B EINVAL
1400 .RB ( FUTEX_CMP_REQUEUE_PI )
1401 The kernel detected an inconsistency between the user-space state at
1402 .I uaddr2
1403 and the kernel state;
1404 that is, the kernel detected a waiter which waits via
1405 .BR FUTEX_WAIT
1406 .\" FIXME tglx did not mention FUTEX_WAIT_BITSET here,
1407 .\" but should that not also be included here?
1408 on
1409 .IR uaddr2 .
1410 .TP
1411 .B EINVAL
1412 .RB ( FUTEX_CMP_REQUEUE_PI )
1413 The kernel detected an inconsistency between the user-space state at
1414 .I uaddr
1415 and the kernel state;
1416 that is, the kernel detected a waiter which waits via
1417 .BR FUTEX_WAIT
1418 or
1419 .BR FUTEX_WAIT_BITESET
1420 on
1421 .IR uaddr .
1422 .TP
1423 .B EINVAL
1424 .RB ( FUTEX_CMP_REQUEUE_PI )
1425 The kernel detected an inconsistency between the user-space state at
1426 .I uaddr
1427 and the kernel state;
1428 that is, the kernel detected a waiter which waits on
1429 .I uaddr
1430 via
1431 .BR FUTEX_LOCK_PI
1432 (instead of
1433 .BR FUTEX_WAIT_REQUEUE_PI ).
1434 .TP
1435 .B EINVAL
1436 .RB ( FUTEX_CMP_REQUEUE_PI )
1437 .\" FIXME XXX The following is a reworded version of Darren Hart's text.
1438 .\" Please check that I did not introduce any errors.
1439 An attempt was made to requeue a waiter to a futex other than that
1440 specified by the matching
1441 .B FUTEX_WAIT_REQUEUE_PI
1442 call for that waiter.
1443 .TP
1444 .B EINVAL
1445 .RB ( FUTEX_CMP_REQUEUE_PI )
1446 The
1447 .I val
1448 argument is not 1.
1449 .TP
1450 .B EINVAL
1451 Invalid argument.
1452 .TP
1453 .BR ENOMEM
1454 .RB ( FUTEX_LOCK_PI ,
1455 .BR FUTEX_TRYLOCK_PI ,
1456 .BR FUTEX_CMP_REQUEUE_PI )
1457 The kernel could not allocate memory to hold state information.
1458 .TP
1459 .B ENFILE
1460 .RB ( FUTEX_FD )
1461 The system limit on the total number of open files has been reached.
1462 .TP
1463 .B ENOSYS
1464 Invalid operation specified in
1465 .IR futex_op .
1466 .TP
1467 .B ENOSYS
1468 The
1469 .BR FUTEX_CLOCK_REALTIME
1470 option was specified in
1471 .IR futex_op ,
1472 but the accompanying operation was neither
1473 .BR FUTEX_WAIT_BITSET
1474 nor
1475 .BR FUTEX_WAIT_REQUEUE_PI .
1476 .TP
1477 .BR ENOSYS
1478 .RB ( FUTEX_LOCK_PI ,
1479 .BR FUTEX_TRYLOCK_PI ,
1480 .BR FUTEX_UNLOCK_PI ,
1481 .BR FUTEX_CMP_REQUEUE_PI ,
1482 .BR FUTEX_WAIT_REQUEUE_PI )
1483 A run-time check determined that the operation is not available.
1484 The PI futex operations are not implemented on all architectures and
1485 are not supported on some CPU variants.
1486 .TP
1487 .BR EPERM
1488 .RB ( FUTEX_LOCK_PI ,
1489 .BR FUTEX_TRYLOCK_PI ,
1490 .BR FUTEX_CMP_REQUEUE_PI )
1491 The caller is not allowed to attach itself to the futex at
1492 .I uaddr
1493 (for
1494 .BR FUTEX_CMP_REQUEUE_PI :
1495 the futex at
1496 .IR uaddr2 ).
1497 (This may be caused by a state corruption in user space.)
1498 .TP
1499 .BR EPERM
1500 .RB ( FUTEX_UNLOCK_PI )
1501 The caller does not own the lock represented by the futex word.
1502 .TP
1503 .BR ESRCH
1504 .RB ( FUTEX_LOCK_PI ,
1505 .BR FUTEX_TRYLOCK_PI ,
1506 .BR FUTEX_CMP_REQUEUE_PI )
1507 .\" FIXME I reworded the following sentence a bit differently from
1508 .\" tglx's formulation. Is it okay?
1509 The thread ID in the futex word at
1510 .I uaddr
1511 does not exist.
1512 .TP
1513 .BR ESRCH
1514 .RB ( FUTEX_CMP_REQUEUE_PI )
1515 .\" FIXME I reworded the following sentence a bit differently from
1516 .\" tglx's formulation. Is it okay?
1517 The thread ID in the futex word at
1518 .I uaddr2
1519 does not exist.
1520 .TP
1521 .B ETIMEDOUT
1522 The operation in
1523 .IR futex_op
1524 employed the timeout specified in
1525 .IR timeout ,
1526 and the timeout expired before the operation completed.
1527 .\"
1528 .\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
1529 .\"
1530 .SH VERSIONS
1531 .PP
1532 Futexes were first made available in a stable kernel release
1533 with Linux 2.6.0.
1534
1535 Initial futex support was merged in Linux 2.5.7 but with different
1536 semantics from what was described above.
1537 A four-argument system call with the semantics
1538 described in this page was introduced in Linux 2.5.40.
1539 In Linux 2.5.70, one argument
1540 was added.
1541 In Linux 2.6.7, a sixth argument was added\(emmessy, especially
1542 on the s390 architecture.
1543 .SH CONFORMING TO
1544 This system call is Linux-specific.
1545 .SH NOTES
1546 Glibc does not provide a wrapper for this system call; call it using
1547 .BR syscall (2).
1548
1549 Several higher-level programming abstractions are implemented via futexes,
1550 including POSIX semaphores and
1551 various POSIX threads synchronization mechanisms
1552 (mutexes, condition variables, read-write locks, and barriers).
1553 .\" TODO FIXME(Torvald) Above, we cite this section and claim it contains
1554 .\" details on the synchronization semantics; add the C11 equivalents
1555 .\" here (or whatever we find consensus for).
1556 .\"
1557 .\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
1558 .\"
1559 .SH EXAMPLE
1560 .\" FIXME Is it worth having an example program?
1561 .\" FIXME Anything obviously broken in the example program?
1562 .\"
1563 The program below demonstrates use of futexes in a program
1564 where parent and child use a pair of futexes located inside a
1565 shared anonymous mapping to synchronize access to a shared resource:
1566 the terminal.
1567 The two processes each write
1568 .IR nloops
1569 (a command-line argument that defaults to 5 if omitted)
1570 messages to the terminal and employ a synchronization protocol
1571 that ensures that they alternate in writing messages.
1572 Upon running this program we see output such as the following:
1573
1574 .in +4n
1575 .nf
1576 $ \fB./futex_demo\fP
1577 Parent (18534) 0
1578 Child (18535) 0
1579 Parent (18534) 1
1580 Child (18535) 1
1581 Parent (18534) 2
1582 Child (18535) 2
1583 Parent (18534) 3
1584 Child (18535) 3
1585 Parent (18534) 4
1586 Child (18535) 4
1587 .fi
1588 .in
1589 .SS Program source
1590 \&
1591 .nf
1592 /* futex_demo.c
1593
1594 Usage: futex_demo [nloops]
1595 (Default: 5)
1596
1597 Demonstrate the use of futexes in a program where parent and child
1598 use a pair of futexes located inside a shared anonymous mapping to
1599 synchronize access to a shared resource: the terminal. The two
1600 processes each write \(aqnum\-loops\(aq messages to the terminal and employ
1601 a synchronization protocol that ensures that they alternate in
1602 writing messages.
1603 */
1604 #define _GNU_SOURCE
1605 #include <stdio.h>
1606 #include <errno.h>
1607 #include <stdlib.h>
1608 #include <unistd.h>
1609 #include <sys/wait.h>
1610 #include <sys/mman.h>
1611 #include <sys/syscall.h>
1612 #include <linux/futex.h>
1613 #include <sys/time.h>
1614
1615 #define errExit(msg) do { perror(msg); exit(EXIT_FAILURE); \\
1616 } while (0)
1617
1618 static int *futex1, *futex2, *iaddr;
1619
1620 static int
1621 futex(int *uaddr, int futex_op, int val,
1622 const struct timespec *timeout, int *uaddr2, int val3)
1623 {
1624 return syscall(SYS_futex, uaddr, futex_op, val,
1625 timeout, uaddr, val3);
1626 }
1627
1628 /* Acquire the futex pointed to by \(aqfutexp\(aq: wait for its value to
1629 become 1, and then set the value to 0. */
1630
1631 static void
1632 fwait(int *futexp)
1633 {
1634 int s;
1635
1636 /* __sync_bool_compare_and_swap(ptr, oldval, newval) is a gcc
1637 built\-in function. It atomically performs the equivalent of:
1638
1639 if (*ptr == oldval)
1640 *ptr = newval;
1641
1642 It returns true if the test yielded true and *ptr was updated.
1643 The alternative here would be to employ the equivalent atomic
1644 machine\-language instructions. For further information, see
1645 the GCC Manual. */
1646
1647 while (1) {
1648
1649 /* Is the futex available? */
1650
1651 if (__sync_bool_compare_and_swap(futexp, 1, 0))
1652 break; /* Yes */
1653
1654 /* Futex is not available; wait */
1655
1656 s = futex(futexp, FUTEX_WAIT, 0, NULL, NULL, 0);
1657 if (s == \-1 && errno != EAGAIN)
1658 errExit("futex\-FUTEX_WAIT");
1659 }
1660 }
1661
1662 /* Release the futex pointed to by \(aqfutexp\(aq: if the futex currently
1663 has the value 0, set its value to 1 and the wake any futex waiters,
1664 so that if the peer is blocked in fpost(), it can proceed. */
1665
1666 static void
1667 fpost(int *futexp)
1668 {
1669 int s;
1670
1671 /* __sync_bool_compare_and_swap() was described in comments above */
1672
1673 if (__sync_bool_compare_and_swap(futexp, 0, 1)) {
1674
1675 s = futex(futexp, FUTEX_WAKE, 1, NULL, NULL, 0);
1676 if (s == \-1)
1677 errExit("futex\-FUTEX_WAKE");
1678 }
1679 }
1680
1681 int
1682 main(int argc, char *argv[])
1683 {
1684 pid_t childPid;
1685 int j, nloops;
1686
1687 setbuf(stdout, NULL);
1688
1689 nloops = (argc > 1) ? atoi(argv[1]) : 5;
1690
1691 /* Create a shared anonymous mapping that will hold the futexes.
1692 Since the futexes are being shared between processes, we
1693 subsequently use the "shared" futex operations (i.e., not the
1694 ones suffixed "_PRIVATE") */
1695
1696 iaddr = mmap(NULL, sizeof(int) * 2, PROT_READ | PROT_WRITE,
1697 MAP_ANONYMOUS | MAP_SHARED, \-1, 0);
1698 if (iaddr == MAP_FAILED)
1699 errExit("mmap");
1700
1701 futex1 = &iaddr[0];
1702 futex2 = &iaddr[1];
1703
1704 *futex1 = 0; /* State: unavailable */
1705 *futex2 = 1; /* State: available */
1706
1707 /* Create a child process that inherits the shared anonymous
1708 mapping */
1709
1710 childPid = fork();
1711 if (childPid == \-1)
1712 errExit("fork");
1713
1714 if (childPid == 0) { /* Child */
1715 for (j = 0; j < nloops; j++) {
1716 fwait(futex1);
1717 printf("Child (%ld) %d\\n", (long) getpid(), j);
1718 fpost(futex2);
1719 }
1720
1721 exit(EXIT_SUCCESS);
1722 }
1723
1724 /* Parent falls through to here */
1725
1726 for (j = 0; j < nloops; j++) {
1727 fwait(futex2);
1728 printf("Parent (%ld) %d\\n", (long) getpid(), j);
1729 fpost(futex1);
1730 }
1731
1732 wait(NULL);
1733
1734 exit(EXIT_SUCCESS);
1735 }
1736 .fi
1737 .SH SEE ALSO
1738 .ad l
1739 .BR get_robust_list (2),
1740 .BR restart_syscall (2),
1741 .BR pthread_mutexattr_getprotocol (3),
1742 .BR futex (7)
1743 .PP
1744 The following kernel source files:
1745 .IP * 2
1746 .I Documentation/pi-futex.txt
1747 .IP *
1748 .I Documentation/futex-requeue-pi.txt
1749 .IP *
1750 .I Documentation/locking/rt-mutex.txt
1751 .IP *
1752 .I Documentation/locking/rt-mutex-design.txt
1753 .IP *
1754 .I Documentation/robust-futex-ABI.txt
1755 .PP
1756 Franke, H., Russell, R., and Kirwood, M., 2002.
1757 \fIFuss, Futexes and Furwocks: Fast Userlevel Locking in Linux\fP
1758 (from proceedings of the Ottawa Linux Symposium 2002),
1759 .br
1760 .UR http://kernel.org\:/doc\:/ols\:/2002\:/ols2002-pages-479-495.pdf
1761 .UE
1762
1763 Hart, D., 2009. \fIA futex overview and update\fP,
1764 .UR http://lwn.net/Articles/360699/
1765 .UE
1766
1767 Hart, D. and Guniguntala, D., 2009.
1768 \fIRequeue-PI: Making Glibc Condvars PI-Aware\fP
1769 (from proceedings of the 2009 Real-Time Linux Workshop),
1770 .UR http://lwn.net/images/conf/rtlws11/papers/proc/p10.pdf
1771 .UE
1772
1773 Drepper, U., 2011. \fIFutexes Are Tricky\fP,
1774 .UR http://www.akkadia.org/drepper/futex.pdf
1775 .UE
1776 .PP
1777 Futex example library, futex-*.tar.bz2 at
1778 .br
1779 .UR ftp://ftp.kernel.org\:/pub\:/linux\:/kernel\:/people\:/rusty/
1780 .UE
1781 .\"
1782 .\" FIXME Are there any other resources that should be listed
1783 .\" in the SEE ALSO section?
1784 .\" FIXME(Torvald) We should probably refer to the glibc code here, in
1785 .\" particular the glibc-internal futex wrapper functions that are
1786 .\" WIP, and the generic pthread_mutex_t and perhaps condvar
1787 .\" implementations.