Fix a race condition in FASYNC handling

Changeset a238b790d5f99c7832f9b73ac8847025815b85f7 (Call fasync()
functions without the BKL) introduced a race which could leave
file->f_flags in a state inconsistent with what the underlying
driver/filesystem believes. Revert that change, and also fix the same
races in ioctl_fioasync() and ioctl_fionbio().

This is a minimal, short-term fix; the real fix will not involve the
BKL.

Reported-by: Oleg Nesterov <oleg@redhat.com>
Cc: Andi Kleen <ak@linux.intel.com>
Cc: Al Viro <viro@zeniv.linux.org.uk>
Cc: stable@kernel.org
Signed-off-by: Jonathan Corbet <corbet@lwn.net>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>

authored by Jonathan Corbet and committed by Linus Torvalds 218d11a8 f2f1fa78

+15 -4
+7
fs/fcntl.c
··· 19 19 #include <linux/signal.h> 20 20 #include <linux/rcupdate.h> 21 21 #include <linux/pid_namespace.h> 22 + #include <linux/smp_lock.h> 22 23 23 24 #include <asm/poll.h> 24 25 #include <asm/siginfo.h> ··· 176 175 if (error) 177 176 return error; 178 177 178 + /* 179 + * We still need a lock here for now to keep multiple FASYNC calls 180 + * from racing with each other. 181 + */ 182 + lock_kernel(); 179 183 if ((arg ^ filp->f_flags) & FASYNC) { 180 184 if (filp->f_op && filp->f_op->fasync) { 181 185 error = filp->f_op->fasync(fd, filp, (arg & FASYNC) != 0); ··· 191 185 192 186 filp->f_flags = (arg & SETFL_MASK) | (filp->f_flags & ~SETFL_MASK); 193 187 out: 188 + unlock_kernel(); 194 189 return error; 195 190 } 196 191
+8 -4
fs/ioctl.c
··· 400 400 401 401 /* Did FASYNC state change ? */ 402 402 if ((flag ^ filp->f_flags) & FASYNC) { 403 - if (filp->f_op && filp->f_op->fasync) { 404 - lock_kernel(); 403 + if (filp->f_op && filp->f_op->fasync) 405 404 error = filp->f_op->fasync(fd, filp, on); 406 - unlock_kernel(); 407 - } else 405 + else 408 406 error = -ENOTTY; 409 407 } 410 408 if (error) ··· 438 440 break; 439 441 440 442 case FIONBIO: 443 + /* BKL needed to avoid races tweaking f_flags */ 444 + lock_kernel(); 441 445 error = ioctl_fionbio(filp, argp); 446 + unlock_kernel(); 442 447 break; 443 448 444 449 case FIOASYNC: 450 + /* BKL needed to avoid races tweaking f_flags */ 451 + lock_kernel(); 445 452 error = ioctl_fioasync(fd, filp, argp); 453 + unlock_kernel(); 446 454 break; 447 455 448 456 case FIOQSIZE: