LKML Archive on lore.kernel.org
help / color / mirror / Atom feed
* Revised futex(2) man page for review
@ 2015-03-28  8:53 Michael Kerrisk (man-pages)
  2015-03-28  8:56 ` Michael Kerrisk (man-pages)
                   ` (2 more replies)
  0 siblings, 3 replies; 22+ messages in thread
From: Michael Kerrisk (man-pages) @ 2015-03-28  8:53 UTC (permalink / raw)
  To: Thomas Gleixner, Darren Hart
  Cc: mtk.manpages, Carlos O'Donell, Darren Hart, Ingo Molnar,
	Jakub Jelinek, linux-man, lkml, Davidlohr Bueso, Arnd Bergmann,
	Steven Rostedt, Peter Zijlstra, Linux API, Torvald Riegel,
	Roland McGrath, Darren Hart, Anton Blanchard, Peter Zijlstra,
	Eric Dumazet, bill o gallmeister, Jan Kiszka, Daniel Wagner,
	Rich Felker, Andy Lutomirski, bert hubert, Rusty Russell,
	Heinrich Schuchardt

Hello all,

As becomes quickly obvious upon reading it, the current futex(2) 
man page is in a sorry state, lacking many important details, and
also the various additions that have been made to the interface
over the last years. I've been working on revising it, first
of all based on input I got in response to a request for help
last year (http://thread.gmane.org/gmane.linux.kernel/1703405), 
especially taking Thomas Gleixner's input 
(http://thread.gmane.org/gmane.linux.kernel/1703405/focus=2952) 
into account. I also got some further offlist input from Darren
 Hart, Torvald Riegel, and Davidlohr Bueso that has been
incorporated into the revised draft. Other than that, I got
some useful info out of Ulrich Drepper's paper (cited at the
end of the page) and one or two web pages (cited in the page
source).

The page has now increased in size by a factor of about 5, but
is far from complete. In particular, as I reworked the page, 
there were many details that I was not 100% certain of, and I
have added FIXME markers to the page source. In addition,
Torvald added some text, and a few more FIXMEs. Some of
the FIXMEs are trivial, as in: I'd like confirmation that
I have correctly captured a technical detail. Others are more 
substantial, probably requiring the addition of further text.

I appreciate that there are probably other things that can be
improved in the page. (Torvald and Darren have some ideas.)
However, before growing the page any further, I would like to
resolve as many of the FIXMEs (and any other problems that people
see) as possible in the existing text. I need help with that. 
(And I know that dealing with that help, if I get it, will in 
itself will be quite a task to deal with, which is why I have 
been delaying it for many weeks now, as my time has been 
rather limited recently.)

So, please take a look at the page below. At this point,
I would most especially appreciate help with the FIXMEs.

Cheers,

Michael

=====
.\" Page by b.hubert
.\" and Copyright (C) 2015, Thomas Gleixner <tglx@linutronix.de>
.\" and Copyright (C) 2015, Michael Kerrisk <mtk.manpages@gmail.com>
.\"
.\" %%%LICENSE_START(FREELY_REDISTRIBUTABLE)
.\" may be freely modified and distributed
.\" %%%LICENSE_END
.\"
.\" Niki A. Rahimi (LTC Security Development, narahimi@us.ibm.com)
.\" added ERRORS section.
.\"
.\" Modified 2004-06-17 mtk
.\" Modified 2004-10-07 aeb, added FUTEX_REQUEUE, FUTEX_CMP_REQUEUE
.\"
.\" FIXME Still to integrate are some points from Torvald Riegel's mail of
.\"       2015-01-23:
.\"       http://thread.gmane.org/gmane.linux.kernel/1703405/focus=7977
.\"
.\" FIXME Do we need add some text regarding Torvald Riegel's 2015-01-24 mail
.\"       at http://thread.gmane.org/gmane.linux.kernel/1703405/focus=1873242
.\"
.TH FUTEX 2 2014-05-21 "Linux" "Linux Programmer's Manual"
.SH NAME
futex \- fast user-space locking
.SH SYNOPSIS
.nf
.sp
.B "#include <linux/futex.h>"
.B "#include <sys/time.h>"
.sp
.BI "int futex(int *" uaddr ", int " futex_op ", int " val ,
.BI "          const struct timespec *" timeout , \
" \fR  /* or: \fBu32 \fIval2\fP */ 
.BI "          int *" uaddr2 ", int " val3 );
.fi

.IR Note :
There is no glibc wrapper for this system call; see NOTES.
.SH DESCRIPTION
.PP
The
.BR futex ()
system call provides a method for waiting until a certain condition becomes
true.
It is typically used as a blocking construct in the context of
shared-memory synchronization: The program implements the majority of
the synchronization in user space, and uses one of operations of
the system call when it is likely that it has to block for
a longer time until the condition becomes true.
The program uses another operation of the system call to wake
anyone waiting for a particular condition.

The condition is represented by the futex word, which is an address
in memory supplied to the
.BR futex ()
system call, and the value at this memory location.
(While the virtual addresses for the same memory in separate
processes may not be equal,
the kernel maps them internally so that the same memory mapped
in different locations will correspond for
.BR futex ()
calls.)

When executing a futex operation that requests to block a thread,
the kernel will only block if the futex word has the value that the
calling thread supplied as expected value.
The load from the futex word, the comparison with
the expected value,
and the actual blocking will happen atomically and totally
ordered with respect to concurrently executing futex operations
on the same futex word,
such as operations that wake threads blocked on this futex word.
Thus, the futex word is used to connect the synchronization in user spac
with the implementation of blocking by the kernel; similar to an atomic
compare-and-exchange operation that potentially changes shared memory,
blocking via a futex is an atomic compare-and-block operation.
See NOTES for
a detailed specification of the synchronization semantics.

One example use of futexes is implementing locks.
The state of the lock (i.e.,
acquired or not acquired) can be represented as an atomically accessed
flag in shared memory.
In the uncontended case,
a thread can access or modify the lock state with atomic instructions,
for example atomically changing it from not acquired to acquired
using an atomic compare-and-exchange instruction.
If a thread cannot acquire a lock because
it is already acquired by another thread,
it can request to block if and only the lock is still acquired by
using the lock's flag as futex word and expecting a value that
represents the acquired state.
When releasing the lock, a thread has to first reset the
lock state to not acquired and then execute the futex operation that
wakes one thread blocked on the futex word that is the lock's flag
(this can be be further optimized to avoid unnecessary wake-ups).
See
.BR futex (7)
for more detail on how to use futexes.

Besides the basic wait and wake-up futex functionality, there are further
futex operations aimed at supporting more complex use cases.
Also note that
no explicit initialization or destruction are necessary to use futexes;
the kernel maintains a futex
(i.e., the kernel-internal implementation artifact)
only while operations such as
.BR FUTEX_WAIT ,
described below, are being performed on a particular futex word.
.\"
.SS Arguments
The
.I uaddr
argument points to the futex word.
On all platforms, futexes are four-byte
integers that must be aligned on a four-byte boundary.
The operation to perform on the futex is specified in the
.I futex_op
argument;
.IR val
is a value whose meaning and purpose depends on
.IR futex_op .

The remaining arguments
.RI ( timeout ,
.IR uaddr2 ,
and
.IR val3 )
are required only for certain of the futex operations described below.
Where one of these arguments is not required, it is ignored.

For several blocking operations, the
.I timeout
argument is a pointer to a
.IR timespec
structure that specifies a timeout for the operation.
However,  notwithstanding the prototype shown above, for some operations,
this argument is instead a four-byte integer whose meaning
is determined by the operation.
For these operations, the kernel casts the
.I timeout
value to
.IR u32 ,
and in the remainder of this page, this argument is referred to as
.I val2
when interpreted in this fashion.

Where it is required, the
.IR uaddr2
argument is a pointer to a second futex word that is employed
by the operation.
The interpretation of the final integer argument,
.IR val3 ,
depends on the operation.
.\"
.\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
.\"
.SS Futex operations
The
.I futex_op
argument consists of two parts:
a command that specifies the operation to be performed,
bit-wise ORed with zero or or more options that
modify the behaviour of the operation.
The options that may be included in
.I futex_op
are as follows:
.TP
.BR FUTEX_PRIVATE_FLAG " (since Linux 2.6.22)"
.\" commit 34f01cc1f512fa783302982776895c73714ebbc2
This option bit can be employed with all futex operations.
It tells the kernel that the futex is process-private and not shared
with another process (i.e., it is only being used for synchronization
between threads of the same process).
This allows the kernel to choose the fast path for validating
the user-space address and avoids expensive VMA lookups,
taking reference counts on file backing store, and so on.

As a convenience,
.IR <linux/futex.h>
defines a set of constants with the suffix
.BR _PRIVATE
that are equivalents of all of the operations listed below,
.\" except the obsolete FUTEX_FD, for which the "private" flag was
.\" meaningless
but with the
.BR FUTEX_PRIVATE_FLAG
ORed into the constant value.
Thus, there are
.BR FUTEX_WAIT_PRIVATE ,
.BR FUTEX_WAKE_PRIVATE ,
and so on.
.TP
.BR FUTEX_CLOCK_REALTIME " (since Linux 2.6.28)"
.\" commit 1acdac104668a0834cfa267de9946fac7764d486
This option bit can be employed only with the
.BR FUTEX_WAIT_BITSET
and
.BR FUTEX_WAIT_REQUEUE_PI
operations.

If this option is set, the kernel treats
.I timeout
as an absolute time based on
.BR CLOCK_REALTIME .

If this option is not set, the kernel treats
.I timeout
as relative time,
.\" FIXME XXX I added CLOCK_MONOTONIC here. Okay?
measured against the
.BR CLOCK_MONOTONIC
clock.
.PP
The operation specified in
.I futex_op
is one of the following:
.\"
.\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
.\"
.TP
.BR FUTEX_WAIT " (since Linux 2.6.0)"
.\" Strictly speaking, since some time in 2.5.x
This operation tests that the value at the
futex word pointed to by the address
.I uaddr
still contains the expected value
.IR val ,
and if so, then sleeps awaiting
.B FUTEX_WAKE
on the futex word.
The load of the value of the futex word is an atomic memory
access (i.e., using atomic machine instructions of the respective
architecture).
This load, the comparison with the expected value, and
starting to sleep are performed atomically and totally ordered with respect
to other futex operations on the same futex word.
If the thread starts to
sleep, it is considered a waiter on this futex word.
If the futex value does not match
.IR val ,
then the call fails immediately with the error
.BR EAGAIN .

The purpose of the comparison with the expected value is to prevent lost
wake-ups: If another thread changed the value of the futex word after the
calling thread decided to block based on the prior value, and if the other
thread executed a
.BR FUTEX_WAKE
operation (or similar wake-up) after the value change and before this
.BR FUTEX_WAIT
operation, then the latter will observe the value change and will not start
to sleep.

If the
.I timeout
argument is non-NULL, its contents specify a relative timeout for the wait,
.\" FIXME XXX I added CLOCK_MONOTONIC here. Okay?
measured according to the
.BR CLOCK_MONOTONIC
clock.
(This interval will be rounded up to the system clock granularity,
and kernel scheduling delays mean that the
blocking interval may overrun by a small amount.)
If
.I timeout
is NULL, the call blocks indefinitely.

The arguments
.I uaddr2
and
.I val3
are ignored.

.\" FIXME(Torvald) I think we should remove this.  Or maybe adapt to a
.\"      different example.
.\" For
.\" .BR futex (7),
.\" this call is executed if decrementing the count gave a negative value
.\" (indicating contention),
.\" and will sleep until another process or thread releases
.\" the futex and executes the
.\" .B FUTEX_WAKE
.\" operation.
.\"
.\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
.\"
.TP
.BR FUTEX_WAKE " (since Linux 2.6.0)"
.\" Strictly speaking, since Linux 2.5.x
This operation wakes at most
.I val
.\" FIXME(Torvald) I believe FUTEX_WAIT_BITSET waiters, for example,
.\"       could also be woken (therefore, make it e.g. instead of i.e.)?
of the waiters that are waiting (e.g., inside
.BR FUTEX_WAIT )
on the futex word at the address
.IR uaddr .
Most commonly,
.I val
is specified as either 1 (wake up a single waiter) or
.BR INT_MAX
(wake up all waiters).
.\" FIXME Please confirm that the following is correct:
No guarantee is provided about which waiters are awoken
(e.g., a waiter with a higher scheduling priority is not guaranteed
to be awoken in preference to a waiter with a lower priority).

The arguments
.IR timeout ,
.IR uaddr2 ,
and
.I val3
are ignored.

.\" FIXME(Torvald) I think we should remove this.  Or maybe adapt to
.\"          a different example.
.\"     For
.\"     .BR futex (7),
.\"     this is executed if incrementing the count showed that
.\"     there were waiters,
.\"     once the futex value has been set to 1
.\"     (indicating that it is available).
.\"
.\" FIXME How does "incrementing the count show that there were waiters"?
.\"
.\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
.\"
.TP
.BR FUTEX_FD " (from Linux 2.6.0 up to and including Linux 2.6.25)"
.\" Strictly speaking, from Linux 2.5.x to 2.6.25
This operation creates a file descriptor that is associated with
the futex at
.IR uaddr .
The caller must close the returned file descriptor after use.
When another process or thread performs a
.BR FUTEX_WAKE
on the futex word, the file descriptor indicates as being readable with
.BR select (2),
.BR poll (2),
and
.BR epoll (7)

The file descriptor can be used to obtain asynchronous notifications: if
.I val
is nonzero, then when another process or thread executes a
.BR FUTEX_WAKE ,
the caller will receive the signal number that was passed in
.IR val .

The arguments
.IR timeout ,
.I uaddr2
and
.I val3
are ignored.

.\" FIXME(Torvald) We never define "upped".  Maybe just remove the
.\"      following sentence?
To prevent race conditions, the caller should test if the futex has
been upped after
.B FUTEX_FD
returns.

Because it was inherently racy,
.B FUTEX_FD
has been removed
.\" commit 82af7aca56c67061420d618cc5a30f0fd4106b80
from Linux 2.6.26 onward.
.\"
.\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
.\"
.TP
.BR FUTEX_REQUEUE " (since Linux 2.6.0)"
.\" Strictly speaking: from Linux 2.5.70
.\" FIXME(Torvald) Is there some indication that it is broken in general,
.\" or is this comment implicitly speaking about the condvar (?) use case?
.\" If the latter we might want to weaken the advice a little.
.IR "Avoid using this operation" .
It is broken for its intended purpose.
Use
.BR FUTEX_CMP_REQUEUE
instead.

This operation performs the same task as
.BR FUTEX_CMP_REQUEUE ,
except that no check is made using the value in
.IR  val3 .
(The argument
.I val3
is ignored.)
.\"
.\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
.\"
.TP
.BR FUTEX_CMP_REQUEUE " (since Linux 2.6.7)"
This operation first checks whether the location
.I uaddr
still contains the value
.IR val3 .
If not, the operation fails with the error
.BR EAGAIN .
Otherwise, the operation wakes up a maximum of
.I val
waiters that are waiting on the futex at
.IR uaddr .
If there are more than
.I val
waiters, then the remaining waiters are removed
from the wait queue of the source futex at
.I uaddr
and added to the wait queue of the target futex at
.IR uaddr2 .
The
.I val2
argument specifies an upper limit on the number of waiters
that are requeued to the futex at
.IR uaddr2 .

.\" FIXME(Torvald) Is this correct?  Or is just the decision which
.\" threads to wake or requeue part of the atomic operation?
The load from
.I uaddr
is an atomic memory access (i.e., using atomic machine instructions of
the respective architecture).
This load, the comparison with
.IR val3 ,
and the requeueing of any waiters are performed atomically and totally
ordered with respect to other operations on the same futex word.

This operation was added as a replacement for the earlier
.BR FUTEX_REQUEUE .
The difference is that the check of the value at
.I uaddr
can be used to ensure that requeueing only happens under certain
conditions.
Both operations can be used to avoid a "thundering herd" effect when
.B FUTEX_WAKE
is used and all of the waiters that are woken need to acquire
another futex.

.\" FIXME Please review the following new paragraph to see if it is
.\"       accurate.
Typical values to specify for
.I val
are 0 or or 1.
(Specifying
.BR INT_MAX
is not useful, because it would make the
.BR FUTEX_CMP_REQUEUE
operation equivalent to
.BR FUTEX_WAKE .)
The limit value specified via
.I val2
is typically either 1 or
.BR INT_MAX .
(Specifying the argument as 0 is not useful, because it would make the
.BR FUTEX_CMP_REQUEUE
operation equivalent to
.BR FUTEX_WAIT .)
.\"
.\" FIXME Here, it would be helpful to have an example of how
.\"       FUTEX_CMP_REQUEUE might be used, at the same time illustrating
.\"       why FUTEX_WAKE is unsuitable for the same use case.
.\"
.\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
.\"
.\" FIXME I added a lengthy piece of text on FUTEX_WAKE_OP text,
.\"       and I'd be happy if someone checked it.
.TP
.BR FUTEX_WAKE_OP " (since Linux 2.6.14)"
.\" commit 4732efbeb997189d9f9b04708dc26bf8613ed721
.\"	Author: Jakub Jelinek <jakub@redhat.com>
.\"	Date:   Tue Sep 6 15:16:25 2005 -0700
.\" FIXME(Torvald) The glibc condvar implementation is currently being
.\"     revised (e.g., to not use an internal lock anymore).
.\"     It is probably more future-proof to remove this paragraph.
This operation was added to support some user-space use cases
where more than one futex must be handled at the same time.
The most notable example is the implementation of
.BR pthread_cond_signal (3),
which requires operations on two futexes,
the one used to implement the mutex and the one used in the implementation
of the wait queue associated with the condition variable.
.BR FUTEX_WAKE_OP
allows such cases to be implemented without leading to
high rates of contention and context switching.

The
.BR FUTEX_WAIT_OP
operation is equivalent to execute the following code atomically
and totally ordered with respect to other futex operations on
any of the two supplied futex words:

.in +4n
.nf
int oldval = *(int *) uaddr2;
*(int *) uaddr2 = oldval \fIop\fP \fIoparg\fP;
futex(uaddr, FUTEX_WAKE, val, 0, 0, 0);
if (oldval \fIcmp\fP \fIcmparg\fP)
    futex(uaddr2, FUTEX_WAKE, val2, 0, 0, 0);
.fi
.in

