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

Memory bandwidth vote and two waiting frames by default; the vote put back for the loader

vcvkkeade32bf50b2
diff --git a/README.md b/README.md
index c78315c..6722a71 100644
--- a/README.md
+++ b/README.md
@@ -228,8 +228,8 @@ 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 |
+| `fb_queue=1` | драйверу экрана может ждать один кадр, как раньше. По умолчанию два: CoreAnimation не задерживается в SwapEnd до следующего тика своих часов (задержанный тик сдвигает её часы, и кадр выходит через 19–20 мс вместо 16,7); `rc.jobs.fps`: 28 % кадров дольше 16,7 мс с двумя, 33 % с одним |
+| `ddr=0` | не голосовать за пропускную способность памяти. По умолчанию (вместе с `cpufreq=1`) ядро через RPMh голосует, как драйвер межсоединений Linux под нагрузкой GPU: контроллер памяти (MC0) и общий узел с системным кэшем (SH0) — на максимум, память включена для процессора (ACV). Все ядра вместе получают от памяти 15 ГБ/с записи вместо 12,4 (`membench=2`), кадров дольше 16,7 мс 28 % вместо 34–36 %: Пункт управления 59 кадров/с вместо 46, открытие Настроек 37 вместо 29, Поиск 45 вместо 36. При возврате в загрузчик (любом, и после паники) голос опускается до `ddr_rest=N` (по умолчанию 1024): с любым голосом от 4 до 4096 ядра получают те же 12–12,4 ГБ/с, что до первого голоса, а без голоса вовсе — 0,2 ГБ/с (память на нижнем пределе, USB загрузчика 8 МБ/с вместо 30), так что у прошивки был свой голос от нашего имени. `ddr_vote=N` — голос N вместо 16383. `ddr=1` — только прочесть и напечатать BCM из базы команд и то, что лежит в слотах команд RPMh |
| `membench=1` / `membench=2` | скорость памяти для одного ядра / для всех наших ядер сразу (сумма — то, что даёт память на своей частоте) |
| `caenv=ИМЯ=ЗНАЧЕНИЕ` | (сколько угодно раз) в окружение оконного сервера: переключатели самой CoreAnimation (`CA_…`) |
| `fb_beat=0` | кадр уходит на панель сразу, как GPU его закончил, а не по собственному такту драйвера 60 Гц (такт держит ровный шаг, но кадр ждёт его в среднем 5–7 мс; панель всё равно обновляется 120 раз в секунду и к такту не привязана) |
diff --git a/xnu/files/bsd/dev/redwood_cpufreq.c b/xnu/files/bsd/dev/redwood_cpufreq.c
index effa4fb..8f06cbb 100644
--- a/xnu/files/bsd/dev/redwood_cpufreq.c
+++ b/xnu/files/bsd/dev/redwood_cpufreq.c
@@ -325,6 +325,15 @@ struct cmd_db_bcm { /* a BCM's auxiliary data (Linux
uint8_t vcd, reserved;
};
+/* (the same condition as the cores' clocks: the addresses are this phone's) */
+static bool
+cpufreq_wanted(void)
+{
+ uint32_t on = 0;
+
+ return PE_parse_boot_argn("cpufreq", &on, sizeof(on)) && on != 0;
+}
+
static void
ddr_look(void)
{
@@ -392,20 +401,28 @@ ddr_slots(void)
}
/*
- * 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).
+ * The memory's bandwidth (on by default; boot-arg ddr=0: not): a vote through RPMh -- 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 casts 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, the same).
+ * All cores together got 12.4 GB/s writing without it (membench=2: what one core gets alone), 14.8
+ * with it; frames over 16.7 ms 28% instead of 34-36%. ddr_vote=N: N instead of the most (16383).
+ * When the kernel goes back to the loader (redwood_ddr_quiesce(), on every way back, a panic's too)
+ * the vote goes down to ddr_rest=N (default 1024). What the firmware had voted cannot be read back,
+ * but what the cores get from memory can be measured (membench=2, writing): with any vote from 4
+ * to 4096 12.0 to 12.4 GB/s, as before the first vote (12.4); with the most, 15.4; with none at all
+ * ("no request", valid clear: what Linux sends for nothing) 0.2 -- the memory at its floor, and the
+ * loader's USB transfers at 8 MB/s instead of 30. So the firmware had a vote of its own in our name,
+ * of that middle range, and one from the middle of it is left.
*/
#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
+#define DDR_REST 1024 /* the vote left for the loader (ddr_rest=N); see redwood_ddr_quiesce() */
static vm_offset_t ddr_rsc;
static uint32_t ddr_mc0, ddr_sh0, ddr_acv;
@@ -509,23 +526,25 @@ ddr_raise(void)
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);
+/* On the way back to the loader (osfmk/arm64/loader_return.c: loader_return(), whatever the reason; the other processors are stopped) */
+void redwood_ddr_quiesce(void);
void
-redwood_ddr_stop(void)
+redwood_ddr_quiesce(void)
{
- uint32_t rest = 0x3fff;
+ uint32_t address[2] = { ddr_mc0, ddr_sh0 };
+ uint32_t rest = DDR_REST, data[2];
+ bool done;
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");
+ PE_parse_boot_argn("ddr_rest", &rest, sizeof(rest));
+ rest = MIN(rest, 0x3fff);
+ data[0] = data[1] = rest != 0 ? BCM_VOTE(rest, rest) : BCM_COMMIT; /* 0: no request */
+ done = ddr_rpmh_write(address, data, 2);
+ tell("ddr: memory bandwidth vote %u for the loader: %s\n", rest, done ? "done" : "FAILED");
}
void
@@ -535,10 +554,12 @@ 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) {
+ enabled = 2;
+ PE_parse_boot_argn("ddr", &enabled, sizeof(enabled));
+ if (enabled == 1) {
ddr_look();
ddr_slots();
- } else if (enabled == 2) {
+ } else if (enabled == 2 && cpufreq_wanted()) {
ddr_raise();
}
enabled = 0;
diff --git a/xnu/files/bsd/dev/redwood_input.c b/xnu/files/bsd/dev/redwood_input.c
index c3bbac8..6c584d6 100644
--- a/xnu/files/bsd/dev/redwood_input.c
+++ b/xnu/files/bsd/dev/redwood_input.c
@@ -32,7 +32,6 @@ 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, ...)
@@ -80,7 +79,6 @@ 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 d7cd76b..aedd919 100644
--- a/xnu/files/iokit/Kernel/MiniIOMobileFramebuffer.cpp
+++ b/xnu/files/iokit/Kernel/MiniIOMobileFramebuffer.cpp
@@ -160,7 +160,7 @@ static TUNABLE(uint32_t, gOnTheBeat, "fb_beat", 1);
*/
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 TUNABLE(uint32_t, gQueue, "fb_queue", 2);
static inline unsigned
swapQueue(void)
{
@@ -241,8 +241,9 @@ 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.)
+ * By default two frames may wait (boot-arg fb_queue=1: one, as before): CoreAnimation draws on a
+ * clock of its own, and a SwapEnd held past its next tick makes that tick late, the clock going
+ * on from there (rc.jobs.fps: 28% of the frames over 16.7 ms with two, 33% with one).
*/
IOLock * fSwapLock; /* around the next five */
uint8_t fSwap[SWAP_QUEUE][SWAP_SIZE]; /* the swaps on their way to the panel (fb_queue), from fSwapFirst on */
diff --git a/xnu/files/osfmk/arm64/loader_return.c b/xnu/files/osfmk/arm64/loader_return.c
index 95705e4..97c677c 100644
--- a/xnu/files/osfmk/arm64/loader_return.c
+++ b/xnu/files/osfmk/arm64/loader_return.c
@@ -51,7 +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);
+extern void redwood_ddr_quiesce(void);
void loader_checkpoint(uint64_t n);
/* Also referenced from the early exception vector in start.s. */
@@ -366,6 +366,7 @@ loader_return(void)
redwood_adreno_quiesce(); /* the GPU block, if it was started, has tables in memory that is about to be reused */
redwood_wifi_quiesce(); /* the Wi-Fi DSP, if it still runs (a panic), is not left to itself */
redwood_adsp_quiesce(); /* nor the audio DSP */
+ redwood_ddr_quiesce(); /* and the vote for the memory's bandwidth taken away */
/*
* A panic's text is first collected in the panic buffer and only later
* flushed to the console; if the console itself is what failed, that
@@ -427,7 +428,6 @@ 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) {
@@ -473,7 +473,6 @@ 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);