Skip to content

Apple's open-source XNU kernel on Android phones: its own loader and drivers, Metal on the Adreno. Runs from RAM; a reboot gives the phone back to Android.

C

Wi-Fi: the radio scans, and the kernel logs the networks it hears

vcvkkc103976a9fd7
diff --git a/README.md b/README.md
index fe11f9a..9e67f9a 100644
--- a/README.md
+++ b/README.md
@@ -163,7 +163,7 @@ XL_SECS=900 XL_CMDLINE="touchscreen=1 cpufreq=1 bootcpu=7 cpus=4" ./xl run #
| `gpu=1` | рисовать графическим процессором телефона (образ с `GL=1`, прошивки в `fw-gpu/`; см. раздел «GPU»). Без него, без прошивок и в QEMU всё рисует программный рендер CoreAnimation |
| `virtio_net=1` | (QEMU; `QEMU_NET=1` добавляет его сам) сетевой интерфейс `en0` на сетевой карте virtio. `net_names=1` — писать в журнал каждое имя, которое система спрашивает у DNS, и каждое начатое TCP-соединение; `net_trace=N` — строка о каждом из первых N кадров |
| `adreno=N` | опыт с GPU телефона: первые N шагов его пробуждения (питание, такты, первые регистры), каждый шаг пишет в журнал, что собирается тронуть и что прочёл; шаги и остальные параметры описаны в начале `bsd/dev/redwood_adreno.c` |
-| `wifi=N` | опыт с Wi-Fi телефона: первые N шагов. 1–5 только читают (общая память процессоров, почтовый ящик процессора питания, RPMh, шины питания, выводы), 6–11 кладут прошивку процессора Wi-Fi в его память, заводят в общей памяти нашу половину его сигнальных битов (SMP2P) и запускают его через TrustZone, 12–14 поднимают связь с ним (GLINK, канал IPCRTR) и QRTR поверх неё: процессор Wi-Fi объявляет свои службы, среди них службу прошивки Wi-Fi; 15 — разговор с этой службой, какой драйвер ведёт до того, как тронет радио (нужны описания сообщений из ath11k: `tools/mk-wlfw.sh`, затем пересобрать ядро): прошивка принимает сообщения ath11k, файл платы и базу регионов телефона, с `wifi_cal=1` калибруется и через 7 секунд говорит «готова»; с `wifi_mission=1` прошивка получает настройку и переходит в рабочий режим; 16 — чтение нескольких регистров радио (`wifi_radio_read=1`): в рабочем режиме они отвечают, вне его чтение кончается ошибкой шины, и шаг его не делает (`adb pull` файлов `wpss.mdt`, `wpss.b02`…`wpss.b07` из `/vendor/firmware_mnt/image` в каталог `fw-wifi/`; в git они не попадают, `userland/build.sh` кладёт их в малый образ). Каждый шаг пишет в журнал, что собирается тронуть и что прочёл. `wifi_keep=1` оставляет процессор Wi-Fi и связь с ним работать, пока идёт сеанс. С `wifi_lx=1` шаг 15 ведёт уже сам драйвер ath11k из Linux (см. «Драйвер Wi-Fi» ниже; ядро собирается после `tools/mk-ath11k.sh`): его `qmi.c` проходит весь разговор с прошивкой до рабочего режима, со своей настройкой и списком теневых регистров, а регистры радио не трогает. С `wifi_lx=2 wifi_smmu=2` потоку радио в SMMU даётся контекст с нашими таблицами страниц (`wifi_smmu=2` в одиночку — только это, с возвратом как было), `ce.c` и `hal.c` драйвера заводят в регистрах радио кольца его «копировальных машин», `htc.c` подключает по ним службу WMI, и прошивка по WMI рассказывает о радио (одно, две антенные цепи, 2,4 и 5 ГГц) и через четверть секунды после запуска шины сообщает, что готова к командам («unified ready»); собственного адреса у прошивки нет (нули). Прерываний при этом нет: кольца опрашиваются раз в миллисекунду. Дальше драйвер пока не собран, и на этом он в правильном порядке сворачивается: сети нет. Остановленный без спроса (ядро, которое до этого не дошло) второй раз без перезагрузки телефона не запускается — такой запуск сбрасывал телефон, и драйвер от него сам отказывается; шаги и остальные параметры описаны в начале `bsd/dev/redwood_wifi.c` |
+| `wifi=N` | опыт с Wi-Fi телефона: первые N шагов. 1–5 только читают (общая память процессоров, почтовый ящик процессора питания, RPMh, шины питания, выводы), 6–11 кладут прошивку процессора Wi-Fi в его память, заводят в общей памяти нашу половину его сигнальных битов (SMP2P) и запускают его через TrustZone, 12–14 поднимают связь с ним (GLINK, канал IPCRTR) и QRTR поверх неё: процессор Wi-Fi объявляет свои службы, среди них службу прошивки Wi-Fi; 15 — разговор с этой службой, какой драйвер ведёт до того, как тронет радио (нужны описания сообщений из ath11k: `tools/mk-wlfw.sh`, затем пересобрать ядро): прошивка принимает сообщения ath11k, файл платы и базу регионов телефона, с `wifi_cal=1` калибруется и через 7 секунд говорит «готова»; с `wifi_mission=1` прошивка получает настройку и переходит в рабочий режим; 16 — чтение нескольких регистров радио (`wifi_radio_read=1`): в рабочем режиме они отвечают, вне его чтение кончается ошибкой шины, и шаг его не делает (`adb pull` файлов `wpss.mdt`, `wpss.b02`…`wpss.b07` из `/vendor/firmware_mnt/image` в каталог `fw-wifi/`; в git они не попадают, `userland/build.sh` кладёт их в малый образ). Каждый шаг пишет в журнал, что собирается тронуть и что прочёл. `wifi_keep=1` оставляет процессор Wi-Fi и связь с ним работать, пока идёт сеанс. С `wifi_lx=1` шаг 15 ведёт уже сам драйвер ath11k из Linux (см. «Драйвер Wi-Fi» ниже; ядро собирается после `tools/mk-ath11k.sh`): его `qmi.c` проходит весь разговор с прошивкой до рабочего режима, со своей настройкой и списком теневых регистров, а регистры радио не трогает. С `wifi_lx=2 wifi_smmu=2` потоку радио в SMMU даётся контекст с нашими таблицами страниц (`wifi_smmu=2` в одиночку — только это, с возвратом как было), `ce.c` и `hal.c` драйвера заводят в регистрах радио кольца его «копировальных машин», `htc.c` подключает по ним службу WMI, и прошивка по WMI рассказывает о радио (одно, две антенные цепи, 2,4 и 5 ГГц) и через четверть секунды после запуска шины сообщает, что готова к командам («unified ready»); собственного адреса у прошивки нет (нули). Прерываний при этом нет: кольца опрашиваются раз в миллисекунду. С `wifi_scan=1` драйвер после этого регистрирует радио, заводит интерфейс в режиме станции и просит прошивку просканировать эфир — только слушая, в эфир ничего не уходит: 26 каналов 2,4 и 5 ГГц за четыре секунды, и в журнале появляются точки доступа вокруг с каналами и уровнем сигнала (имена и адреса чужих сетей — только в журнале запуска на вашей машине). Адрес радио у прошивки свой не записан: он лежит одной строкой в `fw-wifi/mac` (в git не попадает), и `xl run` передаёт его ядру параметром `wifi_mac`. К сети драйвер пока не подключается (тракт данных не собран), после сканирования он в правильном порядке сворачивается: сети нет. Остановленный без спроса (ядро, которое до этого не дошло) второй раз без перезагрузки телефона не запускается — такой запуск сбрасывал телефон, и драйвер от него сам отказывается; шаги и остальные параметры описаны в начале `bsd/dev/redwood_wifi.c` |
Несколько ядер на телефоне проверены (2, 4 и 7 ядер запускаются и чисто возвращаются в загрузчик). Лучший
вариант — **`cpus=4`**: четыре больших ядра (7, 6, 5, 4). На одном и том же сценарии: 929 кадров вместо 671,
@@ -386,12 +386,14 @@ Userland не изменён ни в одном байте: всё, чего е
с которыми FreeBSD собирает драйверы Linux), сверяет контрольные суммы, накладывает `wifi/lx/patches/*.patch` на
заголовки FreeBSD и компилирует файлы драйвера без единой правки, как код ядра FreeBSD. Чего заголовкам не
хватает и всё, что под ними (блокировки, сон, очереди работ, таймеры, память для радио, буферы, файлы прошивки,
-шина радио), — наше, в `wifi/lx/`, и стоит на полутора десятках вызовов, которые даёт ядро
+шина радио), — наше, в `wifi/lx/`, и стоит на без малого двух десятках вызовов, которые даёт ядро
(`bsd/sys/redwood_lx.h`, `bsd/dev/redwood_lx.c`). Получается один объектный файл
`xnu-deps/build/ath11k/out/ath11k.o` с единственным видимым именем; `xnu-build.sh` линкует его в ядро, если он
есть, а без него ядро собирается как раньше и на `wifi_lx` отвечает, что драйвера в нём нет.
-Собрано пока восемь файлов драйвера из трёх с лишним десятков (`core`, `hal`, `qmi`, `ce`, `hw`, `fw`, `htc`, `wmi`); вызовы в
+Собрано пока одиннадцать файлов драйвера из трёх с лишним десятков (`core`, `hal`, `qmi`, `ce`, `hw`, `fw`, `htc`,
+`wmi`, `mac`, `reg`, `peer`); над драйвером вместо mac80211 из Linux стоит наше начало станции
+(`wifi/lx/src/lx_80211.c`): регистрация радио, регуляторный домен, один интерфейс и сканирование. Вызовы в
остальные — заглушки, которые пишут своё имя в журнал (список — `out/stubs.txt` после сборки). Что это уже
делает на телефоне, сказано в строке `wifi=N` таблицы параметров ядра.
diff --git a/tools/mk-ath11k.sh b/tools/mk-ath11k.sh
index 0851445..a806fa3 100755
--- a/tools/mk-ath11k.sh
+++ b/tools/mk-ath11k.sh
@@ -114,7 +114,7 @@ if [ ! -d gen ]; then
fi
# --- compile: the driver's files that are built so far, and ours
-DRIVER="core hal qmi ce hw fw htc wmi"
+DRIVER="core hal qmi ce hw fw htc wmi mac reg peer"
CC="clang -target arm64-apple-ios16.5"
LD=$ROOT/xnu-deps/host/bin/ld64
CFLAGS="-mkernel -mgeneral-regs-only -fno-builtin -fno-common -ffreestanding -fno-strict-aliasing
diff --git a/wifi/lx/include/linux/rhashtable.h b/wifi/lx/include/linux/rhashtable.h
new file mode 100644
index 0000000..a447a17
--- /dev/null
+++ b/wifi/lx/include/linux/rhashtable.h
@@ -0,0 +1,38 @@
+/*
+ * Linux's hash table that resizes itself, as far as the driver uses it: things found by a key
+ * that lies inside them (peer.c: a peer by its address, and by its number). LinuxKPI's header
+ * has the names and nothing behind them -- its rhashtable_init() fails --, so this one stands
+ * in its place: a fixed number of chains, which never resize. The functions are in
+ * src/lx_base.c.
+ */
+#ifndef _LX_LINUX_RHASHTABLE_H
+#define _LX_LINUX_RHASHTABLE_H
+
+#include <linux/types.h>
+
+struct rhash_head {
+ struct rhash_head *next;
+};
+
+struct rhashtable_params {
+ uint16_t head_offset; /* of the thing's rhash_head, in the thing */
+ uint16_t key_len;
+ uint16_t key_offset; /* of the key, in the thing */
+ uint16_t nelem_hint;
+ bool automatic_shrinking;
+};
+
+struct rhashtable {
+ struct rhash_head *chains[64];
+};
+
+int rhashtable_init(struct rhashtable *table, const struct rhashtable_params *params);
+void rhashtable_destroy(struct rhashtable *table);
+/* the thing with that key, or NULL */
+void *rhashtable_lookup_fast(struct rhashtable *table, const void *key, const struct rhashtable_params params);
+/* the thing already there under the new thing's key; or NULL, and the new thing is in */
+void *rhashtable_lookup_get_insert_fast(struct rhashtable *table, struct rhash_head *head,
+ const struct rhashtable_params params);
+int rhashtable_remove_fast(struct rhashtable *table, struct rhash_head *head, const struct rhashtable_params params);
+
+#endif
diff --git a/wifi/lx/include/linux/soc/qcom/qmi.h b/wifi/lx/include/linux/soc/qcom/qmi.h
index 2f6ae84..71332ea 100644
--- a/wifi/lx/include/linux/soc/qcom/qmi.h
+++ b/wifi/lx/include/linux/soc/qcom/qmi.h
@@ -11,6 +11,15 @@
#include <linux/jiffies.h>
#define REDWOOD_QMI_JIFFIES_TO_MS(j) jiffies_to_msecs(j)
#include LX_REDWOOD_QMI_H
+/*
+ * What the driver sends goes past the radio's bus first (src/lx_bus.c), which has to know of one
+ * request: the mode the firmware is asked for. The radio's registers answer in mission mode only.
+ */
+int lx_qmi_send_request(struct qmi_handle *qmi, struct sockaddr_qrtr *sq, struct qmi_txn *txn, int msg_id, size_t largest,
+ const struct qmi_elem_info *ei, const void *structure);
+#ifndef LX_QMI_AS_IT_IS
+#define qmi_send_request lx_qmi_send_request
+#endif
#else
#include <linux/socket.h>
#include_next <linux/soc/qcom/qmi.h>
diff --git a/wifi/lx/patches/include-linux-etherdevice.h.patch b/wifi/lx/patches/include-linux-etherdevice.h.patch
new file mode 100644
index 0000000..d71bb07
--- /dev/null
+++ b/wifi/lx/patches/include-linux-etherdevice.h.patch
@@ -0,0 +1,19 @@
+--- a/sys/compat/linuxkpi/common/include/linux/etherdevice.h
++++ b/sys/compat/linuxkpi/common/include/linux/etherdevice.h
+@@ -131,12 +131,14 @@
+ random_ether_addr(dst);
+ }
+
++/* (the address the machine has for the device, if it has one: not from a device tree here) */
++int linuxkpi_device_get_mac_address(struct device *dev, char *dst);
++
+ static inline int
+ device_get_mac_address(struct device *dev, char *dst)
+ {
+
+- /* XXX get mac address from FDT? */
+- return (-ENOENT);
++ return (linuxkpi_device_get_mac_address(dev, dst));
+ }
+
+ /* Returns network byte order. */
diff --git a/wifi/lx/patches/include-net-cfg80211.h.patch b/wifi/lx/patches/include-net-cfg80211.h.patch
index cbdb12a..961a9d7 100644
--- a/wifi/lx/patches/include-net-cfg80211.h.patch
+++ b/wifi/lx/patches/include-net-cfg80211.h.patch
@@ -16,3 +16,24 @@
int dfs_cac_ms;
struct freq_range {
int start_freq_khz;
+@@ -1714,18 +1716,8 @@
+ struct linuxkpi_ieee80211_regdomain *regd)
+ {
+
+- IMPROVE();
+- if (regd == NULL)
+- return (EINVAL);
+-
+- /* XXX-BZ wild guessing here based on brcmfmac. */
+- if (wiphy->regulatory_flags & REGULATORY_WIPHY_SELF_MANAGED)
+- wiphy->regd = regd;
+- else
+- return (EPERM);
+-
+- /* XXX FIXME, do we have to do anything with reg_notifier? */
+- return (0);
++ /* (the caller keeps and may free regd: a copy is made, as Linux makes one) */
++ return (linuxkpi_regulatory_set_wiphy_regd_sync(wiphy, regd));
+ }
+
+ static __inline int
diff --git a/wifi/lx/src/lx.h b/wifi/lx/src/lx.h
index ab3c0c7..8667c35 100644
--- a/wifi/lx/src/lx.h
+++ b/wifi/lx/src/lx.h
@@ -6,5 +6,7 @@ int lx_base_init(void); /* lx_base.c: the thread that counts the ticks and runs
int lx_pool_init(void); /* lx_base.c: the memory the radio reads and writes; 0, or an errno */
long lx_stub(const char *name); /* lx_base.c: what a function that is not there yet does */
void lx_pause_ms(unsigned ms); /* lx_base.c: sleep */
+void lx_mark(const char *what); /* lx_base.c: a point reached, said and waited at if the kernel was asked to */
+int lx_station_scan(void); /* lx_80211.c: an interface in station mode, a scan, what was heard; 0, or an errno */
#endif
diff --git a/wifi/lx/src/lx_80211.c b/wifi/lx/src/lx_80211.c
index 1364ab2..6f3a560 100644
--- a/wifi/lx/src/lx_80211.c
+++ b/wifi/lx/src/lx_80211.c
@@ -2,19 +2,274 @@
* Where the driver meets 802.11 itself: under Linux that is mac80211 and cfg80211, under FreeBSD
* LinuxKPI's stand-in for them on top of net80211, and here it is ours -- the functions that
* LinuxKPI's headers (net/mac80211.h, net/cfg80211.h) declare under linuxkpi_ names, as far as
- * the files of the driver that are built call them. So far that is wmi.c, which hands what the
- * firmware has received and what it has sent to the layer above; there is no such layer yet, and
- * frames end here.
+ * the files of the driver that are built call them, and the beginning of a station: the layer
+ * that asks the driver for things, in mac80211's order (FreeBSD's linux_80211.c shows it).
+ *
+ * What is here: the radio as the driver describes it when it registers; the regulatory domain
+ * the driver hands over, applied to the radio's channels the way cfg80211 applies it; one
+ * interface in station mode; a scan of every channel the domain allows, which only listens;
+ * and what the radio then hears -- beacons and answers to others' probes --, kept by sender
+ * and said when the scan is over. Nothing joins a network yet, and nothing is sent.
+ *
+ * On the phone, 13 October, this scans: 26 channels in 4.1 s, and the access points around are
+ * heard with their channels and strengths (bsd/dev/redwood_wifi.c, step_driver(), has the
+ * account). What is said of them names other people's networks: it is for the log of the run.
*/
#include <linux/kernel.h>
+#include <linux/etherdevice.h>
#include <linux/skbuff.h>
+#include <linux/slab.h>
+#include <linux/workqueue.h>
#include <net/cfg80211.h>
#include <net/mac80211.h>
+#include <lx_os.h>
#include "lx.h"
int linuxkpi_debug_80211; /* (which of the headers' own remarks are printed: none) */
+#define HEARD_MOST 160
+
+/* A network, as its beacons describe it. */
+struct lx_heard {
+ uint8_t sender[ETH_ALEN]; /* the access point's address (BSSID) */
+ uint8_t name[32], name_length;
+ uint16_t frequency; /* MHz, of the channel it was heard on at its strongest */
+ uint8_t says_channel; /* the channel it says it is on (0: it does not say) */
+ int8_t signal; /* dBm, the strongest */
+ uint16_t capability;
+ bool protected; /* it announces WPA2 or later (an RSN element) */
+ unsigned times;
+};
+
+/* A radio: what stands behind the driver's "hw" and "wiphy". There is one. */
+struct lx_radio {
+ void *memory; /* all of this was allocated as one piece, which begins here */
+ struct wiphy *wiphy;
+ struct ieee80211_hw hw;
+ const struct ieee80211_ops *ops;
+ bool registered;
+ bool kept; /* the channels' flags and powers as the driver set them have been put by */
+ int applying; /* a regulatory domain is being applied to the channels right now */
+ struct workqueue_struct *work; /* for what the driver has "the stack" run for it */
+ struct linuxkpi_ieee80211_regdomain *regd;
+ struct ieee80211_vif *vif; /* the one interface, while it is up */
+ volatile int scan; /* 0: none, 1: running, 2: over, 3: given up by the driver */
+ unsigned frames, others; /* received in all, and of them neither beacon nor probe response */
+ unsigned heard_count, heard_lost;
+ struct lx_heard heard[HEARD_MOST];
+};
+
+static struct lx_radio *the_radio;
+static const uint8_t no_network[ETH_ALEN]; /* the address of the network an interface has joined, while it has joined none */
+
+static struct lx_radio *
+radio_of(struct ieee80211_hw *hw)
+{
+ return (__containerof(hw, struct lx_radio, hw));
+}
+
+/* ---- the radio, as the driver makes and registers it -------------------------------------------- */
+
+struct ieee80211_hw *
+linuxkpi_ieee80211_alloc_hw(size_t private, const struct ieee80211_ops *ops)
+{
+ size_t ours = roundup2(sizeof(struct lx_radio), 64);
+ uint8_t *memory = kzalloc(64 + offsetof(struct wiphy, priv) + ours + private, GFP_KERNEL);
+ struct lx_radio *radio;
+ struct wiphy *wiphy;
+
+ if (memory == NULL) {
+ return (NULL);
+ }
+ wiphy = (struct wiphy *)roundup2((uintptr_t)memory, 64);
+ radio = (struct lx_radio *)wiphy->priv;
+ radio->memory = memory;
+ radio->wiphy = wiphy;
+ radio->ops = ops;
+ radio->hw.wiphy = wiphy;
+ radio->hw.priv = (uint8_t *)radio + ours;
+ radio->work = alloc_ordered_workqueue("wifi-80211", 0);
+ mutex_init(&wiphy->mtx);
+ return (&radio->hw);
+}
+
+struct ieee80211_hw *
+linuxkpi_wiphy_to_ieee80211_hw(struct wiphy *wiphy)
+{
+ return (&((struct lx_radio *)wiphy->priv)->hw);
+}
+
+void
+linuxkpi_set_ieee80211_dev(struct ieee80211_hw *hw)
+{
+}
+
+int
+linuxkpi_80211_wiphy_register(struct wiphy *wiphy)
+{
+ return (0);
+}
+
+/* ieee80211_register_hw(): the driver has described its radio, and from here on may be asked for things. */
+int
+linuxkpi_ieee80211_ifattach(struct ieee80211_hw *hw)
+{
+ struct lx_radio *radio = radio_of(hw);
+ char bands[96] = "";
+
+ for (unsigned band = 0; band < NUM_NL80211_BANDS; band++) {
+ if (hw->wiphy->bands[band] != NULL) {
+ snprintf(bands + strlen(bands), sizeof(bands) - strlen(bands), " %d in band %u,", hw->wiphy->bands[band]->n_channels,
+ band);
+ }
+ }
+ printf("lx: the driver registers a radio: channels:%s (0: 2.4 GHz, 1: 5 GHz, 3: 6 GHz); %s; up to %d names and %u "
+ "bytes of extras in a scan\n", bands, is_zero_ether_addr(hw->wiphy->perm_addr) ? "IT HAS NO ADDRESS" :
+ "it has an address", hw->wiphy->max_scan_ssids, hw->wiphy->max_scan_ie_len);
+ radio->registered = true;
+ the_radio = radio;
+ return (0);
+}
+
+/* The driver takes its radio back, and frees the channels next: nobody may be at them when this returns. */
+void
+linuxkpi_ieee80211_unregister_hw(struct ieee80211_hw *hw)
+{
+ struct lx_radio *radio = radio_of(hw);
+
+ lx_os_lock();
+ radio->registered = false;
+ while (radio->applying != 0) {
+ lx_os_sleep(&radio->applying, 5 * 1000000ull);
+ }
+ if (the_radio == radio) {
+ the_radio = NULL;
+ }
+ lx_os_unlock();
+}
+
+void
+linuxkpi_ieee80211_iffree(struct ieee80211_hw *hw)
+{
+ struct lx_radio *radio = radio_of(hw);
+
+ if (radio->work != NULL) {
+ destroy_workqueue(radio->work);
+ radio->work = NULL;
+ }
+}
+
+void
+linuxkpi_wiphy_free(struct wiphy *wiphy)
+{
+ struct lx_radio *radio = (struct lx_radio *)wiphy->priv;
+
+ kfree(radio->regd);
+ kfree(radio->memory);
+}
+
+/* ---- the regulatory domain ------------------------------------------------------------------------ */
+
+/*
+ * What cfg80211 does with a domain (Linux: net/wireless/reg.c, handle_channel()): a channel
+ * may be used if a rule covers its 20 MHz, and takes the rule's limits; otherwise it is
+ * disabled. The driver reads the result off the channels when it tells the firmware which it
+ * may use (reg.c: ath11k_reg_update_chan_list()), and so does the scan below.
+ */
+static void
+regd_apply(struct lx_radio *radio)
+{
+ const struct linuxkpi_ieee80211_regdomain *regd = radio->regd;
+ char said[160] = "";
+
+ for (unsigned band = 0; band < NUM_NL80211_BANDS; band++) {
+ struct ieee80211_supported_band *has = radio->wiphy->bands[band];
+ int allowed = 0;
+
+ for (int i = 0; has != NULL && i < has->n_channels; i++) {
+ struct linuxkpi_ieee80211_channel *channel = &has->channels[i];
+ const struct ieee80211_reg_rule *rule = NULL;
+
+ if (!radio->kept) {
+ channel->orig_flags = channel->flags;
+ channel->orig_mpwr = channel->max_power;
+ }
+ for (int r = 0; r < regd->n_reg_rules && rule == NULL; r++) {
+ if (regd->reg_rules[r].freq_range.start_freq_khz <= ((int)channel->center_freq - 10) * 1000 &&
+ regd->reg_rules[r].freq_range.end_freq_khz >= ((int)channel->center_freq + 10) * 1000) {
+ rule = &regd->reg_rules[r];
+ }
+ }
+ channel->flags = channel->orig_flags & ~(IEEE80211_CHAN_DISABLED | IEEE80211_CHAN_NO_IR | IEEE80211_CHAN_RADAR);
+ if (rule == NULL) {
+ channel->flags |= IEEE80211_CHAN_DISABLED;
+ continue;
+ }
+ if (rule->flags & NL80211_RRF_NO_IR) {
+ channel->flags |= IEEE80211_CHAN_NO_IR;
+ }
+ if (rule->flags & NL80211_RRF_DFS) {
+ channel->flags |= IEEE80211_CHAN_RADAR;
+ }
+ channel->max_reg_power = rule->power_rule.max_eirp / 100; /* (hundredths of a dBm) */
+ channel->max_antenna_gain = rule->power_rule.max_antenna_gain / 100;
+ channel->max_power = channel->orig_mpwr != 0 && channel->orig_mpwr < channel->max_reg_power ?
+ channel->orig_mpwr : channel->max_reg_power;
+ allowed++;
+ }
+ if (has != NULL) {
+ snprintf(said + strlen(said), sizeof(said) - strlen(said), " %d of %d in band %u,", allowed, has->n_channels, band);
+ }
+ }
+ radio->kept = true;
+ printf("lx: the regulatory domain \"%c%c\" (%d rules) allows the radio's channels:%s\n", regd->alpha2[0], regd->alpha2[1],
+ regd->n_reg_rules, said);
+}
+
+/*
+ * The driver's domain for its radio (which it has from the firmware). It keeps its own copy and
+ * may free it. The driver calls this from work of its own, one call at a time, and may be
+ * waiting for that work to end while it holds the radio's lock: so that lock is not taken here.
+ * A domain that comes when the radio is no longer registered is not applied (the firmware sends
+ * one whenever the country changes, also while the driver is on its way down).
+ */
+int
+linuxkpi_regulatory_set_wiphy_regd_sync(struct wiphy *wiphy, struct linuxkpi_ieee80211_regdomain *regd)
+{
+ struct lx_radio *radio = (struct lx_radio *)wiphy->priv;
+ struct linuxkpi_ieee80211_regdomain *copy, *old;
+ size_t size;
+
+ if (regd == NULL) {
+ return (-EINVAL);
+ }
+ size = sizeof(*regd) + regd->n_reg_rules * sizeof(regd->reg_rules[0]);
+ copy = kmalloc(size, GFP_KERNEL);
+ if (copy == NULL) {
+ return (-ENOMEM);
+ }
+ memcpy(copy, regd, size);
+ lx_os_lock();
+ if (!radio->registered) {
+ lx_os_unlock();
+ kfree(copy);
+ return (-ENODEV);
+ }
+ radio->applying++;
+ lx_os_unlock();
+ old = radio->regd;
+ radio->regd = copy;
+ wiphy->regd = copy;
+ regd_apply(radio);
+ lx_os_lock();
+ radio->applying--;
+ lx_os_wakeup(&radio->applying);
+ lx_os_unlock();
+ kfree(old);
+ return (0);
+}
+
/* IEEE 802.11-2020, Annex E: a channel's centre, in MHz */
uint32_t
linuxkpi_ieee80211_channel_to_frequency(uint32_t channel, enum nl80211_band band)
@@ -31,6 +286,13 @@ linuxkpi_ieee80211_channel_to_frequency(uint32_t channel, enum nl80211_band band
}
}
+static unsigned
+channel_of(unsigned frequency)
+{
+ return (frequency == 2484 ? 14 : frequency < 2484 ? (frequency - 2407) / 5 : frequency < 5950 ? (frequency - 5000) / 5 :
+ (frequency - 5950) / 5);
+}
+
/* The channel of that frequency among those the radio was registered with. */
struct linuxkpi_ieee80211_channel *
linuxkpi_ieee80211_get_channel(struct wiphy *wiphy, uint32_t frequency)
@@ -47,35 +309,343 @@ linuxkpi_ieee80211_get_channel(struct wiphy *wiphy, uint32_t frequency)
return (NULL);
}
-/* (no station is known yet: nothing has joined a network) */
+/* ---- what the driver has the layer above do for it ------------------------------------------------- */
+
+void
+linuxkpi_ieee80211_queue_work(struct ieee80211_hw *hw, struct work_struct *work)
+{
+ queue_work(radio_of(hw)->work, work);
+}
+
+void
+linuxkpi_ieee80211_queue_delayed_work(struct ieee80211_hw *hw, struct delayed_work *work, int delay)
+{
+ queue_delayed_work(radio_of(hw)->work, work, delay);
+}
+
+/* (flags: all interfaces, or those that are up; here the one there is is up for as long as it is there) */
+void
+linuxkpi_ieee80211_iterate_interfaces(struct ieee80211_hw *hw, enum ieee80211_iface_iter flags,
+ void (*function)(void *, uint8_t *, struct ieee80211_vif *), void *argument)
+{
+ struct ieee80211_vif *vif = radio_of(hw)->vif;
+
+ if (vif != NULL) {
+ function(argument, vif->addr, vif);
+ }
+}
+
+/* (no network has been joined: there are no stations and no channel is held) */
+void
+linuxkpi_ieee80211_iterate_stations_atomic(struct ieee80211_hw *hw, void (*function)(void *, struct ieee80211_sta *), void *argument)
+{
+}
+
+void
+linuxkpi_ieee80211_iterate_chan_contexts(struct ieee80211_hw *hw,
+ void (*function)(struct ieee80211_hw *, struct ieee80211_chanctx_conf *, void *), void *argument)
+{
+}
+
+struct ieee80211_sta *
+linuxkpi_ieee80211_find_sta(struct ieee80211_vif *vif, const u8 *address)
+{
+ return (NULL);
+}
+
struct ieee80211_sta *
linuxkpi_ieee80211_find_sta_by_ifaddr(struct ieee80211_hw *hw, const uint8_t *address, const uint8_t *own)
{
return (NULL);
}
-/* A frame the radio has received. */
+struct cfg80211_bss *
+linuxkpi_cfg80211_get_bss(struct wiphy *wiphy, struct linuxkpi_ieee80211_channel *channel, const uint8_t *bssid,
+ const uint8_t *ssid, size_t ssid_length, enum ieee80211_bss_type type, enum ieee80211_privacy privacy)
+{
+ return (NULL);
+}
+
void
-linuxkpi_ieee80211_rx(struct ieee80211_hw *hw, struct sk_buff *skb, struct ieee80211_sta *sta, struct napi_struct *napi,
- struct list_head *list)
+linuxkpi_cfg80211_put_bss(struct wiphy *wiphy, struct cfg80211_bss *bss)
+{
+}
+
+/* (nothing is queued for sending: there is nothing to wake, and nothing sent to account for) */
+void
+linuxkpi_ieee80211_wake_queues(struct ieee80211_hw *hw)
+{
+}
+
+void
+linuxkpi_ieee80211_stop_queues(struct ieee80211_hw *hw)
+{
+}
+
+void
+linuxkpi_ieee80211_handle_wake_tx_queue(struct ieee80211_hw *hw, struct ieee80211_txq *queue)
{
- dev_kfree_skb_any(skb);
}
-/* What became of a frame the driver was given to send. */
void
linuxkpi_ieee80211_tx_status(struct ieee80211_hw *hw, struct sk_buff *skb)
{
dev_kfree_skb_any(skb);
}
+void
+linuxkpi_ieee80211_free_txskb(struct ieee80211_hw *hw, struct sk_buff *skb, int status)
+{
+ dev_kfree_skb_any(skb);
+}
+
+void
+linuxkpi_ieee80211_beacon_loss(struct ieee80211_vif *vif)
+{
+ printf("lx: the driver reports beacons lost\n");
+}
+
+void
+linuxkpi_ieee80211_connection_loss(struct ieee80211_vif *vif)
+{
+ printf("lx: the driver reports the connection lost\n");
+}
+
/* (the driver's recovery after its firmware has died, which nothing here goes through) */
void
linuxkpi_ieee80211_restart_hw(struct ieee80211_hw *hw)
{
}
+/* ---- what the radio hears -------------------------------------------------------------------------- */
+
+/*
+ * A beacon or an answer to a probe (IEEE 802.11-2020, 9.3.3): after the 24 bytes every
+ * management frame begins with -- the sender's network is the third address -- a time stamp, the
+ * beacon interval, the capabilities, and then elements, of which the name (0), the channel the
+ * sender says it is on (3) and whether it announces RSN (48) are taken.
+ */
+static void
+heard(struct lx_radio *radio, const uint8_t *frame, unsigned length, unsigned frequency, int signal)
+{
+ struct lx_heard *network = NULL;
+ const uint8_t *element = frame + 36, *end = frame + length;
+
+ lx_os_lock();
+ for (unsigned i = 0; i < radio->heard_count && network == NULL; i++) {
+ if (memcmp(radio->heard[i].sender, frame + 16, ETH_ALEN) == 0) {
+ network = &radio->heard[i];
+ }
+ }
+ if (network == NULL) {
+ if (radio->heard_count == HEARD_MOST) {
+ radio->heard_lost++;
+ lx_os_unlock();
+ return;
+ }
+ network = &radio->heard[radio->heard_count++];
+ bzero(network, sizeof(*network));
+ memcpy(network->sender, frame + 16, ETH_ALEN);
+ network->signal = -128;
+ }
+ network->times++;
+ network->capability = (uint16_t)(frame[34] | frame[35] << 8);
+ if (signal > network->signal) {
+ network->signal = (int8_t)signal;
+ network->frequency = (uint16_t)frequency;
+ }
+ for (; element + 2 <= end && element + 2 + element[1] <= end; element += 2 + element[1]) {
+ if (element[0] == 0 && element[1] <= sizeof(network->name) && (element[1] != 0 || network->name_length == 0)) {
+ network->name_length = element[1];
+ memcpy(network->name, element + 2, element[1]);
+ } else if (element[0] == 3 && element[1] == 1) {
+ network->says_channel = element[2];
+ } else if (element[0] == 48) {
+ network->protected = true;
+ }
+ }
+ lx_os_unlock();
+}
+
+/* A frame the radio has received (the driver has its description behind it: where and how strong). */
void
-linuxkpi_ieee80211_stop_queues(struct ieee80211_hw *hw)
+linuxkpi_ieee80211_rx(struct ieee80211_hw *hw, struct sk_buff *skb, struct ieee80211_sta *sta, struct napi_struct *napi,
+ struct list_head *list)
+{
+ struct lx_radio *radio = radio_of(hw);
+ const struct ieee80211_rx_status *status = IEEE80211_SKB_RXCB(skb);
+
+ radio->frames++;
+ /* (the first byte: 0x80 a beacon, 0x50 an answer to a probe) */
+ if (skb->len >= 36 && (skb->data[0] == 0x80 || skb->data[0] == 0x50)) {
+ heard(radio, skb->data, skb->len, status->freq, status->signal);
+ } else {
+ radio->others++;
+ }
+ dev_kfree_skb_any(skb);
+}
+
+/* The driver's word that the scan it was asked for is over. */
+void
+linuxkpi_ieee80211_scan_completed(struct ieee80211_hw *hw, struct cfg80211_scan_info *info)
+{
+ struct lx_radio *radio = radio_of(hw);
+
+ lx_os_lock();
+ radio->scan = info != NULL && info->aborted ? 3 : 2;
+ lx_os_wakeup(&radio->scan);
+ lx_os_unlock();
+}
+
+/* What was heard, the strongest first. Names and addresses of other people's networks: for the log of the run only. */
+static void
+say_heard(struct lx_radio *radio)
+{
+ unsigned on_channel[200] = { 0 }, low = 0, high = 0, open = 0, nameless = 0;
+ int strongest = -128, weakest = 127;
+ char line[400] = "";
+ bool said[HEARD_MOST] = { false };
+
+ for (unsigned n = 0; n < radio->heard_count; n++) {
+ const struct lx_heard *network = NULL;
+ char name[33];
+ unsigned which = 0, channel;
+
+ for (unsigned i = 0; i < radio->heard_count; i++) {
+ if (!said[i] && (network == NULL || radio->heard[i].signal > network->signal)) {
+ network = &radio->heard[i];
+ which = i;
+ }
+ }
+ said[which] = true;
+ for (unsigned i = 0; i < network->name_length; i++) {
+ name[i] = network->name[i] >= 0x20 && network->name[i] < 0x7f ? (char)network->name[i] : '?';
+ }
+ name[network->name_length] = 0;
+ channel = channel_of(network->frequency);
+ if (channel < nitems(on_channel)) {
+ on_channel[channel]++;
+ }
+ *(network->frequency < 4000 ? &low : &high) += 1;
+ open += !(network->capability & 0x10);
+ nameless += network->name_length == 0 || network->name[0] == 0;
+ strongest = network->signal > strongest ? network->signal : strongest;
+ weakest = network->signal < weakest ? network->signal : weakest;
+ printf("lx: heard: channel %3u (%u MHz) %4d dBm %02x:%02x:%02x:%02x:%02x:%02x %s, %u times \"%s\"\n", channel,
+ network->frequency, network->signal, network->sender[0], network->sender[1], network->sender[2], network->sender[3],
+ network->sender[4], network->sender[5], !(network->capability & 0x10) ? "open" : network->protected ? "RSN" :
+ "protected", network->times, name);
+ }
+ for (unsigned channel = 0; channel < nitems(on_channel); channel++) {
+ if (on_channel[channel] != 0) {
+ snprintf(line + strlen(line), sizeof(line) - strlen(line), " %u on %u,", on_channel[channel], channel);
+ }
+ }
+ printf("lx: THE SCAN HEARD %u NETWORKS (access points): %u at 2.4 GHz, %u at 5 GHz; by channel:%s the strongest at %d dBm, "
+ "the weakest at %d; %u open, %u without a name; %u frames in all, %u of them neither beacon nor answer to a probe%s\n",
+ radio->heard_count, low, high, line, radio->heard_count ? strongest : 0, radio->heard_count ? weakest : 0, open, nameless,
+ radio->frames, radio->others, radio->heard_lost ? "; MORE WERE HEARD THAN THERE WAS ROOM FOR" : "");
+}
+
+/* ---- the station ------------------------------------------------------------------------------------ */
+
+/*
+ * What mac80211 does when an interface in station mode is brought up and asked to scan, as far
+ * as the driver is concerned: the radio is started, the interface added to it, and a scan
+ * requested of every channel the regulatory domain allows, with no name to ask for -- which
+ * makes it a scan that only listens (mac.c: ath11k_mac_op_hw_scan()). When the driver says the
+ * scan is over, what was heard is said, and the interface and the radio are taken down again.
+ * 0, or an errno.
+ */
+int
+lx_station_scan(void)
{
+ struct lx_radio *radio = the_radio;
+ struct ieee80211_scan_request *request;
+ struct ieee80211_vif *vif;
+ struct ieee80211_hw *hw;
+ uint8_t *memory;
+ unsigned long long began;
+ int channels = 0, ret;
+
+ if (radio == NULL || !radio->registered) {
+ printf("lx: no radio is registered: nothing to scan with\n");
+ return (ENXIO);
+ }
+ hw = &radio->hw;
+ if (is_zero_ether_addr(hw->wiphy->perm_addr)) {
+ printf("lx: THE RADIO HAS NO ADDRESS (the kernel was given none, and the firmware has none): no interface is made\n");
+ return (EADDRNOTAVAIL);
+ }
+ for (unsigned band = 0; band < NUM_NL80211_BANDS; band++) {
+ channels += hw->wiphy->bands[band] != NULL ? hw->wiphy->bands[band]->n_channels : 0;
+ }
+ memory = kzalloc(64 + sizeof(*vif) + hw->vif_data_size, GFP_KERNEL);
+ request = kzalloc(sizeof(*request) + channels * sizeof(request->req.channels[0]), GFP_KERNEL);
+ if (memory == NULL || request == NULL) {
+ return (ENOMEM);
+ }
+ vif = (struct ieee80211_vif *)roundup2((uintptr_t)memory, 64);
+ vif->type = NL80211_IFTYPE_STATION;
+ memcpy(vif->addr, hw->wiphy->perm_addr, ETH_ALEN);
+ memcpy(vif->bss_conf.addr, hw->wiphy->perm_addr, ETH_ALEN);
+ vif->bss_conf.vif = vif;
+ vif->bss_conf.bssid = no_network; /* (the driver compares every beacon's sender with it) */
+ vif->link_conf[0] = &vif->bss_conf;
+
+ mutex_lock(&hw->wiphy->mtx);
+ ret = radio->ops->start(hw);
+ printf("lx: the radio is started: %d\n", ret);
+ if (ret != 0) {
+ mutex_unlock(&hw->wiphy->mtx);
+ return (-ret);
+ }
+ ret = radio->ops->add_interface(hw, vif);
+ printf("lx: an interface in station mode is added to it: %d\n", ret);
+ if (ret != 0) {
+ radio->ops->stop(hw, false);
+ mutex_unlock(&hw->wiphy->mtx);
+ return (-ret);
+ }
+ radio->vif = vif;
+
+ request->req.wiphy = hw->wiphy;
+ for (unsigned band = 0; band < NUM_NL80211_BANDS; band++) {
+ struct ieee80211_supported_band *has = hw->wiphy->bands[band];
+
+ for (int i = 0; has != NULL && i < has->n_channels; i++) {
+ if (!(has->channels[i].flags & IEEE80211_CHAN_DISABLED)) {
+ request->req.channels[request->req.n_channels++] = &has->channels[i];
+ }
+ }
+ }
+ radio->scan = 1;
+ radio->frames = radio->others = radio->heard_count = radio->heard_lost = 0;
+ began = lx_os_nanoseconds();
+ ret = radio->ops->hw_scan(hw, vif, request);
+ mutex_unlock(&hw->wiphy->mtx);
+ printf("lx: THE DRIVER IS ASKED TO SCAN %d channels, listening only: %d\n", request->req.n_channels, ret);
+ if (ret == 0) {
+ lx_os_lock();
+ while (radio->scan == 1 && lx_os_nanoseconds() - began < 40000000000ull) {
+ lx_os_sleep(&radio->scan, 100 * 1000000ull);
+ }
+ lx_os_unlock();
+ printf("lx: %llu ms later the scan is %s\n", (lx_os_nanoseconds() - began) / 1000000ull, radio->scan == 2 ? "OVER" :
+ radio->scan == 3 ? "GIVEN UP by the driver" : "NOT OVER: the driver has not said so");
+ say_heard(radio);
+ }
+
+ mutex_lock(&hw->wiphy->mtx);
+ if (ret == 0 && radio->scan == 1 && radio->ops->cancel_hw_scan != NULL) {
+ radio->ops->cancel_hw_scan(hw, vif);
+ }
+ radio->ops->remove_interface(hw, vif);
+ radio->vif = NULL;
+ radio->ops->stop(hw, false);
+ mutex_unlock(&hw->wiphy->mtx);
+ printf("lx: the interface is removed and the radio stopped\n");
+ kfree(request);
+ kfree(memory);
+ return (ret != 0 ? -ret : radio->scan == 2 ? 0 : ETIMEDOUT);
}
diff --git a/wifi/lx/src/lx_base.c b/wifi/lx/src/lx_base.c
index f17a64a..c97fc67 100644
--- a/wifi/lx/src/lx_base.c
+++ b/wifi/lx/src/lx_base.c
@@ -32,6 +32,7 @@
#include <linux/io.h>
#include <linux/jiffies.h>
#include <linux/kernel.h>
+#include <linux/rhashtable.h>
#include <linux/sched.h>
#include <linux/skbuff.h>
#include <linux/slab.h>
@@ -75,6 +76,7 @@ lx_stub(const char *name)
if (seen[i].name == name) {
if (seen[i].calls++ < 3) {
printf("lx: %s() is not there yet: answers 0%s\n", name, seen[i].calls == 3 ? " (said for the last time)" : "");
+ lx_mark(name);
}
break;
}
@@ -82,6 +84,25 @@ lx_stub(const char *name)
return (0);
}
+/*
+ * A point the driver's start has reached. With the kernel's option wifi_lx_step=MS it is also
+ * waited at, so that whoever follows the log from outside has the line before what comes next:
+ * for finding where a run ends that ends without a word.
+ */
+void
+lx_mark(const char *what)
+{
+ static unsigned wait = ~0u;
+
+ if (wait == ~0u) {
+ wait = lx_os_option("wifi_lx_step");
+ }
+ if (wait != 0) {
+ printf("lx: reached: %s\n", what);
+ lx_pause_ms(wait);
+ }
+}
+
void
linux_dump_stack(void)
{
@@ -196,6 +217,11 @@ ticks_to_ns(unsigned long ticks)
}
static struct timer_list *armed[16];
+static struct {
+ struct delayed_work *work; /* to be queued on ... */
+ struct workqueue_struct *queue; /* ... when the ticks have reached ... */
+ unsigned long when;
+} later[16];
static void
ticker(void *argument)
@@ -204,6 +230,8 @@ ticker(void *argument)
for (;;) {
struct timer_list *due = NULL;
+ struct delayed_work *work = NULL;
+ struct workqueue_struct *queue = NULL;
lx_os_lock();
lx_os_sleep(&jiffies, 2 * 1000000ull);
@@ -214,11 +242,77 @@ ticker(void *argument)
armed[i] = NULL;
}
}
+ for (unsigned i = 0; i < nitems(later) && work == NULL; i++) {
+ if (later[i].work != NULL && (long)(jiffies - later[i].when) >= 0) {
+ work = later[i].work;
+ queue = later[i].queue;
+ later[i].work = NULL;
+ }
+ }
lx_os_unlock();
- if (due != NULL) {
+ /* (a timer that a part of the driver not built yet would have given its function has none) */
+ if (due != NULL && due->function_415 != NULL) {
due->function_415(due);
}
+ if (work != NULL) {
+ linux_queue_work_on(0, queue, &work->work);
+ }
+ }
+}
+
+/* Work that is to be queued when some time has passed: the thread above does that. */
+void
+linux_init_delayed_work(struct delayed_work *dwork, work_func_t function)
+{
+ bzero(dwork, sizeof(*dwork));
+ INIT_WORK(&dwork->work, function);
+}
+
+bool
+linux_queue_delayed_work_on(int cpu, struct workqueue_struct *wq, struct delayed_work *dwork, unsigned long delay)
+{
+ int slot = -1;
+
+ if (delay == 0) {
+ return (linux_queue_work_on(cpu, wq, &dwork->work));
+ }
+ lx_os_lock();
+ for (unsigned i = 0; i < nitems(later); i++) {
+ if (later[i].work == dwork) {
+ lx_os_unlock();
+ return (false); /* (it waits already) */
+ }
+ if (later[i].work == NULL && slot < 0) {
+ slot = (int)i;
+ }
+ }
+ if (slot >= 0) {
+ later[slot].work = dwork;
+ later[slot].queue = wq;
+ later[slot].when = jiffies + delay;
+ }
+ lx_os_unlock();
+ if (slot < 0) {
+ printf("lx: no room for more work that waits for its time: one piece will not be done\n");
+ }
+ return (slot >= 0);
+}
+
+/* Not to be queued any more, if it waits for its time; true if it did. */
+bool
+linux_cancel_delayed_work(struct delayed_work *dwork)
+{
+ bool waited = false;
+
+ lx_os_lock();
+ for (unsigned i = 0; i < nitems(later); i++) {
+ if (later[i].work == dwork) {
+ later[i].work = NULL;
+ waited = true;
+ }
}
+ lx_os_unlock();
+ return (waited);
}
/* (A timer's function that is running on the ticker's thread at this moment is not waited for.) */
@@ -575,8 +669,9 @@ linux_cancel_work_sync(struct work_struct *work)
bool
linux_cancel_delayed_work_sync(struct delayed_work *dwork)
{
- /* (work is never queued with a delay by what is built so far) */
- return (linux_cancel_work_sync(&dwork->work));
+ bool waited = linux_cancel_delayed_work(dwork);
+
+ return (linux_cancel_work_sync(&dwork->work) || waited);
}
void
@@ -931,6 +1026,94 @@ idr_for_each(struct idr *idr, int (*function)(int id, void *p, void *data), void
return (answer);
}
+/*
+ * Things found by a key inside them (linux/rhashtable.h, ours). The chains are changed and walked
+ * under the layer's lock; that a thing found stays there while it is used is the caller's
+ * business, as it is under Linux.
+ */
+static struct rhash_head **
+rht_chain(struct rhashtable *table, const void *key, unsigned length)
+{
+ uint32_t hash = 2166136261u;
+
+ for (unsigned i = 0; i < length; i++) {
+ hash = (hash ^ ((const uint8_t *)key)[i]) * 16777619u;
+ }
+ return (&table->chains[hash % nitems(table->chains)]);
+}
+
+int
+rhashtable_init(struct rhashtable *table, const struct rhashtable_params *params)
+{
+ bzero(table, sizeof(*table));
+ return (0);
+}
+
+void
+rhashtable_destroy(struct rhashtable *table)
+{
+}
+
+static void *
+rht_find(struct rhashtable *table, const void *key, const struct rhashtable_params *params)
+{
+ for (struct rhash_head *head = *rht_chain(table, key, params->key_len); head != NULL; head = head->next) {
+ uint8_t *thing = (uint8_t *)head - params->head_offset;
+
+ if (memcmp(thing + params->key_offset, key, params->key_len) == 0) {
+ return (thing);
+ }
+ }
+ return (NULL);
+}
+
+void *
+rhashtable_lookup_fast(struct rhashtable *table, const void *key, const struct rhashtable_params params)
+{
+ void *thing;
+
+ lx_os_lock();
+ thing = rht_find(table, key, &params);
+ lx_os_unlock();
+ return (thing);
+}
+
+void *
+rhashtable_lookup_get_insert_fast(struct rhashtable *table, struct rhash_head *head, const struct rhashtable_params params)
+{
+ const uint8_t *key = (uint8_t *)head - params.head_offset + params.key_offset;
+ struct rhash_head **chain;
+ void *there;
+
+ lx_os_lock();
+ there = rht_find(table, key, &params);
+ if (there == NULL) {
+ chain = rht_chain(table, key, params.key_len);
+ head->next = *chain;
+ *chain = head;
+ }
+ lx_os_unlock();
+ return (there);
+}
+
+int
+rhashtable_remove_fast(struct rhashtable *table, struct rhash_head *head, const struct rhashtable_params params)
+{
+ const uint8_t *key = (uint8_t *)head - params.head_offset + params.key_offset;
+ int error = -ENOENT;
+
+ lx_os_lock();
+ for (struct rhash_head **link = rht_chain(table, key, params.key_len); *link != NULL; link = &(*link)->next) {
+ if (*link == head) {
+ *link = head->next;
+ error = 0;
+ break;
+ }
+ }
+ lx_os_unlock();
+ return (error);
+}
+
void
arc4random_buf(void *buffer, size_t size)
{
diff --git a/wifi/lx/src/lx_bus.c b/wifi/lx/src/lx_bus.c
index f51d2a4..f8a91a3 100644
--- a/wifi/lx/src/lx_bus.c
+++ b/wifi/lx/src/lx_bus.c
@@ -9,18 +9,21 @@
* Where this stage ends: qmi.c has its exchange with the firmware, core.c starts the firmware
* in mission mode and has ce.c and hal.c set up the copy engines' rings, htc.c connects its
* services over them and wmi.c has the firmware say what the radio is ("service ready") and,
- * given the driver's configuration, that it is ready for commands ("unified ready"). What the
- * firmware said is then put in the log, and the driver is taken down again the way its own
- * removal does it (ath11k_core_deinit()): mac.c and the data path are not built.
+ * given the driver's configuration, that it is ready for commands ("unified ready"); mac.c
+ * registers the radio with what stands in for mac80211 (lx_80211.c). What the firmware said is
+ * then put in the log, with the boot-arg wifi_scan=1 the station of lx_80211.c has the radio
+ * scan, and the driver is taken down again the way its own removal does it
+ * (ath11k_core_deinit()). The data path is not built.
*
* The kernel's boot-arg wifi_lx says how far the radio's registers are touched: 1, not at all
* (every write is said and dropped, every read is 0: the driver's own exchange and nothing
* else); 2, for real.
*
* What the phone said, 13 October: all of that happens, 270 ms from the start of the bus to
- * "unified ready", with the copy engines looked at once a millisecond (bsd/dev/redwood_wifi.c,
- * step_driver(), has the account).
+ * "unified ready", with the copy engines looked at once a millisecond, and the scan hears the
+ * networks around (bsd/dev/redwood_wifi.c, step_driver(), has the account).
*/
+#define LX_QMI_AS_IT_IS /* (this file is where the driver's requests go past) */
#include <linux/kernel.h>
#include <linux/device.h>
#include <linux/io.h>
@@ -42,6 +45,7 @@
static struct {
unsigned how; /* wifi_lx */
+ bool mission; /* the firmware has been asked for mission mode, and for no other since */
bool closed; /* the driver has stopped the bus: the registers are not touched again */
unsigned reads, writes, said, refused;
u32 last, last_value; /* the register written last, and with what ... */
@@ -131,8 +135,7 @@ window(struct ath11k_base *ab, u32 offset)
if ((offset ^ HAL_SEQ_WCSS_UMAC_CE0_SRC_REG(ab)) < ATH11K_PCI_WINDOW_RANGE_MASK) {
return (2 * ATH11K_PCI_WINDOW_START + (offset & ATH11K_PCI_WINDOW_RANGE_MASK));
}
- printf("lx: the driver reaches for the chip's %#x, which no window shows\n", offset);
- return (0);
+ return (0); /* (refused() has kept such a one out) */
}
/*
@@ -142,13 +145,17 @@ window(struct ath11k_base *ab, u32 offset)
* "off", nothing is let through any more.
*/
static bool
-refused(u32 offset)
+refused(struct ath11k_base *ab, u32 offset)
{
- if (!bus.closed) {
+ bool known = offset < ATH11K_PCI_WINDOW_START || (offset ^ HAL_SEQ_WCSS_UMAC_OFFSET) < ATH11K_PCI_WINDOW_RANGE_MASK ||
+ (offset ^ HAL_SEQ_WCSS_UMAC_CE0_SRC_REG(ab)) < ATH11K_PCI_WINDOW_RANGE_MASK;
+
+ if (known && bus.mission && !bus.closed) {
return (false);
}
if (bus.refused++ < 8) {
- printf("lx: the chip's %#x is reached for after the bus was stopped: NOT DONE\n", offset);
+ printf("lx: the chip's %#x is reached for %s: NOT DONE\n", offset, !known ? "which no window shows" : bus.closed ?
+ "after the bus was stopped" : "while the firmware is not in mission mode");
}
return (true);
}
@@ -204,7 +211,7 @@ bus_read32(struct ath11k_base *ab, u32 offset)
{
u32 value = 0;
- if (refused(offset)) {
+ if (refused(ab, offset)) {
return (0);
}
bus.reads++;
@@ -223,7 +230,7 @@ bus_read32(struct ath11k_base *ab, u32 offset)
static void
bus_write32(struct ath11k_base *ab, u32 offset, u32 value)
{
- if (refused(offset)) {
+ if (refused(ab, offset)) {
return;
}
bus.writes++;
@@ -272,7 +279,32 @@ bus_quiet(void)
lx_pause_ms(1);
}
say_repeats();
- bus.closed = true;
+}
+
+/*
+ * A request of the driver's to the firmware, on its way out (linux/soc/qcom/qmi.h, ours). One
+ * matters here: the mode. With any mode but mission the radio's registers stop answering, and
+ * the driver does not always let go of the copy engines first -- where its start fails late,
+ * core.c asks for the mode "off" and stops the bus after that (ath11k_core_stop()). So the
+ * copy engines are let go of here, before the request leaves.
+ */
+int
+lx_qmi_send_request(struct qmi_handle *qmi, struct sockaddr_qrtr *sq, struct qmi_txn *txn, int msg_id, size_t largest,
+ const struct qmi_elem_info *ei, const void *structure)
+{
+ if (msg_id == QMI_WLANFW_WLAN_MODE_REQ_V01) {
+ u32 mode = ((const struct qmi_wlanfw_wlan_mode_req_msg_v01 *)structure)->mode;
+
+ if (mode != ATH11K_FIRMWARE_MODE_NORMAL && bus.looking) {
+ printf("lx: the driver asks for mode %u while the copy engines are still looked at: they are let go of first\n",
+ mode);
+ }
+ if (mode != ATH11K_FIRMWARE_MODE_NORMAL) {
+ bus_quiet();
+ }
+ bus.mission = mode == ATH11K_FIRMWARE_MODE_NORMAL;
+ }
+ return (qmi_send_request(qmi, sq, txn, msg_id, largest, ei, structure));
}
/* pcic.c: ath11k_pcic_start(), with the thread above where it enables the interrupts */
@@ -298,6 +330,7 @@ static void
bus_stop(struct ath11k_base *ab)
{
bus_quiet();
+ bus.closed = true;
timer_delete_sync(&ab->rx_replenish_retry);
ath11k_ce_cleanup_pipes(ab);
printf("lx: the driver stops the bus (%u reads and %u writes of the chip's registers in all, %u of the writes a ring's "
@@ -402,6 +435,17 @@ of_reserved_mem_region_to_resource(const struct device_node *np, unsigned int in
return (-ENODEV);
}
+/*
+ * The radio's own address, which the driver asks its device for before it falls back on what the
+ * firmware says (mac.c: ath11k_mac_register()); this radio's firmware says none. The kernel has
+ * it, if it was given one. Nothing here says the address.
+ */
+int
+linuxkpi_device_get_mac_address(struct device *dev, char *address)
+{
+ return (lx_os_radio_address((unsigned char *)address) ? 0 : -ENOENT);
+}
+
/* ---- what the firmware has said of the radio ------------------------------------------------------- */
/* After "unified ready": what wmi.c has kept of the firmware's two announcements. */
@@ -509,16 +553,10 @@ lx_start(void)
lx_pause_ms(1000); /* (for what the firmware says unasked once it is ready) */
say_radio(ab);
- /*
- * Down again, in the order of the driver's own removal (core.c: ath11k_core_deinit()), by
- * hand: that function first has every radio's interface told to suspend, and there is no
- * such interface until mac.c makes one.
- */
- bus_quiet();
- ath11k_qmi_firmware_stop(ab);
- bus_stop(ab);
- ath11k_wmi_detach(ab);
- ath11k_qmi_deinit_service(ab);
+ ret = lx_os_option("wifi_scan") ? lx_station_scan() : 0;
+
+ /* Down again, as the driver's removal does it (the copy engines are let go of on the way: bus_quiet()). */
+ ath11k_core_deinit(ab);
printf("lx: the driver is down again\n");
- return (0);
+ return (ret);
}
diff --git a/xl b/xl
index 6618f05..7d3cc81 100755
--- a/xl
+++ b/xl
@@ -106,7 +106,13 @@ run() { # run <oem command> <label>
*) [ -f "$rd" ] || { echo "xl: ramdisk $rd not found"; return 1; } ;;
esac
case $K in prebuilt/*) echo "xl: no kernel built here, running $K" >&2 ;; esac
- xnuloader/mkpayload.py -o run-payload.bin kernel=$K ${rd:+ramdisk=$rd} --cmdline "loader_return_after=${XL_SECS:-8} epoch=$(date +%s) sb_delay=${XL_SB_DELAY:-8} ${XL_CMDLINE--v}" >/dev/null || return 1
+ # A run about Wi-Fi is given the radio's own address, which is this phone's and so is kept in a
+ # file that is not in the repository: fw-wifi/mac, one line, six bytes in hexadecimal with colons.
+ local args=${XL_CMDLINE--v}
+ case " $args " in
+ *" wifi="*) [ -s fw-wifi/mac ] && args="$args wifi_mac=$(tr -d ' \n\r' < fw-wifi/mac)" ;;
+ esac
+ xnuloader/mkpayload.py -o run-payload.bin kernel=$K ${rd:+ramdisk=$rd} --cmdline "loader_return_after=${XL_SECS:-8} epoch=$(date +%s) sb_delay=${XL_SB_DELAY:-8} $args" >/dev/null || return 1
FB_TIMEOUT=30 fb stage run-payload.bin | grep -q OKAY || { echo "xl: upload failed"; return 1; }
fi
local live=; live_loader && live=1