In other words,
.BR FUTEX_WAIT_OP
does the following:
.RS
.IP * 3
saves the original value of the futex word at
.IR uaddr2
and performs an operation to modify the value of the futex at
.IR uaddr2 ;
this is an atomic read-modify-write memory access (i.e., using atomic
machine instructions of the respective architecture)
.IP *
wakes up a maximum of
.I val
waiters on the futex for the futex word at
.IR uaddr ;
and
.IP *
dependent on the results of a test of the original value of the
futex word at
.IR uaddr2 ,
wakes up a maximum of
.I val2
waiters on the futex for the futex word at
.IR uaddr2 .
.RE
.IP
The operation and comparison that are to be performed are encoded
in the bits of the argument
.IR val3 .
Pictorially, the encoding is:

.in +8n
.nf
+---+---+-----------+-----------+
|op |cmp|   oparg   |  cmparg   |
+---+---+-----------+-----------+
  4   4       12          12    <== # of bits
.fi
.in

Expressed in code, the encoding is:

.in +4n
.nf
#define FUTEX_OP(op, oparg, cmp, cmparg) \\
                (((op & 0xf) << 28) | \\
                ((cmp & 0xf) << 24) | \\
                ((oparg & 0xfff) << 12) | \\
                (cmparg & 0xfff))
.fi
.in

In the above,
.I op
and
.I cmp
are each one of the codes listed below.
The
.I oparg
and
.I cmparg
components are literal numeric values, except as noted below.

The
.I op
component has one of the following values:

.in +4n
.nf
FUTEX_OP_SET        0  /* uaddr2 = oparg; */
FUTEX_OP_ADD        1  /* uaddr2 += oparg; */
FUTEX_OP_OR         2  /* uaddr2 |= oparg; */
FUTEX_OP_ANDN       3  /* uaddr2 &= ~oparg; */
FUTEX_OP_XOR        4  /* uaddr2 ^= oparg; */
.fi
.in

In addition, bit-wise ORing the following value into
.I op
causes
.IR "(1\ <<\ oparg)"
to be used as the operand:

.in +4n
.nf
FUTEX_OP_ARG_SHIFT  8  /* Use (1 << oparg) as operand */
.fi
.in

The
.I cmp
field is one of the following:

.in +4n
.nf
FUTEX_OP_CMP_EQ     0  /* if (oldval == cmparg) wake */
FUTEX_OP_CMP_NE     1  /* if (oldval != cmparg) wake */
FUTEX_OP_CMP_LT     2  /* if (oldval < cmparg) wake */
FUTEX_OP_CMP_LE     3  /* if (oldval <= cmparg) wake */
FUTEX_OP_CMP_GT     4  /* if (oldval > cmparg) wake */
FUTEX_OP_CMP_GE     5  /* if (oldval >= cmparg) wake */
.fi
.in

The return value of
.BR FUTEX_WAKE_OP
is the sum of the number of waiters woken on the futex
.IR uaddr
plus the number of waiters woken on the futex
.IR uaddr2 .
.\"
.\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
.\"
.TP
.BR FUTEX_WAIT_BITSET " (since Linux 2.6.25)"
.\" commit cd689985cf49f6ff5c8eddc48d98b9d581d9475d
This operation is like
.BR FUTEX_WAIT
except that
.I val3
is used to provide a 32-bit bitset to the kernel.
This bitset is stored in the kernel-internal state of the waiter.
See the description of
.BR FUTEX_WAKE_BITSET
for further details.

The
.BR FUTEX_WAIT_BITSET
operation also interprets the
.I timeout
argument differently from
.BR FUTEX_WAIT .
See the discussion of
.BR FUTEX_CLOCK_REALTIME ,
above.

The
.I uaddr2
argument is ignored.
.\"
.\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
.\"
.TP
.BR FUTEX_WAKE_BITSET " (since Linux 2.6.25)"
.\" commit cd689985cf49f6ff5c8eddc48d98b9d581d9475d
This operation is the same as
.BR FUTEX_WAKE
except that the
.I val3 
argument is used to provide a 32-bit bitset to the kernel.
This bitset is used to select which waiters should be woken up.
The selection is done by a bit-wise AND of the "wake" bitset
(i.e., the value in
.IR val3 )
and the bitset which is stored in the kernel-internal
state of the waiter (the "wait" bitset that is set using
.BR FUTEX_WAIT_BITSET ).
All of the waiters for which the result of the AND is nonzero are woken up;
the remaining waiters are left sleeping.

.\" FIXME XXX Is this paragraph that I added okay?
The effect of
.BR FUTEX_WAIT_BITSET
and
.BR FUTEX_WAKE_BITSET
is to allow selective wake-ups among multiple waiters that are blocked
on the same futex.
Note, however, that using this bitset multiplexing feature on a
futex is less efficient than simply using multiple futexes,
because employing bitset multiplexing requires the kernel
to check all waiters on a futex,
including those that are not interested in being woken up
(i.e., they do not have the relevant bit set in their "wait" bitset).
.\" According to http://locklessinc.com/articles/futex_cheat_sheet/:
.\"
.\"    "The original reason for the addition of these extensions
.\"     was to improve the performance of pthread read-write locks
.\"     in glibc. However, the pthreads library no longer uses the
.\"     same locking algorithm, and these extensions are not used
.\"     without the bitset parameter being all ones.
.\" 
.\" The page goes on to note that the FUTEX_WAIT_BITSET operation
.\" is nevertheless used (with a bitset of all ones) in order to
.\" obtain the absolute timeout functionality that is useful
.\" for efficiently implementing Pthreads APIs (which use absolute
.\" timeouts); FUTEX_WAIT provides only relative timeouts.

The
.I uaddr2
and
.I timeout
arguments are ignored.

The
.BR FUTEX_WAIT
and
.BR FUTEX_WAKE
operations correspond to
.BR FUTEX_WAIT_BITSET
and
.BR FUTEX_WAKE_BITSET
operations where the bitsets are all ones.
.\"
.\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
.\"
.SS Priority-inheritance futexes
Linux supports priority-inheritance (PI) futexes in order to handle
priority-inversion problems that can be encountered with
normal futex locks.
Priority inversion is the problem that occurs when a high-priority
task is blocked waiting to acquire a lock held by a low-priority task,
while tasks at an intermediate priority continuously preempt
the low-priority task from the CPU.
Consequently, the low-priority task makes no progress toward
releasing the lock, and the high-priority task remains blocked.

Priority inheritance is a mechanism for dealing with
the priority-inversion problem.
With this mechanism, when a high-priority task becomes blocked
by a lock held by a low-priority task,
the latter's priority is temporarily raised to that of the former,
so that it is not preempted by any intermediate level tasks,
and can thus make progress toward releasing the lock.
To be effective, priority inheritance must be transitive,
meaning that if a high-priority task blocks on a lock
held by a lower-priority task that is itself blocked by lock
held by another intermediate-priority task
(and so on, for chains of arbitrary length),
then both of those task
(or more generally, all of the tasks in a lock chain)
have their priorities raised to be the same as the high-priority task.

.\" FIXME XXX The following is my attempt at a definition of PI futexes,
.\"       based on mail discussions with Darren Hart. Does it seem okay?
>From a user-space perspective,
what makes a futex PI-aware is a policy agreement between user space
and the kernel about the value of the futex word (described in a moment),
coupled with the use of the PI futex operations described below
(in particular,
.BR FUTEX_LOCK_PI ,
.BR FUTEX_TRYLOCK_PI ,
and
.BR FUTEX_CMP_REQUEUE_PI ).
.\" Quoting Darren Hart:
.\"     These opcodes paired with the PI futex value policy (described below)
.\"     defines a "futex" as PI aware. These were created very specifically
.\"     in support of PI pthread_mutexes, so it makes a lot more sense to
.\"     talk about a PI aware pthread_mutex, than a PI aware futex, since
.\"     there is a lot of policy and scaffolding that has to be built up
.\"     around it to use it properly (this is what a PI pthread_mutex is).

.\" FIXME XXX ===== Start of adapted Hart/Guniguntala text =====
.\"       The following text is drawn from the Hart/Guniguntala paper
.\"       (listed in SEE ALSO), but I have reworded some pieces
.\"       significantly. Please check it.
.\"
The PI futex operations described below differ from the other
futex operations in that they impose policy on the use of the value of the
futex word:
.IP * 3
If the lock is not acquired, the futex word's value shall be 0.
.IP *
If the lock is acquired, the futex word's value shall
be the thread ID (TID;
see
.BR gettid (2))
of the owning thread.
.IP *
.\" FIXME XXX In the following line, I added "the lock is owned and". Okay?
If the lock is owned and there are threads contending for the lock,
then the
.B FUTEX_WAITERS
bit shall be set in the futex word's value; in other words, this value is:

    FUTEX_WAITERS | TID

.PP
Note that a PI futex word never just has the value
.BR FUTEX_WAITERS ,
which is a permissible state for non-PI futexes.

With this policy in place,
a user-space application can acquire a not-acquired
lock or release a lock that no other threads try to acquire using atomic
instructions executed in user space (e.g., a compare-and-swap operation
such as
.I cmpxchg
on the x86 architecture).
Acquiring a lock simply consists of using compare-and-swap to atomically
set the futex word's value to the caller's TID if its previous value was 0.
Releasing a lock requires using compare-and-swap to set the futex word's
value to 0 if the previous value was the expected TID.

If a futex is already acquired (i.e., has a nonzero value),
waiters must employ the
.B FUTEX_LOCK_PI
operation to acquire the lock.
If other threads are waiting for the lock, then the
.B FUTEX_WAITERS
bit is set in the futex value;
in this case, the lock owner must employ the
.B FUTEX_UNLOCK_PI
operation to release the lock.

In the cases where callers are forced into the kernel
(i.e., required to perform a
.BR futex ()
operation),
they then deal directly with a so-called RT-mutex,
a kernel locking mechanism which implements the required
priority-inheritance semantics.
After the RT-mutex is acquired, the futex value is updated accordingly,
before the calling thread returns to user space.
.\" FIXME ===== End of adapted Hart/Guniguntala text =====

It is important to note
.\" FIXME We need some explanation here of *why* it is important to
.\"       note this. Can someone explain?
that the kernel will update the futex word's value prior
to returning to user space.
Unlike the other futex operations described above,
the PI futex operations are designed
for the implementation of very specific IPC mechanisms.
.\"
.\" FIXME XXX In discussing errors for FUTEX_CMP_REQUEUE_PI, Darren Hart
.\"       made the observation that "EINVAL is returned if the non-pi 
.\"       to pi or op pairing semantics are violated."
.\"       Probably there needs to be a general statement about this
.\"       requirement, probably located at about this point in the page.
.\"       Darren, care to take a shot at this?
.\"
.\" FIXME Somewhere on this page (I guess under the discussion of PI
.\"       futexes) we need a discussion of the FUTEX_OWNER_DIED bit.
.\"       Can someone propose a text?

PI futexes are operated on by specifying one of the following values in
.IR futex_op :
.\"
.\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
.\"
.TP
.BR FUTEX_LOCK_PI " (since Linux 2.6.18)"
.\" commit c87e2837be82df479a6bae9f155c43516d2feebc
.\"
.\" FIXME I did some significant rewording of tglx's text.
.\"       Please check, in case I injected errors.
.\"
This operation is used after after an attempt to acquire
the lock via an atomic user-space instruction failed
because the futex word has a nonzero value\(emspecifically,
because it contained the namespace-specific TID of the lock owner.
.\" FIXME In the preceding line, what does "namespace-specific" mean?
.\"       (I kept those words from tglx.)
.\"       That is, what kind of namespace are we talking about?
.\"       (I suppose we are talking PID namespaces here, but I want to
.\"       be sure.)

The operation checks the value of the futex word at the address
.IR uaddr .
If the value is 0, then the kernel tries to atomically set
the futex value to the caller's TID.
If that fails,
.\" FIXME What would be the cause of failure?
or the futex word's value is nonzero,
the kernel atomically sets the
.B FUTEX_WAITERS
bit, which signals the futex owner that it cannot unlock the futex in
user space atomically by setting the futex value to 0.
After that, the kernel tries to find the thread which is
associated with the owner TID,
.\" FIXME Could I get a bit more detail on the next two lines?
.\"       What is "creates or reuses kernel state" about?
creates or reuses kernel state on behalf of the owner
and attaches the waiter to it.
.\" FIXME In the next line, what type of "priority" are we talking about?
.\"       Realtime priorities for SCHED_FIFO and SCHED_RR?
.\"       Or something else?
The enqueueing of the waiter is in descending priority order if more
than one waiter exists.
.\" FIXME What does "bandwidth" refer to in the next line?
The owner inherits either the priority or the bandwidth of the waiter.
.\" FIXME In the preceding line, what determines whether the
.\"       owner inherits the priority versus the bandwidth?
.\"
.\" FIXME Could I get some help translating the next sentence into
.\"       something that user-space developers (and I) can understand?
.\"       In particular, what are "nested locks" in this context?
This inheritance follows the lock chain in the case of
nested locking and performs deadlock detection.

.\" FIXME tglx says "The timeout argument is handled as described in
.\"       FUTEX_WAIT." However, it appears to me that this is not right.
.\"       Is the following formulation correct?
The
.I timeout
argument provides a timeout for the lock attempt.
It is interpreted as an absolute time, measured against the
.BR CLOCK_REALTIME
clock.
If
.I timeout
is NULL, the operation will block indefinitely.

The
.IR uaddr2 ,
.IR val ,
and
.IR val3
arguments are ignored.
.\"
.\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
.\"
.TP
.BR FUTEX_TRYLOCK_PI " (since Linux 2.6.18)"
.\" commit c87e2837be82df479a6bae9f155c43516d2feebc
This operation tries to acquire the futex at
.IR uaddr .
.\" FIXME I think it would be helpful here to say a few more words about
.\"       the difference(s) between FUTEX_LOCK_PI and FUTEX_TRYLOCK_PI.
.\"       Can someone propose something?
.\"
.\" FIXME(Torvald)  Additionally, we claim above that just FUTEX_WAITERS
.\"       is never an allowed state.
It deals with the situation where the TID value at
.I uaddr
is 0, but the
.B FUTEX_WAITERS
bit is set.
.\" FIXME How does the situation in the previous sentence come about?
.\"       Probably it would be helpful to say something about that in
.\"       the man page.
.\" FIXME And *how* does FUTEX_TRYLOCK_PI deal with this situation?
User space cannot handle this condition in a race-free manner

The
.IR uaddr2 ,
.IR val ,
.IR timeout ,
and
.IR val3
arguments are ignored.
.\"
.\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
.\"
.TP
.BR FUTEX_UNLOCK_PI " (since Linux 2.6.18)"
.\" commit c87e2837be82df479a6bae9f155c43516d2feebc
This operation wakes the top priority waiter that is waiting in
.B FUTEX_LOCK_PI
on the futex address provided by the
.I uaddr
argument.

This is called when the user space value at
.I uaddr
cannot be changed atomically from a TID (of the owner) to 0.

The
.IR uaddr2 ,
.IR val ,
.IR timeout ,
and
.IR val3
arguments are ignored.
.\"
.\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
.\"
.TP
.BR FUTEX_CMP_REQUEUE_PI " (since Linux 2.6.31)"
.\" commit 52400ba946759af28442dee6265c5c0180ac7122
This operation is a PI-aware variant of
.BR FUTEX_CMP_REQUEUE .
It requeues waiters that are blocked via
.B FUTEX_WAIT_REQUEUE_PI
on
.I uaddr
from a non-PI source futex
.RI ( uaddr )
to a PI target futex
.RI ( uaddr2 ).

As with
.BR FUTEX_CMP_REQUEUE ,
this operation wakes up a maximum of
.I val
waiters that are waiting on the futex at
.IR uaddr .
However, for
.BR FUTEX_CMP_REQUEUE_PI ,
.I val
is required to be 1
(since the main point is to avoid a thundering herd).
The remaining waiters are removed from the wait queue of the source futex at
.I uaddr
and added to the wait queue of the target futex at
.IR uaddr2 .

The
.I val2
.\" val2 is the cap on the number of requeued waiters.
.\" In the glibc pthread_cond_broadcast() implementation, this argument
.\" is specified as INT_MAX, and for pthread_cond_signal() it is 0.
and
.I val3
arguments serve the same purposes as for
.BR FUTEX_CMP_REQUEUE .
.\"
.\" FIXME The page at http://locklessinc.com/articles/futex_cheat_sheet/
.\"       notes that "priority-inheritance Futex to priority-inheritance
.\"       Futex requeues are currently unsupported". Do we need to say
.\"       something in the man page about that?
.\"
.\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
.\"
.TP
.BR FUTEX_WAIT_REQUEUE_PI " (since Linux 2.6.31)"
.\" commit 52400ba946759af28442dee6265c5c0180ac7122
.\"
.\" FIXME I find the next sentence (from tglx) pretty hard to grok.
.\"       Could someone explain it a bit more?
Wait operation to wait on a non-PI futex at
.I uaddr
and potentially be requeued onto a PI futex at
.IR uaddr2 .
The wait operation on
.I uaddr
is the same as
.BR FUTEX_WAIT .
.\"
.\" FIXME I'm not quite clear on the meaning of the following sentence.
.\"       Is this trying to say that while blocked in a
.\"       FUTEX_WAIT_REQUEUE_PI, it could happen that another
.\"       task does a FUTEX_WAKE on uaddr that simply causes
.\"       a normal wake, with the result that the FUTEX_WAIT_REQUEUE_PI
.\"       does not complete? What happens then to the FUTEX_WAIT_REQUEUE_PI
.\"       opertion? Does it remain blocked, or does it unblock
.\"       In which case, what does user space see?
The waiter can be removed from the wait on
.I uaddr
via
.BR FUTEX_WAKE
without requeueing on
.IR uaddr2 .

.\" FIXME Please check the following. tglx said "The timeout argument
.\"       is handled as described in FUTEX_WAIT.", but the truth is
.\"       as below, AFAICS
If
.I timeout
is not NULL, it specifies a timeout for the wait operation;
this timeout is interpreted as outlined above in the description of the
.BR FUTEX_CLOCK_REALTIME
option.
If
.I timeout
is NULL, the operation can block indefinitely.

The
.I val3
argument is ignored.
.\" FIXME Re the preceding sentence... Actually 'val3' is internally set to
.\"       FUTEX_BITSET_MATCH_ANY before calling futex_wait_requeue_pi().
.\"       I'm not sure we need to say anything about this though.
.\"       Comments?

The
.BR FUTEX_WAIT_REQUEUE_PI
and
.BR FUTEX_CMP_REQUEUE_PI
were added to support a fairly specific use case:
support for priority-inheritance-aware POSIX threads condition variables.
The idea is that these operations should always be paired,
in order to ensure that user space and the kernel remain in sync.
Thus, in the
.BR FUTEX_WAIT_REQUEUE_PI
operation, the user-space application pre-specifies the target
of the requeue that takes place in the
.BR FUTEX_CMP_REQUEUE_PI
operation.
.\"
.\" Darren Hart notes that a patch to allow glibc to fully support
.\" PI-aware pthreads condition variables has not yet been accepted into
.\" glibc. The story is complex, and can be found at
.\" https://sourceware.org/bugzilla/show_bug.cgi?id=11588
.\" Darren notes that in the meantime, the patch is shipped with various
.\" PREEMPT_RT-enabled Linux systems.
.\"
.\" Related to the preceding, Darren proposed that somewhere, man-pages
.\" should document the following point:
.\"
.\"     While the Linux kernel, since 2.6.31, supports requeueing of
.\"     priority-inheritance (PI) aware mutexes via the
.\"     FUTEX_WAIT_REQUEUE_PI and FUTEX_CMP_REQUEUE_PI futex operations,
.\"     the glibc implementation does not yet take full advantage of this.
.\"     Specifically, the condvar internal data lock remains a non-PI aware
.\"     mutex, regardless of the type of the pthread_mutex associated with
.\"     the condvar. This can lead to an unbounded priority inversion on
.\"     the internal data lock even when associating a PI aware
.\"     pthread_mutex with a condvar during a pthread_cond*_wait
.\"     operation. For this reason, it is not recommended to rely on
.\"     priority inheritance when using pthread condition variables.
.\"
.\" The problem is that the obvious location for this text is
.\" the pthread_cond*wait(3) man page. However, such a man page
.\" does not currently exist.
.\"
.\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
.\"
.SH RETURN VALUE
.PP
In the event of an error, all operations return \-1 and set
.I errno
to indicate the cause of the error.
The return value on success depends on the operation,
as described in the following list:
.TP
.B FUTEX_WAIT
Returns 0 if the caller was woken up.
Note that a wake-up can also be caused by common futex usage patterns
in unrelated code that happened to have previously used the futex word's
memory location (e.g., typical futex-based implementations of
Pthreads mutexes can cause this under some conditions).
Therefore, callers should always conservatively assume that a return
value of 0 can mean a spurious wake-up, and use the futex word's value
(i.e., the user space synchronization scheme)
    to decide whether to continue to block or not.
.TP
.B FUTEX_WAKE
Returns the number of waiters that were woken up.
.TP
.B FUTEX_FD
Returns the new file descriptor associated with the futex.
.TP
.B FUTEX_REQUEUE
Returns the number of waiters that were woken up.
.TP
.B FUTEX_CMP_REQUEUE
Returns the total number of waiters that were woken up or
requeued to the futex for the futex word at
.IR uaddr2 .
If this value is greater than
.IR val ,
then difference is the number of waiters requeued to the futex for the
futex word at
.IR uaddr2 .
.TP
.B FUTEX_WAKE_OP
Returns the total number of waiters that were woken up.
This is the sum of the woken waiters on the two futexes for
the futex words at
.I uaddr
and
.IR uaddr2 .
.TP
.B FUTEX_WAIT_BITSET
Returns 0 if the caller was woken up.
See
.B FUTEX_WAIT
for how to interpret this correctly in practice.
.TP
.B FUTEX_WAKE_BITSET
Returns the number of waiters that were woken up.
.TP
.B FUTEX_LOCK_PI
Returns 0 if the futex was successfully locked.
.TP
.B FUTEX_TRYLOCK_PI
Returns 0 if the futex was successfully locked.
.TP
.B FUTEX_UNLOCK_PI
Returns 0 if the futex was successfully unlocked.
.TP
.B FUTEX_CMP_REQUEUE_PI
Returns the total number of waiters that were woken up or
requeued to the futex for the futex word at
.IR uaddr2 .
If this value is greater than
.IR val ,
then difference is the number of waiters requeued to the futex for
the futex word at
.IR uaddr2 .
.TP
.B FUTEX_WAIT_REQUEUE_PI
Returns 0 if the caller was successfully requeued to the futex for
the futex word at
.IR uaddr2 .
.\"
.\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
.\"
.SH ERRORS
.TP
.B EACCES
No read access to the memory of a futex word.
.TP
.B EAGAIN
.RB ( FUTEX_WAIT ,
.BR FUTEX_WAIT_BITSET ,
.BR FUTEX_WAIT_REQUEUE_PI )
The value pointed to by
.I uaddr
was not equal to the expected value
.I val
at the time of the call.

.BR Note :
on Linux, the symbolic names
.B EAGAIN
and
.B EWOULDBLOCK
(both of which appear in different parts of the kernel futex code)
have the same value.
.TP
.B EAGAIN
.RB ( FUTEX_CMP_REQUEUE ,
.BR FUTEX_CMP_REQUEUE_PI )
The value pointed to by
.I uaddr
is not equal to the expected value
.IR val3 .
.\" FIXME: Is the following sentence correct?
.\" I would prefer to remove this sentence. --triegel@redhat.com
(This probably indicates a race;
use the safe
.B FUTEX_WAKE
now.)
.\" 
.\" FIXME XXX Should there be an EAGAIN case for FUTEX_TRYLOCK_PI?
.\"       It seems so, looking at the handling of the rt_mutex_trylock()
.\"       call in futex_lock_pi()
.\"       (Davidlohr also thinks so.)
.\" 
.TP
.BR EAGAIN
.RB ( FUTEX_LOCK_PI ,
.BR FUTEX_TRYLOCK_PI ,
.BR FUTEX_CMP_REQUEUE_PI )
The futex owner thread ID of
.I uaddr
(for
.BR FUTEX_CMP_REQUEUE_PI :
.IR uaddr2 )
is about to exit,
but has not yet handled the internal state cleanup.
Try again.
.TP
.BR EDEADLK
.RB ( FUTEX_LOCK_PI ,
.BR FUTEX_TRYLOCK_PI ,
.BR FUTEX_CMP_REQUEUE_PI )
The futex word at
.I uaddr
is already locked by the caller.
.TP
.BR EDEADLK
.\" FIXME I reworded tglx's text somewhat; is the following okay?
.\" FIXME XXX I see that kernel/locking/rtmutex.c uses EDEADLK in some
.\"       iplaces, and EDEADLOCK in others. On almost all architectures
.\"       these constants are synonymous. Is there a reason that both
.\"       names are used?
.RB ( FUTEX_CMP_REQUEUE_PI )
While requeueing a waiter to the PI futex for the futex word at
.IR uaddr2 ,
the kernel detected a deadlock.
.TP
.B EFAULT
A required pointer argument (i.e.,
.IR uaddr ,
.IR uaddr2 ,
or
.IR timeout )
did not point to a valid user-space address.
.TP
.B EINTR
A
.B FUTEX_WAIT
or
.B FUTEX_WAIT_BITSET
operation was interrupted by a signal (see
.BR signal (7)).
In kernels before Linux 2.6.22, this error could also be returned for
on a spurious wakeup; since Linux 2.6.22, this no longer happens.
.TP
.B EINVAL
The operation in
.IR futex_op
is one of those that employs a timeout, but the supplied
.I timeout
argument was invalid
.RI ( tv_sec
was less than zero, or
.IR tv_nsec
was not less than 1000,000,000).
.TP
.B EINVAL
The operation specified in
.IR futex_op
employs one or both of the pointers
.I uaddr
and
.IR uaddr2 ,
but one of these does not point to a valid object\(emthat is,
the address is not four-byte-aligned.
.TP
.B EINVAL
.RB ( FUTEX_WAIT_BITSET ,
.BR FUTEX_WAKE_BITSET )
The bitset supplied in
.IR val3
is zero.
.TP
.B EINVAL
.RB ( FUTEX_CMP_REQUEUE_PI )
.I uaddr
equals
.IR uaddr2
(i.e., an attempt was made to requeue to the same futex).
.TP
.BR EINVAL
.RB ( FUTEX_FD )
The signal number supplied in
.I val
is invalid.
.TP
.B EINVAL
.RB ( FUTEX_WAKE ,
.BR FUTEX_WAKE_OP ,
.BR FUTEX_WAKE_BITSET ,
.BR FUTEX_REQUEUE ,
.BR FUTEX_CMP_REQUEUE )
The kernel detected an inconsistency between the user-space state at
.I uaddr
and the kernel state\(emthat is, it detected a waiter which waits in
.BR FUTEX_LOCK_PI
on
.IR uaddr .
.TP
.B EINVAL
.RB ( FUTEX_LOCK_PI ,
.BR FUTEX_TRYLOCK_PI ,
.BR FUTEX_UNLOCK_PI )
The kernel detected an inconsistency between the user-space state at
.I uaddr
and the kernel state.
This indicates either state corruption
.\" FIXME tglx did not mention the "state corruption" for FUTEX_UNLOCK_PI.
.\"       Does that case also apply for FUTEX_UNLOCK_PI?
or that the kernel found a waiter on
.I uaddr
which is waiting via
.BR FUTEX_WAIT
or
.BR FUTEX_WAIT_BITSET .
.TP
.B EINVAL
.RB ( FUTEX_CMP_REQUEUE_PI )
The kernel detected an inconsistency between the user-space state at
.I uaddr2
and the kernel state;
that is, the kernel detected a waiter which waits via
.BR FUTEX_WAIT
.\" FIXME tglx did not mention FUTEX_WAIT_BITSET here,
.\"       but should that not also be included here?
on
.IR uaddr2 .
.TP
.B EINVAL
.RB ( FUTEX_CMP_REQUEUE_PI )
The kernel detected an inconsistency between the user-space state at
.I uaddr
and the kernel state;
that is, the kernel detected a waiter which waits via
.BR FUTEX_WAIT
or
.BR FUTEX_WAIT_BITESET
on
.IR uaddr .
.TP
.B EINVAL
.RB ( FUTEX_CMP_REQUEUE_PI )
The kernel detected an inconsistency between the user-space state at
.I uaddr
and the kernel state;
that is, the kernel detected a waiter which waits on
.I uaddr
via
.BR FUTEX_LOCK_PI
(instead of
.BR FUTEX_WAIT_REQUEUE_PI ).
.TP
.B EINVAL
.RB ( FUTEX_CMP_REQUEUE_PI )
.\" FIXME XXX The following is a reworded version of Darren Hart's text.
.\"       Please check that I did not introduce any errors.
An attempt was made to requeue a waiter to a futex other than that
specified by the matching
.B FUTEX_WAIT_REQUEUE_PI
call for that waiter.
.TP
.B EINVAL
.RB ( FUTEX_CMP_REQUEUE_PI )
The
.I val
argument is not 1.
.TP
.B EINVAL
Invalid argument.
.TP
.BR ENOMEM
.RB ( FUTEX_LOCK_PI ,
.BR FUTEX_TRYLOCK_PI ,
.BR FUTEX_CMP_REQUEUE_PI )
The kernel could not allocate memory to hold state information.
.TP
.B ENFILE
.RB ( FUTEX_FD )
The system limit on the total number of open files has been reached.
.TP
.B ENOSYS
Invalid operation specified in
.IR futex_op .
.TP
.B ENOSYS
The
.BR FUTEX_CLOCK_REALTIME
option was specified in
.IR futex_op ,
but the accompanying operation was neither
.BR FUTEX_WAIT_BITSET
nor
.BR FUTEX_WAIT_REQUEUE_PI .
.TP
.BR ENOSYS
.RB ( FUTEX_LOCK_PI ,
.BR FUTEX_TRYLOCK_PI ,
.BR FUTEX_UNLOCK_PI ,
.BR FUTEX_CMP_REQUEUE_PI ,
.BR FUTEX_WAIT_REQUEUE_PI )
A run-time check determined that the operation is not available.
The PI futex operations are not implemented on all architectures and
are not supported on some CPU variants.
.TP
.BR EPERM
.RB ( FUTEX_LOCK_PI ,
.BR FUTEX_TRYLOCK_PI ,
.BR FUTEX_CMP_REQUEUE_PI )
The caller is not allowed to attach itself to the futex at
.I uaddr
(for
.BR FUTEX_CMP_REQUEUE_PI :
the futex at
.IR uaddr2 ).
(This may be caused by a state corruption in user space.)
.TP
.BR EPERM
.RB ( FUTEX_UNLOCK_PI )
The caller does not own the lock represented by the futex word.
.TP
.BR ESRCH
.RB ( FUTEX_LOCK_PI ,
.BR FUTEX_TRYLOCK_PI ,
.BR FUTEX_CMP_REQUEUE_PI )
.\" FIXME I reworded the following sentence a bit differently from
.\"       tglx's formulation. Is it okay?
The thread ID in the futex word at
.I uaddr
does not exist.
.TP
.BR ESRCH
.RB ( FUTEX_CMP_REQUEUE_PI )
.\" FIXME I reworded the following sentence a bit differently from
.\"       tglx's formulation. Is it okay?
The thread ID in the futex word at
.I uaddr2
does not exist.
.TP
.B ETIMEDOUT
The operation in
.IR futex_op
employed the timeout specified in
.IR timeout ,
and the timeout expired before the operation completed.
.\"
.\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
.\"
.SH VERSIONS
.PP
Futexes were first made available in a stable kernel release
with Linux 2.6.0.

Initial futex support was merged in Linux 2.5.7 but with different
semantics from what was described above.
A four-argument system call with the semantics
described in this page was introduced in Linux 2.5.40.
In Linux 2.5.70, one argument
was added.
In Linux 2.6.7, a sixth argument was added\(emmessy, especially
on the s390 architecture.
.SH CONFORMING TO
This system call is Linux-specific.
.SH NOTES
Glibc does not provide a wrapper for this system call; call it using
.BR syscall (2).
.\" TODO FIXME(Torvald) Above, we cite this section and claim it contains
.\" details on the synchronization semantics; add the C11 equivalents
.\" here (or whatever we find consensus for).
.\"
.\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
.\"
.SH EXAMPLE
.\" FIXME Is it worth having an example program?
.\" FIXME Anything obviously broken in the example program?
.\"
The program below demonstrates use of futexes in a program
where parent and child use a pair of futexes located inside a
shared anonymous mapping to synchronize access to a shared resource:
the terminal.
The two processes each write
.IR nloops
(a command-line argument that defaults to 5 if omitted)
messages to the terminal and employ a synchronization protocol
that ensures that they alternate in writing messages.
Upon running this program we see output such as the following:

.in +4n
.nf
$ \fB./futex_demo\fP
Parent (18534) 0
Child  (18535) 0
Parent (18534) 1
Child  (18535) 1
Parent (18534) 2
Child  (18535) 2
Parent (18534) 3
Child  (18535) 3
Parent (18534) 4
Child  (18535) 4
.fi
.in
.SS Program source
\&
.nf
/* futex_demo.c

   Usage: futex_demo [nloops]
                    (Default: 5)

   Demonstrate the use of futexes in a program where parent and child
   use a pair of futexes located inside a shared anonymous mapping to
   synchronize access to a shared resource: the terminal. The two
   processes each write \(aqnum\-loops\(aq messages to the terminal and employ
   a synchronization protocol that ensures that they alternate in
   writing messages.
*/
#define _GNU_SOURCE
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/mman.h>
#include <sys/syscall.h>
#include <linux/futex.h>
#include <sys/time.h>

#define errExit(msg)    do { perror(msg); exit(EXIT_FAILURE); \\
                        } while (0)

static int *futex1, *futex2, *iaddr;

static int
futex(int *uaddr, int futex_op, int val,
      const struct timespec *timeout, int *uaddr2, int val3)
{
    return syscall(SYS_futex, uaddr, futex_op, val,
                   timeout, uaddr, val3);
}

/* Acquire the futex pointed to by \(aqfutexp\(aq: wait for its value to
   become 1, and then set the value to 0. */

static void
fwait(int *futexp)
{
    int s;

    /* __sync_bool_compare_and_swap(ptr, oldval, newval) is a gcc
       built\-in function.  It atomically performs the equivalent of:

           if (*ptr == oldval)
               *ptr = newval;

       It returns true if the test yielded true and *ptr was updated.
       The alternative here would be to employ the equivalent atomic
       machine\-language instructions.  For further information, see
       the GCC Manual. */

    while (1) {

        /* Is the futex available? */

        if (__sync_bool_compare_and_swap(futexp, 1, 0))
            break;      /* Yes */

        /* Futex is not available; wait */

        s = futex(futexp, FUTEX_WAIT, 0, NULL, NULL, 0);
        if (s == \-1 && errno != EAGAIN)
            errExit("futex\-FUTEX_WAIT");
    }
}

/* Release the futex pointed to by \(aqfutexp\(aq: if the futex currently
   has the value 0, set its value to 1 and the wake any futex waiters,
   so that if the peer is blocked in fpost(), it can proceed. */

static void
fpost(int *futexp)
{
    int s;

    /* __sync_bool_compare_and_swap() was described in comments above */

    if (__sync_bool_compare_and_swap(futexp, 0, 1)) {

        s = futex(futexp, FUTEX_WAKE, 1, NULL, NULL, 0);
        if (s  == \-1)
            errExit("futex\-FUTEX_WAKE");
    }
}

int
main(int argc, char *argv[])
{
    pid_t childPid;
    int j, nloops;

    setbuf(stdout, NULL);

    nloops = (argc > 1) ? atoi(argv[1]) : 5;

    /* Create a shared anonymous mapping that will hold the futexes.
       Since the futexes are being shared between processes, we
       subsequently use the "shared" futex operations (i.e., not the
       ones suffixed "_PRIVATE") */

    iaddr = mmap(NULL, sizeof(int) * 2, PROT_READ | PROT_WRITE,
                MAP_ANONYMOUS | MAP_SHARED, \-1, 0);
    if (iaddr == MAP_FAILED)
        errExit("mmap");

    futex1 = &iaddr[0];
    futex2 = &iaddr[1];

    *futex1 = 0;        /* State: unavailable */
    *futex2 = 1;        /* State: available */

    /* Create a child process that inherits the shared anonymous
       mapping */

    childPid = fork();
    if (childPid == \-1)
        errExit("fork");

    if (childPid == 0) {        /* Child */
        for (j = 0; j < nloops; j++) {
            fwait(futex1);
            printf("Child  (%ld) %d\\n", (long) getpid(), j);
            fpost(futex2);
        }

        exit(EXIT_SUCCESS);
    }

    /* Parent falls through to here */

    for (j = 0; j < nloops; j++) {
        fwait(futex2);
        printf("Parent (%ld) %d\\n", (long) getpid(), j);
        fpost(futex1);
    }

    wait(NULL);

    exit(EXIT_SUCCESS);
}
.fi
.SH SEE ALSO
.ad l
.BR get_robust_list (2),
.BR restart_syscall (2),
.BR futex (7)
.PP
The following kernel source files:
.IP * 2
.I Documentation/pi-futex.txt
.IP *
.I Documentation/futex-requeue-pi.txt
.IP *
.I Documentation/locking/rt-mutex.txt
.IP *
.I Documentation/locking/rt-mutex-design.txt
.IP *
.I Documentation/robust-futex-ABI.txt
.PP
Franke, H., Russell, R., and Kirwood, M., 2002.
\fIFuss, Futexes and Furwocks: Fast Userlevel Locking in Linux\fP
(from proceedings of the Ottawa Linux Symposium 2002),
.br
.UR http://kernel.org\:/doc\:/ols\:/2002\:/ols2002-pages-479-495.pdf
.UE

Hart, D., 2009. \fIA futex overview and update\fP,
.UR http://lwn.net/Articles/360699/
.UE

Hart, D. and Guniguntala, D., 2009.
\fIRequeue-PI: Making Glibc Condvars PI-Aware\fP
(from proceedings of the 2009 Real-Time Linux Workshop),
.UR http://lwn.net/images/conf/rtlws11/papers/proc/p10.pdf
.UE

Drepper, U., 2011. \fIFutexes Are Tricky\fP,
.UR http://www.akkadia.org/drepper/futex.pdf
.UE
.PP
Futex example library, futex-*.tar.bz2 at
.br
.UR ftp://ftp.kernel.org\:/pub\:/linux\:/kernel\:/people\:/rusty/
.UE
.\"
.\" FIXME Are there any other resources that should be listed
.\"       in the SEE ALSO section?
.\" FIXME(Torvald) We should probably refer to the glibc code here, in
.\"       particular the glibc-internal futex wrapper functions that are
.\"       WIP, and the generic pthread_mutex_t and perhaps condvar
.\"       implementations.

^ permalink raw reply	[flat|nested] 22+ messages in thread

* Re: Revised futex(2) man page for review
  2015-03-28  8:53 Revised futex(2) man page for review Michael Kerrisk (man-pages)
@ 2015-03-28  8:56 ` Michael Kerrisk (man-pages)
  2015-03-28 11:47 ` Peter Zijlstra
  2015-03-31  1:48 ` Rusty Russell
  2 siblings, 0 replies; 22+ messages in thread
From: Michael Kerrisk (man-pages) @ 2015-03-28  8:56 UTC (permalink / raw)
  To: Thomas Gleixner, Darren Hart
  Cc: mtk.manpages, Carlos O'Donell, Ingo Molnar, Jakub Jelinek,
	linux-man, lkml, Davidlohr Bueso, Arnd Bergmann, Steven Rostedt,
	Peter Zijlstra, Linux API, Torvald Riegel, Roland McGrath,
	Darren Hart, Anton Blanchard, Eric Dumazet, bill o gallmeister,
	Jan Kiszka, Daniel Wagner, Rich Felker, Andy Lutomirski,
	bert hubert, Rusty Russell, Heinrich Schuchardt

On 03/28/2015 09:53 AM, Michael Kerrisk (man-pages) wrote:
> Hello all,
[...]
> So, please take a look at the page below. At this point,
> I would most especially appreciate help with the FIXMEs.

One more point I should have added. The revised page
currently sits in a Git branch, here:
http://git.kernel.org/cgit/docs/man-pages/man-pages.git/log/?h=draft_futex

Thanks,

Michael

-- 
Michael Kerrisk
Linux man-pages maintainer; http://www.kernel.org/doc/man-pages/
Linux/UNIX System Programming Training: http://man7.org/training/

^ permalink raw reply	[flat|nested] 22+ messages in thread

* Re: Revised futex(2) man page for review
  2015-03-28  8:53 Revised futex(2) man page for review Michael Kerrisk (man-pages)
  2015-03-28  8:56 ` Michael Kerrisk (man-pages)
@ 2015-03-28 11:47 ` Peter Zijlstra
  2015-03-28 12:03   ` Peter Zijlstra
                     ` (4 more replies)
  2015-03-31  1:48 ` Rusty Russell
  2 siblings, 5 replies; 22+ messages in thread
From: Peter Zijlstra @ 2015-03-28 11:47 UTC (permalink / raw)
  To: Michael Kerrisk (man-pages)
  Cc: Thomas Gleixner, Darren Hart, Carlos O'Donell, Ingo Molnar,
	Jakub Jelinek, linux-man, lkml, Davidlohr Bueso, Arnd Bergmann,
	Steven Rostedt, Linux API, Torvald Riegel, Roland McGrath,
	Darren Hart, Anton Blanchard, Eric Dumazet, bill o gallmeister,
	Jan Kiszka, Daniel Wagner, Rich Felker, Andy Lutomirski,
	bert hubert, Rusty Russell, Heinrich Schuchardt

On Sat, Mar 28, 2015 at 09:53:21AM +0100, Michael Kerrisk (man-pages) wrote:
> So, please take a look at the page below. At this point,
> I would most especially appreciate help with the FIXMEs.

For people who cannot read that troff gibberish (me)..

---
FUTEX(2)                   Linux Programmer's Manual                  FUTEX(2)




NAME
       futex - fast user-space locking

SYNOPSIS
       #include <linux/futex.h>
       #include <sys/time.h>

       int futex(int *uaddr, int futex_op, int val,
                 const struct timespec *timeout,   /* or: u32 val2 */
                 int *uaddr2, int val3);

       Note: There is no glibc wrapper for this system call; see NOTES.

DESCRIPTION
       The  futex()  system call provides a method for waiting until a certain
       condition becomes true.  It is typically used as a  blocking  construct
       in the context of shared-memory synchronization: The program implements
       the majority of the synchronization in user  space,  and  uses  one  of
       operations  of  the  system call when it is likely that it has to block
       for a longer time until the condition becomes true.  The  program  uses
       another  operation of the system call to wake anyone waiting for a par‐
       ticular condition.

       The condition is represented by the futex word, which is an address  in
       memory  supplied to the futex() system call, and the value at this mem‐
       ory location.  (While the virtual addresses for the same memory in sep‐
       arate  processes  may  not be equal, the kernel maps them internally so
       that the same memory mapped in different locations will correspond  for
       futex() calls.)

       When  executing  a futex operation that requests to block a thread, the
       kernel will only block if the futex word has the value that the calling
       thread  supplied  as expected value.  The load from the futex word, the
       comparison with the expected value, and the actual blocking will happen
       atomically  and  totally ordered with respect to concurrently executing
       futex operations on the same futex word, such as operations  that  wake
       threads  blocked  on  this futex word.  Thus, the futex word is used to
       connect the synchronization in user spac  with  the  implementation  of
       blocking by the kernel; similar to an atomic compare-and-exchange oper‐
       ation that potentially changes shared memory, blocking via a  futex  is
       an atomic compare-and-block operation.  See NOTES for a detailed speci‐
       fication of the synchronization semantics.

       One example use of futexes is implementing locks.   The  state  of  the
       lock  (i.e.,  acquired or not acquired) can be represented as an atomi‐
       cally accessed flag in shared  memory.   In  the  uncontended  case,  a
       thread  can  access  or modify the lock state with atomic instructions,
       for example atomically changing it from not acquired to acquired  using
       an atomic compare-and-exchange instruction.  If a thread cannot acquire
       a lock because it is already acquired by another thread, it can request
       to  block  if  and  only the lock is still acquired by using the lock's
       flag as futex word and expecting a value that represents  the  acquired
       state.   When  releasing the lock, a thread has to first reset the lock
       state to not acquired and then execute the futex operation  that  wakes
       one  thread blocked on the futex word that is the lock's flag (this can
       be be further optimized to avoid unnecessary wake-ups).   See  futex(7)
       for more detail on how to use futexes.

       Besides  the basic wait and wake-up futex functionality, there are fur‐
       ther futex operations aimed at supporting more complex use cases.  Also
       note  that  no  explicit initialization or destruction are necessary to
       use futexes; the kernel maintains a futex  (i.e.,  the  kernel-internal
       implementation  artifact)  only  while  operations  such as FUTEX_WAIT,
       described below, are being performed on a particular futex word.

   Arguments
       The uaddr argument points to the futex word.  On all platforms, futexes
       are  four-byte  integers  that must be aligned on a four-byte boundary.
       The operation to perform on the futex  is  specified  in  the  futex_op
       argument; val is a value whose meaning and purpose depends on futex_op.

       The  remaining  arguments (timeout, uaddr2, and val3) are required only
       for certain of the futex operations  described  below.   Where  one  of
       these arguments is not required, it is ignored.

       For several blocking operations, the timeout argument is a pointer to a
       timespec structure that specifies a timeout for  the  operation.   How‐
       ever,   notwithstanding the prototype shown above, for some operations,
       this argument is instead a four-byte integer whose  meaning  is  deter‐
       mined  by  the  operation.   For these operations, the kernel casts the
       timeout value to u32, and in the remainder of this page, this  argument
       is referred to as val2 when interpreted in this fashion.

       Where  it  is  required,  the  uaddr2 argument is a pointer to a second
       futex word that is employed by the operation.   The  interpretation  of
       the final integer argument, val3, depends on the operation.

   Futex operations
       The  futex_op  argument consists of two parts: a command that specifies
       the operation to be performed, bit-wise  ORed  with  zero  or  or  more
       options  that  modify the behaviour of the operation.  The options that
       may be included in futex_op are as follows:

       FUTEX_PRIVATE_FLAG (since Linux 2.6.22)
              This option bit can be employed with all futex  operations.   It
              tells  the  kernel  that  the  futex  is process-private and not
              shared with another process (i.e., it is  only  being  used  for
              synchronization  between  threads  of  the  same process).  This
              allows the kernel to choose the fast  path  for  validating  the
              user-space address and avoids expensive VMA lookups, taking ref‐
              erence counts on file backing store, and so on.

              As a convenience, <linux/futex.h> defines  a  set  of  constants
              with  the  suffix  _PRIVATE  that  are equivalents of all of the
              operations listed below, but with  the  FUTEX_PRIVATE_FLAG  ORed
              into  the  constant  value.  Thus, there are FUTEX_WAIT_PRIVATE,
              FUTEX_WAKE_PRIVATE, and so on.

       FUTEX_CLOCK_REALTIME (since Linux 2.6.28)
              This option bit can be employed only with the  FUTEX_WAIT_BITSET
              and FUTEX_WAIT_REQUEUE_PI operations.

              If  this option is set, the kernel treats timeout as an absolute
              time based on CLOCK_REALTIME.

              If this option is not set, the kernel treats timeout as relative
              time, measured against the CLOCK_MONOTONIC clock.

       The operation specified in futex_op is one of the following:

       FUTEX_WAIT (since Linux 2.6.0)
              This operation tests that the value at the futex word pointed to
              by the address uaddr still contains the expected value val,  and
              if  so,  then sleeps awaiting FUTEX_WAKE on the futex word.  The
              load of the value of the futex word is an atomic  memory  access
              (i.e.,  using  atomic  machine  instructions  of  the respective
              architecture).  This load,  the  comparison  with  the  expected
              value,  and  starting  to  sleep  are  performed  atomically and
              totally ordered with respect to other futex  operations  on  the
              same  futex  word.  If the thread starts to sleep, it is consid‐
              ered a waiter on this futex word.  If the futex value  does  not
              match  val,  then  the  call  fails  immediately  with the error
              EAGAIN.

              The purpose of the comparison with the expected value is to pre‐
              vent  lost  wake-ups: If another thread changed the value of the
              futex word after the calling thread decided to  block  based  on
              the  prior  value, and if the other thread executed a FUTEX_WAKE
              operation (or similar wake-up) after the value change and before
              this  FUTEX_WAIT  operation,  then  the  latter will observe the
              value change and will not start to sleep.

              If the timeout argument is non-NULL, its contents specify a rel‐
              ative   timeout   for   the  wait,  measured  according  to  the
              CLOCK_MONOTONIC clock.  (This interval will be rounded up to the
              system clock granularity, and kernel scheduling delays mean that
              the blocking interval may overrun by a small amount.)  If  time‐
              out is NULL, the call blocks indefinitely.

              The arguments uaddr2 and val3 are ignored.


       FUTEX_WAKE (since Linux 2.6.0)
              This operation wakes at most val of the waiters that are waiting
              (e.g., inside FUTEX_WAIT) on  the  futex  word  at  the  address
              uaddr.   Most  commonly, val is specified as either 1 (wake up a
              single waiter) or INT_MAX (wake up all waiters).   No  guarantee
              is  provided about which waiters are awoken (e.g., a waiter with
              a higher scheduling priority is not guaranteed to be  awoken  in
              preference to a waiter with a lower priority).

              The arguments timeout, uaddr2, and val3 are ignored.


       FUTEX_FD (from Linux 2.6.0 up to and including Linux 2.6.25)
              This operation creates a file descriptor that is associated with
              the futex at uaddr.  The caller must  close  the  returned  file
              descriptor after use.  When another process or thread performs a
              FUTEX_WAKE on the futex word, the file descriptor  indicates  as
              being readable with select(2), poll(2), and epoll(7)

              The file descriptor can be used to obtain asynchronous notifica‐
              tions: if val is nonzero, then when another  process  or  thread
              executes a FUTEX_WAKE, the caller will receive the signal number
              that was passed in val.

              The arguments timeout, uaddr2 and val3 are ignored.

              To prevent race conditions, the caller should test if the  futex
              has been upped after FUTEX_FD returns.

              Because  it  was inherently racy, FUTEX_FD has been removed from
              Linux 2.6.26 onward.

       FUTEX_REQUEUE (since Linux 2.6.0)
              Avoid using this operation.  It is broken for its intended  pur‐
              pose.  Use FUTEX_CMP_REQUEUE instead.

              This  operation  performs  the  same  task as FUTEX_CMP_REQUEUE,
              except that no check is made using  the  value  in  val3.   (The
              argument val3 is ignored.)

       FUTEX_CMP_REQUEUE (since Linux 2.6.7)
              This  operation  first  checks  whether the location uaddr still
              contains the value val3.  If not, the operation fails  with  the
              error  EAGAIN.   Otherwise,  the operation wakes up a maximum of
              val waiters that are waiting on the futex at  uaddr.   If  there
              are  more  than  val  waiters,  then  the  remaining waiters are
              removed from the wait queue of the source  futex  at  uaddr  and
              added to the wait queue of the target futex at uaddr2.  The val2
              argument specifies an upper limit on the number of waiters  that
              are requeued to the futex at uaddr2.

              The  load  from  uaddr  is  an atomic memory access (i.e., using
              atomic machine instructions  of  the  respective  architecture).
              This  load,  the comparison with val3, and the requeueing of any
              waiters  are  performed  atomically  and  totally  ordered  with
              respect to other operations on the same futex word.

              This  operation  was  added  as  a  replacement  for the earlier
              FUTEX_REQUEUE.  The difference is that the check of the value at
              uaddr  can  be used to ensure that requeueing only happens under
              certain conditions.  Both operations can  be  used  to  avoid  a
              "thundering  herd" effect when FUTEX_WAKE is used and all of the
              waiters that are woken need to acquire another futex.

              Typical values to specify for val are 0 or  or  1.   (Specifying
              INT_MAX   is   not   useful,   because   it   would   make   the
              FUTEX_CMP_REQUEUE  operation  equivalent  to  FUTEX_WAKE.)   The
              limit value specified via val2 is typically either 1 or INT_MAX.
              (Specifying the argument as 0 is not useful,  because  it  would
              make the FUTEX_CMP_REQUEUE operation equivalent to FUTEX_WAIT.)

       FUTEX_WAKE_OP (since Linux 2.6.14)
              This  operation  was  added to support some user-space use cases
              where more than one futex must be handled at the same time.  The
              most  notable example is the implementation of pthread_cond_sig‐
              nal(3), which requires operations on two futexes, the  one  used
              to implement the mutex and the one used in the implementation of
              the  wait  queue  associated  with   the   condition   variable.
              FUTEX_WAKE_OP  allows such cases to be implemented without lead‐
              ing to high rates of contention and context switching.

              The FUTEX_WAIT_OP operation is equivalent to execute the follow‐
              ing  code  atomically  and totally ordered with respect to other
              futex operations on any of the two supplied futex words:

                  int oldval = *(int *) uaddr2;
                  *(int *) uaddr2 = oldval op oparg;
                  futex(uaddr, FUTEX_WAKE, val, 0, 0, 0);
                  if (oldval cmp cmparg)
                      futex(uaddr2, FUTEX_WAKE, val2, 0, 0, 0);

              In other words, FUTEX_WAIT_OP does the following:

              *  saves the original value of the futex word at uaddr2 and per‐
                 forms  an  operation  to  modify  the  value  of the futex at
                 uaddr2; this is an  atomic  read-modify-write  memory  access
                 (i.e.,  using  atomic  machine instructions of the respective
                 architecture)

              *  wakes up a maximum of val waiters on the futex for the  futex
                 word at uaddr; and

              *  dependent  on  the results of a test of the original value of
                 the futex word at uaddr2, wakes up a maximum of val2  waiters
                 on the futex for the futex word at uaddr2.

              The  operation  and  comparison  that  are  to  be performed are
              encoded in the bits of  the  argument  val3.   Pictorially,  the
              encoding is:

                      +---+---+-----------+-----------+
                      |op |cmp|   oparg   |  cmparg   |
                      +---+---+-----------+-----------+
                        4   4       12          12    <== # of bits

              Expressed in code, the encoding is:

                  #define FUTEX_OP(op, oparg, cmp, cmparg) \
                                  (((op & 0xf) << 28) | \
                                  ((cmp & 0xf) << 24) | \
                                  ((oparg & 0xfff) << 12) | \
                                  (cmparg & 0xfff))

              In the above, op and cmp are each one of the codes listed below.
              The oparg and cmparg  components  are  literal  numeric  values,
              except as noted below.

              The op component has one of the following values:

                  FUTEX_OP_SET        0  /* uaddr2 = oparg; */
                  FUTEX_OP_ADD        1  /* uaddr2 += oparg; */
                  FUTEX_OP_OR         2  /* uaddr2 |= oparg; */
                  FUTEX_OP_ANDN       3  /* uaddr2 &= ~oparg; */
                  FUTEX_OP_XOR        4  /* uaddr2 ^= oparg; */

              In  addition,  bit-wise ORing the following value into op causes
              (1 << oparg) to be used as the operand:

                  FUTEX_OP_ARG_SHIFT  8  /* Use (1 << oparg) as operand */

              The cmp field is one of the following:

                  FUTEX_OP_CMP_EQ     0  /* if (oldval == cmparg) wake */
                  FUTEX_OP_CMP_NE     1  /* if (oldval != cmparg) wake */
                  FUTEX_OP_CMP_LT     2  /* if (oldval < cmparg) wake */
                  FUTEX_OP_CMP_LE     3  /* if (oldval <= cmparg) wake */
                  FUTEX_OP_CMP_GT     4  /* if (oldval > cmparg) wake */
                  FUTEX_OP_CMP_GE     5  /* if (oldval >= cmparg) wake */

              The return value of FUTEX_WAKE_OP is the sum of  the  number  of
              waiters  woken  on  the  futex  uaddr plus the number of waiters
              woken on the futex uaddr2.

       FUTEX_WAIT_BITSET (since Linux 2.6.25)
              This operation is like FUTEX_WAIT except that val3  is  used  to
              provide a 32-bit bitset to the kernel.  This bitset is stored in
              the kernel-internal state of the waiter.  See the description of
              FUTEX_WAKE_BITSET for further details.

              The  FUTEX_WAIT_BITSET  operation  also  interprets  the timeout
              argument differently from FUTEX_WAIT.   See  the  discussion  of
              FUTEX_CLOCK_REALTIME, above.

              The uaddr2 argument is ignored.

       FUTEX_WAKE_BITSET (since Linux 2.6.25)
              This  operation  is  the same as FUTEX_WAKE except that the val3
              argument is used to provide a 32-bit bitset to the kernel.  This
              bitset  is used to select which waiters should be woken up.  The
              selection is done by a bit-wise AND of the "wake" bitset  (i.e.,
              the value in val3) and the bitset which is stored in the kernel-
              internal state of the waiter (the  "wait"  bitset  that  is  set
              using  FUTEX_WAIT_BITSET).   All  of  the  waiters for which the
              result of the AND is nonzero are woken up; the remaining waiters
              are left sleeping.

              The  effect  of  FUTEX_WAIT_BITSET  and  FUTEX_WAKE_BITSET is to
              allow selective wake-ups among multiple waiters that are blocked
              on the same futex.  Note, however, that using this bitset multi‐
              plexing feature on a futex is less efficient than  simply  using
              multiple futexes, because employing bitset multiplexing requires
              the kernel to check all waiters on a futex, including those that
              are not interested in being woken up (i.e., they do not have the
              relevant bit set in their "wait" bitset).

              The uaddr2 and timeout arguments are ignored.

              The  FUTEX_WAIT  and   FUTEX_WAKE   operations   correspond   to
              FUTEX_WAIT_BITSET  and  FUTEX_WAKE_BITSET  operations  where the
              bitsets are all ones.

   Priority-inheritance futexes
       Linux supports priority-inheritance (PI) futexes  in  order  to  handle
       priority-inversion  problems  that can be encountered with normal futex
       locks.  Priority inversion is the problem that occurs when a  high-pri‐
       ority  task is blocked waiting to acquire a lock held by a low-priority
       task, while tasks at an intermediate priority continuously preempt  the
       low-priority  task  from  the CPU.  Consequently, the low-priority task
       makes no progress toward releasing the lock, and the high-priority task
       remains blocked.

       Priority  inheritance  is  a  mechanism  for dealing with the priority-
       inversion problem.  With this  mechanism,  when  a  high-priority  task
       becomes  blocked  by  a  lock held by a low-priority task, the latter's
       priority is temporarily raised to that of the former, so that it is not
       preempted  by  any intermediate level tasks, and can thus make progress
       toward releasing the lock.  To be effective, priority inheritance  must
       be  transitive,  meaning  that if a high-priority task blocks on a lock
       held by a lower-priority task that is itself blocked by  lock  held  by
       another  intermediate-priority task (and so on, for chains of arbitrary
       length), then both of those task (or more generally, all of  the  tasks
       in  a  lock  chain)  have their priorities raised to be the same as the
       high-priority task.

       From a user-space perspective, what makes a futex PI-aware is a  policy
       agreement  between  user  space  and  the kernel about the value of the
       futex word (described in a moment), coupled with  the  use  of  the  PI
       futex   operations   described  below  (in  particular,  FUTEX_LOCK_PI,
       FUTEX_TRYLOCK_PI, and FUTEX_CMP_REQUEUE_PI).

       The PI futex operations described below differ  from  the  other  futex
       operations  in  that  they impose policy on the use of the value of the
       futex word:

       *  If the lock is not acquired, the futex word's value shall be 0.

       *  If the lock is acquired, the futex word's value shall be the  thread
          ID (TID; see gettid(2)) of the owning thread.

       *  If  the lock is owned and there are threads contending for the lock,
          then the FUTEX_WAITERS bit shall be set in the futex  word's  value;
          in other words, this value is:

              FUTEX_WAITERS | TID


       Note that a PI futex word never just has the value FUTEX_WAITERS, which
       is a permissible state for non-PI futexes.

       With this policy in place, a user-space application can acquire a  not-
       acquired  lock  or  release a lock that no other threads try to acquire
       using atomic instructions executed in user space (e.g., a  compare-and-
       swap  operation  such as cmpxchg on the x86 architecture).  Acquiring a
       lock simply consists of using compare-and-swap to  atomically  set  the
       futex  word's  value  to  the caller's TID if its previous value was 0.
       Releasing a lock requires  using  compare-and-swap  to  set  the  futex
       word's value to 0 if the previous value was the expected TID.

       If  a  futex  is  already acquired (i.e., has a nonzero value), waiters
       must employ the FUTEX_LOCK_PI operation to acquire the lock.  If  other
       threads  are waiting for the lock, then the FUTEX_WAITERS bit is set in
       the futex  value;  in  this  case,  the  lock  owner  must  employ  the
       FUTEX_UNLOCK_PI operation to release the lock.

       In  the  cases where callers are forced into the kernel (i.e., required
       to perform a futex() operation), they then deal  directly  with  a  so-
       called  RT-mutex,  a  kernel  locking  mechanism  which  implements the
       required  priority-inheritance  semantics.   After  the   RT-mutex   is
       acquired,  the  futex  value is updated accordingly, before the calling
       thread returns to user space.

       It is important to note that the kernel will update  the  futex  word's
       value  prior to returning to user space.  Unlike the other futex opera‐
       tions described above, the PI futex operations  are  designed  for  the
       implementation of very specific IPC mechanisms.

       PI futexes are operated on by specifying one of the following values in
       futex_op:

       FUTEX_LOCK_PI (since Linux 2.6.18)
              This operation is used after after an  attempt  to  acquire  the
              lock  via  an  atomic  user-space instruction failed because the
              futex word has a nonzero  value—specifically,  because  it  con‐
              tained the namespace-specific TID of the lock owner.

              The  operation checks the value of the futex word at the address
              uaddr.  If the value is 0, then the kernel tries  to  atomically
              set  the futex value to the caller's TID.  If that fails, or the
              futex word's value is nonzero, the kernel  atomically  sets  the
              FUTEX_WAITERS  bit, which signals the futex owner that it cannot
              unlock the futex in user space atomically by setting  the  futex
              value  to  0.   After  that, the kernel tries to find the thread
              which is associated with the owner TID, creates or reuses kernel
              state on behalf of the owner and attaches the waiter to it.  The
              enqueueing of the waiter is in descending priority order if more
              than  one waiter exists.  The owner inherits either the priority
              or the bandwidth of the waiter.  This  inheritance  follows  the
              lock  chain  in the case of nested locking and performs deadlock
              detection.

              The timeout argument provides a timeout for  the  lock  attempt.
              It  is  interpreted  as  an  absolute time, measured against the
              CLOCK_REALTIME clock.  If timeout is NULL,  the  operation  will
              block indefinitely.

              The uaddr2, val, and val3 arguments are ignored.

       FUTEX_TRYLOCK_PI (since Linux 2.6.18)
              This  operation  tries  to acquire the futex at uaddr.  It deals
              with the situation where the TID value at uaddr is  0,  but  the
              FUTEX_WAITERS  bit is set.  User space cannot handle this condi‐
              tion in a race-free manner

              The uaddr2, val, timeout, and val3 arguments are ignored.

       FUTEX_UNLOCK_PI (since Linux 2.6.18)
              This operation wakes the top priority waiter that is waiting  in
              FUTEX_LOCK_PI  on  the futex address provided by the uaddr argu‐
              ment.

              This is called when the user space  value  at  uaddr  cannot  be
              changed atomically from a TID (of the owner) to 0.

              The uaddr2, val, timeout, and val3 arguments are ignored.

       FUTEX_CMP_REQUEUE_PI (since Linux 2.6.31)
              This  operation  is a PI-aware variant of FUTEX_CMP_REQUEUE.  It
              requeues waiters that are blocked via  FUTEX_WAIT_REQUEUE_PI  on
              uaddr  from  a  non-PI source futex (uaddr) to a PI target futex
              (uaddr2).

              As with FUTEX_CMP_REQUEUE, this operation wakes up a maximum  of
              val  waiters  that  are waiting on the futex at uaddr.  However,
              for FUTEX_CMP_REQUEUE_PI, val is required to  be  1  (since  the
              main  point is to avoid a thundering herd).  The remaining wait‐
              ers are removed from the wait queue of the source futex at uaddr
              and added to the wait queue of the target futex at uaddr2.

              The  val2  and  val3  arguments  serve  the same purposes as for
              FUTEX_CMP_REQUEUE.

       FUTEX_WAIT_REQUEUE_PI (since Linux 2.6.31)
              Wait operation to wait on a non-PI futex  at  uaddr  and  poten‐
              tially  be  requeued onto a PI futex at uaddr2.  The wait opera‐
              tion on uaddr is the same as  FUTEX_WAIT.   The  waiter  can  be
              removed from the wait on uaddr via FUTEX_WAKE without requeueing
              on uaddr2.

              If timeout is not NULL, it specifies  a  timeout  for  the  wait
              operation;  this timeout is interpreted as outlined above in the
              description of the FUTEX_CLOCK_REALTIME option.  If  timeout  is
              NULL, the operation can block indefinitely.

              The val3 argument is ignored.

              The FUTEX_WAIT_REQUEUE_PI and FUTEX_CMP_REQUEUE_PI were added to
              support a fairly specific use case: support for priority-inheri‐
              tance-aware POSIX threads condition variables.  The idea is that
              these operations should always be paired,  in  order  to  ensure
              that  user  space  and  the kernel remain in sync.  Thus, in the
              FUTEX_WAIT_REQUEUE_PI operation, the user-space application pre-
              specifies  the  target  of  the  requeue that takes place in the
              FUTEX_CMP_REQUEUE_PI operation.

RETURN VALUE
       In the event of an error, all operations return -1  and  set  errno  to
       indicate  the  cause of the error.  The return value on success depends
       on the operation, as described in the following list:

       FUTEX_WAIT
              Returns 0 if the caller was woken up.  Note that a  wake-up  can
              also  be caused by common futex usage patterns in unrelated code
              that happened to have previously used the  futex  word's  memory
              location  (e.g., typical futex-based implementations of Pthreads
              mutexes can cause this under some conditions).  Therefore, call‐
              ers should always conservatively assume that a return value of 0
              can mean a spurious wake-up, and  use  the  futex  word's  value
              (i.e., the user space synchronization scheme)
                  to decide whether to continue to block or not.

       FUTEX_WAKE
              Returns the number of waiters that were woken up.

       FUTEX_FD
              Returns the new file descriptor associated with the futex.

       FUTEX_REQUEUE
              Returns the number of waiters that were woken up.

       FUTEX_CMP_REQUEUE
              Returns  the  total  number  of  waiters  that  were woken up or
              requeued to the futex for the futex word  at  uaddr2.   If  this
              value  is  greater  than  val,  then difference is the number of
              waiters requeued to the futex for the futex word at uaddr2.

       FUTEX_WAKE_OP
              Returns the total number of waiters that were woken up.  This is
              the  sum  of  the woken waiters on the two futexes for the futex
              words at uaddr and uaddr2.

       FUTEX_WAIT_BITSET
              Returns 0 if the caller was woken up.  See FUTEX_WAIT for how to
              interpret this correctly in practice.

       FUTEX_WAKE_BITSET
              Returns the number of waiters that were woken up.

       FUTEX_LOCK_PI
              Returns 0 if the futex was successfully locked.

       FUTEX_TRYLOCK_PI
              Returns 0 if the futex was successfully locked.

       FUTEX_UNLOCK_PI
              Returns 0 if the futex was successfully unlocked.

       FUTEX_CMP_REQUEUE_PI
              Returns  the  total  number  of  waiters  that  were woken up or
              requeued to the futex for the futex word  at  uaddr2.   If  this
              value  is  greater  than  val,  then difference is the number of
              waiters requeued to the futex for the futex word at uaddr2.

       FUTEX_WAIT_REQUEUE_PI
              Returns 0 if the caller was successfully requeued to  the  futex
              for the futex word at uaddr2.

ERRORS
       EACCES No read access to the memory of a futex word.

       EAGAIN (FUTEX_WAIT, FUTEX_WAIT_BITSET, FUTEX_WAIT_REQUEUE_PI) The value
              pointed to by uaddr was not equal to the expected value  val  at
              the time of the call.

              Note:  on Linux, the symbolic names EAGAIN and EWOULDBLOCK (both
              of which appear in different parts of  the  kernel  futex  code)
              have the same value.

       EAGAIN (FUTEX_CMP_REQUEUE,  FUTEX_CMP_REQUEUE_PI)  The value pointed to
              by uaddr is not equal to the expected value val3.  (This  proba‐
              bly indicates a race; use the safe FUTEX_WAKE now.)

       EAGAIN (FUTEX_LOCK_PI,   FUTEX_TRYLOCK_PI,   FUTEX_CMP_REQUEUE_PI)  The
              futex  owner  thread  ID  of  uaddr  (for  FUTEX_CMP_REQUEUE_PI:
              uaddr2)  is  about to exit, but has not yet handled the internal
              state cleanup.  Try again.

       EDEADLK
              (FUTEX_LOCK_PI,  FUTEX_TRYLOCK_PI,   FUTEX_CMP_REQUEUE_PI)   The
              futex word at uaddr is already locked by the caller.

       EDEADLK
              (FUTEX_CMP_REQUEUE_PI) While requeueing a waiter to the PI futex
              for the futex word at uaddr2, the kernel detected a deadlock.

       EFAULT A required pointer argument (i.e., uaddr,  uaddr2,  or  timeout)
              did not point to a valid user-space address.

       EINTR  A FUTEX_WAIT or FUTEX_WAIT_BITSET operation was interrupted by a
              signal (see signal(7)).  In kernels before  Linux  2.6.22,  this
              error  could  also  be  returned for on a spurious wakeup; since
              Linux 2.6.22, this no longer happens.

       EINVAL The operation in futex_op is one of those that employs  a  time‐
              out,  but  the supplied timeout argument was invalid (tv_sec was
              less than zero, or tv_nsec was not less than 1000,000,000).

       EINVAL The operation specified in futex_op employs one or both  of  the
              pointers  uaddr and uaddr2, but one of these does not point to a
              valid object—that is, the address is not four-byte-aligned.

       EINVAL (FUTEX_WAIT_BITSET, FUTEX_WAKE_BITSET) The  bitset  supplied  in
              val3 is zero.

       EINVAL (FUTEX_CMP_REQUEUE_PI) uaddr equals uaddr2 (i.e., an attempt was
              made to requeue to the same futex).

       EINVAL (FUTEX_FD) The signal number supplied in val is invalid.

       EINVAL (FUTEX_WAKE,  FUTEX_WAKE_OP,  FUTEX_WAKE_BITSET,  FUTEX_REQUEUE,
              FUTEX_CMP_REQUEUE)  The kernel detected an inconsistency between
              the user-space state at uaddr and the kernel state—that  is,  it
              detected a waiter which waits in FUTEX_LOCK_PI on uaddr.

       EINVAL (FUTEX_LOCK_PI,  FUTEX_TRYLOCK_PI,  FUTEX_UNLOCK_PI)  The kernel
              detected an inconsistency between the user-space state at  uaddr
              and the kernel state.  This indicates either state corruption or
              that the kernel found a waiter on uaddr  which  is  waiting  via
              FUTEX_WAIT or FUTEX_WAIT_BITSET.

       EINVAL (FUTEX_CMP_REQUEUE_PI)  The  kernel  detected  an  inconsistency
              between the user-space state at uaddr2  and  the  kernel  state;
              that is, the kernel detected a waiter which waits via FUTEX_WAIT
              on uaddr2.

       EINVAL (FUTEX_CMP_REQUEUE_PI)  The  kernel  detected  an  inconsistency
              between the user-space state at uaddr and the kernel state; that
              is, the kernel detected a waiter which waits via  FUTEX_WAIT  or
              FUTEX_WAIT_BITESET on uaddr.

       EINVAL (FUTEX_CMP_REQUEUE_PI)  The  kernel  detected  an  inconsistency
              between the user-space state at uaddr and the kernel state; that
              is,  the  kernel  detected  a  waiter  which  waits on uaddr via
              FUTEX_LOCK_PI (instead of FUTEX_WAIT_REQUEUE_PI).

       EINVAL (FUTEX_CMP_REQUEUE_PI) An attempt was made to requeue  a  waiter
              to   a   futex   other  than  that  specified  by  the  matching
              FUTEX_WAIT_REQUEUE_PI call for that waiter.

       EINVAL (FUTEX_CMP_REQUEUE_PI) The val argument is not 1.

       EINVAL Invalid argument.

       ENOMEM (FUTEX_LOCK_PI, FUTEX_TRYLOCK_PI, FUTEX_CMP_REQUEUE_PI) The ker‐
              nel could not allocate memory to hold state information.

       ENFILE (FUTEX_FD)  The  system  limit on the total number of open files
              has been reached.

       ENOSYS Invalid operation specified in futex_op.

       ENOSYS The FUTEX_CLOCK_REALTIME option was specified in  futex_op,  but
              the  accompanying  operation  was  neither FUTEX_WAIT_BITSET nor
              FUTEX_WAIT_REQUEUE_PI.

       ENOSYS (FUTEX_LOCK_PI,        FUTEX_TRYLOCK_PI,        FUTEX_UNLOCK_PI,
              FUTEX_CMP_REQUEUE_PI,  FUTEX_WAIT_REQUEUE_PI)  A  run-time check
              determined that the operation is not available.   The  PI  futex
              operations  are not implemented on all architectures and are not
              supported on some CPU variants.

       EPERM  (FUTEX_LOCK_PI,  FUTEX_TRYLOCK_PI,   FUTEX_CMP_REQUEUE_PI)   The
              caller  is  not  allowed  to attach itself to the futex at uaddr
              (for FUTEX_CMP_REQUEUE_PI: the futex at uaddr2).  (This  may  be
              caused by a state corruption in user space.)

       EPERM  (FUTEX_UNLOCK_PI)  The  caller does not own the lock represented
              by the futex word.

       ESRCH  (FUTEX_LOCK_PI,  FUTEX_TRYLOCK_PI,   FUTEX_CMP_REQUEUE_PI)   The
              thread ID in the futex word at uaddr does not exist.

       ESRCH  (FUTEX_CMP_REQUEUE_PI) The thread ID in the futex word at uaddr2
              does not exist.

       ETIMEDOUT
              The operation in futex_op  employed  the  timeout  specified  in
              timeout, and the timeout expired before the operation completed.

VERSIONS
       Futexes were first made available in a stable kernel release with Linux
       2.6.0.

       Initial futex support was merged in  Linux  2.5.7  but  with  different
       semantics  from  what was described above.  A four-argument system call
       with the semantics described in  this  page  was  introduced  in  Linux
       2.5.40.   In  Linux  2.5.70, one argument was added.  In Linux 2.6.7, a
       sixth argument was added—messy, especially on the s390 architecture.

CONFORMING TO
       This system call is Linux-specific.

NOTES
       Glibc does not provide a wrapper for this system call;  call  it  using
       syscall(2).

EXAMPLE
       The program below demonstrates use of futexes in a program where parent
       and child use a pair of futexes located inside a shared anonymous  map‐
       ping to synchronize access to a shared resource: the terminal.  The two
       processes each write nloops (a command-line argument that defaults to 5
       if  omitted) messages to the terminal and employ a synchronization pro‐
       tocol that ensures that they alternate in writing messages.  Upon  run‐
       ning this program we see output such as the following:

           $ ./futex_demo
           Parent (18534) 0
           Child  (18535) 0
           Parent (18534) 1
           Child  (18535) 1
           Parent (18534) 2
           Child  (18535) 2
           Parent (18534) 3
           Child  (18535) 3
           Parent (18534) 4
           Child  (18535) 4

   Program source

       /* futex_demo.c

          Usage: futex_demo [nloops]
                           (Default: 5)

          Demonstrate the use of futexes in a program where parent and child
          use a pair of futexes located inside a shared anonymous mapping to
          synchronize access to a shared resource: the terminal. The two
          processes each write 'num-loops' messages to the terminal and employ
          a synchronization protocol that ensures that they alternate in
          writing messages.
       */
       #define _GNU_SOURCE
       #include <stdio.h>
       #include <errno.h>
       #include <stdlib.h>
       #include <unistd.h>
       #include <sys/wait.h>
       #include <sys/mman.h>
       #include <sys/syscall.h>
       #include <linux/futex.h>
       #include <sys/time.h>

       #define errExit(msg)    do { perror(msg); exit(EXIT_FAILURE); \
                               } while (0)

       static int *futex1, *futex2, *iaddr;

       static int
       futex(int *uaddr, int futex_op, int val,
             const struct timespec *timeout, int *uaddr2, int val3)
       {
           return syscall(SYS_futex, uaddr, futex_op, val,
                          timeout, uaddr, val3);
       }

       /* Acquire the futex pointed to by 'futexp': wait for its value to
          become 1, and then set the value to 0. */

       static void
       fwait(int *futexp)
       {
           int s;

           /* __sync_bool_compare_and_swap(ptr, oldval, newval) is a gcc
              built-in function.  It atomically performs the equivalent of:

                  if (*ptr == oldval)
                      *ptr = newval;

              It returns true if the test yielded true and *ptr was updated.
              The alternative here would be to employ the equivalent atomic
              machine-language instructions.  For further information, see
              the GCC Manual. */

           while (1) {

               /* Is the futex available? */

               if (__sync_bool_compare_and_swap(futexp, 1, 0))
                   break;      /* Yes */

               /* Futex is not available; wait */

               s = futex(futexp, FUTEX_WAIT, 0, NULL, NULL, 0);
               if (s == -1 && errno != EAGAIN)
                   errExit("futex-FUTEX_WAIT");
           }
       }

       /* Release the futex pointed to by 'futexp': if the futex currently
          has the value 0, set its value to 1 and the wake any futex waiters,
          so that if the peer is blocked in fpost(), it can proceed. */

       static void
       fpost(int *futexp)
       {
           int s;

           /* __sync_bool_compare_and_swap() was described in comments above */

           if (__sync_bool_compare_and_swap(futexp, 0, 1)) {

               s = futex(futexp, FUTEX_WAKE, 1, NULL, NULL, 0);
               if (s  == -1)
                   errExit("futex-FUTEX_WAKE");
           }
       }

       int
       main(int argc, char *argv[])
       {
           pid_t childPid;
           int j, nloops;

           setbuf(stdout, NULL);

           nloops = (argc > 1) ? atoi(argv[1]) : 5;

           /* Create a shared anonymous mapping that will hold the futexes.
              Since the futexes are being shared between processes, we
              subsequently use the "shared" futex operations (i.e., not the
              ones suffixed "_PRIVATE") */

           iaddr = mmap(NULL, sizeof(int) * 2, PROT_READ | PROT_WRITE,
                       MAP_ANONYMOUS | MAP_SHARED, -1, 0);
           if (iaddr == MAP_FAILED)
               errExit("mmap");

           futex1 = &iaddr[0];
           futex2 = &iaddr[1];

           *futex1 = 0;        /* State: unavailable */
           *futex2 = 1;        /* State: available */

           /* Create a child process that inherits the shared anonymous
              mapping */

           childPid = fork();
           if (childPid == -1)
               errExit("fork");

           if (childPid == 0) {        /* Child */
               for (j = 0; j < nloops; j++) {
                   fwait(futex1);
                   printf("Child  (%ld) %d\n", (long) getpid(), j);
                   fpost(futex2);
               }

               exit(EXIT_SUCCESS);
           }

           /* Parent falls through to here */

           for (j = 0; j < nloops; j++) {
               fwait(futex2);
               printf("Parent (%ld) %d\n", (long) getpid(), j);
               fpost(futex1);
           }

           wait(NULL);

           exit(EXIT_SUCCESS);
       }

SEE ALSO
       get_robust_list(2), restart_syscall(2), futex(7)

       The following kernel source files:

       * Documentation/pi-futex.txt

       * Documentation/futex-requeue-pi.txt

       * Documentation/locking/rt-mutex.txt

       * Documentation/locking/rt-mutex-design.txt

       * Documentation/robust-futex-ABI.txt

       Franke, H., Russell, R., and Kirwood, M., 2002.  Fuss, Futexes and Fur‐
       wocks: Fast Userlevel Locking in Linux (from proceedings of the Ottawa
       Linux Symposium 2002),
       ⟨http://kernel.org/doc/ols/2002/ols2002-pages-479-495.pdf⟩

       Hart, D., 2009. A futex overview and update,
       ⟨http://lwn.net/Articles/360699/⟩

       Hart, D. and Guniguntala, D., 2009.  Requeue-PI: Making Glibc Condvars
       PI-Aware (from proceedings of the 2009 Real-Time Linux Workshop),
       ⟨http://lwn.net/images/conf/rtlws11/papers/proc/p10.pdf⟩

       Drepper, U., 2011. Futexes Are Tricky,
       ⟨http://www.akkadia.org/drepper/futex.pdf⟩

       Futex example library, futex-*.tar.bz2 at
       ⟨ftp://ftp.kernel.org/pub/linux/kernel/people/rusty/⟩



Linux                             2014-05-21                          FUTEX(2)

^ permalink raw reply	[flat|nested] 22+ messages in thread

* Re: Revised futex(2) man page for review
  2015-03-28 11:47 ` Peter Zijlstra
@ 2015-03-28 12:03   ` Peter Zijlstra
  2015-03-31 20:36     ` Davidlohr Bueso
  2015-07-27 11:10     ` Michael Kerrisk (man-pages)
  2015-03-31 14:45   ` Davidlohr Bueso
                     ` (3 subsequent siblings)
  4 siblings, 2 replies; 22+ messages in thread
From: Peter Zijlstra @ 2015-03-28 12:03 UTC (permalink / raw)
  To: Michael Kerrisk (man-pages)
  Cc: Thomas Gleixner, Darren Hart, Carlos O'Donell, Ingo Molnar,
	Jakub Jelinek, linux-man, lkml, Davidlohr Bueso, Arnd Bergmann,
	Steven Rostedt, Linux API, Torvald Riegel, Roland McGrath,
	Darren Hart, Anton Blanchard, Eric Dumazet, bill o gallmeister,
	Jan Kiszka, Daniel Wagner, Rich Felker, Andy Lutomirski,
	bert hubert, Rusty Russell, Heinrich Schuchardt

On Sat, Mar 28, 2015 at 12:47:25PM +0100, Peter Zijlstra wrote:
>        FUTEX_WAIT (since Linux 2.6.0)
>               This operation tests that the value at the futex word pointed to
>               by the address uaddr still contains the expected value val,  and
>               if  so,  then sleeps awaiting FUTEX_WAKE on the futex word.  The
>               load of the value of the futex word is an atomic  memory  access
>               (i.e.,  using  atomic  machine  instructions  of  the respective
>               architecture).  This load,  the  comparison  with  the  expected
>               value,  and  starting  to  sleep  are  performed  atomically and
>               totally ordered with respect to other futex  operations  on  the
>               same  futex  word.  If the thread starts to sleep, it is consid‐
>               ered a waiter on this futex word.  If the futex value  does  not
>               match  val,  then  the  call  fails  immediately  with the error
>               EAGAIN.
> 
>               The purpose of the comparison with the expected value is to pre‐
>               vent  lost  wake-ups: If another thread changed the value of the
>               futex word after the calling thread decided to  block  based  on
>               the  prior  value, and if the other thread executed a FUTEX_WAKE
>               operation (or similar wake-up) after the value change and before
>               this  FUTEX_WAIT  operation,  then  the  latter will observe the
>               value change and will not start to sleep.
> 
>               If the timeout argument is non-NULL, its contents specify a rel‐
>               ative   timeout   for   the  wait,  measured  according  to  the
>               CLOCK_MONOTONIC clock.  (This interval will be rounded up to the
>               system clock granularity, and kernel scheduling delays mean that
>               the blocking interval may overrun by a small amount.)  If  time‐
>               out is NULL, the call blocks indefinitely.

Would it not be better to only state that the wait will not return
before the timeout -- unless woken -- and not bother with clock
granularity and scheduling delays?

^ permalink raw reply	[flat|nested] 22+ messages in thread

* Re: Revised futex(2) man page for review
  2015-03-28  8:53 Revised futex(2) man page for review Michael Kerrisk (man-pages)
  2015-03-28  8:56 ` Michael Kerrisk (man-pages)
  2015-03-28 11:47 ` Peter Zijlstra
@ 2015-03-31  1:48 ` Rusty Russell
  2015-07-27 11:03   ` Michael Kerrisk (man-pages)
  2 siblings, 1 reply; 22+ messages in thread
From: Rusty Russell @ 2015-03-31  1:48 UTC (permalink / raw)
  To: Michael Kerrisk (man-pages), Thomas Gleixner, Darren Hart
  Cc: mtk.manpages, Carlos O'Donell, Darren Hart, Ingo Molnar,
	Jakub Jelinek, linux-man, lkml, Davidlohr Bueso, Arnd Bergmann,
	Steven Rostedt, Peter Zijlstra, Linux API, Torvald Riegel,
	Roland McGrath, Darren Hart, Anton Blanchard, Peter Zijlstra,
	Eric Dumazet, bill o gallmeister, Jan Kiszka, Daniel Wagner,
	Rich Felker, Andy Lutomirski, bert hubert, Heinrich Schuchardt

"Michael Kerrisk (man-pages)" <mtk.manpages@gmail.com> writes:
> When executing a futex operation that requests to block a thread,
> the kernel will only block if the futex word has the value that the
> calling thread supplied as expected value.
> The load from the futex word, the comparison with
> the expected value,
> and the actual blocking will happen atomically and totally
> ordered with respect to concurrently executing futex operations
> on the same futex word,
> such as operations that wake threads blocked on this futex word.
> Thus, the futex word is used to connect the synchronization in user spac

Missing 'e' in "space".

> .\" FIXME Please confirm that the following is correct:
> No guarantee is provided about which waiters are awoken
> (e.g., a waiter with a higher scheduling priority is not guaranteed
> to be awoken in preference to a waiter with a lower priority).

This is true.

I didn't read the rest, as that stuff was all written by others.
Documenting them is pretty heroic; good job!

Thanks,
Rusty.

^ permalink raw reply	[flat|nested] 22+ messages in thread

* Re: Revised futex(2) man page for review
  2015-03-28 11:47 ` Peter Zijlstra
  2015-03-28 12:03   ` Peter Zijlstra
@ 2015-03-31 14:45   ` Davidlohr Bueso
  2015-07-27 11:10     ` Michael Kerrisk (man-pages)
  2015-04-14 21:40   ` Thomas Gleixner
                     ` (2 subsequent siblings)
  4 siblings, 1 reply; 22+ messages in thread
From: Davidlohr Bueso @ 2015-03-31 14:45 UTC (permalink / raw)
  To: Peter Zijlstra
  Cc: Michael Kerrisk (man-pages),
	Thomas Gleixner, Darren Hart, Carlos O'Donell, Ingo Molnar,
	Jakub Jelinek, linux-man, lkml, Arnd Bergmann, Steven Rostedt,
	Linux API, Torvald Riegel, Roland McGrath, Darren Hart,
	Anton Blanchard, Eric Dumazet, bill o gallmeister, Jan Kiszka,
	Daniel Wagner, Rich Felker, Andy Lutomirski, bert hubert,
	Rusty Russell, Heinrich Schuchardt

On Sat, 2015-03-28 at 12:47 +0100, Peter Zijlstra wrote:

>        The condition is represented by the futex word, which is an address  in
>        memory  supplied to the futex() system call, and the value at this mem‐
>        ory location.  (While the virtual addresses for the same memory in sep‐
>        arate  processes  may  not be equal, the kernel maps them internally so
>        that the same memory mapped in different locations will correspond  for
>        futex() calls.)
> 
>        When  executing  a futex operation that requests to block a thread, the
>        kernel will only block if the futex word has the value that the calling

Given the use of "word", you should probably state right away that
futexes are only 32bit.

Thanks,
Davidlohr


^ permalink raw reply	[flat|nested] 22+ messages in thread

* Re: Revised futex(2) man page for review
  2015-03-28 12:03   ` Peter Zijlstra
@ 2015-03-31 20:36     ` Davidlohr Bueso
  2015-07-27 11:00       ` Michael Kerrisk (man-pages)
  2015-07-27 11:10     ` Michael Kerrisk (man-pages)
  1 sibling, 1 reply; 22+ messages in thread
From: Davidlohr Bueso @ 2015-03-31 20:36 UTC (permalink / raw)
  To: Peter Zijlstra
  Cc: Michael Kerrisk (man-pages),
	Thomas Gleixner, Darren Hart, Carlos O'Donell, Ingo Molnar,
	Jakub Jelinek, linux-man, lkml, Arnd Bergmann, Steven Rostedt,
	Linux API, Torvald Riegel, Roland McGrath, Darren Hart,
	Anton Blanchard, Eric Dumazet, bill o gallmeister, Jan Kiszka,
	Daniel Wagner, Rich Felker, Andy Lutomirski, bert hubert,
	Rusty Russell, Heinrich Schuchardt

On Sat, 2015-03-28 at 13:03 +0100, Peter Zijlstra wrote:
> >               If the timeout argument is non-NULL, its contents specify a rel‐
> >               ative   timeout   for   the  wait,  measured  according  to  the
> >               CLOCK_MONOTONIC clock.  (This interval will be rounded up to the
> >               system clock granularity, and kernel scheduling delays mean that
> >               the blocking interval may overrun by a small amount.)  If  time‐
> >               out is NULL, the call blocks indefinitely.
> 
> Would it not be better to only state that the wait will not return
> before the timeout -- unless woken -- and not bother with clock
> granularity and scheduling delays?

Yeah, similarly we also have this:

     FUTEX_PRIVATE_FLAG (since Linux 2.6.22)
              This option bit can be employed with all futex  operations.   It
              tells  the  kernel  that  the  futex  is process-private and not
              shared with another process (i.e., it is  only  being  used  for
              synchronization  between  threads  of  the  same process).  This
              allows the kernel to choose the fast  path  for  validating  the
              user-space address and avoids expensive VMA lookups, taking ref‐
              erence counts on file backing store, and so on.

This to me reads a bit too much into the kernel (fastpath, refcnt,
vmas). Why not just mention that it avoids overhead in the kernel or
something? I don't recall any manpage mentioning such details, but I
could be wrong. In any case its a nit, the whole doc is pretty good and
I hope you can merge it soon and then just increment ;)

