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

Frames: the window server's surfaces made in 0.2 ms again, not 3; memory bandwidth vote; frame queue

vcvkkee69ef66e276
diff --git a/README.md b/README.md
index 62abdbb..c78315c 100644
--- a/README.md
+++ b/README.md
@@ -228,6 +228,10 @@ XL_SECS=900 XL_CMDLINE="touchscreen=1 cpufreq=1 bootcpu=7 cpus=4" ./xl run #
| `fbscale=2` | рисовать в 2 пикселя на точку вместо 3 и растягивать на панель: в 2,25 раза меньше работы программному рендеру (на телефоне пик 28 кадров/с вместо 19), картинка мягче, сверху появляется красная служебная полоса SpringBoard |
| `fb_filter=0` | масштабировать картинку на панель «ближайшим соседом», как раньше. По умолчанию каждый пиксель панели смешивается из четырёх соседних пикселей картинки (билинейно): 1125×2436 на 1080×2400 «ближайший сосед» выбрасывает каждый 25-й столбец и каждую 67-ю строку, и буквы и наклонные линии там, где они попадают на выброшенные, выходят чуть кривыми. Цена — около 9 мс на кадр в потоке драйвера экрана вместо 4 (отдельный поток, частота кадров та же), если считает одно ядро |
| `fb_threads=N` | столько ядер вместе масштабируют кадр на панель (по умолчанию 3: кадр в памяти панели через 3 мс вместо 9–10; `fb_threads=1` — как было) |
+| `fb_queue=2` | драйверу экрана могут ждать два кадра, а не один: CoreAnimation не задерживается в SwapEnd до следующего тика своих часов (задержанный тик сдвигает её часы, и кадр выходит через 19–20 мс вместо 16,7). Разница в замерах мала |
+| `ddr=2` | голос за пропускную способность памяти через RPMh, как у драйвера межсоединений Linux под нагрузкой GPU: контроллер памяти (MC0) и общий узел с системным кэшем (SH0) — на максимум, память включена для процессора (ACV). Все ядра вместе получают от памяти на 17–20 % больше (`membench=2`: 14,8 ГБ/с записи вместо 12,4), кадров дольше 16,7 мс 28 % вместо 34–36 %: Пункт управления 59 кадров/с вместо 46, открытие Настроек 37 вместо 29, Поиск 45 вместо 36. После сеанса голос остаётся максимальным (`ddr_rest=N` — другой; что просила прошивка, прочесть нельзя). `ddr_vote=N` — голос N вместо 16383. `ddr=1` — только прочесть и напечатать BCM из базы команд и то, что лежит в слотах команд RPMh |
+| `membench=1` / `membench=2` | скорость памяти для одного ядра / для всех наших ядер сразу (сумма — то, что даёт память на своей частоте) |
+| `caenv=ИМЯ=ЗНАЧЕНИЕ` | (сколько угодно раз) в окружение оконного сервера: переключатели самой CoreAnimation (`CA_…`) |
| `fb_beat=0` | кадр уходит на панель сразу, как GPU его закончил, а не по собственному такту драйвера 60 Гц (такт держит ровный шаг, но кадр ждёт его в среднем 5–7 мс; панель всё равно обновляется 120 раз в секунду и к такту не привязана) |
| `ca_vbl=1` | (опыт) CoreAnimation ведёт кадры по уведомлениям драйвера экрана о такте (`CA_FORCE_TIMER=1` в backboardd), а не по своим часам; на ровность кадров не повлияло |
| `machine_name=0` | сообщать `hw.machine = arm64` вместо iPhone10,3 (как было раньше; тогда iOS не находит ни одного ресурса с суффиксом `~iphone`, и, например, Пункт управления теряет раскладку) |
diff --git a/userland/src/inject.c b/userland/src/inject.c
index f04104f..7dff42c 100644
--- a/userland/src/inject.c
+++ b/userland/src/inject.c
@@ -845,6 +845,26 @@ redwood_init(void)
setenv("CA_FORCE_TIMER", "1", 1);
say("redwood: ca_vbl=1: CoreAnimation is to take the display driver's refresh notifications\n");
}
+ /*
+ * Boot-arg caenv=NAME=VALUE (as many as wanted): into the window server's environment, for
+ * CoreAnimation's own switches (CA_LOG_TRIPLE_BUFFERING=1, CA_FORCE_DOUBLE_BUFFERING=1 ...).
+ */
+ for (const char *argument = arguments; (argument = strstr(argument, "caenv=")) != NULL; argument += 6) {
+ char setting[128];
+ size_t length = strcspn(argument + 6, " ");
+ char *equals;
+
+ if ((argument != arguments && argument[-1] != ' ') || length == 0 || length >= sizeof(setting)) {
+ continue;
+ }
+ memcpy(setting, argument + 6, length);
+ setting[length] = 0;
+ if ((equals = strchr(setting, '=')) != NULL) {
+ *equals = 0;
+ setenv(setting, equals + 1, 1);
+ say("redwood: caenv: %s=%s for the window server\n", setting, equals + 1);
+ }
+ }
opengl_es();
window_server_fixes();
/*
diff --git a/userland/src/inject_sb.c b/userland/src/inject_sb.c
index e67698a..657c4e9 100644
--- a/userland/src/inject_sb.c
+++ b/userland/src/inject_sb.c
@@ -63,12 +63,14 @@ say(const char *format, ...)
/*
* Boot-arg touch_lat=1: a line for every turn of SpringBoard's main run loop -- when it woke up (a
- * touch, a timer, the display link ...) and when it went to sleep again, CoreAnimation's commit of
- * what that turn changed done (its observer comes before ours) -- in microseconds of
- * mach_absolute_time, as the other "tl:" lines (tools/latency.py, tools/frames.py):
- * tl: a WOKE SLEPT
+ * touch, a timer, the display link ...), when CoreAnimation's commit of what that turn changed
+ * began and when it was done (our observers just before and after its own, of order 2000000), in
+ * microseconds of mach_absolute_time, as the other "tl:" lines (tools/latency.py, tools/frames.py):
+ * tl: a WOKE COMMIT DONE
+ * (a commit with nothing in it takes some microseconds; one that sends changes, a good deal more)
*/
-static uint64_t main_woke;
+#define CA_COMMIT_ORDER 2000000
+static uint64_t main_woke, commit_began;
static mach_timebase_info_data_t timebase;
static uint64_t
@@ -78,12 +80,14 @@ now_us(void)
}
static void
-main_loop_turn(__unused CFRunLoopObserverRef observer, CFRunLoopActivity activity, __unused void *info)
+main_loop_turn(__unused CFRunLoopObserverRef observer, CFRunLoopActivity activity, void *info)
{
if (activity == kCFRunLoopAfterWaiting) {
main_woke = now_us();
+ } else if (activity == kCFRunLoopBeforeWaiting && info == NULL) {
+ commit_began = now_us();
} else if (activity == kCFRunLoopBeforeWaiting && main_woke != 0) {
- say("tl: a %llu %llu\n", main_woke, now_us());
+ say("tl: a %llu %llu %llu\n", main_woke, commit_began, now_us());
main_woke = 0;
}
}
@@ -102,8 +106,14 @@ watch_main_loop(void)
mach_timebase_info(&timebase);
CFRunLoopAddObserver(CFRunLoopGetMain(), CFRunLoopObserverCreate(NULL, kCFRunLoopAfterWaiting, true, LONG_MIN,
main_loop_turn, NULL), kCFRunLoopCommonModes);
- CFRunLoopAddObserver(CFRunLoopGetMain(), CFRunLoopObserverCreate(NULL, kCFRunLoopBeforeWaiting, true, LONG_MAX,
+ CFRunLoopAddObserver(CFRunLoopGetMain(), CFRunLoopObserverCreate(NULL, kCFRunLoopBeforeWaiting, true, CA_COMMIT_ORDER - 1,
main_loop_turn, NULL), kCFRunLoopCommonModes);
+ {
+ CFRunLoopObserverContext after = { .info = (void *)1 };
+
+ CFRunLoopAddObserver(CFRunLoopGetMain(), CFRunLoopObserverCreate(NULL, kCFRunLoopBeforeWaiting, true,
+ CA_COMMIT_ORDER + 1, main_loop_turn, &after), kCFRunLoopCommonModes);
+ }
}
/* ---- methods of SpringBoard's classes, replaced --------------------------------------------------- */
diff --git a/xnu/files/bsd/dev/redwood_cpufreq.c b/xnu/files/bsd/dev/redwood_cpufreq.c
index 9c438ae..effa4fb 100644
--- a/xnu/files/bsd/dev/redwood_cpufreq.c
+++ b/xnu/files/bsd/dev/redwood_cpufreq.c
@@ -13,6 +13,7 @@
*/
#include <kern/clock.h>
#include <kern/thread.h>
+#include <os/atomic_private.h>
#include <libkern/libkern.h>
#include <mach/mach_types.h>
#include <machine/machine_routines.h>
@@ -22,6 +23,7 @@
#include <vm/vm_kern.h>
extern vm_offset_t ml_io_map(vm_offset_t phys_addr, vm_size_t size);
+extern vm_offset_t ml_io_map_wcomb(vm_offset_t phys_addr, vm_size_t size);
extern void loader_log_putc(char c);
extern void redwood_tl(const char *format, ...) __printflike(1, 2);
extern bool ml_cpu_idle_time(int cpu_id, uint64_t *idle);
@@ -146,6 +148,98 @@ memory_bench(void)
kmem_free(kernel_map, b, size);
}
+/*
+ * Boot-arg membench=2: the same on every core of ours at once (a thread each, started together, 16 MB
+ * at a time), 2 s after this starts, so that all the cores are up: the sum of what they get is what
+ * the memory gives at the clock it has been left at.
+ */
+#define BENCH_THREADS 8
+static struct {
+ volatile uint32_t ready, go, done;
+ uint64_t ns[BENCH_THREADS][3];
+ uint32_t core[BENCH_THREADS];
+} bench;
+
+static void
+bench_thread(void *arg, wait_result_t wr __unused)
+{
+ const vm_size_t size = 16u << 20;
+ uintptr_t index = (uintptr_t)arg;
+ vm_offset_t a = 0, b = 0;
+ volatile uint64_t sum = 0;
+
+ if (kmem_alloc(kernel_map, &a, size, KMA_KOBJECT | KMA_DATA, VM_KERN_MEMORY_DIAG) != KERN_SUCCESS ||
+ kmem_alloc(kernel_map, &b, size, KMA_KOBJECT | KMA_DATA, VM_KERN_MEMORY_DIAG) != KERN_SUCCESS) {
+ os_atomic_inc(&bench.ready, relaxed);
+ os_atomic_inc(&bench.done, relaxed);
+ return;
+ }
+ memset((void *)a, 1, size);
+ memset((void *)b, 2, size);
+ os_atomic_inc(&bench.ready, relaxed);
+ while (!os_atomic_load(&bench.go, acquire)) {
+ }
+ bench.core[index] = (uint32_t)(__builtin_arm_rsr64("MPIDR_EL1") >> 8) & 0xff;
+ for (int round = 0; round < 4; round++) {
+ uint64_t began, t;
+
+ began = mach_absolute_time();
+ memset((void *)a, round, size);
+ absolutetime_to_nanoseconds(mach_absolute_time() - began, &t);
+ bench.ns[index][0] += t;
+ began = mach_absolute_time();
+ for (const uint64_t *p = (const uint64_t *)b, *end = (const uint64_t *)(b + size); p < end; p += 8) {
+ sum += p[0] + p[1] + p[2] + p[3] + p[4] + p[5] + p[6] + p[7];
+ }
+ absolutetime_to_nanoseconds(mach_absolute_time() - began, &t);
+ bench.ns[index][1] += t;
+ began = mach_absolute_time();
+ memcpy((void *)b, (const void *)a, size);
+ absolutetime_to_nanoseconds(mach_absolute_time() - began, &t);
+ bench.ns[index][2] += t;
+ }
+ os_atomic_inc(&bench.done, release);
+ kmem_free(kernel_map, a, size);
+ kmem_free(kernel_map, b, size);
+}
+
+static void
+bench_all(void *arg __unused, wait_result_t wr __unused)
+{
+ const uint32_t threads = MIN(ml_get_topology_info()->num_cpus, BENCH_THREADS);
+ const uint64_t mb = 4 * 16; /* per thread and test */
+ uint64_t total[3] = { 0, 0, 0 };
+
+ delay_for_interval(2000, NSEC_PER_MSEC);
+ for (uintptr_t i = 0; i < threads; i++) {
+ thread_t thread;
+
+ if (kernel_thread_start(bench_thread, (void *)i, &thread) == KERN_SUCCESS) {
+ thread_deallocate(thread);
+ } else {
+ os_atomic_inc(&bench.ready, relaxed);
+ os_atomic_inc(&bench.done, relaxed);
+ }
+ }
+ while (os_atomic_load(&bench.ready, relaxed) < threads) {
+ delay_for_interval(1, NSEC_PER_MSEC);
+ }
+ os_atomic_store(&bench.go, 1, release);
+ while (os_atomic_load(&bench.done, acquire) < threads) {
+ delay_for_interval(1, NSEC_PER_MSEC);
+ }
+ for (uint32_t i = 0; i < threads; i++) {
+ tell("membench: all at once: core %u: writing %llu MB/s, reading %llu MB/s, copying %llu MB/s\n", bench.core[i],
+ bench.ns[i][0] ? mb * 1000000000ull / bench.ns[i][0] : 0, bench.ns[i][1] ? mb * 1000000000ull / bench.ns[i][1] : 0,
+ bench.ns[i][2] ? mb * 1000000000ull / bench.ns[i][2] : 0);
+ for (int k = 0; k < 3; k++) {
+ total[k] += bench.ns[i][k] ? mb * 1000000000ull / bench.ns[i][k] : 0;
+ }
+ }
+ tell("membench: all %u at once, together: writing %llu MB/s, reading %llu MB/s, copying %llu MB/s\n", threads, total[0],
+ total[1], total[2]);
+}
+
/*
* Boot-arg cpuload=MS: every MS milliseconds, how busy each of our cores was meanwhile, in
* percent, to the loader's log (tools/frames.py shows it per gesture):
@@ -200,6 +294,240 @@ load_start(void)
}
}
+/*
+ * Boot-arg ddr=1: the memory's bus clock managers ("BCM") in the command database the boot loader
+ * left, with what is needed to vote for bandwidth on them -- only read. (membench=2 says the cores
+ * together get no more from memory than one alone: 12 GB/s; nobody here votes for more.)
+ */
+#define CMD_DB_PHYS 0x80860000UL
+#define CMD_DB_SIZE 0x20000UL
+#define CMD_DB_BCM 5 /* the kind of resource in a slave's id: bus clock managers */
+
+struct cmd_db_slave {
+ uint16_t id, header_offset, data_offset, count, version, reserved[3];
+};
+struct cmd_db_header {
+ uint32_t version;
+ uint8_t magic[4];
+ struct cmd_db_slave slave[8];
+ uint32_t checksum, reserved;
+ uint8_t data[];
+};
+struct cmd_db_entry {
+ char id[8];
+ uint32_t priority[2];
+ uint32_t address;
+ uint16_t length, offset;
+};
+struct cmd_db_bcm { /* a BCM's auxiliary data (Linux: struct bcm_db) */
+ uint32_t unit;
+ uint16_t width;
+ uint8_t vcd, reserved;
+};
+
+static void
+ddr_look(void)
+{
+ /* (memory, not registers: mapped so that reads of any size and alignment are allowed) */
+ const struct cmd_db_header *db = (const struct cmd_db_header *)ml_io_map_wcomb(CMD_DB_PHYS, CMD_DB_SIZE);
+
+ if (db->magic[0] != 0xdb || db->magic[1] != 0x30 || db->magic[2] != 0x03 || db->magic[3] != 0x0c) {
+ tell("ddr: no command database\n");
+ return;
+ }
+ for (unsigned s = 0; s < 8; s++) {
+ const struct cmd_db_slave *slave = &db->slave[s];
+ const struct cmd_db_entry *entry = (const struct cmd_db_entry *)(db->data + slave->header_offset);
+
+ if (slave->id != CMD_DB_BCM || slave->header_offset >= CMD_DB_SIZE - 0x1000 || slave->count > 512) {
+ continue;
+ }
+ for (unsigned i = 0; i < slave->count; i++) {
+ struct cmd_db_bcm aux = { 0 };
+ char name[9] = { 0 };
+
+ memcpy(name, entry[i].id, 8);
+ if (entry[i].length >= sizeof(aux) && slave->data_offset + entry[i].offset + sizeof(aux) < CMD_DB_SIZE - 0x40) {
+ memcpy(&aux, db->data + slave->data_offset + entry[i].offset, sizeof(aux));
+ }
+ tell("ddr: BCM %-8s at %#x: unit %u, width %u, vcd %u (aux %u bytes)\n", name, entry[i].address, aux.unit,
+ aux.width, aux.vcd, entry[i].length);
+ }
+ }
+}
+
+/*
+ * ... and what the boot loader's firmware left in the application processor's RPMh command slots
+ * ("DRV 2"; Linux: rpmh-rsc.c): 2 active, 3 sleep, 3 wake slot sets and a control one, of 16 commands
+ * each (sc7280's qcom,tcs-config): every command with an address, and which of them go to the BCMs
+ * above -- the bandwidth it asked for, and that is in force whenever the processors are awake.
+ */
+#define RSC_PHYS 0x18220000UL
+#define RSC_SIZE 0x10000UL
+#define RSC_TCS(n, reg) (0xd00 + 0x2a0 * (n) + (reg))
+#define RSC_TCS_COUNT 9
+#define RSC_CMDS 16
+
+static void
+ddr_slots(void)
+{
+ vm_offset_t rsc = ml_io_map(RSC_PHYS, RSC_SIZE);
+
+ for (unsigned t = 0; t < RSC_TCS_COUNT; t++) {
+ uint32_t enabled = *(volatile uint32_t *)(rsc + RSC_TCS(t, 0x1c));
+
+ for (unsigned c = 0; c < RSC_CMDS; c++) {
+ uint32_t msgid = *(volatile uint32_t *)(rsc + RSC_TCS(t, 0x30 + 20 * c));
+ uint32_t address = *(volatile uint32_t *)(rsc + RSC_TCS(t, 0x34 + 20 * c));
+ uint32_t data = *(volatile uint32_t *)(rsc + RSC_TCS(t, 0x38 + 20 * c));
+
+ if (address == 0 && data == 0) {
+ continue;
+ }
+ tell("ddr: slot set %u (%s) command %u%s: message %#x, address %#x, data %#x%s\n", t,
+ t < 2 ? "active" : t < 5 ? "sleep" : t < 8 ? "wake" : "control", c, enabled & (1u << c) ? " (on)" : "",
+ msgid, address, data, (address >> 16 & 0xf) == CMD_DB_BCM ? " <- a BCM" : "");
+ }
+ }
+}
+
+/*
+ * Boot-arg ddr=2: votes for the memory's bandwidth -- the most there is -- on the bus clock managers
+ * of the memory controller (MC0: the memory's clock) and of the shared hub in front of it with
+ * the system cache (SH0), as Linux's interconnect driver does for a busy GPU (icc-bcm-voter.c: a
+ * BCM command is commit, valid, the average and the peak, 14 bits each, in the BCM's units; the
+ * BCM takes the highest of its levels the vote reaches), and the memory kept on for this
+ * processor (ACV, bit 3, which the boot loader's firmware had set already). ddr_vote=N: N instead
+ * of the most (16383). At the end of the run the votes go to ddr_rest=N (default 16383: the
+ * memory stays at the clock it was raised to; what the firmware had asked for cannot be read back).
+ */
+#define BCM_COMMIT (1u << 30)
+#define BCM_VALID (1u << 29)
+#define BCM_VOTE(x, y) (BCM_COMMIT | BCM_VALID | ((uint32_t)(x) & 0x3fff) << 14 | ((uint32_t)(y) & 0x3fff))
+#define TCS_REG(reg) (ddr_rsc + 0xd00 + (reg)) /* command slot set 0, an "active" one */
+#define BCM_ACV_APPS 8
+
+static vm_offset_t ddr_rsc;
+static uint32_t ddr_mc0, ddr_sh0, ddr_acv;
+static bool ddr_voted;
+
+static uint32_t
+cmd_db_address(const char *name)
+{
+ const struct cmd_db_header *db = (const struct cmd_db_header *)ml_io_map_wcomb(CMD_DB_PHYS, CMD_DB_SIZE);
+ char id[8] = { 0 };
+
+ if (db->magic[0] != 0xdb || db->magic[1] != 0x30 || db->magic[2] != 0x03 || db->magic[3] != 0x0c) {
+ return 0;
+ }
+ strlcpy(id, name, sizeof(id));
+ for (unsigned s = 0; s < 8; s++) {
+ const struct cmd_db_slave *slave = &db->slave[s];
+ const struct cmd_db_entry *entry = (const struct cmd_db_entry *)(db->data + slave->header_offset);
+
+ if (slave->id != CMD_DB_BCM || slave->header_offset >= CMD_DB_SIZE - 0x1000 || slave->count > 512) {
+ continue;
+ }
+ for (unsigned i = 0; i < slave->count; i++) {
+ if (memcmp(entry[i].id, id, sizeof(id)) == 0) {
+ return entry[i].address;
+ }
+ }
+ }
+ return 0;
+}
+
+/* Up to three writes through command slot set 0, and the wait until RPMh has done them (as bsd/dev/redwood_goodix.c) */
+static bool
+ddr_rpmh_write(const uint32_t *address, const uint32_t *data, unsigned count)
+{
+ uint32_t irq_enable = *(volatile uint32_t *)TCS_REG(0x00);
+ bool done = false;
+
+ for (int i = 0; *(volatile uint32_t *)TCS_REG(0x18) == 0; i++) {
+ if (i > 2000) {
+ tell("ddr: RPMh: the command slots stay busy\n");
+ return false;
+ }
+ delay_for_interval(100, NSEC_PER_USEC);
+ }
+ *(volatile uint32_t *)TCS_REG(0x14) &= ~(1u << 24);
+ *(volatile uint32_t *)TCS_REG(0x14) &= ~(1u << 16);
+ *(volatile uint32_t *)TCS_REG(0x08) = 1;
+ for (unsigned i = 0; i < count; i++) {
+ *(volatile uint32_t *)TCS_REG(0x30 + 20 * i) = 0x10008 | 0x100; /* a 4-byte write, with a response */
+ *(volatile uint32_t *)TCS_REG(0x34 + 20 * i) = address[i];
+ *(volatile uint32_t *)TCS_REG(0x38 + 20 * i) = data[i];
+ }
+ *(volatile uint32_t *)TCS_REG(0x10) = (1u << count) - 1;
+ *(volatile uint32_t *)TCS_REG(0x1c) = (1u << count) - 1;
+ *(volatile uint32_t *)TCS_REG(0x00) = irq_enable | 1;
+ *(volatile uint32_t *)TCS_REG(0x14) = 1u << 16;
+ *(volatile uint32_t *)TCS_REG(0x14) = 1u << 16 | 1u << 24;
+ for (int i = 0; i < 2000 && !done; i++) {
+ done = (*(volatile uint32_t *)TCS_REG(0x04) & 1) != 0;
+ if (!done) {
+ delay_for_interval(100, NSEC_PER_USEC);
+ }
+ }
+ *(volatile uint32_t *)TCS_REG(0x14) &= ~(1u << 24);
+ *(volatile uint32_t *)TCS_REG(0x14) &= ~(1u << 16);
+ *(volatile uint32_t *)TCS_REG(0x1c) = 0;
+ *(volatile uint32_t *)TCS_REG(0x10) = 0;
+ *(volatile uint32_t *)TCS_REG(0x08) = 1;
+ *(volatile uint32_t *)TCS_REG(0x00) = irq_enable;
+ if (!done) {
+ tell("ddr: RPMh: no answer to the vote\n");
+ }
+ return done;
+}
+
+static bool
+ddr_vote(uint32_t vote)
+{
+ uint32_t address[3] = { ddr_mc0, ddr_sh0, ddr_acv };
+ uint32_t data[3] = { BCM_VOTE(vote, vote), BCM_VOTE(vote, vote), BCM_VOTE(0, BCM_ACV_APPS) };
+
+ return ddr_rpmh_write(address, data, 3);
+}
+
+static void
+ddr_raise(void)
+{
+ uint32_t vote = 0x3fff;
+
+ PE_parse_boot_argn("ddr_vote", &vote, sizeof(vote));
+ ddr_mc0 = cmd_db_address("MC0");
+ ddr_sh0 = cmd_db_address("SH0");
+ ddr_acv = cmd_db_address("ACV");
+ if (ddr_mc0 == 0 || ddr_sh0 == 0 || ddr_acv == 0 || vote == 0 || vote > 0x3fff) {
+ tell("ddr: no vote (MC0 %#x, SH0 %#x, ACV %#x, vote %u)\n", ddr_mc0, ddr_sh0, ddr_acv, vote);
+ return;
+ }
+ ddr_rsc = ml_io_map(RSC_PHYS, RSC_SIZE);
+ ddr_voted = ddr_vote(vote);
+ tell("ddr: memory bandwidth vote %u on MC0 (%#x) and SH0 (%#x)%s\n", vote, ddr_mc0, ddr_sh0, ddr_voted ? "" : ": FAILED");
+}
+
+/* At the end of the run (osfmk/arm64/loader_return.c). */
+void redwood_ddr_stop(void);
+
+void
+redwood_ddr_stop(void)
+{
+ uint32_t rest = 0x3fff;
+
+ if (!ddr_voted) {
+ return;
+ }
+ PE_parse_boot_argn("ddr_rest", &rest, sizeof(rest));
+ if (rest == 0 || rest > 0x3fff) {
+ rest = 0x3fff;
+ }
+ ddr_voted = false;
+ printf("ddr: memory bandwidth vote %u for after the run: %s\n", rest, ddr_vote(rest) ? "done" : "FAILED");
+}
+
void
redwood_cpufreq_init(void)
{
@@ -207,6 +535,13 @@ redwood_cpufreq_init(void)
uint32_t enabled = 0, cores[EPSS_DOMAINS] = { 0 }, before, here;
load_start();
+ if (PE_parse_boot_argn("ddr", &enabled, sizeof(enabled)) && enabled == 1) {
+ ddr_look();
+ ddr_slots();
+ } else if (enabled == 2) {
+ ddr_raise();
+ }
+ enabled = 0;
if (!PE_parse_boot_argn("cpufreq", &enabled, sizeof(enabled)) || !enabled) {
return;
}
@@ -222,7 +557,13 @@ redwood_cpufreq_init(void)
}
}
printf("cpufreq: on core %u a loop ran at %u, now at %u\n", here, before, loop_speed());
- if (PE_parse_boot_argn("membench", &enabled, sizeof(enabled)) && enabled) {
+ if (PE_parse_boot_argn("membench", &enabled, sizeof(enabled)) && enabled == 1) {
memory_bench();
+ } else if (enabled == 2) {
+ thread_t thread;
+
+ if (kernel_thread_start(bench_all, NULL, &thread) == KERN_SUCCESS) {
+ thread_deallocate(thread);
+ }
}
}
diff --git a/xnu/files/bsd/dev/redwood_input.c b/xnu/files/bsd/dev/redwood_input.c
index 6c584d6..c3bbac8 100644
--- a/xnu/files/bsd/dev/redwood_input.c
+++ b/xnu/files/bsd/dev/redwood_input.c
@@ -32,6 +32,7 @@ extern void loader_log_line(const char *line);
* log keeps only the last of a run, and a live look at the loader's (XL_FOLLOW) then misses nothing.
*/
void redwood_tl(const char *format, ...) __printflike(1, 2);
+extern void redwood_ddr_stop(void);
void
redwood_tl(const char *format, ...)
@@ -79,6 +80,7 @@ exit_hold_elapsed(__unused thread_call_param_t p0, __unused thread_call_param_t
{
printf("\n--- %d fingers held on the screen for %d ms: back to the loader ---\n", EXIT_FINGERS, EXIT_HOLD_MS);
redwood_adreno_stop();
+ redwood_ddr_stop();
loader_return();
}
diff --git a/xnu/files/iokit/Kernel/MiniIOMobileFramebuffer.cpp b/xnu/files/iokit/Kernel/MiniIOMobileFramebuffer.cpp
index 3efc5c6..d7cd76b 100644
--- a/xnu/files/iokit/Kernel/MiniIOMobileFramebuffer.cpp
+++ b/xnu/files/iokit/Kernel/MiniIOMobileFramebuffer.cpp
@@ -159,6 +159,13 @@ static TUNABLE(uint32_t, gOnTheBeat, "fb_beat", 1);
* to 10 (the phone, 15 October; fb_threads=1 is how it was).
*/
static TUNABLE(uint32_t, gThreads, "fb_threads", 3);
+#define SWAP_QUEUE 2 /* frames that may wait for the panel at most (fb_queue) */
+static TUNABLE(uint32_t, gQueue, "fb_queue", 1);
+static inline unsigned
+swapQueue(void)
+{
+ return gQueue >= 1 && gQueue <= SWAP_QUEUE ? gQueue : 1;
+}
/*
* Boot-arg touch_lat=1: a line for every swap handed over ("tl: s ID at US") and for every frame
* put on the panel ("tl: v ID ready US shown US done US": the GPU done with it, its beat come, the
@@ -234,11 +241,13 @@ public:
* frame waits at a time: the swap after it is held, in SwapEnd, until this one is being
* copied to the panel. Whoever draws is so at most two frames ahead of the panel, and
* needs a third surface to be that: CoreAnimation makes itself a new one for every frame.
+ * Boot-arg fb_queue=2: two frames may wait. (CoreAnimation draws on a clock of its own; a
+ * SwapEnd held past its next tick makes that tick late, and the clock goes on from there.)
*/
IOLock * fSwapLock; /* around the next five */
- uint8_t fSwap[SWAP_SIZE]; /* the swap that is on its way to the panel */
- MiniIOSurface * fSwapSurfaces[SWAP_LAYERS]; /* ... its surfaces, held from SwapEnd on: their maker may let go of them */
- bool fSwapThere;
+ uint8_t fSwap[SWAP_QUEUE][SWAP_SIZE]; /* the swaps on their way to the panel (fb_queue), from fSwapFirst on */
+ MiniIOSurface * fSwapSurfaces[SWAP_QUEUE][SWAP_LAYERS]; /* ... their surfaces, held from SwapEnd on: their maker may let go of them */
+ unsigned fSwapFirst, fSwapsWaiting;
/*
* ... and not whenever the GPU happens to be done, but on a beat of the refresh rate
* (boot-arg fb_beat=0: at once): frames then follow each other at an even pace whatever
@@ -862,21 +871,24 @@ IOMobileFramebuffer::present(const uint8_t * swap)
IOLockLock(fSwapLock);
fStatSwapsLate += fSwapTime != 0 && now - fSwapTime > period && now - fSwapTime < pause;
fSwapTime = now;
- fStatHeld += fSwapThere;
- while (fSwapThere) {
- if (IOLockSleepDeadline(fSwapLock, &fSwapThere, deadline, THREAD_UNINT) == THREAD_TIMED_OUT && fSwapThere) {
+ fStatHeld += fSwapsWaiting >= swapQueue();
+ while (fSwapsWaiting >= swapQueue()) {
+ if (IOLockSleepDeadline(fSwapLock, &fSwapsWaiting, deadline, THREAD_UNINT) == THREAD_TIMED_OUT &&
+ fSwapsWaiting >= swapQueue()) {
fStatLost++; /* (the GPU has stopped answering: the frame before is waiting for it) */
IOLockUnlock(fSwapLock);
return;
}
}
- memcpy(fSwap, swap, SWAP_SIZE);
+ unsigned slot = (fSwapFirst + fSwapsWaiting) % SWAP_QUEUE;
+
+ memcpy(fSwap[slot], swap, SWAP_SIZE);
for (unsigned layer = 0; layer < SWAP_LAYERS; layer++) {
uint32_t sid = swapWord(swap, SWAP_SURFACE(layer));
- fSwapSurfaces[layer] = sid != 0 ? MiniIOSurfaceCopy(sid) : NULL;
+ fSwapSurfaces[slot][layer] = sid != 0 ? MiniIOSurfaceCopy(sid) : NULL;
}
- fSwapThere = true;
+ fSwapsWaiting++;
IOLockWakeup(fSwapLock, fSwap, true);
IOLockUnlock(fSwapLock);
}
@@ -895,11 +907,11 @@ IOMobileFramebuffer::presenter(void)
for (;;) {
IOLockLock(fSwapLock);
- while (!fSwapThere) {
+ while (fSwapsWaiting == 0) {
IOLockSleep(fSwapLock, fSwap, THREAD_UNINT);
}
- memcpy(swap, fSwap, SWAP_SIZE);
- memcpy(surfaces, fSwapSurfaces, sizeof(surfaces));
+ memcpy(swap, fSwap[fSwapFirst], SWAP_SIZE);
+ memcpy(surfaces, fSwapSurfaces[fSwapFirst], sizeof(surfaces));
IOLockUnlock(fSwapLock);
show(swap, surfaces);
for (unsigned layer = 0; layer < SWAP_LAYERS; layer++) {
@@ -956,8 +968,9 @@ IOMobileFramebuffer::show(const uint8_t * swap, MiniIOSurface ** surfaces)
shown = began;
/* its turn has come: the swap after it may be handed over */
IOLockLock(fSwapLock);
- fSwapThere = false;
- IOLockWakeup(fSwapLock, &fSwapThere, true);
+ fSwapFirst = (fSwapFirst + 1) % SWAP_QUEUE;
+ fSwapsWaiting--;
+ IOLockWakeup(fSwapLock, &fSwapsWaiting, true);
IOLockUnlock(fSwapLock);
IOLockLock(fLock);
if (fLastFrame != 0) {
diff --git a/xnu/files/iokit/Kernel/MiniIOSurface.cpp b/xnu/files/iokit/Kernel/MiniIOSurface.cpp
index e27e463..ab0e35a 100644
--- a/xnu/files/iokit/Kernel/MiniIOSurface.cpp
+++ b/xnu/files/iokit/Kernel/MiniIOSurface.cpp
@@ -116,7 +116,9 @@ static struct {
IOBufferMemoryDescriptor * memory;
bool clear; /* cleared since it was last a surface's */
bool busy; /* being cleared right now */
+ uint64_t since; /* when it was kept */
} gSurfaceKept[SURFACE_KEPT];
+static uint32_t gSurfacesNotKept[2]; /* memory not kept: somebody else had it too; it put out a piece kept longer */
static IOLock * gSurfaceKeptLock;
static thread_call_t gSurfaceClearing;
static uint32_t gSurfacesGivenAgain; /* for MiniIOSurfaceCost() */
@@ -185,21 +187,46 @@ surfaceMemory(vm_size_t bytes)
return memory;
}
-/* A surface is gone: its memory is kept for the next, if it is big and nobody else has it. */
+/*
+ * A surface is gone: its memory is kept for the next, if it is big and nobody else has it. When
+ * all the places are taken, it takes the place of the piece kept longest: pieces of a size nobody
+ * asks for again (a big picture made once) once stayed there for good, and then no frame's memory
+ * was kept any more -- each made afresh and freed (2 to 4 ms, and 1 to 2) instead of 0.3 and 0.05.
+ */
static void
surfaceMemoryBack(IOBufferMemoryDescriptor * memory)
{
+ IOBufferMemoryDescriptor * evicted = NULL;
+
+ if (memory->getCapacity() >= SURFACE_KEEP_FROM && memory->getRetainCount() != 1) {
+ OSIncrementAtomic(&gSurfacesNotKept[0]);
+ }
if (memory->getCapacity() >= SURFACE_KEEP_FROM && memory->getRetainCount() == 1 && gSurfaceKeptLock != NULL) {
+ int oldest = -1;
+
IOLockLock(gSurfaceKeptLock);
- for (unsigned i = 0; i < SURFACE_KEPT; i++) {
+ for (unsigned i = 0; i < SURFACE_KEPT && memory != NULL; i++) {
if (gSurfaceKept[i].memory == NULL) {
gSurfaceKept[i].memory = memory;
gSurfaceKept[i].clear = gSurfaceKept[i].busy = false;
+ gSurfaceKept[i].since = mach_absolute_time();
memory = NULL;
- break;
+ } else if (!gSurfaceKept[i].busy && (oldest < 0 || gSurfaceKept[i].since < gSurfaceKept[oldest].since)) {
+ oldest = (int) i;
}
}
+ if (memory != NULL && oldest >= 0) {
+ evicted = gSurfaceKept[oldest].memory;
+ gSurfaceKept[oldest].memory = memory;
+ gSurfaceKept[oldest].clear = gSurfaceKept[oldest].busy = false;
+ gSurfaceKept[oldest].since = mach_absolute_time();
+ memory = NULL;
+ gSurfacesNotKept[1]++;
+ }
IOLockUnlock(gSurfaceKeptLock);
+ if (evicted != NULL) {
+ evicted->release();
+ }
if (memory == NULL) {
if (gSurfaceClear) {
AbsoluteTime deadline;
@@ -1072,7 +1099,9 @@ IOSurfaceRootUserClient::methodCreate(IOExternalMethodArguments * args)
OSSafeReleaseNULL(obj);
return kIOReturnBadArgument;
}
+ uint64_t made_at = mach_absolute_time();
s = surfaceCreate(props, &ret);
+ made_at = mach_absolute_time() - made_at;
if (s == NULL) {
IOLog("MiniIOSurface: create failed 0x%x: %ux%u format 0x%x alloc %u\n", ret,
dictNumber(props, "IOSurfaceWidth", 0), dictNumber(props, "IOSurfaceHeight", 0),
@@ -1092,6 +1121,7 @@ IOSurfaceRootUserClient::methodCreate(IOExternalMethodArguments * args)
(int) (s->info.pixelFormat & 0xff), s->info.bytesPerRow, s->info.planeCount, s->info.allocSize);
}
+ uint64_t mapped_at = mach_absolute_time();
IOLockLock(gSurfaceLock);
ref = addRef(s);
ret = ref ? returnSurface(ref, false, args) : kIOReturnNoMemory;
@@ -1100,8 +1130,37 @@ IOSurfaceRootUserClient::methodCreate(IOExternalMethodArguments * args)
}
surfaceUnhold(s); /* the creator's hold; the client's own is in the ref */
IOLockUnlock(gSurfaceLock);
+ mapped_at = mach_absolute_time() - mapped_at;
OSAddAtomic64((SInt64) (mach_absolute_time() - began), (SInt64 *) &gSurfaceMaking);
OSIncrementAtomic(&gSurfacesMade);
+ if (s->info.allocSize >= SURFACE_KEEP_FROM) {
+ /* the big ones (the window server's of the whole display): where the time to make one goes, every 5 s */
+ static uint64_t since, all, making, mapping;
+ static uint32_t count;
+ uint64_t now = mach_absolute_time(), ns;
+
+ count++;
+ all += now - began;
+ making += made_at;
+ mapping += mapped_at;
+ absolutetime_to_nanoseconds(now - since, &ns);
+ if (since == 0) {
+ since = now;
+ } else if (ns >= 5 * NSEC_PER_SEC) {
+ uint64_t a, m, p;
+
+ absolutetime_to_nanoseconds(all, &a);
+ absolutetime_to_nanoseconds(making, &m);
+ absolutetime_to_nanoseconds(mapping, &p);
+ IOLog("MiniIOSurface: %u big surfaces made, %llu us each: %llu getting the memory and the surface, %llu mapping it "
+ "for its maker; memory not kept as somebody else had it %u times, a piece kept longer put out for it %u times\n",
+ count, a / 1000 / count, m / 1000 / count, p / 1000 / count, OSBitAndAtomic(0, &gSurfacesNotKept[0]),
+ OSBitAndAtomic(0, &gSurfacesNotKept[1]));
+ since = now;
+ count = 0;
+ all = making = mapping = 0;
+ }
+ }
return ret;
}
diff --git a/xnu/files/osfmk/arm64/loader_return.c b/xnu/files/osfmk/arm64/loader_return.c
index 3e6e5c4..95705e4 100644
--- a/xnu/files/osfmk/arm64/loader_return.c
+++ b/xnu/files/osfmk/arm64/loader_return.c
@@ -51,6 +51,7 @@ extern void redwood_wifi_stop(void);
extern void redwood_wifi_quiesce(void);
extern void redwood_adsp_stop(void);
extern void redwood_adsp_quiesce(void);
+extern void redwood_ddr_stop(void);
void loader_checkpoint(uint64_t n);
/* Also referenced from the early exception vector in start.s. */
@@ -426,6 +427,7 @@ loader_return_timer(__unused thread_call_param_t p0, __unused thread_call_param_
redwood_adreno_stop(); /* a GPU kept for the system is given back while there is a thread to wait in */
redwood_wifi_stop(); /* and the Wi-Fi DSP, if it runs, shut down */
redwood_adsp_stop(); /* and the audio DSP */
+ redwood_ddr_stop(); /* and the memory's bandwidth vote put as it is to stay */
}
if (PE_parse_boot_argn("return_cpu", &cpu, sizeof(cpu)) && cpu <= (uint32_t)ml_get_max_cpu_number() &&
cpu_xcall((int)cpu, loader_return_test, (void *)(uintptr_t)(as_panic ? 2 : 1)) == KERN_SUCCESS) {
@@ -471,6 +473,7 @@ loader_stop_poll(__unused thread_call_param_t p0, __unused thread_call_param_t p
redwood_adreno_stop();
redwood_wifi_stop();
redwood_adsp_stop();
+ redwood_ddr_stop();
loader_return();
}
clock_interval_to_deadline(1, NSEC_PER_SEC, &deadline);