From 982d13d4cfd1513bdbd74ceb8b256bad5cf679d5 Mon Sep 17 00:00:00 2001
From: Yu Watanabe <watanabe.yu+github@gmail.com>
Date: Wed, 1 Sep 2021 09:44:26 +0900
Subject: [PATCH] udev-node: check stack directory change even if devlink is
 removed

Otherwise, when multiple device additions and removals occur
simultaneously, symlink to unexisting devnode may be created.

Hopefully fixes #19946.

(cherry picked from commit 1cd4e325693007b3628f1a27297f0ab7114b24b8)

Conflict:NA
Reference:https://github.com/systemd/systemd-stable/commit/982d13d4cfd1513bdbd74ceb8b256bad5cf679d5
---
 src/udev/udev-node.c | 15 ++++++---------
 1 file changed, 6 insertions(+), 9 deletions(-)

diff --git a/src/udev/udev-node.c b/src/udev/udev-node.c
index 46c04fe00b..28e6e8df94 100644
--- a/src/udev/udev-node.c
+++ b/src/udev/udev-node.c
@@ -468,15 +468,12 @@ static int link_update(sd_device *dev, const char *slink_in, bool add) {
                 if (r < 0)
                         return r;
 
-                /* Skip the second stat() if the first failed, stat_inode_unmodified() would return false regardless. */
-                if ((st1.st_mode & S_IFMT) != 0) {
-                        r = stat(dirname, &st2);
-                        if (r < 0 && errno != ENOENT)
-                                return log_device_debug_errno(dev, errno, "Failed to stat %s: %m", dirname);
-
-                        if (stat_inode_unmodified(&st1, &st2))
-                                break;
-                }
+                if (stat(dirname, &st2) < 0 && errno != ENOENT)
+                        return log_device_debug_errno(dev, errno, "Failed to stat %s: %m", dirname);
+
+                if (((st1.st_mode & S_IFMT) == 0 && (st2.st_mode & S_IFMT) == 0) ||
+                    stat_inode_unmodified(&st1, &st2))
+                        return 0;
         }
 
         return i < LINK_UPDATE_MAX_RETRIES ? 0 : -ELOOP;
-- 
2.33.0