Thanks,
Davidlohr



^ permalink raw reply	[flat|nested] 22+ messages in thread

* Re: Revised futex(2) man page for review
  2015-03-28 11:47 ` Peter Zijlstra
  2015-03-28 12:03   ` Peter Zijlstra
  2015-03-31 14:45   ` Davidlohr Bueso
@ 2015-04-14 21:40   ` Thomas Gleixner
  2015-04-15 10:28     ` Torvald Riegel
  2015-04-27 20:37   ` Pavel Machek
  2015-07-28  2:52   ` Davidlohr Bueso
  4 siblings, 1 reply; 22+ messages in thread
From: Thomas Gleixner @ 2015-04-14 21:40 UTC (permalink / raw)
  To: Peter Zijlstra
  Cc: Michael Kerrisk (man-pages),
	Darren Hart, Carlos O'Donell, Ingo Molnar, Jakub Jelinek,
	linux-man, lkml, Davidlohr Bueso, Arnd Bergmann, Steven Rostedt,
	Linux API, Torvald Riegel, Roland McGrath, Darren Hart,
	Anton Blanchard, Eric Dumazet, bill o gallmeister, Jan Kiszka,
	Daniel Wagner, Rich Felker, Andy Lutomirski, bert hubert,
	Rusty Russell, Heinrich Schuchardt

On Sat, 28 Mar 2015, Peter Zijlstra wrote:
> On Sat, Mar 28, 2015 at 09:53:21AM +0100, Michael Kerrisk (man-pages) wrote:
> > So, please take a look at the page below. At this point,
> > I would most especially appreciate help with the FIXMEs.
> 
> For people who cannot read that troff gibberish (me)..

Ditto :)
 
> NOTES
>        Glibc does not provide a wrapper for this system call;  call  it  using
>        syscall(2).

You might mention that pthread_mutex, pthread_condvar interfaces are
high level wrappers for the syscall and recommended to be used for
normal use cases. IIRC unnamed semaphores are implemented with futexes
as well.

Thanks,

	tglx

^ permalink raw reply	[flat|nested] 22+ messages in thread

* Re: Revised futex(2) man page for review
  2015-04-14 21:40   ` Thomas Gleixner
