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

tytso
2010-06-09T12:17:20Z

On Tue, Jun 08, 2010 at 11:24:38PM -0700, Salman wrote:

> A program that repeatedly forks and waits is susceptible to having
> the same pid repeated, especially when it competes with another
> instance of the same program. This is really bad for bash
> implementation. Furthermore, many shell scripts assume that pid
> numbers will not be used for some length of time.
>
> Thanks to Ted Tso for the key ideas of this implementation.
>
> Signed-off-by: Salman Qazi <sqazi@google.com>

Here's a slightly more succint way of expressing it. Others will have
decide if it's easier to understand. (It is for me, but I wrote it. :-P)

- Ted

kernel/pid.c | 9 +++++++--
1 files changed, 7 insertions(+), 2 deletions(-)
diff --git a/kernel/pid.c b/kernel/pid.c
index e9fd8c1..c51f413 100644
--- a/kernel/pid.c
+++ b/kernel/pid.c
@@ -154,8 +154,13 @@ static int alloc_pidmap(struct pid_namespace *pid_ns)
do {
if (!test_and_set_bit(offset, map->page)) {
atomic_dec(&map->nr_free);
- pid_ns->last_pid = pid;
- return pid;
+ while (1) {
+ i = cmpxchg(&pid_ns->last_pid,
+ last, pid);
+ if (i == last || i >= pid)
+ return pid;
+ last = i;
+ }
}
offset = find_next_offset(map, offset);
pid = mk_pid(pid_ns, map, offset);