Skip to content

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

C

SMP: the loader describes the cores, cpu_test, a touch screen that survives a faster start

vcvkkd28a0f39a76a
diff --git a/README.md b/README.md
index 1dadb03..fad0b16 100644
--- a/README.md
+++ b/README.md
@@ -23,7 +23,8 @@
| Экран блокировки, разблокировка свайпом, домашний экран с полным набором значков (две страницы) | Звук, сеть (Wi-Fi/сотовая), Bluetooth, камера |
| Системные жесты: свайп снизу — «домой» и переключатель приложений, свайп от левого края — «назад», Пункт управления | Обои (чёрный фон) |
| Запуск приложений: Настройки (вглубь), Часы, Календарь, Фото, Заметки и др. | GPU/Metal — только программный рендер |
-| Сенсорный экран телефона (Goodix GT9916), мультитач, пробуждение касанием | SMP — работает одно ядро процессора |
+| Сенсорный экран телефона (Goodix GT9916), мультитач, пробуждение касанием | SMP на телефоне не проверено (по умолчанию работает одно ядро процессора) |
+| Несколько ядер процессора (`cpus=N`) — в QEMU | |
| Кнопки «Домой»/«Блокировка»/громкость (в QEMU — клавишами) | Зарядка под нашим ядром (телефон только разряжается) |
| Большое ядро на 2,4 ГГц, загрузка до экрана блокировки ~20 с (телефон) | Safari (лежит в отдельном «App cryptex», которого у нас нет) |
| Снимки экрана и запись экрана с телефона | Сохранение данных: /private/var в памяти, каждая загрузка — «новое устройство» |
@@ -64,6 +65,11 @@ qemu/run-ios.sh 1200 -display gtk > logs/qemu.log # сеанс на 20 ми
(координаты — доли экрана), снимок экрана — `qemu/screendump.sh shot.png`.
- Первый аргумент `run-ios.sh` — длительность сеанса в секундах; по её истечении ядро возвращается в загрузчик
и QEMU завершается. Журнал ядра и демонов идёт в stdout.
+- Несколько ядер процессора: `QEMU_SMP=4 CMDLINE="cpus=4" qemu/run-ios.sh 1200 …` (`QEMU_SMP` — сколько ядер у
+ машины, `cpus=` — сколько из них берёт ядро системы; без `cpus=` оно работает на одном). До экрана блокировки
+ тогда полторы минуты вместо двух с половиной, и всё заметно отзывчивее. Программа `cpu_test` (из
+ `userland/rc.jobs`) пишет в журнал число процессоров и, через четыре минуты, сколько из них на деле работало
+ одновременно.
- Сразу после появления SpringBoard система ещё занята (регистрирует приложения): подождите секунд 30–40,
иначе жесты «растягиваются» и не распознаются.
@@ -120,12 +126,36 @@ XL_SECS=900 XL_CMDLINE="touchscreen=1 cpufreq=1 bootcpu=7" ./xl run # 15 м
|---|---|
| `touchscreen=1` | включить сенсорный экран телефона (`touch_flip=1\|2\|3` — отразить оси) |
| `bootcpu=7` | запустить ядро на самом большом ядре процессора (загрузчик остаётся на нулевом и наблюдает) |
-| `cpufreq=1` | поднять этому ядру частоту до максимума (иначе 300 МГц) |
+| `cpus=N` | использовать N ядер процессора: то, на котором ядро запущено, и ещё N−1 ближайших к нему по номеру (после 7 — 6, 5, 4, потом малые 3, 2, 1); их запускает само ядро через PSCI. `cpumask=M` — выбрать по позиции в этом порядке (бит 0 — загрузочное). Без параметра — одно ядро. **На телефоне не проверено**, порядок проверки — в конце раздела |
+| `cpufreq=1` | поднять частоту до максимума (иначе 300 МГц) всем группам ядер, в которых есть наши |
| `rec_secs=N` | записывать экран N секунд (`rec_start=S`, `rec_mb=M`, не больше 640); потом `./xl recording out.mp4` |
| `-v` | текст загрузки на экране (по умолчанию у `xl run`, если `XL_CMDLINE` не задана) |
| `applog=1` / `applog=2` | stderr приложений в журнал / плюс os_log всех процессов |
| `systrace=1` | печатать неудачные системные вызовы и аварии процессов |
| `machine_name=1` | представляться iPhone10,3 (иначе устройство называется «iPod touch»); мало проверено |
+| `wfi=0 wfe_mode=0` | простаивающее ядро процессора не засыпает, а крутится в цикле, как всегда было с одним ядром (с `cpus=N` простой — это WFI; на случай, если под гипервизором телефона он поведёт себя плохо) |
+| `return_cpu=N`, `return_panic=1` | для проверки возврата в загрузчик с несколькими ядрами: вернуться по таймеру с процессора N (по номеру в ядре: 0 — загрузочный) и/или через панику |
+
+Несколько ядер на телефоне — в каком порядке пробовать (каждый шаг — отдельный `./xl run`, с
+`XL_CMDLINE="touchscreen=1 cpufreq=1 bootcpu=7 …"`; перед первым — `./xl reload`, загрузчик изменился):
+
+1. `cpus=2 wfi=0 wfe_mode=0`, `XL_SECS=60` — одно дополнительное ядро того же типа (6), простой без WFI. В журнале
+ загрузчика должна быть строка `cores for the kernel, in the order it takes them: 700 600 500 400 300 200 100`
+ (ядра, которые прошивка не считает выключенными, туда не попадают: `core … is not off`), в журнале ядра —
+ `GenericARMPE: 2 of 2 processors are running` и от `cpu_test` — `hw.activecpu 2`. Если ядро 6 не поднялось,
+ там же сказано почему: `psci: cpu 1 (MPIDR 0x600) …` — отказ прошивки, исключение до включения MMU (с ESR, ELR,
+ FAR) либо «has not joined», — а система работает дальше на одном. В конце журнала загрузчика не должно быть
+ `THE KERNEL LEFT CORE … RUNNING`.
+2. `cpus=2`, `XL_SECS=300` — то же с WFI в простое; на пятой минуте `cpu_test` пишет «2 threads at once took …
+ and were given … ms of processor time: 1.x processors at work, seen on 0 1» (с одним ядром больше 1.0 не бывает).
+3. `cpus=2 return_cpu=1`, затем `cpus=2 return_cpu=1 return_panic=1` (по минуте) — возврат в загрузчик не с
+ загрузочного ядра и через панику: журнал должен вернуться целиком, со строкой `psci: cpu 1 ends the system`
+ (во втором случае и с текстом паники `return_panic`).
+4. `cpus=4` — все большие ядра (7, 6, 5, 4).
+5. `cpumask=0x11` — большое и малое (7 и 3): разные типы ядер; потом `cpus=7` — все, кроме нулевого.
+
+Паника «Ticket spinlock … timeout» или «Spinlock timeout» при этом значила бы, что ядрам тесно во времени
+(в QEMU так и было, там загрузчик сам увеличивает эти сроки в 20 раз): `ml-timeout-global-scale=4` увеличит их.
## Сборка из исходников
diff --git a/qemu/run.sh b/qemu/run.sh
index 70939ef..dd8667b 100755
--- a/qemu/run.sh
+++ b/qemu/run.sh
@@ -3,6 +3,8 @@
# usage: run.sh [seconds] [extra qemu args...]
# env: QEMU_TB_MB megabytes for QEMU's cache of translated code (default 384; QEMU's own
# default of 1 GB mostly costs host memory)
+# QEMU_SMP processor cores of the machine (default 1); the kernel uses as many of them as
+# its boot-arg cpus=N says (CMDLINE="cpus=4" for run-ios.sh), one without it
# QEMU_EFI, QEMU_VARS the UEFI firmware for aarch64 guests (default: where Arch's edk2-aarch64
# puts it; Debian/Ubuntu: /usr/share/AAVMF/AAVMF_CODE.fd and AAVMF_VARS.fd)
cd "$(dirname "$0")"
@@ -14,7 +16,7 @@ cp "${QEMU_VARS:-/usr/share/edk2/aarch64/QEMU_VARS.fd}" vars.fd 2>/dev/null
# the one built here, or else the one that comes with the repository
L=../xnuloader/loader.efi; [ -f $L ] || L=../prebuilt/loader.efi
mkdir -p esp/EFI/BOOT && cp -u $L esp/EFI/BOOT/BOOTAA64.EFI
-timeout "$T" qemu-system-aarch64 -M virt,gic-version=3 -cpu cortex-a76 -smp 1 -m ${QEMU_MEM:-6G} \
+timeout "$T" qemu-system-aarch64 -M virt,gic-version=3 -cpu cortex-a76 -smp ${QEMU_SMP:-1} -m ${QEMU_MEM:-6G} \
-accel tcg,tb-size=${QEMU_TB_MB:-384} \
-drive if=pflash,format=raw,readonly=on,file="$EFI" \
-drive if=pflash,format=raw,file=vars.fd \
diff --git a/qemu/where.py b/qemu/where.py
index 4bf3ddb..19c6a90 100755
--- a/qemu/where.py
+++ b/qemu/where.py
@@ -1,5 +1,5 @@
#!/usr/bin/env python3
-"""Ask a running QEMU (its monitor: port 4444, or 4444 + 10 * QEMU_INSTANCE) where the guest CPU is, a few times."""
+"""Ask a running QEMU (its monitor: port 4444, or 4444 + 10 * QEMU_INSTANCE) where the guest's CPUs are, a few times."""
import socket, time, re, subprocess, sys, os
n = int(sys.argv[1]) if len(sys.argv) > 1 else 3
try:
@@ -21,10 +21,12 @@ def cmd(c):
cmd('')
pcs = []
for i in range(n):
- r = cmd('info registers')
- m = re.search(r'PC=([0-9a-f]+)', r); l = re.search(r'X30=([0-9a-f]+)', r)
- if m: pcs.append(('0x' + m.group(1), '0x' + l.group(1) if l else '0x0'))
+ # one block of registers per CPU ("CPU#n"); a machine with one CPU prints no such heading
+ for block in re.split(r'(?=CPU#\d+)', cmd('info registers -a')):
+ c = re.match(r'CPU#(\d+)', block)
+ m = re.search(r'PC=([0-9a-f]+)', block); l = re.search(r'X30=([0-9a-f]+)', block)
+ if m: pcs.append((c.group(1) if c else '0', '0x' + m.group(1), '0x' + l.group(1) if l else '0x0'))
time.sleep(1.0)
-for pc, lr in pcs:
+for cpu, pc, lr in pcs:
out = subprocess.run([os.path.join(os.path.dirname(__file__), 'sym.py'), pc, lr], capture_output=True, text=True).stdout.strip().replace('\n', ' <- lr ')
- print(out)
+ print(f'cpu {cpu}: {out}')
diff --git a/tools/update-prebuilt.sh b/tools/update-prebuilt.sh
index 8d7fe99..089433b 100755
--- a/tools/update-prebuilt.sh
+++ b/tools/update-prebuilt.sh
@@ -10,7 +10,7 @@ mkdir -p prebuilt/userland prebuilt/uefi
cp $K prebuilt/mach.development.bcm2837
cp xnuloader/loader.efi prebuilt/loader.efi
cp userland/hello prebuilt/userland/
-for f in init child stage0 hello_dyn svc_test surf_test rwtouch mg_test libredwood.dylib libredwood-sb.dylib; do
+for f in init child stage0 hello_dyn svc_test surf_test rwtouch mg_test cpu_test libredwood.dylib libredwood-sb.dylib; do
cp userland/obj/$f prebuilt/userland/
done
if [ -f $MU/Build/redwoodPkg/RELEASE_CLANGPDB/FV/SILICIUM_UEFI.fd ]; then
diff --git a/userland/build.sh b/userland/build.sh
index e241614..3062601 100755
--- a/userland/build.sh
+++ b/userland/build.sh
@@ -88,6 +88,7 @@ if [ -d $IOS/rootfs/usr/lib ]; then
$DYN -Wno-four-char-constants -framework CoreFoundation -framework IOSurface -o obj/surf_test src/surf_test.c
$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
# 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
@@ -95,6 +96,7 @@ if [ -d $IOS/rootfs/usr/lib ]; then
-o obj/libredwood-sb.dylib src/inject_sb.c
fi
cp 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)
mkdir -p root/lib
cp obj/libredwood.dylib obj/libredwood-sb.dylib root/lib/
echo "$INJECT" > root/etc/inject.conf
diff --git a/userland/rc.jobs b/userland/rc.jobs
index 30a3fff..4c9530c 100644
--- a/userland/rc.jobs
+++ b/userland/rc.jobs
@@ -4,3 +4,6 @@
/redwood/bin/surf_test
/bin/ps -A
/redwood/bin/mg_test
+# the processors: how many, and -- once the system has settled -- whether they work at the same time
+/redwood/bin/cpu_test
+/redwood/bin/cpu_test 240 &
diff --git a/userland/src/cpu_test.c b/userland/src/cpu_test.c
new file mode 100644
index 0000000..50de985
--- /dev/null
+++ b/userland/src/cpu_test.c
@@ -0,0 +1,115 @@
+/*
+ * How many processors the kernel has, and whether they really work at the same time: a fixed
+ * amount of arithmetic on one thread, then the same on each of as many threads as there are
+ * processors (two at least), and how much processor time the threads were given between
+ * them while that took: with one processor never more than the time that passed, with
+ * several of them free several times as much.
+ *
+ * usage: cpu_test [SECONDS] without an argument only the numbers; with one, wait that long
+ * (for a moment when the system is quiet) and then do the work
+ */
+#include <mach/mach_time.h>
+#include <pthread.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <sys/resource.h>
+#include <sys/sysctl.h>
+#include <unistd.h>
+
+#define ROUNDS 60000000ULL
+#define MOST 16
+
+static int
+number(const char *name)
+{
+ int value = -1;
+ size_t size = sizeof(value);
+
+ sysctlbyname(name, &value, &size, NULL, 0);
+ return value;
+}
+
+static uint64_t
+milliseconds(void)
+{
+ static mach_timebase_info_data_t timebase;
+
+ if (timebase.denom == 0) {
+ mach_timebase_info(&timebase);
+ }
+ return mach_absolute_time() * timebase.numer / timebase.denom / 1000000;
+}
+
+/* The processor time this process has used so far, in milliseconds. */
+static uint64_t
+used(void)
+{
+ struct rusage usage;
+
+ getrusage(RUSAGE_SELF, &usage);
+ return (uint64_t)(usage.ru_utime.tv_sec + usage.ru_stime.tv_sec) * 1000 +
+ (uint64_t)(usage.ru_utime.tv_usec + usage.ru_stime.tv_usec) / 1000;
+}
+
+/* The work; says which processor it found itself on at the end. */
+static void *
+work(void *arg)
+{
+ volatile uint64_t sum = 0;
+ size_t cpu = 0;
+
+ for (uint64_t i = 0; i < ROUNDS; i++) {
+ sum += i * i;
+ }
+ pthread_cpu_number_np(&cpu);
+ *(int *)arg = (int)cpu;
+ return NULL;
+}
+
+int
+main(int argc, char **argv)
+{
+ int active = number("hw.activecpu"), threads = active < 2 ? 2 : active > MOST ? MOST : active;
+ int where[MOST], seen = 0;
+ pthread_t thread[MOST];
+ uint64_t start, alone, together, spent;
+
+ if (argc > 1) {
+ sleep((unsigned)atoi(argv[1]));
+ }
+ printf("cpu_test: hw.ncpu %d, hw.activecpu %d, hw.physicalcpu %d, hw.logicalcpu %d\n", number("hw.ncpu"),
+ number("hw.activecpu"), number("hw.physicalcpu"), number("hw.logicalcpu"));
+ if (argc < 2) {
+ return 0;
+ }
+
+ start = milliseconds();
+ work(&where[0]);
+ alone = milliseconds() - start;
+
+ start = milliseconds();
+ spent = used();
+ for (int i = 0; i < threads; i++) {
+ pthread_create(&thread[i], NULL, work, &where[i]);
+ }
+ for (int i = 0; i < threads; i++) {
+ pthread_join(thread[i], NULL);
+ seen |= 1 << where[i];
+ }
+ spent = used() - spent;
+ together = milliseconds() - start;
+ if (together == 0) {
+ together = 1;
+ }
+
+ printf("cpu_test: one thread took %llu ms; %d threads at once took %llu ms and were given %llu ms of processor time: "
+ "%llu.%llu processors at work, seen on", alone, threads, together, spent, spent / together, spent * 10 / together % 10);
+ for (int cpu = 0; cpu < 32; cpu++) {
+ if (seen & (1 << cpu)) {
+ printf(" %d", cpu);
+ }
+ }
+ printf("\n");
+ return 0;
+}
diff --git a/userland/src/inject.c b/userland/src/inject.c
index a8a09f6..b1e747d 100644
--- a/userland/src/inject.c
+++ b/userland/src/inject.c
@@ -272,6 +272,7 @@ extern IOHIDEventSystemClientRef IOHIDEventSystemClientCreateWithType(CFAllocato
extern void IOHIDEventSystemClientScheduleWithDispatchQueue(IOHIDEventSystemClientRef client, dispatch_queue_t queue);
extern IOHIDServiceClientRef IOHIDVirtualServiceClientCreateWithCallbacks(IOHIDEventSystemClientRef client, CFDictionaryRef attributes,
const struct virtual_service_callbacks *callbacks, void *target, void *refcon);
+extern Boolean IOHIDVirtualServiceClientRemove(IOHIDServiceClientRef service);
extern Boolean IOHIDVirtualServiceClientDispatchEvent(IOHIDServiceClientRef service, IOHIDEventRef event);
extern IOHIDEventRef IOHIDEventCreateDigitizerEvent(CFAllocatorRef allocator, uint64_t time, uint32_t transducer, uint32_t index,
uint32_t identity, uint32_t event_mask, uint32_t button_mask, double x, double y, double z, double tip_pressure,
@@ -326,12 +327,18 @@ number(int value)
return CFNumberCreate(NULL, kCFNumberIntType, &value);
}
+/* A service of ours (the callbacks' refcon): what it says of itself, and whether the event server has taken it. */
+struct service {
+ CFMutableDictionaryRef properties;
+ volatile bool opened;
+};
+
/* The properties of a service of ours; the event server asks for them one at a time. */
static CFTypeRef
service_copy_property(__unused void *target, void *refcon, __unused IOHIDServiceClientRef service, CFStringRef key)
{
static CFMutableSetRef asked;
- CFTypeRef value = CFDictionaryGetValue((CFDictionaryRef)refcon, key);
+ CFTypeRef value = CFDictionaryGetValue(((struct service *)refcon)->properties, key);
if (asked == NULL) {
asked = CFSetCreateMutable(NULL, 0, &kCFTypeSetCallBacks);
@@ -359,13 +366,18 @@ static volatile int touch_mode;
/* What the event server tells a service of ours: said once per name, to learn what there is. */
static Boolean
-service_set_property(__unused void *target, __unused void *refcon, __unused IOHIDServiceClientRef service, CFStringRef key,
+service_set_property(__unused void *target, void *refcon, __unused IOHIDServiceClientRef service, CFStringRef key,
CFTypeRef value)
{
static CFMutableSetRef told;
char name[96] = "?", text[160] = "?";
CFStringRef description;
+ /* the last thing the event server does when it opens a service; see make_service() */
+ if (key != NULL && value != NULL && CFEqual(key, CFSTR("DeviceOpenedByEventSystem")) &&
+ CFGetTypeID(value) == CFBooleanGetTypeID() && CFBooleanGetValue(value)) {
+ ((struct service *)refcon)->opened = true;
+ }
if (key != NULL && value != NULL && CFEqual(key, CFSTR("TouchDetectionMode")) && CFGetTypeID(value) == CFNumberGetTypeID()) {
int mode = 0;
@@ -402,10 +414,22 @@ static const struct virtual_service_callbacks service_callbacks = {
.copyProperty = service_copy_property,
};
-/* A HID service of ours inside the event server: built in, with one usage. */
+/*
+ * A HID service of ours inside the event server: built in, with one usage.
+ *
+ * The event server is this very program, and it is still starting. A client that reaches it at
+ * the wrong moment of that (backboardd's "HID system open ... start": the connection is made
+ * and then replaced, "IOHIDEventSystemServer died. Reestablishing connection.") is left with a
+ * service the server cannot talk to and never opens -- and a touch screen that backboardd waits
+ * for in vain ("still waiting for a main screen digitizer"). When that moment comes depends on
+ * how fast the machine is and on how many processors it has, so no fixed delay avoids it:
+ * the service is made again until the server has opened it.
+ */
static IOHIDServiceClientRef
make_service(IOHIDEventSystemClientRef client, const char *product, int page, int usage, bool display)
{
+ struct service *made = calloc(1, sizeof(*made));
+ IOHIDServiceClientRef service = NULL;
CFMutableDictionaryRef properties = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks,
&kCFTypeDictionaryValueCallBacks);
CFMutableDictionaryRef pair = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks,
@@ -432,7 +456,25 @@ make_service(IOHIDEventSystemClientRef client, const char *product, int page, in
CFDictionarySetValue(properties, CFSTR("DisplayIntegrated"), kCFBooleanTrue);
}
/* the dictionary stays: it is what service_copy_property() answers from */
- return IOHIDVirtualServiceClientCreateWithCallbacks(client, properties, &service_callbacks, NULL, properties);
+ made->properties = properties;
+ for (int attempt = 1; attempt <= 20; attempt++) {
+ made->opened = false;
+ service = IOHIDVirtualServiceClientCreateWithCallbacks(client, properties, &service_callbacks, NULL, made);
+ if (service == NULL) {
+ break;
+ }
+ for (int tenths = 0; tenths < 20 && !made->opened; tenths++) {
+ usleep(100000);
+ }
+ if (made->opened) {
+ break;
+ }
+ say("redwood: input: the event server has not opened \"%s\" (attempt %d): making it again\n", product, attempt);
+ IOHIDVirtualServiceClientRemove(service);
+ CFRelease(service);
+ service = NULL;
+ }
+ return service;
}
/* One frame of the touch screen: the hand, and under it every finger that is down or has just lifted. */
@@ -616,10 +658,11 @@ redwood_init(void)
if (strcmp(name, "backboardd") == 0) {
window_server_fixes();
/*
- * brightness_fixes() is not used for now: with it backboardd no longer takes our touch
+ * brightness_fixes() is not used for now: with it backboardd no longer took our touch
* screen service for its own ("still waiting for a main screen digitizer"), whether the
- * service is made before or after the touch processing starts. Why is not known yet;
- * until it is, the five seconds stay.
+ * service was made before or after the touch processing starts. (Most likely it only
+ * moved the start of the event server onto the moment make_service() now knows how to
+ * survive; not tried again since, and until it is, the five seconds stay.)
*/
input_start();
} else if (strncmp(name, "containermanagerd", 17) == 0) {
diff --git a/xnu/README.md b/xnu/README.md
index da4fcf8..bf5f106 100644
--- a/xnu/README.md
+++ b/xnu/README.md
@@ -52,6 +52,7 @@ xnu-deps/setup.sh # ~30 с: исходники зависимостей,
| Файлы | Что |
|---|---|
| `osfmk/arm64/gic_v3_irq.c`, `generic_arm64_support.c`, `kpc.c`, `ppl/`, `tunables/` | платформа: GICv3, таймер, заглушки вырезанных Apple файлов |
+| `osfmk/arm64/psci_smp.c` | несколько процессоров: запуск ядер через PSCI (boot-arg `cpus=N`), их остановка перед возвратом в загрузчик |
| `osfmk/arm64/loader_return.c` | возврат в загрузчик с журналом, «сердцебиение», сторожевой таймер гипервизора Qualcomm |
| `osfmk/arm64/user_exception_trace.c` | отладка userland: `usertrap:`, `userabort:`, стеки потоков (`ustacks`) |
| `osfmk/minicrypto/` | замена corecrypto: MD5/SHA-1/SHA-2, HMAC, DRBG, AES (исходники Apple corecrypto не использованы) |
diff --git a/xnuloader/loader.c b/xnuloader/loader.c
index 86cec63..ad55654 100644
--- a/xnuloader/loader.c
+++ b/xnuloader/loader.c
@@ -449,17 +449,28 @@ struct platform {
uint64_t uart; /* PL011, 0 if none */
int psci_hvc; /* the firmware's power interface is called with HVC, not SMC */
int log_other_cpu; /* keep notes in the log partition while a kernel starts on another core */
+ int cores; /* at most this many processor cores, numbered from 0 ... */
+ int core_shift; /* ... in this bit of MPIDR: the phone numbers them in the second affinity field */
+ uint32_t timeout_scale; /* a kernel on several cores gets this much longer to wait for a lock, 0: as it is */
};
static const struct platform platform_qemu_virt = {
.name = "qemu-virt", .io_base = 0x08000000, .io_size = 0x08000000,
.gic_dist = 0x08000000, .gic_redist = 0x080A0000, .uart = 0x09000000, .psci_hvc = 1,
+ .cores = 8, .core_shift = 0,
+ /*
+ * QEMU's emulated cores stop each other all the time (every flush of a page from all the
+ * TLBs is a rendezvous of all its CPU threads), and the kernel's patience with a spin lock
+ * is that of real hardware: an eighth of a second by a 24 MHz clock, a twentieth here.
+ */
+ .timeout_scale = 20,
};
static const struct platform platform_redwood = {
/* io_base must be non-zero: XNU treats a zero SoC base as "no SoC" and skips clock setup. */
.name = "redwood", .io_base = 0x00400000, .io_size = 0x3FC00000,
.gic_dist = 0x17A00000, .gic_redist = 0x17A60000, .uart = 0, .log_other_cpu = 1,
+ .cores = 8, .core_shift = 8,
};
/* ------------------------------------------------------------------------ */
@@ -657,6 +668,8 @@ jump_to_kernel(uint64_t entry, uint64_t boot_args_pa)
#define PSCI_CPU_OFF 0x84000002u
#define PSCI_CPU_ON 0xC4000003u
+#define PSCI_AFFINITY_INFO 0xC4000004u /* (MPIDR, 0): 0 = that core is on, 1 = off, 2 = being started */
+#define PSCI_NOT_SUPPORTED (-1)
/* each alone in a cache line: one core reads them with its caches off */
static struct {
@@ -857,6 +870,29 @@ note_kernel_progress(const struct kernel_live *live, uint64_t slide, uint64_t se
print("\n");
}
+/* A call of the firmware's power interface, the way this platform makes them. */
+static int64_t
+psci_call(uint64_t function, uint64_t a1, uint64_t a2, uint64_t a3)
+{
+ int64_t status;
+
+ if (PLAT->psci_hvc) {
+ register uint64_t x0 __asm__("x0") = function;
+ register uint64_t x1 __asm__("x1") = a1;
+ register uint64_t x2 __asm__("x2") = a2;
+ register uint64_t x3 __asm__("x3") = a3;
+
+ __asm__ volatile ("hvc #0" : "+r" (x0), "+r" (x1), "+r" (x2), "+r" (x3)
+ : : "x4", "x5", "x6", "x7", "x8", "x9", "x10", "x11", "x12", "x13", "x14", "x15", "x16", "x17");
+ status = (int64_t)x0;
+ } else {
+ smc_x3 = a3;
+ status = (int64_t)smc_call(function, a1, a2, NULL, NULL);
+ smc_x3 = 0;
+ }
+ return status;
+}
+
/*
* Run the kernel on the core with that MPIDR and wait until it is back. Returns 0 when it has
* been and gone (the caller goes on as after loader_return_stub), a negative number if the
@@ -886,20 +922,8 @@ run_on_other_cpu(uint64_t mpidr, uint64_t entry, uint64_t boot_args_pa, const st
clean_dcache((uint64_t)(uintptr_t)&other_cpu_entry, (uint64_t)(uintptr_t)&other_cpu_entry + 0x1000);
clean_dcache((uint64_t)(uintptr_t)loader_ctx, (uint64_t)(uintptr_t)loader_ctx + sizeof(loader_ctx));
- if (psci_by_hvc) {
- register uint64_t x0 __asm__("x0") = PSCI_CPU_ON;
- register uint64_t x1 __asm__("x1") = mpidr;
- register uint64_t x2 __asm__("x2") = (uint64_t)(uintptr_t)&other_cpu_entry;
- register uint64_t x3 __asm__("x3") = (uint64_t)(uintptr_t)&other_cpu_start;
-
- __asm__ volatile ("hvc #0" : "+r" (x0), "+r" (x1), "+r" (x2), "+r" (x3)
- : : "x4", "x5", "x6", "x7", "x8", "x9", "x10", "x11", "x12", "x13", "x14", "x15", "x16", "x17");
- status = (int64_t)x0;
- } else {
- smc_x3 = (uint64_t)(uintptr_t)&other_cpu_start; /* arrives in that core's x0 */
- status = (int64_t)smc_call(PSCI_CPU_ON, mpidr, (uint64_t)(uintptr_t)&other_cpu_entry, NULL, NULL);
- smc_x3 = 0;
- }
+ /* the last argument arrives in that core's x0 */
+ status = psci_call(PSCI_CPU_ON, mpidr, (uint64_t)(uintptr_t)&other_cpu_entry, (uint64_t)(uintptr_t)&other_cpu_start);
started = last_pet = last_beat_at = READ_SYSREG(CNTVCT_EL0);
print("core %x: the firmware answers %d to the request to start it\n", mpidr, (uint64_t)status);
@@ -1443,11 +1467,13 @@ run_kernel(int have_checkpoint, uint64_t checkpoint)
/* "bootcpu=N" among the kernel's arguments: run it on core N (see run_on_other_cpu) */
uint64_t this_mpidr = READ_SYSREG(MPIDR_EL1) & 0xFFFFFF, kernel_mpidr = this_mpidr;
+ /* "cpus=N" or "cpumask=M" there too: the kernel may have more cores than the one it starts on */
+ int more_cores = 0;
for (const char *c = pi.cmdline; *c; c++) {
if (starts_with(c, "bootcpu=") && (c == pi.cmdline || c[-1] == ' ') && c[8] >= '0' && c[8] <= '7') {
- /* this phone numbers its cores in the second affinity field, QEMU in the first */
- kernel_mpidr = (uint64_t)(c[8] - '0') << (PLAT == &platform_redwood ? 8 : 0);
+ kernel_mpidr = (uint64_t)(c[8] - '0') << PLAT->core_shift;
}
+ more_cores |= (starts_with(c, "cpus=") || starts_with(c, "cpumask=")) && (c == pi.cmdline || c[-1] == ' ');
}
if (checkpoint == CHECKPOINT_SELFTEST) {
kernel_mpidr = this_mpidr;
@@ -1525,11 +1551,17 @@ run_kernel(int have_checkpoint, uint64_t checkpoint)
for (const char *c = pi.cmdline; *c; c++) {
own_serial |= starts_with(c, "serial=");
}
- const char *base_cmdline = (PLAT->uart != 0 && !own_serial) ? "debug=0x8 serial=3 cpus=1 " : "debug=0x8 cpus=1 ";
+ const char *base_cmdline = (PLAT->uart != 0 && !own_serial) ? "debug=0x8 serial=3 " : "debug=0x8 ";
uint32_t n = 0;
for (const char *c = base_cmdline; *c && n < BOOT_LINE_LENGTH - 1; c++) {
ba->commandLine[n++] = *c;
}
+ /* one processor unless the payload asks for more (of two "cpus=" the kernel takes the first) */
+ if (!more_cores) {
+ for (const char *c = "cpus=1 "; *c && n < BOOT_LINE_LENGTH - 1; c++) {
+ ba->commandLine[n++] = *c;
+ }
+ }
/* the root is the first RAM disk unless the payload says otherwise */
int own_root = 0;
for (const char *c = pi.cmdline; *c; c++) {
@@ -1586,6 +1618,8 @@ run_kernel(int have_checkpoint, uint64_t checkpoint)
/* what MobileGestalt answers "main screen scale" from: 3 device pixels per point */
dt_prop_u32(&w, "display-scale", 3);
dt_prop_u32(&w, "display-rotation", 0);
+ /* how the kernel is to ask the firmware for more cores (PSCI) */
+ dt_prop_str(&w, "psci-method", plat->psci_hvc ? "hvc" : "smc");
/* the time now, by the firmware's clock (the kernel has no real-time clock driver) */
uint64_t epoch = firmware_epoch();
if (epoch != 0) {
@@ -1639,6 +1673,12 @@ run_kernel(int have_checkpoint, uint64_t checkpoint)
dt_prop(&w, "RAMDisk1", second, sizeof(second));
}
dt_end(&w);
+ if (more_cores && plat->timeout_scale != 0) {
+ /* multiplies every "machine timeout" of the kernel (machine_timeout_init_with_suffix()) */
+ dt_begin(&w, "machine-timeouts");
+ dt_prop_u32(&w, "global-scale", plat->timeout_scale);
+ dt_end(&w);
+ }
dt_end(&w);
dt_begin(&w, "defaults");
@@ -1660,19 +1700,60 @@ run_kernel(int have_checkpoint, uint64_t checkpoint)
dt_prop(&w, "reg", pram_reg, sizeof(pram_reg));
dt_end(&w);
+ /*
+ * The processors. The first is the one the kernel starts on. With "cpus=N" in its
+ * arguments the kernel takes that one and the next N-1 of this list and starts them
+ * itself (PSCI CPU_ON); "cpumask=M" picks by position, bit 0 being the first. So the
+ * order matters: after the boot core come those whose numbers are nearest to its own
+ * (on the phone, where the kernel boots on the biggest core, 7: the other big ones
+ * 6, 5, 4, then the small ones 3, 2, 1). Only cores that are off are listed: the one
+ * this loader stays on while it watches is not the kernel's, nor any the firmware runs.
+ */
+ uint64_t cpu_mpidr[8] = { kernel_mpidr };
+ int cpu_count = 1, boot_core = (int)(kernel_mpidr >> plat->core_shift);
+
+ if (more_cores) {
+ for (int distance = 1; distance < plat->cores; distance++) {
+ for (int side = 0; side < 2; side++) {
+ int core = side == 0 ? boot_core + distance : boot_core - distance;
+ uint64_t mpidr = (uint64_t)core << plat->core_shift;
+ int64_t state;
+
+ if (core < 0 || core >= plat->cores || mpidr == this_mpidr) {
+ continue;
+ }
+ state = psci_call(PSCI_AFFINITY_INFO, mpidr, 0, 0);
+ if (state == 1 || state == PSCI_NOT_SUPPORTED) {
+ cpu_mpidr[cpu_count++] = mpidr;
+ } else if (state >= 0) {
+ print("core %x is not off (the firmware says %d): not the kernel's to take\n", mpidr, (uint64_t)state);
+ }
+ }
+ }
+ print("cores for the kernel, in the order it takes them:");
+ for (int i = 0; i < cpu_count; i++) {
+ print(" %x", cpu_mpidr[i]);
+ }
+ print("\n");
+ }
+
dt_begin(&w, "cpus");
- dt_begin(&w, "cpu0");
- dt_prop_str(&w, "device_type", "cpu");
- dt_prop_str(&w, "state", "running");
- dt_prop_u32(&w, "reg", (uint32_t)kernel_mpidr);
- dt_prop_u32(&w, "cpu-id", 0);
- dt_prop_u64(&w, "timebase-frequency", cntfrq);
- dt_prop_u64(&w, "fixed-frequency", cntfrq);
- dt_prop_u64(&w, "clock-frequency", 1800000000ULL);
- dt_prop_u64(&w, "bus-frequency", 100000000ULL);
- dt_prop_u64(&w, "memory-frequency", 100000000ULL);
- dt_prop_u64(&w, "peripheral-frequency", 24000000ULL);
- dt_end(&w);
+ for (int i = 0; i < cpu_count; i++) {
+ char name[5] = { 'c', 'p', 'u', (char)('0' + i), 0 };
+
+ dt_begin(&w, name);
+ dt_prop_str(&w, "device_type", "cpu");
+ dt_prop_str(&w, "state", i == 0 ? "running" : "waiting");
+ dt_prop_u32(&w, "reg", (uint32_t)cpu_mpidr[i]);
+ dt_prop_u32(&w, "cpu-id", (uint32_t)i);
+ dt_prop_u64(&w, "timebase-frequency", cntfrq);
+ dt_prop_u64(&w, "fixed-frequency", cntfrq);
+ dt_prop_u64(&w, "clock-frequency", 1800000000ULL);
+ dt_prop_u64(&w, "bus-frequency", 100000000ULL);
+ dt_prop_u64(&w, "memory-frequency", 100000000ULL);
+ dt_prop_u64(&w, "peripheral-frequency", 24000000ULL);
+ dt_end(&w);
+ }
dt_end(&w);
dt_begin(&w, "arm-io");
@@ -1770,6 +1851,15 @@ run_kernel(int have_checkpoint, uint64_t checkpoint)
/* --- the kernel came back ------------------------------------------- */
wdt_set_ms(WDT_BITE_MS);
+ /* ... and its other cores should all be off again: the next kernel cannot start one that is not */
+ for (int i = 1; i < cpu_count; i++) {
+ int64_t state = psci_call(PSCI_AFFINITY_INFO, cpu_mpidr[i], 0, 0);
+
+ if (state != 1 && state != PSCI_NOT_SUPPORTED) {
+ print("THE KERNEL LEFT CORE %x RUNNING (the firmware says %d): restart before running another\n", cpu_mpidr[i],
+ (uint64_t)state);
+ }
+ }
recording_data = NULL;
recording_len = 0;
if (kernel_live != NULL && kernel_live->recording != 0 && checkpoint != CHECKPOINT_SELFTEST) {