@ 2015-04-15 10:28     ` Torvald Riegel
  2015-07-27 11:10       ` Michael Kerrisk (man-pages)
  0 siblings, 1 reply; 22+ messages in thread
From: Torvald Riegel @ 2015-04-15 10:28 UTC (permalink / raw)
  To: Thomas Gleixner
  Cc: Peter Zijlstra, Michael Kerrisk (man-pages),
	Darren Hart, Carlos O'Donell, Ingo Molnar, Jakub Jelinek,
	linux-man, lkml, Davidlohr Bueso, Arnd Bergmann, Steven Rostedt,
	Linux API, Roland McGrath, Darren Hart, Anton Blanchard,
	Eric Dumazet, bill o gallmeister, Jan Kiszka, Daniel Wagner,
	Rich Felker, Andy Lutomirski, bert hubert, Rusty Russell,
	Heinrich Schuchardt

On Tue, 2015-04-14 at 23:40 +0200, Thomas Gleixner wrote:
> On Sat, 28 Mar 2015, Peter Zijlstra wrote:
> > On Sat, Mar 28, 2015 at 09:53:21AM +0100, Michael Kerrisk (man-pages) wrote:
> > > So, please take a look at the page below. At this point,
> > > I would most especially appreciate help with the FIXMEs.
> > 
> > For people who cannot read that troff gibberish (me)..
> 
> Ditto :)
>  
> > NOTES
> >        Glibc does not provide a wrapper for this system call;  call  it  using
> >        syscall(2).
> 
> You might mention that pthread_mutex, pthread_condvar interfaces are
> high level wrappers for the syscall and recommended to be used for
> normal use cases. IIRC unnamed semaphores are implemented with futexes
> as well.

If we add this, I'd rephrase it to something like that there are
high-level programming abstractions such as the pthread_condvar
interfaces or semaphores that are implemented using the syscall and that
are typically a better fit for normal use cases.  I'd consider only the
condvars as something like a wrapper, or targeting a similar use case.


^ permalink raw reply	[flat|nested] 22+ messages in thread

* Re: Revised futex(2) man page for review
  2015-03-28 11:47 ` Peter Zijlstra
                     ` (2 preceding siblings ...)
  2015-04-14 21:40   ` Thomas Gleixner
@ 2015-04-27 20:37   ` Pavel Machek
  2015-07-27 11:10     ` Michael Kerrisk (man-pages)
  2015-07-28  2:52   ` Davidlohr Bueso
  4 siblings, 1 reply; 22+ messages in thread
From: Pavel Machek @ 2015-04-27 20:37 UTC (permalink / raw)
  To: Peter Zijlstra
  Cc: Michael Kerrisk (man-pages),
	Thomas Gleixner, Darren Hart, Carlos O'Donell, Ingo Molnar,
	Jakub Jelinek, linux-man, lkml, Davidlohr Bueso, Arnd Bergmann,
	Steven Rostedt, Linux API, Torvald Riegel, Roland McGrath,
	Darren Hart, Anton Blanchard, Eric Dumazet, bill o gallmeister,
	Jan Kiszka, Daniel Wagner, Rich Felker, Andy Lutomirski,
	bert hubert, Rusty Russell, Heinrich Schuchardt

