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

255 Apple shaders draw and the pixel matches, so M1 is done but for the Adreno itself

vcvkk3f7b3b54d56f
diff --git a/docs/air.md b/docs/air.md
index 858ecf5..09bbd63 100644
--- a/docs/air.md
+++ b/docs/air.md
@@ -309,12 +309,22 @@ Three references, each independent of the translator:
AppleMetalGLRenderer, all of them the texture ones), and a compute kernel, which returns
nothing and writes through pointers (47 of them). Reading the buffers back after the call
would settle the kernels and is M4's acceptance test; it is not written.
-2. **The same shader through our NIR on two different Mesa backends.** `air-run` renders (or
- dispatches) the translated NIR with Gallium: on the host through softpipe (NIR → TGSI →
- an interpreter in C), on the phone through freedreno/ir3 on the Adreno. Both outputs are
- compared numerically to (1), per pixel or per buffer element, against a tolerance stated per
- comparison (exact for integer results; a few ULP for arithmetic; looser only where Metal's own
- `fast_` functions allow it, and then it is printed).
+2. **The same shader drawn by a Gallium driver, and the pixel read back.** `air_run.c` puts the
+ translated NIR into a `pipe_shader_state` as `PIPE_SHADER_IR_NIR`, draws one quad into a
+ 32-bit render target and prints the pixel. Both drivers of interest take NIR directly: ir3 is
+ a NIR compiler, and softpipe takes it through `nir_to_tgsi`.
+
+ **255 shaders draw and the pixel matches LLVM, bit for bit, with no GPU** — `cpuref.py --all
+ --draw` compares all three (LLVM's execution, the folded NIR, the drawn pixel). That is M1's
+ acceptance test, run 255 times, with softpipe standing in for the Adreno.
+
+ Three things this caught that compiling never would, each of which looks like a translation
+ bug and is not one: an integer-returning shader read back through a float target (the bits are
+ right, read the wrong way); a shader whose outputs outnumber the framebuffer's attachments,
+ which draws nothing at all; and `clearFragment04`, which writes `FRAG_RESULT_DATA1` alone, so
+ target 0 holds the clear colour. The harness now takes its format from the shader's output
+ type, binds an attachment per render target, and reads back the lowest target the shader
+ actually writes.
3. **NIR's own checks:** `nir_validate` after every pass (the translator runs with validation
on), and unit tests on Mesa's `nir_tests` framework for the translator's building blocks.
@@ -367,15 +377,17 @@ an unhandled metadata key), so "features not yet handled" is a ranked list, not
`llvm-dis` on every one.
- **M1** — `clearFragment01` reaches *adreno*: translated, compiled by ir3, rendered on the
Adreno, framebuffer equal to the colour in its constant buffer.
- **Compiled and checked against LLVM, not yet run on the GPU.** It is `nir_load_ubo` + a store
- to `FRAG_RESULT_DATA0` as predicted, and ir3 turns it into five Adreno instructions (four
- `mov`s out of the constant file, where ir3 promoted the UBO load). Over a buffer of known
- bytes, LLVM's own execution of the module and our folded NIR give the same four floats, bit for
- bit. The framebuffer half of the test — ir3's code actually running on the Adreno and the
- colour read back — needs the phone and has not been done.
+ **Done except for the Adreno itself.** It is `nir_load_ubo` + a store to `FRAG_RESULT_DATA0`
+ as predicted, and ir3 turns it into five Adreno instructions (four `mov`s out of the constant
+ file, where ir3 promoted the UBO load). Over a buffer of known bytes, LLVM's own execution of
+ the module, our folded NIR, and **the pixel drawn by a Gallium driver and read back** all give
+ the same four floats, bit for bit. What has not happened is the draw going through *ir3 on the
+ phone's GPU*: the screen here is softpipe. Section 5a says what is left for that, and it is
+ not much.
- **M2** — the 283 modules with no `air.*` call: a stated fraction reach *ir3*, a growing subset
*softpipe*/*adreno*.
- **262 of the 283 reach ir3**, and 255 of them agree with LLVM numerically. The other 21 are
+ **262 of the 283 reach ir3**, 255 of them agree with LLVM numerically, and those same 255 draw
+ a matching pixel. The other 21 are
`air.visible` library functions, which are not entry points at all (below). Counting every
entry point rather than every module: 275 of 321, 86%. Nothing has run on the Adreno.
- **M3** — textures and samplers, each form with a test that renders a known image.
@@ -397,6 +409,29 @@ pipeline time (`nir_link_shader_functions`). The translator refuses them with
failures. 21 of them call no `air.*` at all, which is why the intrinsic-free count (283) and the
M2 count (262) differ.
+### 5a. Is there a path from a `nir_shader` to a draw on the phone? Yes.
+
+This was the open question, because nothing here had run. The answer is that the harness can ride
+the Mesa already on the phone rather than being built from nothing:
+
+- The port's Mesa **already creates a Gallium screen for the Adreno**:
+ `osmesa_create_gpu_screen()` in `tools/mesa/freedreno-darwin.patch` opens the kernel's `msm`
+ driver through `tools/mesa/redwood-drm` and calls `fd_drm_screen_create_renderonly()`. It also
+ already has `osmesa_surface_resource()`, which wraps an IOSurface as a `pipe_resource`. So the
+ Gallium layer is reachable inside the library CoreAnimation already draws iOS through.
+- **freedreno takes NIR natively** (`PIPE_SHADER_CAP_SUPPORTED_IRS` includes
+ `PIPE_SHADER_IR_NIR`; `ir3_gallium.c` handles `cso->ir_type == PIPE_SHADER_IR_NIR`), so nothing
+ has to go through GLSL on the way.
+- `air_run.c` is written against that interface and nothing else. Here it asks for a software
+ screen (`sw_screen_create(null_sw_create())`); on the phone it wants the screen
+ `osmesa_create_gpu_screen()` makes, and **no line below that changes**.
+
+What is left to do on the phone is therefore small and known: export that screen from the port's
+Mesa (one function, beside the `osmesa_surface_resource` the patch already exports), cross-build
+`air_run.c` with `userland/build.sh`, and run it. What is *not* known until it is tried is
+whether the kernel's GPU driver and the submit path behave for a draw that does not come from
+CoreAnimation; the GLES path is the only consumer of that Mesa today.
+
## 6. Running it
```
@@ -413,7 +448,9 @@ build/mesa-host/build/src/compiler/air/air2nir --eval FILE[.metallib] [FUNCTION]
build/mesa-host/build/src/gallium/drivers/freedreno/ir3_compiler \
--chip-id 0x007506030500 FILE[.metallib] [FUNCTION] # Adreno code
tools/air/cpuref.py --compare FILE[.metallib] [FUNCTION] # ours against LLVM's own answer
-tools/air/cpuref.py --all FILE.metallib # every function of a library
+tools/air/cpuref.py --all --draw FILE.metallib # every function: LLVM, folded, drawn
+build/mesa-host/build/src/gallium/drivers/freedreno/air_run \
+ FILE[.metallib] [FUNCTION] # draw with it, print the pixel
```
`0x007506030500` is how freedreno names the redwood's Adreno 7c+ Gen 3 (A635); it has no
diff --git a/tools/air/check.sh b/tools/air/check.sh
index a823257..d906e58 100755
--- a/tools/air/check.sh
+++ b/tools/air/check.sh
@@ -53,16 +53,19 @@ else
fi
echo
-echo "== against LLVM on the processor, shader by shader"
+echo "== against LLVM on the processor, and drawn, shader by shader"
# The strongest check there is, and it needs no GPU: LLVM runs the same module
# over the same buffer bytes, our NIR is folded over them, and the numbers are
# compared. Only the class where this is decidable -- an entry point whose
# arguments are all buffers and which returns its result -- is counted; the
-# rest say why not. See tools/air/cpuref.py.
+# rest say why not. --draw also puts each one through a Gallium driver and
+# compares the pixel that comes back, which is M1's acceptance test with
+# softpipe standing in for the Adreno. See tools/air/cpuref.py and air_run.c.
cpu_rc=0
for f in "${LIBS[@]}"; do
echo "$(basename "$(dirname "$f")")/$(basename "$f"):"
- python3 "$ROOT/tools/air/cpuref.py" --all "$f" 2>&1 | tail -2 | sed 's/^/ /' || cpu_rc=1
+ python3 "$ROOT/tools/air/cpuref.py" --all --draw "$f" 2>&1 | tail -3 | sed 's/^/ /' ||
+ cpu_rc=1
done
exit $((reader_rc | cpu_rc))
diff --git a/tools/air/cpuref.py b/tools/air/cpuref.py
index a6d8abe..541b137 100755
--- a/tools/air/cpuref.py
+++ b/tools/air/cpuref.py
@@ -38,6 +38,9 @@ import metallib # noqa: E402
AIR2NIR = os.environ.get(
"AIR2NIR", os.path.join(ROOT, "build/mesa-host/build/src/compiler/air/air2nir"))
+AIR_RUN = os.environ.get(
+ "AIR_RUN",
+ os.path.join(ROOT, "build/mesa-host/build/src/gallium/drivers/freedreno/air_run"))
# The pattern every buffer is filled with. Arbitrary, but fixed and not all
# zeros: a shader that ignores its input and one that reads it must differ.
@@ -295,6 +298,8 @@ def main():
help="every function of the file, comparing each")
ap.add_argument("--tolerance", type=float, default=0.0,
help="relative difference allowed (default: none, bit-exact)")
+ ap.add_argument("--draw", action="store_true",
+ help="also draw with it (air_run) and compare the pixel")
args = ap.parse_args()
if args.all:
return run_all(args)
@@ -349,6 +354,24 @@ def main():
return 0
+def draw_ours(path, function):
+ """air_run: the same shader drawn by a Gallium driver, pixel read back."""
+ out = subprocess.run([AIR_RUN, path, function], capture_output=True, text=True)
+ if out.returncode:
+ return None, (out.stderr or out.stdout).strip().splitlines()[-1][:160] \
+ if (out.stderr or out.stdout).strip() else "air_run failed"
+ values, taking = [], False
+ for line in out.stdout.splitlines():
+ if line.startswith("air_run: the pixel"):
+ taking = True
+ continue
+ if taking and line.startswith(" "):
+ values.append(line.strip())
+ elif taking:
+ break
+ return (values, None) if values else (None, "air_run printed no pixel")
+
+
def evaluate_ours(path, function):
"""air2nir --eval: the same shader folded over the same buffer bytes."""
out = subprocess.run([AIR2NIR, "--eval", path, function],
@@ -388,7 +411,7 @@ def compare(theirs, ours, tol):
def run_all(args):
"""Every function of a .metallib, with a count at the end."""
b, header, funcs = metallib.parse(args.file)
- agree = differ = skipped = with_air = 0
+ agree = differ = skipped = with_air = drawn = not_drawn = 0
for f in funcs:
name = f.get("name")
if not name:
@@ -417,6 +440,22 @@ def run_all(args):
skipped += 1
continue
bad = compare(theirs, ours, args.tolerance)
+ drawn_note = ""
+ if not bad and args.draw:
+ pixel, why = draw_ours(args.file, name)
+ if why:
+ drawn_note = " (not drawn: %s)" % why
+ not_drawn += 1
+ else:
+ # the pixel is render target 0, which is the result's first
+ # field for every shader of this corpus
+ dbad = compare(theirs[:len(pixel)], pixel, args.tolerance)
+ if dbad:
+ print("DRAWN DIFFERS %-38s %s" % (name, dbad))
+ differ += 1
+ continue
+ drawn += 1
+ drawn_note = " drawn and matching"
if bad:
print("DIFFER %-44s %s" % (name, bad))
differ += 1
@@ -424,7 +463,7 @@ def run_all(args):
agree += 1
if calls_air(b, header, f):
with_air += 1
- print("agree %-44s %s" % (name, " ".join(theirs[:4])))
+ print("agree %-44s %s%s" % (name, " ".join(theirs[:4]), drawn_note))
print("\ncpuref: %d agree with LLVM, %d differ, %d could not be compared (of %d)"
% (agree, differ, skipped, len(funcs)))
# Which part of the frontend this actually exercised. A shader that calls
@@ -433,6 +472,9 @@ def run_all(args):
print("cpuref: of the %d that agree, %d call an air.* function; %d are plain LLVM IR, "
"so they test the reader, the interface and the instructions but no intrinsic"
% (agree, with_air, agree - with_air))
+ if args.draw:
+ print("cpuref: %d of them were also DRAWN by a Gallium driver and the pixel matched; "
+ "%d could not be drawn" % (drawn, not_drawn))
return 1 if differ else 0
diff --git a/tools/air/mk-host.sh b/tools/air/mk-host.sh
index 35b7711..70725cd 100755
--- a/tools/air/mk-host.sh
+++ b/tools/air/mk-host.sh
@@ -14,6 +14,7 @@
# What comes out, in build/mesa-host/build:
# src/compiler/air/air2nir the frontend alone
# src/gallium/drivers/freedreno/ir3_compiler AIR -> NIR -> Adreno
+# src/gallium/drivers/freedreno/air_run AIR -> NIR -> drawn, pixel read back
set -e
ROOT=$(cd "$(dirname "$(readlink -f "$0")")/../.." && pwd)
VERSION=25.0.7
@@ -94,7 +95,9 @@ export PATH=$B/venv/bin:$PATH
-Dexpat=disabled > meson-setup.log
ninja -C build src/compiler/air/air2nir \
- src/gallium/drivers/freedreno/ir3_compiler > ninja.log
+ src/gallium/drivers/freedreno/ir3_compiler \
+ src/gallium/drivers/freedreno/air_run > ninja.log
echo "mk-host.sh: $B/build/src/compiler/air/air2nir"
echo "mk-host.sh: $B/build/src/gallium/drivers/freedreno/ir3_compiler"
+echo "mk-host.sh: $B/build/src/gallium/drivers/freedreno/air_run"
diff --git a/tools/mesa/air-ir3.patch b/tools/mesa/air-ir3.patch
index f8a28ac..3a113f2 100644
--- a/tools/mesa/air-ir3.patch
+++ b/tools/mesa/air-ir3.patch
@@ -10,6 +10,10 @@ shows against AIR as it does against the others.
redwood's Adreno 7c+ Gen 3 (A635) has no gpu-id of its own: freedreno knows it
only as chip_id 0x007506030500.
+It also declares air_run here, next to ir3_compiler: air_run draws with a translated shader and
+reads the pixel back, and it needs libgallium, which meson has not defined yet where the rest of
+the frontend is read (src/compiler comes before src/gallium). Its source stays with the frontend.
+
Also removes this tool's own call of ir3_nir_lower_variant, which is a bug of
the tool: ir3_context_init already calls it on its clone of the NIR, and the
const-state setup inside asserts the second time. It shows on any shader whose
@@ -189,3 +193,25 @@ dimensions -- and hides on the rest, which is presumably why it survived.
idep_vtn,
idep_mesautil,
],
+@@ -318,6 +319,21 @@
+ install : false,
+ )
+
++# air_run: draw with a Metal shader and read the pixels back. It lives here,
++# beside ir3_compiler, because this is where libgallium exists; its source is
++# with the rest of the frontend in src/compiler/air.
++air_run = executable(
++ 'air_run',
++ files('../../../compiler/air/air_run.c'),
++ include_directories : [inc_include, inc_src, inc_mapi, inc_mesa, inc_gallium,
++ inc_gallium_aux, inc_gallium_winsys_sw,
++ include_directories('../../drivers')],
++ dependencies : [dep_m, idep_air, idep_mesautil, driver_softpipe],
++ link_with : [libgallium, libgalliumvl_stub, libws_null],
++ build_by_default : false,
++ install : false,
++)
++
+ gmemtool = executable(
+ 'gmemtool',
+ [
diff --git a/tools/mesa/air/air_run.c b/tools/mesa/air/air_run.c
new file mode 100644
index 0000000..c962324
--- /dev/null
+++ b/tools/mesa/air/air_run.c
@@ -0,0 +1,371 @@
+/*
+ * Copyright © 2026 Darwin on redwood contributors
+ * SPDX-License-Identifier: MIT
+ */
+
+/*
+ * air_run: draw with a Metal shader and read the pixels back.
+ *
+ * This is the half of M1 that compiling cannot give. The shader comes out of a
+ * .metallib, through air_to_nir, into a Gallium pipe_shader_state as
+ * PIPE_SHADER_IR_NIR -- which both drivers of interest accept natively: ir3
+ * is a NIR compiler, and softpipe takes NIR through nir_to_tgsi. One quad is
+ * drawn into a 32-bit-float render target and one pixel is printed, so the
+ * result is a number and not a picture.
+ *
+ * On this machine the screen is softpipe, so the whole path can be run with no
+ * GPU at all. On the phone the same source wants the freedreno screen that
+ * tools/mesa/freedreno-darwin.patch already creates inside the port's Mesa
+ * (osmesa_create_gpu_screen), and nothing else about it changes.
+ *
+ * usage: air_run FILE[.metallib] [FUNCTION]
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "nir.h"
+#include "nir_builder.h"
+#include "nir_air.h"
+#include "air_module.h"
+
+#include "pipe/p_context.h"
+#include "pipe/p_defines.h"
+#include "pipe/p_screen.h"
+#include "pipe/p_shader_tokens.h"
+#include "pipe/p_state.h"
+#include "target-helpers/inline_sw_helper.h"
+#include "null/null_sw_winsys.h"
+#include "util/format/u_format.h"
+#include "util/u_inlines.h"
+#include "util/u_memory.h"
+
+#define WIDTH 4
+#define HEIGHT 4
+
+/* the pattern cpuref.py and air2nir --eval fill their buffers with, so that
+ * all three agree on what the shader was given
+ */
+static uint8_t
+pattern_byte(unsigned i)
+{
+ return (i * 7 + 13) & 0xff;
+}
+
+/* A vertex shader for the quad: it takes the position as attribute 0 and
+ * passes it through. Written here rather than translated, because what is
+ * under test is the fragment shader; when the .metallib has a vertex shader of
+ * its own that is a separate run.
+ */
+static nir_shader *
+quad_vertex_shader(const nir_shader_compiler_options *options)
+{
+ nir_builder b = nir_builder_init_simple_shader(MESA_SHADER_VERTEX, options, "quad");
+ nir_variable *in = nir_variable_create(b.shader, nir_var_shader_in,
+ glsl_vec4_type(), "pos_in");
+ in->data.location = VERT_ATTRIB_GENERIC0;
+ in->data.driver_location = 0;
+ nir_variable *out = nir_variable_create(b.shader, nir_var_shader_out,
+ glsl_vec4_type(), "pos_out");
+ out->data.location = VARYING_SLOT_POS;
+ out->data.driver_location = 0;
+ nir_store_var(&b, out, nir_load_var(&b, in), 0xf);
+ b.shader->num_inputs = 1;
+ b.shader->num_outputs = 1;
+ return b.shader;
+}
+
+/* What a Gallium driver expects of a shader it is handed: NIR's own system
+ * values lowered to the hardware's, and I/O as intrinsics rather than
+ * variables. The same three passes are in tools/mesa/air-ir3.patch; when a
+ * fourth place needs them they should become one function of the frontend.
+ */
+static int
+type_size_vec4(const struct glsl_type *type, bool bindless)
+{
+ return glsl_count_attribute_slots(type, false);
+}
+
+static void
+finalize_for_gallium(nir_shader *nir)
+{
+ NIR_PASS(_, nir, nir_lower_system_values);
+ NIR_PASS(_, nir, nir_lower_compute_system_values, NULL);
+ NIR_PASS(_, nir, nir_lower_io, nir_var_shader_in | nir_var_shader_out,
+ type_size_vec4, 0);
+}
+
+int
+main(int argc, char **argv)
+{
+ if (argc < 2) {
+ fprintf(stderr, "usage: air_run FILE[.metallib] [FUNCTION]\n");
+ return 2;
+ }
+
+ glsl_type_singleton_init_or_ref();
+ void *ctx = ralloc_context(NULL);
+
+ /* the module */
+ FILE *f = fopen(argv[1], "rb");
+ if (!f) {
+ perror(argv[1]);
+ return 1;
+ }
+ fseek(f, 0, SEEK_END);
+ size_t size = ftell(f);
+ fseek(f, 0, SEEK_SET);
+ void *data = ralloc_size(ctx, size);
+ if (fread(data, 1, size, f) != size) {
+ fprintf(stderr, "air_run: short read of %s\n", argv[1]);
+ return 1;
+ }
+ fclose(f);
+
+ const void *bitcode = data;
+ size_t bitcode_size = size;
+ const char *want = argc > 2 ? argv[2] : NULL;
+ const char *name = argv[1];
+ if (size >= 4 && !memcmp(data, "MTLB", 4)) {
+ struct air_metallib lib;
+ const char *err;
+ if (!air_metallib_parse(ctx, data, size, &lib, &err)) {
+ fprintf(stderr, "air_run: %s: %s\n", argv[1], err);
+ return 1;
+ }
+ unsigned pick = lib.num_functions;
+ for (unsigned i = 0; i < lib.num_functions; i++) {
+ if (!want || !strcmp(want, lib.functions[i].name)) {
+ pick = i;
+ break;
+ }
+ }
+ if (pick == lib.num_functions) {
+ fprintf(stderr, "air_run: no function %s\n", want ? want : "(any)");
+ return 1;
+ }
+ bitcode = lib.functions[pick].bitcode;
+ bitcode_size = lib.functions[pick].bitcode_size;
+ name = lib.functions[pick].name;
+ }
+
+ /* The screen. Here it is softpipe, drawing into memory with no GPU at all,
+ * which is the point: the whole path can be checked on this machine. On the
+ * phone it is the freedreno screen that the port's Mesa already makes
+ * (osmesa_create_gpu_screen in tools/mesa/freedreno-darwin.patch), and
+ * nothing below this line changes.
+ */
+ struct pipe_screen *screen = sw_screen_create(null_sw_create());
+ if (!screen) {
+ fprintf(stderr, "air_run: no gallium screen\n");
+ return 1;
+ }
+ printf("air_run: %s on %s\n", name, screen->get_name(screen));
+
+ const void *options =
+ screen->get_compiler_options(screen, PIPE_SHADER_IR_NIR, PIPE_SHADER_FRAGMENT);
+ if (!options) {
+ fprintf(stderr, "air_run: this screen takes no NIR\n");
+ return 1;
+ }
+
+ /* the shader */
+ struct air_constant_value *fc;
+ unsigned num_fc = air_module_function_constants(ctx, bitcode, bitcode_size, &fc);
+ struct air_to_nir_options air_options = { .constants = fc, .num_constants = num_fc };
+ struct air_shader_info info;
+ const char *err;
+ nir_shader *fs = air_to_nir(ctx, bitcode, bitcode_size, NULL, &air_options, options,
+ &info, &err);
+ if (!fs) {
+ fprintf(stderr, "air_run: %s: %s\n", name, err);
+ return 1;
+ }
+ if (info.stage != MESA_SHADER_FRAGMENT) {
+ fprintf(stderr, "air_run: %s is a %s shader; only fragment shaders are drawn here\n",
+ name, gl_shader_stage_name(info.stage));
+ return 1;
+ }
+ /* The render target's format follows the shader's own output type. A Metal
+ * fragment shader returning uint4 writes integers, and reading those back
+ * through a float target gives the right bits read the wrong way -- which
+ * looks exactly like a translation bug and is not one.
+ */
+ enum pipe_format rt_format = PIPE_FORMAT_R32G32B32A32_FLOAT;
+ bool rt_is_float = true;
+ /* Which attachment to read back: the lowest one the shader writes, not
+ * target 0. clearFragment04 writes FRAG_RESULT_DATA1 alone, and target 0
+ * then holds the clear colour -- a correct result that looks exactly like
+ * a shader which stored nothing.
+ */
+ unsigned read_rt = ~0u;
+ nir_foreach_variable_with_modes(var, fs, nir_var_shader_out) {
+ if (var->data.location < FRAG_RESULT_DATA0)
+ continue;
+ unsigned idx = var->data.location - FRAG_RESULT_DATA0;
+ if (idx >= read_rt)
+ continue;
+ read_rt = idx;
+ enum glsl_base_type base = glsl_get_base_type(glsl_without_array(var->type));
+ if (base != GLSL_TYPE_FLOAT && base != GLSL_TYPE_FLOAT16 &&
+ base != GLSL_TYPE_DOUBLE) {
+ /* unsigned, not signed: an LLVM integer carries no signedness, so
+ * both this and tools/air/cpuref.py print the bits unsigned and the
+ * two can be compared
+ */
+ rt_format = PIPE_FORMAT_R32G32B32A32_UINT;
+ rt_is_float = false;
+ } else {
+ rt_format = PIPE_FORMAT_R32G32B32A32_FLOAT;
+ rt_is_float = true;
+ }
+ }
+ if (read_rt == ~0u) {
+ fprintf(stderr, "air_run: %s writes no colour attachment\n", name);
+ return 1;
+ }
+
+ finalize_for_gallium(fs);
+
+ struct pipe_context *pipe = screen->context_create(screen, NULL, 0);
+
+ /* One target per render target the shader writes: a shader whose outputs
+ * outnumber the framebuffer's attachments draws nothing at all, which
+ * looks like a translation that produced no stores.
+ */
+ unsigned num_rt = MAX2(info.num_render_targets, read_rt + 1);
+ if (num_rt > PIPE_MAX_COLOR_BUFS) {
+ fprintf(stderr, "air_run: %u render targets, more than this can bind\n", num_rt);
+ return 1;
+ }
+ struct pipe_resource templ = {
+ .target = PIPE_TEXTURE_2D,
+ .format = rt_format,
+ .width0 = WIDTH,
+ .height0 = HEIGHT,
+ .depth0 = 1,
+ .array_size = 1,
+ .bind = PIPE_BIND_RENDER_TARGET | PIPE_BIND_SAMPLER_VIEW,
+ };
+ struct pipe_resource *target = NULL;
+ struct pipe_framebuffer_state fb = {
+ .width = WIDTH, .height = HEIGHT, .nr_cbufs = num_rt,
+ };
+ for (unsigned i = 0; i < num_rt; i++) {
+ struct pipe_resource *res = screen->resource_create(screen, &templ);
+ fb.cbufs[i] = pipe->create_surface(pipe, res,
+ &(struct pipe_surface){ .format = templ.format });
+ if (i == read_rt)
+ target = res;
+ }
+ pipe->set_framebuffer_state(pipe, &fb);
+
+ pipe->set_viewport_states(pipe, 0, 1, &(struct pipe_viewport_state){
+ .scale = { WIDTH / 2.0f, HEIGHT / 2.0f, 1.0f },
+ .translate = { WIDTH / 2.0f, HEIGHT / 2.0f, 0.0f },
+ });
+
+ void *blend = pipe->create_blend_state(pipe, &(struct pipe_blend_state){
+ .rt[0].colormask = PIPE_MASK_RGBA,
+ });
+ pipe->bind_blend_state(pipe, blend);
+ void *dsa = pipe->create_depth_stencil_alpha_state(pipe,
+ &(struct pipe_depth_stencil_alpha_state){ 0 });
+ pipe->bind_depth_stencil_alpha_state(pipe, dsa);
+ void *rast = pipe->create_rasterizer_state(pipe, &(struct pipe_rasterizer_state){
+ .cull_face = PIPE_FACE_NONE, .half_pixel_center = 1, .bottom_edge_rule = 1,
+ .depth_clip_near = 1, .depth_clip_far = 1,
+ });
+ pipe->bind_rasterizer_state(pipe, rast);
+
+ /* every constant buffer the shader reads, filled with the pattern */
+ for (unsigned i = 0; i < info.num_resources; i++) {
+ const struct air_resource *r = &info.resources[i];
+ if (r->kind != AIR_RESOURCE_CONSTANT_BUFFER && r->kind != AIR_RESOURCE_DEVICE_BUFFER)
+ continue;
+ unsigned bytes = r->size ? r->size : 256;
+ uint8_t *bits = malloc(bytes);
+ for (unsigned k = 0; k < bytes; k++)
+ bits[k] = pattern_byte(k);
+ struct pipe_resource *buf = pipe_buffer_create(screen, PIPE_BIND_CONSTANT_BUFFER,
+ PIPE_USAGE_DEFAULT, bytes);
+ pipe_buffer_write(pipe, buf, 0, bytes, bits);
+ pipe->set_constant_buffer(pipe, PIPE_SHADER_FRAGMENT, r->index, false,
+ &(struct pipe_constant_buffer){
+ .buffer = buf, .buffer_size = bytes,
+ });
+ printf("air_run: %s buffer at index %u, %u bytes of (i * 7 + 13) & 0xff\n",
+ r->kind == AIR_RESOURCE_CONSTANT_BUFFER ? "constant" : "device",
+ r->index, bytes);
+ free(bits);
+ }
+
+ /* the quad */
+ static const float verts[] = {
+ -1, -1, 0, 1, 1, -1, 0, 1, -1, 1, 0, 1, 1, 1, 0, 1,
+ };
+ struct pipe_resource *vbuf = pipe_buffer_create(screen, PIPE_BIND_VERTEX_BUFFER,
+ PIPE_USAGE_DEFAULT, sizeof(verts));
+ pipe_buffer_write(pipe, vbuf, 0, sizeof(verts), verts);
+ pipe->set_vertex_buffers(pipe, 1, &(struct pipe_vertex_buffer){
+ .buffer.resource = vbuf, .buffer_offset = 0,
+ });
+ void *velem = pipe->create_vertex_elements_state(pipe, 1,
+ &(struct pipe_vertex_element){
+ .src_offset = 0, .src_stride = 16, .vertex_buffer_index = 0,
+ .src_format = PIPE_FORMAT_R32G32B32A32_FLOAT,
+ });
+ pipe->bind_vertex_elements_state(pipe, velem);
+
+ nir_shader *vs = quad_vertex_shader(options);
+ finalize_for_gallium(vs);
+ void *vs_cso = pipe->create_vs_state(pipe, &(struct pipe_shader_state){
+ .type = PIPE_SHADER_IR_NIR, .ir.nir = vs,
+ });
+ pipe->bind_vs_state(pipe, vs_cso);
+ void *fs_cso = pipe->create_fs_state(pipe, &(struct pipe_shader_state){
+ .type = PIPE_SHADER_IR_NIR, .ir.nir = fs,
+ });
+ pipe->bind_fs_state(pipe, fs_cso);
+
+ union pipe_color_union clear = { .ui = { 0, 0, 0, 0 } };
+ pipe->clear(pipe, PIPE_CLEAR_COLOR, NULL, &clear, 0.0, 0);
+
+ struct pipe_draw_info draw = {
+ .mode = MESA_PRIM_TRIANGLE_STRIP, .index_bounds_valid = true,
+ .max_index = 3, .instance_count = 1,
+ };
+ struct pipe_draw_start_count_bias sc = { .start = 0, .count = 4 };
+ pipe->draw_vbo(pipe, &draw, 0, NULL, &sc, 1);
+ pipe->flush(pipe, NULL, 0);
+
+ /* the pixel */
+ struct pipe_transfer *xfer;
+ void *pix = pipe->texture_map(pipe, target, 0, PIPE_MAP_READ,
+ &(struct pipe_box){ .width = WIDTH, .height = HEIGHT,
+ .depth = 1 }, &xfer);
+ if (!pix) {
+ fprintf(stderr, "air_run: the render target could not be read back\n");
+ return 1;
+ }
+ printf("air_run: the pixel at (0, 0) of render target %u came back as:\n",
+ read_rt);
+ for (unsigned c = 0; c < 4; c++) {
+ if (rt_is_float)
+ printf(" %.9g\n", (double)((float *)pix)[c]);
+ else
+ printf(" %u\n", ((uint32_t *)pix)[c]);
+ }
+ pipe->texture_unmap(pipe, xfer);
+
+ printf("air_run: drew %ux%u into %s, %u render target%s\n",
+ WIDTH, HEIGHT, util_format_short_name(rt_format), num_rt,
+ num_rt == 1 ? "" : "s");
+
+ pipe->destroy(pipe);
+ screen->destroy(screen);
+ ralloc_free(ctx);
+ glsl_type_singleton_decref();
+ return 0;
+}
diff --git a/tools/mesa/air/meson.build b/tools/mesa/air/meson.build
index 4a6bff3..81be917 100644
--- a/tools/mesa/air/meson.build
+++ b/tools/mesa/air/meson.build
@@ -35,6 +35,11 @@ idep_air = declare_dependency(
include_directories : include_directories('.'),
)
+# air_run (air_run.c) draws with a translated shader and reads the pixels back,
+# so it needs libgallium -- which meson has not defined yet when this file is
+# read. Its executable is declared in src/gallium/drivers/freedreno instead,
+# by tools/mesa/air-ir3.patch, next to ir3_compiler.
+
air2nir = executable(
'air2nir',
files('air2nir.c'),