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
UFS: a driver of the kernel's own beside UEFI's, and the probe that finds no room for it
vcvkk4767396a3a63
diff --git a/README.md b/README.mdindex 89d9daf..8561c2a 100644--- a/README.md+++ b/README.md@@ -569,6 +569,30 @@ UEFI, а тот на ядре 0, пока работает ядро порта,154 275 запросов обхода тома 62 310 продолжают предыдущий, но между ними ядру нечего делать, а ненужное упреждениезадерживает следующий запрос (обход без хеша 35 132 → 36 172 мс); оно убрано.+**Свой драйвер контроллера UFS рядом с UEFI — на этом телефоне некуда.** `ufs_native=1`+(`bsd/dev/redwood_ufshc.c`) задуман так: контроллер остаётся у UEFI (ни сброса, ни старта линка, ни UIC-команд,+ни смены адресов списков, прерываний, питания), ядро кладёт свои запросы в свободные слоты списка UEFI (16–31,+по одному на строку кэша), звонит в их биты `UTRLDBR` и ждёт, пока контроллер их сбросит; каждая команда+проходит один белый список (READ(10)/READ(16), TEST UNIT READY, REQUEST SENSE, INQUIRY, READ CAPACITY и запросы+QUERY на чтение — всё остальное отказывается и пишется в журнал; на старте он проверяется на 20 придуманных+командах, от WRITE и UNMAP до SET FLAG); в конце сеанса (`loader_return`) ядро ждёт свои слоты и возвращает их+содержимое. При любой неожиданности на пробе — чтение через загрузчик, как было (`ufs_native=0` — по умолчанию,+`ufs_native=2` — только посмотреть). Проба на телефоне (`ufs_native=2`, ни одной команды): контроллер на+`0x1d84000`, UFSHCI 3.0, 32 слота, 64-битные адреса, включён и работает, прерывания выключены (`IE=0`), агрегации+и автоматического hibern8 нет — но список UEFI на `0xccf96000` рассчитан на один запрос: дескриптор команды+слота 0 лежит на `0xccf96100`, внутри того килобайта, что заняли бы остальные 31. «Слоты» 8–14 — это UPIU+команды UEFI (последний — READ(10) раздела `logdump`), его ответ и таблица PRD (адреса прямо в буфер+загрузчика: UFSDxe читает без промежуточного буфера), 1–7 и 15–17 — другие данные драйвера. Свободного слота,+кроме собственного слота UEFI, нет; проба отказывает (по двум независимым проверкам), чтение идёт через+загрузчик. Несколько запросов в полёте возможны только со своим списком (сменой `UTRLBA` на время сеанса) — это+уже не «оставить контроллер как был».++Загрузчик теперь после каждой записи журнала в `logdump` читает его обратно и пишет в копию для компьютера+`log: N bytes written to logdump (0), read back the same (0)`; в его странице для ядра у каждого раздела есть+логический блок и начало на нём, а сами логические блоки (`unit0`…`unit5`, в порядке UEFI; их пути — узлы+производителя с GUID, номера LUN в них нет) идут за разделами — для сравнения чтения своим драйвером с чтением+через загрузчик (`ufs_native_check=1`, на этом телефоне не дошло: проба отказывает раньше).+## Снимки экранаВсё снято с экрана телефона за один сеанс: образ `GL=1 REST=1`, запуск с `gpu=1`, касания подаёт сценарийdiff --git a/xnu/files/bsd/dev/redwood_ufs.c b/xnu/files/bsd/dev/redwood_ufs.cindex 9f85b1f..8912d87 100644--- a/xnu/files/bsd/dev/redwood_ufs.c+++ b/xnu/files/bsd/dev/redwood_ufs.c@@ -41,6 +41,7 @@#include <sys/systm.h>#include <sys/sysctl.h>#include <sys/redwood_input.h>+#include <libkern/crc.h>#include <vm/memory_types.h>extern vm_offset_t ml_io_map_unmappable(vm_offset_t phys_addr, vm_size_t size, unsigned int flags);@@ -50,13 +51,20 @@ extern void FlushPoC_DcacheRegion(vm_offset_t va, size_t length); /* osfmk/arm/* the page the loader publishes: the same layout as struct loader_block in xnuloader/loader.c */#define BLOCK_MAGIC 0x4b434f4c42574452ULL /* "RDWBLOCK" */-#define BLOCK_VERSION 1-#define BLOCK_MAX_PARTS 128+#define BLOCK_VERSION 2+#define BLOCK_MAX_PARTS 160+#define BLOCK_MAX_UNITS 16+#define BLOCK_PART_UNIT 1u /* a whole logical unit, not a partition */struct loader_block_part {char name[36];uint32_t block_size;uint64_t blocks;+ uint64_t start_lba; /* where it begins on its unit, in the unit's blocks */+ uint16_t unit; /* the unit it is on, its number among the units; 0xffff: not known */+ uint8_t lun; /* a unit's logical unit number as its device path says; 0xff: it does not */+ uint8_t flags; /* BLOCK_PART_UNIT */+ uint32_t reserved;};struct loader_block {@@ -94,6 +102,21 @@ static uint64_t ufs_sequential; /* requests that start where thestatic uint32_t ufs_last_part = ~0u;static uint64_t ufs_last_end;+/*+ * This kernel's own UFS driver (redwood_ufshc.c), with ufs_native=1: each partition's logical+ * unit and where it begins there, in bytes; reads go that way unless it fails, and then through+ * the loader again.+ */+extern bool ufshc_probe(bool only);+extern bool ufshc_available(void);+extern int ufshc_read(uint8_t lun, uint64_t offset, uint8_t *dst, uint64_t len);+extern void ufshc_report(const char *when);+static uint8_t ufs_lun[BLOCK_MAX_PARTS]; /* 0xff: not known, read through the loader */+static uint64_t ufs_lun_offset[BLOCK_MAX_PARTS];+static bool ufs_native_mapped;+static volatile bool ufs_native_on;+static uint64_t ufs_native_fallbacks;+static LCK_GRP_DECLARE(ufs_lck_grp, "redwood-ufs");static LCK_MTX_DECLARE(ufs_lock, &ufs_lck_grp);@@ -218,6 +241,7 @@ redwood_ufs_report(const char *when)if (!ufs_ready) {return;}+ ufshc_report(when);absolutetime_to_nanoseconds(ufs_page->answer.ticks, &loader_ns);printf("ufs: %s: %llu requests (%llu of 4 KB or less, %llu to 64 KB, %llu more; %llu right after ""the one before), %llu errors, %llu bytes; waiting %llu ms, of it in ReadBlocks %llu ms; "@@ -226,11 +250,12 @@ redwood_ufs_report(const char *when)}/*- * Bytes [offset, offset + len) of partition part into dst, whatever their alignment: the native- * blocks that cover them are read a buffer at a time and the wanted bytes copied out.+ * Bytes [offset, offset + len) of partition part into dst, whatever their alignment, through the+ * loader: the native blocks that cover them are read a buffer at a time and the wanted bytes+ * copied out.*/static int-ufs_read(uint32_t part, uint64_t offset, uint8_t *dst, uint64_t len)+ufs_read_mailbox(uint32_t part, uint64_t offset, uint8_t *dst, uint64_t len){uint64_t nbs = ufs_page->part[part].block_size, per = ufs_buffer_size / nbs;static uint8_t *bounce;@@ -270,6 +295,34 @@ ufs_read(uint32_t part, uint64_t offset, uint8_t *dst, uint64_t len)return error;}+/* The same, through this kernel's own driver: the partition's unit, from where it begins there */+static int+ufs_read_native(uint32_t part, uint64_t offset, uint8_t *dst, uint64_t len)+{+ if (part >= ufs_parts || ufs_lun[part] == 0xff) {+ return ENXIO;+ }+ return ufshc_read(ufs_lun[part], ufs_lun_offset[part] + offset, dst, len);+}++/* The way chosen (ufs_native=, kern.redwood.ufs_native); if this kernel's own fails, the loader's */+static int+ufs_read(uint32_t part, uint64_t offset, uint8_t *dst, uint64_t len)+{+ if (ufs_native_on && ufs_lun[part] != 0xff) {+ int error = ufs_read_native(part, offset, dst, len);++ if (error == 0) {+ return 0;+ }+ ufs_native_on = false;+ ufs_native_fallbacks++;+ printf("ufs: %s: bytes %llu..%llu: this kernel's own read failed (%d); through the loader from now on\n",+ ufs_page->part[part].name, offset, offset + len - 1, error);+ }+ return ufs_read_mailbox(part, offset, dst, len);+}+static uint64_tufs_part_bytes(uint32_t part){@@ -281,7 +334,7 @@ ufs_part_bytes(uint32_t part)static intufs_open(dev_t dev, int flags, __unused int devtype, __unused proc_t p){- if (!ufs_ready || (uint32_t)minor(dev) >= ufs_parts) {+ if (!ufs_ready || (uint32_t)minor(dev) >= ufs_parts || (ufs_page->part[minor(dev)].flags & BLOCK_PART_UNIT)) {return ENXIO;}if (flags & FWRITE) {@@ -530,6 +583,269 @@ ufs_bench(__unused void *arg, __unused wait_result_t wr)redwood_ufs_report("after the bench");}+/* ---- this kernel's own driver: which unit is which, and whether it reads what the loader reads ---- */++static uint64_t+ufs_fnv(uint64_t h, const uint8_t *p, uint64_t n)+{+ for (uint64_t i = 0; i < n; i++) {+ h = (h ^ p[i]) * 0x100000001b3ULL;+ }+ return h;+}++/*+ * Each unit's logical unit number: the one its device path gives, if it gives one, else the first+ * of 0..7 not yet taken whose block 1 (the GPT header, with the unit's own GUID in it) is what the+ * loader reads as block 1 of that unit. Either way it is so only if the two are the same.+ */+static bool+ufs_native_map(void)+{+ uint8_t *a = kalloc_data(2 * 4096, Z_WAITOK), *b = a + 4096;+ uint8_t unit_lun[BLOCK_MAX_UNITS];+ uint32_t taken = 0, units = 0;+ bool all = true;++ memset(unit_lun, 0xff, sizeof(unit_lun));+ memset(ufs_lun, 0xff, sizeof(ufs_lun));+ if (a == NULL) {+ return false;+ }+ for (uint32_t i = 0; i < ufs_parts && all; i++) {+ volatile struct loader_block_part *e = &ufs_page->part[i];+ bool found = false;++ if ((e->flags & BLOCK_PART_UNIT) == 0) {+ continue;+ }+ units++;+ if (e->unit >= BLOCK_MAX_UNITS || e->block_size != 4096 || ufs_read_mailbox(i, 4096, a, 4096) != 0 ||+ memcmp(a, "EFI PART", 8) != 0) {+ printf("ufs: native: %s: no GPT header to know it by (block size %u)\n", e->name, e->block_size);+ all = false;+ break;+ }+ for (uint32_t k = 0; k < 8 && !found; k++) {+ uint32_t lun = e->lun != 0xff ? e->lun : (k == 0 ? e->unit : k - 1);++ if (lun >= 8 || (taken & (1u << lun)) || (e->lun != 0xff && k > 0)) {+ continue;+ }+ if (ufshc_read((uint8_t)lun, 4096, b, 4096) == 0 && memcmp(a, b, 4096) == 0) {+ unit_lun[e->unit] = (uint8_t)lun;+ taken |= 1u << lun;+ found = true;+ printf("ufs: native: %s is LUN %u (%s; its GPT header read both ways is the same)\n", e->name, lun,+ e->lun != 0xff ? "its device path says so" : "found by its GPT header");+ }+ }+ if (!found) {+ printf("ufs: native: %s: no logical unit reads as it does through the loader\n", e->name);+ all = false;+ }+ }+ kfree_data(a, 2 * 4096);+ if (!all || units == 0) {+ memset(ufs_lun, 0xff, sizeof(ufs_lun));+ return false;+ }+ for (uint32_t i = 0; i < ufs_parts; i++) {+ volatile struct loader_block_part *e = &ufs_page->part[i];++ if (e->unit < BLOCK_MAX_UNITS && unit_lun[e->unit] != 0xff && e->block_size == 4096) {+ ufs_lun[i] = unit_lun[e->unit];+ ufs_lun_offset[i] = e->start_lba * 4096;+ }+ }+ return true;+}++static uint64_t ufs_cmp_mailbox_ns, ufs_cmp_native_ns, ufs_cmp_bytes, ufs_cmp_regions, ufs_cmp_differ;++/*+ * Bytes [offset, offset + len) of entry part, read both ways a megabyte at a time and compared;+ * FNV-1a of what was read (each way), and of its first ref bytes if ref is not 0.+ */+static bool+ufs_compare(uint32_t part, uint64_t offset, uint64_t len, uint64_t ref, const char *what, bool quiet)+{+ static uint8_t *x, *y;+ uint64_t hx = 0xcbf29ce484222325ULL, hy = hx, href = 0, done = 0, t, ns, mailbox_ns = 0, native_ns = 0;+ int ex = 0, ey = 0;+ bool same = true;++ if (x == NULL) {+ x = kalloc_data(2 << 20, Z_WAITOK);+ y = x + (1 << 20);+ }+ while (done < len && same && ex == 0 && ey == 0) {+ uint64_t n = len - done < (1 << 20) ? len - done : (1 << 20);++ t = mach_absolute_time();+ ex = ufs_read_mailbox(part, offset + done, x, n);+ absolutetime_to_nanoseconds(mach_absolute_time() - t, &ns);+ mailbox_ns += ns;+ t = mach_absolute_time();+ ey = ufs_read_native(part, offset + done, y, n);+ absolutetime_to_nanoseconds(mach_absolute_time() - t, &ns);+ native_ns += ns;+ if (ex == 0 && ey == 0 && memcmp(x, y, n) != 0) {+ uint64_t at = 0;++ while (x[at] == y[at]) {+ at++;+ }+ printf("ufs: native check: %s %s: DIFFERENT at byte %llu (%02x through the loader, %02x here)\n",+ ufs_page->part[part].name, what, offset + done + at, x[at], y[at]);+ same = false;+ }+ if (ref != 0 && done < ref) {+ uint64_t m = ref - done < n ? ref - done : n;++ href = ufs_fnv(done == 0 ? 0xcbf29ce484222325ULL : href, x, m);+ }+ hx = ufs_fnv(hx, x, n);+ hy = ufs_fnv(hy, y, n);+ done += n;+ }+ if (ex != 0 || ey != 0) {+ printf("ufs: native check: %s %s: read failed (through the loader %d, here %d)\n", ufs_page->part[part].name,+ what, ex, ey);+ same = false;+ }+ ufs_cmp_regions++;+ ufs_cmp_bytes += done;+ ufs_cmp_mailbox_ns += mailbox_ns;+ ufs_cmp_native_ns += native_ns;+ ufs_cmp_differ += !same;+ if (!quiet || !same) {+ printf("ufs: native check: %s %s: %llu bytes from %llu %s: fnv %llx / %llx; loader %llu ms, here %llu ms\n",+ ufs_page->part[part].name, what, done, offset, same ? "the same" : "NOT THE SAME", hx, hy,+ mailbox_ns / 1000000, native_ns / 1000000);+ if (ref != 0) {+ printf("ufs: native check: %s: fnv %llx over the first %llu bytes (the loader's and ufs_check's hash)\n",+ ufs_page->part[part].name, href, ref);+ }+ }+ return same;+}++static uint32_t+ufs_entry(const char *name)+{+ for (uint32_t i = 0; i < ufs_parts; i++) {+ if (strcmp((const char *)ufs_page->part[i].name, name) == 0) {+ return i;+ }+ }+ return BLOCK_MAX_PARTS;+}++/*+ * ufs_native_check=1: what this kernel's own driver reads is what the loader reads, byte for+ * byte: every unit's GPT (protective MBR, header, table, and the backup table and header at the+ * end), the partitions the loader hashes (the ROM's images: xbl, tz, modem, ...) whole, the start+ * of super (its geometry and metadata), and of darwin 64 spread megabytes, 512 scattered blocks+ * and some reads that begin and end inside a block.+ */+static void+ufs_native_check(void)+{+ uint8_t *h = kalloc_data(4096, Z_WAITOK);+ uint32_t part;+ uint64_t seed = 0x9e3779b97f4a7c15ULL;++ printf("ufs: native check: through the loader and through this kernel's own driver, compared\n");+ for (uint32_t i = 0; h != NULL && i < ufs_parts; i++) {+ volatile struct loader_block_part *e = &ufs_page->part[i];+ uint64_t entries_lba, count, size, table, alt, alt_entries;++ if ((e->flags & BLOCK_PART_UNIT) == 0 || ufs_read_mailbox(i, 4096, h, 4096) != 0) {+ continue;+ }+ entries_lba = *(uint64_t *)(h + 72);+ count = *(uint32_t *)(h + 80);+ size = *(uint32_t *)(h + 84);+ alt = *(uint64_t *)(h + 32);+ table = (count * size + 4095) / 4096;+ {+ uint32_t want = *(uint32_t *)(h + 16), got;++ *(uint32_t *)(h + 16) = 0;+ got = crc32(0, h, *(uint32_t *)(h + 12));+ printf("ufs: native check: %s: GPT header crc %s, table at block %llu, %llu entries of %llu bytes, backup "+ "header at block %llu\n", e->name, got == want ? "right" : "WRONG", entries_lba, count, size, alt);+ }+ ufs_compare(i, 0, (entries_lba + table) * 4096, 0, "GPT (MBR, header, table)", false);+ if (alt < e->blocks && ufs_read_mailbox(i, alt * 4096, h, 4096) == 0 && memcmp(h, "EFI PART", 8) == 0) {+ alt_entries = *(uint64_t *)(h + 72);+ if (alt_entries <= alt) {+ ufs_compare(i, alt_entries * 4096, (alt + 1 - alt_entries) * 4096, 0, "backup GPT (table, header)",+ false);+ }+ }+ }+ for (part = 0; part < ufs_parts; part++) {+ if (ufs_page->part[part].flags & BLOCK_PART_UNIT) {+ continue;+ }+ for (unsigned r = 0; r < sizeof(ufs_references) / sizeof(ufs_references[0]); r++) {+ if (ufs_is_reference((const char *)ufs_page->part[part].name, ufs_references[r].name)) {+ ufs_compare(part, 0, ufs_part_bytes(part), ufs_references[r].bytes, "whole", false);+ }+ }+ }+ if ((part = ufs_entry("super")) < BLOCK_MAX_PARTS) {+ ufs_compare(part, 0, 8 << 20, 0, "first 8 MB (geometry, metadata)", false);+ }+ if ((part = ufs_entry("darwin")) < BLOCK_MAX_PARTS) {+ uint64_t bytes = ufs_part_bytes(part), r0 = ufs_cmp_regions, d0 = ufs_cmp_differ;++ for (uint64_t k = 0; k < 64; k++) {+ ufs_compare(part, (bytes - (1 << 20)) / 64 * k / 4096 * 4096, 1 << 20, 0, "spread megabyte", true);+ }+ for (uint64_t k = 0; k < 512; k++) {+ seed = seed * 6364136223846793005ULL + 1442695040888963407ULL;+ ufs_compare(part, (seed >> 16) % (bytes / 4096) * 4096, 4096, 0, "scattered block", true);+ }+ for (uint64_t k = 0; k < 64; k++) {+ seed = seed * 6364136223846793005ULL + 1442695040888963407ULL;+ ufs_compare(part, (seed >> 16) % (bytes - (2 << 20)), 1 + (seed >> 40) % (1 << 20), 0, "unaligned piece", true);+ }+ printf("ufs: native check: darwin: %llu spread megabytes, scattered blocks and unaligned pieces: %llu not the same\n",+ ufs_cmp_regions - r0, ufs_cmp_differ - d0);+ }+ if (h != NULL) {+ kfree_data(h, 4096);+ }+ printf("ufs: native check done: %llu regions, %llu bytes, %llu NOT THE SAME; through the loader %llu ms, "+ "through this kernel's own driver %llu ms\n", ufs_cmp_regions, ufs_cmp_bytes, ufs_cmp_differ,+ ufs_cmp_mailbox_ns / 1000000, ufs_cmp_native_ns / 1000000);+ ufshc_report("after the check");+}++/* kern.redwood.ufs_native: 1 while reads go through this kernel's own driver; 0 or 1 may be set */+static int+ufs_sysctl_native(__unused struct sysctl_oid *oidp, __unused void *arg1, __unused int arg2, struct sysctl_req *req)+{+ int value = ufs_native_on, error, changed = 0;++ error = sysctl_io_number(req, value, sizeof(value), &value, &changed);+ if (error != 0 || !changed) {+ return error;+ }+ if (value != 0 && !(ufs_native_mapped && ufshc_available())) {+ return ENXIO;+ }+ ufs_native_on = value != 0;+ return 0;+}+SYSCTL_PROC(_kern_redwood, OID_AUTO, ufs_native, CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED, NULL, 0,+ ufs_sysctl_native, "I", "1: the phone's storage is read by this kernel's own UFS driver, 0: through the loader");+SYSCTL_QUAD(_kern_redwood, OID_AUTO, ufs_native_fallbacks, CTLFLAG_RD | CTLFLAG_LOCKED, &ufs_native_fallbacks,+ "times a read of this kernel's own UFS driver failed and the loader's was used instead");+/* ---- bringing it up ---- */void@@ -569,6 +885,9 @@ redwood_ufs_init(void)char name[48];ufs_bsize[i] = ufs_page->part[i].block_size;+ if (ufs_page->part[i].flags & BLOCK_PART_UNIT) {+ continue; /* the units are for this kernel's own driver to be checked against */+ }snprintf(name, sizeof(name), "ufs_%s", ufs_page->part[i].name);if (devfs_make_node(makedev(ufs_bmajor, i), DEVFS_BLOCK, UID_ROOT, GID_OPERATOR, 0640, "%s", name) == NULL) {printf("ufs: no node for %s (the same name twice?)\n", name);@@ -582,6 +901,27 @@ redwood_ufs_init(void)printf("ufs: %u partitions of the phone's storage as /dev/ufs_NAME and /dev/rufs_NAME, read only, ""through the loader's page at %llx and its %u KB buffer\n", made, pa, ufs_buffer_size >> 10);+ /* ufs_native=1: through this kernel's own driver instead, if the controller is as expected; 2: only look */+ check = 0;+ memset(ufs_lun, 0xff, sizeof(ufs_lun));+ if (PE_parse_boot_argn("ufs_native", &check, sizeof(check)) && check != 0) {+ if (ufshc_probe(check == 2) && ufs_native_map()) {+ ufs_native_mapped = true;+ ufs_native_on = true;+ printf("ufs: the partitions are read by this kernel's own UFS driver (kern.redwood.ufs_native=0: "+ "through the loader)\n");+ } else if (check != 2) {+ printf("ufs: this kernel's own UFS driver is not used: through the loader\n");+ }+ check = 0;+ if (ufs_native_mapped && PE_parse_boot_argn("ufs_native_check", &check, sizeof(check)) && check != 0) {+ /* right here, in bsd_init's thread, and then back to the loader */+ ufs_native_check();+ redwood_ufs_report("after the check");+ loader_return();+ }+ }+if (PE_parse_boot_argn("ufs_bench", &check, sizeof(check)) && check != 0) {/* right here, in bsd_init's thread, and then back to the loader: nothing else is wanted */ufs_bench(NULL, THREAD_AWAKENED);diff --git a/xnu/files/bsd/dev/redwood_ufshc.c b/xnu/files/bsd/dev/redwood_ufshc.cnew file mode 100644index 0000000..636f9fc--- /dev/null+++ b/xnu/files/bsd/dev/redwood_ufshc.c@@ -0,0 +1,769 @@+/*+ * The phone's UFS host controller, driven from this kernel -- read only, and shared with UEFI.+ *+ * Reading the storage through the loader (redwood_ufs.c) is one request at a time: Qualcomm's+ * UFS driver in UEFI (UFSDxe) reads synchronously on core 0, and its asynchronous reads finish+ * only from a UEFI timer that does not tick there while the kernel runs. The controller itself+ * takes up to 32 requests at once. This file puts requests of its own into it, next to UEFI's,+ * without taking the controller away from UEFI: UEFI still reads for the loader and writes the+ * run's log at its end.+ *+ * What it does not do, ever: reset or enable the controller, start the link, send UIC commands+ * (DME_GET/DME_SET), change the request lists' addresses, the interrupt enables, aggregation,+ * clocks or power modes, clear a request (UTRLCLR), or touch the task management list. It reads+ * the registers that say where UEFI's request list is and whether the controller runs, writes+ * request descriptors into slots of that list that UEFI does not use, rings their doorbell bits+ * (UTRLDBR is write-one-to-set: the other bits are not affected), and polls UTRLDBR until the+ * controller clears them. Requests are made with the interrupt bit clear, so that they raise no+ * completion status of their own in IS.+ *+ * Read only by construction: every command passes through ufshc_permitted() on its way to the+ * doorbell, a whitelist that lets through SCSI READ(10)/READ(16), TEST UNIT READY, REQUEST+ * SENSE, INQUIRY, READ CAPACITY(10/16) to a normal logical unit and query *read* requests (read+ * descriptor, attribute, flag), and nothing else; no data ever goes from host to device. What is+ * refused is logged and never reaches the doorbell. This file builds READ(10) only.+ *+ * WHAT THE PROBE FOUND ON THIS PHONE, AND WHY THIS PATH IS NOT USED THERE: Qualcomm's UFSDxe sets+ * up a list of one. The controller has 32 slots, UTRLBA points at 0xccf96000, slot 0 there is+ * UEFI's request descriptor -- and its command descriptor is at 0xccf96100, inside the 1 KB the+ * other 31 would take: "slots" 8..14 are its command UPIU, response and PRD table (pointing into+ * the loader's buffer), and 1..7 and 15..17 hold other data of the driver. No slot but UEFI's own+ * is free memory, so the probe refuses (twice over: the command descriptor inside the list, and+ * slots 16..31 that are not descriptors) and the storage is read through the loader. What+ * follows is how the path works where the list does have room.+ *+ * Which slots: UEFI's driver takes the first free slot for each request it makes, synchronously,+ * so it uses slot 0 (and during a run it reads only when the loader is asked to, and writes only+ * the log, after the run). This file keeps to the upper half of the list, 16..31, and makes its+ * requests in the even ones: a descriptor is 32 bytes and a cache line 64, and a line is only+ * ever written back here while its one request is not in flight, so nothing the controller+ * writes into a descriptor (its status) is overwritten by a stale copy of the line's other half.+ *+ * At the probe (ufshc_probe), anything unexpected leaves this path off and the loader's in use:+ * the controller not enabled and running, a version other than 2.x/3.x, fewer than 32 slots, no+ * 64-bit addressing, the list in memory this kernel manages, any of the slots 16..31 busy or+ * holding something that is not a request descriptor, a fatal error status. The slots' original+ * contents are kept and put back at the end of the run (redwood_ufs_quiesce, from+ * loader_return), after waiting until none of them is busy, so that the list is as UEFI left it+ * when it writes the run's log.+ *+ * Memory: each slot has a page for its command descriptor (command UPIU at 0, response UPIU at+ * 512, the PRD table at 1024) and a contiguous buffer the controller reads into; the descriptors+ * are cleaned to the point of coherency before the doorbell and invalidated before they are+ * read back, and so is the data, so it does not matter whether the controller's accesses are+ * coherent with the caches.+ */+#include <kern/clock.h>+#include <kern/locks.h>+#include <kern/thread.h>+#include <libkern/libkern.h>+#include <mach/mach_types.h>+#include <mach/vm_param.h>+#include <pexpert/pexpert.h>+#include <sys/errno.h>+#include <sys/param.h>+#include <sys/proc.h>+#include <sys/systm.h>+#include <sys/sysctl.h>+#include <vm/vm_kern.h>+#include <vm/memory_types.h>++extern vm_offset_t ml_io_map(vm_offset_t phys_addr, vm_size_t size);+extern vm_offset_t ml_io_map_unmappable(vm_offset_t phys_addr, vm_size_t size, unsigned int flags);+extern uint64_t kvtophys(vm_offset_t va); /* pmap_paddr_t */+extern boolean_t pmap_valid_address(uint64_t addr);+extern void FlushPoC_DcacheRegion(vm_offset_t va, size_t length);+extern void CleanPoC_DcacheRegion(vm_offset_t va, size_t length);+extern void IOSleep(unsigned int milliseconds);++#define UFSHC_PHYS 0x1d84000ULL /* ufshc@1d84000, "ufs_mem", in the phone's Android device tree */+#define UFSHC_SIZE 0x3000++/* UFSHCI registers (JESD223). 0x38..0x48, the UIC error codes, clear when read: never read here. */+#define UFSHC_CAP 0x00+#define UFSHC_VER 0x08+#define UFSHC_HCDDID 0x10+#define UFSHC_HCPMID 0x14+#define UFSHC_AHIT 0x18+#define UFSHC_IS 0x20+#define UFSHC_IE 0x24+#define UFSHC_HCS 0x30+#define UFSHC_HCE 0x34+#define UFSHC_UTRIACR 0x4c+#define UFSHC_UTRLBA 0x50+#define UFSHC_UTRLBAU 0x54+#define UFSHC_UTRLDBR 0x58+#define UFSHC_UTRLRSR 0x60+#define UFSHC_UTRLCNR 0x64+#define UFSHC_UTMRLBA 0x70+#define UFSHC_UTMRLBAU 0x74+#define UFSHC_UTMRLDBR 0x78+#define UFSHC_UTMRLRSR 0x80++#define CAP_NUTRS(c) (((c) & 0x1f) + 1)+#define CAP_64AS (1u << 24)+#define HCS_DP (1u << 0)+#define HCS_UTRLRDY (1u << 1)+#define IS_FATAL ((1u << 2) | (1u << 11) | (1u << 12) | (1u << 16) | (1u << 17)) /* UE, DFES, UTPES, HCFES, SBFES */+#define IS_UTRCS (1u << 0)++/* the request descriptor's first word: UFS storage command type, data direction */+#define UTRD_CT_UFS (1u << 28)+#define UTRD_DD_MASK (3u << 25)+#define UTRD_DD_NONE (0u << 25)+#define UTRD_DD_OUT (1u << 25) /* host to device: never */+#define UTRD_DD_IN (2u << 25)+#define OCS_SUCCESS 0x0+#define OCS_INVALID 0xf++#define UPIU_COMMAND 0x01+#define UPIU_QUERY_REQUEST 0x16+#define UPIU_RESPONSE 0x21+#define UPIU_FLAG_READ 0x40+#define UPIU_FLAG_WRITE 0x20++#define UCD_SIZE 0x4000 /* a page per slot */+#define UCD_RESPONSE 512+#define UCD_PRDT 1024+#define PRD_MAX (256u << 10) /* the most one table entry describes */++#define SLOT_FIRST 16 /* this kernel's part of the list: 16..31 */+#define SLOTS_RESERVED 0xffff0000u+#define SLOT_MAX 8+#define SLOT_BUFFER_DEFAULT (512u << 10)+#define BLOCK 4096u /* the logical block size of every unit here */++#define SPIN_US 5000 /* look without sleeping this long, then a millisecond at a time */+#define TIMEOUT_MS 10000++struct ufshc_slot {+ uint32_t number; /* in the list */+ volatile uint32_t *utrd; /* its descriptor, in UEFI's list */+ uint8_t *ucd;+ uint64_t ucd_pa;+ uint8_t *data;+ uint64_t data_pa;+ uint32_t original[8]; /* what the descriptor held at the probe, put back at the end */+};++static vm_offset_t hc; /* the registers */+static volatile uint32_t *hc_list; /* UEFI's request list, cacheable */+static uint64_t hc_list_pa;+static struct ufshc_slot hc_slots[SLOT_MAX];+static uint32_t hc_nslots, hc_free, hc_slot_buffer = SLOT_BUFFER_DEFAULT;+static uint32_t hc_is_at_probe;+static bool hc_usable; /* the probe found it as expected and the memory is there */+static volatile bool hc_closed, hc_dead;+static uint64_t hc_requests, hc_errors, hc_bytes, hc_wait_us, hc_refused, hc_most_in_flight;+static uint32_t hc_in_flight;++static LCK_GRP_DECLARE(hc_lck_grp, "redwood-ufshc");+static LCK_MTX_DECLARE(hc_lock, &hc_lck_grp);++SYSCTL_DECL(_kern_redwood);+SYSCTL_QUAD(_kern_redwood, OID_AUTO, ufs_native_requests, CTLFLAG_RD | CTLFLAG_LOCKED, &hc_requests,+ "requests this kernel's own UFS driver has had answered");+SYSCTL_QUAD(_kern_redwood, OID_AUTO, ufs_native_errors, CTLFLAG_RD | CTLFLAG_LOCKED, &hc_errors,+ "requests of this kernel's own UFS driver that failed");+SYSCTL_QUAD(_kern_redwood, OID_AUTO, ufs_native_bytes, CTLFLAG_RD | CTLFLAG_LOCKED, &hc_bytes,+ "bytes this kernel's own UFS driver has read");+SYSCTL_QUAD(_kern_redwood, OID_AUTO, ufs_native_wait_us, CTLFLAG_RD | CTLFLAG_LOCKED, &hc_wait_us,+ "microseconds spent waiting for the controller, summed over the requests");+SYSCTL_QUAD(_kern_redwood, OID_AUTO, ufs_native_refused, CTLFLAG_RD | CTLFLAG_LOCKED, &hc_refused,+ "commands the whitelist refused (there should never be one)");++static inline uint32_t+hc_read(uint32_t reg)+{+ return *(volatile uint32_t *)(hc + reg);+}++/* Nothing more is sent from here on; whoever waits for a slot is told. */+static void+hc_off(void)+{+ hc_dead = true;+ lck_mtx_lock(&hc_lock);+ wakeup(&hc_free);+ lck_mtx_unlock(&hc_lock);+}++static uint64_t+hc_us_since(uint64_t start)+{+ uint64_t ns;++ absolutetime_to_nanoseconds(mach_absolute_time() - start, &ns);+ return ns / 1000;+}++/* ---- the whitelist: the one check every command passes on its way to the doorbell ---- */++static const char *+hc_refusal(const uint8_t *upiu, uint32_t dw0)+{+ const uint8_t *cdb = upiu + 16;+ uint32_t dd = dw0 & UTRD_DD_MASK;++ if (dd == UTRD_DD_OUT || dd == UTRD_DD_MASK) {+ return "data from host to device";+ }+ if ((dw0 & 0xf0000000u) != UTRD_CT_UFS) {+ return "not a UFS storage command type";+ }+ switch (upiu[0] & 0x3f) {+ case UPIU_COMMAND:+ if (upiu[1] & UPIU_FLAG_WRITE) {+ return "a command that writes";+ }+ if (upiu[2] >= 8) {+ return "a well-known logical unit";+ }+ if (upiu[4] & 0x0f) {+ return "not the SCSI command set";+ }+ switch (cdb[0]) {+ case 0x28: /* READ(10) */+ case 0x88: /* READ(16) */+ return dd == UTRD_DD_IN && (upiu[1] & UPIU_FLAG_READ) ? NULL : "a read without data in";+ case 0x00: /* TEST UNIT READY */+ return dd == UTRD_DD_NONE ? NULL : "TEST UNIT READY with data";+ case 0x03: /* REQUEST SENSE */+ case 0x12: /* INQUIRY */+ case 0x25: /* READ CAPACITY(10) */+ return NULL;+ case 0x9e: /* SERVICE ACTION IN(16): READ CAPACITY(16) only */+ return (cdb[1] & 0x1f) == 0x10 ? NULL : "a SERVICE ACTION IN other than READ CAPACITY(16)";+ default:+ return "a SCSI operation not on the list";+ }+ case UPIU_QUERY_REQUEST:+ if (upiu[5] != 0x01) {+ return "a query that is not a standard read request";+ }+ if (upiu[12] != 0x01 && upiu[12] != 0x03 && upiu[12] != 0x05) {+ return "a query opcode other than read descriptor/attribute/flag";+ }+ return dd == UTRD_DD_NONE ? NULL : "a query with data";+ default:+ return "a transaction that is neither a command nor a query";+ }+}++static bool+ufshc_permitted(const uint8_t *upiu, uint32_t dw0)+{+ const char *why = hc_refusal(upiu, dw0);++ if (why == NULL) {+ return true;+ }+ hc_refused++;+ printf("ufs: native: REFUSED %s: UPIU %02x %02x %02x %02x, CDB %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x, "+ "descriptor %08x; nothing was sent\n", why, upiu[0], upiu[1], upiu[2], upiu[3], upiu[16], upiu[17], upiu[18],+ upiu[19], upiu[20], upiu[21], upiu[22], upiu[23], upiu[24], upiu[25], dw0);+ return false;+}++/*+ * The whitelist tried on commands made up here and never sent: those that must be refused,+ * and the read that must pass. Pure bytes; nothing touches the controller.+ */+static bool+hc_whitelist_selftest(void)+{+ static const struct {+ uint8_t type, flags, lun, cdb0, cdb1, query_function, query_opcode;+ uint32_t dd;+ bool pass;+ const char *what;+ } cases[] = {+ { UPIU_COMMAND, UPIU_FLAG_READ, 0, 0x28, 0, 0, 0, UTRD_DD_IN, true, "READ(10)" },+ { UPIU_COMMAND, UPIU_FLAG_READ, 0, 0x88, 0, 0, 0, UTRD_DD_IN, true, "READ(16)" },+ { UPIU_COMMAND, UPIU_FLAG_READ, 0, 0x25, 0, 0, 0, UTRD_DD_IN, true, "READ CAPACITY(10)" },+ { UPIU_QUERY_REQUEST, 0, 0, 0, 0, 0x01, 0x01, UTRD_DD_NONE, true, "QUERY READ DESCRIPTOR" },+ { UPIU_COMMAND, UPIU_FLAG_WRITE, 0, 0x2a, 0, 0, 0, UTRD_DD_OUT, false, "WRITE(10)" },+ { UPIU_COMMAND, 0, 0, 0x2a, 0, 0, 0, UTRD_DD_NONE, false, "WRITE(10) without the W flag" },+ { UPIU_COMMAND, UPIU_FLAG_READ, 0, 0x2a, 0, 0, 0, UTRD_DD_IN, false, "WRITE(10) dressed as a read" },+ { UPIU_COMMAND, UPIU_FLAG_WRITE, 0, 0x8a, 0, 0, 0, UTRD_DD_OUT, false, "WRITE(16)" },+ { UPIU_COMMAND, UPIU_FLAG_WRITE, 0, 0x42, 0, 0, 0, UTRD_DD_OUT, false, "UNMAP" },+ { UPIU_COMMAND, 0, 0, 0x04, 0, 0, 0, UTRD_DD_NONE, false, "FORMAT UNIT" },+ { UPIU_COMMAND, 0, 0, 0x1b, 0, 0, 0, UTRD_DD_NONE, false, "START STOP UNIT" },+ { UPIU_COMMAND, 0, 0, 0x35, 0, 0, 0, UTRD_DD_NONE, false, "SYNCHRONIZE CACHE(10)" },+ { UPIU_COMMAND, UPIU_FLAG_WRITE, 0, 0x3b, 0, 0, 0, UTRD_DD_OUT, false, "WRITE BUFFER" },+ { UPIU_COMMAND, UPIU_FLAG_READ, 0x44, 0x28, 0, 0, 0, UTRD_DD_IN, false, "READ(10) to the RPMB unit" },+ { UPIU_COMMAND, UPIU_FLAG_READ, 0, 0x9e, 0x11, 0, 0, UTRD_DD_IN, false, "SERVICE ACTION IN 0x11" },+ { UPIU_QUERY_REQUEST, 0, 0, 0, 0, 0x81, 0x02, UTRD_DD_NONE, false, "QUERY WRITE DESCRIPTOR" },+ { UPIU_QUERY_REQUEST, 0, 0, 0, 0, 0x81, 0x06, UTRD_DD_NONE, false, "QUERY SET FLAG" },+ { UPIU_QUERY_REQUEST, 0, 0, 0, 0, 0x01, 0x04, UTRD_DD_NONE, false, "QUERY WRITE ATTRIBUTE as a read" },+ { 0x04, 0, 0, 0, 0, 0, 0, UTRD_DD_NONE, false, "TASK MANAGEMENT" },+ { 0x00, 0, 0, 0, 0, 0, 0, UTRD_DD_NONE, false, "NOP OUT" },+ };+ uint64_t refused = hc_refused;+ bool right = true;++ for (unsigned i = 0; i < sizeof(cases) / sizeof(cases[0]); i++) {+ uint8_t upiu[32] = { 0 };+ bool passed;++ upiu[0] = cases[i].type;+ upiu[1] = cases[i].flags;+ upiu[2] = cases[i].lun == 0x44 ? 0xc4 : cases[i].lun;+ upiu[5] = cases[i].query_function;+ upiu[12] = cases[i].query_opcode;+ upiu[16] = cases[i].cdb0;+ upiu[17] = cases[i].cdb1;+ passed = hc_refusal(upiu, UTRD_CT_UFS | cases[i].dd) == NULL;+ if (passed != cases[i].pass) {+ printf("ufs: native: the whitelist %s %s\n", passed ? "LETS THROUGH" : "refuses", cases[i].what);+ right = false;+ }+ }+ hc_refused = refused;+ printf("ufs: native: whitelist tried on %u commands made up and never sent (READ(10/16), READ CAPACITY, "+ "QUERY READ DESCRIPTOR pass; WRITE(10/16), UNMAP, FORMAT UNIT, START STOP UNIT, SYNCHRONIZE CACHE, "+ "WRITE BUFFER, RPMB, query writes and set flag, task management, NOP OUT refused): %s\n",+ (unsigned)(sizeof(cases) / sizeof(cases[0])), right ? "as it should" : "WRONG");+ return right;+}++/* ---- one request in one slot ---- */++static int+hc_submit(struct ufshc_slot *s, uint8_t lun, uint32_t lba, uint32_t blocks)+{+ uint32_t bytes = blocks * BLOCK, n = 0, dw0 = UTRD_CT_UFS | UTRD_DD_IN;+ uint8_t *cmd = s->ucd;++ /* the command UPIU and an empty response */+ bzero(s->ucd, UCD_PRDT);+ cmd[0] = UPIU_COMMAND;+ cmd[1] = UPIU_FLAG_READ; /* simple task attribute */+ cmd[2] = lun;+ cmd[3] = (uint8_t)s->number; /* task tag */+ cmd[12] = (uint8_t)(bytes >> 24);+ cmd[13] = (uint8_t)(bytes >> 16);+ cmd[14] = (uint8_t)(bytes >> 8);+ cmd[15] = (uint8_t)bytes;+ cmd[16] = 0x28; /* READ(10) */+ cmd[18] = (uint8_t)(lba >> 24);+ cmd[19] = (uint8_t)(lba >> 16);+ cmd[20] = (uint8_t)(lba >> 8);+ cmd[21] = (uint8_t)lba;+ cmd[23] = (uint8_t)(blocks >> 8);+ cmd[24] = (uint8_t)blocks;+ /* the data's place, in pieces of at most 256 KB */+ for (uint32_t at = 0; at < bytes; at += PRD_MAX, n++) {+ volatile uint32_t *prd = (volatile uint32_t *)(s->ucd + UCD_PRDT + 16 * n);+ uint64_t pa = s->data_pa + at;+ uint32_t len = bytes - at < PRD_MAX ? bytes - at : PRD_MAX;++ prd[0] = (uint32_t)pa;+ prd[1] = (uint32_t)(pa >> 32);+ prd[2] = 0;+ prd[3] = len - 1;+ }+ FlushPoC_DcacheRegion((vm_offset_t)s->ucd, UCD_PRDT + 16 * n);+ /* nothing of the buffer is left in a cache to be written back over what the controller writes */+ FlushPoC_DcacheRegion((vm_offset_t)s->data, bytes);++ s->utrd[0] = dw0; /* no interrupt, no inline encryption */+ s->utrd[1] = 0;+ s->utrd[2] = OCS_INVALID;+ s->utrd[3] = 0;+ s->utrd[4] = (uint32_t)s->ucd_pa;+ s->utrd[5] = (uint32_t)(s->ucd_pa >> 32);+ s->utrd[6] = ((UCD_RESPONSE / 4) << 16) | (UCD_RESPONSE / 4); /* response: offset, length in dwords */+ s->utrd[7] = ((UCD_PRDT / 4) << 16) | n; /* PRD table: offset in dwords, entries */+ FlushPoC_DcacheRegion((vm_offset_t)s->utrd, 32);++ /* what the controller will read is what the whitelist sees */+ if (!ufshc_permitted(s->ucd, s->utrd[0])) {+ return EPERM;+ }+ if (hc_closed || hc_dead) {+ return ENXIO;+ }+ if (hc_read(UFSHC_UTRLDBR) & (1u << s->number)) {+ printf("ufs: native: slot %u is busy before it is used: this path is off from now on\n", s->number);+ hc_off();+ return EIO;+ }+ __asm__ volatile ("dsb sy" ::: "memory");+ *(volatile uint32_t *)(hc + UFSHC_UTRLDBR) = 1u << s->number;+ return 0;+}++/* Until the controller is done with the slot's request; then whether it went well. */+static int+hc_complete(struct ufshc_slot *s, uint8_t lun, uint32_t lba, uint32_t blocks)+{+ uint64_t started = mach_absolute_time(), us;+ const uint8_t *r = s->ucd + UCD_RESPONSE;+ uint32_t ocs;++ while (hc_read(UFSHC_UTRLDBR) & (1u << s->number)) {+ us = hc_us_since(started);+ if (us < SPIN_US) {+ __builtin_arm_yield();+ continue;+ }+ if (us > TIMEOUT_MS * 1000ULL) {+ printf("ufs: native: slot %u (LUN %u, blocks %u..%u) not done in %u s (doorbell %08x, IS %08x, HCS %08x): "+ "this path is off from now on\n", s->number, lun, lba, lba + blocks - 1, TIMEOUT_MS / 1000,+ hc_read(UFSHC_UTRLDBR), hc_read(UFSHC_IS), hc_read(UFSHC_HCS));+ hc_off();+ return ETIMEDOUT;+ }+ IOSleep(1);+ }+ __asm__ volatile ("dsb sy" ::: "memory");+ hc_wait_us += hc_us_since(started);+ FlushPoC_DcacheRegion((vm_offset_t)s->utrd, 32);+ FlushPoC_DcacheRegion((vm_offset_t)r, 64);+ ocs = s->utrd[2] & 0xff;+ if (ocs != OCS_SUCCESS || (r[0] & 0x3f) != UPIU_RESPONSE || r[3] != s->number || r[6] != 0 || r[7] != 0) {+ /* sense data follows the 32 bytes of the header: length (2), then the fixed format */+ FlushPoC_DcacheRegion((vm_offset_t)r + 64, 64);+ printf("ufs: native: slot %u, LUN %u, blocks %u..%u: OCS %x, response %02x tag %02x, response %02x status %02x, "+ "sense key %x asc %02x ascq %02x\n", s->number, lun, lba, lba + blocks - 1, ocs, r[0], r[3], r[6], r[7],+ r[34 + 2] & 0x0f, r[34 + 12], r[34 + 13]);+ hc_errors++;+ return EIO;+ }+ FlushPoC_DcacheRegion((vm_offset_t)s->data, blocks * BLOCK);+ hc_requests++;+ hc_bytes += blocks * BLOCK;+ return 0;+}++static struct ufshc_slot *+hc_take(bool wait)+{+ struct ufshc_slot *s = NULL;++ lck_mtx_lock(&hc_lock);+ while (hc_free == 0 && wait && !hc_dead) {+ msleep(&hc_free, &hc_lock, PRIBIO, "ufshc", NULL);+ }+ if (hc_free != 0) {+ uint32_t i = (uint32_t)__builtin_ctz(hc_free);++ hc_free &= ~(1u << i);+ s = &hc_slots[i];+ if (++hc_in_flight > hc_most_in_flight) {+ hc_most_in_flight = hc_in_flight;+ }+ }+ lck_mtx_unlock(&hc_lock);+ return s;+}++static void+hc_give(struct ufshc_slot *s)+{+ lck_mtx_lock(&hc_lock);+ hc_free |= 1u << (s - hc_slots);+ hc_in_flight--;+ wakeup(&hc_free);+ lck_mtx_unlock(&hc_lock);+}++/*+ * Bytes [offset, offset + len) of logical unit lun into dst: the blocks that cover them, a slot's+ * buffer at a time, with as many slots in flight at once as are free (at least one), the wanted+ * bytes copied out of each as it is done.+ */+int+ufshc_read(uint8_t lun, uint64_t offset, uint8_t *dst, uint64_t len)+{+ struct {+ struct ufshc_slot *slot;+ uint32_t lba, blocks, skip, take;+ uint8_t *to;+ } q[SLOT_MAX];+ uint32_t head = 0, tail = 0, per = hc_slot_buffer / BLOCK;+ int error = 0;++ if (!hc_usable || hc_dead || hc_closed) {+ return ENXIO;+ }+ while ((len > 0 && error == 0) || head != tail) {+ /* as many more requests as there are free slots (and one, waiting for it, if none is in flight) */+ while (len > 0 && error == 0 && tail - head < SLOT_MAX) {+ uint64_t first = offset / BLOCK, skip = offset % BLOCK;+ uint64_t blocks = (skip + len + BLOCK - 1) / BLOCK, take;+ struct ufshc_slot *s = hc_take(head == tail);+ int e;++ if (s == NULL) {+ if (head == tail) {+ error = EIO; /* the path went off while waiting */+ }+ break;+ }+ if (blocks > per) {+ blocks = per;+ }+ if (first + blocks > 0xffffffffULL) {+ hc_give(s);+ error = EINVAL;+ break;+ }+ take = blocks * BLOCK - skip;+ if (take > len) {+ take = len;+ }+ e = hc_submit(s, lun, (uint32_t)first, (uint32_t)blocks);+ if (e != 0) {+ hc_give(s);+ error = e;+ break;+ }+ q[tail % SLOT_MAX].slot = s;+ q[tail % SLOT_MAX].lba = (uint32_t)first;+ q[tail % SLOT_MAX].blocks = (uint32_t)blocks;+ q[tail % SLOT_MAX].skip = (uint32_t)skip;+ q[tail % SLOT_MAX].take = (uint32_t)take;+ q[tail % SLOT_MAX].to = dst;+ tail++;+ offset += take;+ dst += take;+ len -= take;+ }+ /* the oldest one done, copied out, its slot free again */+ if (head != tail) {+ typeof(q[0]) *e = &q[head % SLOT_MAX];+ int r = hc_complete(e->slot, lun, e->lba, e->blocks);++ if (r == 0 && error == 0) {+ memcpy(e->to, e->slot->data + e->skip, e->take);+ } else if (error == 0) {+ error = r;+ }+ if (r != ETIMEDOUT) {+ hc_give(e->slot); /* (a slot that never came back is not used again) */+ }+ head++;+ }+ }+ return error;+}++bool+ufshc_available(void)+{+ return hc_usable && !hc_dead && !hc_closed;+}++void+ufshc_report(const char *when)+{+ if (!hc_usable) {+ return;+ }+ printf("ufs: native: %s: %llu requests, %llu errors, %llu bytes, %llu ms waiting (summed over requests), "+ "at most %llu in flight, %llu refused%s\n", when, hc_requests, hc_errors, hc_bytes, hc_wait_us / 1000,+ hc_most_in_flight, hc_refused, hc_dead ? "; THE PATH IS OFF" : "");+}++/* ---- the probe ---- */++static bool+hc_looks_like_descriptor(const volatile uint32_t *d)+{+ bool zero = true;++ for (int i = 0; i < 8; i++) {+ zero &= d[i] == 0;+ }+ /* never used, or a UFS storage request with its command descriptor 128-byte aligned */+ return zero || ((d[0] & 0xf0000000u) == UTRD_CT_UFS && (d[4] & 0x7f) == 0 && (d[0] & UTRD_DD_MASK) != UTRD_DD_MASK);+}++/*+ * What the controller looks like as UEFI left it, and whether this kernel may put requests of+ * its own into it (only == true: say so and do not touch anything but registers' reads).+ */+bool+ufshc_probe(bool only)+{+ uint32_t cap, ver, hcs, hce, is, ie, iacr, ahit, base, baseu, db, rsr, cnr, tm_base, tm_baseu, tm_db, tm_rsr;+ uint64_t ucd0 = 0, list_end;+ const char *no = NULL;+ vm_offset_t list_va;++ if (!hc_whitelist_selftest()) {+ return false;+ }+ PE_parse_boot_argn("ufs_native_buffer", &hc_slot_buffer, sizeof(hc_slot_buffer));+ if (hc_slot_buffer < BLOCK || hc_slot_buffer > (4u << 20) || hc_slot_buffer % BLOCK) {+ hc_slot_buffer = SLOT_BUFFER_DEFAULT;+ }+ hc = ml_io_map(UFSHC_PHYS, UFSHC_SIZE);+ cap = hc_read(UFSHC_CAP);+ ver = hc_read(UFSHC_VER);+ hcs = hc_read(UFSHC_HCS);+ hce = hc_read(UFSHC_HCE);+ is = hc_read(UFSHC_IS);+ ie = hc_read(UFSHC_IE);+ iacr = hc_read(UFSHC_UTRIACR);+ ahit = hc_read(UFSHC_AHIT);+ base = hc_read(UFSHC_UTRLBA);+ baseu = hc_read(UFSHC_UTRLBAU);+ db = hc_read(UFSHC_UTRLDBR);+ rsr = hc_read(UFSHC_UTRLRSR);+ cnr = hc_read(UFSHC_UTRLCNR);+ tm_base = hc_read(UFSHC_UTMRLBA);+ tm_baseu = hc_read(UFSHC_UTMRLBAU);+ tm_db = hc_read(UFSHC_UTMRLDBR);+ tm_rsr = hc_read(UFSHC_UTMRLRSR);+ hc_is_at_probe = is;+ printf("ufs: native: controller at %llx: CAP %08x (%u slots, 64-bit %s), VER %08x, HCDDID %08x, HCPMID %08x\n",+ UFSHC_PHYS, cap, CAP_NUTRS(cap), (cap & CAP_64AS) ? "yes" : "no", ver, hc_read(UFSHC_HCDDID),+ hc_read(UFSHC_HCPMID));+ printf("ufs: native: HCE %08x, HCS %08x, IS %08x, IE %08x, UTRIACR %08x, AHIT %08x\n", hce, hcs, is, ie, iacr, ahit);+ printf("ufs: native: transfer list %08x:%08x, doorbell %08x, run %08x, completion %08x; "+ "task management list %08x:%08x, doorbell %08x, run %08x\n", baseu, base, db, rsr, cnr, tm_baseu, tm_base,+ tm_db, tm_rsr);+ hc_list_pa = (uint64_t)baseu << 32 | base;+ list_end = hc_list_pa + 32ULL * CAP_NUTRS(cap);++ if ((hce & 1) == 0) {+ no = "the controller is not enabled";+ } else if ((hcs & (HCS_DP | HCS_UTRLRDY)) != (HCS_DP | HCS_UTRLRDY)) {+ no = "no device present or the transfer list not ready";+ } else if ((rsr & 1) == 0) {+ no = "the transfer list is not running";+ } else if (ver < 0x200 || ver >= 0x400) {+ no = "a controller version other than 2.x or 3.x";+ } else if (CAP_NUTRS(cap) < 32) {+ no = "fewer than 32 slots";+ } else if ((cap & CAP_64AS) == 0) {+ no = "no 64-bit addressing";+ } else if (is & IS_FATAL) {+ no = "an error status";+ } else if (hc_list_pa == 0 || (hc_list_pa & 0x3ff) != 0) {+ no = "no transfer list, or one not 1 KB aligned";+ } else if (pmap_valid_address(hc_list_pa) || pmap_valid_address(list_end - 1)) {+ no = "the transfer list is in memory this kernel manages";+ } else if (db & SLOTS_RESERVED) {+ no = "a slot of 16..31 is busy";+ }+ if (no != NULL) {+ printf("ufs: native: not used: %s; the storage is read through the loader\n", no);+ return false;+ }++ /* UEFI's list: what each slot holds now (the ones that hold anything) */+ list_va = ml_io_map_unmappable((vm_offset_t)(hc_list_pa & ~(vm_offset_t)PAGE_MASK),+ (vm_size_t)round_page(list_end - (hc_list_pa & ~(uint64_t)PAGE_MASK)), VM_WIMG_DEFAULT);+ hc_list = (volatile uint32_t *)(list_va + (hc_list_pa & PAGE_MASK));+ FlushPoC_DcacheRegion((vm_offset_t)hc_list, 32 * 32);+ for (uint32_t i = 0; i < 32; i++) {+ const volatile uint32_t *d = hc_list + 8 * i;++ if ((d[0] | d[1] | d[2] | d[3] | d[4] | d[5] | d[6] | d[7]) != 0) {+ printf("ufs: native: slot %2u: %08x %08x %08x %08x %08x %08x %08x %08x\n", i, d[0], d[1], d[2], d[3], d[4],+ d[5], d[6], d[7]);+ }+ if (i >= SLOT_FIRST && !hc_looks_like_descriptor(d)) {+ no = "a slot of 16..31 holds something that is not a request descriptor";+ }+ if (i < SLOT_FIRST && ucd0 == 0 && (d[4] | d[5]) != 0) {+ ucd0 = (uint64_t)d[5] << 32 | d[4];+ }+ }+ if (ucd0 != 0) {+ /* UEFI's own command descriptor: the last command it sent, and where it is */+ vm_offset_t va = ml_io_map_unmappable((vm_offset_t)(ucd0 & ~(uint64_t)PAGE_MASK), PAGE_SIZE * 2, VM_WIMG_DEFAULT);+ const volatile uint8_t *u = (const volatile uint8_t *)(va + (ucd0 & PAGE_MASK));++ FlushPoC_DcacheRegion((vm_offset_t)u, 1024);+ printf("ufs: native: UEFI's command descriptor at %llx: command UPIU %02x %02x %02x %02x, CDB %02x %02x %02x %02x %02x "+ "%02x %02x %02x %02x %02x; response %02x .. %02x %02x\n", ucd0, u[0], u[1], u[2], u[3], u[16], u[17], u[18],+ u[19], u[20], u[21], u[22], u[23], u[24], u[25], u[512], u[518], u[519]);+ if (ucd0 < list_end && ucd0 + 1024 > hc_list_pa) {+ no = "UEFI's command descriptor is inside the list";+ }+ }+ if (no != NULL) {+ printf("ufs: native: not used: %s; the storage is read through the loader\n", no);+ return false;+ }+ if (only) {+ printf("ufs: native: as expected; ufs_native=2 asks for no more than this look\n");+ return false;+ }++ /* this kernel's slots: the even ones of 16..31, a page of descriptor and a buffer each */+ for (uint32_t i = 0; i < SLOT_MAX; i++) {+ struct ufshc_slot *s = &hc_slots[i];+ vm_offset_t ucd = 0, data = 0;++ if (kmem_alloc_contig(kernel_map, &ucd, UCD_SIZE, PAGE_MASK, 0, 0, KMA_KOBJECT | KMA_ZERO | KMA_DATA,+ VM_KERN_MEMORY_IOKIT) != KERN_SUCCESS ||+ kmem_alloc_contig(kernel_map, &data, round_page(hc_slot_buffer), PAGE_MASK, 0, 0,+ KMA_KOBJECT | KMA_ZERO | KMA_DATA, VM_KERN_MEMORY_IOKIT) != KERN_SUCCESS) {+ printf("ufs: native: no memory for slot buffers; the storage is read through the loader\n");+ return false;+ }+ s->number = SLOT_FIRST + 2 * i;+ s->utrd = hc_list + 8 * s->number;+ s->ucd = (uint8_t *)ucd;+ s->ucd_pa = kvtophys(ucd);+ s->data = (uint8_t *)data;+ s->data_pa = kvtophys(data);+ for (int w = 0; w < 8; w++) {+ s->original[w] = s->utrd[w];+ }+ FlushPoC_DcacheRegion(ucd, UCD_SIZE);+ FlushPoC_DcacheRegion(data, hc_slot_buffer);+ }+ hc_nslots = SLOT_MAX;+ hc_free = (1u << SLOT_MAX) - 1;+ hc_usable = true;+ printf("ufs: native: in use: slots 16, 18, .. 30 of UEFI's list at %llx, %u KB a request; UEFI keeps the rest\n",+ hc_list_pa, hc_slot_buffer >> 10);+ return true;+}++/*+ * Before the kernel gives the phone back to the loader (loader_return, the other processors+ * already stopped): nothing more is sent, what is in flight is waited for, and the slots'+ * descriptors are put back as they were, so that UEFI finds its list as it left it.+ */+void+redwood_ufs_quiesce(void)+{+ uint64_t started = mach_absolute_time();+ uint32_t db = 0, is;++ if (!hc_usable) {+ return;+ }+ hc_closed = true;+ __asm__ volatile ("dsb sy" ::: "memory");+ while ((db = hc_read(UFSHC_UTRLDBR)) & SLOTS_RESERVED) {+ if (hc_us_since(started) > 2000000) {+ break;+ }+ }+ is = hc_read(UFSHC_IS);+ if (db & SLOTS_RESERVED) {+ printf("ufs: native: at the end, slots still busy after 2 s (doorbell %08x, IS %08x): the descriptors "+ "are left as they are\n", db, is);+ return;+ }+ for (uint32_t i = 0; i < hc_nslots; i++) {+ struct ufshc_slot *s = &hc_slots[i];++ for (int w = 0; w < 8; w++) {+ s->utrd[w] = s->original[w];+ }+ FlushPoC_DcacheRegion((vm_offset_t)s->utrd, 32);+ }+ printf("ufs: native: at the end: none of slots 16..31 busy (doorbell %08x), their descriptors as they were; "+ "IS %08x (at the probe %08x); %llu requests, %llu errors, %llu refused\n", db, is, hc_is_at_probe,+ hc_requests, hc_errors, hc_refused);+}diff --git a/xnu/files/osfmk/arm64/loader_return.c b/xnu/files/osfmk/arm64/loader_return.cindex bf969dc..1595d1d 100644--- a/xnu/files/osfmk/arm64/loader_return.c+++ b/xnu/files/osfmk/arm64/loader_return.c@@ -56,6 +56,7 @@ extern void redwood_haptic_quiesce(void);extern void redwood_torch_quiesce(void);extern void redwood_camera_quiesce(void);extern void redwood_mic_quiesce(void);+extern void redwood_ufs_quiesce(void);void loader_checkpoint(uint64_t n);/* Also referenced from the early exception vector in start.s. */@@ -367,6 +368,7 @@ loader_return(void)*/psci_smp_stop_others();#endif+ redwood_ufs_quiesce(); /* this kernel's requests to the storage done, UEFI's list as it was, for the log */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 */diff --git a/xnu/redwood.patch b/xnu/redwood.patchindex 76dea0f..83412d0 100644--- a/xnu/redwood.patch+++ b/xnu/redwood.patch@@ -62,10 +62,10 @@ index a4d25040f38f..aad72993d139 100644kern_debug.o_INCFLAGS += -I$(SRCROOT)/osfmkdiff --git a/bsd/conf/files b/bsd/conf/files-index 44274016a4cf..872767b197b8 100644+index 44274016a4cf..14810c85d6dd 100644--- a/bsd/conf/files+++ b/bsd/conf/files-@@ -109,6 +109,35 @@ bsd/dev/munge.c optional config_requires_u32_munging+@@ -109,6 +109,36 @@ bsd/dev/munge.c optional config_requires_u32_mungingbsd/dev/unix_startup.c standardbsd/dev/monotonic.c optional monotonic@@ -75,6 +75,7 @@ index 44274016a4cf..872767b197b8 100644+bsd/dev/redwood_buttons.c standard+bsd/dev/redwood_battery.c standard+bsd/dev/redwood_ufs.c standard++bsd/dev/redwood_ufshc.c standard+bsd/dev/redwood_net.c standard+bsd/dev/redwood_virtio_net.c standard+bsd/dev/redwood_apple80211.c standard@@ -101,7 +102,7 @@ index 44274016a4cf..872767b197b8 100644bsd/dev/dev_perfmon.c optional config_perfmonbsd/libkern/crc32.c standard-@@ -155,6 +184,14 @@ bsd/miscfs/devfs/devfs_vfsops.c optional devfs+@@ -155,6 +185,14 @@ bsd/miscfs/devfs/devfs_vfsops.c optional devfsbsd/miscfs/mockfs/mockfs_fsnode.c optional mockfsbsd/miscfs/mockfs/mockfs_vfsops.c optional mockfsbsd/miscfs/mockfs/mockfs_vnops.c optional mockfs@@ -116,7 +117,7 @@ index 44274016a4cf..872767b197b8 100644bsd/miscfs/routefs/routefs_ops.c optional routefs-@@ -361,6 +398,7 @@ bsd/security/audit/audit_syscalls.c standard+@@ -361,6 +399,7 @@ bsd/security/audit/audit_syscalls.c standardbsd/security/audit/audit_worker.c optional config_auditbsd/pthread/pthread_shims.c standard@@ -124,7 +125,7 @@ index 44274016a4cf..872767b197b8 100644bsd/pthread/pthread_priority.c standardbsd/pthread/pthread_workqueue.c standard-@@ -383,6 +421,7 @@ bsd/kern/kern_debug.c standard+@@ -383,6 +422,7 @@ bsd/kern/kern_debug.c standardbsd/kern/kern_symfile.c standardbsd/kern/kern_descrip.c standardbsd/kern/kern_guarded.c standarddiff --git a/xnuloader/efi.h b/xnuloader/efi.hindex 5100529..14c7b62 100644--- a/xnuloader/efi.h+++ b/xnuloader/efi.h@@ -96,8 +96,16 @@ typedef struct {efi_handle stderr_handle; efi_text_output *std_err;efi_runtime_services *rt;efi_boot_services *bs;+ uint64_t nr_tables; /* the configuration tables: ACPI, a device tree, ... */+ struct { efi_guid guid; void *table; } *tables;} efi_system_table;+/* a device path is a list of these, each followed by its data, ending with type 0x7f subtype 0xff */+typedef struct {+ uint8_t type, subtype;+ uint8_t length[2]; /* of the whole node, header included, little endian */+} efi_device_path;+/* Graphics Output */typedef struct {uint32_t version, width, height, pixel_format;@@ -246,6 +254,7 @@ typedef struct {#define EFI_GOP_GUID { 0x9042a9de, 0x23dc, 0x4a38, { 0x96, 0xfb, 0x7a, 0xde, 0xd0, 0x80, 0x51, 0x6a } }#define EFI_BLOCK_IO_GUID { 0x964e5b21, 0x6459, 0x11d2, { 0x8e, 0x39, 0x00, 0xa0, 0xc9, 0x69, 0x72, 0x3b } }#define EFI_BLOCK_IO2_GUID { 0xa77b2472, 0xe282, 0x4e9f, { 0xa2, 0x45, 0xc2, 0xc0, 0xe2, 0x7b, 0xbc, 0xc1 } }+#define EFI_DEVICE_PATH_GUID { 0x09576e91, 0x6d3f, 0x11d2, { 0x8e, 0x39, 0x00, 0xa0, 0xc9, 0x69, 0x72, 0x3b } }#define EFI_PARTITION_INFO_GUID { 0x8cf2f62c, 0xbc9b, 0x4821, { 0x80, 0x8d, 0xec, 0x9e, 0xc4, 0x21, 0xa1, 0xa0 } }#define QCOM_CHARGER_EX_GUID { 0x6edc8a6d, 0x2663, 0x43cd, { 0x90, 0xff, 0x46, 0x21, 0xff, 0xd1, 0x0d, 0xf5 } }#define QCOM_CHARGER_GUID { 0x21bfb78b, 0x02ea, 0x4ab7, { 0x99, 0x40, 0xb5, 0x8a, 0x2a, 0xd6, 0x58, 0x29 } }diff --git a/xnuloader/loader.c b/xnuloader/loader.cindex f6f4774..ff02f56 100644--- a/xnuloader/loader.c+++ b/xnuloader/loader.c@@ -98,6 +98,19 @@ memset(void *dst, int c, size_t n)return dst;}+int+memcmp(const void *a, const void *b, size_t n)+{+ const uint8_t *x = a, *y = b;++ for (; n > 0; n--, x++, y++) {+ if (*x != *y) {+ return *x < *y ? -1 : 1;+ }+ }+ return 0;+}+void *memcpy(void *dst, const void *src, size_t n){@@ -280,6 +293,9 @@ find_log_partition(void)* fetches over USB (fastboot get_staged).*/static char out_buf[2 * 1024 * 1024];+/* the storage's reads for the kernel land here (block_poll); also where the log is read back */+#define BLOCK_BUFFER_SIZE (4u << 20)+static uint8_t block_buffer[BLOCK_BUFFER_SIZE] __attribute__((aligned(0x2000)));static const char *staged_data = out_buf; /* what "upload" sends: normally the log in out_buf */static uint64_t staged_len;@@ -325,9 +341,24 @@ write_logs(const char *klog, uint64_t klog_len)}uint64_t bs = bio->media->block_size;uint64_t len = (staged_len + 1 + bs - 1) / bs * bs;- if (!EFI_ERROR(bio->write_blocks(bio, bio->media->media_id, 0, len, out_buf))) {+ efi_status ws = bio->write_blocks(bio, bio->media->media_id, 0, len, out_buf), rs = 0;+ int same = 0;++ if (!EFI_ERROR(ws)) {bio->flush_blocks(bio);+ /*+ * And read back: that the log is in the partition is what a run of the kernel's own UFS+ * driver must leave possible (the controller is shared with this one). The line goes into+ * the copy the host fetches over USB, not into the partition, which already has the rest.+ */+ if (len <= sizeof(block_buffer)) {+ rs = bio->read_blocks(bio, bio->media->media_id, 0, len, block_buffer);+ same = !EFI_ERROR(rs) && memcmp(block_buffer, out_buf, len) == 0;+ }}+ print("log: %d bytes written to logdump (%x), read back %s (%x)\n", len, ws,+ EFI_ERROR(ws) ? "not tried" : same ? "the same" : "DIFFERENT", rs);+ compose_logs(klog, klog_len);}static void@@ -1410,14 +1441,26 @@ ufs_survey(void)* back over the data.*/#define BLOCK_MAGIC 0x4b434f4c42574452ULL /* "RDWBLOCK" */-#define BLOCK_VERSION 1-#define BLOCK_MAX_PARTS 128-#define BLOCK_BUFFER_SIZE (4u << 20)+#define BLOCK_VERSION 2+#define BLOCK_MAX_PARTS 160+#define BLOCK_MAX_UNITS 16+#define BLOCK_PART_UNIT 1u /* the entry is a whole logical unit, not a partition */+/*+ * The partitions first, then the logical units they are on (BLOCK_PART_UNIT, named unit0, unit1,+ * ... in the order UEFI lists them). Each partition says which of those it is on and where it+ * begins there, so that a reader of the units themselves -- the kernel's own UFS driver -- finds+ * it; a unit says its logical unit number if its device path does.+ */struct loader_block_part {char name[36];uint32_t block_size;uint64_t blocks;+ uint64_t start_lba; /* where it begins on its unit, in the unit's blocks (0 for a unit) */+ uint16_t unit; /* the unit it is on, its number among the units; 0xffff: not known */+ uint8_t lun; /* a unit's logical unit number as its device path says; 0xff: it does not */+ uint8_t flags; /* BLOCK_PART_UNIT */+ uint32_t reserved;};struct loader_block {@@ -1446,10 +1489,73 @@ struct loader_block {static struct loader_block block_shared __attribute__((aligned(0x2000)));static void block_io2_probe(efi_handle h, efi_block_io *bio);static int block_probe_requested; /* ufs_probe=1: block_io2_probe() at block_start() */-static uint8_t block_buffer[BLOCK_BUFFER_SIZE] __attribute__((aligned(0x2000)));static efi_block_io *block_bios[BLOCK_MAX_PARTS];static int block_enabled;+/* the bytes of a device path before its end node */+static uint64_t+device_path_bytes(const efi_device_path *dp)+{+ const uint8_t *p = (const uint8_t *)dp;+ uint64_t n = 0;++ for (int nodes = 0; nodes < 64; nodes++) {+ uint64_t len = p[n + 2] | (uint64_t)p[n + 3] << 8;++ if (p[n] == 0x7f || len < 4) {+ break;+ }+ n += len;+ }+ return n;+}++/*+ * A unit's device path, a node at a time ("ufs: unit N: path TYPE.SUBTYPE[data] ..."), and its+ * logical unit number if a UFS node (messaging, subtype 0x19: target, then LUN) says it.+ */+static uint8_t+device_path_print(uint64_t unit, const efi_device_path *dp)+{+ const uint8_t *p = (const uint8_t *)dp;+ uint64_t n = 0, total = device_path_bytes(dp);+ uint8_t lun = 0xff;++ print("ufs: unit %d: path", unit);+ while (n < total) {+ uint64_t len = p[n + 2] | (uint64_t)p[n + 3] << 8;++ print(" %x.%x[", (uint64_t)p[n], (uint64_t)p[n + 1]);+ for (uint64_t i = 4; i < len && i < 4 + 24; i++) {+ print("%s%x", (uint64_t)p[n + i] < 16 ? "0" : "", (uint64_t)p[n + i]);+ }+ print("%s]", len > 4 + 24 ? "..." : "");+ if (p[n] == 3 && p[n + 1] == 0x19 && len >= 6) {+ lun = p[n + 5];+ }+ n += len;+ }+ print(lun == 0xff ? "\n" : " (LUN %d)\n", (uint64_t)lun);+ return lun;+}++/*+ * The firmware's configuration tables, by GUID (an ACPI or device tree table among them would say+ * where the storage controller is).+ */+static void+block_tables(void)+{+ for (uint64_t i = 0; ST->tables != NULL && i < ST->nr_tables && i < 32; i++) {+ const efi_guid *g = &ST->tables[i].guid;++ print("ufs: firmware table %d: %x-%x-%x-%x%x-%x%x%x%x%x%x at %x\n", i, (uint64_t)g->a, (uint64_t)g->b,+ (uint64_t)g->c, (uint64_t)g->d[0], (uint64_t)g->d[1], (uint64_t)g->d[2], (uint64_t)g->d[3],+ (uint64_t)g->d[4], (uint64_t)g->d[5], (uint64_t)g->d[6], (uint64_t)g->d[7],+ (uint64_t)(uintptr_t)ST->tables[i].table);+ }+}+static voidblock_start(void){@@ -1458,15 +1564,44 @@ block_start(void)efi_handle *handles;uint64_t count;+ static const efi_guid dp_guid = EFI_DEVICE_PATH_GUID;+ static struct {+ efi_block_io *bio;+ const efi_device_path *path;+ uint64_t path_bytes;+ uint8_t lun;+ } units[BLOCK_MAX_UNITS];+ uint64_t nunits = 0;+memset(&block_shared, 0, sizeof(block_shared));+ block_tables();+ /* the logical units: the block devices that are not partitions of another */+ if (!EFI_ERROR(BS->locate_handle_buffer(ByProtocol, &blk_guid, NULL, &count, &handles))) {+ for (uint64_t i = 0; i < count && nunits < BLOCK_MAX_UNITS; i++) {+ efi_block_io *bio;+ efi_device_path *dp;++ if (EFI_ERROR(BS->handle_protocol(handles[i], &blk_guid, (void **)&bio)) || bio->media->logical ||+ bio->media->block_size == 0 || bio->media->block_size > BLOCK_BUFFER_SIZE ||+ EFI_ERROR(BS->handle_protocol(handles[i], &dp_guid, (void **)&dp))) {+ continue;+ }+ units[nunits].bio = bio;+ units[nunits].path = dp;+ units[nunits].path_bytes = device_path_bytes(dp);+ units[nunits].lun = device_path_print(nunits, dp);+ nunits++;+ }+ }if (EFI_ERROR(BS->locate_handle_buffer(ByProtocol, &part_guid, NULL, &count, &handles))) {print("ufs: no partition information: the block service is off\n");return;}- for (uint64_t i = 0; i < count && block_shared.parts < BLOCK_MAX_PARTS; i++) {+ for (uint64_t i = 0; i < count && block_shared.parts + nunits < BLOCK_MAX_PARTS; i++) {struct loader_block_part *bp = &block_shared.part[block_shared.parts];efi_partition_info *info;efi_block_io *bio;+ efi_device_path *dp;if (EFI_ERROR(BS->handle_protocol(handles[i], &part_guid, (void **)&info)) || info->type != 2 ||EFI_ERROR(BS->handle_protocol(handles[i], &blk_guid, (void **)&bio)) ||@@ -1476,12 +1611,43 @@ block_start(void)ufs_name(info, bp->name, sizeof(bp->name));bp->block_size = bio->media->block_size;bp->blocks = bio->media->last_block + 1;+ bp->start_lba = info->start_lba;+ bp->unit = 0xffff;+ bp->lun = 0xff;+ /* its unit: the one whose device path its own begins with */+ if (!EFI_ERROR(BS->handle_protocol(handles[i], &dp_guid, (void **)&dp))) {+ uint64_t bytes = device_path_bytes(dp);++ for (uint64_t u = 0; u < nunits; u++) {+ if (units[u].path_bytes < bytes &&+ memcmp(units[u].path, dp, units[u].path_bytes) == 0) {+ bp->unit = (uint16_t)u;+ bp->lun = units[u].lun;+ }+ }+ }block_bios[block_shared.parts++] = bio;if (block_probe_requested && bp->name[0] == 'd' && bp->name[1] == 'a' && bp->name[2] == 'r' &&bp->name[3] == 'w' && bp->name[4] == 'i' && bp->name[5] == 'n' && bp->name[6] == 0) {block_io2_probe(handles[i], bio);}}+ for (uint64_t u = 0; u < nunits; u++) {+ struct loader_block_part *bp = &block_shared.part[block_shared.parts];+ char *n = bp->name;++ n[0] = 'u', n[1] = 'n', n[2] = 'i', n[3] = 't';+ n[4] = (char)('0' + u / 10 % 10), n[5] = (char)('0' + u % 10), n[6] = 0;+ if (u < 10) {+ n[4] = n[5], n[5] = 0;+ }+ bp->block_size = units[u].bio->media->block_size;+ bp->blocks = units[u].bio->media->last_block + 1;+ bp->unit = (uint16_t)u;+ bp->lun = units[u].lun;+ bp->flags = BLOCK_PART_UNIT;+ block_bios[block_shared.parts++] = units[u].bio;+ }block_shared.magic = BLOCK_MAGIC;block_shared.version = BLOCK_VERSION;block_shared.size = sizeof(block_shared);@@ -1489,8 +1655,9 @@ block_start(void)block_shared.buffer_pa = (uint64_t)(uintptr_t)block_buffer;clean_dcache((uint64_t)(uintptr_t)&block_shared, (uint64_t)(uintptr_t)&block_shared + sizeof(block_shared));block_enabled = 1;- print("ufs: block service: %d partitions, page %x, buffer %x of %d KB\n", (uint64_t)block_shared.parts,- (uint64_t)(uintptr_t)&block_shared, block_shared.buffer_pa, (uint64_t)(BLOCK_BUFFER_SIZE >> 10));+ print("ufs: block service: %d partitions and %d units, page %x, buffer %x of %d KB\n",+ (uint64_t)block_shared.parts - nunits, nunits, (uint64_t)(uintptr_t)&block_shared, block_shared.buffer_pa,+ (uint64_t)(BLOCK_BUFFER_SIZE >> 10));}/*