From 08e6f56176e4bb873337afc76df9ab22908698ea Mon Sep 17 00:00:00 2001 From: hujun5 Date: Fri, 12 Apr 2024 14:32:39 +0800 Subject: [PATCH] fdcheck: fix race condition in fdcheck reason: ioctl will use the fl_lock file lock, causing context switching, further leading to the failure of g_fdcheck_lock protection Configuring NuttX and compile: $ ./tools/configure.sh -l qemu-armv8a:nsh_smp $ make Running with qemu $ qemu-system-aarch64 -cpu cortex-a53 -smp 4 -nographic \ -machine virt,virtualization=on,gic-version=3 \ -net none -chardev stdio,id=con,mux=on -serial chardev:con \ -mon chardev=con,mode=readline -kernel ./nuttx Signed-off-by: hujun5 --- libs/libc/misc/lib_fdcheck.c | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/libs/libc/misc/lib_fdcheck.c b/libs/libc/misc/lib_fdcheck.c index 8cf56dcc3b6..504e98dfe6b 100644 --- a/libs/libc/misc/lib_fdcheck.c +++ b/libs/libc/misc/lib_fdcheck.c @@ -102,6 +102,8 @@ int fdcheck_protect(int fd) DEBUGASSERT(ret >= 0); if (tag == 0) { + uint8_t fdcheck_tag; + irqstate_t flags = spin_lock_irqsave(&g_fdcheck_lock); if ((++g_fdcheck_tag & TAG_MASK) == 0) { @@ -110,9 +112,11 @@ int fdcheck_protect(int fd) g_fdcheck_tag &= TAG_MASK; protect_fd |= g_fdcheck_tag << TAG_SHIFT; - ret = ioctl(fd, FIOC_SETTAG_FDCHECK, &g_fdcheck_tag); - DEBUGASSERT(ret == 0); + fdcheck_tag = g_fdcheck_tag; spin_unlock_irqrestore(&g_fdcheck_lock, flags); + + ret = ioctl(fd, FIOC_SETTAG_FDCHECK, &fdcheck_tag); + DEBUGASSERT(ret == 0); } else {