[libc] Implement pthread_getcpuclockid (#243852)
On Linux, the ID of a thread's CPU clock is derived from its TID, using
an encoding defined by the kernel. clock_getcpuclockid already did the
same thing for process clocks, so I'm moving the encoding into a header
which can be shared by both functions.
pthread_getcpuclockid doesn't check whether the thread is still running,
as POSIX.1-2024 says that the pthread_t of a terminated thread remains
valid until the thread is joined or detached. This means that the
returned clock ID can be invalid, or (worse) refer to a different
thread, as the kernel can reuse the TID once the thread exits. However,
the same thing can happen to a clock ID obtained while the thread was
still running, so I don't think it makes sense to try to detect this.
POSIX doesn't explicitly say what clock_gettime should return for
threads in this dead-but-unjoined state. A reasonable interpretation
would be to return the CPU time the thread used while it was alive.
That's something we *could* implement -- by saving the CPU time just
before the thread exits, and then reading it from clock_gettime. For
that, we would need to use our own encoding of clockid_t (something
derived from pthread_t), independent of what the kernel uses for the
underlying syscall. However, that would be a very novel approach (I'm
not aware of any implementation doing that), and would slow down the
clock_gettime fast path, which is why I'm not attempting it.
A related corner case is fork(). The TID field in the thread attributes
doubles as the TID cache, and fork() (as well as some clone()
invocations) sets it to zero for the duration of the syscall. If another
thread calls pthread_getcpuclockid on the forking thread at that time,
it will get a clock ID encoding a zero TID, which the kernel interprets
as "the calling thread". The same problem already exists for
pthread_getschedparam and pthread_setschedparam (the sched_* syscalls
also treat zero as the calling thread), so I'm not trying to fix it
here.
With pthread_getcpuclockid in place, we support the Thread CPU-Time
Clocks option, so I'm also changing _POSIX_THREAD_CPUTIME (and the value
returned by sysconf(_SC_THREAD_CPUTIME)) to say so.
Assisted-by: Claude