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 in an ordinary session: wifi=1

vcvkkf9f73335e9ad
diff --git a/.gitignore b/.gitignore
index 6cf715d..f349cc9 100644
--- a/.gitignore
+++ b/.gitignore
@@ -42,7 +42,7 @@ __pycache__/
!/userland/build.sh
!/userland/*.py
!/userland/rc.*
-!/userland/com.redwood.demo.plist
+!/userland/com.redwood.*.plist
!/userland/src/
!/userland/libmini/
!/userland/var/
diff --git a/README.md b/README.md
index e4cd1fa..0545e22 100644
--- a/README.md
+++ b/README.md
@@ -91,14 +91,18 @@ qemu/run-ios.sh 1200 -display gtk > logs/qemu.log # сеанс на 20 ми
ходить на серверы Apple (в первые минуты около 30 МБ данных Карт), а приложения Apple — Погода, App Store,
Подкасты — данных всё равно не получают: им нужна служба `fairplayd`, которой в образе нет. В Настройках
Wi-Fi остаётся «Выкл.» (это не Wi-Fi). По умолчанию сети нет, и без `QEMU_NET=1` ничего не меняется.
-- **Сеть по Wi-Fi телефона (опытно).** Радио телефона подключается к одной сети WPA2 с паролем, и iOS выходит
- через него в интернет: адрес по DHCP, DNS, HTTPS. Нужны прошивка радио в `fw-wifi/` (см. `wifi=N` в таблице
- параметров ядра), адрес радио одной строкой в `fw-wifi/mac` и файл `fw-wifi/network` — имя сети первой строкой,
- пароль второй (оба файла в git не попадают; `userland/build.sh` кладёт второй в малый образ, на командную
- строку ядра он не идёт, в журнал пишутся только длины). Затем `tools/mk-ath11k.sh`, `./xnu-build.sh`,
- `REST=1 userland/build.sh` и запуск с
- `XL_CMDLINE="-v bootcpu=7 wifi=15 wifi_lx=2 wifi_smmu=2 wifi_join=1 wifi_keep=1" ./xl run`. Интерфейс тот же
- `en0`, настроить его нужно так же, как в QEMU (`RC_JOBS=rc.jobs.net` это делает при загрузке). Чего нет:
+- **Wi-Fi телефона (опытно): `wifi=1`.** Радио телефона подключается к одной сети WPA2 с паролем, и iOS выходит
+ через него в интернет: адрес по DHCP, DNS, HTTPS. Нужны прошивка радио в `fw-wifi/` (см. `wifi_step=N` в
+ таблице параметров ядра), адрес радио одной строкой в `fw-wifi/mac` и файл `fw-wifi/network` — имя сети первой
+ строкой, пароль второй (оба файла в git не попадают; `userland/build.sh` кладёт второй в малый образ, на
+ командную строку ядра он не идёт, в журнал пишутся только длины). Затем `tools/mk-ath11k.sh`, `./xnu-build.sh`,
+ `GL=1 REST=1 userland/build.sh`, и к обычной командной строке сеанса добавляется одно слово:
+ `XL_CMDLINE="touchscreen=1 cpufreq=1 bootcpu=7 cpus=4 gpu=1 wifi=1" ./xl run`. Радио поднимается рядом с
+ загрузкой системы и её не задерживает (сеть есть через 12 секунд после старта ядра), интерфейс — тот же `en0`;
+ настроить его просит configd задание `com.redwood.wifi`, которое есть в каждом образе и без `wifi=1` ничего не
+ делает. Без прошивки или без файла сети ядро говорит об этом одной строкой и идёт дальше. В Safari при наборе в
+ строке поиска появляются подсказки поисковика — они приходят уже по этой сети; сами страницы Safari открывает
+ (замок и имя сайта в адресной строке), но не рисует: поле страницы остаётся чёрным, с GPU и без него. Чего нет:
выбора сети и пароля в Настройках (там Wi-Fi по-прежнему «Выкл.»), WPA3, открытых сетей, каналов шире 20 МГц,
экономии энергии; скорость — около 15 Мбит/с.
- Несколько QEMU сразу: `QEMU_INSTANCE=1 qemu/run-ios.sh …` (у каждого номера свои порты; `touch.py`,
@@ -173,7 +177,8 @@ 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»); собственного адреса у прошивки нет (нули). Прерываний при этом нет: кольца опрашиваются раз в миллисекунду. С `wifi_scan=1` драйвер после этого регистрирует радио, заводит интерфейс в режиме станции и просит прошивку просканировать эфир — только слушая, в эфир ничего не уходит: 26 каналов 2,4 и 5 ГГц за четыре секунды, и в журнале появляются точки доступа вокруг с каналами и уровнем сигнала (имена и адреса чужих сетей — только в журнале запуска на вашей машине). Адрес радио у прошивки свой не записан: он лежит одной строкой в `fw-wifi/mac` (в git не попадает), и `xl run` передаёт его ядру параметром `wifi_mac`. С `wifi_join=1` драйвер подключается к сети из `fw-wifi/network` (WPA2 с паролем): находит её точку доступа, проходит аутентификацию, ассоциацию и четырёхстороннее рукопожатие, отдаёт ключи прошивке и становится тем, что стоит за `en0`; с `wifi_keep=1` он остаётся работать, пока идёт сеанс, без него — сворачивается, когда шаги кончились (`wifi_hold=S` — на S секунд позже). Остановленный без спроса (ядро, которое до этого не дошло) второй раз без перезагрузки телефона не запускается — такой запуск сбрасывал телефон, и драйвер от него сам отказывается; шаги и остальные параметры описаны в начале `bsd/dev/redwood_wifi.c` |
+| `wifi=1` | Wi-Fi телефона, всё сразу (см. «Wi-Fi телефона» выше): процессор радио, драйвер, подключение к сети из `fw-wifi/network`, и так до конца сеанса; рядом с загрузкой системы, в журнале — только итог (`wifi_loud=1` — со всеми подробностями шагов) |
+| `wifi_step=N` | то же по шагам, как это выяснялось: первые 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`. С `wifi_join=1` драйвер подключается к сети из `fw-wifi/network` (WPA2 с паролем): находит её точку доступа, проходит аутентификацию, ассоциацию и четырёхстороннее рукопожатие, отдаёт ключи прошивке и становится тем, что стоит за `en0`; с `wifi_keep=1` он остаётся работать, пока идёт сеанс, без него — сворачивается, когда шаги кончились (`wifi_hold=S` — на S секунд позже). Остановленный без спроса (ядро, которое до этого не дошло) второй раз без перезагрузки телефона не запускается — такой запуск сбрасывал телефон, и драйвер от него сам отказывается; шаги и остальные параметры описаны в начале `bsd/dev/redwood_wifi.c` |
Несколько ядер на телефоне проверены (2, 4 и 7 ядер запускаются и чисто возвращаются в загрузчик). Лучший
вариант — **`cpus=4`**: четыре больших ядра (7, 6, 5, 4). На одном и том же сценарии: 929 кадров вместо 671,
diff --git a/tools/mk-ath11k.sh b/tools/mk-ath11k.sh
index e087acd..f06a33b 100755
--- a/tools/mk-ath11k.sh
+++ b/tools/mk-ath11k.sh
@@ -177,8 +177,8 @@ for s in $(cat out/undefined.txt); do
done
[ -z "$missing" ] || exit 1
$CC -c out/stubs.s -o out/stubs.o
-# three names are shown: where the kernel enters (lx_start(), lx_stop() and lx_transmit() of redwood_lx.h)
-printf '_lx_start\n_lx_stop\n_lx_transmit\n' > out/exported.txt
+# four names are shown: where the kernel enters (lx_prepare(), lx_start(), lx_stop() and lx_transmit() of redwood_lx.h)
+printf '_lx_prepare\n_lx_start\n_lx_stop\n_lx_transmit\n' > out/exported.txt
$LD -r -arch arm64 -exported_symbols_list out/exported.txt out/all.o out/stubs.o -o out/ath11k.o 2> out/ld.err ||
{ cat out/ld.err; exit 1; }
rm -f out/all.o
diff --git a/userland/build.sh b/userland/build.sh
index 7e9794a..80cbb11 100755
--- a/userland/build.sh
+++ b/userland/build.sh
@@ -156,7 +156,7 @@ if [ -d $IOS/rootfs/usr/lib ]; then
cp ${RC:-rc.launchd} root/etc/rc
cp ${RC_JOBS:-rc.jobs} root/etc/rc.jobs
# the jobs the iOS launchd will see (/System/Library/LaunchDaemons is a symlink to this directory)
- cp com.redwood.demo.plist root/LaunchDaemons/
+ cp com.redwood.demo.plist com.redwood.wifi.plist root/LaunchDaemons/
[ -n "$IOS_JOBS" ] && OSLOG=${OSLOG-com.apple.backboardd} ./mkjobs.py ${REST:+--rest} $IOS/rootfs root/LaunchDaemons $IOS_JOBS
fi
# firmware of the phone's own hardware, where somebody has pulled it from the phone's Android into ../fw-gpu
diff --git a/userland/com.redwood.wifi.plist b/userland/com.redwood.wifi.plist
new file mode 100644
index 0000000..ae1b6a4
--- /dev/null
+++ b/userland/com.redwood.wifi.plist
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>Label</key>
+ <string>com.redwood.wifi</string>
+ <!-- with wifi=1 among the kernel's arguments: has configd configure the radio's interface (src/net_test.m,
+ "wifi"); without, it ends at once -->
+ <key>ProgramArguments</key>
+ <array>
+ <string>/redwood/bin/net_test</string>
+ <string>wifi</string>
+ </array>
+ <key>RunAtLoad</key>
+ <true/>
+ <key>StandardOutPath</key>
+ <string>/dev/console</string>
+ <key>StandardErrorPath</key>
+ <string>/dev/console</string>
+</dict>
+</plist>
diff --git a/userland/src/net_test.m b/userland/src/net_test.m
index 8aa506e..f730d01 100644
--- a/userland/src/net_test.m
+++ b/userland/src/net_test.m
@@ -15,6 +15,9 @@
* system's trust store and trustd as well
* reach NAME what SCNetworkReachability says: the question applications ask first
* wait SECONDS
+ * wifi what the job com.redwood.wifi runs in every image: if the kernel was
+ * started with wifi=1, wait for the radio's interface (en0) to appear
+ * and ask for it to be configured by DHCP ("dhcp en0"); else nothing
*
* The interface (en0, bsd/dev/redwood_net.c) has no IOKit object behind it, and configd makes
* its network services out of those. But the plugin that does the configuring keeps its own list
@@ -32,6 +35,7 @@
#include <arpa/inet.h>
#include <ifaddrs.h>
#include <mach/mach.h>
+#include <sys/sysctl.h>
#include <mach/mach_time.h>
#include <net/if.h>
#include <net/if_dl.h>
@@ -336,6 +340,40 @@ reach(const char *name)
}
}
+/*
+ * The radio's interface is made by the kernel when its driver is up, a quarter of a minute into
+ * the system's start, and nothing in iOS configures an interface that has no IOKit object: with
+ * wifi=1 among the kernel's arguments this waits for en0 and makes the one call that does. From
+ * then on configd's own machinery has it: DHCP when the link comes up, again when it comes back.
+ */
+static void
+wifi(void)
+{
+ char arguments[1024] = "";
+ size_t size = sizeof(arguments) - 1;
+ double start = seconds();
+ bool wanted = false, there = false;
+
+ if (sysctlbyname("kern.bootargs", arguments, &size, NULL, 0) != 0) {
+ return;
+ }
+ for (const char *word = strtok(arguments, " "); word != NULL; word = strtok(NULL, " ")) {
+ wanted |= strcmp(word, "wifi=1") == 0;
+ }
+ if (!wanted) {
+ return;
+ }
+ while (!(there = if_nametoindex("en0") != 0) && seconds() - start < 120) {
+ usleep(500000);
+ }
+ if (!there) {
+ printf("net_test: wifi: no en0 after %.0f s: the radio has not come up\n", seconds() - start);
+ return;
+ }
+ printf("net_test: wifi: en0 is there after %.1f s\n", seconds() - start);
+ dhcp("en0");
+}
+
int
main(int argc, char **argv)
{
@@ -371,6 +409,8 @@ main(int argc, char **argv)
reach(argv[++i]);
} else if (strcmp(step, "wait") == 0 && i + 1 < argc) {
usleep((useconds_t)(atof(argv[++i]) * 1e6));
+ } else if (strcmp(step, "wifi") == 0) {
+ wifi();
} else {
fprintf(stderr, "net_test: bad step \"%s\"\n", step);
return 1;
diff --git a/wifi/lx/src/lx.h b/wifi/lx/src/lx.h
index bc52286..87f22e6 100644
--- a/wifi/lx/src/lx.h
+++ b/wifi/lx/src/lx.h
@@ -5,6 +5,8 @@
int lx_base_init(void); /* lx_base.c: the thread that counts the ticks and runs the timers */
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_tell(const char *format, ...) __printflike(1, 2); /* lx_base.c: a line that is always said (printf: may be kept back) */
+void lx_memory_say(void); /* lx_base.c: what the layer holds of memory */
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 */
diff --git a/wifi/lx/src/lx_80211.c b/wifi/lx/src/lx_80211.c
index c8213a1..ecef462 100644
--- a/wifi/lx/src/lx_80211.c
+++ b/wifi/lx/src/lx_80211.c
@@ -105,7 +105,8 @@ struct lx_radio {
struct work_struct group_work; /* a new group key, later on */
struct ieee80211_key_conf *pairwise_key, *group_key;
volatile bool joined; /* keys set: frames pass */
- unsigned sent, sent_lost, received, received_group, eapol;
+ unsigned sent, sent_lost, received, received_group, eapol, rekeys;
+ unsigned long long joined_at; /* nanoseconds */
};
static struct lx_radio *the_radio;
@@ -821,7 +822,7 @@ management_received(struct lx_radio *radio, const uint8_t *f, unsigned length)
} else if (f[0] == 0xc0 || f[0] == 0xa0) { /* the access point shows us the door: with a reason */
status = f[24] | f[25] << 8;
answer = ANSWER_GONE;
- printf("lx: THE ACCESS POINT %s US, reason %u\n", f[0] == 0xc0 ? "DEAUTHENTICATES" : "DISASSOCIATES", status);
+ lx_tell("lx: THE ACCESS POINT %s US, reason %u\n", f[0] == 0xc0 ? "DEAUTHENTICATES" : "DISASSOCIATES", status);
if (radio->joined) {
radio->joined = false;
lx_os_net_link(0);
@@ -877,7 +878,7 @@ station_up(struct lx_radio *radio)
return (0);
}
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");
+ lx_tell("lx: THE RADIO HAS NO ADDRESS (the kernel was given none, and the firmware has none): no interface is made\n");
return (EADDRNOTAVAIL);
}
radio->vif_memory = kzalloc(64 + sizeof(*vif) + hw->vif_data_size, GFP_KERNEL);
@@ -1275,8 +1276,9 @@ group_rekey(struct work_struct *work)
struct ieee80211_key_conf *old = radio->group_key;
int error = 0;
+ radio->rekeys++;
radio->group_key = key_set(radio, radio->wpa.group, radio->wpa.group_index, false, &error);
- printf("lx: the group's new key (number %u) is given to the driver: %d\n", radio->wpa.group_index, error);
+ lx_tell("lx: the group's new key (number %u) is given to the driver: %d\n", radio->wpa.group_index, error);
key_drop(radio, &old, false);
}
@@ -1387,7 +1389,7 @@ station_join(struct lx_radio *radio, const uint8_t *name, unsigned name_length,
station_scan(radio, name, name_length);
}
if (!target->found) {
- printf("lx: THE NETWORK THAT IS WANTED WAS NOT HEARD (a name of %u bytes), in three scans\n", name_length);
+ lx_tell("lx: THE NETWORK THAT IS WANTED WAS NOT HEARD (a name of %u bytes), in three scans\n", name_length);
return (ENOENT);
}
channel = linuxkpi_ieee80211_get_channel(hw->wiphy, target->frequency);
@@ -1397,7 +1399,7 @@ station_join(struct lx_radio *radio, const uint8_t *name, unsigned name_length,
channel = linuxkpi_ieee80211_get_channel(hw->wiphy, linuxkpi_ieee80211_channel_to_frequency(e[2], channel->band));
}
obstacle = protection(target, &group_cipher);
- printf("lx: the network that is wanted: an access point on channel %u (%u MHz) at %d dBm, capabilities %#x, beacons every "
+ lx_tell("lx: the network that is wanted: an access point on channel %u (%u MHz) at %d dBm, capabilities %#x, beacons every "
"%u units; HT %s, VHT %s, WMM %s; %s%s\n", channel != NULL ? channel_of(channel->center_freq) : 0, channel != NULL ?
channel->center_freq : 0, target->signal, target->capability, target->interval, element(target->elements,
target->elements_length, 45) ? "yes" : "no", element(target->elements, target->elements_length, 191) ? "yes" : "no",
@@ -1484,7 +1486,7 @@ station_join(struct lx_radio *radio, const uint8_t *name, unsigned name_length,
frame_send(radio, skb);
answer = answer_wait(radio, 500);
}
- printf("lx: AUTHENTICATION: %s (status %u)\n", answer == ANSWER_AUTHENTICATED ? "the access point accepts" : answer ==
+ lx_tell("lx: AUTHENTICATION: %s (status %u)\n", answer == ANSWER_AUTHENTICATED ? "the access point accepts" : answer ==
ANSWER_NONE ? "NO ANSWER from the access point to three requests" : "THE ACCESS POINT REFUSES", radio->answer_status);
if (answer != ANSWER_AUTHENTICATED || (ret = station_state(radio, IEEE80211_STA_NONE, IEEE80211_STA_AUTH)) != 0) {
error = answer == ANSWER_NONE ? ETIMEDOUT : ECONNREFUSED;
@@ -1510,7 +1512,7 @@ station_join(struct lx_radio *radio, const uint8_t *name, unsigned name_length,
frame_send(radio, skb);
answer = answer_wait(radio, 500);
}
- printf("lx: ASSOCIATION: %s (status %u); we are its station number %u; its answer has %u bytes of elements\n", answer ==
+ lx_tell("lx: ASSOCIATION: %s (status %u); we are its station number %u; its answer has %u bytes of elements\n", answer ==
ANSWER_ASSOCIATED ? "THE ACCESS POINT ACCEPTS" : answer == ANSWER_NONE ? "NO ANSWER from the access point to three "
"requests" : "THE ACCESS POINT REFUSES", radio->answer_status, radio->aid, radio->answer_length);
if (answer != ANSWER_ASSOCIATED) {
@@ -1556,7 +1558,7 @@ station_join(struct lx_radio *radio, const uint8_t *name, unsigned name_length,
}
lx_os_unlock();
if (radio->handshake != LX_WPA_KEYS) {
- printf("lx: THE HANDSHAKE DID NOT COME THROUGH in %llu ms: %s%s (%u of its messages came)\n", (lx_os_nanoseconds() - began) /
+ lx_tell("lx: THE HANDSHAKE DID NOT COME THROUGH in %llu ms: %s%s (%u of its messages came)\n", (lx_os_nanoseconds() - began) /
1000000ull, radio->answer == ANSWER_GONE ? "the access point has shown us the door (a wrong passphrase gives this)" :
radio->handshake == LX_WPA_BAD ? "a message was not good: " : radio->handshake == LX_WPA_ANSWER ? "our message 2 was "
"not answered (a wrong passphrase gives this)" : "the access point did not begin it", radio->handshake == LX_WPA_BAD ?
@@ -1569,7 +1571,7 @@ station_join(struct lx_radio *radio, const uint8_t *name, unsigned name_length,
if (ret == 0) {
radio->group_key = key_set(radio, radio->wpa.group, radio->wpa.group_index, false, &ret);
}
- printf("lx: THE KEYS ARE GIVEN TO THE DRIVER, %llu ms after the association: ours with the access point, and the group's "
+ lx_tell("lx: THE KEYS ARE GIVEN TO THE DRIVER, %llu ms after the association: ours with the access point, and the group's "
"(number %u, %u bytes): %d\n", (lx_os_nanoseconds() - began) / 1000000ull, radio->wpa.group_index,
radio->wpa.group_length, ret);
if (ret != 0 || (ret = station_state(radio, IEEE80211_STA_ASSOC, IEEE80211_STA_AUTHORIZED)) != 0) {
@@ -1577,10 +1579,11 @@ station_join(struct lx_radio *radio, const uint8_t *name, unsigned name_length,
goto out;
}
state = IEEE80211_STA_AUTHORIZED;
- radio->sent = radio->sent_lost = radio->received = radio->received_group = 0;
+ radio->sent = radio->sent_lost = radio->received = radio->received_group = radio->rekeys = 0;
+ radio->joined_at = lx_os_nanoseconds();
radio->joined = true;
lx_os_net_link(1);
- printf("lx: THE NETWORK IS JOINED: frames can pass\n");
+ lx_tell("lx: THE NETWORK IS JOINED: frames can pass\n");
return (0);
out:
station_leave(radio, state);
@@ -1599,7 +1602,7 @@ lx_station_join(void)
int error;
if (radio == NULL || !radio->registered) {
- printf("lx: no radio is registered: nothing to join with\n");
+ lx_tell("lx: no radio is registered: nothing to join with\n");
return (ENXIO);
}
if (!lx_os_network(name, &name_length, passphrase, &passphrase_length)) {
@@ -1618,9 +1621,10 @@ lx_station_say(void)
struct lx_radio *radio = the_radio;
if (radio != NULL) {
- printf("lx: the network is %s: %u frames sent (%u could not be), %u received for us and %u sent to everybody; %u "
- "messages of the handshake\n", radio->joined ? "joined" : "NOT joined", radio->sent, radio->sent_lost, radio->received,
- radio->received_group, radio->eapol);
+ lx_tell("lx: the network is %s, %llu s after it was joined: %u frames sent (%u could not be), %u received for us and "
+ "%u sent to everybody; %u messages of the handshake, the group's key changed %u times\n", radio->joined ? "joined" :
+ "NOT joined", radio->joined_at != 0 ? (lx_os_nanoseconds() - radio->joined_at) / 1000000000ull : 0, radio->sent,
+ radio->sent_lost, radio->received, radio->received_group, radio->eapol, radio->rekeys);
}
}
@@ -1636,7 +1640,7 @@ lx_station_leave(void)
lx_station_say();
if (radio->sta != NULL) {
station_leave(radio, radio->joined ? IEEE80211_STA_AUTHORIZED : IEEE80211_STA_ASSOC);
- printf("lx: the network is left\n");
+ lx_tell("lx: the network is left\n");
}
station_down(radio);
}
diff --git a/wifi/lx/src/lx_base.c b/wifi/lx/src/lx_base.c
index fe4422c..df4daee 100644
--- a/wifi/lx/src/lx_base.c
+++ b/wifi/lx/src/lx_base.c
@@ -60,6 +60,19 @@ printf(const char *format, ...)
return (0);
}
+/* A line that is said whatever the kernel does with the others (lx_os_tell()): outcomes, and what has gone wrong. */
+void
+lx_tell(const char *format, ...)
+{
+ char line[400];
+ va_list list;
+
+ va_start(list, format);
+ vsnprintf(line, sizeof(line), format, list);
+ va_end(list);
+ lx_os_tell(line);
+}
+
/* A function of a part of the driver that is not built yet (out/stubs.s): its name, a few times; the answer is 0. */
long
lx_stub(const char *name)
@@ -189,20 +202,31 @@ local_bh_enable(void)
{
}
-/* (What Linux guards with RCU is guarded here by the locks around it, or was never shared.) */
+/*
+ * RCU, as far as the driver needs it: readers say when they begin and end to look at something
+ * shared, and whoever is about to free such a thing waits until nobody is looking any more
+ * (which is more than Linux asks: it waits only for those who were looking already).
+ */
+static volatile int rcu_readers;
+
void
-linux_synchronize_rcu(unsigned type)
+linux_rcu_read_lock(unsigned type)
{
+ __sync_fetch_and_add(&rcu_readers, 1);
}
void
-linux_rcu_read_lock(unsigned type)
+linux_rcu_read_unlock(unsigned type)
{
+ __sync_fetch_and_sub(&rcu_readers, 1);
}
void
-linux_rcu_read_unlock(unsigned type)
+linux_synchronize_rcu(unsigned type)
{
+ for (unsigned ms = 0; rcu_readers != 0 && ms < 1000; ms++) {
+ lx_pause_ms(1);
+ }
}
/* A thousand ticks a second, counted by a thread that also runs the timers that have come due. */
@@ -683,6 +707,8 @@ linux_work_fn(void *context, int pending)
/* ---- memory ------------------------------------------------------------------------------------- */
/* kmalloc(): the size goes in front, because kfree() is not told it. */
+static volatile long allocations, allocated; /* pieces out now, and their bytes: for lx_memory_say() */
+
void *
lkpi_kmalloc(size_t size, gfp_t flags)
{
@@ -692,6 +718,8 @@ lkpi_kmalloc(size_t size, gfp_t flags)
return (NULL);
}
block[0] = size + 16;
+ __sync_fetch_and_add(&allocations, 1);
+ __sync_fetch_and_add(&allocated, (long)(size + 16));
return (block + 2);
}
@@ -701,6 +729,8 @@ lkpi_kfree(const void *memory)
size_t *block = (size_t *)(uintptr_t)memory - 2;
if (memory != NULL) {
+ __sync_fetch_and_sub(&allocations, 1);
+ __sync_fetch_and_sub(&allocated, (long)block[0]);
lx_os_free(block, block[0]);
}
}
@@ -740,6 +770,9 @@ static struct {
int
lx_pool_init(void)
{
+ if (pool.memory != NULL) {
+ return (0);
+ }
pool.memory = lx_os_radio_memory(POOL_SIZE, &pool.address);
if (pool.memory == NULL) {
return (ENOMEM);
@@ -1181,8 +1214,22 @@ linux_dmi_first_match(const struct dmi_system_id *list)
return (NULL); /* (no table of the machine's maker here) */
}
+/* What the layer holds of the kernel's memory right now: a number that keeps growing is a leak. */
+void
+lx_memory_say(void)
+{
+ lx_tell("lx: memory: %ld pieces of the kernel's out, %ld KB; of the radio's %u MB: %u KB of rings, %u of %u buffers out\n",
+ allocations, allocated >> 10, POOL_SIZE >> 20, pool.rings_used >> 10, POOL_SLOTS - pool.free_count, POOL_SLOTS);
+}
+
int
lx_base_init(void)
{
+ static bool begun;
+
+ if (begun) {
+ return (0);
+ }
+ begun = true;
return (lx_os_thread("wifi-ticks", ticker, NULL));
}
diff --git a/wifi/lx/src/lx_bus.c b/wifi/lx/src/lx_bus.c
index 55275c0..66ed904 100644
--- a/wifi/lx/src/lx_bus.c
+++ b/wifi/lx/src/lx_bus.c
@@ -81,13 +81,23 @@ ath11k_info(struct ath11k_base *ab, const char *format, ...)
va_end(list);
}
+/* (the driver's warnings and errors are said whatever happens to the rest) */
+static void
+driver_complains(const char *kind, const char *format, va_list list)
+{
+ char line[320];
+
+ vsnprintf(line, sizeof(line), format, list);
+ lx_tell("ath11k %s: %s%s", kind, line, line[0] != 0 && line[strlen(line) - 1] == '\n' ? "" : "\n");
+}
+
void
ath11k_warn(struct ath11k_base *ab, const char *format, ...)
{
va_list list;
va_start(list, format);
- driver_says(" WARNS", format, list);
+ driver_complains("WARNS", format, list);
va_end(list);
}
@@ -97,7 +107,7 @@ ath11k_err(struct ath11k_base *ab, const char *format, ...)
va_list list;
va_start(list, format);
- driver_says(" ERROR", format, list);
+ driver_complains("ERROR", format, list);
va_end(list);
}
@@ -155,7 +165,7 @@ refused(struct ath11k_base *ab, u32 offset)
return (false);
}
if (bus.refused++ < 8) {
- printf("lx: the chip's %#x is reached for %s: NOT DONE\n", offset, !known ? "which no window shows" : bus.closed ?
+ lx_tell("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);
@@ -261,11 +271,18 @@ static void
bus_looks(void *argument)
{
struct ath11k_base *ab = argument;
+ unsigned long long said = lx_os_nanoseconds();
bus.looks = true;
while (bus.looking) {
bool more = false;
+ if (lx_os_nanoseconds() - said > 300000000000ull) { /* every five minutes: how the station and memory stand */
+ said = lx_os_nanoseconds();
+ lx_station_say();
+ lx_memory_say();
+ }
+
for (unsigned i = 0; i < ab->hw_params.ce_count; i++) {
ath11k_ce_per_engine_service(ab, i);
}
@@ -318,6 +335,7 @@ lx_qmi_send_request(struct qmi_handle *qmi, struct sockaddr_qrtr *sq, struct qmi
bus_quiet();
}
bus.mission = mode == ATH11K_FIRMWARE_MODE_NORMAL;
+ lx_tell("lx: the firmware is asked for mode %u (0: mission, 4: off, 7: calibration)\n", mode);
}
return (qmi_send_request(qmi, sq, txn, msg_id, largest, ei, structure));
}
@@ -332,6 +350,7 @@ bus_start(struct ath11k_base *ab)
ab->qmi.ce_cfg.shadow_reg_v2_len);
ath11k_ce_rx_post_buf(ab);
say_repeats();
+ lx_tell("lx: the rings are set up and the copy engines have their buffers: the bus is started\n");
bus.looking = true;
if (lx_os_thread("wifi-rings", bus_looks, ab) != 0) {
bus.looking = false;
@@ -503,11 +522,17 @@ lx_start(void)
int ret;
bus.how = lx_os_option("wifi_lx");
- if (lx_base_init() != 0 || lx_pool_init() != 0) {
- printf("lx: no thread, or no memory the radio can be given\n");
+ if (lx_prepare() != 0) {
+ lx_tell("lx: no thread, or no memory the radio can be given\n");
return (ENOMEM);
}
- ath11k_debug_mask = ATH11K_DBG_QMI | ATH11K_DBG_BOOT | ATH11K_DBG_AHB | ATH11K_DBG_WMI | ATH11K_DBG_REG | ATH11K_DBG_MAC;
+ /* what the driver has to say while it is being looked into; not in a session that just uses the radio */
+ if (lx_os_option("wifi_quiet")) {
+ ath11k_debug_mask = 0;
+ bus.said = SAID_FIRST;
+ } else {
+ ath11k_debug_mask = ATH11K_DBG_QMI | ATH11K_DBG_BOOT | ATH11K_DBG_AHB | ATH11K_DBG_WMI | ATH11K_DBG_REG | ATH11K_DBG_MAC;
+ }
/*
* The driver's parameter "frame_mode": Ethernet. The firmware then puts frames into 802.11
* and takes them out of it, and ciphers them: what passes between the driver and the layer
@@ -526,7 +551,7 @@ lx_start(void)
ab->hw_rev = ATH11K_HW_WCN6750_HW10;
ab->fw_mode = ATH11K_FIRMWARE_MODE_NORMAL;
if ((ret = ath11k_core_pre_init(ab)) != 0 || (ret = ath11k_hal_srng_init(ab)) != 0 || (ret = ath11k_ce_alloc_pipes(ab)) != 0) {
- printf("lx: the driver does not get as far as its exchange with the firmware: %d\n", ret);
+ lx_tell("lx: the driver does not get as far as its exchange with the firmware: %d\n", ret);
return (-ret);
}
ab->qmi.ce_cfg.tgt_ce_len = ab->hw_params.target_ce_count;
@@ -537,7 +562,7 @@ lx_start(void)
printf("lx: the driver (\"%s\") is set up; its exchange with the firmware begins (registers: %s)\n", ab->hw_params.name,
bus.how >= 2 ? "for real" : "NOT TOUCHED, wifi_lx=1");
if ((ret = ath11k_core_init(ab)) != 0) {
- printf("lx: the driver's start fails: %d\n", ret);
+ lx_tell("lx: the driver's start fails: %d\n", ret);
return (-ret);
}
@@ -552,7 +577,7 @@ lx_start(void)
lx_pause_ms(10);
}
up = test_bit(ATH11K_FLAG_REGISTERED, &ab->dev_flags) && bus.looks;
- printf("lx: %llu ms after its start the driver %s; its flags: %#lx\n", (lx_os_nanoseconds() - began) / 1000000ull,
+ lx_tell("lx: %llu ms after its start the driver %s; its flags: %#lx\n", (lx_os_nanoseconds() - began) / 1000000ull,
up ? "IS UP as far as it is built: the firmware has said \"unified ready\"" : test_bit(ATH11K_FLAG_REGISTERED,
&ab->dev_flags) ? "HAS GIVEN UP on the way and wound itself down" : "HAS NOT GOT THROUGH its exchange with the firmware",
ab->dev_flags);
@@ -580,6 +605,13 @@ lx_start(void)
return (ret);
}
+/* The thread that counts the ticks, and the memory the radio is shown: once. 0, or an errno. */
+int
+lx_prepare(void)
+{
+ return (lx_base_init() != 0 || lx_pool_init() != 0 ? ENOMEM : 0);
+}
+
/* The network left, and the driver down as its own removal does it (the copy engines are let go of on the way: bus_quiet()). */
void
lx_stop(void)
@@ -592,7 +624,7 @@ lx_stop(void)
driver = NULL;
lx_station_leave();
ath11k_core_deinit(ab);
- printf("lx: the driver is down again\n");
+ lx_tell("lx: the driver is down again\n");
}
int
diff --git a/xl b/xl
index 7d3cc81..d978ea2 100755
--- a/xl
+++ b/xl
@@ -110,7 +110,7 @@ run() { # run <oem command> <label>
# 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)" ;;
+ *" wifi="*|*" wifi_step="*) [ -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; }