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
A network interface, and iOS using it: en0 on virtio-net under QEMU
vcvkk4655b2470196
diff --git a/README.md b/README.mdindex 197637e..b0d4272 100644--- a/README.md+++ b/README.md@@ -83,6 +83,14 @@ qemu/run-ios.sh 1200 -display gtk > logs/qemu.log # сеанс на 20 ми- Память гостя — 7 ГБ (ядру достаётся то же окно 4,2 ГБ, что и на телефоне), отображённые из разрежённого файла`qemu/ram.img` (образ системы лежит в нём по нужному смещению). На btrfs/xfs это reflink и места не занимает,на ext4 образ копируется (ещё 2,5 ГБ). Один запущенный QEMU занимает 2,5–3 ГБ памяти компьютера.+- **Сеть (опытно, только в QEMU).** `QEMU_NET=1 qemu/run-ios.sh …` добавляет машине сетевую карту virtio, за+ которой стоит «пользовательская» сеть самого QEMU (DHCP, DNS и выход в сеть компьютера, без прав root); ядро+ делает из неё интерфейс `en0`. Сам по себе интерфейс iOS не настраивает: образ, собранный с+ `RC_JOBS=rc.jobs.net`, при загрузке просит об этом штатный configd (`userland/src/net_test.m`), после чего у+ системы есть адрес, работают DNS (через mDNSResponder) и HTTPS (CFNetwork). Штатные службы тут же начинают+ ходить на серверы Apple (в первые минуты около 30 МБ данных Карт), а приложения Apple — Погода, App Store,+ Подкасты — данных всё равно не получают: им нужна служба `fairplayd`, которой в образе нет. В Настройках+ Wi-Fi остаётся «Выкл.» (это не Wi-Fi). По умолчанию сети нет, и без `QEMU_NET=1` ничего не меняется.- Несколько QEMU сразу: `QEMU_INSTANCE=1 qemu/run-ios.sh …` (у каждого номера свои порты; `touch.py`,`screendump.sh`, `stop.sh` понимают ту же переменную). `qemu/stop.sh` завершает QEMU досрочно.- Прошивка UEFI для aarch64 ищется там, куда её кладёт Arch. В Debian/Ubuntu (пакет `qemu-efi-aarch64`):@@ -152,6 +160,7 @@ XL_SECS=900 XL_CMDLINE="touchscreen=1 cpufreq=1 bootcpu=7 cpus=4" ./xl run #| `wfi=0 wfe_mode=0` | простаивающее ядро процессора не засыпает, а крутится в цикле, как всегда было с одним ядром (с `cpus=N` простой — это WFI; на случай, если под гипервизором телефона он поведёт себя плохо) || `return_cpu=N`, `return_panic=1` | для проверки возврата в загрузчик с несколькими ядрами: вернуться по таймеру с процессора N (по номеру в ядре: 0 — загрузочный) и/или через панику || `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` |Несколько ядер на телефоне проверены (2, 4 и 7 ядер запускаются и чисто возвращаются в загрузчик). Лучшийdiff --git a/qemu/run-ios.sh b/qemu/run-ios.shindex 5c88a7a..9be70f2 100755--- a/qemu/run-ios.sh+++ b/qemu/run-ios.sh@@ -7,6 +7,10 @@# QEMU_RAM_GB=<n> the guest's RAM, default 7: memory then ends where the phone's does and the# kernel gets the same 4.2 GB window (the system image included) as on the phone.# The host needs about 2.5 GB per running instance.+# QEMU_NET=1 with a network: a virtio network device, behind it QEMU's own "user" network+# (it hands out an address by DHCP, answers DNS and passes connections on to+# this machine's network; no privileges needed). The kernel makes en0 of it+# (boot-arg virtio_net=1, added here); see userland/src/net_test.m for the rest.# QEMU_INSTANCE=<n> to run several at once: each number has its own monitor and QMP ports# (4444 + 10n, 4445 + 10n); the file qemu/instance sets it for a working copy.# touch.py, screendump.sh and stop.sh follow the same rule.@@ -49,11 +53,16 @@ while done < total:done += os.copy_file_range(src, dst, total - done, done, offset + done)PYfi+NET=()+if [ -n "$QEMU_NET" ] && [ "$QEMU_NET" != 0 ]; then+ NET=(-netdev user,id=net0 -device virtio-net-device,netdev=net0)+ CMDLINE="virtio_net=1 $CMDLINE"+fixnuloader/mkpayload.py -o qemu/payload.bin kernel=$K ramdisk=$ROOT --rdres "$(printf '%x' "$(stat -c %s "$IMG")")" \--cmdline "loader_return_after=$SECS epoch=$(date +%s) virtio_input=1 $CMDLINE" >/dev/null || exit 1QEMU_MEM=${RAM_GB}G exec qemu/run.sh $((SECS + 40)) \-object memory-backend-file,id=ram,size=$RAM_SIZE,mem-path="$PWD/qemu/ram.img",share=off \-machine memory-backend=ram \- -global virtio-mmio.force-legacy=false -device virtio-tablet-device -device virtio-keyboard-device \+ -global virtio-mmio.force-legacy=false -device virtio-tablet-device -device virtio-keyboard-device "${NET[@]}" \-device ramfb -monitor tcp:127.0.0.1:$((4444 + 10 * INSTANCE)),server,nowait \-qmp tcp:127.0.0.1:$((4445 + 10 * INSTANCE)),server,nowait "$@"diff --git a/userland/build.sh b/userland/build.shindex 7c69f70..240f612 100755--- a/userland/build.sh+++ b/userland/build.sh@@ -103,6 +103,7 @@ if [ -d $IOS/rootfs/usr/lib ]; then$DYN -o obj/rwtouch src/rwtouch.c$DYN -framework CoreFoundation -lMobileGestalt -o obj/mg_test src/mg_test.c$DYN -o obj/cpu_test src/cpu_test.c+ $DYN -fobjc-arc -framework Foundation -framework SystemConfiguration -o obj/net_test src/net_test.m# our library for inside stock iOS programs (the jobs in INJECT are started with it)$DYN -dynamiclib -install_name /redwood/lib/libredwood.dylib -framework CoreFoundation -framework IOKit -lobjc \-o obj/libredwood.dylib src/inject.c@@ -126,6 +127,7 @@ if [ -d $IOS/rootfs/usr/lib ]; thenficp obj/hello_dyn obj/svc_test obj/surf_test obj/rwtouch obj/mg_test root/bin/[ -f obj/cpu_test ] && cp obj/cpu_test root/bin/ # (a prebuilt/ from before this program has none)+ [ -f obj/net_test ] && cp obj/net_test root/bin/for f in $EXTRA; do cp "$f" root/bin/; donemkdir -p root/libcp obj/libredwood.dylib obj/libredwood-sb.dylib root/lib/diff --git a/userland/rc.jobs.net b/userland/rc.jobs.netnew file mode 100644index 0000000..ab3b9e7--- /dev/null+++ b/userland/rc.jobs.net@@ -0,0 +1,7 @@+# Commands run by the launchd job com.redwood.demo (see com.redwood.demo.plist).+# The network (RC_JOBS=rc.jobs.net, with a kernel that has en0: under QEMU, QEMU_NET=1): the+# interface as the kernel has it, then configured by configd's IPConfiguration over DHCP, a name+# resolved, a page fetched over plain TCP and over CFNetwork's HTTPS. See src/net_test.m.+/redwood/bin/net_test show dhcp en0 waitaddr en0 40 store+/redwood/bin/net_test resolve example.com tcp example.com 80 reach example.com+/redwood/bin/net_test fetch https://example.com/ fetch https://www.apple.com/library/test/success.htmldiff --git a/userland/src/net_test.m b/userland/src/net_test.mnew file mode 100644index 0000000..8aa506e--- /dev/null+++ b/userland/src/net_test.m@@ -0,0 +1,381 @@+/*+ * net_test: bring the network interface up the way iOS itself would, and see whether iOS can+ * use it. Each step is one layer of what a stock application needs:+ *+ * usage: net_test STEP...+ * show the interfaces and their addresses, as the kernel has them+ * store [PATTERN] what configd has in its dynamic store (default: everything under+ * State:/Network and Setup:/Network)+ * dhcp IF ask configd's IPConfiguration plugin to configure IF by DHCP+ * waitaddr IF SECONDS wait until IF has an IPv4 address+ * resolve NAME getaddrinfo(): the question goes to mDNSResponder, which asks the+ * servers configd has told it about+ * tcp HOST PORT connect a socket, send an HTTP request, show the first line of the answer+ * fetch URL the same through CFNetwork (NSURLSession): for https this is TLS, the+ * system's trust store and trustd as well+ * reach NAME what SCNetworkReachability says: the question applications ask first+ * wait SECONDS+ *+ * 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+ * of interfaces, straight from the kernel, and has a Mach interface of its own, the one the+ * "ipconfig" command of macOS uses ("ipconfig set en0 DHCP"; the command itself is not part of+ * iOS). "dhcp" is one of its calls: the plugin makes a service for the interface that exists in+ * no preferences file, runs DHCP, and publishes what it learns; the rest of configd then treats+ * it like any other service.+ * (Not "ipconfig set", the first call one thinks of: the service that one makes is gone at+ * configd's next look at its configuration, half a second later at boot, and the protocol is+ * detached from the interface again. "ipconfig setservice" makes one that stays.)+ */+#import <Foundation/Foundation.h>+#include <SystemConfiguration/SCNetworkReachability.h>+#include <arpa/inet.h>+#include <ifaddrs.h>+#include <mach/mach.h>+#include <mach/mach_time.h>+#include <net/if.h>+#include <net/if_dl.h>+#include <netdb.h>+#include <netinet/in.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include <sys/socket.h>+#include <unistd.h>++/* not in the iOS SDK's headers, in the libraries all the same */+extern mach_port_t bootstrap_port;+extern kern_return_t bootstrap_look_up(mach_port_t bootstrap, const char *name, mach_port_t *service);+typedef const struct __SCDynamicStore *SCDynamicStoreRef;+extern SCDynamicStoreRef SCDynamicStoreCreate(CFAllocatorRef allocator, CFStringRef name, void *callout, void *context);+extern CFArrayRef SCDynamicStoreCopyKeyList(SCDynamicStoreRef store, CFStringRef pattern);+extern CFPropertyListRef SCDynamicStoreCopyValue(SCDynamicStoreRef store, CFStringRef key);++static double+seconds(void)+{+ static mach_timebase_info_data_t base;++ if (base.denom == 0) {+ mach_timebase_info(&base);+ }+ return (double)mach_absolute_time() * base.numer / base.denom / 1e9;+}++/* ---- show ------------------------------------------------------------------------------------------ */++static bool+show(const char *only, bool quiet)+{+ struct ifaddrs *list, *a;+ bool has_ipv4 = false;+ char text[64];++ if (getifaddrs(&list) != 0) {+ perror("net_test: getifaddrs");+ return false;+ }+ for (a = list; a != NULL; a = a->ifa_next) {+ if (a->ifa_addr == NULL || (only != NULL && strcmp(a->ifa_name, only) != 0)) {+ continue;+ }+ if (a->ifa_addr->sa_family == AF_LINK) {+ struct sockaddr_dl *dl = (struct sockaddr_dl *)a->ifa_addr;+ const unsigned char *m = (const unsigned char *)LLADDR(dl);++ if (quiet) {+ continue;+ }+ printf("net_test: %s: flags %#x%s%s, type %#x", a->ifa_name, a->ifa_flags, (a->ifa_flags & IFF_UP) ? " up" : "",+ (a->ifa_flags & IFF_RUNNING) ? " running" : "", dl->sdl_type);+ if (dl->sdl_alen == 6) {+ printf(", address %02x:%02x:%02x:%02x:%02x:%02x", m[0], m[1], m[2], m[3], m[4], m[5]);+ }+ printf("\n");+ } else if (a->ifa_addr->sa_family == AF_INET) {+ struct sockaddr_in *in = (struct sockaddr_in *)a->ifa_addr, *mask = (struct sockaddr_in *)a->ifa_netmask;++ has_ipv4 = true;+ if (!quiet) {+ printf("net_test: %s: inet %s", a->ifa_name, inet_ntop(AF_INET, &in->sin_addr, text, sizeof(text)));+ printf(" netmask %s\n", mask ? inet_ntop(AF_INET, &mask->sin_addr, text, sizeof(text)) : "?");+ }+ } else if (a->ifa_addr->sa_family == AF_INET6 && !quiet) {+ struct sockaddr_in6 *in6 = (struct sockaddr_in6 *)a->ifa_addr;++ printf("net_test: %s: inet6 %s\n", a->ifa_name, inet_ntop(AF_INET6, &in6->sin6_addr, text, sizeof(text)));+ }+ }+ freeifaddrs(list);+ return has_ipv4;+}++/* ---- store ----------------------------------------------------------------------------------------- */++static void+store(const char *pattern)+{+ SCDynamicStoreRef session = SCDynamicStoreCreate(NULL, CFSTR("net_test"), NULL, NULL);+ NSString *wanted = pattern ? @(pattern) : @"(State|Setup):/Network/.*";+ NSArray *keys;++ if (session == NULL) {+ printf("net_test: store: no session with configd\n");+ return;+ }+ keys = CFBridgingRelease(SCDynamicStoreCopyKeyList(session, (__bridge CFStringRef)wanted));+ printf("net_test: store: %lu keys match %s\n", (unsigned long)keys.count, wanted.UTF8String);+ for (NSString *key in [keys sortedArrayUsingSelector:@selector(compare:)]) {+ id value = CFBridgingRelease(SCDynamicStoreCopyValue(session, (__bridge CFStringRef)key));+ NSString *text = [[[value description] componentsSeparatedByCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet]+ componentsJoinedByString:@" "];++ while ([text containsString:@" "]) {+ text = [text stringByReplacingOccurrencesOfString:@" " withString:@" "];+ }+ printf("net_test: %s = %s\n", key.UTF8String, text.length > 400 ? [text substringToIndex:400].UTF8String : text.UTF8String);+ }+ CFRelease(session);+}++/* ---- dhcp ------------------------------------------------------------------------------------------ */++/*+ * The one call of the plugin's interface that is needed, written out by hand (bootp's+ * ipconfig.defs, subsystem 20000, the twelfth routine):+ * routine ipconfig_set_service(server; name : array[16] of char; method_data : ^array[] of byte;+ * out serviceID : array[128] of char; out status : int)+ * method_data is a property list, { ConfigMethod = DHCP }, sent out of line. Only root may ask.+ */+#pragma pack(push, 4)+struct set_request {+ mach_msg_header_t head;+ mach_msg_body_t body;+ mach_msg_ool_descriptor_t method;+ NDR_record_t ndr;+ char name[16];+ mach_msg_type_number_t method_length;+};+struct set_reply {+ mach_msg_header_t head;+ NDR_record_t ndr;+ kern_return_t result;+ char service[128];+ int status;+ mach_msg_max_trailer_t trailer;+};+#pragma pack(pop)++static void+dhcp(const char *interface)+{+ static const char *const statuses[] = { "done", "permission denied", "no such interface", "invalid parameter",+ "invalid operation", "allocation failed", "internal error", "not supported" };+ NSData *method = [NSPropertyListSerialization dataWithPropertyList:@{ @"ConfigMethod": @"DHCP" }+ format:NSPropertyListBinaryFormat_v1_0 options:0 error:NULL];+ mach_port_t server = MACH_PORT_NULL, reply_port = mig_get_reply_port();+ union {+ struct set_request request;+ struct set_reply reply;+ } message;+ kern_return_t result;++ result = bootstrap_look_up(bootstrap_port, "com.apple.network.IPConfiguration", &server);+ if (result != KERN_SUCCESS) {+ printf("net_test: dhcp: configd's IPConfiguration is not there: %#x\n", result);+ return;+ }+ memset(&message, 0, sizeof(message));+ message.request.head.msgh_bits = MACH_MSGH_BITS_COMPLEX | MACH_MSGH_BITS(MACH_MSG_TYPE_COPY_SEND, MACH_MSG_TYPE_MAKE_SEND_ONCE);+ message.request.head.msgh_size = sizeof(message.request);+ message.request.head.msgh_remote_port = server;+ message.request.head.msgh_local_port = reply_port;+ message.request.head.msgh_id = 20011;+ message.request.body.msgh_descriptor_count = 1;+ message.request.method.address = (void *)method.bytes;+ message.request.method.size = (mach_msg_size_t)method.length;+ message.request.method.deallocate = FALSE;+ message.request.method.copy = MACH_MSG_VIRTUAL_COPY;+ message.request.method.type = MACH_MSG_OOL_DESCRIPTOR;+ message.request.ndr = NDR_record;+ strlcpy(message.request.name, interface, sizeof(message.request.name));+ message.request.method_length = (mach_msg_type_number_t)method.length;+ result = mach_msg(&message.request.head, MACH_SEND_MSG | MACH_RCV_MSG, sizeof(message.request), sizeof(message), reply_port,+ MACH_MSG_TIMEOUT_NONE, MACH_PORT_NULL);+ if (result != KERN_SUCCESS) {+ printf("net_test: dhcp: the message did not go through: %#x\n", result);+ } else if (message.reply.result != KERN_SUCCESS) {+ printf("net_test: dhcp: IPConfiguration does not take the message: %d\n", message.reply.result);+ } else {+ int status = message.reply.status;++ message.reply.service[sizeof(message.reply.service) - 1] = 0;+ printf("net_test: dhcp: IPConfiguration says of \"setservice %s DHCP\": %d (%s), service %s\n", interface, status,+ status >= 0 && status < 8 ? statuses[status] : "?", message.reply.service);+ }+}++/* ---- resolve, tcp ---------------------------------------------------------------------------------- */++static bool+resolve(const char *name, char *first, size_t size)+{+ struct addrinfo hints = { .ai_socktype = SOCK_STREAM }, *list = NULL, *a;+ double start = seconds();+ int error = getaddrinfo(name, NULL, &hints, &list);+ char text[64];++ if (error != 0) {+ printf("net_test: resolve %s: %s (after %.2f s)\n", name, gai_strerror(error), seconds() - start);+ return false;+ }+ printf("net_test: resolve %s, %.2f s:", name, seconds() - start);+ for (a = list; a != NULL; a = a->ai_next) {+ void *address = a->ai_family == AF_INET ? (void *)&((struct sockaddr_in *)a->ai_addr)->sin_addr :+ (void *)&((struct sockaddr_in6 *)a->ai_addr)->sin6_addr;++ printf(" %s", inet_ntop(a->ai_family, address, text, sizeof(text)));+ if (a->ai_family == AF_INET && first != NULL && first[0] == 0) {+ strlcpy(first, text, size);+ }+ }+ printf("\n");+ freeaddrinfo(list);+ return true;+}++static void+tcp(const char *host, const char *port)+{+ struct addrinfo hints = { .ai_family = AF_INET, .ai_socktype = SOCK_STREAM }, *list = NULL;+ char request[256], answer[2048], *end;+ double start = seconds();+ ssize_t n, total = 0;+ int s, error;++ error = getaddrinfo(host, port, &hints, &list);+ if (error != 0) {+ printf("net_test: tcp %s: %s\n", host, gai_strerror(error));+ return;+ }+ s = socket(AF_INET, SOCK_STREAM, 0);+ if (s < 0 || connect(s, list->ai_addr, list->ai_addrlen) != 0) {+ printf("net_test: tcp %s port %s: %s (after %.2f s)\n", host, port, strerror(errno), seconds() - start);+ freeaddrinfo(list);+ return;+ }+ printf("net_test: tcp %s port %s: connected in %.2f s\n", host, port, seconds() - start);+ snprintf(request, sizeof(request), "GET / HTTP/1.0\r\nHost: %s\r\nUser-Agent: net_test\r\n\r\n", host);+ write(s, request, strlen(request));+ answer[0] = 0;+ while ((n = read(s, total == 0 ? answer : request, total == 0 ? sizeof(answer) - 1 : sizeof(request))) > 0) {+ if (total == 0) {+ answer[n] = 0;+ }+ total += n;+ }+ if ((end = strpbrk(answer, "\r\n")) != NULL) {+ *end = 0;+ }+ printf("net_test: tcp %s: %zd bytes in %.2f s, the answer begins \"%s\"\n", host, total, seconds() - start, answer);+ close(s);+ freeaddrinfo(list);+}++/* ---- fetch, reach ---------------------------------------------------------------------------------- */++static void+fetch(const char *address)+{+ NSURL *url = [NSURL URLWithString:@(address)];+ NSURLSessionConfiguration *configuration = NSURLSessionConfiguration.ephemeralSessionConfiguration;+ dispatch_semaphore_t done = dispatch_semaphore_create(0);+ double start = seconds();++ configuration.timeoutIntervalForRequest = 60;+ [[[NSURLSession sessionWithConfiguration:configuration] dataTaskWithURL:url+ completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {+ if (error != nil) {+ printf("net_test: fetch %s: FAILED after %.2f s: %s (%s %ld)\n", address, seconds() - start,+ error.localizedDescription.UTF8String, error.domain.UTF8String, (long)error.code);+ } else {+ NSString *text = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];+ NSRange title = [text rangeOfString:@"<title>"], close = [text rangeOfString:@"</title>"];++ printf("net_test: fetch %s: status %ld, %lu bytes in %.2f s", address,+ (long)((NSHTTPURLResponse *)response).statusCode, (unsigned long)data.length, seconds() - start);+ if (title.location != NSNotFound && close.location != NSNotFound && close.location > title.location) {+ printf(", title \"%s\"", [text substringWithRange:NSMakeRange(NSMaxRange(title),+ close.location - NSMaxRange(title))].UTF8String);+ }+ printf("\n");+ }+ dispatch_semaphore_signal(done);+ }] resume];+ if (dispatch_semaphore_wait(done, dispatch_time(DISPATCH_TIME_NOW, 90 * NSEC_PER_SEC)) != 0) {+ printf("net_test: fetch %s: no answer and no error in 90 s\n", address);+ }+}++static void+reach(const char *name)+{+ SCNetworkReachabilityRef target = SCNetworkReachabilityCreateWithName(NULL, name);+ SCNetworkReachabilityFlags flags = 0;++ if (target == NULL || !SCNetworkReachabilityGetFlags(target, &flags)) {+ printf("net_test: reach %s: no answer\n", name);+ } else {+ printf("net_test: reach %s: flags %#x:%s%s%s%s\n", name, flags, (flags & kSCNetworkReachabilityFlagsReachable) ?+ " reachable" : " NOT reachable", (flags & kSCNetworkReachabilityFlagsConnectionRequired) ? ", connection required" : "",+ (flags & kSCNetworkReachabilityFlagsIsWWAN) ? ", cellular" : "",+ (flags & kSCNetworkReachabilityFlagsIsDirect) ? ", direct" : "");+ }+ if (target != NULL) {+ CFRelease(target);+ }+}++int+main(int argc, char **argv)+{+ setvbuf(stdout, NULL, _IOLBF, 0);+ @autoreleasepool {+ for (int i = 1; i < argc; i++) {+ const char *step = argv[i];++ if (strcmp(step, "show") == 0) {+ show(NULL, false);+ } else if (strcmp(step, "store") == 0) {+ store(i + 1 < argc && strchr(argv[i + 1], ':') != NULL ? argv[++i] : NULL);+ } else if (strcmp(step, "dhcp") == 0 && i + 1 < argc) {+ dhcp(argv[++i]);+ } else if (strcmp(step, "waitaddr") == 0 && i + 2 < argc) {+ const char *interface = argv[++i];+ double start = seconds(), limit = atof(argv[++i]);++ while (!show(interface, true) && seconds() - start < limit) {+ usleep(250000);+ }+ printf("net_test: waitaddr %s: %s after %.1f s\n", interface, show(interface, true) ? "an address" :+ "NO address", seconds() - start);+ show(interface, false);+ } else if (strcmp(step, "resolve") == 0 && i + 1 < argc) {+ resolve(argv[++i], NULL, 0);+ } else if (strcmp(step, "tcp") == 0 && i + 2 < argc) {+ tcp(argv[i + 1], argv[i + 2]);+ i += 2;+ } else if (strcmp(step, "fetch") == 0 && i + 1 < argc) {+ fetch(argv[++i]);+ } else if (strcmp(step, "reach") == 0 && i + 1 < argc) {+ reach(argv[++i]);+ } else if (strcmp(step, "wait") == 0 && i + 1 < argc) {+ usleep((useconds_t)(atof(argv[++i]) * 1e6));+ } else {+ fprintf(stderr, "net_test: bad step \"%s\"\n", step);+ return 1;+ }+ }+ }+ return 0;+}diff --git a/xnu/README.md b/xnu/README.mdindex 10c32f0..2e88225 100644--- a/xnu/README.md+++ b/xnu/README.md@@ -62,6 +62,7 @@ xnu-deps/setup.sh # ~30 с: исходники зависимостей,| `bsd/kern/kern_minimac.c`, `libkern/amfi/` | заглушки AMFI и Sandbox (MAC-политики), права из подписи программы || `bsd/dev/redwood_input.c`, `redwood_goodix.c`, `redwood_virtio_input.c` | ввод: `/dev/redwood-touch`, драйвер Goodix GT9916 (SPI бит-бангом по GPIO), virtio-input для QEMU || `bsd/dev/redwood_cpufreq.c` | частота процессора (Qualcomm EPSS) |+| `bsd/dev/redwood_net.c`, `bsd/sys/redwood_net.h`, `redwood_virtio_net.c` | сетевой интерфейс `en0` через сетевой KPI ядра (без IONetworkingFamily) и граница между ним и тем, что носит кадры («линк»: три функции в `redwood_net.h`); первый линк — virtio-net для QEMU || `bsd/dev/redwood_adreno.c`, `iokit/Kernel/RedwoodGPU.cpp` | GPU телефона (Adreno 642L): пошаговое включение (`adreno=N`: питание, GMU, zap-шейдер, микрокод), буферы и очередь команд; клиент IOKit с подмножеством msm DRM для Mesa || `bsd/pthread/pthread_kext_static.c` | pthread kext, слинкованный в ядро |diff --git a/xnu/files/bsd/dev/redwood_input.c b/xnu/files/bsd/dev/redwood_input.cindex f496be6..79abb10 100644--- a/xnu/files/bsd/dev/redwood_input.c+++ b/xnu/files/bsd/dev/redwood_input.c@@ -171,5 +171,6 @@ redwood_input_init(void)redwood_virtio_input_init();redwood_goodix_init();redwood_buttons_init();+ redwood_net_init();redwood_adreno_init();}diff --git a/xnu/files/bsd/dev/redwood_net.c b/xnu/files/bsd/dev/redwood_net.cnew file mode 100644index 0000000..c12efb6--- /dev/null+++ b/xnu/files/bsd/dev/redwood_net.c@@ -0,0 +1,355 @@+/*+ * en0: a network interface that is Ethernet as far as the rest of the kernel and iOS can tell.+ *+ * iOS expects its interfaces from IONetworkingFamily, which this kernel does not have; the BSD+ * half of the kernel does not need it. The interface is made with the kernel's own interface+ * KPI, the way bsd/net/if_fake.c makes its "feth": family Ethernet, the stock Ethernet framing+ * and demultiplexing, one function that is given a frame to send and one call to hand a frame+ * that has arrived to the stack. What iOS's user space makes of an interface that has no+ * IOKit object behind it is another matter: see userland/src/net_test.m.+ *+ * What carries the frames is a link driver's business; sys/redwood_net.h is all that the two+ * know of each other. The first link is QEMU's virtio network device (redwood_virtio_net.c).+ */+#include <kern/clock.h>+#include <kern/locks.h>+#include <kern/thread.h>+#include <libkern/libkern.h>+#include <mach/mach_types.h>+#include <net/bpf.h>+#include <net/ethernet.h>+#include <net/if.h>+#include <net/if_ether.h>+#include <net/if_media.h>+#include <net/if_types.h>+#include <net/kpi_interface.h>+#include <netinet/in.h>+#include <pexpert/pexpert.h>+#include <sys/kern_event.h>+#include <sys/kpi_mbuf.h>+#include <sys/redwood_net.h>+#include <sys/sockio.h>+#include <sys/systm.h>++static LCK_GRP_DECLARE(net_lck_grp, "redwood-net");+static LCK_MTX_DECLARE(net_tx_lock, &net_lck_grp);+static const struct redwood_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;++/*+ * Boot-arg net_trace=N: a line in the log for each of the first N frames, either way.+ * Boot-arg net_names=1: a line for every name asked of a DNS server and for every TCP connection+ * begun from here -- which is how to see what a system that has just been given a network does+ * with it (up to NAMES_MAX lines).+ */+#define NAMES_MAX 3000+static uint32_t net_trace, net_names;++static void+trace_frame(const char *way, const uint8_t *frame, size_t length, size_t whole)+{+ static uint32_t said, names;+ const uint8_t *end = frame + length, *ip = frame + ETHER_HDR_LEN, *l4;+ uint16_t type;+ bool ports;++ if (length < ETHER_HDR_LEN + 28 || (said >= net_trace && (!net_names || names >= NAMES_MAX))) {+ return;+ }+ type = (uint16_t)(frame[12] << 8 | frame[13]);+ l4 = ip + 4 * (ip[0] & 0xf);+ ports = type == ETHERTYPE_IP && (ip[9] == IPPROTO_TCP || ip[9] == IPPROTO_UDP) && l4 + 4 <= end;+ if (net_names && names < NAMES_MAX && ports && way[0] == 'o') {+ if (ip[9] == IPPROTO_UDP && (l4[2] << 8 | l4[3]) == 53 && l4 + 8 + 12 < end) {+ char name[128];+ const uint8_t *label = l4 + 8 + 12;+ size_t n = 0;++ /* the question: lengths and labels, up to a zero */+ while (label < end && *label != 0 && *label < 64 && label + 1 + *label < end && n + *label + 2 < sizeof(name)) {+ memcpy(name + n, label + 1, *label);+ n += *label;+ name[n++] = '.';+ label += 1 + *label;+ }+ name[n ? n - 1 : 0] = 0;+ names++;+ printf("net: asks for the name %s (type %u)\n", name, label + 2 < end ? label[1] << 8 | label[2] : 0);+ } else if (ip[9] == IPPROTO_TCP && l4 + 14 <= end && (l4[13] & 0x12) == 0x02) {+ names++;+ printf("net: connects to %u.%u.%u.%u port %u\n", ip[16], ip[17], ip[18], ip[19], l4[2] << 8 | l4[3]);+ }+ }+ if (said >= net_trace) {+ return;+ }+ said++;+ if (type == ETHERTYPE_IP) {+ printf("net: %s %zu bytes: IPv4 %s %u.%u.%u.%u:%u -> %u.%u.%u.%u:%u%s\n", way, whole, ip[9] == IPPROTO_TCP ? "TCP" :+ ip[9] == IPPROTO_UDP ? "UDP" : ip[9] == IPPROTO_ICMP ? "ICMP" : "protocol?", ip[12], ip[13], ip[14], ip[15],+ ports ? l4[0] << 8 | l4[1] : 0, ip[16], ip[17], ip[18], ip[19], ports ? l4[2] << 8 | l4[3] : 0,+ ip[9] == IPPROTO_TCP && ports && l4 + 14 <= end ? (l4[13] & 2 ? " SYN" : l4[13] & 1 ? " FIN" : l4[13] & 4 ? " RST" : "") : "");+ } else {+ printf("net: %s %zu bytes: %s (type %#x) to %02x:%02x:%02x:%02x:%02x:%02x\n", way, whole, type == ETHERTYPE_ARP ? "ARP" :+ type == ETHERTYPE_IPV6 ? "IPv6" : "?", type, frame[0], frame[1], frame[2], frame[3], frame[4], frame[5]);+ }+}++/* ... of a frame on its way out: the start of it is enough */+static void+trace_packet(mbuf_t packet, size_t length)+{+ uint8_t start[192];+ size_t have = length < sizeof(start) ? length : sizeof(start);++ if ((net_trace || net_names) && mbuf_copydata(packet, 0, have, start) == 0) {+ trace_frame("out", start, have, length);+ }+}++/* ---- the interface -------------------------------------------------------------------------------- */++/* The stack has a frame to send (a chain of mbufs that starts with the Ethernet header). */+static errno_t+net_output(ifnet_t ifp, mbuf_t packet)+{+ size_t length = mbuf_pkthdr_len(packet);+ bool sent = false;++ if (length <= REDWOOD_NET_FRAME_MAX && net_link_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);+ }+ if (sent) {+ net_count.sent++;+ net_count.sent_bytes += length;+ ifnet_stat_increment_out(ifp, 1, (uint32_t)length, 0);+ } else {+ net_count.dropped_out++;+ ifnet_stat_increment_out(ifp, 0, 0, 1);+ }+ mbuf_freem(packet);+ return 0;+}++/* A frame has arrived. */+void+redwood_net_input(const uint8_t *frame, size_t length)+{+ struct ifnet_stat_increment_param stats = { .packets_in = 1, .bytes_in = (uint32_t)length };+ unsigned int chunks = 1;+ mbuf_t packet = NULL;+ char *header;++ trace_frame("in ", frame, length, length);+ if (net_ifp == NULL || length < ETHER_HDR_LEN || length > REDWOOD_NET_FRAME_MAX ||+ mbuf_allocpacket(MBUF_DONTWAIT, length, &chunks, &packet) != 0) {+ net_count.dropped_in++;+ return;+ }+ if (mbuf_copyback(packet, 0, length, frame, MBUF_DONTWAIT) != 0) {+ mbuf_freem(packet);+ net_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_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);+}++static errno_t+net_ioctl(ifnet_t ifp, u_long command, void *data)+{+ static const int media[] = { IFM_ETHER | IFM_AUTO };+ struct ifreq *request = data;+ struct ifmediareq *media_request = data;+ user_addr_t list;+ errno_t error = 0;++ switch (command) {+ case SIOCSIFADDR:+ ifnet_set_flags(ifp, IFF_UP, IFF_UP);+ break;+ case SIOCSIFFLAGS:+ /* running whenever it is up: the link is there or it is not, nothing is switched on */+ ifnet_set_flags(ifp, (ifnet_flags(ifp) & IFF_UP) ? IFF_RUNNING : 0, IFF_RUNNING);+ break;+ case SIOCGIFMEDIA32:+ case SIOCGIFMEDIA64:+ /* what configd asks to learn whether the cable is in */+ list = command == SIOCGIFMEDIA64 ? ((struct ifmediareq64 *)media_request)->ifmu_ulist :+ 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);+ if (list != USER_ADDR_NULL && media_request->ifm_count > 0) {+ error = copyout(media, list, sizeof(media));+ }+ media_request->ifm_count = 1;+ break;+ case SIOCGIFDEVMTU:+ request->ifr_devmtu.ifdm_current = ifnet_mtu(ifp);+ request->ifr_devmtu.ifdm_max = ETHERMTU;+ request->ifr_devmtu.ifdm_min = IF_MINMTU;+ break;+ case SIOCSIFMTU:+ error = request->ifr_mtu > ETHERMTU || request->ifr_mtu < IF_MINMTU ? EINVAL : ifnet_set_mtu(ifp, request->ifr_mtu);+ break;+ case SIOCADDMULTI:+ case SIOCDELMULTI:+ break; /* the link hands us everything anyway */+ default:+ error = EOPNOTSUPP;+ break;+ }+ return error;+}++/* Tell whoever listens for kernel events (configd does) that the link is up, or down. */+static void+net_link_event(ifnet_t ifp, uint32_t code)+{+ _Alignas(struct kern_event_msg) char message[sizeof(struct kern_event_msg) + sizeof(struct net_event_data)] = { 0 };+ struct kern_event_msg *header = (struct kern_event_msg *)message;+ struct net_event_data *about = (struct net_event_data *)(header + 1);++ header->total_size = sizeof(message);+ header->vendor_code = KEV_VENDOR_APPLE;+ header->kev_class = KEV_NETWORK_CLASS;+ header->kev_subclass = KEV_DL_SUBCLASS;+ header->event_code = code;+ about->if_family = ifnet_family(ifp);+ about->if_unit = ifnet_unit(ifp);+ strlcpy(about->if_name, ifnet_name(ifp), IFNAMSIZ);+ ifnet_event(ifp, header);+}++void+redwood_net_link_state(bool up)+{+ if (net_ifp == NULL || up == net_link_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);+}++/* 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)+{+ uint64_t said = 0, total;+ unsigned quiet = 0;++ for (unsigned tick = 1;; tick++) {+ quiet = net_link->poll != NULL && net_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;+ 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);+ }+ delay_for_interval(quiet < 100 ? 2 : 10, NSEC_PER_MSEC);+ }+}++bool+redwood_net_attach(const struct redwood_net_link *link)+{+ struct ifnet_init_eparams init = {+ .ver = IFNET_INIT_CURRENT_VERSION,+ .len = sizeof(init),+ /*+ * The simple model: every frame straight to net_output(). And no Skywalk "nexus" made for+ * the interface by itself: sockets are all that is asked of it so far.+ */+ .flags = IFNET_INIT_LEGACY | IFNET_INIT_NX_NOAUTO,+ .uniqueid = "redwood-en0",+ .uniqueid_len = 11,+ .name = "en",+ .unit = 0,+ .family = IFNET_FAMILY_ETHERNET,+ .subfamily = link->wireless ? IFNET_SUBFAMILY_WIFI : IFNET_SUBFAMILY_ANY,+ .type = IFT_ETHER,+ .output = net_output,+ .demux = ether_demux,+ .add_proto = ether_add_proto,+ .del_proto = ether_del_proto,+ .check_multi = ether_check_multi,+ .framer_extended = ether_frameout_extended,+ .ioctl = net_ioctl,+ .broadcast_addr = etherbroadcastaddr,+ .broadcast_len = ETHER_ADDR_LEN,+ };+ const uint8_t *address = link->address;+ ifnet_t ifp = NULL;+ 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);+ return false;+ }+ net_link = link;+ net_link_up = link->up;+ error = ifnet_allocate_extended(&init, &ifp);+ if (error != 0) {+ printf("net: the interface cannot be made: error %d\n", error);+ net_link = NULL;+ return false;+ }+ ifnet_set_capabilities_enabled(ifp, 0, -1);+ ifnet_set_addrlen(ifp, ETHER_ADDR_LEN);+ ifnet_set_baudrate(ifp, 100 * 1000 * 1000);+ ifnet_set_mtu(ifp, ETHERMTU);+ ifnet_set_flags(ifp, IFF_BROADCAST | IFF_MULTICAST | IFF_SIMPLEX, 0xffff);+ ifnet_set_hdrlen(ifp, ETHER_HDR_LEN);+ ifnet_set_offload(ifp, 0);+ error = ifnet_attach(ifp, NULL);+ if (error != 0) {+ printf("net: the interface cannot be attached: error %d\n", error);+ ifnet_release(ifp);+ net_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) {+ net_link_event(ifp, KEV_DL_LINK_ON);+ }+ printf("net: en0 attached on %s%s, address %02x:%02x:%02x:%02x:%02x:%02x, link %s\n", link->name,+ link->wireless ? " (a radio)" : "", address[0], address[1], address[2], address[3], address[4], address[5],+ net_link_up ? "up" : "down");+ if (kernel_thread_start(net_thread, NULL, &thread) == KERN_SUCCESS) {+ thread_deallocate(thread);+ }+ return true;+}++void+redwood_net_init(void)+{+ PE_parse_boot_argn("net_trace", &net_trace, sizeof(net_trace));+ PE_parse_boot_argn("net_names", &net_names, sizeof(net_names));+ redwood_virtio_net_init();+}diff --git a/xnu/files/bsd/dev/redwood_virtio_net.c b/xnu/files/bsd/dev/redwood_virtio_net.cnew file mode 100644index 0000000..3c4c981--- /dev/null+++ b/xnu/files/bsd/dev/redwood_virtio_net.c@@ -0,0 +1,293 @@+/*+ * QEMU's virtio network device as the link behind en0 (see sys/redwood_net.h for what a link is).+ *+ * "-device virtio-net-device" on the virt machine's virtio-mmio bus, which must be the current+ * one, not "legacy" (-global virtio-mmio.force-legacy=false), with any "-netdev" behind it;+ * qemu/run-ios.sh does that with QEMU_NET=1. Only with boot-arg virtio_net=1: the bus address is+ * QEMU's and means nothing on the phone.+ *+ * Nothing of what the device offers is taken (no checksums or segmentation left to it, no+ * merged receive buffers): a 12-byte header nobody reads, then the frame, one buffer each.+ * No interrupt is used; the interface's thread asks (virtio_poll()).+ */+#include <kern/thread.h>+#include <libkern/libkern.h>+#include <mach/mach_types.h>+#include <mach/vm_param.h>+#include <net/ethernet.h>+#include <pexpert/pexpert.h>+#include <sys/kpi_mbuf.h>+#include <sys/redwood_net.h>+#include <sys/systm.h>+#include <vm/vm_kern.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); /* pmap_paddr_t */++#define VIRTIO_BUS 0x0a000000UL /* QEMU virt: 32 transports of 0x200 bytes */+#define VIRTIO_SLOTS 32+#define VIRTIO_SLOT_SIZE 0x200++#define VIRTIO_MAGIC 0x000 /* "virt" */+#define VIRTIO_VERSION 0x004+#define VIRTIO_DEVICE_ID 0x008+#define VIRTIO_DEVICE_FEATURES 0x010+#define VIRTIO_DEVICE_FEATURES_SEL 0x014+#define VIRTIO_DRIVER_FEATURES 0x020+#define VIRTIO_DRIVER_FEATURES_SEL 0x024+#define VIRTIO_QUEUE_SEL 0x030+#define VIRTIO_QUEUE_NUM_MAX 0x034+#define VIRTIO_QUEUE_NUM 0x038+#define VIRTIO_QUEUE_READY 0x044+#define VIRTIO_QUEUE_NOTIFY 0x050+#define VIRTIO_STATUS 0x070+#define VIRTIO_QUEUE_DESC 0x080+#define VIRTIO_QUEUE_DRIVER 0x090+#define VIRTIO_QUEUE_DEVICE 0x0a0+#define VIRTIO_CONFIG 0x100 /* the device's own: for a network device, its address first */++#define VIRTIO_ID_NET 1+#define VIRTIO_NET_F_MAC (1u << 5) /* the device has an address of its own */+#define STATUS_ACKNOWLEDGE 1+#define STATUS_DRIVER 2+#define STATUS_DRIVER_OK 4+#define STATUS_FEATURES_OK 8++#define QUEUE_SIZE 64 /* descriptors, and buffers, per queue */+#define QUEUE_RECEIVE 0+#define QUEUE_TRANSMIT 1+#define BUFFER_SIZE 2048 /* a buffer never crosses a page: one address will do for it */+#define DESC_F_WRITE 2+#define AVAIL_F_NO_INTERRUPT 1++struct vq_desc {+ uint64_t addr;+ uint32_t len;+ uint16_t flags;+ uint16_t next;+};+struct vq_avail {+ uint16_t flags;+ uint16_t idx;+ uint16_t ring[QUEUE_SIZE];+};+struct vq_used {+ uint16_t flags;+ uint16_t idx;+ struct {+ uint32_t id;+ uint32_t len;+ } ring[QUEUE_SIZE];+};+/* before every frame, either way; nothing of it is used (no checksum or segmentation is left to the device) */+struct virtio_net_header {+ uint8_t flags, gso_type;+ uint16_t header_length, gso_size, checksum_start, checksum_offset, buffers;+};++/* the rings of a queue are in one page */+#define OFFSET_DESC 0x0000+#define OFFSET_AVAIL 0x0400+#define OFFSET_USED 0x0800++struct queue {+ struct vq_desc * desc;+ struct vq_avail * avail;+ struct vq_used * used;+ uint8_t * buffers; /* QUEUE_SIZE of BUFFER_SIZE */+ uint16_t seen; /* how far the used ring has been read */+ uint16_t free[QUEUE_SIZE]; /* transmit: the buffers the device does not have */+ unsigned free_count;+};++static vm_offset_t virtio; /* the device's registers */+static struct queue receive_queue, transmit_queue;++static inline uint32_t+reg_read(uint32_t reg)+{+ return *(volatile uint32_t *)(virtio + reg);+}++static inline void+reg_write(uint32_t reg, uint32_t value)+{+ *(volatile uint32_t *)(virtio + reg) = value;+}++static inline void+reg_write64(uint32_t reg, uint64_t value)+{+ reg_write(reg, (uint32_t)value);+ reg_write(reg + 4, (uint32_t)(value >> 32));+}++static bool+queue_make(struct queue *q, uint32_t index, bool device_writes)+{+ vm_offset_t rings = 0, buffers = 0;++ reg_write(VIRTIO_QUEUE_SEL, index);+ if (reg_read(VIRTIO_QUEUE_NUM_MAX) < QUEUE_SIZE) {+ printf("net: virtio queue %u holds only %u\n", index, reg_read(VIRTIO_QUEUE_NUM_MAX));+ return false;+ }+ if (kmem_alloc(kernel_map, &rings, PAGE_SIZE, KMA_KOBJECT | KMA_ZERO | KMA_DATA, VM_KERN_MEMORY_IOKIT) != KERN_SUCCESS ||+ kmem_alloc(kernel_map, &buffers, round_page(QUEUE_SIZE * BUFFER_SIZE), KMA_KOBJECT | KMA_ZERO | KMA_DATA,+ VM_KERN_MEMORY_IOKIT) != KERN_SUCCESS) {+ return false;+ }+ q->desc = (struct vq_desc *)(rings + OFFSET_DESC);+ q->avail = (struct vq_avail *)(rings + OFFSET_AVAIL);+ q->used = (struct vq_used *)(rings + OFFSET_USED);+ q->buffers = (uint8_t *)buffers;+ for (int i = 0; i < QUEUE_SIZE; i++) {+ q->desc[i].addr = kvtophys(buffers + (vm_offset_t)i * BUFFER_SIZE);+ q->desc[i].len = BUFFER_SIZE;+ q->desc[i].flags = device_writes ? DESC_F_WRITE : 0;+ if (device_writes) {+ q->avail->ring[i] = (uint16_t)i; /* the device gets them all, to fill */+ } else {+ q->free[q->free_count++] = (uint16_t)i;+ }+ }+ q->avail->flags = AVAIL_F_NO_INTERRUPT;+ q->avail->idx = device_writes ? QUEUE_SIZE : 0;+ reg_write(VIRTIO_QUEUE_NUM, QUEUE_SIZE);+ reg_write64(VIRTIO_QUEUE_DESC, kvtophys(rings) + OFFSET_DESC);+ reg_write64(VIRTIO_QUEUE_DRIVER, kvtophys(rings) + OFFSET_AVAIL);+ reg_write64(VIRTIO_QUEUE_DEVICE, kvtophys(rings) + OFFSET_USED);+ __builtin_arm_dmb(0xb); /* ISH */+ reg_write(VIRTIO_QUEUE_READY, 1);+ return true;+}++/* A frame to send. */+static bool+virtio_transmit(mbuf_t packet, size_t length)+{+ struct queue *q = &transmit_queue;+ uint8_t *buffer;+ uint16_t id;++ /* the buffers the device has done with */+ while (q->seen != *(volatile uint16_t *)&q->used->idx) {+ q->free[q->free_count++] = (uint16_t)(q->used->ring[q->seen++ % QUEUE_SIZE].id % QUEUE_SIZE);+ }+ if (q->free_count == 0) {+ return false;+ }+ id = q->free[--q->free_count];+ buffer = q->buffers + (size_t)id * BUFFER_SIZE;+ bzero(buffer, sizeof(struct virtio_net_header));+ if (mbuf_copydata(packet, 0, length, buffer + sizeof(struct virtio_net_header)) != 0) {+ q->free[q->free_count++] = id;+ return false;+ }+ q->desc[id].len = (uint32_t)(sizeof(struct virtio_net_header) + length);+ q->avail->ring[q->avail->idx % QUEUE_SIZE] = id;+ __builtin_arm_dmb(0xb);+ q->avail->idx++;+ __builtin_arm_dmb(0xb);+ reg_write(VIRTIO_QUEUE_NOTIFY, QUEUE_TRANSMIT);+ return true;+}++/* Hand up what has arrived; returns how many frames that was. */+static unsigned+virtio_poll(void)+{+ struct queue *q = &receive_queue;+ unsigned frames = 0;++ while (q->seen != *(volatile uint16_t *)&q->used->idx) {+ uint32_t id = q->used->ring[q->seen % QUEUE_SIZE].id % QUEUE_SIZE;+ uint32_t length = q->used->ring[q->seen % QUEUE_SIZE].len;++ q->seen++;+ if (length > sizeof(struct virtio_net_header) && length <= BUFFER_SIZE) {+ redwood_net_input(q->buffers + (size_t)id * BUFFER_SIZE + sizeof(struct virtio_net_header),+ length - sizeof(struct virtio_net_header));+ }+ /* give the buffer back */+ q->avail->ring[q->avail->idx % QUEUE_SIZE] = (uint16_t)id;+ __builtin_arm_dmb(0xb);+ q->avail->idx++;+ frames++;+ }+ if (frames) {+ __builtin_arm_dmb(0xb);+ reg_write(VIRTIO_QUEUE_NOTIFY, QUEUE_RECEIVE);+ }+ return frames;+}++static bool+virtio_net_start(uint8_t address[ETHER_ADDR_LEN])+{+ vm_offset_t bus = ml_io_map(VIRTIO_BUS, VIRTIO_SLOTS * VIRTIO_SLOT_SIZE);+ uint32_t features;+ int slot;++ for (slot = 0; slot < VIRTIO_SLOTS; slot++) {+ virtio = bus + (vm_offset_t)slot * VIRTIO_SLOT_SIZE;+ if (reg_read(VIRTIO_MAGIC) == 0x74726976 && reg_read(VIRTIO_DEVICE_ID) == VIRTIO_ID_NET) {+ break;+ }+ }+ if (slot == VIRTIO_SLOTS) {+ printf("net: no virtio network device (start QEMU with -device virtio-net-device)\n");+ return false;+ }+ if (reg_read(VIRTIO_VERSION) != 2) {+ printf("net: slot %d is a legacy transport; start QEMU with -global virtio-mmio.force-legacy=false\n", slot);+ return false;+ }+ reg_write(VIRTIO_STATUS, 0); /* reset */+ reg_write(VIRTIO_STATUS, STATUS_ACKNOWLEDGE);+ reg_write(VIRTIO_STATUS, STATUS_ACKNOWLEDGE | STATUS_DRIVER);+ reg_write(VIRTIO_DEVICE_FEATURES_SEL, 0);+ features = reg_read(VIRTIO_DEVICE_FEATURES);+ reg_write(VIRTIO_DRIVER_FEATURES_SEL, 0);+ reg_write(VIRTIO_DRIVER_FEATURES, features & VIRTIO_NET_F_MAC); /* and nothing else of what it offers */+ reg_write(VIRTIO_DRIVER_FEATURES_SEL, 1);+ reg_write(VIRTIO_DRIVER_FEATURES, 1); /* bit 32: VIRTIO_F_VERSION_1 */+ reg_write(VIRTIO_STATUS, STATUS_ACKNOWLEDGE | STATUS_DRIVER | STATUS_FEATURES_OK);+ if (!(reg_read(VIRTIO_STATUS) & STATUS_FEATURES_OK)) {+ printf("net: slot %d: features refused (the device offers %#x)\n", slot, features);+ return false;+ }+ if (!queue_make(&receive_queue, QUEUE_RECEIVE, true) || !queue_make(&transmit_queue, QUEUE_TRANSMIT, false)) {+ return false;+ }+ if (features & VIRTIO_NET_F_MAC) {+ for (int i = 0; i < ETHER_ADDR_LEN; i++) {+ address[i] = *(volatile uint8_t *)(virtio + VIRTIO_CONFIG + i);+ }+ }+ reg_write(VIRTIO_STATUS, STATUS_ACKNOWLEDGE | STATUS_DRIVER | STATUS_FEATURES_OK | STATUS_DRIVER_OK);+ reg_write(VIRTIO_QUEUE_NOTIFY, QUEUE_RECEIVE);+ printf("net: virtio network device in slot %d (it offers features %#x)\n", slot, features);+ return true;+}++static struct redwood_net_link virtio_link = {+ .name = "QEMU's virtio network device",+ .address = { 0x02, 'r', 'e', 'd', 'w', 'd' }, /* if the device has none: one "locally administered" */+ .up = true,+ .transmit = virtio_transmit,+ .poll = virtio_poll,+};++void+redwood_virtio_net_init(void)+{+ uint32_t enabled = 0;++ if (!PE_parse_boot_argn("virtio_net", &enabled, sizeof(enabled)) || !enabled) {+ return;+ }+ if (!virtio_net_start(virtio_link.address) || !redwood_net_attach(&virtio_link)) {+ printf("net: no network interface\n");+ }+}diff --git a/xnu/files/bsd/sys/redwood_input.h b/xnu/files/bsd/sys/redwood_input.hindex 01f7cef..29b5b3f 100644--- a/xnu/files/bsd/sys/redwood_input.h+++ b/xnu/files/bsd/sys/redwood_input.h@@ -42,6 +42,7 @@ void redwood_input_init(void);void redwood_virtio_input_init(void); /* boot-arg virtio_input=1: QEMU's virtio pointer and keyboard */void redwood_goodix_init(void); /* boot-arg touchscreen=1: the phone's touch screen */void redwood_buttons_init(void); /* boot-arg buttons=1: the phone's power and volume keys */+void redwood_net_init(void); /* en0, if there is something to carry its frames: sys/redwood_net.h */void redwood_cpufreq_init(void); /* boot-arg cpufreq=1: the phone's processor at full speed */void redwood_adreno_init(void); /* boot-arg adreno=N: the first N steps of waking the phone's GPU */void redwood_adreno_quiesce(void); /* on the way back to the loader: the GPU block stopped, out of our memory */diff --git a/xnu/files/bsd/sys/redwood_net.h b/xnu/files/bsd/sys/redwood_net.hnew file mode 100644index 0000000..293d285--- /dev/null+++ b/xnu/files/bsd/sys/redwood_net.h@@ -0,0 +1,61 @@+/*+ * en0, and what stands behind it.+ *+ * The network interface iOS uses here is made in bsd/dev/redwood_net.c with the kernel's own+ * interface KPI: Ethernet as far as the rest of the kernel and user space can tell. What carries+ * the frames is a "link", a driver of its own that knows nothing about interfaces: QEMU's virtio+ * network device today (bsd/dev/redwood_virtio_net.c), the phone's radio or frames carried over+ * the boot loader's USB channel tomorrow. This is all the two know of each other.+ *+ * A link driver+ * - fills in a struct redwood_net_link and calls redwood_net_attach() once, when it is ready+ * to carry frames (for a radio: when its firmware is up, not when it has joined a network);+ * - hands every frame that arrives to redwood_net_input(): from its own thread, or from+ * the poll function the interface's thread calls for it. Not from interrupt context;+ * - says with redwood_net_link_state() when frames can pass and when they no longer can+ * (the cable, or for a radio: associated and the keys set). configd starts DHCP on that.+ * A frame is what goes over an Ethernet cable without the checksum at its end: destination,+ * source, type, payload; at most REDWOOD_NET_FRAME_MAX bytes. A radio whose frames are 802.11+ * converts in its driver (or has its firmware do it: "Ethernet decap/encap").+ */+#ifndef _SYS_REDWOOD_NET_H_+#define _SYS_REDWOOD_NET_H_++#ifdef KERNEL+#include <sys/kpi_mbuf.h>++#define REDWOOD_NET_FRAME_MAX 1514++struct redwood_net_link {+ const char * name; /* for the log */+ 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 */+ bool up; /* frames can pass from the start (else: wait for redwood_net_link_state()) */+ /*+ * Send one frame: a chain of mbufs, `length` bytes in all, the Ethernet header first. The+ * packet stays the caller's: copy it (mbuf_copydata()). Returns false if it had to be dropped.+ * Called by one thread at a time, never from interrupt context.+ */+ bool (*transmit)(mbuf_t packet, size_t length);+ /*+ * Optional. Look whether frames have arrived and call redwood_net_input() for each; returns+ * how many there were. The interface's thread calls it every 2 ms while frames are coming and+ * every 10 ms when none has for a while. A link that has a thread or an interrupt of its own+ * leaves it NULL.+ */+ unsigned (*poll)(void);+};++/* Make en0 on top of that link (the structure must stay). One link, once: false if there is one already. */+bool redwood_net_attach(const struct redwood_net_link *link);+/* A frame has arrived. Copied; the buffer is the caller's again on return. */+void redwood_net_input(const uint8_t *frame, size_t length);+/* Frames can pass now / can no longer pass. */+void redwood_net_link_state(bool up);++void redwood_net_init(void); /* the links there are: each looks for its hardware (or its boot-arg) */+void redwood_virtio_net_init(void); /* boot-arg virtio_net=1: QEMU's virtio network device */+#endif /* KERNEL */++#endif /* _SYS_REDWOOD_NET_H_ */diff --git a/xnu/redwood.patch b/xnu/redwood.patchindex 07893ee..3f417d1 100644--- a/xnu/redwood.patch+++ b/xnu/redwood.patch@@ -46,10 +46,10 @@ index 222158a93918..68bb0f3e56bf 100755####################################################################### HISTORYdiff --git a/bsd/conf/files b/bsd/conf/files-index 44274016a4cf..6cf54551f728 100644+index 44274016a4cf..08b8d51a49ca 100644--- a/bsd/conf/files+++ b/bsd/conf/files-@@ -109,6 +109,12 @@ bsd/dev/munge.c optional config_requires_u32_munging+@@ -109,6 +109,14 @@ bsd/dev/munge.c optional config_requires_u32_mungingbsd/dev/unix_startup.c standardbsd/dev/monotonic.c optional monotonic@@ -57,12 +57,14 @@ index 44274016a4cf..6cf54551f728 100644+bsd/dev/redwood_virtio_input.c standard+bsd/dev/redwood_goodix.c standard+bsd/dev/redwood_buttons.c standard++bsd/dev/redwood_net.c standard++bsd/dev/redwood_virtio_net.c standard+bsd/dev/redwood_cpufreq.c standard+bsd/dev/redwood_adreno.c standardbsd/dev/dev_perfmon.c optional config_perfmonbsd/libkern/crc32.c standard-@@ -155,6 +161,10 @@ bsd/miscfs/devfs/devfs_vfsops.c optional devfs+@@ -155,6 +163,10 @@ 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@@ -73,7 +75,7 @@ index 44274016a4cf..6cf54551f728 100644bsd/miscfs/routefs/routefs_ops.c optional routefs-@@ -361,6 +371,7 @@ bsd/security/audit/audit_syscalls.c standard+@@ -361,6 +373,7 @@ bsd/security/audit/audit_syscalls.c standardbsd/security/audit/audit_worker.c optional config_auditbsd/pthread/pthread_shims.c standard@@ -81,7 +83,7 @@ index 44274016a4cf..6cf54551f728 100644bsd/pthread/pthread_priority.c standardbsd/pthread/pthread_workqueue.c standard-@@ -383,6 +394,7 @@ bsd/kern/kern_debug.c standard+@@ -383,6 +396,7 @@ bsd/kern/kern_debug.c standardbsd/kern/kern_symfile.c standardbsd/kern/kern_descrip.c standardbsd/kern/kern_guarded.c standard