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
2.0: the IPA data path for this processor and en1 on it -- GSI rings and the AP endpoints (hakios.ipa.c), the IPA's tables by immediate commands before the modem, an Ethernet-looking interface with ARP and DHCP answered in the kernel (hakios.cell.c), two units in hakios.net.c; WDA data format and WDS mux binding before the session; the SMMU map covers all of DDR; a detected USIM is provisioned too; the status bar's setters called as blocks, the operator's name set; docs
shimoku7444b1583a40c6
diff --git a/README.md b/README.mdindex 3a147e6..54d8cc4 100644--- a/README.md+++ b/README.md@@ -41,7 +41,7 @@ Not in the repository, never:| Works | Not yet ||---|---|-| Lock screen, home screen, Control Center, gestures, the stock apps | Cellular: the modem boots, sees the network, the SIM is bound; registration and the status bar bars are in progress (`docs/cellular.md`) |+| Lock screen, home screen, Control Center, gestures, the stock apps | Cellular: the modem boots, sees the network, the SIM is bound, the IPA data path and `en1` are in place; registration, the data session and the status bar bars are in progress (`docs/cellular.md`) || Touch screen, multitouch, power and volume buttons | Bluetooth || All 8 CPU cores, the big core at 2.4 GHz | Charging under this kernel || GPU rendering on Adreno (`gpu=1`, OpenGL ES through Mesa) | Metal (there is a shader compiler, no Metal) |@@ -125,7 +125,7 @@ module, or the open lzfse library gets built). User space and the images: `REST=| Directory | Contents ||---|---|| `xnu/` | the kernel patch and files; `apply.sh`, `export.sh`; a README about the kernel |-| `xnu/files/bsd/dev/hakios_*.c` | my drivers: display, touch, UFS, GPU, Wi-Fi, audio, modem (`hakios.mpss.c`), SIM/NAS, haptics, cameras |+| `xnu/files/bsd/dev/hakios.*.c` | my drivers: display, touch, UFS, GPU, Wi-Fi, audio, modem (`hakios.mpss.c`), its packets (`hakios.ipa.c`, `hakios.cell.c`), SIM/NAS, haptics, cameras || `xnuloader/` | the boot loader (a UEFI application) || `userland/` | my programs and libraries (`src/`), the image build, launchd jobs || `sysimage/` | scripts that fetch and unpack the OS files from the IPSW (none of the files themselves) |@@ -140,7 +140,7 @@ module, or the open lzfse library gets built). User space and the images: `REST=The kernel, loader and user space are shared. Everything about one phone lives in`devices/<name>/`: its UEFI, device tree, firmware list and tools. Today there is one,`devices/poco-x5-pro/`, and its README is the map of what a port to another Qualcomm phone must bring.-The phone's drivers are the files `xnu/files/bsd/dev/hakios_*.c`; the head of each says where its+The phone's drivers are the files `xnu/files/bsd/dev/hakios.*.c`; the head of each says where itsnumbers came from.## Cellulardiff --git a/README.uk.md b/README.uk.mdindex 40f7fc7..d16e59c 100644--- a/README.uk.md+++ b/README.uk.md@@ -108,7 +108,7 @@ make images # користувацький простір і образи| Каталог | Вміст ||---|---|| `xnu/` | патч і файли ядра; `apply.sh`, `export.sh`; README про ядро |-| `xnu/files/bsd/dev/hakios_*.c` | мої драйвери: екран, тач, UFS, GPU, Wi-Fi, звук, модем, SIM/NAS, вібро, камери |+| `xnu/files/bsd/dev/hakios.*.c` | мої драйвери: екран, тач, UFS, GPU, Wi-Fi, звук, модем, SIM/NAS, вібро, камери || `xnuloader/` | завантажувач (застосунок UEFI) || `userland/` | мої програми й бібліотеки (`src/`), збірка образів, завдання launchd || `sysimage/` | скрипти, що беруть і розпаковують файли ОС з IPSW (самих файлів немає) |diff --git a/README.zh.md b/README.zh.mdindex 4462033..9fca9a4 100644--- a/README.zh.md+++ b/README.zh.md@@ -102,7 +102,7 @@ make images # 用户空间和镜像| 目录 | 内容 ||---|---|| `xnu/` | 内核补丁和文件;`apply.sh`、`export.sh`;内核 README |-| `xnu/files/bsd/dev/hakios_*.c` | 我的驱动:显示、触摸、UFS、GPU、Wi-Fi、音频、调制解调器、SIM/NAS、振动、摄像头 |+| `xnu/files/bsd/dev/hakios.*.c` | 我的驱动:显示、触摸、UFS、GPU、Wi-Fi、音频、调制解调器、SIM/NAS、振动、摄像头 || `xnuloader/` | 引导程序(UEFI 应用) || `userland/` | 我的程序和库(`src/`)、镜像构建、launchd 任务 || `sysimage/` | 从 IPSW 取得并解包系统文件的脚本(不含文件本身) |diff --git a/docs/cellular.md b/docs/cellular.mdindex 86bcfc0..37c4811 100644--- a/docs/cellular.md+++ b/docs/cellular.md@@ -20,11 +20,35 @@ Where the modem stands (October 2026). The detailed, step-by-step diary in Russi- SpringBoard's status bar: the signal item is hooked (`userland/src/inject_sb.c`) and shows thekernel's bars (`sysctl kern.hakios.cellular_bars`) once the modem is registered.+- The data session: once NAS reports registration, the kernel binds its QMI WDS client to QMAP+ mux 1 of the embedded port (the IPA), sets the port's data format (WDA: raw IP in QMAP, no+ checksum offload), starts an IPv4 session on the SIM's default profile and reads its settings+ (address, gateway, DNS, MTU: `sysctl kern.hakios.cellular_ip`, `_gateway`, `_dns`, `_mtu`,+ `_data`).++## The data path (2.0)++Packets go through the IPA, the SoC's packet engine, the way Linux's `drivers/net/ipa` does it+for IPA 4.11; everything is in `xnu/files/bsd/dev/hakios.ipa.c` and `hakios.cell.c`.++- Before the modem starts, the kernel sets up this processor's side of the IPA: four GSI+ channels with their event rings (the command channel 5, the LAN receive channel 14, the modem+ transmit channel 2 and the modem receive channel 7), the matching endpoints (7, 9, 2, 16:+ QMAP headers, deaggregation on the way out, aggregation up to 12 KB or 500 us on the way in),+ and the IPA's filter, route and header tables through immediate commands, so that the modem+ finds valid tables and adds its own rules to them.+- The rings are polled by the interface's thread; no interrupt is taken from the GSI.+- The modem's packets are an Ethernet-looking interface, `en1`, with a made-up router behind it.+ The kernel answers ARP for every address and DHCP with the session's address, a /24 around it,+ the router and the DNS servers, so iOS's configd configures `en1` as it would a USB Ethernet+ adapter and routes through it. IPv6 is not carried.+- `modem_ipa_data_off=1` leaves all of this out; `modem_ipa_data_trace=1` logs every packet.+## Not yet- Network registration itself: the modem sees the network but has not registered; the last- change (binding the provisioning session) is being tested.-- The data path (IPA endpoints for the AP), calls, SMS.+ change (binding the provisioning session) is being tested, and the data path above waits on it.+- Calls, SMS, IPv6.## How to run it@@ -49,3 +73,8 @@ XL_SB_DELAY=8 tools/modem-cycle.sh "modem=1 modem_again=1 modem_buffer=0xa800000| `modem_ipa=3` (default) | the SMP2P entry `ipa`: valid, clock on || `modem_sim_switch_off=1` | do not point logical slot 1 at the slot with the ready card || `modem_sim_probe_off=1` | no SIM and network-selection queries |+| `modem_data_off=1` | no data session (no WDS/WDA) |+| `modem_data_nobind=1` | the session without binding the client to the mux |+| `modem_apn=NAME` | the session to that APN instead of the SIM's default profile |+| `modem_ipa_data_off=1` | no IPA data path for this processor, no `en1` |+| `modem_ipa_data_trace=1` | a log line per packet, command and DHCP/ARP answer |diff --git a/prebuilt/SHA256SUMS b/prebuilt/SHA256SUMSindex ab9e4f1..202edc7 100644--- a/prebuilt/SHA256SUMS+++ b/prebuilt/SHA256SUMS@@ -1,6 +1,6 @@-Built 2026-10-25 18:06 from this tree.+Built 2026-10-25 18:43 from this tree.-b358a5cda881fda36385e78faaf71314b3ebcbcd08051592bf8b0a3a3d0d2486 prebuilt/mach.development.bcm2837+63b409d38aadb68f6a287f40f96555b11ad8a5845827e00750ce635aa17c5305 prebuilt/mach.development.bcm28373de0d8b2095989a9a8f9f9679b8bec01d80bad38eee535d934d29b7b76fee984 prebuilt/loader.efi932c856c04e87611b16c872da37c461d572c6258da0202ecd875d91c29886e03 prebuilt/userland/HakiosAudio45bffe2da6b2484836bd29074b39bd5cc67b4cdaa253c2aa39561ce5188d6ddc prebuilt/userland/child@@ -11,7 +11,7 @@ b089fec6fe19149c3a61f8645ea3c28b19a051d4d053794ae459ff6a7c947805 prebuilt/userlef496beee457476dcda607d27cb26398b1fc463b6f6c7fe21012eb4c0c26edb9 prebuilt/userland/libhakios.app.dylib530c2e681093ece2afe7f5180a4723bd46d92f7af39edc0a8c77136136a4dad6 prebuilt/userland/libhakios.dylibd8680034e5f0cdecd396cd7488e9d0f30037223ebc57f5309f99a6cd45a4ad26 prebuilt/userland/libhakios.media.dylib-6ae63b56634e1024a254859acf08831680278211820c8a6e2447f1d98f3dfe52 prebuilt/userland/libhakios.sb.dylib+84f517b8bde52a6d376e17a325127c27193cae8106d8da634a5f77bb0445c617 prebuilt/userland/libhakios.sb.dylibda392e632eb6978164c4c191b73773cf4ceac2c288d1b9697d35fd1f938f73f3 prebuilt/userland/libhakios.tweaks.dylib8ba7ffba4ff62aff74ab144fc25c61873408320511a83c9b8faf941f32e965d0 prebuilt/userland/mg_test8dccf07fb4d9f406fcf558355cc9f3a1614a39c29e5bb79740aa5c5e972023fe prebuilt/userland/net_testdiff --git a/prebuilt/mach.development.bcm2837 b/prebuilt/mach.development.bcm2837index df0aeb8..f69eb21 100755Binary files a/prebuilt/mach.development.bcm2837 and b/prebuilt/mach.development.bcm2837 differdiff --git a/prebuilt/userland/libhakios.sb.dylib b/prebuilt/userland/libhakios.sb.dylibindex 914e3e3..19fd4e2 100755Binary files a/prebuilt/userland/libhakios.sb.dylib and b/prebuilt/userland/libhakios.sb.dylib differdiff --git a/tools/modem-cycle.sh b/tools/modem-cycle.shindex 2ccd995..4cf2f9d 100755--- a/tools/modem-cycle.sh+++ b/tools/modem-cycle.sh@@ -12,7 +12,7 @@ echo "$(date +%T) phone: $s"; [ "$s" = absent ] && { echo "NO PHONE"; exit 1; }XL_SB_DELAY=${XL_SB_DELAY:-600} XL_CMDLINE="debug=0x8 rd=md0 hv_wdt_pet=1 bootcpu=7 cpus=8 cpufreq=1 ufs=2 $ARGS" XL_SECS=$SECS XL_FOLLOW=1 XL_FOLLOW_KEEP=1 ./xl run 2>&1 | tail -2echo "$(date +%T) state after run: $(./xl state)"L=$(ls -t logs/*-run.log.live | head -1); F=${L%.live}; echo "LOG=$F"-cat $L $F 2>/dev/null | grep -a "mpss: \(7: \(THE\|the watch\)\|11\|rmtfs\|tftp\|servreg\|dms\|nas\|ipa: \(THE\|from node\|the modem\|a probe\)\|link: \(THE\|tftp\)\|LAST WORDS\|step 1[01]\)\|serving system\|panic(" | grep -v "about to ask\|about to tell" | sed 's/^\[ *[0-9.]*\]: //' | awk '!seen[$0]++' | cut -c1-230 | head -80+cat $L $F 2>/dev/null | grep -a "mpss: \(7: \(THE\|the watch\)\|11\|rmtfs\|tftp\|servreg\|dms\|nas\|ipa: \(THE\|from node\|the modem\|a probe\)\|link: \(THE\|tftp\)\|LAST WORDS\|step 1[01]\)\|serving system\|panic(\|ipa: \|cell: \|net: en1\|wda: \|wds: \(THE\|the client\|about\)" | grep -v "about to ask\|about to tell" | sed 's/^\[ *[0-9.]*\]: //' | awk '!seen[$0]++' | cut -c1-230 | head -80echo "== back to Android"case "$(./xl state)" in loader|fastboot) XL_FORCE=1 ./xl reboot >/dev/null 2>&1 ;; esacfor i in $(seq 1 40); do s=$(./xl state); [ "$s" = android ] && break; sleep 5; donediff --git a/userland/src/inject_sb.c b/userland/src/inject_sb.cindex 81b833b..08619db 100644--- a/userland/src/inject_sb.c+++ b/userland/src/inject_sb.c@@ -276,6 +276,14 @@ static void (*original_update_signal_item)(id self, SEL sel, long item, void *dastatic id cellular_aggregator;static int cellular_last_bars = -2, cellular_said;+/* The getters and setters are blocks (their type is "@?"): called through the block's own invoke pointer, with the block first. */+struct block_layout {+ void *isa;+ int flags, reserved;+ void (*invoke)(void *, ...);+};+#define BLOCK_CALL(block, type, ...) ((type)((struct block_layout *)(block))->invoke)((block), __VA_ARGS__)+static voidupdate_signal_item(id self, SEL sel, long item, void *data, id sim, void *getter, void *setter){@@ -291,7 +299,7 @@ update_signal_item(id self, SEL sel, long item, void *data, id sim, void *getteritem, data, (void *)sim, getter, setter, up, registered, bars);}if (up > 0 && registered > 0 && bars >= 0 && bars <= 5 && setter != NULL && data != NULL) {- ((void (*)(void *, int))setter)(data, bars);+ BLOCK_CALL(setter, void (*)(void *, void *, int), data, bars);((void (*)(id, SEL, long, BOOL))objc_msgSend)(self, sel_registerName("_setItem:enabled:"), item, YES);if (bars != cellular_last_bars) {say("hakios: cellular: %d bars shown (item %ld)\n", bars, item);@@ -303,24 +311,42 @@ update_signal_item(id self, SEL sel, long item, void *data, id sim, void *getterstatic void (*original_update_service_item)(id self, SEL sel, long item, void *data, id sim, id other, void *g1, void *s1, void *g2, void *s2,void *g3, void *s3, void *g4, void *s4);-/* The service item ("No SIM", the network's name): looked at first; its string setter is for the next step. */+/*+ * The service item ("No SIM", the network's name): once the kernel's modem is registered, the+ * network's name (sysctl kern.hakios.cellular_operator) goes in through the item's string setter+ * and the item is switched on.+ */static voidupdate_service_item(id self, SEL sel, long item, void *data, id sim, id other, void *g1, void *s1, void *g2, void *s2, void *g3, void *s3,void *g4, void *s4){static int said;+ static char shown[64];+ char name[64] = "";+ size_t size = sizeof(name) - 1;+ int registered = sysctl_int("kern.hakios.cellular_registered");if (original_update_service_item) {original_update_service_item(self, sel, item, data, sim, other, g1, s1, g2, s2, g3, s3, g4, s4);}+ sysctlbyname("kern.hakios.cellular_operator", name, &size, NULL, 0);if (said++ < 4) {- char name[64] = "";- size_t size = sizeof(name) - 1;-- sysctlbyname("kern.hakios.cellular_operator", name, &size, NULL, 0);say("hakios: cellular: service item %ld: data %p, SIM info %p, other %p; string getter %p setter %p, content type getter %p ""setter %p; the kernel's network \"%s\"\n", item, data, (void *)sim, (void *)other, g1, s1, g3, s3, name);}+ if (registered > 0 && name[0] != 0 && s1 != NULL && data != NULL) {+ CFStringRef string = CFStringCreateWithCString(NULL, name, kCFStringEncodingUTF8);++ if (string != NULL) {+ BLOCK_CALL(s1, void (*)(void *, void *, CFStringRef), data, string);+ ((void (*)(id, SEL, long, BOOL))objc_msgSend)(self, sel_registerName("_setItem:enabled:"), item, YES);+ if (strcmp(shown, name) != 0) {+ snprintf(shown, sizeof(shown), "%s", name);+ say("hakios: cellular: service \"%s\" shown (item %ld)\n", name, item);+ }+ CFRelease(string);+ }+ }}static voiddiff --git a/xnu/files/bsd/dev/hakios.cell.c b/xnu/files/bsd/dev/hakios.cell.cnew file mode 100644index 0000000..21dfcaa--- /dev/null+++ b/xnu/files/bsd/dev/hakios.cell.c@@ -0,0 +1,358 @@+/*+ * en1: the modem's packets as a network interface iOS will use.+ *+ * iOS's own cellular interface (pdp_ip0) is made by its baseband stack, which is not here. What+ * is here is the kernel's Ethernet-looking interface (hakios.net.c) and configd, which treats an+ * Ethernet interface whose link comes up the way it treats a USB Ethernet adapter: it runs DHCP+ * on it, takes the address, the router and the DNS servers it is given, and routes through it.+ * So the modem's IP packets (hakios.ipa.c, QMAP mux 1) are shown as Ethernet frames between two+ * made-up stations, the interface's and "the router's", and this file answers, in the kernel,+ * what the stack asks of the router: ARP for any address (everything is behind the router) and+ * DHCP with the data session's settings (the address and DNS servers the modem got from the+ * network, hakios.mpss.c, QMI WDS). Packets to the router go to the modem; packets from the modem+ * come from the router. IPv6 is not carried (the session is IPv4).+ *+ * The mask and the router given to DHCP are not the modem's: a cellular session is a point-to-point+ * link, and its "gateway" need not be in any subnet with the address, which DHCP cannot express.+ * The interface gets a /24 around its address with the router at its .1 (or .2): any router will+ * do, since every packet goes to the modem anyway.+ */+#include <kern/locks.h>+#include <libkern/libkern.h>+#include <mach/mach_types.h>+#include <pexpert/pexpert.h>+#include <sys/kpi_mbuf.h>+#include <sys/systm.h>+#include <sys/hakios.net.h>+#include <sys/hakios.ipa.h>++#define CELL_UNIT 1+#define CELL_MUX 1 /* the QMAP mux id the session is bound to (WDS Bind Mux Data Port) */++static const uint8_t cell_mac[6] = { 0x02, 0x68, 0x61, 0x6b, 0x69, 0x01 }; /* locally administered: "haki", 1 */+static const uint8_t router_mac[6] = { 0x02, 0x68, 0x61, 0x6b, 0x69, 0xfe };++static LCK_GRP_DECLARE(cell_lock_group, "hakios-cell");+static LCK_MTX_DECLARE(cell_lock, &cell_lock_group);+static struct {+ bool up;+ uint32_t address, mask, router, dns1, dns2, mtu; /* host order; what DHCP gives out */+ uint32_t modem_mask, modem_gateway; /* what the modem said, for the log */+} session;+static struct {+ uint64_t arp, dhcp, to_modem, from_modem, dropped_out, dropped_in, not_ip4;+} cell_count;+static bool cell_attached, cell_trace;++static inline uint32_t+get32(const uint8_t *p)+{+ return (uint32_t)p[0] << 24 | (uint32_t)p[1] << 16 | (uint32_t)p[2] << 8 | p[3];+}++static inline void+put32(uint8_t *p, uint32_t v)+{+ p[0] = (uint8_t)(v >> 24); p[1] = (uint8_t)(v >> 16); p[2] = (uint8_t)(v >> 8); p[3] = (uint8_t)v;+}++static inline void+put16(uint8_t *p, uint32_t v)+{+ p[0] = (uint8_t)(v >> 8); p[1] = (uint8_t)v;+}++static uint16_t+checksum(const uint8_t *data, size_t length)+{+ uint32_t sum = 0;++ for (size_t i = 0; i + 1 < length; i += 2) {+ sum += (uint32_t)data[i] << 8 | data[i + 1];+ }+ if (length & 1) {+ sum += (uint32_t)data[length - 1] << 8;+ }+ while (sum >> 16) {+ sum = (sum & 0xffff) + (sum >> 16);+ }+ return (uint16_t)~sum;+}++/* ---- ARP: the router answers for everything ---------------------------------------------------- */++static bool+arp_answer(const uint8_t *frame, size_t length)+{+ const uint8_t *arp = frame + 14;+ uint8_t reply[42];++ /* Ethernet/IPv4, a request, not for our own address */+ if (length < 42 || get32(arp) != 0x00010800 || arp[4] != 6 || arp[5] != 4 || arp[7] != 1 || get32(arp + 24) == session.address) {+ return false;+ }+ memcpy(reply, frame + 6, 6); /* to the asker */+ memcpy(reply + 6, router_mac, 6);+ put16(reply + 12, 0x0806);+ put32(reply + 14, 0x00010800);+ reply[18] = 6; reply[19] = 4;+ put16(reply + 20, 2); /* a reply */+ memcpy(reply + 22, router_mac, 6); /* "that address is me" */+ memcpy(reply + 28, arp + 24, 4);+ memcpy(reply + 32, arp + 8, 10); /* the asker's addresses */+ cell_count.arp++;+ if (cell_trace) {+ printf("cell: ARP: %u.%u.%u.%u is the router\n", arp[24], arp[25], arp[26], arp[27]);+ }+ hakios_net_input_unit(CELL_UNIT, reply, sizeof(reply));+ return true;+}++/* ---- DHCP: the session's settings ---------------------------------------------------------------- */++#define DHCP_DISCOVER 1+#define DHCP_OFFER 2+#define DHCP_REQUEST 3+#define DHCP_ACK 5+#define DHCP_NAK 6++/* Is this a DHCP request (UDP 68 -> 67)? `udp` is set to its UDP header. */+static bool+dhcp_request(const uint8_t *frame, size_t length, const uint8_t **udp)+{+ const uint8_t *ip = frame + 14;+ size_t ihl;++ if (length < 14 + 20 + 8 + 240 || (ip[0] >> 4) != 4 || ip[9] != 17) {+ return false;+ }+ ihl = 4 * (ip[0] & 0xf);+ if (ihl < 20 || 14 + ihl + 8 + 240 > length) {+ return false;+ }+ *udp = ip + ihl;+ return ((*udp)[2] << 8 | (*udp)[3]) == 67;+}++/* The answer to a DHCP request: an offer for a discover, an acknowledgement for a request, with the session's settings. */+static bool+dhcp_answer(const uint8_t *frame, size_t length, const uint8_t *udp)+{+ const uint8_t *request = udp + 8, *end = frame + length, *option;+ uint8_t reply[14 + 20 + 8 + 240 + 64], *ip = reply + 14, *rudp = ip + 20, *bootp = rudp + 8, *o;+ uint32_t type = 0, wanted = 0, kind;+ size_t size;++ if (request[0] != 1 || request[1] != 1 || request[2] != 6 || get32(request + 236) != 0x63825363) {+ return false;+ }+ /* the options: the message type, the address asked for */+ for (option = request + 240; option + 2 <= end && *option != 255; option += option[0] == 0 ? 1 : 2 + option[1]) {+ if (option[0] == 0) {+ continue;+ }+ if (option + 2 + option[1] > end) {+ break;+ }+ if (option[0] == 53 && option[1] == 1) {+ type = option[2];+ } else if (option[0] == 50 && option[1] == 4) {+ wanted = get32(option + 2);+ }+ }+ if (type != DHCP_DISCOVER && type != DHCP_REQUEST) {+ return false;+ }+ kind = type == DHCP_DISCOVER ? DHCP_OFFER : wanted != 0 && wanted != session.address ? DHCP_NAK : DHCP_ACK;+ bzero(reply, sizeof(reply));+ /* BOOTP */+ bootp[0] = 2; bootp[1] = 1; bootp[2] = 6; /* a reply, Ethernet */+ memcpy(bootp + 4, request + 4, 4); /* the transaction */+ memcpy(bootp + 10, request + 10, 2); /* the flags (broadcast) */+ if (kind != DHCP_NAK) {+ put32(bootp + 16, session.address); /* yiaddr */+ put32(bootp + 20, session.router); /* siaddr */+ }+ memcpy(bootp + 28, request + 28, 16); /* the client's hardware address */+ put32(bootp + 236, 0x63825363);+ o = bootp + 240;+ *o++ = 53; *o++ = 1; *o++ = (uint8_t)kind;+ *o++ = 54; *o++ = 4; put32(o, session.router); o += 4; /* the server: the router */+ if (kind != DHCP_NAK) {+ *o++ = 51; *o++ = 4; put32(o, 86400); o += 4; /* a day's lease */+ *o++ = 1; *o++ = 4; put32(o, session.mask); o += 4;+ *o++ = 3; *o++ = 4; put32(o, session.router); o += 4;+ if (session.dns1 != 0 || session.dns2 != 0) {+ *o++ = 6; *o++ = (uint8_t)(4 * ((session.dns1 != 0) + (session.dns2 != 0)));+ if (session.dns1 != 0) { put32(o, session.dns1); o += 4; }+ if (session.dns2 != 0) { put32(o, session.dns2); o += 4; }+ }+ if (session.mtu >= 576 && session.mtu <= 1500) {+ *o++ = 26; *o++ = 2; put16(o, session.mtu); o += 2;+ }+ }+ *o++ = 255;+ size = (size_t)(o - bootp);+ if (size < 300) {+ size = 300; /* the traditional minimum, padded with zeros */+ }+ /* UDP 67 -> 68, no checksum */+ put16(rudp, 67); put16(rudp + 2, 68); put16(rudp + 4, (uint32_t)(8 + size)); put16(rudp + 6, 0);+ /* IPv4 from the router to everyone */+ ip[0] = 0x45; ip[1] = 0;+ put16(ip + 2, (uint32_t)(20 + 8 + size));+ put16(ip + 4, 0); put16(ip + 6, 0);+ ip[8] = 64; ip[9] = 17;+ put32(ip + 12, session.router);+ put32(ip + 16, 0xffffffff);+ put16(ip + 10, checksum(ip, 20));+ /* Ethernet to the client */+ memcpy(reply, request + 28, 6);+ memcpy(reply + 6, router_mac, 6);+ put16(reply + 12, 0x0800);+ cell_count.dhcp++;+ printf("cell: DHCP %s answered with %s: %u.%u.%u.%u/%u.%u.%u.%u, router %u.%u.%u.%u, DNS %u.%u.%u.%u %u.%u.%u.%u, MTU %u\n",+ type == DHCP_DISCOVER ? "discover" : "request", kind == DHCP_OFFER ? "an offer" : kind == DHCP_ACK ? "an acknowledgement" : "a refusal",+ session.address >> 24, (session.address >> 16) & 0xff, (session.address >> 8) & 0xff, session.address & 0xff,+ session.mask >> 24, (session.mask >> 16) & 0xff, (session.mask >> 8) & 0xff, session.mask & 0xff,+ session.router >> 24, (session.router >> 16) & 0xff, (session.router >> 8) & 0xff, session.router & 0xff,+ session.dns1 >> 24, (session.dns1 >> 16) & 0xff, (session.dns1 >> 8) & 0xff, session.dns1 & 0xff,+ session.dns2 >> 24, (session.dns2 >> 16) & 0xff, (session.dns2 >> 8) & 0xff, session.dns2 & 0xff, session.mtu);+ hakios_net_input_unit(CELL_UNIT, reply, 14 + 20 + 8 + size);+ return true;+}++/* ---- the link ----------------------------------------------------------------------------------- */++/* A frame from the stack: answered here, or its IP packet to the modem. */+static bool+cell_transmit(mbuf_t packet, size_t length)+{+ uint8_t frame[HAKIOS_NET_FRAME_MAX];+ const uint8_t *udp;+ uint32_t type;+ bool ok;++ if (length < 14 || length > sizeof(frame) || mbuf_copydata(packet, 0, length, frame) != 0) {+ return false;+ }+ type = (uint32_t)frame[12] << 8 | frame[13];+ lck_mtx_lock(&cell_lock);+ if (type == 0x0806) {+ ok = arp_answer(frame, length);+ } else if (type == 0x0800 && dhcp_request(frame, length, &udp)) {+ ok = session.up && dhcp_answer(frame, length, udp);+ } else if (type == 0x0800) {+ ok = session.up && hakios_ipa_transmit(CELL_MUX, frame + 14, length - 14);+ if (ok) {+ cell_count.to_modem++;+ } else {+ cell_count.dropped_out++;+ }+ } else {+ cell_count.not_ip4++; /* IPv6 and the rest: not carried */+ ok = false;+ }+ lck_mtx_unlock(&cell_lock);+ return ok;+}++/* A packet from the modem: an Ethernet frame from the router made around it. */+static void+cell_receive(uint8_t mux, const uint8_t *packet, size_t length)+{+ uint8_t frame[HAKIOS_NET_FRAME_MAX];+ uint32_t version = length > 0 ? packet[0] >> 4 : 0;++ if (length < 20 || length + 14 > sizeof(frame) || (version != 4 && version != 6)) {+ cell_count.dropped_in++;+ return;+ }+ if (cell_trace) {+ printf("cell: %zu bytes from the modem on mux %u (IPv%u)\n", length, mux, version);+ }+ memcpy(frame, cell_mac, 6);+ memcpy(frame + 6, router_mac, 6);+ put16(frame + 12, version == 4 ? 0x0800 : 0x86dd);+ memcpy(frame + 14, packet, length);+ cell_count.from_modem++;+ hakios_net_input_unit(CELL_UNIT, frame, 14 + length);+}++static unsigned+cell_poll(void)+{+ static unsigned ticks;+ unsigned got = hakios_ipa_poll(cell_receive);++ if (++ticks % 30000 == 0 && (cell_count.to_modem != 0 || cell_count.from_modem != 0 || cell_count.dropped_out != 0)) {+ char line[256];++ hakios_ipa_status(line, sizeof(line));+ printf("cell: so far %llu packets to the modem, %llu from it; dropped %llu out, %llu in; %llu not IPv4; ARP %llu, DHCP %llu; "+ "IPA: %s\n", cell_count.to_modem, cell_count.from_modem, cell_count.dropped_out, cell_count.dropped_in, cell_count.not_ip4,+ cell_count.arp, cell_count.dhcp, line);+ }+ return got;+}++static struct hakios_net_link cell_link = {+ .name = "the modem through the IPA",+ .unit = CELL_UNIT,+ .address = { 0x02, 0x68, 0x61, 0x6b, 0x69, 0x01 },+ .wireless = false,+ .up = false,+ .transmit = cell_transmit,+ .poll = cell_poll,+};++void+hakios_cell_session(bool up, uint32_t address, uint32_t mask, uint32_t gateway, uint32_t dns1, uint32_t dns2, uint32_t mtu)+{+ uint32_t router;++ lck_mtx_lock(&cell_lock);+ session.modem_mask = mask;+ session.modem_gateway = gateway;+ /* a /24 around the address, with the router in it (see the top of the file) */+ mask = 0xffffff00;+ router = (address & mask) | 1;+ if (router == address) {+ router = (address & mask) | 2;+ }+ session.address = address;+ session.mask = mask;+ session.router = router;+ session.dns1 = dns1;+ session.dns2 = dns2;+ session.mtu = mtu;+ session.up = up && address != 0;+ lck_mtx_unlock(&cell_lock);+ printf("cell: the data session is %s: %u.%u.%u.%u (the modem's mask %u.%u.%u.%u and gateway %u.%u.%u.%u; en1 is told /24 and router "+ "%u.%u.%u.%u), DNS %u.%u.%u.%u %u.%u.%u.%u, MTU %u%s\n", session.up ? "UP" : "down",+ address >> 24, (address >> 16) & 0xff, (address >> 8) & 0xff, address & 0xff,+ session.modem_mask >> 24, (session.modem_mask >> 16) & 0xff, (session.modem_mask >> 8) & 0xff, session.modem_mask & 0xff,+ gateway >> 24, (gateway >> 16) & 0xff, (gateway >> 8) & 0xff, gateway & 0xff,+ router >> 24, (router >> 16) & 0xff, (router >> 8) & 0xff, router & 0xff,+ dns1 >> 24, (dns1 >> 16) & 0xff, (dns1 >> 8) & 0xff, dns1 & 0xff, dns2 >> 24, (dns2 >> 16) & 0xff, (dns2 >> 8) & 0xff, dns2 & 0xff,+ mtu, cell_attached ? "" : " (no en1: the IPA's data path is not up)");+ if (cell_attached) {+ hakios_net_link_state_unit(CELL_UNIT, session.up);+ }+}++void+hakios_cell_attach(void)+{+ uint32_t t = 0;++ if (cell_attached || !hakios_ipa_data_ready()) {+ return;+ }+ PE_parse_boot_argn("modem_ipa_data_trace", &t, sizeof(t));+ cell_trace = t != 0;+ cell_attached = hakios_net_attach(&cell_link);+ if (cell_attached && session.up) {+ hakios_net_link_state_unit(CELL_UNIT, true);+ }+}diff --git a/xnu/files/bsd/dev/hakios.ipa.c b/xnu/files/bsd/dev/hakios.ipa.cnew file mode 100644index 0000000..d5d853b--- /dev/null+++ b/xnu/files/bsd/dev/hakios.ipa.c@@ -0,0 +1,853 @@+/*+ * The IPA's data path for this processor: GSI rings, the IPA's endpoints for the application+ * processor, and the immediate commands that give the IPA its tables.+ *+ * The IPA (Qualcomm's "IP accelerator", here IPA 4.11 with GSI 2.11) moves packets between the+ * modem and this processor. Each side has "endpoints" (pipes) in the IPA and "channels" in the+ * GSI (the DMA engine beside it): a channel is a ring of transfer elements (TREs: address, length,+ * flags; 16 bytes) that this processor fills and the hardware consumes, and an event ring the+ * hardware fills with one event per finished TRE. Writing a doorbell register tells the hardware+ * how far the ring is filled; the event ring's write pointer, read from a register, tells us how+ * far the hardware got. No interrupt is used: the interface's thread polls (hakios.cell.c).+ *+ * What this processor needs, as Linux's driver sets them up for IPA 4.11 (drivers/net/ipa,+ * ipa_data-v4.11.c, gsi.c, ipa_endpoint.c, ipa_cmd.c, ipa_table.c; the register layout from+ * reg/gsi_reg-v4.11.c and reg/ipa_reg-v4.11.c):+ * - the command endpoint (7, channel 5): immediate commands to the IPA itself, which is how it+ * is told where its filter and route tables and its header table are;+ * - the "LAN" receive endpoint (9, channel 14): the IPA's default route (what matches no rule)+ * and its exceptions end here; it is looked at and dropped;+ * - the modem transmit endpoint (2, channel 2): IP packets to the modem, each behind a QMAP+ * header (4 bytes: pad length, mux id, packet length, big-endian);+ * - the modem receive endpoint (16, channel 7): IP packets from the modem, QMAP-framed, several+ * per buffer (the IPA aggregates them until 12 KB or 500 us).+ * No checksum offload, no status packets: the network stack computes its checksums itself and+ * the modem is told QMAP without checksum (hakios.mpss.c, WDA Set Data Format).+ *+ * All of this is done before the modem starts (Linux does the same): the tables the commands+ * write hold pointers to one "zero rule", and the modem then writes its own rules into its part+ * of them. The IPA reaches this memory through the SMMU context the modem driver gave it, which+ * shows DDR as it is (physical addresses). The memory is cached for us, so every buffer is+ * written back and dropped from the cache (dc civac) before the hardware looks at it and before+ * we look at what the hardware wrote.+ *+ * modem_ipa_data_off=1: none of this. modem_ipa_data_trace=1: a line per packet.+ */+#include <kern/clock.h>+#include <kern/kalloc.h>+#include <kern/locks.h>+#include <libkern/libkern.h>+#include <mach/mach_types.h>+#include <mach/vm_param.h>+#include <pexpert/pexpert.h>+#include <sys/systm.h>+#include <vm/vm_kern.h>+#include <sys/hakios.ipa.h>++extern vm_offset_t ml_io_map(vm_offset_t phys_addr, vm_size_t size);+extern uint64_t kvtophys(vm_offset_t va);+extern void FlushPoC_DcacheRegion(vm_offset_t va, size_t length);++static LCK_GRP_DECLARE(ipa_lock_group, "hakios-ipa");+static LCK_MTX_DECLARE(ipa_lock, &ipa_lock_group);++/* ---- the registers ---------------------------------------------------------------------------- */++#define IPA_REGS_PHYS 0x01e40000ull+#define IPA_REGS_SIZE 0x1000+#define GSI_PHYS 0x01e04000ull+#define GSI_FROM 0xc000 /* what is used of the GSI's registers: from the inter-EE masks (0xc020) to the scratch (0x12400) */+#define GSI_SIZE 0x7000++static vm_offset_t ipa_regs, gsi_regs; /* gsi_regs maps GSI_PHYS + GSI_FROM */++static inline uint32_t+ipa_rd(uint32_t offset)+{+ return *(volatile uint32_t *)(ipa_regs + offset);+}++static inline void+ipa_wr(uint32_t offset, uint32_t value)+{+ *(volatile uint32_t *)(ipa_regs + offset) = value;+ __asm__ volatile ("dsb sy" ::: "memory");+}++static inline uint32_t+gsi_rd(uint32_t offset)+{+ return *(volatile uint32_t *)(gsi_regs + (offset - GSI_FROM));+}++static inline void+gsi_wr(uint32_t offset, uint32_t value)+{+ *(volatile uint32_t *)(gsi_regs + (offset - GSI_FROM)) = value;+ __asm__ volatile ("dsb sy" ::: "memory");+}++/* The GSI's registers for our execution environment (EE 0; another EE's are 0x4000 further) */+#define CH_CNTXT(c, n) (0xf000 + 0x80 * (c) + 4 * (n)) /* n 0..3: type/dir/event ring/state, length, address */+#define CH_QOS(c) (0xf05c + 0x80 * (c))+#define CH_SCRATCH(c, n) (0xf060 + 0x80 * (c) + 4 * (n))+#define EV_CNTXT(e, n) (0x10000 + 0x80 * (e) + 4 * (n)) /* n 0..13: type/state, length, address, read/write pointers, moderation, MSI */+#define CH_DOORBELL(c) (0x11000 + 8 * (c))+#define EV_DOORBELL(e) (0x11100 + 8 * (e))+#define GSI_STATUS 0x12000+#define CH_CMD 0x12008+#define EV_CH_CMD 0x12010+#define CNTXT_TYPE_IRQ 0x12080+#define CNTXT_TYPE_IRQ_MSK 0x12088+#define CNTXT_SRC_CH_IRQ 0x12090+#define CNTXT_SRC_EV_CH_IRQ 0x12094+#define CNTXT_SRC_CH_IRQ_MSK 0x12098+#define CNTXT_SRC_EV_CH_IRQ_MSK 0x1209c+#define CNTXT_SRC_CH_IRQ_CLR 0x120a0+#define CNTXT_SRC_EV_CH_IRQ_CLR 0x120a4+#define CNTXT_SRC_IEOB_IRQ 0x120b0+#define CNTXT_SRC_IEOB_IRQ_MSK 0x120b8+#define CNTXT_SRC_IEOB_IRQ_CLR 0x120c0+#define CNTXT_GLOB_IRQ_STTS 0x12100+#define CNTXT_GLOB_IRQ_EN 0x12108+#define CNTXT_GLOB_IRQ_CLR 0x12110+#define CNTXT_GSI_IRQ_STTS 0x12118+#define CNTXT_GSI_IRQ_EN 0x12120+#define CNTXT_GSI_IRQ_CLR 0x12128+#define CNTXT_INTSET 0x12180+#define ERROR_LOG 0x12200+#define ERROR_LOG_CLR 0x12210+#define INTER_EE_SRC_CH_IRQ_MSK 0xc020+#define INTER_EE_SRC_EV_CH_IRQ_MSK 0xc024++#define GSI_CH_ALLOCATE 0x0 /* channel commands (CH_CMD bits 31:24; the channel in 7:0) */+#define GSI_CH_START 0x1+#define GSI_CH_STOP 0x2+#define GSI_CH_RESET 0x9+#define GSI_CH_DE_ALLOC 0xa+#define GSI_EVT_ALLOCATE 0x0 /* event ring commands (EV_CH_CMD, the same layout) */+#define GSI_EVT_RESET 0x9+#define GSI_EVT_DE_ALLOC 0xa+#define CH_STATE_NOT_ALLOCATED 0 /* CH_CNTXT 0 bits 23:20 */+#define CH_STATE_ALLOCATED 1+#define CH_STATE_STARTED 2+#define CH_STATE_STOPPED 3+#define EV_STATE_NOT_ALLOCATED 0 /* EV_CNTXT 0 bits 23:20 */+#define EV_STATE_ALLOCATED 1+#define GSI_CHANNEL_TYPE_GPI 2+#define ELEMENT_SIZE 16++/* The IPA's endpoint registers (0x70 apart) */+#define ENDP_INIT_CFG(ep) (0x808 + 0x70 * (ep))+#define ENDP_INIT_NAT(ep) (0x80c + 0x70 * (ep))+#define ENDP_INIT_HDR(ep) (0x810 + 0x70 * (ep))+#define ENDP_INIT_HDR_EXT(ep) (0x814 + 0x70 * (ep))+#define ENDP_INIT_HDR_METADATA_MASK(ep) (0x818 + 0x70 * (ep))+#define ENDP_INIT_MODE(ep) (0x820 + 0x70 * (ep))+#define ENDP_INIT_AGGR(ep) (0x824 + 0x70 * (ep))+#define ENDP_INIT_HOL_BLOCK_EN(ep) (0x82c + 0x70 * (ep))+#define ENDP_INIT_DEAGGR(ep) (0x834 + 0x70 * (ep))+#define ENDP_INIT_RSRC_GRP(ep) (0x838 + 0x70 * (ep))+#define ENDP_INIT_SEQ(ep) (0x83c + 0x70 * (ep))+#define ENDP_STATUS(ep) (0x840 + 0x70 * (ep))+#define IPA_SHARED_MEM_SIZE 0x54 /* bits 31:16: the local memory's offset in 8-byte units */+#define IPA_FILT_ROUT_HASH_FLUSH 0x14c++/* ---- memory the hardware reads and writes ------------------------------------------------------ */++struct dma {+ vm_offset_t virt;+ uint64_t phys;+};++/* One page (16 KB), zeroed, written out of the cache; false if there is none. */+static bool+dma_page(struct dma *d)+{+ vm_offset_t virt = 0;++ if (kmem_alloc(kernel_map, &virt, PAGE_SIZE, KMA_KOBJECT | KMA_ZERO | KMA_DATA, VM_KERN_MEMORY_IOKIT) != KERN_SUCCESS) {+ return false;+ }+ d->virt = virt;+ d->phys = kvtophys(virt);+ FlushPoC_DcacheRegion(virt, PAGE_SIZE);+ return true;+}++/* Written back and dropped from the cache: before the hardware reads it, and before we read what the hardware wrote. */+static inline void+dma_sync(vm_offset_t virt, size_t size)+{+ vm_offset_t from = virt & ~63ul;++ FlushPoC_DcacheRegion(from, ((virt + size + 63) & ~63ul) - from);+ __asm__ volatile ("dsb sy" ::: "memory");+}++/* ---- the channels ------------------------------------------------------------------------------ */++struct tre {+ uint64_t addr;+ uint16_t len_opcode; /* bytes to transfer, or the immediate command's opcode */+ uint16_t reserved;+ uint32_t flags; /* TRE_* */+};+#define TRE_CHAIN (1u << 0)+#define TRE_IEOT (1u << 9) /* an event when done */+#define TRE_BEI (1u << 10) /* ... but no interrupt for it */+#define TRE_TYPE_XFER (2u << 16)+#define TRE_TYPE_COMMAND (3u << 16)++struct event {+ uint64_t xfer; /* the address of the TRE that finished */+ uint16_t len; /* bytes moved (what a receive buffer got) */+ uint8_t reserved1;+ uint8_t code;+ uint16_t reserved2;+ uint8_t type;+ uint8_t chid;+};++struct channel {+ const char * name;+ uint8_t id, ring_id, endpoint; /* the channel, its event ring, the IPA's endpoint */+ bool to_ipa, command, qmap, aggregate, close_eof;+ uint32_t slots; /* TREs in the ring, and buffers (a power of two; they fit one page: at most 1024) */+ uint32_t tlv; /* the endpoint's TLV FIFO: how many TREs may be outstanding (ipa_data-v4.11.c tlv_count) */+ uint32_t buffer_size; /* bytes per slot (a divisor or a multiple of the page size) */+ struct dma tre_ring, event_ring;+ struct dma * pages; /* the buffers, slot by slot */+ uint32_t page_count;+ uint32_t next; /* the next TRE to fill (counts up; the slot is next % slots) */+ uint32_t done; /* the next TRE whose completion is awaited (transmit) */+ uint32_t events; /* the next event to read (counts up) */+ bool started;+ uint64_t packets, bytes, dropped, errors;+};++/*+ * The four: numbers from Linux's ipa_data-v4.11.c (channel, endpoint, TLV counts, which has+ * QMAP and aggregation). Rings here are smaller than Linux's; the buffers are a page for a receive+ * slot (the IPA aggregates into it) and 2 KB for a transmit slot (one packet and its header).+ */+static struct channel command = { "command", 5, 0, 7, true, true, false, false, false, 16, 20, 64 };+#define RECEIVE_BUFFER 16384 /* a page: the IPA aggregates into it */+static struct channel lan_rx = { "lan-rx", 14, 1, 9, false, false, false, true, false, 16, 9, RECEIVE_BUFFER };+static struct channel modem_tx = { "modem-tx", 2, 2, 2, true, false, true, false, false, 64, 16, 2048 };+static struct channel modem_rx = { "modem-rx", 7, 3, 16, false, false, true, true, true, 64, 9, RECEIVE_BUFFER };+static struct channel *channels[] = { &command, &lan_rx, &modem_tx, &modem_rx };+#define AGGR_LIMIT_KB 12 /* the IPA closes a receive buffer once this much is in it (a page holds another 4 KB packet) */+#define AGGR_TIME_TICKS 5 /* ... or after 5 ticks of the first pulse generator: 500 us (TIMERS_PULSE_GRAN_CFG gran 0 = 100 us) */++static bool ready, trace;+static uint32_t mem_offset; /* the local memory's offset within the IPA's shared memory */+static struct dma table, zero; /* the tables' page (below) and a page of zeros */++static inline vm_offset_t+slot_virt(const struct channel *ch, uint32_t slot)+{+ uint64_t at = (uint64_t)slot * ch->buffer_size;++ return ch->pages[at / PAGE_SIZE].virt + at % PAGE_SIZE;+}++static inline uint64_t+slot_phys(const struct channel *ch, uint32_t slot)+{+ uint64_t at = (uint64_t)slot * ch->buffer_size;++ return ch->pages[at / PAGE_SIZE].phys + at % PAGE_SIZE;+}++static inline struct tre *+tre_at(const struct channel *ch, uint32_t index)+{+ return (struct tre *)(ch->tre_ring.virt + (index % ch->slots) * ELEMENT_SIZE);+}++static bool+channel_memory(struct channel *ch)+{+ uint64_t bytes = (uint64_t)ch->slots * ch->buffer_size;++ ch->page_count = (uint32_t)((bytes + PAGE_SIZE - 1) / PAGE_SIZE);+ ch->pages = kalloc_type(struct dma, ch->page_count, Z_WAITOK | Z_ZERO);+ if (ch->pages == NULL || !dma_page(&ch->tre_ring) || !dma_page(&ch->event_ring)) {+ return false;+ }+ for (uint32_t p = 0; p < ch->page_count; p++) {+ if (!dma_page(&ch->pages[p])) {+ return false;+ }+ }+ return true;+}++static void+gsi_error(const char *what)+{+ uint32_t log = gsi_rd(ERROR_LOG);++ printf("ipa: %s: GSI status %#x, error log %#x (code %u, type %u, EE %u, index %u, args %#x), global %#x, general %#x\n", what,+ gsi_rd(GSI_STATUS), log, (log >> 12) & 0xf, (log >> 24) & 0xf, log >> 28, (log >> 19) & 0x1f, log & 0xfff,+ gsi_rd(CNTXT_GLOB_IRQ_STTS), gsi_rd(CNTXT_GSI_IRQ_STTS));+ if (log != 0) {+ gsi_wr(ERROR_LOG, 0);+ gsi_wr(ERROR_LOG_CLR, ~0u);+ }+}++static inline uint32_t+channel_state(const struct channel *ch)+{+ return (gsi_rd(CH_CNTXT(ch->id, 0)) >> 20) & 0xf;+}++static inline uint32_t+event_ring_state(const struct channel *ch)+{+ return (gsi_rd(EV_CNTXT(ch->ring_id, 0)) >> 20) & 0xf;+}++/* A command to the GSI about a channel or an event ring; true once the state is `wanted` (within 50 ms). */+static bool+gsi_command(struct channel *ch, bool event, uint32_t opcode, uint32_t wanted)+{+ uint32_t state = 0, number = event ? ch->ring_id : ch->id;++ gsi_wr(event ? EV_CH_CMD : CH_CMD, number | opcode << 24);+ for (unsigned us = 0; us < 50000; us += 100) {+ state = event ? event_ring_state(ch) : channel_state(ch);+ if (state == wanted) {+ break;+ }+ delay_for_interval(100, NSEC_PER_USEC);+ }+ /* (the completion is also flagged as an interrupt source, masked: cleared) */+ gsi_wr(event ? CNTXT_SRC_EV_CH_IRQ_CLR : CNTXT_SRC_CH_IRQ_CLR, 1u << number);+ if (state != wanted) {+ printf("ipa: %s: command %#x on %s %u leaves it in state %u, not %u\n", ch->name, opcode, event ? "event ring" : "channel", number,+ state, wanted);+ gsi_error(ch->name);+ return false;+ }+ return true;+}++/* As Linux's gsi_irq_setup(): interrupts, not MSIs; every source masked (nothing is handled here: the rings are polled). */+static void+gsi_interrupts_off(void)+{+ gsi_wr(CNTXT_INTSET, 1);+ gsi_wr(CNTXT_TYPE_IRQ_MSK, 0);+ gsi_wr(CNTXT_SRC_CH_IRQ_MSK, 0);+ gsi_wr(CNTXT_SRC_EV_CH_IRQ_MSK, 0);+ gsi_wr(CNTXT_GLOB_IRQ_EN, 0);+ gsi_wr(CNTXT_SRC_IEOB_IRQ_MSK, 0);+ gsi_wr(INTER_EE_SRC_CH_IRQ_MSK, 0);+ gsi_wr(INTER_EE_SRC_EV_CH_IRQ_MSK, 0);+ gsi_wr(CNTXT_GSI_IRQ_EN, 0);+}++/* As Linux's gsi_evt_ring_program() and gsi_channel_program(), for the GPI protocol. */+static bool+channel_setup(struct channel *ch)+{+ uint32_t e = ch->ring_id, c = ch->id, value;++ if (!gsi_command(ch, true, GSI_EVT_ALLOCATE, EV_STATE_ALLOCATED)) {+ return false;+ }+ gsi_wr(EV_CNTXT(e, 0), GSI_CHANNEL_TYPE_GPI | 1u << 16 /* INTYPE: interrupt, not MSI */ | ELEMENT_SIZE << 24);+ gsi_wr(EV_CNTXT(e, 1), ch->slots * ELEMENT_SIZE);+ gsi_wr(EV_CNTXT(e, 2), (uint32_t)ch->event_ring.phys);+ gsi_wr(EV_CNTXT(e, 3), (uint32_t)(ch->event_ring.phys >> 32));+ gsi_wr(EV_CNTXT(e, 8), 32 /* moderation: 1 ms at 32 kHz */ | 1u << 16 /* MODC */);+ for (unsigned n = 9; n <= 13; n++) {+ gsi_wr(EV_CNTXT(e, n), 0); /* no MSI, no read pointer updates */+ }+ /* "the last processed event": the ring's last entry, as nothing has been processed */+ gsi_wr(EV_DOORBELL(e), (uint32_t)(ch->event_ring.phys + (ch->slots - 1) * ELEMENT_SIZE));++ if (!gsi_command(ch, false, GSI_CH_ALLOCATE, CH_STATE_ALLOCATED)) {+ return false;+ }+ gsi_wr(CH_CNTXT(c, 0), GSI_CHANNEL_TYPE_GPI | (ch->to_ipa ? 1u << 3 : 0) | e << 14 | ELEMENT_SIZE << 24);+ gsi_wr(CH_CNTXT(c, 1), ch->slots * ELEMENT_SIZE);+ gsi_wr(CH_CNTXT(c, 2), (uint32_t)ch->tre_ring.phys);+ gsi_wr(CH_CNTXT(c, 3), (uint32_t)(ch->tre_ring.phys >> 32));+ /* QOS: the command channel gets the lowest round-robin weight and no escape buffer; the doorbell counts bytes */+ value = (ch->command ? 0xf : 0) | (ch->command ? 0 : 1u << 10 /* PREFETCH_MODE: escape buffer only */) | 1u << 24;+ gsi_wr(CH_QOS(c), value);+ /* the GPI scratch: the most outstanding TREs (in bytes), the threshold 2 TREs */+ gsi_wr(CH_SCRATCH(c, 0), (ch->tlv * ELEMENT_SIZE) << 16);+ gsi_wr(CH_SCRATCH(c, 1), (2 * ELEMENT_SIZE) << 16);+ gsi_wr(CH_SCRATCH(c, 2), 0);+ gsi_wr(CH_SCRATCH(c, 3), gsi_rd(CH_SCRATCH(c, 3)) & 0xffff);+ return true;+}++/* As Linux's ipa_endpoint_program() for IPA 4.11, with no checksum offload and no status. */+static void+endpoint_program(const struct channel *ch)+{+ uint32_t ep = ch->endpoint, value;++ ipa_wr(ENDP_INIT_CFG(ep), 0); /* no fragment or checksum offload */+ ipa_wr(ENDP_INIT_NAT(ep), 0); /* NAT bypassed */+ value = 0;+ if (ch->qmap) {+ value = 4 /* HDR_LEN */ | 1u << 6 /* HDR_OFST_METADATA_VALID, at 0 */;+ if (!ch->to_ipa) {+ /* where the IPA writes the mux id (byte 1) and the packet's length (bytes 2-3) of the header it makes */+ value |= 1u << 7 /* HDR_OFST_METADATA */ | 1u << 19 /* HDR_OFST_PKT_SIZE_VALID */ | 2u << 20 /* HDR_OFST_PKT_SIZE */;+ }+ }+ ipa_wr(ENDP_INIT_HDR(ep), value);+ value = 0;+ if (ch->qmap) {+ value = 1 /* HDR_ENDIANNESS: big */;+ if (!ch->to_ipa) {+ value |= 1u << 1 /* HDR_TOTAL_LEN_OR_PAD_VALID (pad) */ | 1u << 3 /* HDR_PAYLOAD_LEN_INC_PADDING */;+ }+ }+ ipa_wr(ENDP_INIT_HDR_EXT(ep), value);+ if (!ch->to_ipa) {+ ipa_wr(ENDP_INIT_HDR_METADATA_MASK(ep), ch->qmap ? 0xff000000 : 0); /* the metadata's low byte, big-endian */+ } else {+ /* the command endpoint moves its data to the LAN receive endpoint (DMA mode); the rest is basic */+ ipa_wr(ENDP_INIT_MODE(ep), ch->command ? 3 | (uint32_t)lan_rx.endpoint << 4 : 0);+ }+ if (!ch->to_ipa && ch->aggregate) {+ value = 1 /* AGGR_EN: aggregate */ | 4u << 2 /* AGGR_TYPE: generic */ | AGGR_LIMIT_KB << 5 | AGGR_TIME_TICKS << 12 |+ (ch->close_eof ? 1u << 23 /* SW_EOF_ACTIVE */ : 0);+ } else if (ch->to_ipa && ch->qmap) {+ value = 2 /* AGGR_EN: deaggregate */ | 6u << 2 /* AGGR_TYPE: QCMAP */;+ } else {+ value = 0;+ }+ ipa_wr(ENDP_INIT_AGGR(ep), value);+ if (!ch->to_ipa) {+ ipa_wr(ENDP_INIT_HOL_BLOCK_EN(ep), 0); /* no head-of-line blocking drops */+ } else {+ ipa_wr(ENDP_INIT_DEAGGR(ep), 0);+ }+ ipa_wr(ENDP_INIT_RSRC_GRP(ep), 0); /* resource group 0: UL/DL (the only one with limits) */+ if (ch->to_ipa) {+ ipa_wr(ENDP_INIT_SEQ(ep), ch->command ? 0 /* DMA */ : 4 /* 2_PASS_SKIP_LAST_UC */);+ }+ ipa_wr(ENDP_STATUS(ep), 0); /* no status packets */+}++/* The TRE at `index` of the channel's ring, filled and written out; the doorbell is rung separately. */+static void+tre_fill(struct channel *ch, uint32_t index, uint64_t addr, uint16_t len_opcode, uint32_t flags)+{+ struct tre *t = tre_at(ch, index);++ t->addr = addr;+ t->len_opcode = len_opcode;+ t->reserved = 0;+ t->flags = flags;+ dma_sync((vm_offset_t)t, sizeof(*t));+}++static inline void+channel_doorbell(struct channel *ch)+{+ gsi_wr(CH_DOORBELL(ch->id), (uint32_t)(ch->tre_ring.phys + (ch->next % ch->slots) * ELEMENT_SIZE));+}++/*+ * The events the hardware has written since last time, each to `each`. The event ring's write+ * pointer is in its context register 4; the doorbell afterwards tells the hardware the last event+ * read, which makes room.+ */+static unsigned+channel_events(struct channel *ch, void (*each)(struct channel *, const struct event *, void *), void *context)+{+ uint32_t wp = gsi_rd(EV_CNTXT(ch->ring_id, 4)), base = (uint32_t)ch->event_ring.phys, index;+ unsigned n = 0;++ if (wp < base || wp >= base + ch->slots * ELEMENT_SIZE) {+ if (ch->errors++ == 0) {+ printf("ipa: %s: the event ring's write pointer %#x is outside the ring at %#x\n", ch->name, wp, base);+ }+ return 0;+ }+ index = (wp - base) / ELEMENT_SIZE;+ while (ch->events % ch->slots != index) {+ struct event *e = (struct event *)(ch->event_ring.virt + (ch->events % ch->slots) * ELEMENT_SIZE);++ dma_sync((vm_offset_t)e, sizeof(*e));+ each(ch, e, context);+ ch->events++;+ n++;+ }+ if (n != 0) {+ gsi_wr(EV_DOORBELL(ch->ring_id), (uint32_t)(ch->event_ring.phys + ((ch->events - 1) % ch->slots) * ELEMENT_SIZE));+ }+ return n;+}++/* ---- immediate commands ------------------------------------------------------------------------- */++#define IPA_CMD_IP_V4_FILTER_INIT 0x3+#define IPA_CMD_IP_V6_FILTER_INIT 0x4+#define IPA_CMD_IP_V4_ROUTING_INIT 0x7+#define IPA_CMD_IP_V6_ROUTING_INIT 0x8+#define IPA_CMD_HDR_INIT_LOCAL 0x9+#define IPA_CMD_DMA_SHARED_MEM 0x13++struct command_done {+ uint64_t tre;+ bool done;+ uint8_t code;+};++static void+command_event(__unused struct channel *ch, const struct event *e, void *context)+{+ struct command_done *waiting = context;++ if (e->xfer == waiting->tre) {+ waiting->done = true;+ waiting->code = e->code;+ }+ command.done++;+}++/* One immediate command, waited for (up to 200 ms). The payload is copied into the slot's buffer. */+static bool+ipa_command(const char *what, uint8_t opcode, const void *payload, size_t size)+{+ uint32_t slot = command.next % command.slots;+ struct command_done waiting = { .tre = command.tre_ring.phys + slot * ELEMENT_SIZE };++ if (size > command.buffer_size || command.next - command.done >= command.slots) {+ return false;+ }+ memcpy((void *)slot_virt(&command, slot), payload, size);+ dma_sync(slot_virt(&command, slot), size);+ tre_fill(&command, command.next, slot_phys(&command, slot), opcode, TRE_TYPE_COMMAND | TRE_IEOT);+ command.next++;+ channel_doorbell(&command);+ for (unsigned us = 0; us < 200000 && !waiting.done; us += 200) {+ channel_events(&command, command_event, &waiting);+ if (!waiting.done) {+ delay_for_interval(200, NSEC_PER_USEC);+ }+ }+ if (!waiting.done) {+ printf("ipa: the command %s (opcode %#x) is not answered in 200 ms; channel state %u\n", what, opcode, channel_state(&command));+ gsi_error(what);+ return false;+ }+ if (trace) {+ printf("ipa: the command %s (opcode %#x) done, code %u\n", what, opcode, waiting.code);+ }+ return true;+}++/*+ * The tables, as Linux's ipa_table_init() lays them out in one buffer: a "zero rule" (8 bytes of+ * zero, which every table entry points at until somebody installs a rule), then the filter+ * table's bitmap of the endpoints that filter (bit n+1 for endpoint n: 2, 5 and 8 -- our modem+ * transmit endpoint and two of the modem's), then as many entries as the longest table (15: the+ * route tables' size, 0x78 bytes), each the zero rule's address. The filter table is the bitmap+ * and 3 entries from offset 8; a route table the 15 entries from offset 16.+ *+ * The IPA's local memory, in the layout the modem driver zeroed (Android's ipa_4_11_mem_part,+ * the same offsets as Linux's ipa_mem_local_data for these): IPv4 filter hashed 0x288, not+ * hashed 0x308, IPv6 0x388/0x408; IPv4 route 0x488/0x508, IPv6 0x588/0x608; the modem's and our+ * headers 0x688, 0x440 bytes in all.+ */+#define FILTERED_ENDPOINTS ((1ull << 2) | (1ull << 5) | (1ull << 8))+#define FILTER_ENTRIES 4 /* the bitmap and one per filtering endpoint */+#define ROUTE_ENTRIES 15++static bool+table_init(const char *what, uint8_t opcode, bool filter, uint32_t hashed_offset, uint32_t offset)+{+ struct {+ uint64_t hash_rules_addr, flags, nhash_rules_addr;+ } payload;+ uint32_t entries = filter ? FILTER_ENTRIES : ROUTE_ENTRIES, size = entries * 8;+ uint64_t source = table.phys + (filter ? 8 : 16);++ payload.hash_rules_addr = source;+ payload.nhash_rules_addr = source;+ payload.flags = (uint64_t)size | (uint64_t)(mem_offset + hashed_offset) << 12 | (uint64_t)size << 28 |+ (uint64_t)(mem_offset + offset) << 40;+ return ipa_command(what, opcode, &payload, sizeof(payload));+}++static bool+tables_setup(void)+{+ uint64_t *t = (uint64_t *)table.virt;+ struct {+ uint64_t hdr_table_addr;+ uint32_t flags, reserved;+ } headers;++ t[0] = 0; /* the zero rule */+ t[1] = FILTERED_ENDPOINTS << 1; /* the filter bitmap */+ for (unsigned n = 0; n < ROUTE_ENTRIES; n++) {+ t[2 + n] = table.phys;+ }+ dma_sync(table.virt, (2 + ROUTE_ENTRIES) * 8);+ if (!table_init("IPv4 route table init", IPA_CMD_IP_V4_ROUTING_INIT, false, 0x488, 0x508) ||+ !table_init("IPv6 route table init", IPA_CMD_IP_V6_ROUTING_INIT, false, 0x588, 0x608) ||+ !table_init("IPv4 filter table init", IPA_CMD_IP_V4_FILTER_INIT, true, 0x288, 0x308) ||+ !table_init("IPv6 filter table init", IPA_CMD_IP_V6_FILTER_INIT, true, 0x388, 0x408)) {+ return false;+ }+ headers.hdr_table_addr = zero.phys;+ headers.flags = 0x440 | (mem_offset + 0x688) << 12;+ headers.reserved = 0;+ if (!ipa_command("header table init", IPA_CMD_HDR_INIT_LOCAL, &headers, sizeof(headers))) {+ return false;+ }+ ipa_wr(IPA_FILT_ROUT_HASH_FLUSH, 0x1111); /* the hashed tables' caches, flushed */+ return true;+}++/* ---- receiving and sending ---------------------------------------------------------------------- */++/* A receive slot handed to the hardware (one TRE for the whole buffer). */+static void+receive_post(struct channel *ch, uint32_t slot)+{+ tre_fill(ch, ch->next, slot_phys(ch, slot), (uint16_t)(ch->buffer_size > 0xffff ? 0xffff : ch->buffer_size), TRE_TYPE_XFER | TRE_IEOT);+ ch->next++;+}++struct receive_context {+ void (*receive)(uint8_t mux, const uint8_t *packet, size_t length);+ unsigned packets;+};++/* A receive buffer is full (or closed): the QMAP packets in it, one by one; then the slot is posted again. */+static void+receive_event(struct channel *ch, const struct event *e, void *context)+{+ struct receive_context *rc = context;+ uint32_t slot = (uint32_t)((e->xfer - ch->tre_ring.phys) / ELEMENT_SIZE), length = e->len;+ const uint8_t *buffer;++ if (slot >= ch->slots || e->xfer < ch->tre_ring.phys) {+ if (ch->errors++ < 4) {+ printf("ipa: %s: an event for TRE %#llx, outside the ring at %#llx\n", ch->name, e->xfer, ch->tre_ring.phys);+ }+ return;+ }+ if (slot != ch->next % ch->slots) {+ if (ch->errors++ < 4) {+ printf("ipa: %s: slot %u finished while slot %u was expected\n", ch->name, slot, ch->next % ch->slots);+ }+ }+ buffer = (const uint8_t *)slot_virt(ch, slot);+ if (length > ch->buffer_size) {+ length = ch->buffer_size;+ }+ dma_sync((vm_offset_t)buffer, length);+ ch->bytes += length;+ if (trace) {+ printf("ipa: %s: slot %u: %u bytes (code %u): %02x %02x %02x %02x %02x %02x %02x %02x ...\n", ch->name, slot, length, e->code,+ buffer[0], buffer[1], buffer[2], buffer[3], buffer[4], buffer[5], buffer[6], buffer[7]);+ }+ if (ch->qmap) {+ for (uint32_t at = 0; at + 4 <= length;) {+ uint32_t pad = buffer[at] & 0x3f, cmd = buffer[at] & 0x80, mux = buffer[at + 1];+ uint32_t packet = (uint32_t)buffer[at + 2] << 8 | buffer[at + 3];++ if (packet == 0 || at + 4 + packet > length || pad > packet) {+ break;+ }+ if (cmd == 0) {+ ch->packets++;+ rc->packets++;+ if (rc->receive != NULL) {+ rc->receive((uint8_t)mux, buffer + at + 4, packet - pad);+ }+ } else if (trace) {+ printf("ipa: %s: a QMAP command (%u bytes) on mux %u\n", ch->name, packet, mux);+ }+ at += 4 + packet;+ }+ } else {+ ch->packets++; /* the LAN endpoint: looked at, dropped */+ }+ /* the slot posted again -- the one at the ring's next TRE, which is this one while the hardware finishes in order */+ receive_post(ch, ch->next % ch->slots);+ channel_doorbell(ch);+}++static void+transmit_event(struct channel *ch, const struct event *e, __unused void *context)+{+ uint32_t slot = (uint32_t)((e->xfer - ch->tre_ring.phys) / ELEMENT_SIZE);++ if (slot != ch->done % ch->slots && ch->errors++ < 4) {+ printf("ipa: %s: slot %u finished while slot %u was expected (code %u)\n", ch->name, slot, ch->done % ch->slots, e->code);+ }+ ch->done++;+}++bool+hakios_ipa_transmit(uint8_t mux, const void *packet, size_t length)+{+ struct channel *ch = &modem_tx;+ uint32_t slot;+ uint8_t *buffer;++ if (!ready || length == 0 || length + 4 > ch->buffer_size) {+ return false;+ }+ lck_mtx_lock(&ipa_lock);+ channel_events(ch, transmit_event, NULL);+ if (ch->next - ch->done >= ch->slots) {+ ch->dropped++;+ lck_mtx_unlock(&ipa_lock);+ return false;+ }+ slot = ch->next % ch->slots;+ buffer = (uint8_t *)slot_virt(ch, slot);+ buffer[0] = 0; /* no pad, not a command */+ buffer[1] = mux;+ buffer[2] = (uint8_t)(length >> 8);+ buffer[3] = (uint8_t)length;+ memcpy(buffer + 4, packet, length);+ dma_sync((vm_offset_t)buffer, length + 4);+ tre_fill(ch, ch->next, slot_phys(ch, slot), (uint16_t)(length + 4), TRE_TYPE_XFER | TRE_IEOT | TRE_BEI);+ ch->next++;+ channel_doorbell(ch);+ ch->packets++;+ ch->bytes += length;+ if (trace) {+ printf("ipa: %s: slot %u: %zu bytes on mux %u\n", ch->name, slot, length, mux);+ }+ lck_mtx_unlock(&ipa_lock);+ return true;+}++unsigned+hakios_ipa_poll(void (*receive)(uint8_t mux, const uint8_t *packet, size_t length))+{+ struct receive_context rc = { receive, 0 };++ if (!ready) {+ return 0;+ }+ lck_mtx_lock(&ipa_lock);+ channel_events(&modem_rx, receive_event, &rc);+ channel_events(&lan_rx, receive_event, &rc);+ channel_events(&modem_tx, transmit_event, NULL);+ lck_mtx_unlock(&ipa_lock);+ return rc.packets;+}++bool+hakios_ipa_data_ready(void)+{+ return ready;+}++void+hakios_ipa_status(char *to, size_t size)+{+ snprintf(to, size, "to the modem %llu packets (%llu bytes, %llu dropped), from it %llu (%llu bytes), %llu to the LAN endpoint; "+ "errors %llu/%llu/%llu; channels %u/%u/%u/%u", modem_tx.packets, modem_tx.bytes, modem_tx.dropped, modem_rx.packets, modem_rx.bytes,+ lan_rx.packets, modem_tx.errors, modem_rx.errors, lan_rx.errors, channel_state(&command), channel_state(&lan_rx),+ channel_state(&modem_tx), channel_state(&modem_rx));+}++/* ---- setting up ---------------------------------------------------------------------------------- */++bool+hakios_ipa_data_setup(void)+{+ uint32_t status, shared;+ char line[256];++ if (ready) {+ return true;+ }+ {+ uint32_t off = 0;++ if (PE_parse_boot_argn("modem_ipa_data_off", &off, sizeof(off)) && off != 0) {+ printf("ipa: no data path (modem_ipa_data_off)\n");+ return false;+ }+ PE_parse_boot_argn("modem_ipa_data_trace", &off, sizeof(off));+ trace = off != 0;+ }+ if (PAGE_SIZE != RECEIVE_BUFFER) {+ printf("ipa: pages of %lu bytes, not %u: no data path\n", (unsigned long)PAGE_SIZE, RECEIVE_BUFFER);+ return false;+ }+ if (ipa_regs == 0) {+ ipa_regs = ml_io_map(IPA_REGS_PHYS, IPA_REGS_SIZE);+ gsi_regs = ml_io_map(GSI_PHYS + GSI_FROM, GSI_SIZE);+ }+ if (ipa_regs == 0 || gsi_regs == 0) {+ printf("ipa: the registers cannot be mapped: no data path\n");+ return false;+ }+ status = gsi_rd(GSI_STATUS);+ shared = ipa_rd(IPA_SHARED_MEM_SIZE);+ mem_offset = 8 * (shared >> 16);+ if ((status & 1) == 0) {+ printf("ipa: the GSI is not enabled (status %#x): no data path\n", status);+ return false;+ }+ if (!dma_page(&table) || !dma_page(&zero)) {+ printf("ipa: no memory for the tables: no data path\n");+ return false;+ }+ for (unsigned n = 0; n < 4; n++) {+ if (!channel_memory(channels[n])) {+ printf("ipa: no memory for the %s channel: no data path\n", channels[n]->name);+ return false;+ }+ }+ printf("ipa: setting up this processor's data path: GSI status %#x, local memory at %#x; rings and buffers in DDR from %#llx "+ "(the tables at %#llx)\n", status, mem_offset, modem_rx.pages[0].phys, table.phys);+ gsi_interrupts_off();+ for (unsigned n = 0; n < 4; n++) {+ struct channel *ch = channels[n];++ if (!channel_setup(ch)) {+ printf("ipa: the %s channel (%u, event ring %u) cannot be set up: no data path\n", ch->name, ch->id, ch->ring_id);+ return false;+ }+ endpoint_program(ch);+ }+ for (unsigned n = 0; n < 4; n++) {+ struct channel *ch = channels[n];++ if (!gsi_command(ch, false, GSI_CH_START, CH_STATE_STARTED)) {+ printf("ipa: the %s channel does not start: no data path\n", ch->name);+ return false;+ }+ ch->started = true;+ if (!ch->to_ipa) {+ for (uint32_t slot = 0; slot < ch->slots; slot++) {+ receive_post(ch, slot);+ }+ channel_doorbell(ch);+ }+ }+ if (!tables_setup()) {+ printf("ipa: the IPA does not take its tables: no data path (the channels stay)\n");+ return false;+ }+ ready = true;+ hakios_ipa_status(line, sizeof(line));+ printf("ipa: THE DATA PATH IS UP: endpoints %u (commands), %u (LAN in), %u (to the modem), %u (from the modem); the tables set; %s\n",+ command.endpoint, lan_rx.endpoint, modem_tx.endpoint, modem_rx.endpoint, line);+ return true;+}diff --git a/xnu/files/bsd/dev/hakios.mpss.c b/xnu/files/bsd/dev/hakios.mpss.cindex 73b1a47..3b63a16 100644--- a/xnu/files/bsd/dev/hakios.mpss.c+++ b/xnu/files/bsd/dev/hakios.mpss.c@@ -77,6 +77,7 @@#include <sys/vnode_internal.h>#include <vm/vm_kern.h>#include <sys/hakios.input.h>+#include <sys/hakios.ipa.h>#include <sys/hakios.nas.h>#include <sys/hakios.qrtr.h>#include <sys/sysctl.h>@@ -2096,6 +2097,11 @@ ipa_space_on(void)}soc[(IPA_IMEM >> 21) & 0x1ff] = IPA_IMEM | IPA_BLOCK_DEVICE;root[IPA_SPACE_BASE >> 30] = kvtophys((vm_offset_t)ddr) | IPA_TABLE;+ /* the rest of DDR (the phone has 6 or 8 GB from 0x80000000), as 1 GB blocks of the root: the data path's rings and+ * buffers (hakios.ipa.c) are wherever the kernel's memory is */+ for (unsigned g = (IPA_SPACE_BASE >> 30) + 1; g < (IPA_SPACE_BASE >> 30) + 8; g++) {+ root[g] = ((uint64_t)g << 30) | IPA_BLOCK;+ }root[IPA_IMEM >> 30] = kvtophys((vm_offset_t)soc) | IPA_TABLE;FlushPoC_DcacheRegion(ipa_space.tables, 3 * 4096);settle();@@ -2344,6 +2350,10 @@ ipa_firmware_load(void)if (!option("modem_ipa_raw")) {ipa_memory_init();ipa_hardware_init();+ /* this processor's own channels and endpoints, and the IPA's tables, before the modem (hakios.ipa.c); then en1 on them */+ if (hakios_ipa_data_setup()) {+ hakios_cell_attach();+ }}ok = true;out:@@ -5309,10 +5319,75 @@ static bool keep; /* (defined below: the DSP and the link#define QMI_WDS 0x01#define WDS_START_NETWORK_INTERFACE 0x0020#define WDS_GET_CURRENT_SETTINGS 0x002d-static struct hakios_qrtr_port *wds_port;-static uint32_t wds_node, wds_port_number;-static volatile bool wds_started, wds_up;+#define WDS_BIND_MUX_DATA_PORT 0x00a2+#define QMI_WDA 0x1a+#define WDA_SET_DATA_FORMAT 0x0020+#define DATA_ENDPOINT_EMBEDDED 4 /* the IPA, "interface" 1: where the packets of this session go (as ModemManager binds it) */+#define DATA_ENDPOINT_INTERFACE 1+#define DATA_MUX 1 /* the QMAP mux id (hakios.cell.c carries mux 1) */+static struct hakios_qrtr_port *wds_port, *wda_port;+static uint32_t wds_node, wds_port_number, wda_node, wda_port_number;+static volatile bool wds_started, wds_up, wds_bound, wda_set;static uint32_t wds_handle;+static void wds_send_start(void);++/*+ * Before the session: the modem is told how the packets of the embedded port (the IPA) are+ * framed -- raw IP in QMAP, without checksum offload, aggregated up to 16 packets or 14 KB+ * downlink -- (WDA Set Data Format 0x20, as ModemManager does for the IPA), and our WDS client is+ * bound to QMAP mux 1 of that port (WDS Bind Mux Data Port 0xa2), so that this session's packets+ * are the ones with mux 1 that hakios.ipa.c sends and receives.+ */+static void+wda_receive(__unused void *context, __unused uint32_t node, __unused uint32_t port, const void *data, size_t length)+{+ const uint8_t *m = data;+ uint16_t size = 0;+ const uint8_t *v;+ uint32_t result = ~0u, error = ~0u, link = 0, ul = 0, dl = 0;++ if (length < 7 || m[0] != 2 || (uint16_t)(m[3] | m[4] << 8) != WDA_SET_DATA_FORMAT) {+ return;+ }+ probe_dump("wda", m, length);+ if ((v = qmi_tlv(m, length, 2, &size)) != NULL && size >= 4) {+ result = (uint32_t)(v[0] | v[1] << 8);+ error = (uint32_t)(v[2] | v[3] << 8);+ }+ if ((v = qmi_tlv(m, length, 0x11, &size)) != NULL && size >= 4) { link = (uint32_t)(v[0] | v[1] << 8 | v[2] << 16 | v[3] << 24); }+ if ((v = qmi_tlv(m, length, 0x12, &size)) != NULL && size >= 4) { ul = (uint32_t)(v[0] | v[1] << 8 | v[2] << 16 | v[3] << 24); }+ if ((v = qmi_tlv(m, length, 0x13, &size)) != NULL && size >= 4) { dl = (uint32_t)(v[0] | v[1] << 8 | v[2] << 16 | v[3] << 24); }+ wda_set = result == 0;+ tell("mpss: wda: the data format %s: result %u error %u; link layer %u (2: raw IP), aggregation up %u down %u (5: QMAP)\n",+ result == 0 ? "is set" : "IS REFUSED", result, error, link, ul, dl);+}++static void+wda_server(__unused void *context, bool arrived, uint32_t service, __unused uint32_t version, __unused uint32_t instance, uint32_t node,+ uint32_t port)+{+ if (service != QMI_WDA) {+ return;+ }+ if (arrived) {+ /* raw IP, QMAP both ways, downlink at most 16 packets or 14 KB per aggregate, on the embedded port */+ uint8_t request[7 + 7 + 7 + 7 + 7 + 7 + 11] = { 0, 0x43, 0, WDA_SET_DATA_FORMAT & 0xff, WDA_SET_DATA_FORMAT >> 8, 0, 0,+ 0x11, 4, 0, 2, 0, 0, 0,+ 0x12, 4, 0, 5, 0, 0, 0,+ 0x13, 4, 0, 5, 0, 0, 0,+ 0x15, 4, 0, 16, 0, 0, 0,+ 0x16, 4, 0, 0x00, 0x38, 0, 0,+ 0x17, 8, 0, DATA_ENDPOINT_EMBEDDED, 0, 0, 0, DATA_ENDPOINT_INTERFACE, 0, 0, 0 };++ wda_node = node;+ wda_port_number = port;+ request[5] = sizeof(request) - 7;+ tell("mpss: wda: about to set the data format of the embedded port: raw IP in QMAP, no checksum offload\n");+ qrtr_send(wda_port, node, port, request, sizeof(request));+ } else if (node == wda_node && port == wda_port_number) {+ wda_node = wda_port_number = 0;+ }+}static voidip4_string(char *to, size_t size, uint32_t address)@@ -5353,6 +5428,17 @@ wds_receive(__unused void *context, __unused uint32_t node, __unused uint32_t potell("mpss: wds: THE DATA SESSION IS REFUSED: result %u, error %u, call end reason %u\n", result, error, reason);wds_started = false; /* (asked again on the next change of NAS's state) */}+ } else if (m[0] == 2 && message == WDS_BIND_MUX_DATA_PORT) {+ uint32_t result = ~0u, error = ~0u;++ if ((v = qmi_tlv(m, length, 2, &size)) != NULL && size >= 4) {+ result = (uint32_t)(v[0] | v[1] << 8);+ error = (uint32_t)(v[2] | v[3] << 8);+ }+ wds_bound = result == 0;+ tell("mpss: wds: the client %s to mux %u of the embedded port (result %u, error %u); the session is started %s\n",+ wds_bound ? "is bound" : "IS NOT BOUND", DATA_MUX, result, error, wds_bound ? "on it" : "all the same");+ wds_send_start();} else if (m[0] == 2 && message == WDS_GET_CURRENT_SETTINGS) {uint32_t ip = 0, gw = 0, mask = 0, dns1 = 0, dns2 = 0, mtu = 0;char a[20], g[20], d1[20], d2[20], mk[20];@@ -5377,6 +5463,9 @@ wds_receive(__unused void *context, __unused uint32_t node, __unused uint32_t powds_up = true;}tell("mpss: wds: THE DATA SESSION'S SETTINGS: address %s, gateway %s, netmask %s, DNS %s %s, MTU %u\n", a, g, mk, d1, d2, mtu);+ if (ip != 0) {+ hakios_cell_session(true, ip, mask, gw, dns1, dns2, mtu); /* en1 (hakios.cell.c) */+ }}}@@ -5404,20 +5493,44 @@ wds_open(void)qrtr_lookup(wds_port, QMI_WDS, 0, 0);}}+ if (wda_port == NULL && !option("modem_data_off")) {+ wda_port = qrtr_open(wda_receive, wda_server, NULL);+ if (wda_port != NULL) {+ qrtr_lookup(wda_port, QMI_WDA, 0, 0);+ }+ }}-/* The session, started: from the link's thread, when NAS says the modem is registered. */+/* The session, started: from the link's thread, when NAS says the modem is registered. First the binding to the mux. */static voidwds_start(void)+{+ uint8_t bind[7 + 11 + 4] = { 0, 0x44, 0, WDS_BIND_MUX_DATA_PORT & 0xff, WDS_BIND_MUX_DATA_PORT >> 8, 15, 0,+ 0x10, 8, 0, DATA_ENDPOINT_EMBEDDED, 0, 0, 0, DATA_ENDPOINT_INTERFACE, 0, 0, 0,+ 0x11, 1, 0, DATA_MUX };++ if (wds_port == NULL || wds_port_number == 0 || wds_started) {+ return;+ }+ wds_started = true;+ if (option("modem_data_nobind")) {+ wds_send_start();+ return;+ }+ tell("mpss: wds: about to bind the client to mux %u of the embedded port (the IPA)\n", DATA_MUX);+ qrtr_send(wds_port, wds_node, wds_port_number, bind, sizeof(bind));+}++static void+wds_send_start(void){uint8_t request[7 + 4 + 3 + 100];unsigned at = 7;char apn[64] = "";- if (wds_port == NULL || wds_port_number == 0 || wds_started) {+ if (wds_port == NULL || wds_port_number == 0) {return;}- wds_started = true;request[0] = 0; request[1] = 0x41; request[2] = 0;request[3] = WDS_START_NETWORK_INTERFACE & 0xff; request[4] = WDS_START_NETWORK_INTERFACE >> 8;request[at++] = 0x19; request[at++] = 1; request[at++] = 0; request[at++] = 4; /* IPv4 */@@ -5440,8 +5553,15 @@ wds_close(void)qrtr_close(wds_port);wds_port = NULL;}- wds_node = wds_port_number = 0;- wds_started = wds_up = false;+ if (wda_port != NULL) {+ qrtr_close(wda_port);+ wda_port = NULL;+ }+ wds_node = wds_port_number = wda_node = wda_port_number = 0;+ wds_started = wds_up = wds_bound = wda_set = false;+ if (cellular_data) {+ hakios_cell_session(false, 0, 0, 0, 0, 0, 0);+ }cellular_data = 0;cellular_ip[0] = cellular_gateway[0] = cellular_dns[0] = 0;}@@ -5546,7 +5666,9 @@ uim_receive(__unused void *context, __unused uint32_t node, __unused uint32_t poif (card == 1 && state == 7 && sim_slot_ready == 0) {sim_slot_ready = slot + 1;}- if (slot == 0 && card == 1 && state == 7 && (type == 2 || type == 1) && aid <= 32 && at + 7 + aid <= size) {+ /* a USIM (or SIM) in logical slot 1 that is READY, or only "detected" (cycle 37: the card sits in slot 1 with its+ * application detected and never initialized, as no provisioning session names it): either is provisioned below */+ if (slot == 0 && card == 1 && (state == 7 || state == 1) && (type == 2 || type == 1) && aid <= 32 && at + 7 + aid <= size) {ready_aid[0] = (uint8_t)aid;memcpy(ready_aid + 1, v + at + 7, aid);}@@ -5580,7 +5702,8 @@ uim_receive(__unused void *context, __unused uint32_t node, __unused uint32_t pon += ready_aid[0];pr[5] = (uint8_t)(n - 7); pr[6] = (uint8_t)((n - 7) >> 8);sim_provisioned = true;- tell("mpss: uim: THE USIM OF SLOT 1 IS MADE THE PRIMARY GW APPLICATION (AID of %u bytes)\n", ready_aid[0]);+ tell("mpss: uim: THE USIM OF SLOT 1 IS MADE THE PRIMARY GW APPLICATION (AID of %u bytes; its state is looked at again)\n",+ ready_aid[0]);qrtr_send(uim_port, uim_node, uim_port_number, pr, n);}if (first_card != 1 && sim_slot_ready > 1 && !sim_slot_switched && !option("modem_sim_switch_off") && uim_port != NULL) {diff --git a/xnu/files/bsd/dev/hakios.net.c b/xnu/files/bsd/dev/hakios.net.cindex 84fa548..5714d38 100644--- a/xnu/files/bsd/dev/hakios.net.c+++ b/xnu/files/bsd/dev/hakios.net.c@@ -10,6 +10,8 @@** What carries the frames is a link driver's business; sys/hakios.net.h is all that the two* know of each other. The first link is QEMU's virtio network device (hakios.virtio_net.c).+ * There can be two interfaces: en0 for the Wi-Fi (or virtio), en1 for the modem's packets+ * through the IPA (hakios.cell.c); each has its link, its state and its thread.*/#include <kern/clock.h>#include <kern/locks.h>@@ -35,15 +37,33 @@extern void HakiosWLANStart(const char *interface, const uint8_t *address); /* iokit/Kernel/hakios.wlan.cpp */static LCK_GRP_DECLARE(net_lck_grp, "hakios-net");-static LCK_MTX_DECLARE(net_tx_lock, &net_lck_grp);-static const struct hakios_net_link *net_link;-static bool net_link_up;-static ifnet_t net_ifp;-/* What has gone through: said once a minute while anything moves. */-static struct {- uint64_t sent, received, sent_bytes, received_bytes, dropped_out, dropped_in;-} net_count;+/* One interface: enN on its link. */+struct net_if {+ unsigned unit;+ const struct hakios_net_link *link;+ bool up; /* the link says frames can pass */+ ifnet_t ifp;+ lck_mtx_t tx_lock; /* one frame at a time to the link */+ /* What has gone through: said once a minute while anything moves. */+ struct {+ uint64_t sent, received, sent_bytes, received_bytes, dropped_out, dropped_in;+ } count;+};+static struct net_if net_ifs[HAKIOS_NET_UNITS];++static inline struct net_if *+net_if_of(ifnet_t ifp)+{+ return ifnet_softc(ifp);+}++/* The interface on unit `unit`, once attached; NULL before. */+static struct net_if *+net_if_unit(unsigned unit)+{+ return unit < HAKIOS_NET_UNITS && net_ifs[unit].ifp != NULL ? &net_ifs[unit] : NULL;+}/** Boot-arg net_trace=N: a line in the log for each of the first N frames, either way.@@ -122,58 +142,68 @@ trace_packet(mbuf_t packet, size_t length)static errno_tnet_output(ifnet_t ifp, mbuf_t packet){+ struct net_if *n = net_if_of(ifp);size_t length = mbuf_pkthdr_len(packet);bool sent = false;- if (length <= HAKIOS_NET_FRAME_MAX && net_link_up) {+ if (length <= HAKIOS_NET_FRAME_MAX && n->up) {bpf_tap_out(ifp, DLT_EN10MB, packet, NULL, 0);trace_packet(packet, length);- lck_mtx_lock(&net_tx_lock);- sent = net_link->transmit(packet, length);- lck_mtx_unlock(&net_tx_lock);+ lck_mtx_lock(&n->tx_lock);+ sent = n->link->transmit(packet, length);+ lck_mtx_unlock(&n->tx_lock);}if (sent) {- net_count.sent++;- net_count.sent_bytes += length;+ n->count.sent++;+ n->count.sent_bytes += length;ifnet_stat_increment_out(ifp, 1, (uint32_t)length, 0);} else {- net_count.dropped_out++;+ n->count.dropped_out++;ifnet_stat_increment_out(ifp, 0, 0, 1);}mbuf_freem(packet);return 0;}-/* A frame has arrived. */+/* A frame has arrived on unit `unit`. */void-hakios_net_input(const uint8_t *frame, size_t length)+hakios_net_input_unit(unsigned unit, const uint8_t *frame, size_t length){+ struct net_if *n = net_if_unit(unit);struct ifnet_stat_increment_param stats = { .packets_in = 1, .bytes_in = (uint32_t)length };unsigned int chunks = 1;mbuf_t packet = NULL;char *header;+ if (n == NULL) {+ return;+ }trace_frame("in ", frame, length, length);- if (net_ifp == NULL || length < ETHER_HDR_LEN || length > HAKIOS_NET_FRAME_MAX ||- mbuf_allocpacket(MBUF_DONTWAIT, length, &chunks, &packet) != 0) {- net_count.dropped_in++;+ if (length < ETHER_HDR_LEN || length > HAKIOS_NET_FRAME_MAX || mbuf_allocpacket(MBUF_DONTWAIT, length, &chunks, &packet) != 0) {+ n->count.dropped_in++;return;}if (mbuf_copyback(packet, 0, length, frame, MBUF_DONTWAIT) != 0) {mbuf_freem(packet);- net_count.dropped_in++;+ n->count.dropped_in++;return;}/* as every Ethernet driver hands a frame up: the header noted and stepped over */header = mbuf_data(packet);- mbuf_pkthdr_setrcvif(packet, net_ifp);+ mbuf_pkthdr_setrcvif(packet, n->ifp);mbuf_pkthdr_setheader(packet, header);mbuf_pkthdr_adjustlen(packet, -ETHER_HDR_LEN);mbuf_setdata(packet, header + ETHER_HDR_LEN, length - ETHER_HDR_LEN);- bpf_tap_in(net_ifp, DLT_EN10MB, packet, header, ETHER_HDR_LEN);- net_count.received++;- net_count.received_bytes += length;- ifnet_input(net_ifp, packet, &stats);+ bpf_tap_in(n->ifp, DLT_EN10MB, packet, header, ETHER_HDR_LEN);+ n->count.received++;+ n->count.received_bytes += length;+ ifnet_input(n->ifp, packet, &stats);+}++void+hakios_net_input(const uint8_t *frame, size_t length)+{+ hakios_net_input_unit(0, frame, length);}static unsigned net_ioctls_said;@@ -181,14 +211,15 @@ static unsigned net_ioctls_said;static errno_tnet_ioctl(ifnet_t ifp, u_long command, void *data){+ struct net_if *n = net_if_of(ifp);/* (a radio says it is one here too: IO80211.framework lists the interfaces whose media is 802.11) */- const int media[] = { (net_link->wireless ? IFM_IEEE80211 : IFM_ETHER) | IFM_AUTO };+ const int media[] = { (n->link->wireless ? IFM_IEEE80211 : IFM_ETHER) | IFM_AUTO };struct ifreq *request = data;struct ifmediareq *media_request = data;user_addr_t list;errno_t error = 0;- if (net_link->wireless && net_ioctls_said < 80) {+ if (n->link->wireless && net_ioctls_said < 80) {char who[32] = "?";/* (while iOS's Wi-Fi side is being got to talk to this: who asks the interface what) */@@ -213,7 +244,7 @@ net_ioctl(ifnet_t ifp, u_long command, void *data)CAST_USER_ADDR_T(((struct ifmediareq32 *)media_request)->ifmu_ulist);media_request->ifm_active = media_request->ifm_current = media[0];media_request->ifm_mask = 0;- media_request->ifm_status = IFM_AVALID | (net_link_up ? IFM_ACTIVE : 0);+ media_request->ifm_status = IFM_AVALID | (n->up ? IFM_ACTIVE : 0);if (list != USER_ADDR_NULL && media_request->ifm_count > 0) {error = copyout(media, list, sizeof(media));}@@ -232,7 +263,7 @@ net_ioctl(ifnet_t ifp, u_long command, void *data)break; /* the link hands us everything anyway */default:/* what iOS's Wi-Fi side asks of a radio's interface: bsd/dev/hakios.apple80211.c */- error = net_link->wireless ? hakios_apple80211_ioctl(command, data) : EOPNOTSUPP;+ error = n->link->wireless ? hakios_apple80211_ioctl(command, data) : EOPNOTSUPP;break;}return error;@@ -258,32 +289,41 @@ net_link_event(ifnet_t ifp, uint32_t code)}void-hakios_net_link_state(bool up)+hakios_net_link_state_unit(unsigned unit, bool up){- if (net_ifp == NULL || up == net_link_up) {+ struct net_if *n = net_if_unit(unit);++ if (n == NULL || up == n->up) {return;}- net_link_up = up;- printf("net: the link (%s) is %s\n", net_link->name, up ? "up" : "down");- net_link_event(net_ifp, up ? KEV_DL_LINK_ON : KEV_DL_LINK_OFF);+ n->up = up;+ printf("net: en%u's link (%s) is %s\n", n->unit, n->link->name, up ? "up" : "down");+ net_link_event(n->ifp, up ? KEV_DL_LINK_ON : KEV_DL_LINK_OFF);+}++void+hakios_net_link_state(bool up)+{+ hakios_net_link_state_unit(0, up);}/* The interface's own thread: for a link that wants to be asked, and for the minute's line in the log. */static void-net_thread(__unused void *parameter, __unused wait_result_t result)+net_thread(void *parameter, __unused wait_result_t result){+ struct net_if *n = parameter;uint64_t said = 0, total;unsigned quiet = 0;for (unsigned tick = 1;; tick++) {- quiet = net_link->poll != NULL && net_link->poll() ? 0 : quiet + 1;+ quiet = n->link->poll != NULL && n->link->poll() ? 0 : quiet + 1;/* about once a minute, if anything has moved since */- total = net_count.sent + net_count.received + net_count.dropped_out + net_count.dropped_in;+ total = n->count.sent + n->count.received + n->count.dropped_out + n->count.dropped_in;if (tick % 8192 == 0 && total != said) {said = total;- printf("net: so far %llu frames sent (%llu bytes), %llu received (%llu bytes); dropped: %llu out, %llu in\n",- net_count.sent, net_count.sent_bytes, net_count.received, net_count.received_bytes,- net_count.dropped_out, net_count.dropped_in);+ printf("net: en%u so far %llu frames sent (%llu bytes), %llu received (%llu bytes); dropped: %llu out, %llu in\n",+ n->unit, n->count.sent, n->count.sent_bytes, n->count.received, n->count.received_bytes,+ n->count.dropped_out, n->count.dropped_in);}delay_for_interval(quiet < 100 ? 2 : 10, NSEC_PER_MSEC);}@@ -292,6 +332,9 @@ net_thread(__unused void *parameter, __unused wait_result_t result)boolhakios_net_attach(const struct hakios_net_link *link){+ unsigned unit = link->unit;+ struct net_if *n = unit < HAKIOS_NET_UNITS ? &net_ifs[unit] : NULL;+ char uniqueid[16];struct ifnet_init_eparams init = {.ver = IFNET_INIT_CURRENT_VERSION,.len = sizeof(init),@@ -300,10 +343,11 @@ hakios_net_attach(const struct hakios_net_link *link)* the interface by itself: sockets are all that is asked of it so far.*/.flags = IFNET_INIT_LEGACY | IFNET_INIT_NX_NOAUTO,- .uniqueid = "hakios-en0",+ .uniqueid = uniqueid,.uniqueid_len = 11,.name = "en",- .unit = 0,+ .unit = unit,+ .softc = n,.family = IFNET_FAMILY_ETHERNET,.subfamily = link->wireless ? IFNET_SUBFAMILY_WIFI : IFNET_SUBFAMILY_ANY,.type = IFT_ETHER,@@ -322,16 +366,23 @@ hakios_net_attach(const struct hakios_net_link *link)thread_t thread;errno_t error;- if (net_link != NULL) {- printf("net: en0 is on %s already; %s is not attached\n", net_link->name, link->name);+ if (n == NULL) {+ printf("net: there is no unit %u for %s\n", unit, link->name);+ return false;+ }+ if (n->link != NULL) {+ printf("net: en%u is on %s already; %s is not attached\n", unit, n->link->name, link->name);return false;}- net_link = link;- net_link_up = link->up;+ snprintf(uniqueid, sizeof(uniqueid), "hakios-en%u", unit);+ n->unit = unit;+ n->link = link;+ n->up = link->up;+ lck_mtx_init(&n->tx_lock, &net_lck_grp, LCK_ATTR_NULL);error = ifnet_allocate_extended(&init, &ifp);if (error != 0) {- printf("net: the interface cannot be made: error %d\n", error);- net_link = NULL;+ printf("net: the interface en%u cannot be made: error %d\n", unit, error);+ n->link = NULL;return false;}ifnet_set_capabilities_enabled(ifp, 0, -1);@@ -343,26 +394,26 @@ hakios_net_attach(const struct hakios_net_link *link)ifnet_set_offload(ifp, 0);error = ifnet_attach(ifp, NULL);if (error != 0) {- printf("net: the interface cannot be attached: error %d\n", error);+ printf("net: the interface en%u cannot be attached: error %d\n", unit, error);ifnet_release(ifp);- net_link = NULL;+ n->link = NULL;return false;}ifnet_set_lladdr(ifp, address, ETHER_ADDR_LEN);bpfattach(ifp, DLT_EN10MB, ETHER_HDR_LEN);- net_ifp = ifp;- if (net_link_up) {+ n->ifp = ifp;+ if (n->up) {net_link_event(ifp, KEV_DL_LINK_ON);}if (link->wireless) {/* (a radio's address is the phone's own: not for the log; and iOS's Wi-Fi side finds the interface by a service) */- printf("net: en0 attached on %s (a radio), link %s\n", link->name, net_link_up ? "up" : "down");- HakiosWLANStart("en0", address);+ printf("net: en%u attached on %s (a radio), link %s\n", unit, link->name, n->up ? "up" : "down");+ HakiosWLANStart(uniqueid + 7, address);} else {- printf("net: en0 attached on %s, address %02x:%02x:%02x:%02x:%02x:%02x, link %s\n", link->name, address[0],- address[1], address[2], address[3], address[4], address[5], net_link_up ? "up" : "down");+ printf("net: en%u attached on %s, address %02x:%02x:%02x:%02x:%02x:%02x, link %s\n", unit, link->name, address[0],+ address[1], address[2], address[3], address[4], address[5], n->up ? "up" : "down");}- if (kernel_thread_start(net_thread, NULL, &thread) == KERN_SUCCESS) {+ if (kernel_thread_start(net_thread, n, &thread) == KERN_SUCCESS) {thread_deallocate(thread);}return true;diff --git a/xnu/files/bsd/sys/hakios.ipa.h b/xnu/files/bsd/sys/hakios.ipa.hnew file mode 100644index 0000000..e5f5fa9--- /dev/null+++ b/xnu/files/bsd/sys/hakios.ipa.h@@ -0,0 +1,52 @@+/*+ * The modem's packets: the IPA's data path for this processor (bsd/dev/hakios.ipa.c) and the+ * network interface that stands on it (bsd/dev/hakios.cell.c).+ *+ * The IPA (the SoC's packet engine) carries IP packets between the modem and this processor in+ * QMAP framing: a 4-byte header (pad length, mux id, packet length) before each packet. The+ * driver of the modem (hakios.mpss.c) brings the IPA up; hakios.ipa.c sets up this processor's+ * side of it -- GSI rings, the IPA's endpoints, its tables -- before the modem is started, and+ * then moves packets. hakios.cell.c makes an Ethernet-looking interface (en1) out of that, with+ * an ARP and DHCP responder of its own, so that iOS configures it as it would a USB Ethernet+ * adapter: address, router and DNS come from the modem's data session (QMI WDS), which+ * hakios.mpss.c reports with hakios_cell_session().+ */+#ifndef _SYS_HAKIOS_IPA_H_+#define _SYS_HAKIOS_IPA_H_++#ifdef KERNEL+#include <stdbool.h>+#include <stdint.h>+#include <stddef.h>++/* ---- hakios.ipa.c: the IPA's endpoints for this processor ---- */++/*+ * Set up this processor's channels and endpoints; before the modem starts, with the IPA's clock on,+ * its firmware running and its SMMU context in place (the modem driver's doing). False: no data+ * path (the log says why); everything else goes on without it.+ */+bool hakios_ipa_data_setup(void);+bool hakios_ipa_data_ready(void);+/* One IP packet to the modem on QMAP mux `mux`. Copied. False if dropped (no room, too long). */+bool hakios_ipa_transmit(uint8_t mux, const void *packet, size_t length);+/*+ * Packets from the modem: `receive` is called for each, with its mux id, from the caller's thread.+ * Returns how many there were. Also finishes transmissions (frees their buffers).+ */+unsigned hakios_ipa_poll(void (*receive)(uint8_t mux, const uint8_t *packet, size_t length));+/* What has gone through, for the log. */+void hakios_ipa_status(char *to, size_t size);++/* ---- hakios.cell.c: the interface ---- */++/*+ * Called by the modem driver: the data session is up with these settings (network byte order+ * addresses; mtu 0: unknown), or down. From any thread.+ */+void hakios_cell_session(bool up, uint32_t address, uint32_t mask, uint32_t gateway, uint32_t dns1, uint32_t dns2, uint32_t mtu);+/* Make en1 on the IPA's data path once hakios_ipa_data_setup() has succeeded. */+void hakios_cell_attach(void);++#endif /* KERNEL */+#endif /* _SYS_HAKIOS_IPA_H_ */diff --git a/xnu/files/bsd/sys/hakios.net.h b/xnu/files/bsd/sys/hakios.net.hindex 02e00df..bc52577 100644--- a/xnu/files/bsd/sys/hakios.net.h+++ b/xnu/files/bsd/sys/hakios.net.h@@ -25,9 +25,11 @@#include <sys/kpi_mbuf.h>#define HAKIOS_NET_FRAME_MAX 1514+#define HAKIOS_NET_UNITS 2 /* en0: the radio (or virtio); en1: the modem's packets (hakios.cell.c) */struct hakios_net_link {const char * name; /* for the log */+ unsigned unit; /* which enN this is (0 unless said otherwise) */uint8_t address[6]; /* the interface's Ethernet address */bool wireless; /* the interface is told to be Wi-Fi (its "subfamily"), which is how the* network stack and configd tell a radio from a cable */@@ -47,12 +49,14 @@ struct hakios_net_link {unsigned (*poll)(void);};-/* Make en0 on top of that link (the structure must stay). One link, once: false if there is one already. */+/* Make en<unit> on top of that link (the structure must stay). One link per unit, once: false if there is one already. */bool hakios_net_attach(const struct hakios_net_link *link);-/* A frame has arrived. Copied; the buffer is the caller's again on return. */+/* A frame has arrived (on en0 / on en<unit>). Copied; the buffer is the caller's again on return. */void hakios_net_input(const uint8_t *frame, size_t length);-/* Frames can pass now / can no longer pass. */+void hakios_net_input_unit(unsigned unit, const uint8_t *frame, size_t length);+/* Frames can pass now / can no longer pass (on en0 / on en<unit>). */void hakios_net_link_state(bool up);+void hakios_net_link_state_unit(unsigned unit, bool up);void hakios_net_init(void); /* the links there are: each looks for its hardware (or its boot-arg) *//* an Apple80211 request (SIOCGA80211, SIOCSA80211) for the interface of a radio: hakios.apple80211.c */diff --git a/xnu/hakios.patch b/xnu/hakios.patchindex 34b35d6..769d5f3 100644--- a/xnu/hakios.patch+++ b/xnu/hakios.patch@@ -62,10 +62,10 @@ index a4d25040f38f..aad72993d139 100644kern_debug.o_INCFLAGS += -I$(SRCROOT)/osfmkdiff --git a/bsd/conf/files b/bsd/conf/files-index 44274016a4cf..432af34d4c22 100644+index 44274016a4cf..be702e28890d 100644--- a/bsd/conf/files+++ b/bsd/conf/files-@@ -109,6 +109,39 @@ bsd/dev/munge.c optional config_requires_u32_munging+@@ -109,6 +109,41 @@ bsd/dev/munge.c optional config_requires_u32_mungingbsd/dev/unix_startup.c standardbsd/dev/monotonic.c optional monotonic@@ -77,6 +77,8 @@ index 44274016a4cf..432af34d4c22 100644+bsd/dev/hakios.ufs.c standard+bsd/dev/hakios.ufshc.c standard+bsd/dev/hakios.net.c standard++bsd/dev/hakios.ipa.c standard++bsd/dev/hakios.cell.c standard+bsd/dev/hakios.virtio_net.c standard+bsd/dev/hakios.apple80211.c standard+bsd/dev/hakios.cpufreq.c standard@@ -105,7 +107,7 @@ index 44274016a4cf..432af34d4c22 100644bsd/dev/dev_perfmon.c optional config_perfmonbsd/libkern/crc32.c standard-@@ -155,6 +188,14 @@ bsd/miscfs/devfs/devfs_vfsops.c optional devfs+@@ -155,6 +190,14 @@ bsd/miscfs/devfs/devfs_vfsops.c optional devfsbsd/miscfs/mockfs/mockfs_fsnode.c optional mockfsbsd/miscfs/mockfs/mockfs_vfsops.c optional mockfsbsd/miscfs/mockfs/mockfs_vnops.c optional mockfs@@ -120,7 +122,7 @@ index 44274016a4cf..432af34d4c22 100644bsd/miscfs/routefs/routefs_ops.c optional routefs-@@ -361,6 +402,7 @@ bsd/security/audit/audit_syscalls.c standard+@@ -361,6 +404,7 @@ bsd/security/audit/audit_syscalls.c standardbsd/security/audit/audit_worker.c optional config_auditbsd/pthread/pthread_shims.c standard@@ -128,7 +130,7 @@ index 44274016a4cf..432af34d4c22 100644bsd/pthread/pthread_priority.c standardbsd/pthread/pthread_workqueue.c standard-@@ -383,6 +425,7 @@ bsd/kern/kern_debug.c standard+@@ -383,6 +427,7 @@ bsd/kern/kern_debug.c standardbsd/kern/kern_symfile.c standardbsd/kern/kern_descrip.c standardbsd/kern/kern_guarded.c standard