Hi!

>               The FUTEX_WAIT_OP operation is equivalent to execute the follow???
>               ing  code  atomically  and totally ordered with respect to other
>               futex operations on any of the two supplied futex words:

"to executing"?

>               The  operation  and  comparison  that  are  to  be performed are
>               encoded in the bits of  the  argument  val3.   Pictorially,  the
>               encoding is:
> 
>                       +---+---+-----------+-----------+
>                       |op |cmp|   oparg   |  cmparg   |
>                       +---+---+-----------+-----------+
>                         4   4       12          12    <== # of bits
> 

:-)

> RETURN VALUE
>        In the event of an error, all operations return -1  and  set  errno  to
>        indicate  the  cause of the error.  The return value on success depends
>        on the operation, as described in the following list:

Did you say (at the begining) that there is no glibc wrapper?

>        EINVAL The operation in futex_op is one of those that employs  a  time???
>               out,  but  the supplied timeout argument was invalid (tv_sec was
>               less than zero, or tv_nsec was not less than 1000,000,000).

1,000...?

> NOTES
>        Glibc does not provide a wrapper for this system call;  call  it  using
>        syscall(2).

-- 
(english) http://www.livejournal.com/~pavelmachek
(cesky, pictures) http://atrey.karlin.mff.cuni.cz/~pavel/picture/horses/blog.html

^ permalink raw reply	[flat|nested] 22+ messages in thread

* Re: Revised futex(2) man page for review
  2015-03-31 20:36     ` Davidlohr Bueso
@ 2015-07-27 11:00       ` Michael Kerrisk (man-pages)
  0 siblings, 0 replies; 22+ messages in thread
From: Michael Kerrisk (man-pages) @ 2015-07-27 11:00 UTC (permalink / raw)
  To: Davidlohr Bueso, Peter Zijlstra
  Cc: mtk.manpages, Thomas Gleixner, Darren Hart, Carlos O'Donell,
	Ingo Molnar, Jakub Jelinek, linux-man, lkml, Arnd Bergmann,
	Steven Rostedt, Linux API, Torvald Riegel, Roland McGrath,
	Darren Hart, Anton Blanchard, Eric Dumazet, bill o gallmeister,
	Jan Kiszka, Daniel Wagner, Rich Felker, Andy Lutomirski,
	bert hubert, Rusty Russell, Heinrich Schuchardt

Hi David,

On 03/31/2015 10:36 PM, Davidlohr Bueso wrote:
> On Sat, 2015-03-28 at 13:03 +0100, Peter Zijlstra wrote:
>>>               If the timeout argument is non-NULL, its contents specify a rel‐
>>>               ative   timeout   for   the  wait,  measured  according  to  the
>>>               CLOCK_MONOTONIC clock.  (This interval will be rounded up to the
>>>               system clock granularity, and kernel scheduling delays mean that
>>>               the blocking interval may overrun by a small amount.)  If  time‐
>>>               out is NULL, the call blocks indefinitely.
>>
>> Would it not be better to only state that the wait will not return
>> before the timeout -- unless woken -- and not bother with clock
>> granularity and scheduling delays?
> 
> Yeah, similarly we also have this:
> 
>      FUTEX_PRIVATE_FLAG (since Linux 2.6.22)
>               This option bit can be employed with all futex  operations.   It
>               tells  the  kernel  that  the  futex  is process-private and not
>               shared with another process (i.e., it is  only  being  used  for
>               synchronization  between  threads  of  the  same process).  This
>               allows the kernel to choose the fast  path  for  validating  the
>               user-space address and avoids expensive VMA lookups, taking ref‐
>               erence counts on file backing store, and so on.
> 
> This to me reads a bit too much into the kernel (fastpath, refcnt,
> vmas). Why not just mention that it avoids overhead in the kernel or
> something? I don't recall any manpage mentioning such details, but I
> could be wrong. 

Thanks. Agreed. I changed this to

    This allows the kernel to make some additional performance optimizations.

> In any case its a nit, the whole doc is pretty good and
> I hope you can merge it soon and then just increment ;)

I ran out of time and energy at a certain point. And also got a little
disheartened that I got more people complaining about groff markup
than actually looked looked at the FIXMEs in the page source :-). 
I'll try to reboot the process.

Cheers,

Michael


-- 
Michael Kerrisk
Linux man-pages maintainer; http://www.kernel.org/doc/man-pages/
Linux/UNIX System Programming Training: http://man7.org/training/

^ permalink raw reply	[flat|nested] 22+ messages in thread

* Re: Revised futex(2) man page for review
  2015-03-31  1:48 ` Rusty Russell
@ 2015-07-27 11:03   ` Michael Kerrisk (man-pages)
  0 siblings, 0 replies; 22+ messages in thread
From: Michael Kerrisk (man-pages) @ 2015-07-27 11:03 UTC (permalink / raw)
  To: Rusty Russell, Thomas Gleixner, Darren Hart
  Cc: mtk.manpages, Carlos O'Donell, Ingo Molnar, Jakub Jelinek,
	linux-man, lkml, Davidlohr Bueso, Arnd Bergmann, Steven Rostedt,
	Peter Zijlstra, Linux API, Torvald Riegel, Roland McGrath,
	Darren Hart, Anton Blanchard, Eric Dumazet, bill o gallmeister,
	Jan Kiszka, Daniel Wagner, Rich Felker, Andy Lutomirski,
	bert hubert, Heinrich Schuchardt

On 03/31/2015 03:48 AM, Rusty Russell wrote:
> "Michael Kerrisk (man-pages)" <mtk.manpages@gmail.com> writes:
>> When executing a futex operation that requests to block a thread,
>> the kernel will only block if the futex word has the value that the
>> calling thread supplied as expected value.
>> The load from the futex word, the comparison with
>> the expected value,
>> and the actual blocking will happen atomically and totally
>> ordered with respect to concurrently executing futex operations
>> on the same futex word,
>> such as operations that wake threads blocked on this futex word.
>> Thus, the futex word is used to connect the synchronization in user spac
> 
> Missing 'e' in "space".

Already fixed.

>> .\" FIXME Please confirm that the following is correct:
>> No guarantee is provided about which waiters are awoken
>> (e.g., a waiter with a higher scheduling priority is not guaranteed
>> to be awoken in preference to a waiter with a lower priority).
> 
> This is true.

Thanks! FIXME removed.

Cheers,

Michael



> I didn't read the rest, as that stuff was all written by others.
> Documenting them is pretty heroic; good job!
> 
> Thanks,
> Rusty.
> 


-- 
Michael Kerrisk
Linux man-pages maintainer; http://www.kernel.org/doc/man-pages/
Linux/UNIX System Programming Training: http://man7.org/training/

^ permalink raw reply	[flat|nested] 22+ messages in thread

* Re: Revised futex(2) man page for review
  2015-04-15 10:28     ` Torvald Riegel
@ 2015-07-27 11:10       ` Michael Kerrisk (man-pages)
  0 siblings, 0 replies; 22+ messages in thread
From: Michael Kerrisk (man-pages) @ 2015-07-27 11:10 UTC (permalink / raw)
  To: Torvald Riegel, Thomas Gleixner
  Cc: mtk.manpages, Peter Zijlstra, Darren Hart, Carlos O'Donell,
	Ingo Molnar, Jakub Jelinek, linux-man, lkml, Davidlohr Bueso,
	Arnd Bergmann, Steven Rostedt, Linux API, Roland McGrath,
	Darren Hart, Anton Blanchard, Eric Dumazet, bill o gallmeister,
	Jan Kiszka, Daniel Wagner, Rich Felker, Andy Lutomirski,
	bert hubert, Rusty Russell, Heinrich Schuchardt

On 04/15/2015 12:28 PM, Torvald Riegel wrote:
> On Tue, 2015-04-14 at 23:40 +0200, Thomas Gleixner wrote:
>> On Sat, 28 Mar 2015, Peter Zijlstra wrote:
>>> On Sat, Mar 28, 2015 at 09:53:21AM +0100, Michael Kerrisk (man-pages) wrote:
>>>> So, please take a look at the page below. At this point,
>>>> I would most especially appreciate help with the FIXMEs.
>>>
>>> For people who cannot read that troff gibberish (me)..
>>
>> Ditto :)
>>  
>>> NOTES
>>>        Glibc does not provide a wrapper for this system call;  call  it  using
>>>        syscall(2).
>>
>> You might mention that pthread_mutex, pthread_condvar interfaces are
>> high level wrappers for the syscall and recommended to be used for
>> normal use cases. IIRC unnamed semaphores are implemented with futexes
>> as well.
> 
> If we add this, I'd rephrase it to something like that there are
> high-level programming abstractions such as the pthread_condvar
> interfaces or semaphores that are implemented using the syscall and that
> are typically a better fit for normal use cases.  I'd consider only the
> condvars as something like a wrapper, or targeting a similar use case.

I added this under NOTES:

       Various higher-level programming abstractions are implemented via
       futexes, including POSIX threads mutexes and condition variables,
       as well as POSIX semaphores.

Cheers,

Michael


-- 
Michael Kerrisk
Linux man-pages maintainer; http://www.kernel.org/doc/man-pages/
Linux/UNIX System Programming Training: http://man7.org/training/

^ permalink raw reply	[flat|nested] 22+ messages in thread

* Re: Revised futex(2) man page for review
  2015-03-31 14:45   ` Davidlohr Bueso
@ 2015-07-27 11:10     ` Michael Kerrisk (man-pages)
  2015-07-28  3:16       ` Davidlohr Bueso
  0 siblings, 1 reply; 22+ messages in thread
From: Michael Kerrisk (man-pages) @ 2015-07-27 11:10 UTC (permalink / raw)
  To: Davidlohr Bueso, Peter Zijlstra
  Cc: mtk.manpages, Thomas Gleixner, Darren Hart, Carlos O'Donell,
	Ingo Molnar, Jakub Jelinek, linux-man, lkml, Arnd Bergmann,
	Steven Rostedt, Linux API, Torvald Riegel, Roland McGrath,
	Darren Hart, Anton Blanchard, Eric Dumazet, bill o gallmeister,
	Jan Kiszka, Daniel Wagner, Rich Felker, Andy Lutomirski,
	bert hubert, Rusty Russell, Heinrich Schuchardt

Hi David,

On 03/31/2015 04:45 PM, Davidlohr Bueso wrote:
> On Sat, 2015-03-28 at 12:47 +0100, Peter Zijlstra wrote:
> 
>>        The condition is represented by the futex word, which is an address  in
>>        memory  supplied to the futex() system call, and the value at this mem‐
>>        ory location.  (While the virtual addresses for the same memory in sep‐
>>        arate  processes  may  not be equal, the kernel maps them internally so
>>        that the same memory mapped in different locations will correspond  for
>>        futex() calls.)
>>
>>        When  executing  a futex operation that requests to block a thread, the
>>        kernel will only block if the futex word has the value that the calling
> 
> Given the use of "word", you should probably state right away that
> futexes are only 32bit.

So, I made the opening sentence here:

       The  condition  is  represented  by  the  futex word, which is an
       address in memory supplied to the futex() system  call,  and  the
       32-bit  value  at  this  memory  location. 

Okay?

Cheers,

Michael

-- 
Michael Kerrisk
Linux man-pages maintainer; http://www.kernel.org/doc/man-pages/
Linux/UNIX System Programming Training: http://man7.org/training/

^ permalink raw reply	[flat|nested] 22+ messages in thread

* Re: Revised futex(2) man page for review
  2015-04-27 20:37   ` Pavel Machek
@ 2015-07-27 11:10     ` Michael Kerrisk (man-pages)
  0 siblings, 0 replies; 22+ messages in thread
From: Michael Kerrisk (man-pages) @ 2015-07-27 11:10 UTC (permalink / raw)
  To: Pavel Machek, Peter Zijlstra
  Cc: mtk.manpages, Thomas Gleixner, Darren Hart, Carlos O'Donell,
	Ingo Molnar, Jakub Jelinek, linux-man, lkml, Davidlohr Bueso,
	Arnd Bergmann, Steven Rostedt, Linux API, Torvald Riegel,
	Roland McGrath, Darren Hart, Anton Blanchard, Eric Dumazet,
	bill o gallmeister, Jan Kiszka, Daniel Wagner, Rich Felker,
	Andy Lutomirski, bert hubert, Rusty Russell, Heinrich Schuchardt

Hello Pavel,

On 04/27/2015 10:37 PM, Pavel Machek wrote:
> Hi!
> 
>>               The FUTEX_WAIT_OP operation is equivalent to execute the follow???
>>               ing  code  atomically  and totally ordered with respect to other
>>               futex operations on any of the two supplied futex words:
> 
> "to executing"?

Yep. Fixed.

>>               The  operation  and  comparison  that  are  to  be performed are
>>               encoded in the bits of  the  argument  val3.   Pictorially,  the
>>               encoding is:
>>
>>                       +---+---+-----------+-----------+
>>                       |op |cmp|   oparg   |  cmparg   |
>>                       +---+---+-----------+-----------+
>>                         4   4       12          12    <== # of bits
>>
> 
> :-)
> 
>> RETURN VALUE
>>        In the event of an error, all operations return -1  and  set  errno  to
>>        indicate  the  cause of the error.  The return value on success depends
>>        on the operation, as described in the following list:
> 
> Did you say (at the begining) that there is no glibc wrapper?

Yes, this could be clearer. I changed it to

RETURN VALUE
       In the event of an error (and assuming that futex()  was  invoked
       via  syscall(2)), all operations return -1 and set errno to indi‐
       cate the cause of the error.

>>        EINVAL The operation in futex_op is one of those that employs  a  time???
>>               out,  but  the supplied timeout argument was invalid (tv_sec was
>>               less than zero, or tv_nsec was not less than 1000,000,000).
> 
> 1,000...?

Fixed.

Thanks for the comments!

Cheers,

Michael


-- 
Michael Kerrisk
Linux man-pages maintainer; http://www.kernel.org/doc/man-pages/
Linux/UNIX System Programming Training: http://man7.org/training/

^ permalink raw reply	[flat|nested] 22+ messages in thread

* Re: Revised futex(2) man page for review
  2015-03-28 12:03   ` Peter Zijlstra
  2015-03-31 20:36     ` Davidlohr Bueso
@ 2015-07-27 11:10     ` Michael Kerrisk (man-pages)
  1 sibling, 0 replies; 22+ messages in thread
