From 4ea97e60c544ad44ee7396c815064d87f0d25874 Mon Sep 17 00:00:00 2001
From: Douglas Gilbert <dgilbert@interlog.com>
Date: Sun, 7 Aug 2022 02:49:03 +0000
Subject: [PATCH] rescan-scsi-bus: sgdevice26: do not traverse sg class if
 scsi_device isnot added

For system which has a massive number of scsi_devices, it would takes a long time to
traverse /sys/class/scsi_generic to find a related sg. If the scsi_device of specific
scsiid host:channel:target:lun did not added, the traverse would find no sg neither.

Signed-off-by: Wenchao Hao <haowenchao@huawei.com>

From: https://github.com/doug-gilbert/sg3_utils/pull/21


git-svn-id: https://svn.bingwo.ca/repos/sg3_utils/trunk@965 6180dd3e-e324-4e3e-922d-17de1ae2f315
---
 scripts/rescan-scsi-bus.sh | 19 +++++++++++--------
 1 file changed, 11 insertions(+), 8 deletions(-)

diff --git a/scripts/rescan-scsi-bus.sh b/scripts/rescan-scsi-bus.sh
index 0c33384..f3e3b2c 100755
--- a/scripts/rescan-scsi-bus.sh
+++ b/scripts/rescan-scsi-bus.sh
@@ -184,18 +184,21 @@ sgdevice26 ()
 {
   local gendev
 
+  # if the scsi device has not been added, then there would not
+  # a related sgdev. So it's pointless to scan all sgs to find
+  # a related sg.
+  scsidev=/sys/class/scsi_device/${host}:${channel}:${id}:${lun}
+  if [ ! -e "$scsidev" ]; then
+    SGDEV=""
+    return
+  fi
+
   gendev=/sys/class/scsi_device/${host}:${channel}:${id}:${lun}/device/generic
   if [ -e "$gendev" ] ; then
     SGDEV=$(basename "$(readlink "$gendev")")
-  else
-    for SGDEV in /sys/class/scsi_generic/sg*; do
-      DEV=$(readlink "$SGDEV/device")
-      if [ "${DEV##*/}" = "$host:$channel:$id:$lun" ] ; then
-        SGDEV=$(basename "$SGDEV"); return
-      fi
-    done
-    SGDEV=""
+    return
   fi
+  SGDEV=""
 }
 
 # Find sg device with 2.4 report-devs extensions
-- 
2.27.0

