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: the cause is ir3, not the a6xx instruction, and I had it wrong

vcvkk8c69f16c9264
diff --git a/README.md b/README.md
index 2c78aba..be12b39 100644
--- a/README.md
+++ b/README.md
@@ -542,7 +542,7 @@ P3 поверхности кадров копировались, и этого
(`AGXCompilerCore`, 137 строк-суффиксов), а не угадан — так нашлась и одна ошибка в наших догадках.
Операции проверены численно — на хосте: из 119 разных `air.*`, что встречаются в корпусе, 78 прогнаны
-по одной против эталона вне этого дерева, 71 из них совпадает с функциями C на каждом из 45 607 случаев,
+по одной против эталона вне этого дерева, 71 из них совпадает с функциями C на каждом из 45 652 случаев,
47 — ещё и когда их **исполняет** softpipe, а не складывает оптимизатор (2 586 случаев), 10 атомиков и
барьер — на написанных для них ядрах, 13 текстурных операций — точно, по нескольким текселям каждая.
**И все 78 прогнаны на самом Adreno телефона** (`logs/084315-run.log`, 20 октября): из 71 точно
@@ -561,8 +561,15 @@ P3 поверхности кадров копировались, и этого
математику). Наш фронтенд при этом выдаёт правильный опкод `nir_u2f32`, а ir3 превращает его в
одиночную `cov.u32f32` без доводки — машинный код модуля это пять инструкций, четыре из них `cov`,
и между загрузкой и преобразованием ничего. То есть виноваты не мы и не понижение в ir3, а сама
-инструкция a6xx; **кто должен это компенсировать — не установлено**, для этого нужна документация на
-ISA a6xx, которой здесь нет. Предсказание, которое из этого следовало, **проверено и сбылось**: `bin/u2f_test` (`src/u2f_test.c`,
+инструкция a6xx — **и это было неверно**. У инструкции `cov` есть поле режима округления
+(`ROUND_ZERO = 0`, `ROUND_EVEN = 1`), и ir3 ставит его для назначения F16/F32 из
+`float_controls_execution_mode`, то есть из объявления SPIR-V; когда не объявлено ничего,
+`nir_get_rounding_mode_from_float_controls` возвращает `undef`, ни одна ветка не срабатывает, и поле
+остаётся нулём — то есть усечением. **Железо умеет округлять; ir3 спрашивает режим только у того, кто
+его объявил, и не ставит умолчания, которого требуют IEEE-754 и GLSL.** Поэтому оба пути, GLES и AIR,
+и дают одно и то же неверное число. Починка — одна строка, и, в отличие от бага с `ir3_cmdline`, этот
+файл Mesa сохраняет, а воспроизведение есть с двух независимых сторон: это первое за всю работу, что
+можно отправить вверх. Предсказание, которое из этого следовало, **проверено и сбылось**: `bin/u2f_test` (`src/u2f_test.c`,
`RC=rc.u2f`) спрашивает то же самое у GLSL ES 3.0 через ту же Mesa и тот же ir3, мимо AIR целиком, —
значение идёт униформой, чтобы его нечего было свернуть на хосте, а ответ возвращается четырьмя
байтами через RGBA8, чтобы биты были точными. На `freedreno; Adreno 7c+ Gen 3; OpenGL ES 3.2 Mesa
diff --git a/docs/air.md b/docs/air.md
index c751a6f..ec3cf34 100644
--- a/docs/air.md
+++ b/docs/air.md
@@ -30,7 +30,7 @@ And of the 119 distinct `air.*` operations those modules call (`tools/air/intrin
| | of 119 |
| --- | --- |
| checked numerically, one operation at a time, against a reference outside this tree | 78 |
-| of those, exactly defined and agreeing on every case (45 607 cases) | 71 |
+| 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** (808 cases) and agreeing there | 66 |
@@ -47,11 +47,11 @@ functions and not entry points at all.
- **The arithmetic operations are checked; two of them have now been checked against the
Adreno, and the other 76 have not.** 71 of the corpus's declarations agree with C's own
- functions on every one of 45 607 cases, and 47 of them agree again when *executed* by softpipe
+ functions on every one of 45 652 cases, and 47 of them agree again when *executed* by softpipe
instead of folded — which is a real answer to what used to be the largest hole here (section 4,
item 4), and found three bugs getting there. But those two engines are both on an x86 host. An
opcode whose Adreno instruction differs from what `nir_opt_constant_folding` and TGSI compute is
- invisible to all 48 193 of those cases, and the 24 narrow-type declarations softpipe cannot run
+ 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
@@ -115,6 +115,33 @@ functions and not entry points at all.
float by truncating, the window server's drawing included**, and this frontend is not party to
it: it is physically absent from that test.
+ **The cause is ir3 and not the a6xx instruction, and an earlier draft of this section had that
+ wrong.** It said inspection had eliminated two of three culprits and the remaining one was the
+ hardware. The steps were right and the conclusion was not: `create_cov` ends with a rounding
+ field that the reading stopped short of. `cov` *has* a rounding mode — `ROUND_ZERO = 0`,
+ `ROUND_EVEN = 1` in `instr-a3xx.h` — and `ir3_compiler_nir.c` sets it for a destination of
+ `TYPE_F16` or `TYPE_F32` from `float_controls_execution_mode`, which is a SPIR-V declaration.
+ `nir_get_rounding_mode_from_float_controls` returns `nir_rounding_mode_undef` when nothing is
+ declared, so neither branch fires and the field keeps its zero, which is truncation. GLSL ES
+ declares nothing and this frontend declares nothing, which is exactly why two independent paths
+ returned the same wrong number. **The hardware can round; ir3 only asks when someone else has
+ asked first, and supplies no default where IEEE-754 and GLSL both require round-to-nearest.**
+ The fix is one line, and unlike the `ir3_cmdline` bug this one is in a file upstream still
+ carries, with reproduction down two independent paths — so it is the first thing in this work
+ that can actually be reported. A peer session is testing the one-line change in its own build.
+
+ **The same branch covers `TYPE_F16`, and that half of it this suite was not asking about.** The
+ corpus has four integer-to-half conversions — `air.convert.f.f16.{s.i32,u.i16,u.i32,u.i8}` —
+ and all four agreed on the Adreno. The agreement was empty: the pool gave them only values that
+ overflow `f16`, so their expectations read `[0, inf, inf, inf]`, which tests saturation and says
+ nothing whatever about rounding. In `f16` integers are exact to 2048 and spaced by 2 above it, so
+ **2051** is the discriminator — between 2050 and 2052 with an odd lower neighbour, where
+ round-to-nearest-even gives 2052 and truncation gives 2050 — and 2049 is carried beside it as a
+ midpoint where both rules agree, to show that a midpoint is not automatically a test. The pool now
+ interleaves the two precisions so `--cases 4` reaches a discriminator for each. The prediction,
+ untested at the time of writing: these four must currently return 2050, and the one-line fix above
+ must turn them into 2052.
+
**Which rule it is, as against merely "not round-to-nearest", is settled by one value.**
`0x01000003` is 2²⁴+3, half way between the representable 2²⁴+2 and 2²⁴+4; round-half-to-even and
round-half-away-from-zero both give 2²⁴+4, and the GPU gives 2²⁴+2. That is truncation and nothing
@@ -543,7 +570,7 @@ Three references, each independent of the translator:
--eval`. The reference is the C library's own `roundf`, `floorf`, `fmaxf`, `ldexpf` and the
IEEE definitions, evaluated at the operation's own precision.
- **71 exactly defined operations agree on every one of 45 607 cases; none differ.** Seven are
+ **71 exactly defined operations agree on every one of 45 652 cases; none differ.** Seven are
approximate (`fast_sin`, `fast_cos`, `fast_exp`, `fast_pow`, `fast_atan2`) and are reported
with their worst distance from libm and counted as nothing — see below.
diff --git a/tools/air/intrincheck.py b/tools/air/intrincheck.py
index f329240..947c03c 100755
--- a/tools/air/intrincheck.py
+++ b/tools/air/intrincheck.py
@@ -810,8 +810,23 @@ FEW_INTS = [0, 1, -1, 7, -32768, 32767, 2147483647, -2147483648]
# First in the list are the ones that decide a rule, because --cases N keeps the
# first N: the suite carried to the phone used 4, which took [0, 1, -1, 7] and
# so never asked about a midpoint at all.
-CONV_INTS = [0, -1, 16777217, 16777219, 2147483647, 16777215, 1, 7,
- -32768, 32767, -2147483648]
+# A half destination needs its own midpoints, and for the same reason one level
+# down: f16 holds integers exactly only to 2048, above which the spacing is 2.
+# 2051 half way between 2050 and 2052, whose lower neighbour is odd, so
+# round-to-nearest-even gives 2052 and truncation gives 2050 -- the f16
+# discriminator, the counterpart of 16777219
+# 2049 half way between 2048 and 2050, where both rules give 2048: carried to
+# show that a midpoint is not automatically a test
+# 2048 the last integer f16 holds exactly
+# Without these the four half-destination declarations of the corpus were asked
+# only about values that overflow f16, and answered inf to all of them: the
+# expectations read [0, inf, inf, inf], which tests saturation and says nothing
+# whatever about rounding. They agreed on the Adreno and that agreement was
+# empty. The order interleaves the two precisions so that --cases 4 reaches a
+# discriminator for each: 0 for sanity, -1 for a whole-ulp f32 difference,
+# 16777219 for the f32 rule, 2051 for the f16 rule.
+CONV_INTS = [0, -1, 16777219, 2051, 16777217, 2049, 2048, 16777215,
+ 2147483647, 1, 7, -32768, 32767, -2147483648]
FEW_INTS2 = [1, -1, 0, 7]
FEW_DOT = [0.0, 1.0, -1.0, 2.0, -4.0, 0.5, -0.25, 8.0]
@@ -844,7 +859,7 @@ def pool_for_full(ty, family):
# and widening it would grow the whole exhaustive grid for one question
# that belongs to one family.
if family == "convert" and bty == "i32":
- return INTS + [16777215, 16777217, 16777219]
+ return INTS + [16777215, 16777217, 16777219, 2048, 2049, 2051]
return INTS
return DOT_FLOATS if family == "dot" else FLOATS