From f01c62e5943c8dc7013e3e7bfcc304dd23cea45b Mon Sep 17 00:00:00 2001
From: David Bauer <mail@david-bauer.net>
Date: Sat, 17 Jul 2021 22:50:02 +0200
Subject: [PATCH] gluon-core: wireless: support PHY lookup for multi-PHY
 devices (#2267)

The PHY lookup helper "find_phy_by_path" could not lookup the PHY name
for paths from multi-phy devices.

An example for such a path would be:
'1e140000.pcie/pci0000:00/0000:00:01.0/0000:02:00.0+1'

The integer after the plus (+) character determines the PHY index of the
specific device in relation to the PHY with the lowest index of the
device.

For example, if the device provides phy2 and phy3, the above path would
describe phy3. In case the device provides phy0 and phy1, it would
describe phy1.

Rewrite the "find_phy_by_path" function to support those paths as well
as regular device paths in a universal manner.

Signed-off-by: David Bauer <mail@david-bauer.net>
---
 .../luasrc/usr/lib/lua/gluon/wireless.lua     | 34 ++++++++++++++++---
 1 file changed, 30 insertions(+), 4 deletions(-)

diff --git a/package/gluon-core/luasrc/usr/lib/lua/gluon/wireless.lua b/package/gluon-core/luasrc/usr/lib/lua/gluon/wireless.lua
index 4f2cf0882..0eb68023e 100644
--- a/package/gluon-core/luasrc/usr/lib/lua/gluon/wireless.lua
+++ b/package/gluon-core/luasrc/usr/lib/lua/gluon/wireless.lua
@@ -2,16 +2,42 @@ local sysconfig = require 'gluon.sysconfig'
 local site = require 'gluon.site'
 local util = require 'gluon.util'
 
+local unistd = require 'posix.unistd'
+local dirent = require 'posix.dirent'
+
 
 local M = {}
 
 local function find_phy_by_path(path)
-	local phy = util.glob('/sys/devices/' .. path .. '/ieee80211/phy*')[1]
-		or util.glob('/sys/devices/platform/' .. path .. '/ieee80211/phy*')[1]
+	local device_path, phy_offset = string.match(path, "^(.+)%+(%d+)$")
+
+	-- Special handling required for multi-phy devices
+	if device_path == nil then
+		device_path = path
+		phy_offset = '0'
+	end
 
-	if phy then
-		return phy:match('([^/]+)$')
+	-- Find the device path. Either it's located at /sys/devices or /sys/devices/platform
+	local path_prefix = ''
+	if not unistd.access('/sys/devices/' .. device_path .. '/ieee80211') then
+		path_prefix = 'platform/'
 	end
+
+	-- Get all available PHYs of the device and dertermine the one with the lowest index
+	local phy_names = dirent.dir('/sys/devices/' .. path_prefix .. device_path .. '/ieee80211')
+	local device_phy_idxs = {}
+	for _, v in ipairs(phy_names) do
+		local phy_idx = v:match('^phy(%d+)$')
+
+		if phy_idx ~= nil then
+			table.insert(device_phy_idxs, tonumber(phy_idx))
+		end
+	end
+
+	table.sort(device_phy_idxs)
+
+	-- Index starts at 1
+	return 'phy' .. device_phy_idxs[tonumber(phy_offset) + 1]
 end
 
 local function find_phy_by_macaddr(macaddr)
-- 
GitLab