Re: [PATCH] Fix a race in pid generation that causes pids to be reused immediately.

tytso
2010-06-09T17:34:33Z

On Wed, Jun 09, 2010 at 10:25:50AM -0700, Linus Torvalds wrote:
>
>
> On Wed, 9 Jun 2010, Linus Torvalds wrote:
> >
> > Otherwise you have three threads, two of which pick the same pid (because
> > the test-and-set isn't atomic), and a third of which picks a new one.
>
> In fact, I don't think you need three threads at all. It's perfectly ok to
> just have two threads, and they'd both end up picking the same 'pid'
> without the atomicity guarantees of that 'test_and_set()' bitmap access.
>
> And they'd both be perfectly fine setting last_pid to that (shared) pid if
> I read that cmpxchg loop right. No?

Well, I was thinking about something like this:

while (1) {
last = pid_ns->last_pid;
pid = last + 1;
if (pid >= pid_max)
pid = RESERVED_PIDS;
if (cmpxchg(&pid_ns->last_pid, last, pid) == last)
return pid;
}

Which I don't think is racy, unless I'm missing something. Both might
end up picking the same pid, but only one will successfully set
last_pid, and the other will just loop and try again.

There appears to be some interesting uses of the bitmap by
find_ge_pid() and next_pidmap() that I haven't completely grokked yet,
especially as to why they're needed, though. Assuming they are
needed, we might end up needing the bitmap after all, though.

- Ted