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

air: carry the ir3 rounding fix, and measure the Adreno before and after

vcvkk150a08595cc8
diff --git a/README.md b/README.md
index 0dc9154..40d1294 100644
--- a/README.md
+++ b/README.md
@@ -545,19 +545,26 @@ P3 поверхности кадров копировались, и этого
по одной против эталона вне этого дерева, 71 из них совпадает с функциями C на каждом из 45 652 случаев,
47 — ещё и когда их **исполняет** softpipe, а не складывает оптимизатор (2 586 случаев), 10 атомиков и
барьер — на написанных для них ядрах, 13 текстурных операций — точно, по нескольким текселям каждая.
-**И все 78 прогнаны на самом Adreno телефона** (`logs/090218-run.log`, 20 октября): из 71 точно
-определённой операции **56 совпадают с C на каждом из 714 случаев, 5 расходятся, а 10 отложены** —
-и все пять расходящихся это преобразования целого в float: `air.convert.f.{f32,v2f32,v3f32}.u.*`,
+**И все 78 прогнаны на самом Adreno телефона**, причём дважды: как порт стоял, и с однострочной
+починкой округления в `ir3`, которую это дерево теперь несёт (`tools/mesa/ir3-round-default.patch`).
+
+| прогон | совпадают | расходятся | отложены | случаев |
+| --- | --- | --- | --- | --- |
+| как порт стоял (`logs/090218-run.log`) | 56 | **5** | 10 | 714 |
+| с починкой (`logs/090918-run.log`) | **61** | **0** | 10 | 714 |
+
+Все пять расходившихся — преобразования целого в float: `air.convert.f.{f32,v2f32,v3f32}.u.*`,
а после того как пул научился спрашивать про середины, ещё и знаковые
-`air.convert.f.{f32,v2f32}.s.*`, то есть `i2f` усекает так же, как `u2f`.
-
-Отложенные десять возвращают `half`, и проверить их прогоном `air_run` нельзя: он читает результат
-через 32-битный таргет, 16-битного у него нет вовсе, поэтому половина сразу расширяется, NIR
-сворачивает преобразование в 32-битное, и эталон описывает операцию, которой шейдер не выполняет.
-Раньше здесь стояло «66 совпадают на 808 случаях» и отдельно — что все 24 узких объявления прошли
-на Adreno и совпали; это было неверно ровно на эти десять, и неверно в той части, которая и была
-интересна. Из узких типов `i1`, `i8` и `i16` действительно прошли и совпали, а `f16` не спрашивали.
-56 + 5 + 10 = 71, счёт сходится.
+`air.convert.f.{f32,v2f32}.s.*`, то есть `i2f` усекает так же, как `u2f`. С починкой сходятся все
+пять, и больше ничего не сдвинулось — то есть починка чинит ровно то, что было неверно.
+
+Отложенные десять возвращают `half`, и проверить их прогоном `air_run` нельзя ни до, ни после: он
+читает результат через 32-битный таргет, 16-битного у него нет вовсе, поэтому половина сразу
+расширяется, NIR сворачивает преобразование в 32-битное, и эталон описывает операцию, которой шейдер
+не выполняет. Раньше здесь стояло «66 совпадают на 808 случаях» и отдельно — что все 24 узких
+объявления прошли на Adreno и совпали; это было неверно ровно на эти десять, и неверно в той части,
+которая и была интересна. Из узких типов `i1`, `i8` и `i16` действительно прошли и совпали, а `f16`
+не спрашивали. 61 + 0 + 10 = 71, счёт сходится.
Эти 3 — единственное за всю работу, что нельзя было найти на хосте никаким движением, и ровно за этим
набор и ехал на телефон: **Adreno усекает `u32 → f32` там, где C, NIR и softpipe округляют.**
diff --git a/docs/air.md b/docs/air.md
index 3056a17..0d0d9cd 100644
--- a/docs/air.md
+++ b/docs/air.md
@@ -33,8 +33,8 @@ And of the 119 distinct `air.*` operations those modules call (`tools/air/intrin
| of those, exactly defined and agreeing on every case (45 652 cases) | 71 |
| of those, approximate, so measured against libm and nothing concluded | 7 |
| of those, also *run* by a Gallium driver rather than folded (softpipe, 2 586 cases) | 47 |
-| of those, run **on the phone's own Adreno** (714 cases) and agreeing there | 56 |
-| of those, **disagreeing on the Adreno** where every host engine agrees | 5 |
+| of those, run **on the phone's own Adreno** (714 cases) and agreeing there | 61 |
+| of those, disagreeing before the `ir3` rounding fix this port now carries (0 after) | 5 |
| of those, set aside: they return `half`, which `air_run` cannot read back | 10 |
| the atomics and the barrier, against kernels written for them (`atomiccheck.py`) | 10 |
| texture operations verified exactly, on several texels each (`texopcheck.py`) | 13 |
@@ -55,13 +55,22 @@ functions and not entry points at all.
invisible to all 48 238 of those cases, and the 24 narrow-type declarations softpipe cannot run
at all are exactly the ones where ir3 differs most from it.
- On 20 October that stopped being true. All 78 declarations ran on the phone's own Adreno
- (`logs/090218-run.log`, section 4 item 4): **56 of the 71 exactly-defined ones agree with C on
- every one of 714 cases, 5 disagree, and 10 are set aside** — and the 5 are the whole point of
- having gone there, because every engine on this machine agrees with C about them. All five are
- integer-to-float conversions: `air.convert.f.{f32,v2f32,v3f32}.u.*` and, once the pool was
- sharpened to ask, `air.convert.f.{f32,v2f32}.s.*` as well — `i2f` truncates exactly as `u2f`
- does, which the earlier pool had no value to notice.
+ On 20 October that stopped being true. All 78 declarations ran on the phone's own Adreno, and
+ twice: once as the port stood, and once with the one-line `ir3` rounding fix this tree now
+ carries (`tools/mesa/ir3-round-default.patch`).
+
+ | | agree | differ | set aside | cases |
+ | --- | --- | --- | --- | --- |
+ | as the port stood (`logs/090218-run.log`) | 56 | **5** | 10 | 714 |
+ | with the rounding fix (`logs/090918-run.log`) | **61** | **0** | 10 | 714 |
+
+ The 5 were the whole point of having gone there, because every engine on this machine agrees
+ with C about them. All five are integer-to-float conversions:
+ `air.convert.f.{f32,v2f32,v3f32}.u.*` and, once the pool was sharpened to ask,
+ `air.convert.f.{f32,v2f32}.s.*` as well — `i2f` truncates exactly as `u2f` does, which the
+ earlier pool had no value to notice. With the fix all five agree and nothing else moved, which is
+ the useful shape of an after-measurement: the thing that was wrong is right, and nothing that was
+ right has changed.
**An earlier version of this paragraph said 66 agree on 808 cases, and that was 10 declarations
too many.** It also said the 24 narrow-type declarations softpipe cannot run had all run on the
diff --git a/tools/mesa/ir3-round-default.patch b/tools/mesa/ir3-round-default.patch
new file mode 100644
index 0000000..28c9a19
--- /dev/null
+++ b/tools/mesa/ir3-round-default.patch
@@ -0,0 +1,65 @@
+ir3: round integer-to-float conversions to nearest when nothing says otherwise.
+
+The a6xx `cov` instruction has a rounding-mode field, and create_cov() sets it
+only from float_controls_execution_mode, which is a SPIR-V declaration. When
+nothing is declared, nir_get_rounding_mode_from_float_controls returns
+nir_rounding_mode_undef, neither branch fires, and the field keeps the zero it
+was built with -- ROUND_ZERO in instr-a3xx.h, which is truncation toward zero.
+
+So every shader that does not come from SPIR-V with an explicit rounding mode
+gets truncation where IEEE-754, GLSL and OpenCL all require round-to-nearest-even.
+On this port that is every shader: the port's OpenGL ES declares nothing, and so
+does the AIR frontend. The hardware is not at fault -- it can round, and setting
+the field makes it.
+
+Measured on the phone's Adreno 7c+ Gen 3, uint -> float, GLSL ES 3.0 through
+OSMesa with the value in a uniform so nothing could be folded on the host
+(userland/src/u2f_test.c, RC=rc.u2f), expectations from C on the host:
+
+ input before after C
+ 0xFFFFFFFF 4294967040 4294967296 4294967296
+ 0xFFFFFF80 4294967040 4294967296 4294967296
+ 0x01000001 16777216 16777216 16777216
+ 0x01000003 16777218 16777220 16777220
+ 0x7FFFFFFF 2147483520 2147483648 2147483648
+ 0x00FFFFFF 16777215 16777215 16777215
+
+0x01000003 is the value that identifies the rule rather than merely showing a
+disagreement: it is 2^24+3, half way between the representable 2^24+2 and
+2^24+4, and both round-half-to-even and round-half-away-from-zero give 2^24+4.
+The hardware gave 2^24+2, which is neither -- it is the low bits dropped. The
+two inputs that agree before the change are exactly the two where truncation and
+rounding coincide, so agreement there is the absence of a question.
+
+Reproduced independently down a second path with no GLSL in it at all: the AIR
+frontend's own test suite (tools/air/intrincheck.py, docs/air.md section 4)
+compiles one Metal operation per module and executes it on the same GPU, and
+air.convert.f.{f32,v2f32,v3f32}.{u,s}.* disagree with C on exactly the inputs
+that need rounding -- 5 declarations, and i2f truncates just as u2f does. Two
+unrelated front ends reaching the same instruction return the same wrong number.
+
+Not verified: whether the same field is honoured for a 16-bit destination. That
+branch covers TYPE_F16 as well, but this port's harness cannot read a half back
+(air_run has no 16-bit render target), so the ten half-returning declarations of
+the corpus are set aside rather than claimed either way.
+
+The block is byte-identical in Mesa 26.2.5, the newest release at the time of
+writing, checked by extracting that one file from archive.mesa3d.org, so this is
+not an artefact of the 25.0.7 this port pins. Worth sending upstream.
+
+--- a/src/freedreno/ir3/ir3_compiler_nir.c
++++ b/src/freedreno/ir3/ir3_compiler_nir.c
+@@ -408,6 +408,13 @@
+ set_cat1_round(cov.rpts, nrpt, ROUND_EVEN);
+ else if (rounding_mode == nir_rounding_mode_rtz)
+ set_cat1_round(cov.rpts, nrpt, ROUND_ZERO);
++ else
++ /* Nothing declared a mode, and the field defaults to ROUND_ZERO,
++ * which is truncation. IEEE-754, GLSL and OpenCL all require
++ * round-to-nearest-even here, so ask for it rather than letting the
++ * hardware's own default stand.
++ */
++ set_cat1_round(cov.rpts, nrpt, ROUND_EVEN);
+ }
+
+ return cov;