From: Michael Kerrisk (man-pages) @ 2015-07-27 11:10 UTC (permalink / raw)
  To: Peter Zijlstra
  Cc: mtk.manpages, Thomas Gleixner, Darren Hart, Carlos O'Donell,
	Ingo Molnar, Jakub Jelinek, linux-man, lkml, Davidlohr Bueso,
	Arnd Bergmann, Steven Rostedt, Linux API, Torvald Riegel,
	Roland McGrath, Darren Hart, Anton Blanchard, Eric Dumazet,
	bill o gallmeister, Jan Kiszka, Daniel Wagner, Rich Felker,
	Andy Lutomirski, bert hubert, Rusty Russell, Heinrich Schuchardt

Hi Peter,

On 03/28/2015 01:03 PM, Peter Zijlstra wrote:
> On Sat, Mar 28, 2015 at 12:47:25PM +0100, Peter Zijlstra wrote:
>>        FUTEX_WAIT (since Linux 2.6.0)
>>               This operation tests that the value at the futex word pointed to
>>               by the address uaddr still contains the expected value val,  and
>>               if  so,  then sleeps awaiting FUTEX_WAKE on the futex word.  The
>>               load of the value of the futex word is an atomic  memory  access
>>               (i.e.,  using  atomic  machine  instructions  of  the respective
>>               architecture).  This load,  the  comparison  with  the  expected
>>               value,  and  starting  to  sleep  are  performed  atomically and
>>               totally ordered with respect to other futex  operations  on  the
>>               same  futex  word.  If the thread starts to sleep, it is consid‐
>>               ered a waiter on this futex word.  If the futex value  does  not
>>               match  val,  then  the  call  fails  immediately  with the error
>>               EAGAIN.
>>
>>               The purpose of the comparison with the expected value is to pre‐
>>               vent  lost  wake-ups: If another thread changed the value of the
>>               futex word after the calling thread decided to  block  based  on
>>               the  prior  value, and if the other thread executed a FUTEX_WAKE
>>               operation (or similar wake-up) after the value change and before
>>               this  FUTEX_WAIT  operation,  then  the  latter will observe the
>>               value change and will not start to sleep.
>>
>>               If the timeout argument is non-NULL, its contents specify a rel‐
>>               ative   timeout   for   the  wait,  measured  according  to  the
>>               CLOCK_MONOTONIC clock.  (This interval will be rounded up to the
>>               system clock granularity, and kernel scheduling delays mean that
>>               the blocking interval may overrun by a small amount.)  If  time‐
>>               out is NULL, the call blocks indefinitely.
> 
> Would it not be better to only state that the wait will not return
> before the timeout -- unless woken -- and not bother with clock
> granularity and scheduling delays?

Many of the pages that talk about system calls that have timeouts
carry similar language, since people often have confusions about what time
timeout (e.g., that it's an upper limit, not a minimum; or that it's precise
to some very small granularity). Why do you think the language here is a
problem?

Cheers,

Michael



-- 
Michael Kerrisk
Linux man-pages maintainer; http://www.kernel.org/doc/man-pages/
Linux/UNIX System Programming Training: http://man7.org/training/

^ permalink raw reply	[flat|nested] 22+ messages in thread

* Re: Revised futex(2) man page for review
  2015-03-28 11:47 ` Peter Zijlstra
                     ` (3 preceding siblings ...)
  2015-04-27 20:37   ` Pavel Machek
@ 2015-07-28  2:52   ` Davidlohr Bueso
  2015-07-28  6:39     ` Michael Kerrisk (man-pages)
  4 siblings, 1 reply; 22+ messages in thread
From: Davidlohr Bueso @ 2015-07-28  2:52 UTC (permalink / raw)
  To: Peter Zijlstra
  Cc: Michael Kerrisk (man-pages),
	Thomas Gleixner, Darren Hart, Carlos O'Donell, Ingo Molnar,
	Jakub Jelinek, linux-man, lkml, Arnd Bergmann, Steven Rostedt,
	Linux API, Torvald Riegel, Roland McGrath, Darren Hart,
	Anton Blanchard, Eric Dumazet, bill o gallmeister, Jan Kiszka,
	Daniel Wagner, Rich Felker, Andy Lutomirski, bert hubert,
	Rusty Russell, Heinrich Schuchardt

On Sat, 2015-03-28 at 12:47 +0100, Peter Zijlstra wrote:
> SEE ALSO
>        get_robust_list(2), restart_syscall(2), futex(7)

For pi futexes, I also suggest pthread_mutexattr_getprotocol(3), which
is a common entry point.


^ permalink raw reply	[flat|nested] 22+ messages in thread

* Re: Revised futex(2) man page for review
  2015-07-27 11:10     ` Michael Kerrisk (man-pages)
@ 2015-07-28  3:16       ` Davidlohr Bueso
  2015-07-28  7:44         ` Michael Kerrisk (man-pages)
  0 siblings, 1 reply; 22+ messages in thread
From: Davidlohr Bueso @ 2015-07-28  3:16 UTC (permalink / raw)
  To: Michael Kerrisk (man-pages)
  Cc: Peter Zijlstra, Thomas Gleixner, Darren Hart,
	Carlos O'Donell, Ingo Molnar, Jakub Jelinek, linux-man, lkml,
	Arnd Bergmann, Steven Rostedt, Linux API, Torvald Riegel,
	Roland McGrath, Darren Hart, Anton Blanchard, Eric Dumazet,
	bill o gallmeister, Jan Kiszka, Daniel Wagner, Rich Felker,
	Andy Lutomirski, bert hubert, Rusty Russell, Heinrich Schuchardt

On Mon, 2015-07-27 at 13:10 +0200, Michael Kerrisk (man-pages) wrote:
> Hi David,
> 
> On 03/31/2015 04:45 PM, Davidlohr Bueso wrote:
> > On Sat, 2015-03-28 at 12:47 +0100, Peter Zijlstra wrote:
> > 
> >>        The condition is represented by the futex word, which is an address  in
> >>        memory  supplied to the futex() system call, and the value at this mem‐
> >>        ory location.  (While the virtual addresses for the same memory in sep‐
> >>        arate  processes  may  not be equal, the kernel maps them internally so
> >>        that the same memory mapped in different locations will correspond  for
> >>        futex() calls.)
> >>
> >>        When  executing  a futex operation that requests to block a thread, the
> >>        kernel will only block if the futex word has the value that the calling
> > 
> > Given the use of "word", you should probably state right away that
> > futexes are only 32bit.
> 
> So, I made the opening sentence here:
> 
>        The  condition  is  represented  by  the  futex word, which is an
>        address in memory supplied to the futex() system  call,  and  the
>        32-bit  value  at  this  memory  location. 
> 
> Okay?

I think we can still improve :)

I've re-read the whole first paragraphs, and have a few comments that
touch upon this specific wording. Lets see. You have:

>        The  futex()  system call provides a method for waiting until a certain
>        condition becomes true.  It is typically used as a  blocking  construct
>        in the context of shared-memory synchronization: The program implements
>        the majority of the synchronization in user  space,  and  uses  one  of
>        operations  of  the  system call when it is likely that it has to block
>        for a longer time until the condition becomes true.  The  program  uses
>        another  operation of the system call to wake anyone waiting for a par‐
>        ticular condition.

I've rephrased the next paragraph. How about adding this to follow?

       A futex is in essence a 32-bit user-space address. All futex operations and
       conditions are governed by this variable, from now on referred to as 'futex
       word'. As such, a futex is identified by the address in shared memory, which
       may or may not be shared between different processes. For virtual memory, the
       kernel will internally handle and resolve the later. This futex word, along
       with the value at its the memory location, are supplied to the futex() system
       call.

Feel free to reword however you think is better.

Thanks,
Davidlohr


^ permalink raw reply	[flat|nested] 22+ messages in thread

* Re: Revised futex(2) man page for review
  2015-07-28  2:52   ` Davidlohr Bueso
@ 2015-07-28  6:39     ` Michael Kerrisk (man-pages)
  0 siblings, 0 replies; 22+ messages in thread
From: Michael Kerrisk (man-pages) @ 2015-07-28  6:39 UTC (permalink / raw)
  To: Davidlohr Bueso, Peter Zijlstra
  Cc: mtk.manpages, Thomas Gleixner, Darren Hart, Carlos O'Donell,
	Ingo Molnar, Jakub Jelinek, linux-man, lkml, Arnd Bergmann,
	Steven Rostedt, Linux API, Torvald Riegel, Roland McGrath,
	Darren Hart, Anton Blanchard, Eric Dumazet, bill o gallmeister,
	Jan Kiszka, Daniel Wagner, Rich Felker, Andy Lutomirski,
	bert hubert, Rusty Russell, Heinrich Schuchardt

On 07/28/2015 04:52 AM, Davidlohr Bueso wrote:
> On Sat, 2015-03-28 at 12:47 +0100, Peter Zijlstra wrote:
>> SEE ALSO
>>        get_robust_list(2), restart_syscall(2), futex(7)
> 
> For pi futexes, I also suggest pthread_mutexattr_getprotocol(3), which
> is a common entry point.

Thanks. Added.

Cheers,

Michael


-- 
Michael Kerrisk
Linux man-pages maintainer; http://www.kernel.org/doc/man-pages/
Linux/UNIX System Programming Training: http://man7.org/training/

^ permalink raw reply	[flat|nested] 22+ messages in thread

* Re: Revised futex(2) man page for review
  2015-07-28  3:16       ` Davidlohr Bueso
@ 2015-07-28  7:44         ` Michael Kerrisk (man-pages)
  2015-07-28 17:52           ` Davidlohr Bueso
  0 siblings, 1 reply; 22+ messages in thread
From: Michael Kerrisk (man-pages) @ 2015-07-28  7:44 UTC (permalink / raw)
  To: Davidlohr Bueso
  Cc: mtk.manpages, Peter Zijlstra, Thomas Gleixner, Darren Hart,
	Carlos O'Donell, Ingo Molnar, Jakub Jelinek, linux-man, lkml,
	Arnd Bergmann, Steven Rostedt, Linux API, Torvald Riegel,
	Roland McGrath, Darren Hart, Anton Blanchard, Eric Dumazet,
	bill o gallmeister, Jan Kiszka, Daniel Wagner, Rich Felker,
	Andy Lutomirski, bert hubert, Rusty Russell, Heinrich Schuchardt

Hi David,

On 07/28/2015 05:16 AM, Davidlohr Bueso wrote:
> On Mon, 2015-07-27 at 13:10 +0200, Michael Kerrisk (man-pages) wrote:
>> Hi David,
>>
>> On 03/31/2015 04:45 PM, Davidlohr Bueso wrote:
>>> On Sat, 2015-03-28 at 12:47 +0100, Peter Zijlstra wrote:
>>>
>>>>        The condition is represented by the futex word, which is an address  in
>>>>        memory  supplied to the futex() system call, and the value at this mem‐
>>>>        ory location.  (While the virtual addresses for the same memory in sep‐
>>>>        arate  processes  may  not be equal, the kernel maps them internally so
>>>>        that the same memory mapped in different locations will correspond  for
>>>>        futex() calls.)
>>>>
>>>>        When  executing  a futex operation that requests to block a thread, the
>>>>        kernel will only block if the futex word has the value that the calling
>>>
>>> Given the use of "word", you should probably state right away that
>>> futexes are only 32bit.
>>
>> So, I made the opening sentence here:
>>
>>        The  condition  is  represented  by  the  futex word, which is an
>>        address in memory supplied to the futex() system  call,  and  the
>>        32-bit  value  at  this  memory  location. 
>>
>> Okay?
> 
> I think we can still improve :)
> 
> I've re-read the whole first paragraphs, and have a few comments that
> touch upon this specific wording. Lets see. You have:
> 
>>        The  futex()  system call provides a method for waiting until a certain
>>        condition becomes true.  It is typically used as a  blocking  construct
>>        in the context of shared-memory synchronization: The program implements
>>        the majority of the synchronization in user  space,  and  uses  one  of
>>        operations  of  the  system call when it is likely that it has to block
>>        for a longer time until the condition becomes true.  The  program  uses
>>        another  operation of the system call to wake anyone waiting for a par‐
>>        ticular condition.
> 
> I've rephrased the next paragraph. How about adding this to follow?
> 
>        A futex is in essence a 32-bit user-space address. All futex operations and
>        conditions are governed by this variable, from now on referred to as 'futex
>        word'. As such, a futex is identified by the address in shared memory, which
>        may or may not be shared between different processes. For virtual memory, the
>        kernel will internally handle and resolve the later. This futex word, along
>        with the value at its the memory location, are supplied to the futex() system
>        call.
> 
> Feel free to reword however you think is better.


I agree with you that that second paragraph is a bit broken. But, like Heinrich,
I'm confused by this term "32-bit ... address".

I've rewritten the paragraph as:

       A futex is a 32-bit value—referred to below as a futex word—whose
       address is supplied to the futex()  system  call.   (Futexes  are
       32-bits in size on all platforms, including 64-bit systems.)  All
       futex operations are governed by this value.  In order to share a
       futex  between  processes,  the  futex  is  placed in a region of
       shared memory, created using (for example) mmap(2)  or  shmat(2).
       (Thus the futex word may have different virtual addresses in dif‐
       ferent processes, but these addresses all refer to the same loca‐
       tion in physical memory.)

Maybe you still have some further improvements for the paragraph?

Cheers,

Michael

-- 
Michael Kerrisk
Linux man-pages maintainer; http://www.kernel.org/doc/man-pages/
Linux/UNIX System Programming Training: http://man7.org/training/

^ permalink raw reply	[flat|nested] 22+ messages in thread

* Re: Revised futex(2) man page for review
  2015-07-28  7:44         ` Michael Kerrisk (man-pages)
@ 2015-07-28 17:52           ` Davidlohr Bueso
  2015-07-28 18:09             ` Michael Kerrisk (man-pages)
  0 siblings, 1 reply; 22+ messages in thread
From: Davidlohr Bueso @ 2015-07-28 17:52 UTC (permalink / raw)
  To: Michael Kerrisk (man-pages)
  Cc: Peter Zijlstra, Thomas Gleixner, Darren Hart,
	Carlos O'Donell, Ingo Molnar, Jakub Jelinek, linux-man, lkml,
	Arnd Bergmann, Steven Rostedt, Linux API, Torvald Riegel,
	Roland McGrath, Darren Hart, Anton Blanchard, Eric Dumazet,
	bill o gallmeister, Jan Kiszka, Daniel Wagner, Rich Felker,
	Andy Lutomirski, bert hubert, Rusty Russell, Heinrich Schuchardt

On Tue, 2015-07-28 at 09:44 +0200, Michael Kerrisk (man-pages) wrote:
> Maybe you still have some further improvements for the paragraph?

Nah, this is fine enough. Looks good.

Thanks,
Davidlohr


^ permalink raw reply	[flat|nested] 22+ messages in thread

* Re: Revised futex(2) man page for review
  2015-07-28 17:52           ` Davidlohr Bueso
@ 2015-07-28 18:09             ` Michael Kerrisk (man-pages)
  0 siblings, 0 replies; 22+ messages in thread
From: Michael Kerrisk (man-pages) @ 2015-07-28 18:09 UTC (permalink / raw)
  To: Davidlohr Bueso
  Cc: mtk.manpages, Peter Zijlstra, Thomas Gleixner, Darren Hart,
	Carlos O'Donell, Ingo Molnar, Jakub Jelinek, linux-man, lkml,
	Arnd Bergmann, Steven Rostedt, Linux API, Torvald Riegel,
	Roland McGrath, Darren Hart, Anton Blanchard, Eric Dumazet,
	bill o gallmeister, Jan Kiszka, Daniel Wagner, Rich Felker,
	Andy Lutomirski, bert hubert, Rusty Russell, Heinrich Schuchardt

On 07/28/2015 07:52 PM, Davidlohr Bueso wrote:
> On Tue, 2015-07-28 at 09:44 +0200, Michael Kerrisk (man-pages) wrote:
>> Maybe you still have some further improvements for the paragraph?
> 
> Nah, this is fine enough. Looks good.

Okay. Thanks. I added a Reviewed-by: for you.

Cheers,

Michael


-- 
Michael Kerrisk
Linux man-pages maintainer; http://www.kernel.org/doc/man-pages/
Linux/UNIX System Programming Training: http://man7.org/training/

^ permalink raw reply	[flat|nested] 22+ messages in thread

end of thread, other threads:[~2015-07-28 18:09 UTC | newest]

Thread overview: 22+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2015-03-28  8:53 Revised futex(2) man page for review Michael Kerrisk (man-pages)
2015-03-28  8:56 ` Michael Kerrisk (man-pages)
2015-03-28 11:47 ` Peter Zijlstra
2015-03-28 12:03   ` Peter Zijlstra
2015-03-31 20:36     ` Davidlohr Bueso
2015-07-27 11:00       ` Michael Kerrisk (man-pages)
2015-07-27 11:10     ` Michael Kerrisk (man-pages)
2015-03-31 14:45   ` Davidlohr Bueso
2015-07-27 11:10     ` Michael Kerrisk (man-pages)
2015-07-28  3:16       ` Davidlohr Bueso
2015-07-28  7:44         ` Michael Kerrisk (man-pages)
2015-07-28 17:52           ` Davidlohr Bueso
2015-07-28 18:09             ` Michael Kerrisk (man-pages)
2015-04-14 21:40   ` Thomas Gleixner
2015-04-15 10:28     ` Torvald Riegel
2015-07-27 11:10       ` Michael Kerrisk (man-pages)
2015-04-27 20:37   ` Pavel Machek
2015-07-27 11:10     ` Michael Kerrisk (man-pages)
2015-07-28  2:52   ` Davidlohr Bueso
2015-07-28  6:39     ` Michael Kerrisk (man-pages)
2015-03-31  1:48 ` Rusty Russell
2015-07-27 11:03   ` Michael Kerrisk (man-pages)

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).