diff --git a/include/drm-uapi/apple_sgx_drm.h b/include/drm-uapi/apple_sgx_drm.h new file mode 100644 index 00000000000..5400b2faa9b --- /dev/null +++ b/include/drm-uapi/apple_sgx_drm.h @@ -0,0 +1,263 @@ +/* SPDX-License-Identifier: MIT */ +/* + * Apple S5L8940X (A5) PowerVR SGX543MP2: the render node's interface. + * + * EXPERIMENTAL. This is the first interface Mesa and sgx2d talk to the GPU + * through (docs/research/p105-mesa.md, M9); it will change while the Mesa + * driver is written, and nothing outside this repository should depend on + * it yet. APPLE_SGX_PARAM_UAPI_VERSION says which revision a kernel has. + * + * The model, kept as small as the hardware allows: + * + * - One GPU address space, shared by every client (the microkernel's own + * buffers are in it too, at 0x80000000). Buffers are GEM objects mapped + * into it for their whole life; the kernel picks the address (64 KiB + * aligned for buffers of 64 KiB or more: a render target needs it), or + * the caller asks for one (APPLE_SGX_BO_FIXED_VA). The GPU's own pointer + * encodings decide where things may go -- PDS data pointers only reach + * 0x80000000 and up, and USSE code is addressed relative to a code base + * register -- so the usable range and the code zone are parameters. + * + * - USE_CODE_BASE_3 and USE_CODE_BASE_5 (the ones iOS's GL driver uses) + * point at APPLE_SGX_PARAM_CODE_BASE. A DOUTU word for code at GPU + * address A is ((A - CODE_BASE) / 8) << 4 | 3, the index in 20 bits: + * code has to be within 8 MiB of the base. Buffers created with + * APPLE_SGX_BO_USSE_CODE land there (kernels before 2026-10-04 gave + * CODE_VA_END as base + 16 MiB and used the top of it: out of reach). + * + * - A render (the TA, then the 3D pass) is submitted as the TA command iOS + * puts in a render context's CCB, built by the caller as for debugfs's + * "rkick" (docs/research/p105-gpu.md, M4): the kernel copies it into the + * render queue, points its completion at its own memory, writes the + * render context into the render details (+0x20, +0xa4), sets the + * parameter buffer descriptor, and kicks. The job is done when the + * microkernel clears the render details' word at +0x24 after the 3D pass. + * Renders run one at a time, in submission order across all clients. + * + * - Synchronisation is syncobjs: a submit waits for in_syncs and signals + * out_sync when its 3D pass is over. Every buffer the render touches + * must be listed in bo_handles; they stay alive and mapped until then. + */ +#ifndef _APPLE_SGX_DRM_H_ +#define _APPLE_SGX_DRM_H_ + +#include "drm.h" + +#if defined(__cplusplus) +extern "C" { +#endif + +#define DRM_APPLE_SGX_GET_PARAM 0x00 +#define DRM_APPLE_SGX_GEM_CREATE 0x01 +#define DRM_APPLE_SGX_GEM_MMAP_OFFSET 0x02 +#define DRM_APPLE_SGX_GEM_WAIT 0x03 +#define DRM_APPLE_SGX_SUBMIT 0x04 +#define DRM_APPLE_SGX_GEM_INFO 0x05 +#define DRM_APPLE_SGX_OVERLAY 0x06 + +#define DRM_IOCTL_APPLE_SGX_GET_PARAM \ + DRM_IOWR(DRM_COMMAND_BASE + DRM_APPLE_SGX_GET_PARAM, struct drm_apple_sgx_get_param) +#define DRM_IOCTL_APPLE_SGX_GEM_CREATE \ + DRM_IOWR(DRM_COMMAND_BASE + DRM_APPLE_SGX_GEM_CREATE, struct drm_apple_sgx_gem_create) +#define DRM_IOCTL_APPLE_SGX_GEM_MMAP_OFFSET \ + DRM_IOWR(DRM_COMMAND_BASE + DRM_APPLE_SGX_GEM_MMAP_OFFSET, struct drm_apple_sgx_gem_mmap_offset) +#define DRM_IOCTL_APPLE_SGX_GEM_WAIT \ + DRM_IOW(DRM_COMMAND_BASE + DRM_APPLE_SGX_GEM_WAIT, struct drm_apple_sgx_gem_wait) +#define DRM_IOCTL_APPLE_SGX_SUBMIT \ + DRM_IOW(DRM_COMMAND_BASE + DRM_APPLE_SGX_SUBMIT, struct drm_apple_sgx_submit) +#define DRM_IOCTL_APPLE_SGX_GEM_INFO \ + DRM_IOWR(DRM_COMMAND_BASE + DRM_APPLE_SGX_GEM_INFO, struct drm_apple_sgx_gem_info) +#define DRM_IOCTL_APPLE_SGX_OVERLAY \ + DRM_IOWR(DRM_COMMAND_BASE + DRM_APPLE_SGX_OVERLAY, struct drm_apple_sgx_overlay) + +/* ---- GET_PARAM ---------------------------------------------------------- */ + +enum drm_apple_sgx_param { + APPLE_SGX_PARAM_UAPI_VERSION = 0, /* 3 (2: no kernel PB, 1: no GEM_INFO) */ + APPLE_SGX_PARAM_CORE_ID = 1, /* MASTER_CORE_ID: 0x01194201 */ + APPLE_SGX_PARAM_CORE_REVISION = 2, /* 0x00010202 = 1.2.2 */ + APPLE_SGX_PARAM_NUM_CORES = 3, /* 2 */ + APPLE_SGX_PARAM_CLOCK_KHZ = 4, /* the GPU clock */ + APPLE_SGX_PARAM_UKERNEL_UP = 5, /* 1 while the microkernel runs */ + + /* GPU addresses: [VA_START, VA_END) is where buffers may be mapped, + * [CODE_VA_START, CODE_VA_END) the code zone, CODE_BASE what + * USE_CODE_BASE_3 and _5 hold (see above). */ + APPLE_SGX_PARAM_VA_START = 6, + APPLE_SGX_PARAM_VA_END = 7, + APPLE_SGX_PARAM_CODE_BASE = 8, + APPLE_SGX_PARAM_CODE_VA_START = 9, + APPLE_SGX_PARAM_CODE_VA_END = 10, + + /* The framebuffer (simplefb's memory), mapped by the kernel for the 2D + * engine; a render can write straight into it. 0 if there is none. + * Linear a8r8g8b8; stride in bytes. */ + APPLE_SGX_PARAM_FB_VA = 11, + APPLE_SGX_PARAM_FB_WIDTH = 12, + APPLE_SGX_PARAM_FB_HEIGHT = 13, + APPLE_SGX_PARAM_FB_STRIDE = 14, + + /* Renders submitted, completed, and timed out since the module loaded; + * microkernel (re)starts. */ + APPLE_SGX_PARAM_RENDERS_SUBMITTED = 15, + APPLE_SGX_PARAM_RENDERS_DONE = 16, + APPLE_SGX_PARAM_RENDERS_TIMED_OUT = 17, + APPLE_SGX_PARAM_UKERNEL_BOOTS = 18, + + /* UAPI 3: the kernel's parameter buffer (a submit with pb_va 0 uses + * it), and where APPLE_SGX_BO_TA_HEAP buffers go -- above the TA's + * base, 0x87800000, within the 256 MiB the TA's addresses reach. */ + APPLE_SGX_PARAM_PB_VA = 19, + APPLE_SGX_PARAM_TA_HEAP_START = 20, + APPLE_SGX_PARAM_TA_HEAP_END = 21, + + /* The APPLE_SGX_BO_* flags GEM_CREATE takes; kernels before + * APPLE_SGX_BO_SCANOUT do not have this parameter (EINVAL), and every + * flag before it. Still UAPI 3: a flag more is no new interface. */ + APPLE_SGX_PARAM_BO_FLAGS = 22, +}; + +struct drm_apple_sgx_get_param { + __u32 param; /* in: enum drm_apple_sgx_param */ + __u32 pad; /* in: 0 */ + __u64 value; /* out */ +}; + +/* ---- GEM_CREATE --------------------------------------------------------- */ + +/* Map at drm_apple_sgx_gem_create.va instead of an address the kernel + * picks. Fails with EEXIST if anything is mapped there already. */ +#define APPLE_SGX_BO_FIXED_VA (1 << 0) +/* USSE code: in the code zone, where a DOUTU can reach it. */ +#define APPLE_SGX_BO_USSE_CODE (1 << 1) +/* The GPU may only read it (PTE READONLY). */ +#define APPLE_SGX_BO_GPU_READONLY (1 << 2) +/* Without the PTE's CACHECONSISTENT bit, which every other buffer has (the + * microkernel only sees CPU writes to cache-consistent pages; the + * framebuffer is mapped without it). */ +#define APPLE_SGX_BO_NOT_CACHE_CONSISTENT (1 << 3) +/* In the TA's heap (UAPI 3): render target data, whose state buffer the 3D + * register block names by its offset from the TA's base. */ +#define APPLE_SGX_BO_TA_HEAP (1 << 4) +/* A buffer the screen may show (APPLE_SGX_PARAM_BO_FLAGS lists it): one of + * the screen's size is made physically contiguous when memory allows, and + * KMS then shows it by pointing the display at it instead of copying it + * onto the screen. Not an error when it cannot be: the buffer is an + * ordinary one, and GEM_INFO's flags leave this out. */ +#define APPLE_SGX_BO_SCANOUT (1 << 5) + +#define APPLE_SGX_BO_FLAGS 0x3f + +struct drm_apple_sgx_gem_create { + __u64 size; /* in: bytes, rounded up to 4 KiB */ + __u32 flags; /* in: APPLE_SGX_BO_* */ + __u32 handle; /* out */ + __u32 va; /* in with APPLE_SGX_BO_FIXED_VA, out: the GPU address */ + __u32 pad; /* in: 0 */ +}; + +/* ---- GEM_MMAP_OFFSET: the offset to mmap() the buffer at (write-combined) */ + +struct drm_apple_sgx_gem_mmap_offset { + __u32 handle; /* in */ + __u32 flags; /* in: 0 */ + __u64 offset; /* out */ +}; + +/* ---- GEM_WAIT: until no render that lists the buffer is running -------- */ + +struct drm_apple_sgx_gem_wait { + __u32 handle; /* in */ + __u32 pad; /* in: 0 */ + __s64 timeout_ns; /* in: absolute, CLOCK_MONOTONIC; 0 just polls */ +}; + +/* ---- SUBMIT: one render, the TA and then the 3D pass -------------------- */ + +#define APPLE_SGX_TA_CMD_MIN 0x11c +#define APPLE_SGX_TA_CMD_MAX 0x200 + +struct drm_apple_sgx_submit { + /* in: user pointer to the TA command, as iOS's render submit builds + * it (0x80bfca20): word 0 its size in bytes, a multiple of 8 between + * APPLE_SGX_TA_CMD_MIN and _MAX; the kernel rewrites words 0, 0x64, + * 0x68 and 0x6c. */ + __u64 cmd; + __u32 cmd_size; /* in: bytes copied from cmd; >= word 0 */ + __u32 flags; /* in: 0 */ + + __u32 pb_va; /* in: the parameter buffer's descriptor; 0: the + * kernel's, shared by every client (UAPI 3) */ + __u32 details_handle; /* in: the buffer holding the render details */ + __u32 details_offset; /* in: where in it, 4-byte aligned */ + __u32 cache_control; /* in: SGXMKIF_CC_* to add to the kick, normally 0 */ + + __u64 bo_handles; /* in: user pointer to __u32 handles */ + __u32 bo_handle_count; + __u32 in_sync_count; + __u64 in_syncs; /* in: user pointer to __u32 syncobj handles */ + __u32 out_sync; /* in: syncobj to signal when it is done, or 0 */ + __u32 pad; /* in: 0 */ +}; + +/* ---- GEM_INFO: what a handle is, for one that came from a dma-buf ------ */ + +/* Every buffer is the render node's own (dma-bufs of other devices are not + * taken), so a dma-buf's handle names a buffer already mapped: this says + * where. UAPI version 2 on. */ +struct drm_apple_sgx_gem_info { + __u32 handle; /* in */ + __u32 flags; /* out: the APPLE_SGX_BO_* it was made with */ + __u32 va; /* out: its GPU address */ + __u32 pad; /* in: 0 */ + __u64 size; /* out: bytes */ +}; + +/* ---- OVERLAY: a picture over the screen, whatever shows it -------------- */ + +/* + * A buffer of the render node blended over the screen -- straight alpha, + * colour = overlay * a + screen * (1 - a) -- after every copy of KMS's + * plane onto it, and at once when it is set: an on-screen control over a + * fullscreen game, with no compositor (tools/screenpad). Its pixels are + * the plane's, turned as the plane is; width x height must be the plane's + * size now (out_width x out_height), or it is not shown until it is set + * again for the new size. The rectangles listed (out to 16 pixels on every + * side) say where it is: a copy that meets any of them blends the box + * round those it meets, so the buffer's pixels outside them must be + * transparent. A change to its pixels shows when it is set again. handle 0 takes it away, and so does closing the + * file that set it; one file at a time has it (-EBUSY for the others). + * Shown while a KMS client has a framebuffer on the plane (X, a game on + * KMS), not on the text console. Root only. + * + * Kernels from 2026-10-23 on. It changed nothing else, so it did not + * change APPLE_SGX_PARAM_UAPI_VERSION: Mesa (sgx_device.c) refuses a + * version it does not know and falls back to software -- XFCE on softpipe + * -- so a kernel that only adds to the interface keeps the number, and a + * program asks for the addition itself (QUERY: -EINVAL where there is + * none). + */ +#define APPLE_SGX_OVERLAY_QUERY (1 << 0) /* only the out fields */ +#define APPLE_SGX_OVERLAY_MAX_RECTS 16 + +struct drm_apple_sgx_overlay_rect { + __u16 x, y, w, h; +}; + +struct drm_apple_sgx_overlay { + __u32 flags; /* in: APPLE_SGX_OVERLAY_* */ + __u32 handle; /* in: the buffer (BGRA8888, its alpha used), or 0 */ + __u32 pitch; /* in: bytes a line, a multiple of 64 */ + __u16 width, height; /* in: pixels: the plane's size */ + __u32 nrects; /* in: how many rects are used */ + struct drm_apple_sgx_overlay_rect rects[APPLE_SGX_OVERLAY_MAX_RECTS]; + __u16 out_width; /* out: the plane's size now; 0 x 0 with no */ + __u16 out_height; /* framebuffer shown */ + __u32 out_rotation; /* out: the plane's DRM_MODE_ROTATE_* */ +}; + +#if defined(__cplusplus) +} +#endif + +#endif /* _APPLE_SGX_DRM_H_ */ diff --git a/meson.build b/meson.build index c1d17bccc2b..d8fde4165bc 100644 --- a/meson.build +++ b/meson.build @@ -231,6 +231,7 @@ with_gallium_i915 = gallium_drivers.contains('i915') with_gallium_svga = gallium_drivers.contains('svga') with_gallium_virgl = gallium_drivers.contains('virgl') with_gallium_lima = gallium_drivers.contains('lima') +with_gallium_sgx = gallium_drivers.contains('sgx') with_gallium_zink = gallium_drivers.contains('zink') with_gallium_d3d12 = gallium_drivers.contains('d3d12') with_gallium_asahi = gallium_drivers.contains('asahi') diff --git a/meson.options b/meson.options index b0f065a7542..ee754320c1e 100644 --- a/meson.options +++ b/meson.options @@ -87,7 +87,7 @@ option( 'all', 'auto', 'asahi', 'crocus', 'd3d12', 'ethosu', 'etnaviv', 'freedreno', 'i915', 'iris', 'lima', 'llvmpipe', 'nouveau', 'panfrost', 'r300', 'r600', 'radeonsi', - 'rocket', 'softpipe', 'svga', 'tegra', 'v3d', 'vc4', 'virgl', 'zink', + 'rocket', 'sgx', 'softpipe', 'svga', 'tegra', 'v3d', 'vc4', 'virgl', 'zink', ], description : 'List of gallium drivers to build. If this is set to auto ' + 'all drivers applicable to the target OS/architecture ' + diff --git a/src/compiler/nir/nir_lower_uniforms_to_ubo.c b/src/compiler/nir/nir_lower_uniforms_to_ubo.c index 717b87d97a9..a616f90af91 100644 --- a/src/compiler/nir/nir_lower_uniforms_to_ubo.c +++ b/src/compiler/nir/nir_lower_uniforms_to_ubo.c @@ -97,9 +97,13 @@ nir_lower_uniforms_to_ubo_instr(nir_builder *b, nir_instr *instr, void *data) * nir_lower_ubo_vec4.c) */ if (nir_src_is_const(intr->src[0])) { + /* (the offset in the multiplier's units too, as the address + * has it: an offset of 1 vec4 is 16 bytes, not 1 -- + * nir_lower_ubo_vec4 asserted on a matrix's second column) + */ nir_intrinsic_set_align(load, NIR_ALIGN_MUL_MAX, - (nir_src_as_uint(intr->src[0]) + - nir_intrinsic_base(intr) * multiplier) % + ((nir_src_as_uint(intr->src[0]) + + nir_intrinsic_base(intr)) * multiplier) % NIR_ALIGN_MUL_MAX); } else { nir_intrinsic_set_align(load, MAX2(multiplier, intr->def.bit_size / 8), 0); diff --git a/src/gallium/auxiliary/pipe-loader/pipe_loader_drm.c b/src/gallium/auxiliary/pipe-loader/pipe_loader_drm.c index dc631b4c86d..96a7737f10e 100644 --- a/src/gallium/auxiliary/pipe-loader/pipe_loader_drm.c +++ b/src/gallium/auxiliary/pipe-loader/pipe_loader_drm.c @@ -88,6 +88,7 @@ static const struct drm_driver_descriptor *driver_descriptors[] = { ðosu_driver_descriptor, &tegra_driver_descriptor, &lima_driver_descriptor, + &apple_sgx_driver_descriptor, &zink_driver_descriptor, &kmsro_driver_descriptor, }; diff --git a/src/gallium/auxiliary/target-helpers/drm_helper.h b/src/gallium/auxiliary/target-helpers/drm_helper.h index e53b7ede84c..6a18901f66e 100644 --- a/src/gallium/auxiliary/target-helpers/drm_helper.h +++ b/src/gallium/auxiliary/target-helpers/drm_helper.h @@ -417,6 +417,23 @@ DRM_DRIVER_DESCRIPTOR(lima, lima_driconf, ARRAY_SIZE(lima_driconf)) DRM_DRIVER_DESCRIPTOR_STUB(lima) #endif +#ifdef GALLIUM_SGX +#include "sgx/drm/sgx_drm_public.h" + +static struct pipe_screen * +pipe_apple_sgx_create_screen(int fd, const struct pipe_screen_config *config) +{ + struct pipe_screen *screen; + + screen = sgx_drm_screen_create(fd, config); + return screen ? debug_screen_wrap(screen) : NULL; +} +DRM_DRIVER_DESCRIPTOR(apple_sgx, NULL, 0) + +#else +DRM_DRIVER_DESCRIPTOR_STUB(apple_sgx) +#endif + #ifdef GALLIUM_ZINK #include "zink/zink_public.h" diff --git a/src/gallium/auxiliary/target-helpers/drm_helper_public.h b/src/gallium/auxiliary/target-helpers/drm_helper_public.h index fe0e12280f6..0a9f3fee25d 100644 --- a/src/gallium/auxiliary/target-helpers/drm_helper_public.h +++ b/src/gallium/auxiliary/target-helpers/drm_helper_public.h @@ -26,6 +26,7 @@ extern const struct drm_driver_descriptor rocket_driver_descriptor; extern const struct drm_driver_descriptor ethosu_driver_descriptor; extern const struct drm_driver_descriptor tegra_driver_descriptor; extern const struct drm_driver_descriptor lima_driver_descriptor; +extern const struct drm_driver_descriptor apple_sgx_driver_descriptor; extern const struct drm_driver_descriptor zink_driver_descriptor; extern const struct drm_driver_descriptor kmsro_driver_descriptor; diff --git a/src/gallium/drivers/sgx/drm-shim/meson.build b/src/gallium/drivers/sgx/drm-shim/meson.build new file mode 100644 index 00000000000..b061b38d90f --- /dev/null +++ b/src/gallium/drivers/sgx/drm-shim/meson.build @@ -0,0 +1,11 @@ +# Copyright 2026 Project Cascadia +# SPDX-License-Identifier: MIT + +libsgx_noop_drm_shim = shared_library( + 'sgx_noop_drm_shim', + 'sgx_noop.c', + include_directories : [inc_include, inc_src], + dependencies : [dep_drm_shim, idep_mesautil], + gnu_symbol_visibility : 'hidden', + install : true, +) diff --git a/src/gallium/drivers/sgx/drm-shim/sgx_noop.c b/src/gallium/drivers/sgx/drm-shim/sgx_noop.c new file mode 100644 index 00000000000..8f2ae6f3a69 --- /dev/null +++ b/src/gallium/drivers/sgx/drm-shim/sgx_noop.c @@ -0,0 +1,106 @@ +/* + * Copyright 2026 Project Cascadia + * SPDX-License-Identifier: MIT + * + * A pretend apple_sgx render node, for running the driver where there is no + * iPad (Mesa's drm-shim): + * + * LD_PRELOAD=libsgx_noop_drm_shim.so glclear + * + * Buffers are memory, renders do nothing and are done at once. What it + * reports is what the iPad mini's kernel reports, but without a + * framebuffer. + */ +#include +#include + +#include "drm-shim/drm_shim.h" +#include "drm-uapi/apple_sgx_drm.h" +#include "util/u_math.h" + +/* below the BIF's tiled window, as the kernel picks them since 2026-10-04 */ +static uint32_t next_va = 0xe0000000, next_code = 0x9b000000; + +static int +sgx_ioctl_noop(int fd, unsigned long request, void *arg) +{ + return 0; +} + +static int +sgx_ioctl_get_param(int fd, unsigned long request, void *arg) +{ + struct drm_apple_sgx_get_param *gp = arg; + + switch (gp->param) { + case APPLE_SGX_PARAM_UAPI_VERSION: gp->value = 1; break; + case APPLE_SGX_PARAM_CORE_ID: gp->value = 0x01194201; break; + case APPLE_SGX_PARAM_CORE_REVISION: gp->value = 0x00010202; break; + case APPLE_SGX_PARAM_NUM_CORES: gp->value = 2; break; + case APPLE_SGX_PARAM_CLOCK_KHZ: gp->value = 256500; break; + case APPLE_SGX_PARAM_UKERNEL_UP: gp->value = 1; break; + case APPLE_SGX_PARAM_VA_START: gp->value = 0x80800000; break; + case APPLE_SGX_PARAM_VA_END: gp->value = 0xf0000000; break; + case APPLE_SGX_PARAM_CODE_BASE: + case APPLE_SGX_PARAM_CODE_VA_START: gp->value = 0x9a000000; break; + case APPLE_SGX_PARAM_CODE_VA_END: gp->value = 0x9b000000; break; + default: gp->value = 0; break; + } + return 0; +} + +static int +sgx_ioctl_gem_create(int fd, unsigned long request, void *arg) +{ + struct drm_apple_sgx_gem_create *create = arg; + struct shim_fd *shim_fd = drm_shim_fd_lookup(fd); + struct shim_bo *bo = calloc(1, sizeof(*bo)); + size_t size = align(create->size, 4096); + + drm_shim_bo_init(bo, size); + create->handle = drm_shim_bo_get_handle(shim_fd, bo); + drm_shim_bo_put(bo); + /* top down, a guard page each, as the kernel does it */ + if (!(create->flags & APPLE_SGX_BO_FIXED_VA)) { + uint32_t *top = create->flags & APPLE_SGX_BO_USSE_CODE ? &next_code : &next_va; + + *top -= size + 4096; + create->va = *top; + } + return 0; +} + +static int +sgx_ioctl_gem_mmap_offset(int fd, unsigned long request, void *arg) +{ + struct drm_apple_sgx_gem_mmap_offset *m = arg; + struct shim_fd *shim_fd = drm_shim_fd_lookup(fd); + struct shim_bo *bo = drm_shim_bo_lookup(shim_fd, m->handle); + + if (!bo) + return -1; + m->offset = drm_shim_bo_get_mmap_offset(shim_fd, bo); + drm_shim_bo_put(bo); + return 0; +} + +static ioctl_fn_t driver_ioctls[] = { + [DRM_APPLE_SGX_GET_PARAM] = sgx_ioctl_get_param, + [DRM_APPLE_SGX_GEM_CREATE] = sgx_ioctl_gem_create, + [DRM_APPLE_SGX_GEM_MMAP_OFFSET] = sgx_ioctl_gem_mmap_offset, + [DRM_APPLE_SGX_GEM_WAIT] = sgx_ioctl_noop, + [DRM_APPLE_SGX_SUBMIT] = sgx_ioctl_noop, +}; + +void +drm_shim_driver_init(void) +{ + shim_device.driver_ioctls = driver_ioctls; + shim_device.driver_ioctl_count = ARRAY_SIZE(driver_ioctls); + shim_device.version_major = 0; + shim_device.version_minor = 1; + shim_device.version_patchlevel = 0; + + /* (Mesa 27: the platform device's uevent and its subsystem link) */ + drm_shim_platform_device_setup("apple_sgx", "/arm-io/gpu@5100000", "apple,s5l8940x-sgx"); +} diff --git a/src/gallium/drivers/sgx/meson.build b/src/gallium/drivers/sgx/meson.build new file mode 100644 index 00000000000..738441be973 --- /dev/null +++ b/src/gallium/drivers/sgx/meson.build @@ -0,0 +1,45 @@ +# Copyright 2026 Project Cascadia +# SPDX-License-Identifier: MIT + +files_sgx = files( + 'sgx_compiler.c', + 'sgx_compiler.h', + 'sgx_context.c', + 'sgx_context.h', + 'sgx_device.c', + 'sgx_device.h', + 'sgx_draw.c', + 'sgx_draw.h', + 'sgx_frame.c', + 'sgx_frame.h', + 'sgx_resource.c', + 'sgx_resource.h', + 'sgx_rt.c', + 'sgx_rt.h', + 'sgx_screen.c', + 'sgx_screen.h', + 'sgx_template.c', + 'sgx_template.h', + 'sgx_usse.c', + 'sgx_usse.h', +) + +libsgx = static_library( + 'sgx', + files_sgx, + include_directories : [ + inc_src, inc_include, inc_gallium, inc_gallium_aux, inc_gallium_drivers, + ], + dependencies : [dep_libdrm, idep_nir_headers, idep_mesautil], + gnu_symbol_visibility : 'hidden', +) + +driver_sgx = declare_dependency( + compile_args : '-DGALLIUM_SGX', + link_with : [libsgx, libsgxwinsys], + dependencies : idep_nir, +) + +if with_tools.contains('drm-shim') + subdir('drm-shim') +endif diff --git a/src/gallium/drivers/sgx/sgx_compiler.c b/src/gallium/drivers/sgx/sgx_compiler.c new file mode 100644 index 00000000000..be823372cbd --- /dev/null +++ b/src/gallium/drivers/sgx/sgx_compiler.c @@ -0,0 +1,7328 @@ +/* + * Copyright 2026 Project Cascadia + * SPDX-License-Identifier: MIT + * + * NIR to USSE, fragment shaders (sgx_compiler.h; docs/research/p105-mesa.md, + * M13c). The first compiler is deliberately plain: + * + * - every value is a scalar 32-bit word (NIR scalarised): an F32, or + * (M44) an integer -- the hardware's own, booleans 0 and ~0; until M44 + * ints and bools were lowered to floats, as for the float-only GPUs; + * - the shader is one block: NIR unrolls loops and turns ifs into + * selects, and what it cannot flatten is not compiled; + * - values live in temporaries, one each, always the even (x) lane of a + * 64-bit register, so no instruction ever has to line lanes up; the + * varyings stay where the PDS iterated them (input i in pa4i..pa4i+3, + * F32) and the uniforms where it loaded them (constant buffer word n in + * san), any lane, which the float instructions' swizzles reach; + * - a temporary is taken when a value is made and given back after its + * last use, in the order NIR has the instructions; + * - constants are loaded (LIMM) where they are used; + * - negation and absolute value fold into the operands that have them; + * - comparisons subtract and test the difference (a conditional move); + * - the colour is moved into four registers in a row and packed to 8 bits + * a channel into o0. + * + * Speed (F16 for mediump, two lanes an instruction, constants from the + * hardware's table, sharing loaded constants) comes later -- but for one + * kind of program, a colour of varyings and texels multiplied and added, + * which is all F16, four lanes an instruction (M38, f16_colour()). + */ +#include "sgx_compiler.h" + +#include +#include +#include +#include +#include + +#include "compiler/glsl_types.h" +#include "compiler/nir/nir.h" +#include "compiler/nir/nir_builder.h" +#include "util/bitscan.h" +#include "compiler/nir/nir_format_convert.h" +#include "compiler/nir/nir_lower_blend.h" +#include "util/format/u_formats.h" +#include "util/half_float.h" +#include "util/hash_table.h" +#include "util/ralloc.h" +#include "util/u_dynarray.h" +#include "util/u_math.h" +#include "util/u_memory.h" + +#include "sgx_usse.h" + +/* 32-bit temporaries the compiler hands out; values made by the ALU take + * even ones, a texture's four values a block of four */ +#define MAX_TEMPS 64 +#define MAX_UNITS 32 + +struct operand { + unsigned id; /* the value: its def's index * 4 + the component */ + bool neg, abs; + bool is_const; + float c; + uint32_t u; /* (M44) a constant's bits: an integer's, or c's */ +}; + +/* temporaries made for one instruction, given back after it */ +struct scratch { + unsigned reg[12]; + unsigned n; +}; + +/* a loop's span: its first instruction's index, its end marker's */ +struct loop_span { + int start, end; +}; + +/* (M47) the components of a vector a dot product reads, made in registers + * in a row from an even one (VDP's src1 as it is, or one V32NMAD loading it + * into an internal register): the first, -1 until one is made; the + * components that are values (bit k: component k) */ +struct vgroup { + int base; + unsigned n, mask; +}; + +/* (M47) an internal register (i0..i2) as a vertex program's: the values + * its lanes hold (copies: the values stay where they are too), the + * instruction that wrote it and the last that read it */ +struct ireg { + bool valid; + unsigned n; + struct operand lane[4]; + unsigned from, last; +}; + +struct comp { + struct sgx_fs *fs; /* a fragment shader's, or */ + struct sgx_vs *vs; /* a vertex shader's */ + struct util_dynarray code; /* uint64_t */ + struct usse_reg *loc; /* where each value is */ + bool *owned; /* loc is a temporary of its own (any lane) */ + unsigned nvalues; /* of loc, owned, last_use */ + unsigned spare; /* (M47) an id of no value's, for a temporary */ + int *last_use; /* the last instruction that reads it */ + bool used[MAX_TEMPS]; + unsigned top; /* temporaries used: highest + 1 */ + int input_of_slot[VARYING_SLOT_MAX]; + unsigned ninputs, nuniforms; + /* the uniform words the shader reads (M32): in sa when they fit with + * the rest -- otherwise words 0..sa_uniforms in sa, and all of them in + * memory, read by VLDST from the address (less 4) in sa word ubuf_sa */ + unsigned uwords, sa_uniforms, ubuf_sa; + /* (M43) the uniform buffers read (bit k for buffer k), each one's + * address less 4 in sa word ubo_sa[k] */ + uint16_t ubo_mask; + unsigned ubo_sa[SGX_FRAME_MAX_UBOS]; + bool ubuf; + /* a fragment program whose branches go alike for every pixel (M33): + * the pixels run together, the branches all of theirs -- or one with + * some that do not, its pixels each on its own (M20's way) */ + bool divergent; + bool derivatives; /* DSX or DSY in it */ + /* (M34) the colour's four registers, from the start: the values the + * colour is made of are made there (colour_id: their operands' ids, + * -1 none), not moved there at the end */ + int out_base; + int colour_id[4]; + int slot_of_unit[MAX_UNITS]; /* a texture unit's state words, by slot */ + unsigned nsamplers, sampler_sa; + bool smp; /* an SMP in the program */ + /* (M35) the lookups the PDS makes before the program runs -- a 2D + * texture at a varying's x and y, nothing else -- their varyings, and + * the varyings only they read (not iterated into the registers) */ + const nir_tex_instr *fetch[SGX_FRAME_MAX_FETCH]; + unsigned fetch_slot[SGX_FRAME_MAX_FETCH]; + unsigned nfetch; + bool fetch_only[VARYING_SLOT_MAX]; + /* (M39) lookups lower_fetch_coords() gave a varying's x and y as they + * are, the vertex side doing the rest: each one's SGX_FIX_*; and each + * lookup's of the PDS (fetch[k]'s) */ + const nir_tex_instr *fixed[SGX_FRAME_MAX_FETCH]; + uint8_t fixed_fix[SGX_FRAME_MAX_FETCH]; + unsigned nfixed; + uint8_t fetch_fix[SGX_FRAME_MAX_FETCH]; + const uint8_t *vary_fix; /* a vertex shader's: each varying's SGX_FIX_* */ + /* (M37) the flat-shaded varyings (st's nir_lower_flatshade: GL's + * glShadeModel(GL_FLAT) colours): the TA's colours, two at most, each + * iterated into one register after the inputs, its bytes as o0's -- + * colour_of_slot[] their index, -1 not one */ + bool flat[VARYING_SLOT_MAX]; + int colour_of_slot[VARYING_SLOT_MAX]; + unsigned colour_slot[2], ncolours; + /* a rectangle texture's 1 / width, 1 / height, two words a texture + * after their state words (nir_lower_tex's lower_rect: GL's rectangle + * textures are 2D ones to the sampler) -- -1 none */ + int scale_sa; + bool scales; + /* (M44) the textures' sizes, SGX_FS_SIZE_WORDS a texture after the + * scales (sgx_fs.size_sa): textureSize, texelFetch -- -1 none */ + int size_sa; + bool sizes; + int blend_sa; /* the blend colour's words, -1 none */ + /* (M46) the program's constants, in sa after the rest, two words each + * from an even word: an F32's (its bits, 0: lane x), or four F16 (the F16 + * path's) -- the driver's to write per draw */ + uint32_t kconst[2 * SGX_FS_MAX_KCONST]; + unsigned nkconst, kconst_sa; + /* (M46) the pool's pairs the draw works out (bit k: pair k is one) */ + struct sgx_fs_derived derived[SGX_FS_MAX_DERIVED]; + unsigned nderived; + uint32_t kconst_derived; + /* GL's blending by a SOP2 on the colour packed to bytes and the tile's + * (o0): src1 the colour unless swapped (M25) */ + bool sop2, sop2_swap; + struct usse_sop2 sop2_factors; + /* (M46) GL's constant factors with it: the colour times the packed + * blend colour (sa blend_sa) before the blending, the tile's colour, or + * the result's alpha after it -- a SOP2 each (sop2_plan) */ + bool sop2_pre_src, sop2_pre_dst, sop2_post; + struct usse_sop2 sop2_src_f, sop2_dst_f, sop2_post_f; + bool f16; /* the whole program F16's (M38: f16_colour) */ + /* (M46) an F16 program's lookups at coordinates it works out: their + * varyings iterated as F32 (input i: bit i), each input's first primary + * attribute then, the PDS's texels' first, and where the instructions + * that write the output start (the sampler's 2x2 blocks: skipinv) */ + uint8_t in_f32; + uint8_t smp_norm; /* (M46) slots whose state says F16, 0..1 */ + unsigned in_pa[SGX_FRAME_MAX_VARYINGS], fetch_pa; + unsigned f16_out_at; + int logicop; /* GL's logic op (pipe_logicop), -1 none (M37) */ + struct operand colour[4]; + bool have_colour[4]; + int kill; /* the temporary that is not 0 for a pixel discarded, or -1 */ + bool kills; /* the shader discards (scan) */ + /* control flow (M20): the ifs and loops around the instruction, each + * SSA def's instruction, each loop's span (its first instruction, its + * end marker), the loops a walk is in, whether the code branches */ + int depth; + int *def_at; + struct util_dynarray loops; /* struct loop_span */ + unsigned nloops; + struct loop_span active[16]; + unsigned nactive; + bool branches; + bool front_when_set; /* gl_FrontFacing: the facing bit set is the front */ + /* a vertex shader's outputs: 0 the position, 1 + k varying k of the + * layout (varying_slot[k]) -- which are written, and the position's + * values (the varyings go to their registers as they are stored); the + * attributes it reads */ + const unsigned *varying_slot; + unsigned nvaryings, nattrs; + unsigned pa_base; /* a vertex program's temporaries: pa from here */ + const uint8_t *attr; /* how each attribute comes (M26) */ + struct operand vout[1 + SGX_FRAME_MAX_VARYINGS][4]; + bool have_vout[1 + SGX_FRAME_MAX_VARYINGS][4]; + /* (M46) a value made straight into a varying's output register (its + * number + 1; 0: a temporary): plan_vs_outputs() */ + unsigned *vs_out; + char *why; + unsigned why_size; + bool failed; + bool keep_order; /* NIR's order, not nir_opt_move's (M36) */ + /* (M44) the shader and NIR's range analysis of it: an integer known + * small enough for one instruction (a product, a shift) */ + nir_shader *nir; + struct hash_table *range; + /* (M47) a vertex program's vector instructions (VDP) on the internal + * registers: what each holds, and the spans of code (pairs of indices, + * from and the last read) over which one held a value read later -- + * nosched on each instruction of a span, the registers being the + * pipe's */ + bool vec; + struct ireg ireg[USSE_NINTERNAL]; + struct util_dynarray ispans; + /* (M47) the vectors made in a row (plan_groups()): each value's group * + * 4 + its component, -1 none */ + struct vgroup *vgroups; + unsigned nvgroups; + int *group_of; + /* (M47) defs another instruction made already (a comparison of the + * other lane, compare_mask()): skipped, by def index */ + bool *premade; +}; + +static void +fail(struct comp *c, const char *fmt, ...) +{ + va_list ap; + + if (c->failed) + return; + va_start(ap, fmt); + vsnprintf(c->why, c->why_size, fmt, ap); + va_end(ap); + c->failed = true; +} + +static void +emit(struct comp *c, uint64_t w) +{ + util_dynarray_append(&c->code, w); +} + +static unsigned here(struct comp *c); + +/* n free temporaries in a row, the first a multiple of align */ +static unsigned +block(struct comp *c, unsigned n, unsigned align) +{ + for (unsigned r = 0; r + n <= MAX_TEMPS; r += align) { + unsigned i; + + for (i = 0; i < n && !c->used[r + i]; i++) + ; + if (i < n) + continue; + for (i = 0; i < n; i++) + c->used[r + i] = true; + c->top = MAX2(c->top, r + n); + return r; + } + fail(c, "more values live at once than %u temporaries hold", MAX_TEMPS); + return 0; +} + +/* block()'s, -1 when there is no room (and the compile goes on) */ +static int +block_try(struct comp *c, unsigned n, unsigned align) +{ + for (unsigned r = 0; r + n <= MAX_TEMPS; r += align) { + unsigned i; + + for (i = 0; i < n && !c->used[r + i]; i++) + ; + if (i < n) + continue; + for (i = 0; i < n; i++) + c->used[r + i] = true; + c->top = MAX2(c->top, r + n); + return r; + } + return -1; +} + +static unsigned +take(struct comp *c) /* an even temporary */ +{ + return block(c, 1, 2); +} + +static void +give_back(struct comp *c, unsigned r) +{ + c->used[r] = false; +} + +/* temporary r as a register: a vertex program's are primary attributes + * after the vertex's (iOS's vertex programs use them as scratch too, the + * corpus's x03: the fetch's register count covers them) */ +static struct usse_reg +treg(struct comp *c, unsigned r) +{ + return c->vs ? usse_reg(USSE_PA, c->pa_base + r) : usse_reg(USSE_TEMP, r); +} + +static unsigned +scratch_take(struct comp *c, struct scratch *s) +{ + unsigned r = take(c); + + assert(s->n < ARRAY_SIZE(s->reg)); + s->reg[s->n++] = r; + return r; +} + +static void +scratch_give_back(struct comp *c, struct scratch *s) +{ + for (unsigned i = 0; i < s->n; i++) + give_back(c, s->reg[i]); + s->n = 0; +} + +static uint32_t +f32_bits(float f) +{ + uint32_t u; + + memcpy(&u, &f, 4); + return u; +} + +/* a constant's bits in a temporary made for this instruction */ +static struct usse_reg +constant_bits(struct comp *c, struct scratch *s, uint32_t u) +{ + struct usse_reg r = treg(c, scratch_take(c, s)); + + emit(c, usse_limm(r, u)); + return r; +} + +static struct usse_reg +constant(struct comp *c, struct scratch *s, float f) +{ + return constant_bits(c, s, f32_bits(f)); +} + +/* (M46) a constant from the program's pool in sa (plan_constants()), for an + * operand slot that reads sa; else made in a temporary as above */ +static struct usse_reg +constant_sa(struct comp *c, struct scratch *s, uint32_t u) +{ + for (unsigned k = 0; k < c->nkconst; k++) + if (c->kconst[2 * k] == u && !c->kconst[2 * k + 1]) + return usse_reg(USSE_SA, c->kconst_sa + 2 * k); + return constant_bits(c, s, u); +} + +/* The value a source reads, through moves, vectors, negation and absolute + * value (outermost first: an fabs keeps an outer negation, an fneg under an + * fabs does nothing). */ +static struct operand +resolve(nir_scalar s) +{ + struct operand o = { 0 }; + + for (;;) { + s = nir_scalar_chase_movs(s); + if (!nir_scalar_is_alu(s)) + break; + if (nir_scalar_alu_op(s) == nir_op_fneg) { + if (!o.abs) + o.neg = !o.neg; + } else if (nir_scalar_alu_op(s) == nir_op_fabs) { + o.abs = true; + } else { + break; + } + s = nir_scalar_chase_alu_src(s, 0); + } + o.id = s.def->index * 4 + s.comp; + if (nir_scalar_is_const(s)) { + /* (M44) the bits as they are -- an integer's, or a float's with the + * float modifiers applied to its sign bit */ + uint32_t u = (uint32_t)nir_scalar_as_uint(s); + + o.is_const = true; + u = o.abs ? u & 0x7fffffffu : u; + u = o.neg ? u ^ 0x80000000u : u; + o.u = u; + memcpy(&o.c, &u, 4); + o.neg = o.abs = false; + } + return o; +} + +static struct operand +alu_operand(nir_alu_instr *alu, unsigned i) +{ + return resolve(nir_get_scalar(alu->src[i].src.ssa, alu->src[i].swizzle[0])); +} + +/* (M46) a float constant V32NMAD's src1 swizzle makes -- 0, 1, 2, 0.5, + * either sign (the sign src1's negation): no LIMM for it. + * SGX_NO_KSWZ=1: as before */ +static bool +k_code(uint32_t u, unsigned *code, bool *neg) +{ + static int off = -1; + + if (off < 0) + off = getenv("SGX_NO_KSWZ") != NULL; + if (off) + return false; + *neg = u >> 31; + switch (u & 0x7fffffffu) { + case 0x00000000: *code = USSE_K_0; return true; + case 0x3f800000: *code = USSE_K_1; return true; + case 0x40000000: *code = USSE_K_2; return true; + case 0x3f000000: *code = USSE_K_HALF; return true; + default: return false; + } +} + +/* operand slots: what each takes without a move first */ +enum { + TAKES_NEG = 1 << 0, + TAKES_ABS = 1 << 1, + TAKES_LANE_Y = 1 << 2, + TAKES_SA = 1 << 3, + TAKES_ALL = TAKES_NEG | TAKES_ABS | TAKES_LANE_Y | TAKES_SA, +}; + +/* d = r with its modifiers applied, times one: (+-1) * |r| -- the one + * src1's swizzle constant, carrying r's negation (src2 takes none) */ +static uint64_t +times_one(struct comp *c, struct usse_reg d, struct usse_reg r, struct scratch *s) +{ + struct usse_reg one = r, x = r; + unsigned code; + bool neg; + + if (!k_code(f32_bits(1.0f), &code, &neg)) + return usse_fop(USSE_NMAD_MUL, d, r, constant(c, s, 1.0f)); + one.abs = false; + x.neg = false; + return usse_fop_sw(USSE_NMAD_MUL, d, one, USSE_SW_CONST(code), x); +} + +/* The register for an operand in a slot that takes what `takes` says: the + * value where it is, or a temporary made for this instruction. */ +static struct usse_reg +get(struct comp *c, struct operand o, unsigned takes, struct scratch *s) +{ + struct usse_reg r, t; + + if (o.is_const) + return takes & TAKES_SA ? constant_sa(c, s, o.u) : constant_bits(c, s, o.u); + r = c->loc[o.id]; + r.neg = o.neg; + r.abs = o.abs; + if ((r.neg && !(takes & TAKES_NEG)) || (r.abs && !(takes & TAKES_ABS)) || + ((r.num & 1) && !(takes & TAKES_LANE_Y)) || + (r.bank == USSE_SA && !(takes & TAKES_SA))) { + t = treg(c, scratch_take(c, s)); + if (r.neg || r.abs) /* the modifiers applied: times one */ + emit(c, times_one(c, t, r, s)); + else + emit(c, usse_fmov(t, r)); + return t; + } + return r; +} + +/* (M47) a value of a vector made in a row (plan_groups()): its register in + * its group's -- taken at the group's first value, the components that + * are not values given back -- false when it is none's (or there is no + * room for the group) */ +static bool +vgroup_member(struct comp *c, unsigned id, unsigned *r) +{ + struct vgroup *g; + unsigned k; + + if (!c->group_of || c->group_of[id] < 0) + return false; + g = &c->vgroups[c->group_of[id] / 4]; + k = c->group_of[id] % 4; + if (g->base == -1) { + g->base = block_try(c, g->n, 2); + if (g->base < 0) { + g->base = -2; + return false; + } + for (unsigned i = 0; i < g->n; i++) + if (!(g->mask & 1u << i)) + give_back(c, g->base + i); + } + if (g->base < 0) + return false; + *r = g->base + k; + c->loc[id] = treg(c, *r); + c->owned[id] = true; + if (c->last_use[id] < 0) { + give_back(c, *r); + c->owned[id] = false; + } + return true; +} + +/* the value an instruction makes, in a temporary of its own */ +static struct usse_reg +define(struct comp *c, nir_def *def) +{ + unsigned id = def->index * 4, r; + + for (unsigned i = 0; i < 4; i++) + if (c->colour_id[i] == (int)id) { + /* (the colour's registers taken at its first value: from the + * start they held four the program wanted -- 67 a pixel) */ + if (c->out_base == -1 && (c->out_base = block_try(c, 4, 2)) < 0) + c->out_base = -2; + if (c->out_base < 0) + break; + c->loc[id] = treg(c, c->out_base + i); + c->owned[id] = false; + return c->loc[id]; + } + if (c->vs_out && c->vs_out[id]) { + c->loc[id] = usse_reg(USSE_OUTPUT, c->vs_out[id] - 1); + c->owned[id] = false; + return c->loc[id]; + } + if (vgroup_member(c, id, &r)) + return c->loc[id]; + r = take(c); + + c->loc[id] = treg(c, r); + c->owned[id] = true; + if (c->last_use[id] < 0) { /* never read */ + give_back(c, r); + c->owned[id] = false; + } + return c->loc[id]; +} + +/* (M44) the same for a 32-bit word an integer instruction makes (VBW, + * I32MAD2, VMOV's INT32 moves, LIMM): any temporary, odd ones too -- a + * float instruction that wants lane x moves it first (get()). atan's + * copysign, bits, took 67 registers a pixel in even ones alone (dEQP's + * atan2.*_vec4_fragment) */ +static struct usse_reg +define_word(struct comp *c, nir_def *def) +{ + unsigned id = def->index * 4, r; + + if (vgroup_member(c, id, &r)) + return c->loc[id]; + r = block(c, 1, 1); + + c->loc[id] = treg(c, r); + c->owned[id] = true; + if (c->last_use[id] < 0) { + give_back(c, r); + c->owned[id] = false; + } + return c->loc[id]; +} + +/* d = op(a, b) into def's register -- or, def NULL, into dest */ +static void +binary_ops(struct comp *c, enum usse_nmad_op op, struct operand a, struct operand b, + nir_def *def, struct usse_reg dest, struct scratch *s) +{ + struct operand t; + struct usse_reg ra, rb; + unsigned code; + bool kneg; + + /* (M46) a constant 0, 1, 2 or 0.5 in src1's swizzle (all four commute), + * the other in src2 -- which takes no negation: a product's goes onto + * the constant */ + if (a.is_const && !b.is_const) { + t = a; + a = b; + b = t; + } + if (b.is_const && !a.is_const && k_code(b.u, &code, &kneg) && + (!a.neg || op == USSE_NMAD_MUL)) { + struct usse_reg k; + + if (a.neg) { + a.neg = false; + kneg = !kneg; + } + ra = get(c, a, TAKES_ALL & ~TAKES_NEG, s); + k = ra; + k.neg = kneg; + k.abs = false; + emit(c, usse_fop_sw(op, def ? define(c, def) : dest, k, USSE_SW_CONST(code), ra)); + return; + } + + /* the second source takes no negation: swap (all four commute), and + * a product of two negations is the product */ + if (b.neg && !a.neg) { + t = a; + a = b; + b = t; + } + if (op == USSE_NMAD_MUL && a.neg && b.neg) + a.neg = b.neg = false; + ra = get(c, a, TAKES_ALL, s); + rb = get(c, b, TAKES_ALL & ~TAKES_NEG, s); + emit(c, usse_fop(op, def ? define(c, def) : dest, ra, rb)); +} + +static void +binary(struct comp *c, enum usse_nmad_op op, nir_alu_instr *alu, struct scratch *s) +{ + binary_ops(c, op, alu_operand(alu, 0), alu_operand(alu, 1), &alu->def, usse_reg(USSE_TEMP, 0), + s); +} + +/* (M46) ffma (a vertex shader's: sgx_screen.c fuses them there): FMAD, + * d = src0 * src1 + src2 -- src0 a temporary or a primary attribute + * without negation (a product's sign goes onto src1), src1 and src2 + * anything with their modifiers, each its own lane */ +static void +fma_ops(struct comp *c, struct operand a, struct operand b, struct operand x, nir_def *def, + struct usse_reg dest, struct scratch *s) +{ + struct operand t; + struct usse_reg r0, r1, r2; + + /* src0: one in a register that is not sa */ + if (a.is_const || c->loc[a.id].bank == USSE_SA) { + t = a; + a = b; + b = t; + } + if (a.neg) { + a.neg = false; + if (b.is_const) { + b.u ^= 0x80000000u; + memcpy(&b.c, &b.u, 4); + } else { + b.neg = !b.neg; + } + } + r0 = get(c, a, TAKES_ABS | TAKES_LANE_Y, s); + r1 = get(c, b, TAKES_ALL, s); + r2 = get(c, x, TAKES_ALL, s); + emit(c, usse_fmad(def ? define(c, def) : dest, r0, r1, r2)); +} + +static void +fma_(struct comp *c, nir_alu_instr *alu, struct scratch *s) +{ + fma_ops(c, alu_operand(alu, 0), alu_operand(alu, 1), alu_operand(alu, 2), &alu->def, + usse_reg(USSE_TEMP, 0), s); +} + +/* ---- vector instructions (M47) --------------------------------------------- + * + * A vertex program's dot products (NIR's fdot2..4 and fdph, which the + * scalar lowering leaves whole in a vertex shader) as VDPs: dot(src1, i), + * one instruction -- src1 four registers in a row (a uniform's, an + * attribute's) through a swizzle of its own, the other vector in one of the + * three internal registers. That one is loaded there (V32NMAD's add of 0 + * to four lanes at once) and kept: the next dot product of it -- a vector + * times a matrix is three or four -- reads it where it is. The internal + * registers are the pipe's, not the task's: another task's program writes + * them between two of ours unless every instruction from the write to the + * last read has its nosched flag (usse_nosched(), set over each span when + * the code is made). */ + +/* (M47) the dot products a vertex shader keeps whole (vec_filter()) */ +static bool +is_dot(nir_op op) +{ + return op == nir_op_fdot2 || op == nir_op_fdot3 || op == nir_op_fdot4 || op == nir_op_fdph; +} + +static bool +same_operand(const struct operand *a, const struct operand *b) +{ + if (a->is_const || b->is_const) + return a->is_const && b->is_const && a->u == b->u; + return a->id == b->id && a->neg == b->neg && a->abs == b->abs; +} + +/* a constant as a channel of src1's swizzle (0, 1, 2, 0.5) */ +static bool +k_channel(const struct operand *o, unsigned *code) +{ + bool neg; + + return o->is_const && k_code(o->u, code, &neg) && !neg; +} + +/* the n operands as src1 of a VDP or a V32NMAD: their registers four in a + * row from an even one (the swizzle's x y z w), the constants 0, 1, 2 and + * 0.5 the swizzle's own, the same modifiers on all -- the first register + * (its modifiers) and the swizzle; false when they are not that */ +static bool +src1_group(struct comp *c, const struct operand *o, unsigned n, struct usse_reg *base, + unsigned *sw) +{ + int lo = -1, bank = -1; + bool neg = false, abs = false, any = false; + unsigned code; + + for (unsigned k = 0; k < n; k++) { + struct usse_reg r; + + if (o[k].is_const) + continue; + r = c->loc[o[k].id]; + if (r.bank != USSE_TEMP && r.bank != USSE_PA && r.bank != USSE_SA && + r.bank != USSE_OUTPUT) + return false; + if (any && (r.bank != bank || o[k].neg != neg || o[k].abs != abs)) + return false; + bank = r.bank; + neg = o[k].neg; + abs = o[k].abs; + any = true; + lo = lo < 0 ? r.num & ~1 : MIN2(lo, r.num & ~1); + } + *sw = 0; + for (unsigned k = 0; k < 4; k++) { + unsigned ch = USSE_K_0; + + if (k < n && o[k].is_const) { + /* (a negated vector negates its constants too: 0 only) */ + if (!k_channel(&o[k], &code) || (neg && o[k].u)) + return false; + ch = code; + } else if (k < n) { + unsigned d = c->loc[o[k].id].num - lo; + + if (d > 3) + return false; + ch = d; + } + *sw |= ch << 3 * k; + } + *base = any ? usse_reg(bank, lo) : usse_reg(USSE_TEMP, 0); + base->neg = neg; + base->abs = abs; + return true; +} + +static void +ireg_close(struct comp *c, unsigned k) +{ + struct ireg *r = &c->ireg[k]; + + if (r->valid && r->last > r->from) { + util_dynarray_append(&c->ispans, r->from); + util_dynarray_append(&c->ispans, r->last); + } + r->valid = false; +} + +/* every internal register forgotten: before a wait (WDF), which lets the + * pipe run other tasks whatever the flags say */ +static void +ireg_barrier(struct comp *c) +{ + for (unsigned k = 0; k < USSE_NINTERNAL; k++) + ireg_close(c, k); +} + +/* the internal register that holds o[k] in lane k for each k of mask, -1 + * none */ +static int +ireg_find(struct comp *c, const struct operand *o, unsigned mask) +{ + for (unsigned k = 0; k < USSE_NINTERNAL; k++) { + unsigned l; + + if (!c->ireg[k].valid) + continue; + for (l = 0; l < 4; l++) + if ((mask & 1u << l) && + (l >= c->ireg[k].n || !same_operand(&c->ireg[k].lane[l], &o[l]))) + break; + if (l == 4) + return k; + } + return -1; +} + +/* o[0..n-1] into an internal register's lanes: the one free, or the one + * read longest ago -- by one V32NMAD when they are four registers in a row + * (or constants of the swizzle's), else a lane at a time */ +static unsigned +ireg_load(struct comp *c, const struct operand *o, unsigned n, struct scratch *s) +{ + unsigned k = 0, sw; + struct usse_reg base; + + for (unsigned i = 1; i < USSE_NINTERNAL; i++) + if (c->ireg[k].valid && (!c->ireg[i].valid || c->ireg[i].last < c->ireg[k].last)) + k = i; + ireg_close(c, k); + c->ireg[k].from = here(c); + if (src1_group(c, o, n, &base, &sw)) { + emit(c, usse_fop_ex(USSE_NMAD_ADD, usse_ireg(k, 0), (1u << n) - 1, base, sw, USSE_ZERO, + USSE_SW2_X)); + } else { + for (unsigned l = 0; l < n; l++) { + struct usse_reg r; + unsigned code; + + if (k_channel(&o[l], &code)) { + emit(c, usse_fop_ex(USSE_NMAD_ADD, usse_ireg(k, l), 1u << l, usse_reg(USSE_TEMP, 0), + USSE_SW_CONST(code), USSE_ZERO, USSE_SW2_X)); + continue; + } + r = get(c, o[l], TAKES_ALL, s); + emit(c, usse_fop_ex(USSE_NMAD_ADD, usse_ireg(k, l), 1u << l, r, + (r.bank == USSE_SPECIAL ? 0 : r.num & 1) * 0x249, USSE_ZERO, + USSE_SW2_X)); + } + } + c->ireg[k].valid = true; + c->ireg[k].n = n; + memcpy(c->ireg[k].lane, o, n * sizeof(*o)); + c->ireg[k].last = c->ireg[k].from; + return k; +} + +/* the dot product of a[] and b[] (n components) as instructions of one + * lane: a product, products added to it (FMAD) -- where VDP cannot take + * them, or the program does not use the internal registers */ +static void +dot_scalar(struct comp *c, const struct operand *a, const struct operand *b, unsigned n, + nir_def *def, struct scratch *s) +{ + int terms[4], nt = 0; + struct usse_reg acc = usse_reg(USSE_TEMP, 0); + + for (unsigned k = 0; k < n; k++) + if (!(a[k].is_const && !(a[k].u & 0x7fffffffu)) && !(b[k].is_const && !(b[k].u & 0x7fffffffu))) + terms[nt++] = k; + if (!nt) { + emit(c, usse_limm(define(c, def), 0)); + return; + } + for (int i = 0; i < nt; i++) { + unsigned k = terms[i]; + bool last = i == nt - 1; + struct usse_reg d = last ? usse_reg(USSE_TEMP, 0) : treg(c, scratch_take(c, s)); + struct operand x; + + if (!i) { + binary_ops(c, USSE_NMAD_MUL, a[k], b[k], last ? def : NULL, d, s); + } else { + x = (struct operand){ 0 }; + /* (the sum so far: a temporary of this instruction's -- an + * operand of its own, through loc's spare entry) */ + x.id = c->spare; + c->loc[x.id] = acc; + fma_ops(c, a[k], b[k], x, last ? def : NULL, d, s); + } + acc = d; + } +} + +static void +dot_product(struct comp *c, nir_alu_instr *alu, struct scratch *s) +{ + struct operand a[4], b[4], one = { .is_const = true, .c = 1.0f, .u = 0x3f800000u }; + struct operand zero = { .is_const = true }; + unsigned n = nir_ssa_alu_instr_src_components(alu, 1), sw = 0, swg0 = USSE_SW2_XYZW, mask; + struct usse_reg base = usse_reg(USSE_TEMP, 0); + const struct operand *g; + bool dp4; + int k = -1; + + for (unsigned i = 0; i < n; i++) { + a[i] = i < nir_ssa_alu_instr_src_components(alu, 0) ? + resolve(nir_get_scalar(alu->src[0].src.ssa, alu->src[0].swizzle[i])) : one; + b[i] = resolve(nir_get_scalar(alu->src[1].src.ssa, alu->src[1].swizzle[i])); + } + /* (fdph: a's w the 1 above, dot(a.xyz, b.xyz) + b.w) */ + if (!c->vec) { + dot_scalar(c, a, b, n, &alu->def, s); + return; + } + if (n == 2) { + a[2] = b[2] = zero; + n = 3; + } + dp4 = n == 4; + /* gpi0: a vector an internal register holds already (a's with w 1 by + * the swizzle xyz1), the other src1; or the one not in sa loaded, the + * uniform the swizzle's (a vector times the columns of a matrix) */ + mask = (1u << n) - 1; + g = NULL; + if ((k = ireg_find(c, a, mask)) >= 0 && src1_group(c, b, n, &base, &sw)) { + g = a; + } else if (dp4 && same_operand(&a[3], &one) && (k = ireg_find(c, a, 7)) >= 0 && + src1_group(c, b, n, &base, &sw)) { + g = a; + swg0 = USSE_SWG_XYZ1; + } else if ((k = ireg_find(c, b, mask)) >= 0 && src1_group(c, a, n, &base, &sw)) { + g = b; + } else { + bool a_sa = true; + + for (unsigned i = 0; i < n; i++) + a_sa &= a[i].is_const || c->loc[a[i].id].bank == USSE_SA; + if (!a_sa && src1_group(c, b, n, &base, &sw)) + g = a; + else if (src1_group(c, a, n, &base, &sw)) + g = b; + else if (src1_group(c, b, n, &base, &sw)) + g = a; + if (!g) { + dot_scalar(c, a, b, n, &alu->def, s); + return; + } + /* (w 1 from the swizzle: three lanes loaded, which the next vector + * with that w finds too) */ + if (dp4 && same_operand(&g[3], &one)) { + k = ireg_load(c, g, 3, s); + swg0 = USSE_SWG_XYZ1; + } else { + k = ireg_load(c, g, n, s); + } + } + c->ireg[k].last = here(c); + /* (SGX_IREG_NOREUSE=1, a test: each dot product its own load) */ + if (getenv("SGX_IREG_NOREUSE")) { + c->ireg[k].last++; + ireg_close(c, k); + } + { + struct usse_reg d = define(c, &alu->def); + + emit(c, usse_vdp(d, 1u << (d.bank == USSE_INTERNAL ? d.num & 3 : d.num & 1), dp4, base, sw, + k, swg0)); + } +} + +static void fsat_ops(struct comp *c, struct operand o, nir_def *def, struct usse_reg dest, + struct scratch *s); + +/* (M47) a vertex shader's vector arithmetic -- fadd, fmul, fmin, fmax, ffma + * and fsat of two to four components, which the scalar lowering leaves + * whole there (vec_filter()) -- two lanes an instruction (V32NMAD, VMAD2 + * with a mask of x and y): the components made in registers in a row from + * an even one (or the output registers they are bound for), an instruction + * a pair, where each operand's half is a pair of registers in order or one + * value for both lanes (a uniform's, an attribute's, a vector made so, a + * scalar); else a lane at a time, as the scalar code. SGX_NO_VS_VEC2=1: a + * lane at a time always */ +static bool +is_vec_op(nir_op op) +{ + return op == nir_op_fadd || op == nir_op_fmul || op == nir_op_fmin || op == nir_op_fmax || + op == nir_op_ffma || op == nir_op_fsat; +} + +static struct usse_reg +op_reg(struct comp *c, const struct operand *o) +{ + struct usse_reg r = c->loc[o->id]; + + r.neg = o->neg; + r.abs = o->abs; + return r; +} + +/* whether two lanes' operand o[0], o[1] can be read as a pair by a source + * of a table's swizzle (V32NMAD's src2: VEC4_STD; VMAD2's three: each has + * xxxx yyyy zzzz wwww at 0..3, xyzw at 4): one value for both (a register's + * lane broadcast, a constant), or two registers in order from an even one. + * Negation: src0's and src2's take none -- neg_ok; sa: sa_ok */ +static bool +pair_ok(struct comp *c, const struct operand *o, bool neg_ok, bool sa_ok) +{ + struct usse_reg a, b; + + if (same_operand(&o[0], &o[1])) { + if (o[0].is_const) + return true; + a = op_reg(c, &o[0]); + return (neg_ok || !a.neg) && (sa_ok || a.bank != USSE_SA) && + (a.bank == USSE_TEMP || a.bank == USSE_PA || a.bank == USSE_SA || + a.bank == USSE_OUTPUT || a.bank == USSE_INTERNAL); + } + if (o[0].is_const || o[1].is_const || o[0].neg != o[1].neg || o[0].abs != o[1].abs) + return false; + a = op_reg(c, &o[0]); + b = op_reg(c, &o[1]); + return (neg_ok || !a.neg) && (sa_ok || a.bank != USSE_SA) && a.bank == b.bank && + (a.bank == USSE_TEMP || a.bank == USSE_PA || a.bank == USSE_SA || + a.bank == USSE_OUTPUT) && !(a.num & 1) && b.num == a.num + 1; +} + +/* pair_ok()'s register and swizzle (a constant made in a temporary) */ +static struct usse_reg +pair_get(struct comp *c, const struct operand *o, bool sa_ok, struct scratch *s, unsigned *sw) +{ + struct usse_reg r; + + if (same_operand(&o[0], &o[1])) { + r = o[0].is_const ? (sa_ok ? constant_sa(c, s, o[0].u) : constant_bits(c, s, o[0].u)) : + op_reg(c, &o[0]); + *sw = r.bank == USSE_INTERNAL ? r.num & 3 : r.num & 1; + return r; + } + *sw = 4; + return op_reg(c, &o[0]); +} + +/* o's negation moved: the constants' signs, the values' modifiers */ +static void +negate2(struct operand *o) +{ + for (unsigned l = 0; l < 2; l++) { + if (o[l].is_const) { + o[l].u ^= 0x80000000u; + memcpy(&o[l].c, &o[l].u, 4); + } else { + o[l].neg = !o[l].neg; + } + } +} + +/* d.xy = op(x, y), two lanes: one operand through src1's swizzle (any four + * registers in a row, constants), the other src2 as a pair */ +static bool +binary2(struct comp *c, enum usse_nmad_op op, struct usse_reg d, const struct operand *x, + const struct operand *y, struct scratch *s) +{ + for (int swap = 0; swap < 2; swap++) { + struct operand p[2] = { swap ? y[0] : x[0], swap ? y[1] : x[1] }; + struct operand q[2] = { swap ? x[0] : y[0], swap ? x[1] : y[1] }; + struct usse_reg r1, r2; + unsigned sw1, sw2; + + /* (src2 takes no negation: a product's onto src1) */ + if (!q[0].is_const && !q[1].is_const && q[0].neg && q[1].neg && op == USSE_NMAD_MUL) { + negate2(q); + negate2(p); + } + if (!src1_group(c, p, 2, &r1, &sw1) || !pair_ok(c, q, false, true)) + continue; + r2 = pair_get(c, q, true, s, &sw2); + emit(c, usse_fop_ex(op, d, 3, r1, sw1, r2, sw2)); + return true; + } + return false; +} + +/* d.xy = a * b + x, two lanes (VMAD2): src0 a or b in a temporary or a + * primary attribute, without negation */ +static bool +fma2(struct comp *c, struct usse_reg d, const struct operand *a, const struct operand *b, + const struct operand *x, struct scratch *s) +{ + for (int swap = 0; swap < 2; swap++) { + struct operand p[2] = { swap ? b[0] : a[0], swap ? b[1] : a[1] }; + struct operand q[2] = { swap ? a[0] : b[0], swap ? a[1] : b[1] }; + struct usse_reg r0, r1, r2; + unsigned sw0, sw1, sw2; + bool p_reg = !p[0].is_const && !p[1].is_const; + + if (p_reg && p[0].neg && p[1].neg) { + negate2(p); + negate2(q); + } + if (!pair_ok(c, p, false, false) || !pair_ok(c, q, true, true) || !pair_ok(c, x, true, true)) + continue; + if (p_reg) { + struct usse_reg r = op_reg(c, &p[0]); + + if (r.bank != USSE_TEMP && r.bank != USSE_PA && r.bank != USSE_INTERNAL) + continue; + } + r0 = pair_get(c, p, false, s, &sw0); + r1 = pair_get(c, q, true, s, &sw1); + r2 = pair_get(c, x, true, s, &sw2); + emit(c, usse_fmad_ex(d, 3, r0, sw0, r1, sw1, r2, sw2)); + return true; + } + return false; +} + +/* d.xy = fsat(x), two lanes: max with 0 (c0) through src1's swizzle (any + * modifiers), then min with 1 (src1's constant) of that pair */ +static bool +sat2(struct comp *c, struct usse_reg d, const struct operand *x, struct scratch *s) +{ + struct usse_reg r1, t; + unsigned sw1, code1; + bool n1; + int b; + + if (!src1_group(c, x, 2, &r1, &sw1) || !k_code(f32_bits(1.0f), &code1, &n1) || + (b = block_try(c, 2, 2)) < 0) + return false; + assert(s->n + 2 <= ARRAY_SIZE(s->reg)); + s->reg[s->n++] = b; + s->reg[s->n++] = b + 1; + t = treg(c, b); + emit(c, usse_fop_ex(USSE_NMAD_MAX, t, 3, r1, sw1, USSE_ZERO, USSE_SW2_X)); + emit(c, usse_fop_ex(USSE_NMAD_MIN, d, 3, t, USSE_SW_CONST(code1), t, USSE_SW2_XYZW)); + return true; +} + +/* the registers a vector's components are made in: the output registers + * the ones bound for one are (plan_vs_outputs()), the rest temporaries in a + * row from an even one; *base that block's first */ +static void +vec_dest(struct comp *c, nir_def *def, unsigned n, struct usse_reg *d, int *base) +{ + unsigned id = def->index * 4; + + /* (no room for them in a row: one each, as the scalar code's) */ + *base = block_try(c, n, 2); + for (unsigned l = 0; l < n; l++) { + if (c->vs_out && c->vs_out[id + l]) { + d[l] = usse_reg(USSE_OUTPUT, c->vs_out[id + l] - 1); + c->owned[id + l] = false; + } else { + d[l] = treg(c, *base >= 0 ? *base + l : take(c)); + c->owned[id + l] = true; + } + c->loc[id + l] = d[l]; + } +} + +static void +vector_alu(struct comp *c, nir_alu_instr *alu, struct scratch *s) +{ + static int off = -1; + unsigned n = alu->def.num_components, id = alu->def.index * 4; + unsigned nin = nir_op_infos[alu->op].num_inputs; + int base; + enum usse_nmad_op op = alu->op == nir_op_fadd ? USSE_NMAD_ADD : + alu->op == nir_op_fmul ? USSE_NMAD_MUL : + alu->op == nir_op_fmin ? USSE_NMAD_MIN : USSE_NMAD_MAX; + struct operand o[3][4]; + struct usse_reg d[4]; + + if (off < 0) + off = getenv("SGX_NO_VS_VEC2") != NULL; + for (unsigned i = 0; i < nin; i++) + for (unsigned l = 0; l < n; l++) + o[i][l] = resolve(nir_get_scalar(alu->src[i].src.ssa, alu->src[i].swizzle[l])); + vec_dest(c, &alu->def, n, d, &base); + for (unsigned l = 0; l < n; l += 2) { + bool done = false; + + if (!off && l + 1 < n && d[l].bank == d[l + 1].bank && !(d[l].num & 1) && + d[l + 1].num == d[l].num + 1) { + if (alu->op == nir_op_ffma) + done = fma2(c, d[l], &o[0][l], &o[1][l], &o[2][l], s); + else if (alu->op == nir_op_fsat) + done = sat2(c, d[l], &o[0][l], s); + else + done = binary2(c, op, d[l], &o[0][l], &o[1][l], s); + } + for (unsigned j = l; !done && j < MIN2(l + 2, n); j++) { + if (alu->op == nir_op_ffma) + fma_ops(c, o[0][j], o[1][j], o[2][j], NULL, d[j], s); + else if (alu->op == nir_op_fsat) + fsat_ops(c, o[0][j], NULL, d[j], s); + else + binary_ops(c, op, o[0][j], o[1][j], NULL, d[j], s); + } + scratch_give_back(c, s); + } + /* (the components nothing reads: their registers back; the block's + * for the ones bound for outputs too) */ + for (unsigned l = 0; l < n; l++) + if (c->owned[id + l] && c->last_use[id + l] < 0) { + give_back(c, d[l].num - (c->vs ? c->pa_base : 0)); + c->owned[id + l] = false; + } else if (!c->owned[id + l] && d[l].bank == USSE_OUTPUT && base >= 0) { + give_back(c, base + l); + } +} + +/* nosched over each span an internal register held something alive + * (struct comp's ispans) */ +static void +ireg_nosched(struct comp *c) +{ + static int tight = -1; + unsigned *span; + + if (tight < 0) + tight = getenv("SGX_IREG_TIGHT") != NULL; + ireg_barrier(c); + /* SGX_VS_NOSCHED_ALL=1 (a test): every instruction's */ + if (getenv("SGX_VS_NOSCHED_ALL")) { + for (unsigned i = 1; i < here(c); i++) + usse_nosched(util_dynarray_element(&c->code, uint64_t, i)); + return; + } + /* the instruction before the write and the last reader too: with the + * flag from the write to the one before the last read, a vertex + * program's dot products still read another task's vector now and then + * (glvsmath's ppsspp: 8 runs of 12 wrong, PPSSPP's three lights each + * reading the normal) -- 0 of 12 with either (M47). SGX_IREG_TIGHT=1: + * from the write to the one before the last read */ + for (span = util_dynarray_begin(&c->ispans); span < (unsigned *)util_dynarray_end(&c->ispans); + span += 2) + for (unsigned i = span[0] - (!tight && span[0] > 1); i < span[1] + !tight; i++) + if (!usse_nosched(util_dynarray_element(&c->code, uint64_t, i)) && + i >= span[0] && i < span[1]) + fail(c, "an instruction with no nosched flag known among the internal " + "registers' (%016llx)", + (unsigned long long)*util_dynarray_element(&c->code, uint64_t, i)); +} + +/* fsat: max with 0, min with 1 -- into def's register, or (def NULL) dest */ +static void +fsat_ops(struct comp *c, struct operand o, nir_def *def, struct usse_reg dest, struct scratch *s) +{ + unsigned code0, code1; + struct usse_reg a, t, d; + bool n0, n1; + + if (k_code(f32_bits(0.0f), &code0, &n0) && k_code(f32_bits(1.0f), &code1, &n1)) { + /* (M46) the bounds from src1's swizzle, the value in src2 */ + struct usse_reg k; + + a = get(c, o, TAKES_ALL & ~TAKES_NEG, s); + t = treg(c, scratch_take(c, s)); + k = a; + k.neg = k.abs = false; + emit(c, usse_fop_sw(USSE_NMAD_MAX, t, k, USSE_SW_CONST(code0), a)); + d = def ? define(c, def) : dest; + k = t; + emit(c, usse_fop_sw(USSE_NMAD_MIN, d, k, USSE_SW_CONST(code1), t)); + return; + } + a = get(c, o, TAKES_ALL, s); + t = treg(c, scratch_take(c, s)); + emit(c, usse_fop(USSE_NMAD_MAX, t, a, constant_sa(c, s, f32_bits(0.0f)))); + d = def ? define(c, def) : dest; + emit(c, usse_fop(USSE_NMAD_MIN, d, t, constant_sa(c, s, f32_bits(1.0f)))); +} + +static void +comparison(struct comp *c, nir_alu_instr *alu, struct scratch *s) +{ + struct operand a = alu_operand(alu, 0), b = alu_operand(alu, 1); + struct usse_reg diff = treg(c, scratch_take(c, s)), one, zero, ra, rb; + enum usse_test test = alu->op == nir_op_slt || alu->op == nir_op_sge ? + USSE_TEST_LT0 : USSE_TEST_EQ0; + bool swap = alu->op == nir_op_sge || alu->op == nir_op_sne; + uint64_t w; + + /* a - b = -b + a */ + b.neg = !b.neg; + if (b.is_const) + b.c = -b.c, b.u ^= 0x80000000u, b.neg = false; + ra = get(c, a, TAKES_ALL & ~TAKES_NEG, s); + rb = get(c, b, TAKES_ALL, s); + emit(c, usse_fop(USSE_NMAD_ADD, diff, rb, ra)); + one = constant(c, s, 1.0f); + zero = constant(c, s, 0.0f); + usse_fmovc(&w, test, define(c, &alu->def), diff, swap ? zero : one, swap ? one : zero); + emit(c, w); +} + +bool sgx_compiler_pixels_apart; + +static void +select_(struct comp *c, nir_alu_instr *alu, struct scratch *s) +{ + /* fcsel: c != 0 ? a : b -- a conditional move: no modifiers, one lane; + * the test not in sa (VMOV's first source read 0 from there, dEQP's + * select_iteration_count loops; iOS tests a uniform with VTST, M31) */ + struct usse_reg rc = get(c, alu_operand(alu, 0), 0, s); + struct usse_reg ra = get(c, alu_operand(alu, 1), TAKES_SA, s); + struct usse_reg rb = get(c, alu_operand(alu, 2), TAKES_SA, s); + uint64_t w; + + if (!usse_fmovc(&w, USSE_TEST_NE0, define(c, &alu->def), rc, ra, rb)) + fail(c, "a select's operands in different lanes"); + emit(c, w); +} + +/* ---- 32-bit integers (M44) ------------------------------------------------ + * + * NIR's integers, the hardware's own; booleans 0 and ~0 + * (nir_lower_bool_to_int32). Each instruction found on the device (glldr + * --probe; docs/research/p105-mesa.md, M44): I32MAD2 for sums, differences + * and products (it multiplies src1's low 16 bits, unsigned: a full product + * is two of them and two shifts), VBW for the bits and the shifts (by the + * count as it is: NIR's is taken modulo 32), VTST's integer subtraction for + * the comparisons -- right where the difference overflows -- into p0 and + * then the word under it, VMOV's INT32 moves for the selects, VPCK through + * 16-bit halves for the conversions. */ + +/* an operand as a 32-bit word: any register, any lane, a constant in a + * temporary */ +static struct usse_reg +word(struct comp *c, struct operand o, struct scratch *s) +{ + return get(c, o, TAKES_SA | TAKES_LANE_Y, s); +} + +/* the same, an immediate where it fits one (I32MAD2's and VTST's sources: + * 0..127) */ +static struct usse_reg +word_or_imm(struct comp *c, struct operand o, struct scratch *s) +{ + if (o.is_const && o.u < 128) + return usse_reg(USSE_IMM, o.u); + return word(c, o, s); +} + +/* the same for VMOV's INT32 moves, which name registers 0..63 -- and its + * test (src0) not in sa (M31's VMOV read 0 there); the constants 0 and ~0 + * are the hardware's own (c0, c56) */ +static struct usse_reg +word64(struct comp *c, struct operand o, bool test, struct scratch *s) +{ + struct usse_reg r, t; + + if (o.is_const && !test && (o.u == 0 || o.u == ~0u)) + return o.u ? USSE_ALL_ONES : USSE_ZERO; + r = word(c, o, s); + if (r.num < 64 && !(test && r.bank == USSE_SA)) + return r; + /* (M47) a value read where it is (a uniform past sa63, PPSSPP's + * u_cullRangeMax.w in four selects): moved into a temporary of its own + * once, which the reads after read, in a program's straight line */ + if (!o.is_const && !o.neg && !o.abs && c->depth == 0 && r.bank == c->loc[o.id].bank && + r.num == c->loc[o.id].num && !c->owned[o.id] && c->last_use[o.id] >= 0) { + int k = block_try(c, 1, 1); + + if (k >= 0 && k + (c->vs ? c->pa_base : 0) < 64) { + t = treg(c, k); + emit(c, usse_vbw_or(t, r, 0)); + c->loc[o.id] = t; + c->owned[o.id] = true; + return t; + } + if (k >= 0) + give_back(c, k); + } + t = treg(c, scratch_take(c, s)); + emit(c, usse_vbw_or(t, r, 0)); + return t; +} + +/* v as VBW's immediate: 16 bits, rotated left */ +static bool +vbw_immediate(uint32_t v, unsigned *imm, unsigned *rot) +{ + for (unsigned r = 0; r < 32; r++) { + uint32_t x = r ? v >> r | v << (32 - r) : v; + + if (x <= 0xffff) { + *imm = x; + *rot = r; + return true; + } + } + return false; +} + +/* the largest value source i of alu can have, unsigned (NIR's range + * analysis; a constant's own) */ +static uint32_t +upper_bound(struct comp *c, nir_alu_instr *alu, unsigned i) +{ + return nir_unsigned_upper_bound(c->nir, c->range, + nir_get_scalar(alu->src[i].src.ssa, alu->src[i].swizzle[0])); +} + +/* iadd, isub: src0 * 1 + src2, src2 negated for a difference */ +static void +int_add(struct comp *c, nir_alu_instr *alu, struct scratch *s) +{ + struct operand a = alu_operand(alu, 0), b = alu_operand(alu, 1), t; + struct usse_reg one = usse_reg(USSE_IMM, 1), ra, rb; + bool sub = alu->op == nir_op_isub; + + if (a.is_const && !b.is_const) { + /* the constant src2: b + a, or -b + a */ + t = a; + a = b; + b = t; + one.neg = sub; + sub = false; + } + ra = word(c, a, s); + rb = word_or_imm(c, b, s); + rb.neg = sub; + emit(c, usse_imad(define_word(c, &alu->def), ra, one, rb, true)); +} + +/* imul: one I32MAD2 when either operand fits its 16 bits, else a * hi16(b) + * shifted up, plus a * lo16(b) */ +static void +int_mul(struct comp *c, nir_alu_instr *alu, struct scratch *s) +{ + struct operand a = alu_operand(alu, 0), b = alu_operand(alu, 1), t; + uint32_t bound_a = upper_bound(c, alu, 0), bound_b = upper_bound(c, alu, 1); + struct usse_reg ra, rb, h; + + if (bound_b > 0xffff && bound_a <= 0xffff) { + t = a; + a = b; + b = t; + bound_b = bound_a; + } + ra = word(c, a, s); + if (bound_b <= 0xffff) { + rb = word_or_imm(c, b, s); + emit(c, usse_imad(define_word(c, &alu->def), ra, rb, usse_reg(USSE_IMM, 0), true)); + return; + } + rb = word(c, b, s); + h = treg(c, scratch_take(c, s)); + emit(c, usse_vbw_imm(USSE_VBW_SHR, h, rb, 16, 0)); + emit(c, usse_imad(h, ra, h, usse_reg(USSE_IMM, 0), true)); + emit(c, usse_vbw_imm(USSE_VBW_SHL, h, h, 16, 0)); + emit(c, usse_imad(define_word(c, &alu->def), ra, rb, h, true)); +} + +static void +bitwise(struct comp *c, nir_alu_instr *alu, struct scratch *s) +{ + enum usse_vbw_op op = alu->op == nir_op_iand ? USSE_VBW_AND : + alu->op == nir_op_ior ? USSE_VBW_OR : USSE_VBW_XOR; + struct operand a = alu_operand(alu, 0), b = alu_operand(alu, 1), t; + unsigned imm, rot; + struct usse_reg ra; + + if (a.is_const && !b.is_const) { + t = a; + a = b; + b = t; + } + ra = word(c, a, s); + if (b.is_const && vbw_immediate(b.u, &imm, &rot)) { + emit(c, usse_vbw_imm(op, define_word(c, &alu->def), ra, imm, rot)); + return; + } + { + struct usse_reg rb = word(c, b, s); + + emit(c, usse_vbw(op, define_word(c, &alu->def), ra, rb, false)); + } +} + +static void +shift(struct comp *c, nir_alu_instr *alu, struct scratch *s) +{ + enum usse_vbw_op op = alu->op == nir_op_ishl ? USSE_VBW_SHL : + alu->op == nir_op_ishr ? USSE_VBW_ASR : USSE_VBW_SHR; + struct operand b = alu_operand(alu, 1); + struct usse_reg ra = word(c, alu_operand(alu, 0), s), rb; + + if (b.is_const) { + emit(c, usse_vbw_imm(op, define_word(c, &alu->def), ra, b.u & 31, 0)); + return; + } + rb = word(c, b, s); + if (upper_bound(c, alu, 1) > 31) { + /* (the hardware shifts by the count as it is: 36 is all out) */ + struct usse_reg t = treg(c, scratch_take(c, s)); + + emit(c, usse_vbw_imm(USSE_VBW_AND, t, rb, 31, 0)); + rb = t; + } + emit(c, usse_vbw(op, define_word(c, &alu->def), ra, rb, false)); +} + +/* two F32 operands in one lane, for VTST: the one in lane y moved */ +static void +same_lane(struct comp *c, struct usse_reg *ra, struct usse_reg *rb, struct scratch *s) +{ + struct usse_reg *y, t; + + if ((ra->bank == USSE_SPECIAL || !(ra->num & 1)) == (rb->bank == USSE_SPECIAL || !(rb->num & 1))) + return; + y = ra->bank != USSE_SPECIAL && (ra->num & 1) ? ra : rb; + t = treg(c, scratch_take(c, s)); + emit(c, usse_fmov(t, *y)); + *y = t; +} + +/* a comparison into p0: integers by VTST's ISUB32 / ISUBU32, floats by its + * F32 subtraction; lt or eq -- the rest their inverse */ +static void +test_p0(struct comp *c, nir_alu_instr *alu, bool fl, bool is_signed, bool eq, struct scratch *s) +{ + struct operand a = alu_operand(alu, 0), b = alu_operand(alu, 1); + struct usse_reg ra, rb; + uint64_t w; + + /* an equality with an infinity (isinf: |x| == inf): its bits, as an + * integer's -- inf - inf is NaN, which no zero test passes */ + if (fl && eq && ((b.is_const && (b.u & 0x7fffffffu) == 0x7f800000u) || + (a.is_const && (a.u & 0x7fffffffu) == 0x7f800000u))) + fl = false; + if (!fl) { + /* (VTST's immediate is src2's alone, seven bits sign-extended: #64 + * is -64, and 3 < #100 false -- glldr --probe) */ + ra = word(c, a, s); + rb = b.is_const && (b.u < 64 || b.u >= 0xffffffc0u) ? usse_reg(USSE_IMM, b.u & 0x7f) : + word(c, b, s); + emit(c, usse_vtst_int(0, ra, rb, is_signed, eq)); + return; + } + ra = get(c, a, TAKES_SA | TAKES_LANE_Y, s); + rb = get(c, b, TAKES_SA | TAKES_LANE_Y, s); + same_lane(c, &ra, &rb, s); + if (!usse_vtst_f32(&w, 0, ra, rb, eq)) + fail(c, "a comparison's operands in different lanes"); + emit(c, w); +} + +static enum usse_cmp +float_cmp(nir_op op, bool *ok) +{ + *ok = true; + switch (op) { + case nir_op_flt32: return USSE_CMP_LT; + case nir_op_fge32: return USSE_CMP_GE; + case nir_op_feq32: return USSE_CMP_EQ; + case nir_op_fneu32: return USSE_CMP_NE; + default: *ok = false; return USSE_CMP_LT; + } +} + +/* whether operand o is now in register r's other lane (r's pair, the + * other half, the same bank and modifiers) -- or, r c0, the constant 0 */ +static bool +other_lane(struct comp *c, const struct operand *o, struct operand ref, struct usse_reg r, + int at) +{ + struct usse_reg q; + + if (r.bank == USSE_SPECIAL) + return o->is_const && !(o->u & 0x7fffffffu); + if (o->is_const || o->neg != ref.neg || o->abs != ref.abs || r.bank == USSE_INTERNAL || + c->def_at[o->id / 4] >= at) + return false; + q = c->loc[o->id]; + return q.bank == r.bank && q.num == (r.num ^ 1u); +} + +/* (M47) a float comparison soon after alu's (32 instructions on, in its + * block) of the same kind whose operands are the other lanes of ra's and + * rb's pairs, operands made already: VTSTMSK compares both lanes at once + * (PPSSPP's projPos.x < min.x, projPos.y < min.y) -- its def, or NULL */ +static nir_def * +pair_compare(struct comp *c, nir_alu_instr *alu, struct operand a, struct operand b, + struct usse_reg ra, struct usse_reg rb, enum usse_cmp cmp) +{ + static const enum usse_cmp swapped[] = { USSE_CMP_GT, USSE_CMP_GE, USSE_CMP_EQ, USSE_CMP_NE, + USSE_CMP_LE, USSE_CMP_LT }; + int at = c->def_at[alu->def.index]; + nir_instr *i = &alu->instr; + + if (!c->premade || ra.bank == USSE_SPECIAL || ra.num != c->loc[a.id].num || + ra.bank != c->loc[a.id].bank || + (rb.bank != USSE_SPECIAL && (b.is_const || rb.num != c->loc[b.id].num || + rb.bank != c->loc[b.id].bank))) + return NULL; + for (unsigned n = 0; n < 32 && (i = nir_instr_next(i)); n++) { + nir_alu_instr *x; + struct operand a2, b2, t; + enum usse_cmp k; + bool ok; + + if (i->type != nir_instr_type_alu) + continue; + x = nir_instr_as_alu(i); + k = float_cmp(x->op, &ok); + if (!ok || c->premade[x->def.index] || x->def.num_components != 1) + continue; + a2 = alu_operand(x, 0); + b2 = alu_operand(x, 1); + if (a2.is_const && !(a2.u & 0x7fffffffu) && !(b2.is_const && !(b2.u & 0x7fffffffu))) { + t = a2; + a2 = b2; + b2 = t; + k = swapped[k]; + } + if (k == cmp && other_lane(c, &a2, a, ra, at) && other_lane(c, &b2, b, rb, at)) + return &x->def; + } + return NULL; +} + +/* (M47) a float comparison as a boolean in one instruction: VTSTMSK's mask + * (~0 or 0) for each lane of a pair -- both written, so the result's + * register a pair of its own, the other half given back; 0 the hardware's + * c0 (either lane). SGX_NO_TSTMSK=1: VTST and two LIMMs as before */ +static bool +compare_mask(struct comp *c, nir_alu_instr *alu, struct scratch *s) +{ + static int off = -1; + static const enum usse_cmp swapped[] = { USSE_CMP_GT, USSE_CMP_GE, USSE_CMP_EQ, USSE_CMP_NE, + USSE_CMP_LE, USSE_CMP_LT }; + struct operand a = alu_operand(alu, 0), b = alu_operand(alu, 1), t; + enum usse_cmp cmp; + struct usse_reg ra, rb; + unsigned id = alu->def.index * 4, l; + int base; + + if (off < 0) + off = getenv("SGX_NO_TSTMSK") != NULL; + switch (alu->op) { + case nir_op_flt32: cmp = USSE_CMP_LT; break; + case nir_op_fge32: cmp = USSE_CMP_GE; break; + case nir_op_feq32: cmp = USSE_CMP_EQ; break; + case nir_op_fneu32: cmp = USSE_CMP_NE; break; + default: return false; + } + if (off) + return false; + /* (0 as src2, the constant's register c0; src1 negated, src2 not) */ + if (a.is_const && !(a.u & 0x7fffffffu) && !(b.is_const && !(b.u & 0x7fffffffu))) { + t = a; + a = b; + b = t; + cmp = swapped[cmp]; + } + if (b.neg || b.abs || a.abs) + return false; + ra = get(c, a, TAKES_SA | TAKES_LANE_Y | TAKES_NEG, s); + if (b.is_const && !(b.u & 0x7fffffffu)) { + rb = USSE_ZERO; + } else { + rb = get(c, b, TAKES_SA | TAKES_LANE_Y, s); + same_lane(c, &ra, &rb, s); + } + l = ra.bank == USSE_SPECIAL ? 0 : ra.num & 1; + if ((base = block_try(c, 2, 2)) < 0) + return false; + emit(c, usse_vtstmsk_f32(treg(c, base), ra, rb, cmp)); + c->loc[id] = treg(c, base + l); + c->owned[id] = c->last_use[id] >= 0; + if (!c->owned[id]) + give_back(c, base + l); + /* the other lane: a comparison after this one, the same, of the other + * lanes of these registers -- made here, skipped there */ + { + nir_def *other = pair_compare(c, alu, a, b, ra, rb, cmp); + unsigned oid; + + if (!other) { + give_back(c, base + 1 - l); + return true; + } + oid = other->index * 4; + c->loc[oid] = treg(c, base + 1 - l); + c->owned[oid] = c->last_use[oid] >= 0; + if (!c->owned[oid]) + give_back(c, base + 1 - l); + c->premade[other->index] = true; + } + return true; +} + +/* a comparison as a boolean: p0, then 0 or ~0 under it */ +static void +compare32(struct comp *c, nir_alu_instr *alu, struct scratch *s) +{ + bool fl = false, is_signed = true, eq = false, inv = false; + struct usse_reg d; + + if (compare_mask(c, alu, s)) + return; + + switch (alu->op) { + case nir_op_ilt32: break; + case nir_op_ige32: inv = true; break; + case nir_op_ult32: is_signed = false; break; + case nir_op_uge32: is_signed = false; inv = true; break; + case nir_op_ieq32: eq = true; break; + case nir_op_ine32: eq = inv = true; break; + case nir_op_flt32: fl = true; break; + case nir_op_fge32: fl = inv = true; break; + case nir_op_feq32: fl = eq = true; break; + default: fl = eq = inv = true; break; /* fneu32 */ + } + test_p0(c, alu, fl, is_signed, eq, s); + d = define_word(c, &alu->def); + emit(c, usse_limm(d, inv ? ~0u : 0)); + emit(c, usse_limm_pred(d, inv ? 0 : ~0u, 1)); +} + +/* imin, imax, umin, umax: a < b into p0, then one moved and the other + * under it */ +static void +min_max(struct comp *c, nir_alu_instr *alu, struct scratch *s) +{ + bool is_signed = alu->op == nir_op_imin || alu->op == nir_op_imax; + bool min = alu->op == nir_op_imin || alu->op == nir_op_umin; + struct usse_reg ra = word(c, alu_operand(alu, 0), s), rb = word(c, alu_operand(alu, 1), s); + struct usse_reg d; + + emit(c, usse_vtst_int(0, ra, rb, is_signed, false)); + d = define_word(c, &alu->def); + emit(c, usse_vbw_or(d, min ? rb : ra, 0)); + emit(c, usse_pred(usse_vbw_or(d, min ? ra : rb, 0), 1)); +} + +/* b32csel: c != 0 ? a : b, a 32-bit move whatever the words are */ +static void +select32(struct comp *c, nir_alu_instr *alu, struct scratch *s) +{ + struct usse_reg rc = word64(c, alu_operand(alu, 0), true, s); + struct usse_reg ra = word64(c, alu_operand(alu, 1), false, s); + struct usse_reg rb = word64(c, alu_operand(alu, 2), false, s); + uint64_t w; + + if (!usse_imovc(&w, USSE_TEST_NE0, define_word(c, &alu->def), rc, ra, rb)) + fail(c, "a select past register 63"); + emit(c, w); +} + +/* d = the integer r as F32: the two halves to F32, hi * 65536 + lo -- + * exact, rounded once */ +static void +emit_i2f(struct comp *c, struct usse_reg d, struct usse_reg r, bool is_signed) +{ + struct scratch s = { 0 }; + struct usse_reg hi = treg(c, scratch_take(c, &s)), lo = treg(c, scratch_take(c, &s)); + + emit(c, usse_cvt16_f32(hi, r, 1, is_signed)); + emit(c, usse_cvt16_f32(lo, r, 0, false)); + emit(c, usse_fmad(d, hi, constant(c, &s, 65536.0f), lo)); + scratch_give_back(c, &s); +} + +/* i2f32, u2f32 */ +static void +int_to_float(struct comp *c, nir_alu_instr *alu, struct scratch *s) +{ + struct usse_reg r = word(c, alu_operand(alu, 0), s); + + emit_i2f(c, define(c, &alu->def), r, alu->op == nir_op_i2f32); +} + +/* f2i32, f2u32: |x| truncated in F32 (|x| - fract |x|), split into its 16-bit + * halves -- hi = floor(t / 65536), lo = t - 65536 hi, both exact whole + * numbers -- packed into the word's halves by VPCK (which rounds: they are + * whole already), and the sign put back for f2i. f2i makes |x| larger by + * 2^-13 of itself first (1/16 at most), as lower_ftrunc() does: a whole + * number interpolated a little short is that number (M31: 24 comes as + * 23.9995) -- not f2u, which only nir_lower_idiv's reciprocal makes here. */ +static void +float_to_int(struct comp *c, nir_alu_instr *alu, struct scratch *s) +{ + bool is_signed = alu->op == nir_op_f2i32; + struct operand o = alu_operand(alu, 0); + struct usse_reg x = { 0 }, a, k, p, q, r, u, d; + + /* (f2i: x as it is, modifiers applied -- its sign tested at the end) */ + if (is_signed) + a = x = word64(c, o, true, s); + else + a = get(c, o, TAKES_ALL, s); + a.neg = false; + a.abs = true; + k = treg(c, scratch_take(c, s)); + p = treg(c, scratch_take(c, s)); + q = treg(c, scratch_take(c, s)); + r = treg(c, scratch_take(c, s)); + if (is_signed) { + emit(c, usse_limm(k, f32_bits(1.0f / (1 << 13)))); + emit(c, usse_fop(USSE_NMAD_MUL, p, a, k)); + emit(c, usse_limm(k, f32_bits(0.0625f))); + emit(c, usse_fop(USSE_NMAD_MIN, p, p, k)); + emit(c, usse_fop(USSE_NMAD_ADD, q, a, p)); + a = q; + } + emit(c, usse_fop(USSE_NMAD_FRC, p, a, a)); + p.neg = true; + emit(c, usse_fop(USSE_NMAD_ADD, r, p, a)); /* t */ + p.neg = false; + emit(c, usse_limm(k, f32_bits(1.0f / 65536.0f))); + emit(c, usse_fop(USSE_NMAD_MUL, p, r, k)); /* t / 65536 */ + emit(c, usse_fop(USSE_NMAD_FRC, q, p, p)); + q.neg = true; + emit(c, usse_fop(USSE_NMAD_ADD, p, q, p)); /* hi */ + q.neg = false; + emit(c, usse_limm(k, f32_bits(-65536.0f))); + emit(c, usse_fmad(q, p, k, r)); /* lo */ + u = is_signed ? r : define_word(c, &alu->def); + emit(c, usse_cvt_f32_16(u, q, 0, false)); + emit(c, usse_cvt_f32_16(u, p, 1, false)); + if (is_signed) { + struct usse_reg n = usse_reg(USSE_IMM, 1); + uint64_t w; + + n.neg = true; + emit(c, usse_imad(p, u, n, usse_reg(USSE_IMM, 0), true)); + d = define_word(c, &alu->def); + if (!usse_imovc(&w, USSE_TEST_LT0, d, x, p, u)) + fail(c, "a conversion past register 63"); + emit(c, w); + } +} + +/* the integer and boolean operations; false: not one */ +static bool +int_alu(struct comp *c, nir_alu_instr *alu, struct scratch *s) +{ + struct usse_reg ra, n; + uint64_t w; + + switch (alu->op) { + case nir_op_iadd: + case nir_op_isub: + int_add(c, alu, s); + return true; + case nir_op_ineg: + n = usse_reg(USSE_IMM, 1); + n.neg = true; + ra = word(c, alu_operand(alu, 0), s); + emit(c, usse_imad(define_word(c, &alu->def), ra, n, usse_reg(USSE_IMM, 0), true)); + return true; + case nir_op_iabs: + /* x < 0 ? -x : x */ + ra = word64(c, alu_operand(alu, 0), true, s); + n = usse_reg(USSE_IMM, 1); + n.neg = true; + { + struct usse_reg t = treg(c, scratch_take(c, s)); + + emit(c, usse_imad(t, ra, n, usse_reg(USSE_IMM, 0), true)); + if (!usse_imovc(&w, USSE_TEST_LT0, define_word(c, &alu->def), ra, t, ra)) + fail(c, "an iabs past register 63"); + emit(c, w); + } + return true; + case nir_op_imul: + int_mul(c, alu, s); + return true; + case nir_op_iand: + case nir_op_ior: + case nir_op_ixor: + bitwise(c, alu, s); + return true; + case nir_op_inot: + ra = word(c, alu_operand(alu, 0), s); + emit(c, usse_vbw(USSE_VBW_XOR, define_word(c, &alu->def), ra, USSE_ALL_ONES, false)); + return true; + case nir_op_ishl: + case nir_op_ishr: + case nir_op_ushr: + shift(c, alu, s); + return true; + case nir_op_imin: + case nir_op_imax: + case nir_op_umin: + case nir_op_umax: + min_max(c, alu, s); + return true; + case nir_op_ilt32: + case nir_op_ige32: + case nir_op_ult32: + case nir_op_uge32: + case nir_op_ieq32: + case nir_op_ine32: + case nir_op_flt32: + case nir_op_fge32: + case nir_op_feq32: + case nir_op_fneu32: + compare32(c, alu, s); + return true; + case nir_op_b32csel: + select32(c, alu, s); + return true; + case nir_op_b2f32: + /* ~0 & 1.0's bits */ + ra = word(c, alu_operand(alu, 0), s); + emit(c, usse_vbw_imm(USSE_VBW_AND, define_word(c, &alu->def), ra, 0x3f80, 16)); + return true; + case nir_op_b2i32: + ra = word(c, alu_operand(alu, 0), s); + emit(c, usse_vbw_imm(USSE_VBW_AND, define_word(c, &alu->def), ra, 1, 0)); + return true; + case nir_op_i2f32: + case nir_op_u2f32: + int_to_float(c, alu, s); + return true; + case nir_op_f2i32: + case nir_op_f2u32: + float_to_int(c, alu, s); + return true; + default: + return false; + } +} + +static void +alu(struct comp *c, nir_alu_instr *alu, struct scratch *s) +{ + struct usse_reg a, t; + + if (alu->op == nir_op_mov || alu->op == nir_op_fneg || alu->op == nir_op_fabs || + nir_op_is_vec(alu->op)) + return; /* read through by resolve() */ + if (c->premade && c->premade[alu->def.index]) + return; /* (made with another comparison) */ + if (is_dot(alu->op)) { + dot_product(c, alu, s); + return; + } + if (alu->def.num_components > 1 && is_vec_op(alu->op) && alu->def.bit_size == 32) { + vector_alu(c, alu, s); + return; + } + if (alu->def.bit_size != 32 || alu->def.num_components != 1) { + fail(c, "%s: %u x %u bits", nir_op_infos[alu->op].name, alu->def.num_components, + alu->def.bit_size); + return; + } + if (int_alu(c, alu, s)) + return; + switch (alu->op) { + case nir_op_fadd: binary(c, USSE_NMAD_ADD, alu, s); return; + case nir_op_fmul: binary(c, USSE_NMAD_MUL, alu, s); return; + case nir_op_fmin: binary(c, USSE_NMAD_MIN, alu, s); return; + case nir_op_fmax: binary(c, USSE_NMAD_MAX, alu, s); return; + case nir_op_ffma: fma_(c, alu, s); return; + case nir_op_frcp: + case nir_op_frsq: + case nir_op_flog2: + case nir_op_fexp2: + a = get(c, alu_operand(alu, 0), TAKES_ALL, s); + emit(c, usse_fcomp(alu->op == nir_op_frcp ? USSE_COMP_RCP : + alu->op == nir_op_frsq ? USSE_COMP_RSQ : + alu->op == nir_op_flog2 ? USSE_COMP_LOG2 : USSE_COMP_EXP2, + define(c, &alu->def), a)); + return; + case nir_op_fsqrt: /* 1 / (1 / sqrt x): 0 for 0, where x * rsq x is not */ + a = get(c, alu_operand(alu, 0), TAKES_ALL, s); + t = treg(c, scratch_take(c, s)); + emit(c, usse_fcomp(USSE_COMP_RSQ, t, a)); + emit(c, usse_fcomp(USSE_COMP_RCP, define(c, &alu->def), t)); + return; + case nir_op_ffract: + a = get(c, alu_operand(alu, 0), TAKES_LANE_Y | TAKES_SA, s); + emit(c, usse_fop(USSE_NMAD_FRC, define(c, &alu->def), a, a)); + return; + case nir_op_fsat: + fsat_ops(c, alu_operand(alu, 0), &alu->def, usse_reg(USSE_TEMP, 0), s); + return; + case nir_op_slt: + case nir_op_sge: + case nir_op_seq: + case nir_op_sne: + comparison(c, alu, s); + return; + case nir_op_fcsel: + select_(c, alu, s); + return; + default: + fail(c, "no %s yet", nir_op_infos[alu->op].name); + return; + } +} + +static bool uniform_word(struct comp *c, nir_intrinsic_instr *in, unsigned *at); + +/* an operand into a given register (any lane) */ +static void +move_into(struct comp *c, struct usse_reg d, struct operand o, struct scratch *s) +{ + struct usse_reg r; + + if (o.is_const) { + emit(c, usse_limm(d, o.u)); + return; + } + r = c->loc[o.id]; + r.neg = o.neg; + r.abs = o.abs; + if (r.neg || r.abs) /* the modifiers applied: times one */ + emit(c, times_one(c, d, r, s)); + else + emit(c, usse_fmov(d, r)); +} + +static struct operand +tex_operand(nir_tex_instr *tex, int src, unsigned comp) +{ + return resolve(nir_get_scalar(tex->src[src].src.ssa, comp)); +} + +/* (M44) textureSize (its level 0: nir_lower_tex's lower_txs_lod does the + * rest) and textureQueryLevels: the words the draw puts in sa (size_sa) -- + * no instruction */ +static void +texture_size(struct comp *c, nir_tex_instr *tex) +{ + unsigned id = tex->def.index * 4, z; + + if (tex->texture_index >= MAX_UNITS || c->slot_of_unit[tex->texture_index] < 0 || + c->size_sa < 0) { + fail(c, "a texture's size for a texture not sampled"); + return; + } + z = c->size_sa + SGX_FS_SIZE_WORDS * c->slot_of_unit[tex->texture_index]; + for (unsigned i = 0; i < tex->def.num_components; i++) { + c->loc[id + i] = usse_reg(USSE_SA, z + (tex->op == nir_texop_query_levels ? 2 : MIN2(i, 1))); + c->owned[id + i] = false; + } +} + +/* (M44) texelFetch's coordinates as the sampler takes them: each whole + * number's texel centre over its level's size, (x + 0.5) / max(w >> lod, + * 1) -- at level 0 x * (1 / w) + 0.5 / w, both words the draw's -- into a + * pair; the level, a float, into lodreg, sampled at it */ +static void +txf_coords(struct comp *c, nir_tex_instr *tex, struct scratch *s, struct usse_reg *coords, + struct usse_reg *lodreg) +{ + int ci = nir_tex_instr_src_index(tex, nir_tex_src_coord); + int li = nir_tex_instr_src_index(tex, nir_tex_src_lod); + struct operand lod = li >= 0 ? tex_operand(tex, li, 0) : (struct operand){ .is_const = true }; + unsigned z = c->size_sa + SGX_FS_SIZE_WORDS * c->slot_of_unit[tex->texture_index]; + unsigned pair = block(c, 2, 2); + bool level0 = lod.is_const && lod.u == 0; + + for (unsigned i = 0; i < 2; i++) { + struct usse_reg u = treg(c, pair + i), x; + + s->reg[s->n++] = pair + i; + x = i < tex->coord_components ? word(c, tex_operand(tex, ci, i), s) : constant_bits(c, s, 0); + emit_i2f(c, u, x, true); + if (level0) { + emit(c, usse_fmad(u, u, usse_reg(USSE_SA, z + 4 + i), usse_reg(USSE_SA, z + 6 + i))); + } else { + struct scratch t = { 0 }; + struct usse_reg w = treg(c, scratch_take(c, &t)), l = word(c, lod, &t); + + emit(c, usse_vbw(USSE_VBW_SHR, w, usse_reg(USSE_SA, z + i), l, false)); + emit(c, usse_vtst_int(0, w, usse_reg(USSE_IMM, 1), true, false)); + emit(c, usse_limm_pred(w, 1, 1)); + emit_i2f(c, w, w, false); + emit(c, usse_fcomp(USSE_COMP_RCP, w, w)); + emit(c, usse_fop(USSE_NMAD_ADD, u, u, constant(c, &t, 0.5f))); + emit(c, usse_fop(USSE_NMAD_MUL, u, u, w)); + scratch_give_back(c, &t); + } + } + *coords = treg(c, pair); + *lodreg = treg(c, scratch_take(c, s)); + if (level0) + emit(c, usse_limm(*lodreg, 0)); + else + emit_i2f(c, *lodreg, word(c, lod, s), true); +} + +/* texture2D and textureCube, with a bias or a level: the coordinates into + * registers in a row (a pair; a cube map's direction three), SMP for the + * texel, wait for it. The texture's four state words are in sa, after the + * uniforms (the draw puts them there, sgx_draw.c). (M44) And texelFetch: + * txf_coords() */ +static void +texture(struct comp *c, nir_tex_instr *tex, struct scratch *s) +{ + int coord = nir_tex_instr_src_index(tex, nir_tex_src_coord); + int bias = nir_tex_instr_src_index(tex, nir_tex_src_bias); + int lod = nir_tex_instr_src_index(tex, nir_tex_src_lod); + enum usse_smp_lod mode = USSE_SMP_NONE; + struct usse_reg coords; + struct usse_reg lodreg = treg(c, 0); + unsigned pair, d, id = tex->def.index * 4; + bool cube = tex->sampler_dim == GLSL_SAMPLER_DIM_CUBE; + unsigned ncoord = cube ? 3 : 2; + uint64_t (*smp)(enum usse_smp_out, enum usse_smp_coord, struct usse_reg, struct usse_reg, + struct usse_reg, enum usse_smp_lod, struct usse_reg) = + cube ? usse_smp3d : usse_smp2d; + + if (tex->op == nir_texop_txs || tex->op == nir_texop_query_levels) { + texture_size(c, tex); + return; + } + for (unsigned k = 0; k < c->nfetch; k++) { + if (c->fetch[k] != tex) + continue; + /* the PDS's lookup (M35): the texel in the primary attribute after + * the inputs, as it is -- two VPCKs to F32 0..1 */ + d = block(c, 4, 4); + emit(c, usse_unpack_unorm8(treg(c, d), + usse_reg(USSE_PA, 4 * c->ninputs + c->ncolours + k), 0)); + emit(c, usse_unpack_unorm8(treg(c, d + 2), + usse_reg(USSE_PA, 4 * c->ninputs + c->ncolours + k), 2)); + goto out; + } + /* (a rectangle texture's coordinates are scaled by now: load_texture_scale, + * and the dimension left as it was) */ + if ((tex->op != nir_texop_tex && tex->op != nir_texop_txb && tex->op != nir_texop_txl && + tex->op != nir_texop_txf) || + (tex->sampler_dim != GLSL_SAMPLER_DIM_2D && tex->sampler_dim != GLSL_SAMPLER_DIM_EXTERNAL && + tex->sampler_dim != GLSL_SAMPLER_DIM_RECT && !cube) || + (tex->op == nir_texop_txf && (cube || c->size_sa < 0)) || + tex->is_shadow || tex->is_array || + coord < 0 || tex->texture_index >= MAX_UNITS || + c->slot_of_unit[tex->texture_index] < 0) { + fail(c, "no such texture lookups yet"); + return; + } + if (tex->op == nir_texop_txf) { + txf_coords(c, tex, s, &coords, &lodreg); + mode = USSE_SMP_LOD; + goto sample; + } + /* the coordinates where they are when they are registers in a row + * from an even one -- a varying's x and y (M34) -- else moved there */ + { + struct operand o0 = tex_operand(tex, coord, 0); + bool in_place = true; + + for (unsigned i = 0; i < ncoord && in_place; i++) { + struct operand o = tex_operand(tex, coord, i); + + in_place = !o.is_const && !o.neg && !o.abs && c->loc[o.id].bank == USSE_PA && + !(c->loc[o0.id].num & 1) && c->loc[o.id].num == c->loc[o0.id].num + i; + } + if (in_place) { + coords = c->loc[o0.id]; + } else { + pair = block(c, ncoord, 2); + for (unsigned i = 0; i < ncoord; i++) { + s->reg[s->n++] = pair + i; + move_into(c, treg(c, pair + i), tex_operand(tex, coord, i), s); + } + coords = treg(c, pair); + } + } + if (bias >= 0 || lod >= 0) { + /* (a bias where the pixels run each on their own: the level the bias + * names, from level 0 -- see below) */ + mode = bias >= 0 && !c->divergent ? USSE_SMP_BIAS : USSE_SMP_LOD; + lodreg = treg(c, scratch_take(c, s)); + move_into(c, lodreg, tex_operand(tex, bias >= 0 ? bias : lod, 0), s); + } else if (c->divergent) { + /* A program whose pixels each run on their own: a lookup with its + * level of detail from the 2x2 block hangs the GPU or reads the wrong + * level (the block's pixels are not there together) -- level 0 + * (exact for a texture without levels whose filters agree; GLSL + * leaves the derivatives undefined where pixels part, M33) */ + mode = USSE_SMP_LOD; + lodreg = constant(c, s, 0.0f); + mesa_logw_once("sgx: a texture sampled in a program whose branches differ between " + "pixels: level 0"); + } +sample: + d = block(c, 4, 4); + if (c->fs->blend.tex_f16 >> tex->texture_index & 1) { + /* (M43) a copy of half floats: four F32 back, as they are */ + emit(c, smp(USSE_SMP_F32, USSE_SMP_COORD_F32, treg(c, d), coords, + usse_reg(USSE_SA, c->sampler_sa + 4 * c->slot_of_unit[tex->texture_index]), + mode, lodreg)); + emit(c, USSE_WDF0); + } else if (getenv("SGX_TEX_F32")) { + emit(c, smp(USSE_SMP_F32, USSE_SMP_COORD_F32, treg(c, d), + coords, + usse_reg(USSE_SA, c->sampler_sa + 4 * c->slot_of_unit[tex->texture_index]), + mode, lodreg)); + emit(c, USSE_WDF0); + /* the sampler hands an 8-bit channel back as its integer value + * (0..255, checked with gltex): to 0..1 (the copy it reads is always + * RGBA8) */ + struct usse_reg k = constant(c, s, 1.0f / 255.0f); + + for (unsigned i = 0; i < 4; i++) + if (i < tex->def.num_components && c->last_use[id + i] >= 0) + emit(c, usse_fop(USSE_NMAD_MUL, treg(c, d + i), + treg(c, d + i), k)); + } else { + /* the texel as it is, four bytes in one register (the copy it reads + * is always RGBA8), then two VPCKs to F32 0..1 -- not four F32s + * scaled by 1/255 one by one (M25) */ + struct usse_reg raw = treg(c, scratch_take(c, s)); + + emit(c, smp(USSE_SMP_RAW, USSE_SMP_COORD_F32, raw, coords, + usse_reg(USSE_SA, c->sampler_sa + 4 * c->slot_of_unit[tex->texture_index]), + mode, lodreg)); + emit(c, USSE_WDF0); + if (c->fs->blend.tex_depth >> tex->texture_index & 1) { + /* a depth texture's texel is F32 (M37): d, 0, 0, 1 through the + * view's swizzle (a shadow lookup's comparison has its own) */ + const uint8_t *swz = c->fs->blend.depth_swizzle[tex->texture_index]; + bool shadow_done = c->fs->blend.tex_shadow >> tex->texture_index & 1; + + for (unsigned i = 0; i < 4; i++) { + unsigned w = shadow_done ? PIPE_SWIZZLE_X : swz[i]; + + if (w == PIPE_SWIZZLE_X) + emit(c, usse_fmov(treg(c, d + i), raw)); + else + emit(c, usse_fmov(treg(c, d + i), constant(c, s, w == PIPE_SWIZZLE_W || + w == PIPE_SWIZZLE_1 ? 1.0f : 0.0f))); + } + } else { + emit(c, usse_unpack_unorm8(treg(c, d), raw, 0)); + emit(c, usse_unpack_unorm8(treg(c, d + 2), raw, 2)); + } + } + c->smp = true; +out: + for (unsigned i = 0; i < 4; i++) { + c->loc[id + i] = treg(c, d + i); + c->owned[id + i] = i < tex->def.num_components && c->last_use[id + i] >= 0; + if (!c->owned[id + i]) + give_back(c, d + i); + } +} + +/* a varying the vertex side hands over as it does the generic ones: the + * colours, fog, texture coordinates -- and the back colours (M37: st's + * nir_lower_two_sided_color picks them by gl_FrontFacing in the program) */ +static bool +colour_or_generic(int slot) +{ + return slot >= VARYING_SLOT_VAR0 || + (slot >= VARYING_SLOT_COL0 && slot <= VARYING_SLOT_TEX7) || + slot == VARYING_SLOT_BFC0 || slot == VARYING_SLOT_BFC1; +} + +/* a fragment shader input's varying slot, -1 if it is not a varying read + * at a constant offset */ +static int +input_slot(nir_intrinsic_instr *in) +{ + nir_src *offset; + + if (in->intrinsic == nir_intrinsic_load_frag_coord) + return VARYING_SLOT_POS; + if (in->intrinsic != nir_intrinsic_load_input) + return -1; + offset = nir_get_io_offset_src(in); + if (!nir_src_is_const(*offset)) + return -1; + return nir_intrinsic_io_semantics(in).location + nir_src_as_uint(*offset); +} + +/* A lookup the PDS can make (M35): a 2D texture, the level of detail its + * own, at x and y of a varying as the PDS iterates it -- what iOS's driver + * does for them (corpus s00..s04, s11). Its varying's slot. */ +static int +fixed_index(const struct comp *c, const nir_tex_instr *tex) +{ + for (unsigned i = 0; i < c->nfixed; i++) + if (c->fixed[i] == tex) + return i; + return -1; +} + +static int +fetch_slot(const struct comp *c, nir_tex_instr *tex, unsigned *shift) +{ + int coord = nir_tex_instr_src_index(tex, nir_tex_src_coord), slot = -1; + + /* (a rectangle texture's: when the vertex side scales the coordinates) */ + if (tex->op != nir_texop_tex || tex->is_shadow || tex->is_array || tex->num_srcs != 1 || + (tex->sampler_dim != GLSL_SAMPLER_DIM_2D && + tex->sampler_dim != GLSL_SAMPLER_DIM_EXTERNAL && + (tex->sampler_dim != GLSL_SAMPLER_DIM_RECT || fixed_index(c, tex) < 0)) || + coord < 0 || tex->coord_components != 2 || tex->texture_index >= MAX_UNITS) + return -1; + for (unsigned i = 0; i < 2; i++) { + nir_scalar x = nir_scalar_chase_movs(nir_get_scalar(tex->src[coord].src.ssa, i)); + nir_intrinsic_instr *in; + int at; + + if (!nir_def_is_intrinsic(x.def) || + (in = nir_def_as_intrinsic(x.def))->intrinsic != nir_intrinsic_load_input) + return -1; + at = input_slot(in); + /* (M46) x and y, or two components further on (SGX_FIX_SHIFT) */ + if (!i) + *shift = nir_intrinsic_component(in) + x.comp; + if (at < 0 || !colour_or_generic(at) || *shift > 2 || + nir_intrinsic_component(in) + x.comp != *shift + i || (i && at != slot) || + (*shift && (fixed_index(c, tex) >= 0 || getenv("SGX_NO_SHIFT")))) + return -1; + slot = at; + } + return slot; +} + +/* ---- coordinates the vertex side makes ready (M39) ------------------------ + * + * A projective lookup's coordinates (texture2DProj, the fixed function's + * TXP: x and y times 1 / z or w, NIR's lower_txp) and a rectangle + * texture's (x and y times 1 / its size, load_texture_scale), at a varying + * that nothing else reads: the lookup is made at the varying's x and y as + * they are, the PDS's -- its projective kind divides them -- and the + * vertex side does the rest to the varying (SGX_FIX_*: sgx_fs.vary_fix). + * xfwm4's composition, the fixed function's texture2DRect of TEX0 / + * TEX0.w, is one texel then. */ + +/* a varying's component, as a load_input's scalar: its slot and which */ +static bool +input_component(nir_scalar s, int *slot, unsigned *comp) +{ + nir_intrinsic_instr *in; + int at; + + if (!nir_scalar_is_intrinsic(s) || + (in = nir_def_as_intrinsic(s.def))->intrinsic != nir_intrinsic_load_input || + (at = input_slot(in)) < 0 || !colour_or_generic(at) || (*slot >= 0 && at != *slot)) + return false; + *slot = at; + *comp = nir_intrinsic_component(in) + s.comp; + return true; +} + +/* coordinate i of tex, a product: of the varying's component i (bit 0 of + * have), the texture's scale's i (bit 1), 1 / the varying's z or w (bit 2, + * which in *div) -- each once, nothing else */ +static bool +coord_factors(nir_scalar s, unsigned i, const nir_tex_instr *tex, unsigned *have, int *slot, + unsigned *div, unsigned depth) +{ + unsigned comp; + + s = nir_scalar_chase_movs(s); + if (depth > 4) + return false; + if (nir_scalar_is_alu(s) && nir_scalar_alu_op(s) == nir_op_fmul) + return coord_factors(nir_scalar_chase_alu_src(s, 0), i, tex, have, slot, div, depth + 1) && + coord_factors(nir_scalar_chase_alu_src(s, 1), i, tex, have, slot, div, depth + 1); + if (nir_scalar_is_alu(s) && nir_scalar_alu_op(s) == nir_op_frcp) { + if ((*have & 4) || + !input_component(nir_scalar_chase_movs(nir_scalar_chase_alu_src(s, 0)), slot, &comp) || + comp < 2 || comp > 3 || (*div && *div != comp)) + return false; + *div = comp; + *have |= 4; + return true; + } + if (nir_scalar_is_intrinsic(s) && + nir_def_as_intrinsic(s.def)->intrinsic == nir_intrinsic_load_texture_scale) { + nir_intrinsic_instr *in = nir_def_as_intrinsic(s.def); + + if ((*have & 2) || tex->sampler_dim != GLSL_SAMPLER_DIM_RECT || + !nir_src_is_const(in->src[0]) || nir_src_as_uint(in->src[0]) != tex->texture_index || + s.comp != i) + return false; + *have |= 2; + return true; + } + if ((*have & 1) || !input_component(s, slot, &comp) || comp != i) + return false; + *have |= 1; + return true; +} + +/* def's every use, through ALU instructions, ends in the coordinates of + * one of the lookups tex[] */ +static bool +feeds_only(nir_def *def, nir_tex_instr *const *tex, unsigned n, unsigned depth) +{ + if (depth > 6) + return false; + nir_foreach_use_including_if(src, def) { + nir_instr *p; + bool ok = false; + + if (nir_src_is_if(src)) + return false; + p = nir_src_use_instr(src); + if (p->type == nir_instr_type_alu) { + if (!feeds_only(&nir_instr_as_alu(p)->def, tex, n, depth + 1)) + return false; + continue; + } + for (unsigned k = 0; k < n && !ok; k++) + ok = p == &tex[k]->instr; + if (!ok) + return false; + } + return true; +} + +static void +lower_fetch_coords(struct comp *c, nir_shader *s, nir_function_impl *impl) +{ + nir_tex_instr *cand[SGX_FRAME_MAX_FETCH]; + int cand_slot[SGX_FRAME_MAX_FETCH]; + uint8_t cand_fix[SGX_FRAME_MAX_FETCH]; + unsigned ncand = 0, nplain = 0; + bool progress = false; + + if (getenv("SGX_NOFETCH") || getenv("SGX_NO_PROJ_FETCH")) + return; + nir_foreach_block(block, impl) { + nir_foreach_instr(instr, block) { + nir_tex_instr *tex; + unsigned have[2] = { 0, 0 }, div = 0, fix; + int coord, slot = -1; + + if (instr->type != nir_instr_type_tex) + continue; + tex = nir_instr_as_tex(instr); + coord = nir_tex_instr_src_index(tex, nir_tex_src_coord); + if (tex->op != nir_texop_tex || tex->is_shadow || tex->is_array || + tex->num_srcs != 1 || coord < 0 || tex->coord_components != 2 || + tex->texture_index >= MAX_UNITS || + ((c->fs->blend.tex_depth | c->fs->blend.tex_f16) >> tex->texture_index & 1) || + (tex->sampler_dim != GLSL_SAMPLER_DIM_2D && + tex->sampler_dim != GLSL_SAMPLER_DIM_EXTERNAL && + tex->sampler_dim != GLSL_SAMPLER_DIM_RECT)) + continue; + for (unsigned i = 0; i < 2; i++) + if (!coord_factors(nir_get_scalar(tex->src[coord].src.ssa, i), i, tex, &have[i], + &slot, &div, 0)) + have[0] = 0; + if (!(have[0] & 1) || !(have[1] & 1) || ((have[0] ^ have[1]) & 6) || + (tex->sampler_dim == GLSL_SAMPLER_DIM_RECT && !(have[0] & 2)) || c->flat[slot]) + continue; + fix = (have[0] & 2 ? SGX_FIX_SCALE : 0) | (have[0] & 4 ? div : 0); + if (!fix) { + nplain++; /* the PDS's already */ + continue; + } + if (ncand == SGX_FRAME_MAX_FETCH) + continue; + cand[ncand] = tex; + cand_slot[ncand] = slot; + cand_fix[ncand++] = fix; + } + } + for (unsigned k = 0; k < ncand; k++) { + nir_tex_instr *same[SGX_FRAME_MAX_FETCH]; + nir_intrinsic_instr *first = NULL; + unsigned n = 0; + bool ok = cand[k] != NULL && nplain + c->nfixed < SGX_FRAME_MAX_FETCH; + + if (!cand[k]) + continue; + /* every lookup of the varying the same (and the same texture's + * scale), nothing else reading it */ + for (unsigned j = k; j < ncand; j++) + if (cand[j] && cand_slot[j] == cand_slot[k]) { + ok &= cand_fix[j] == cand_fix[k] && + (!(cand_fix[k] & SGX_FIX_SCALE) || + cand[j]->texture_index == cand[k]->texture_index); + same[n++] = cand[j]; + } + nir_foreach_block(block, impl) { + nir_foreach_instr(instr, block) { + nir_intrinsic_instr *in; + + if (!ok || instr->type != nir_instr_type_intrinsic || + (in = nir_instr_as_intrinsic(instr))->intrinsic != nir_intrinsic_load_input || + input_slot(in) != cand_slot[k]) + continue; + ok = feeds_only(&in->def, same, n, 0) && nir_intrinsic_component(in) == 0 && + nir_src_is_const(*nir_get_io_offset_src(in)); + if (!first) + first = in; + } + } + ok &= first != NULL && c->nfixed + n + nplain <= SGX_FRAME_MAX_FETCH; + for (unsigned j = k; j < ncand; j++) { + if (!cand[j] || cand_slot[j] != cand_slot[k]) + continue; + if (ok) { + nir_tex_instr *tex = cand[j]; + nir_builder b = nir_builder_at(nir_before_instr(&tex->instr)); + nir_def *xy = nir_load_input(&b, 2, 32, + nir_imm_int(&b, nir_src_as_uint(*nir_get_io_offset_src(first))), + .base = nir_intrinsic_base(first), .component = 0, + .dest_type = nir_intrinsic_dest_type(first), + .io_semantics = nir_intrinsic_io_semantics(first)); + + nir_src_rewrite(&tex->src[nir_tex_instr_src_index(tex, nir_tex_src_coord)].src, xy); + c->fixed[c->nfixed] = tex; + c->fixed_fix[c->nfixed++] = cand_fix[j]; + progress = true; + } + if (j != k) + cand[j] = NULL; + } + } + if (progress) { + nir_progress(true, impl, nir_metadata_control_flow); + NIR_PASS(_, s, nir_opt_dce); + } +} + +static bool +is_fetch(const struct comp *c, const nir_instr *instr) +{ + for (unsigned k = 0; k < c->nfetch; k++) + if (&c->fetch[k]->instr == instr) + return true; + return false; +} + +/* Before anything is emitted, a fragment shader's lookups the PDS makes + * (M35; SGX_NOFETCH=1 none), the varyings only they read, and the inputs + * (the varyings iterated into the registers) in their order -- the + * texels go after them */ +static void +plan_inputs(struct comp *c, nir_function_impl *impl) +{ + bool read[VARYING_SLOT_MAX] = { false }; + + if (!getenv("SGX_NOFETCH")) { + nir_foreach_block(block, impl) { + nir_foreach_instr(instr, block) { + int slot; + unsigned shift = 0; + int fix; + + if (instr->type != nir_instr_type_tex || c->nfetch == SGX_FRAME_MAX_FETCH || + (slot = fetch_slot(c, nir_instr_as_tex(instr), &shift)) < 0 || c->flat[slot] || + ((c->fs->blend.tex_depth | c->fs->blend.tex_f16) >> + nir_instr_as_tex(instr)->texture_index & 1)) + continue; + fix = fixed_index(c, nir_instr_as_tex(instr)); + c->fetch_fix[c->nfetch] = fix < 0 ? SGX_FIX_SHIFT(shift) : c->fixed_fix[fix]; + c->fetch_slot[c->nfetch] = slot; + c->fetch[c->nfetch++] = nir_instr_as_tex(instr); + } + } + } + /* the varyings something besides the lookups reads */ + nir_foreach_block(block, impl) { + nir_foreach_instr(instr, block) { + nir_intrinsic_instr *in; + int slot; + + if (instr->type != nir_instr_type_intrinsic || + (slot = input_slot(in = nir_instr_as_intrinsic(instr))) < 0) + continue; + nir_foreach_use_including_if(src, &in->def) + read[slot] |= nir_src_is_if(src) || !is_fetch(c, nir_src_use_instr(src)); + } + } + for (unsigned k = 0; k < c->nfetch; k++) + c->fetch_only[c->fetch_slot[k]] = !read[c->fetch_slot[k]]; + /* (a lookup lower_fetch_coords() made ready is the PDS's, its varying + * only the lookups') */ + for (unsigned i = 0; i < c->nfixed; i++) { + bool ok = false; + + for (unsigned k = 0; k < c->nfetch && !ok; k++) + ok = c->fetch[k] == c->fixed[i] && c->fetch_only[c->fetch_slot[k]]; + if (!ok) + fail(c, "a lookup made ready for the PDS not its"); + } + /* the inputs, as intrinsic() would number them */ + nir_foreach_block(block, impl) { + nir_foreach_instr(instr, block) { + int slot; + + if (instr->type != nir_instr_type_intrinsic || + (slot = input_slot(nir_instr_as_intrinsic(instr))) < 0 || + c->fetch_only[slot] || c->input_of_slot[slot] >= 0 || + c->colour_of_slot[slot] >= 0 || c->ninputs == SGX_FRAME_MAX_VARYINGS) + continue; + /* (two of the TA's colours: flat shading with two-sided colours + * besides has its back ones smooth) */ + if (c->flat[slot] && c->ncolours < 2) { + c->colour_slot[c->ncolours] = slot; + c->colour_of_slot[slot] = c->ncolours++; + continue; + } + c->fs->input_slot[c->ninputs] = slot; + c->input_of_slot[slot] = c->ninputs++; + } + } +} + +/* Before anything is emitted: how many uniform words the shader reads (the + * texture states go after them) and a slot for each texture unit. */ +static void +scan(struct comp *c, nir_function_impl *impl) +{ + nir_foreach_block(block, impl) { + nir_foreach_instr(instr, block) { + if (instr->type == nir_instr_type_intrinsic) { + nir_intrinsic_instr *in = nir_instr_as_intrinsic(instr); + unsigned at; + + if (in->intrinsic == nir_intrinsic_load_ubo) { + /* (M43) a uniform buffer: its address in sa. The uniforms + * are load_uniform's (lower_uniforms_to_ubo is off): block + * k is the state tracker's constant buffer k + 1 */ + if (!nir_src_is_const(in->src[0]) || + nir_src_as_uint(in->src[0]) + 1 >= SGX_FRAME_MAX_UBOS) { + fail(c, "a uniform buffer chosen by an index"); + return; + } + c->ubo_mask |= 1u << (nir_src_as_uint(in->src[0]) + 1); + } else if (in->intrinsic == nir_intrinsic_load_uniform && + !nir_src_is_const(in->src[0])) { + /* an array read through an index: all of it (M21) */ + at = (nir_intrinsic_base(in) + nir_intrinsic_range(in)) * 4; + c->uwords = MAX2(c->uwords, at); + } else if (in->intrinsic == nir_intrinsic_load_uniform && uniform_word(c, in, &at)) { + c->uwords = MAX2(c->uwords, at + in->def.num_components); + } + if (in->intrinsic == nir_intrinsic_terminate || + in->intrinsic == nir_intrinsic_terminate_if || + in->intrinsic == nir_intrinsic_demote || + in->intrinsic == nir_intrinsic_demote_if) + c->kills = true; + if (c->vs && in->intrinsic == nir_intrinsic_load_input && + nir_src_is_const(*nir_get_io_offset_src(in))) + c->nattrs = MAX2(c->nattrs, nir_intrinsic_base(in) + + nir_src_as_uint(*nir_get_io_offset_src(in)) + 1); + if (in->intrinsic == nir_intrinsic_load_texture_scale) + c->scales = true; + if (in->intrinsic == nir_intrinsic_load_blend_const_color_r_float || + in->intrinsic == nir_intrinsic_load_blend_const_color_g_float || + in->intrinsic == nir_intrinsic_load_blend_const_color_b_float || + in->intrinsic == nir_intrinsic_load_blend_const_color_a_float) + c->blend_sa = 0; /* placed below */ + } else if (instr->type == nir_instr_type_tex) { + nir_tex_instr *tex = nir_instr_as_tex(instr); + + if (c->vs) { + fail(c, "texture lookups in a vertex shader"); + return; + } + if (tex->op == nir_texop_txs || tex->op == nir_texop_query_levels || + tex->op == nir_texop_txf) + c->sizes = true; + if (tex->texture_index < MAX_UNITS && c->slot_of_unit[tex->texture_index] < 0) { + if (c->nsamplers == SGX_FS_MAX_SAMPLERS) { + fail(c, "more than %u textures", SGX_FS_MAX_SAMPLERS); + return; + } + c->fs->sampler_unit[c->nsamplers] = tex->texture_index; + c->slot_of_unit[tex->texture_index] = c->nsamplers++; + } + } + } + } + /* sa: the uniforms, then a fragment shader's textures' state words (four + * each, from a multiple of four) and the blend colour, a vertex shader's + * constant attributes and its clip words -- 128 words at most. Past that + * the uniforms are in memory too (M32): the first ones still in sa, the + * block's address after them */ + { + unsigned nconst = 0, extra; + + for (unsigned a = 0; c->vs && a < c->nattrs; a++) + nconst += SGX_ATTR_KIND(c->attr[a]) == SGX_ATTR_CONST; + extra = c->vs ? 4 * nconst + 4 : + (c->nsamplers ? 3 + 4 * c->nsamplers : 0) + (c->blend_sa >= 0 ? 4 : 0) + + (c->scales ? 4 + 2 * c->nsamplers : 0) + + (c->sizes ? SGX_FS_SIZE_WORDS * c->nsamplers : 0); + extra += util_bitcount(c->ubo_mask); + c->ubuf = c->uwords + extra > 128; + if (c->ubuf) { + c->sa_uniforms = MIN2(c->uwords, (128 - extra - 4) & ~3u); + c->ubuf_sa = c->sa_uniforms; + c->nuniforms = c->ubuf_sa + 1; + } else { + c->sa_uniforms = c->nuniforms = c->uwords; + } + /* (M43) the uniform buffers' addresses */ + u_foreach_bit(k, c->ubo_mask) + c->ubo_sa[k] = c->nuniforms++; + } + c->sampler_sa = align(c->nuniforms, 4); + c->pa_base = 4 * MAX2(c->nattrs, 1); + /* a vertex shader's attributes that are constants (M26): four sa words + * each after the uniforms */ + for (unsigned a = 0; c->vs && a < c->nattrs; a++) + if (SGX_ATTR_KIND(c->attr[a]) == SGX_ATTR_CONST) { + c->vs->attr_sa[a] = c->nuniforms; + c->nuniforms += 4; + } + if (c->scales) + c->scale_sa = c->sampler_sa + 4 * c->nsamplers; + if (c->sizes) + c->size_sa = c->scales ? c->scale_sa + 2 * c->nsamplers : c->sampler_sa + 4 * c->nsamplers; + if (c->blend_sa >= 0) + c->blend_sa = c->sizes ? c->size_sa + SGX_FS_SIZE_WORDS * c->nsamplers : + c->scales ? align(c->scale_sa + 2 * c->nsamplers, 4) : + c->sampler_sa + 4 * c->nsamplers; +} + +static unsigned +type_size_vec4(const struct glsl_type *type, bool bindless) +{ + return glsl_count_attribute_slots(type, false); +} + +/* the constant buffer word a uniform load starts at; false (and fail) if + * it is not one we take */ +static bool +uniform_word(struct comp *c, nir_intrinsic_instr *in, unsigned *at) +{ + /* vec4 slots (the screen does not pack uniforms) */ + if (!nir_src_is_const(in->src[0])) { + fail(c, "an indirect uniform"); + return false; + } + *at = (nir_intrinsic_base(in) + nir_src_as_uint(in->src[0])) * 4; + return true; +} + +/* A uniform array's element through an index (M21): index1 = its first + * sa word -- 4 x the offset + the array's base (M44: integers; a float's + * low bits of 2^23 + it before) -- then each word read through index1 by + * a 32-bit move, as iOS's c04_loop_break reads its array */ +static struct usse_reg +imm_or_constant(struct comp *c, uint32_t v, struct scratch *s) +{ + return v < 128 ? usse_reg(USSE_IMM, v) : constant_bits(c, s, v); +} + +static void +indirect_uniform(struct comp *c, nir_intrinsic_instr *in) +{ + unsigned id = in->def.index * 4, base = nir_intrinsic_base(in) * 4; + struct operand off = resolve(nir_get_scalar(in->src[0].ssa, 0)); + struct scratch s = { 0 }; + struct usse_reg t = treg(c, scratch_take(c, &s)), ro = word(c, off, &s); + + emit(c, usse_imad(t, ro, usse_reg(USSE_IMM, 4), imm_or_constant(c, base, &s), true)); + emit(c, usse_vbw_and(usse_reg(USSE_INDEX, 1), t, 0xffff)); + for (unsigned i = 0; i < in->def.num_components; i++) { + unsigned r; + + if (c->last_use[id + i] < 0) + continue; + r = take(c); + c->loc[id + i] = treg(c, r); + c->owned[id + i] = true; + emit(c, usse_vbw_or(treg(c, r), usse_reg(USSE_IDX1, 3 << 5 | i), 0)); + } + scratch_give_back(c, &s); +} + +/* Uniform words from memory (M32): VLDST of the value's words from word + * at of the block -- through an index, at + 4 x the offset, with 4 in the + * high half (4 bytes a word) -- into temporaries in a row, then WDF0 */ +static void +memory_uniform(struct comp *c, nir_intrinsic_instr *in, unsigned at, bool indexed) +{ + unsigned id = in->def.index * 4, n = in->def.num_components, r = block(c, n, 1); + struct scratch s = { 0 }; + + ireg_barrier(c); + + if (indexed) { + struct operand off = resolve(nir_get_scalar(in->src[0].ssa, 0)); + struct usse_reg t = treg(c, scratch_take(c, &s)), ro = word(c, off, &s); + + emit(c, usse_imad(t, ro, usse_reg(USSE_IMM, 4), imm_or_constant(c, at, &s), true)); + emit(c, usse_vbw_or_rot(t, t, 4, 16)); + emit(c, usse_ldr_reg(treg(c, r), c->ubuf_sa, t, n)); + } else if (at < 128) { + emit(c, usse_ldr_imm(treg(c, r), c->ubuf_sa, at, n)); + } else { + struct usse_reg t = treg(c, scratch_take(c, &s)); + + emit(c, usse_limm(t, 4u << 16 | at)); + emit(c, usse_ldr_reg(treg(c, r), c->ubuf_sa, t, n)); + } + emit(c, USSE_WDF0); + scratch_give_back(c, &s); + for (unsigned i = 0; i < n; i++) { + c->loc[id + i] = treg(c, r + i); + c->owned[id + i] = c->last_use[id + i] >= 0; + if (!c->owned[id + i]) + give_back(c, r + i); + } +} + +/* (M43) a uniform buffer's words (ARB_uniform_buffer_object): VLDST from + * the buffer's address in sa word ubo_sa[k], at the offset in bytes -- + * a constant, or the program's (a quarter of it the words) */ +static void +ubo_load(struct comp *c, nir_intrinsic_instr *in, unsigned k) +{ + unsigned id = in->def.index * 4, n = in->def.num_components, r = block(c, n, 1); + unsigned sa = c->ubo_sa[k]; + struct scratch s = { 0 }; + + ireg_barrier(c); + + if (nir_src_is_const(in->src[1])) { + unsigned at = nir_src_as_uint(in->src[1]) / 4; + + if (at < 128) { + emit(c, usse_ldr_imm(treg(c, r), sa, at, n)); + } else { + struct usse_reg t = treg(c, scratch_take(c, &s)); + + emit(c, usse_limm(t, 4u << 16 | at)); + emit(c, usse_ldr_reg(treg(c, r), sa, t, n)); + } + } else { + struct operand off = resolve(nir_get_scalar(in->src[1].ssa, 0)); + struct usse_reg t = treg(c, scratch_take(c, &s)); + + emit(c, usse_vbw_imm(USSE_VBW_SHR, t, word(c, off, &s), 2, 0)); + emit(c, usse_vbw_or_rot(t, t, 4, 16)); + emit(c, usse_ldr_reg(treg(c, r), sa, t, n)); + } + emit(c, USSE_WDF0); + scratch_give_back(c, &s); + for (unsigned i = 0; i < n; i++) { + c->loc[id + i] = treg(c, r + i); + c->owned[id + i] = c->last_use[id + i] >= 0; + if (!c->owned[id + i]) + give_back(c, r + i); + } +} + +static void tile_read(struct comp *c, unsigned d); + +static void +intrinsic(struct comp *c, nir_intrinsic_instr *in) +{ + nir_src *offset; + unsigned at, id = in->def.index * 4; + + switch (in->intrinsic) { + case nir_intrinsic_load_frag_coord: + case nir_intrinsic_load_input: { + unsigned slot, comp = 0; + + if (c->vs) { + /* attribute n (its vertex element) where the fetch put it -- four + * words from pa4n, vs_prologue() made floats -- or, a constant, + * in sa */ + offset = nir_get_io_offset_src(in); + if (in->intrinsic != nir_intrinsic_load_input || !nir_src_is_const(*offset)) { + fail(c, "an indirect attribute"); + return; + } + at = nir_intrinsic_base(in) + nir_src_as_uint(*offset); + if (at >= SGX_VS_MAX_ATTRIBS) { + fail(c, "attribute %u", at); + return; + } + if (at >= c->nattrs) { + fail(c, "attribute %u read but not found", at); + return; + } + for (unsigned i = 0; i < in->def.num_components; i++) + c->loc[id + i] = SGX_ATTR_KIND(c->attr[at]) == SGX_ATTR_CONST ? + usse_reg(USSE_SA, c->vs->attr_sa[at] + nir_intrinsic_component(in) + i) : + usse_reg(USSE_PA, 4 * at + nir_intrinsic_component(in) + i); + return; + } + if (in->intrinsic == nir_intrinsic_load_frag_coord) { + /* the PDS iterates the pixel's position like a varying */ + slot = VARYING_SLOT_POS; + } else { + offset = nir_get_io_offset_src(in); + if (!nir_src_is_const(*offset)) { + fail(c, "an indirect varying"); + return; + } + slot = nir_intrinsic_io_semantics(in).location + nir_src_as_uint(*offset); + comp = nir_intrinsic_component(in); + if (!colour_or_generic(slot)) { + fail(c, "input %s", gl_varying_slot_name_for_stage(slot, MESA_SHADER_FRAGMENT)); + return; + } + } + if (c->fetch_only[slot]) { + /* read by the PDS's lookups only (M35): not in the registers */ + for (unsigned i = 0; i < in->def.num_components; i++) + c->loc[id + i] = usse_reg(USSE_PA, 0); + return; + } + if (c->colour_of_slot[slot] >= 0) { + /* one of the TA's colours (M37): its bytes, unpacked as o0's are + * for blending */ + struct usse_reg raw = usse_reg(USSE_PA, 4 * c->ninputs + c->colour_of_slot[slot]); + unsigned d = block(c, 4, 4); + + emit(c, usse_unpack_unorm8(treg(c, d), raw, 0)); + emit(c, usse_unpack_unorm8(treg(c, d + 2), raw, 2)); + for (unsigned i = 0; i < 4; i++) { + bool mine = i >= comp && i < comp + in->def.num_components; + + if (mine) { + c->loc[id + i - comp] = treg(c, d + i); + c->owned[id + i - comp] = c->last_use[id + i - comp] >= 0; + } + if (!mine || c->last_use[id + i - comp] < 0) + give_back(c, d + i); + } + return; + } + if (c->input_of_slot[slot] < 0) { + if (c->ninputs == SGX_FRAME_MAX_VARYINGS) { + fail(c, "more than %u varyings", SGX_FRAME_MAX_VARYINGS); + return; + } + c->fs->input_slot[c->ninputs] = slot; + c->input_of_slot[slot] = c->ninputs++; + } + at = 4 * c->input_of_slot[slot] + comp; + for (unsigned i = 0; i < in->def.num_components; i++) + c->loc[id + i] = usse_reg(USSE_PA, at + i); + return; + } + case nir_intrinsic_load_uniform: + if (!nir_src_is_const(in->src[0])) { + /* (in sa when all of the array is) */ + if (c->ubuf && (nir_intrinsic_base(in) + nir_intrinsic_range(in)) * 4 > c->sa_uniforms) + memory_uniform(c, in, nir_intrinsic_base(in) * 4, true); + else + indirect_uniform(c, in); + return; + } + if (!uniform_word(c, in, &at)) + return; + if (at + in->def.num_components > c->sa_uniforms) { + memory_uniform(c, in, at, false); + return; + } + for (unsigned i = 0; i < in->def.num_components; i++) + c->loc[id + i] = usse_reg(USSE_SA, at + i); + return; + case nir_intrinsic_load_ubo: + /* (M43: block k, constant buffer k + 1 -- scan()) */ + ubo_load(c, in, nir_src_as_uint(in->src[0]) + 1); + return; + case nir_intrinsic_ddx: + case nir_intrinsic_ddx_fine: + case nir_intrinsic_ddx_coarse: + case nir_intrinsic_ddy: + case nir_intrinsic_ddy_fine: + case nir_intrinsic_ddy_coarse: { + /* the difference across the pixel's 2x2 block (M33; scalar: the + * screen's scalarize_ddx) */ + struct scratch sc = { 0 }; + struct usse_reg a = get(c, resolve(nir_get_scalar(in->src[0].ssa, 0)), + TAKES_LANE_Y | TAKES_SA, &sc); + bool x = in->intrinsic == nir_intrinsic_ddx || in->intrinsic == nir_intrinsic_ddx_fine || + in->intrinsic == nir_intrinsic_ddx_coarse; + + emit(c, usse_fop(x ? USSE_NMAD_DSX : USSE_NMAD_DSY, define(c, &in->def), a, a)); + scratch_give_back(c, &sc); + c->derivatives = true; + return; + } + case nir_intrinsic_decl_reg: + /* a phi web's register (M20): a temporary a component, the whole + * program long */ + if (nir_intrinsic_num_array_elems(in) || nir_intrinsic_bit_size(in) != 32) { + fail(c, "an array register"); + return; + } + for (unsigned i = 0; i < nir_intrinsic_num_components(in); i++) + c->loc[id + i] = treg(c, take(c)); + return; + case nir_intrinsic_store_reg: { + unsigned reg = in->src[1].ssa->index * 4, mask = nir_intrinsic_write_mask(in); + struct scratch sc = { 0 }; + + for (unsigned i = 0; i < in->src[0].ssa->num_components; i++) { + if (mask & 1 << i) + move_into(c, c->loc[reg + i], resolve(nir_get_scalar(in->src[0].ssa, i)), &sc); + scratch_give_back(c, &sc); + } + return; + } + case nir_intrinsic_load_reg: { + /* a copy: the register changes while the value may still be read */ + unsigned reg = in->src[0].ssa->index * 4; + + for (unsigned i = 0; i < in->def.num_components; i++) { + unsigned r; + + if (c->last_use[id + i] < 0) + continue; + r = take(c); + c->loc[id + i] = treg(c, r); + c->owned[id + i] = true; + emit(c, usse_fmov(treg(c, r), c->loc[reg + i])); + } + return; + } + case nir_intrinsic_store_output: { + unsigned loc = nir_intrinsic_io_semantics(in).location; + unsigned mask = nir_intrinsic_write_mask(in), comp = nir_intrinsic_component(in); + + if (c->depth) { + fail(c, "an output written in control flow"); + return; + } + + if (c->vs) { + int k = -1; + + /* the position, or a varying the fragment shader reads; the rest + * (the point size, varyings nobody reads) go nowhere */ + loc += nir_src_as_uint(*nir_get_io_offset_src(in)); + /* (M46: a varying the fragment shader reads twice, once moved -- + * SGX_FIX_SHIFT -- goes to each) */ + for (int j = -1; j < (int)c->nvaryings; j++) { + k = j < 0 ? (loc == VARYING_SLOT_POS ? 0 : -1) : + c->varying_slot[j] == loc ? 1 + j : -1; + for (unsigned i = 0; k >= 0 && i < in->src[0].ssa->num_components; i++) { + struct operand o; + + if (!(mask & 1 << i) || comp + i >= 4) + continue; + o = resolve(nir_get_scalar(in->src[0].ssa, i)); + c->have_vout[k][comp + i] = true; + /* (the position, and a varying the vertex side does more to: + * at the end, vertex_output()) */ + if (k == 0 || (c->vary_fix && c->vary_fix[k - 1])) { + c->vout[k][comp + i] = o; + } else { + /* a varying straight into its output register: kept until + * the end, eight vec4s took more temporaries than there + * are (M30) */ + struct scratch sc = { 0 }; + + if (!o.is_const && !o.neg && !o.abs && + c->loc[o.id].bank == USSE_OUTPUT && c->loc[o.id].num == 4 * k + comp + i) + continue; /* (made there: plan_vs_outputs) */ + move_into(c, usse_reg(USSE_OUTPUT, 4 * k + comp + i), o, &sc); + scratch_give_back(c, &sc); + } + } + } + return; + } + /* (M43) the second colour of dual-source blending: nir_lower_blend + * took it into the blending; with no blending, nothing */ + if (nir_intrinsic_io_semantics(in).dual_source_blend_index) + return; + if (loc != FRAG_RESULT_COLOR && loc != FRAG_RESULT_DATA0) { + fail(c, "output %s", gl_frag_result_name(loc)); + return; + } + for (unsigned i = 0; i < in->src[0].ssa->num_components; i++) { + if (!(mask & 1 << i) || comp + i >= 4) + continue; + c->colour[comp + i] = resolve(nir_get_scalar(in->src[0].ssa, i)); + c->have_colour[comp + i] = true; + } + return; + } + case nir_intrinsic_load_output: { + /* the colour the tile holds (blending, nir_lower_blend): o0's four + * 8-bit channels into four temporaries */ + unsigned d; + + if (!nir_intrinsic_io_semantics(in).fb_fetch_output || + (nir_intrinsic_io_semantics(in).location != FRAG_RESULT_DATA0 && + nir_intrinsic_io_semantics(in).location != FRAG_RESULT_COLOR)) { + fail(c, "reads an output"); + return; + } + d = block(c, 4, 2); + { + /* SGX_DEBUG_FBFETCH=word: unpack a constant instead of o0 (a test + * of the channel selects) */ + const char *dbg = getenv("SGX_DEBUG_FBFETCH"); + struct usse_reg src = usse_reg(USSE_OUTPUT, 0); + unsigned k = 0; + + if (dbg) { + k = take(c); + src = treg(c, k); + emit(c, usse_limm(src, strtoul(dbg, NULL, 0))); + } + if (c->fs->blend.rt_kind != SGX_RT_UNORM8 && !dbg) { + tile_read(c, d); + } else { + emit(c, usse_unpack_unorm8(treg(c, d), src, 0)); + emit(c, usse_unpack_unorm8(treg(c, d + 2), src, 2)); + } + for (unsigned i = 0; i < 4; i++) { + c->loc[id + i] = treg(c, d + i); + c->owned[id + i] = i < in->def.num_components && c->last_use[id + i] >= 0; + if (!c->owned[id + i]) + give_back(c, d + i); + } + if (dbg) + give_back(c, k); + } + return; + } + case nir_intrinsic_load_texture_scale: { + unsigned unit = nir_src_is_const(in->src[0]) ? nir_src_as_uint(in->src[0]) : MAX_UNITS; + + if (unit >= MAX_UNITS || c->slot_of_unit[unit] < 0 || c->scale_sa < 0) { + fail(c, "a texture's size for a texture not sampled"); + return; + } + c->loc[id] = usse_reg(USSE_SA, c->scale_sa + 2 * c->slot_of_unit[unit]); + c->loc[id + 1] = usse_reg(USSE_SA, c->scale_sa + 2 * c->slot_of_unit[unit] + 1); + return; + } + case nir_intrinsic_load_blend_const_color_r_float: + case nir_intrinsic_load_blend_const_color_g_float: + case nir_intrinsic_load_blend_const_color_b_float: + case nir_intrinsic_load_blend_const_color_a_float: + /* (the intrinsics are not in rgba order) */ + c->loc[id] = usse_reg(USSE_SA, c->blend_sa + + (in->intrinsic == nir_intrinsic_load_blend_const_color_r_float ? 0 : + in->intrinsic == nir_intrinsic_load_blend_const_color_g_float ? 1 : + in->intrinsic == nir_intrinsic_load_blend_const_color_b_float ? 2 : 3)); + return; + case nir_intrinsic_terminate: + case nir_intrinsic_terminate_if: + case nir_intrinsic_demote: + case nir_intrinsic_demote_if: { + /* discard: the conditions gathered (or'ed: booleans 0 and ~0, M44) + * into a temporary of its own (two: output() copies it to the odd + * one, made 0.0 or 1.0 first), which output() tests */ + bool cond = in->intrinsic == nir_intrinsic_terminate_if || + in->intrinsic == nir_intrinsic_demote_if; + struct operand o = cond ? resolve(nir_get_scalar(in->src[0].ssa, 0)) : + (struct operand){ .is_const = true, .u = ~0u }; + struct scratch sc = { 0 }; + + if (!c->fs || c->kill < 0) { + fail(c, "discard in a vertex shader"); + break; + } + /* (kill is 0 from the program's start: a discard in a branch may + * not run) */ + if (o.is_const) { + if (o.u) + emit(c, usse_limm(treg(c, c->kill), ~0u)); + } else { + emit(c, usse_vbw(USSE_VBW_OR, treg(c, c->kill), treg(c, c->kill), word(c, o, &sc), false)); + } + scratch_give_back(c, &sc); + break; + } + case nir_intrinsic_load_front_face_fsign: { + /* +1 front, -1 back, by the facing bit (iOS's v09_frontfacing) */ + struct usse_reg d = define(c, &in->def); + + emit(c, usse_limm(d, f32_bits(c->front_when_set ? -1.0f : 1.0f))); + emit(c, usse_vtst_facing(0)); + emit(c, usse_limm_pred(d, f32_bits(c->front_when_set ? 1.0f : -1.0f), 1)); + break; + } + case nir_intrinsic_load_barycentric_pixel: + case nir_intrinsic_load_barycentric_centroid: + case nir_intrinsic_load_barycentric_sample: + return; + default: + fail(c, "no %s yet", nir_intrinsic_infos[in->intrinsic].name); + return; + } +} + +static bool +is_derivative(const nir_intrinsic_instr *in) +{ + switch (in->intrinsic) { + case nir_intrinsic_ddx: + case nir_intrinsic_ddx_fine: + case nir_intrinsic_ddx_coarse: + case nir_intrinsic_ddy: + case nir_intrinsic_ddy_fine: + case nir_intrinsic_ddy_coarse: + return true; + default: + return false; + } +} + +/* what an instruction reads, for liveness: f(c, operand) for each */ +static void +for_each_read(struct comp *c, nir_instr *instr, void (*f)(struct comp *, struct operand, int), + int index) +{ + if (instr->type == nir_instr_type_alu) { + nir_alu_instr *alu = nir_instr_as_alu(instr); + + if (alu->op == nir_op_mov || alu->op == nir_op_fneg || alu->op == nir_op_fabs || + nir_op_is_vec(alu->op)) + return; + /* (M47: a vector instruction's every component) */ + for (unsigned i = 0; i < nir_op_infos[alu->op].num_inputs; i++) + for (unsigned k = 0; k < nir_ssa_alu_instr_src_components(alu, i); k++) + f(c, resolve(nir_get_scalar(alu->src[i].src.ssa, alu->src[i].swizzle[k])), index); + } else if (instr->type == nir_instr_type_intrinsic) { + nir_intrinsic_instr *in = nir_instr_as_intrinsic(instr); + + if (in->intrinsic == nir_intrinsic_store_output) + for (unsigned i = 0; i < in->src[0].ssa->num_components; i++) + f(c, resolve(nir_get_scalar(in->src[0].ssa, i)), index); + if (in->intrinsic == nir_intrinsic_terminate_if || + in->intrinsic == nir_intrinsic_demote_if || is_derivative(in)) + f(c, resolve(nir_get_scalar(in->src[0].ssa, 0)), index); + if (in->intrinsic == nir_intrinsic_store_reg) + for (unsigned i = 0; i < in->src[0].ssa->num_components; i++) + f(c, resolve(nir_get_scalar(in->src[0].ssa, i)), index); + if (in->intrinsic == nir_intrinsic_load_uniform && !nir_src_is_const(in->src[0])) + f(c, resolve(nir_get_scalar(in->src[0].ssa, 0)), index); + } else if (instr->type == nir_instr_type_tex) { + nir_tex_instr *tex = nir_instr_as_tex(instr); + + for (unsigned i = 0; i < tex->num_srcs; i++) { + if (tex->src[i].src_type == nir_tex_src_coord) { + for (unsigned k = 0; k < MIN2(tex->src[i].src.ssa->num_components, 3); k++) + f(c, tex_operand(tex, i, k), index); + } else if (tex->src[i].src_type == nir_tex_src_bias || + tex->src[i].src_type == nir_tex_src_lod) { + f(c, tex_operand(tex, i, 0), index); + } + } + } +} + +static void +note_use(struct comp *c, struct operand o, int index) +{ + if (o.is_const) + return; + /* read in a loop it was made before: alive until that loop's end (the + * outermost such), every iteration reads it */ + for (unsigned i = 0; i < c->nactive; i++) + if (c->active[i].start > c->def_at[o.id / 4]) { + index = MAX2(index, c->active[i].end); + break; + } + c->last_use[o.id] = MAX2(c->last_use[o.id], index); +} + +static void +release(struct comp *c, struct operand o, int index) +{ + /* the colour's values stay until output() has moved them */ + if (c->have_colour[0] || c->have_colour[1] || c->have_colour[2] || c->have_colour[3]) + for (unsigned i = 0; i < 4; i++) + if (c->have_colour[i] && !c->colour[i].is_const && c->colour[i].id == o.id) + return; + /* and the position's until vertex_output() has, and those of the + * varyings the vertex side does more to (M39) */ + for (unsigned k = 0; c->vs && k <= c->nvaryings; k++) { + if (k && !(c->vary_fix && c->vary_fix[k - 1])) + continue; + for (unsigned i = 0; i < 4; i++) + if (c->have_vout[k][i] && !c->vout[k][i].is_const && c->vout[k][i].id == o.id) + return; + } + if (!o.is_const && c->last_use[o.id] == index && c->owned[o.id]) { + give_back(c, c->loc[o.id].num - (c->vs ? c->pa_base : 0)); + c->owned[o.id] = false; + } +} + +/* GL's logic op (M37) as iOS's driver does it (es1 e03..e10): the colour + * packed to bytes, then a VBW with the tile's (o0) -- `xor o0, pa0, o0`; + * not x is `and c56, ~x`, c56 all ones. The colour mask after it, on the + * bytes (o0 is B G R A, as the target), and a discarded pixel keeps o0: + * both through a temporary, the result moved or unpacked at the end. */ +static void +logic_output(struct comp *c, unsigned base) +{ + const unsigned mask = c->fs->blend.colormask; + const bool direct = c->kill < 0 && mask == 0xf; + struct usse_reg src = treg(c, take(c)), t = treg(c, take(c)); + struct usse_reg o0 = usse_reg(USSE_OUTPUT, 0), ones = USSE_ALL_ONES; + struct usse_reg r = direct ? o0 : t; + uint64_t w; + + emit(c, usse_pack_unorm8_to(src, treg(c, base))); + switch (c->logicop) { + case PIPE_LOGICOP_CLEAR: w = usse_vbw(USSE_VBW_XOR, r, o0, o0, false); break; + case PIPE_LOGICOP_NOR: + emit(c, usse_vbw(USSE_VBW_OR, t, src, o0, false)); + w = usse_vbw(USSE_VBW_AND, r, ones, t, true); + break; + case PIPE_LOGICOP_AND_INVERTED: w = usse_vbw(USSE_VBW_AND, r, o0, src, true); break; + case PIPE_LOGICOP_COPY_INVERTED: w = usse_vbw(USSE_VBW_AND, r, ones, src, true); break; + case PIPE_LOGICOP_AND_REVERSE: w = usse_vbw(USSE_VBW_AND, r, src, o0, true); break; + case PIPE_LOGICOP_INVERT: w = usse_vbw(USSE_VBW_AND, r, ones, o0, true); break; + case PIPE_LOGICOP_XOR: w = usse_vbw(USSE_VBW_XOR, r, src, o0, false); break; + case PIPE_LOGICOP_NAND: + emit(c, usse_vbw(USSE_VBW_AND, t, src, o0, false)); + w = usse_vbw(USSE_VBW_AND, r, ones, t, true); + break; + case PIPE_LOGICOP_AND: w = usse_vbw(USSE_VBW_AND, r, src, o0, false); break; + case PIPE_LOGICOP_EQUIV: + emit(c, usse_vbw(USSE_VBW_XOR, t, src, o0, false)); + w = usse_vbw(USSE_VBW_AND, r, ones, t, true); + break; + case PIPE_LOGICOP_NOOP: w = usse_vbw(USSE_VBW_OR, r, o0, o0, false); break; + case PIPE_LOGICOP_OR_INVERTED: w = usse_vbw(USSE_VBW_OR, r, o0, src, true); break; + case PIPE_LOGICOP_COPY: w = usse_vbw(USSE_VBW_OR, r, src, src, false); break; + case PIPE_LOGICOP_OR_REVERSE: w = usse_vbw(USSE_VBW_OR, r, src, o0, true); break; + case PIPE_LOGICOP_OR: w = usse_vbw(USSE_VBW_OR, r, src, o0, false); break; + default: w = usse_vbw(USSE_VBW_OR, r, o0, o0, true); break; /* SET */ + } + if (direct) { + emit(c, w | USSE_END); + return; + } + emit(c, w); + if (mask != 0xf) { + /* t = (t & m) | (o0 & ~m), m the bytes of the channels written */ + struct usse_reg m = treg(c, take(c)); + uint32_t bytes = (mask & PIPE_MASK_R ? 0x00ff0000u : 0) | + (mask & PIPE_MASK_G ? 0x0000ff00u : 0) | + (mask & PIPE_MASK_B ? 0x000000ffu : 0) | + (mask & PIPE_MASK_A ? 0xff000000u : 0); + + emit(c, usse_limm(m, bytes)); + emit(c, usse_vbw(USSE_VBW_AND, t, t, m, false)); + emit(c, usse_vbw(USSE_VBW_AND, src, o0, m, true)); + emit(c, usse_vbw(USSE_VBW_OR, t, t, src, false)); + } + if (c->kill < 0) { + emit(c, usse_vbw_or(o0, t, 0) | USSE_END); + return; + } + /* discarded: o0 as it was -- the result and the tile's unpacked, the + * channels chosen, packed again (exact for bytes) */ + { + unsigned d = block(c, 4, 2); + + emit(c, usse_vbw_imm(USSE_VBW_AND, treg(c, c->kill), treg(c, c->kill), 0x3f80, 16)); + emit(c, usse_fmov(treg(c, c->kill + 1), treg(c, c->kill))); + emit(c, usse_unpack_unorm8(treg(c, base), t, 0)); + emit(c, usse_unpack_unorm8(treg(c, base + 2), t, 2)); + emit(c, usse_unpack_unorm8(treg(c, d), o0, 0)); + emit(c, usse_unpack_unorm8(treg(c, d + 2), o0, 2)); + for (unsigned i = 0; i < 4; i++) { + usse_fmovc(&w, USSE_TEST_NE0, treg(c, base + i), treg(c, c->kill + (i & 1)), + treg(c, d + i), treg(c, base + i)); + emit(c, w); + } + emit(c, usse_pack_unorm8(0, treg(c, base)) | USSE_END); + } +} + +/* the colour: four registers in a row, packed into o0 */ +/* (M43) the colour the tile holds, R G B A as F32 into d..d + 3 (d even), + * for a target not of RGBA bytes: half floats (o0, o1 or o0 alone), F32 + * (o0, o1 or o0 alone); the channels it has not 0, alpha 1 */ +static void +tile_read(struct comp *c, unsigned d) +{ + struct usse_reg o0 = usse_reg(USSE_OUTPUT, 0); + + switch (c->fs->blend.rt_kind) { + case SGX_RT_F16X4: + emit(c, usse_unpack_f16(treg(c, d), o0, 0)); + emit(c, usse_unpack_f16(treg(c, d + 2), o0, 2)); + return; + case SGX_RT_F16X2: + emit(c, usse_unpack_f16(treg(c, d), o0, 0)); + break; + case SGX_RT_F32: + emit(c, usse_fmov(treg(c, d), o0)); + emit(c, usse_limm(treg(c, d + 1), 0)); + break; + default: + emit(c, usse_fmov(treg(c, d), o0)); + emit(c, usse_fmov(treg(c, d + 1), usse_reg(USSE_OUTPUT, 1))); + break; + } + emit(c, usse_limm(treg(c, d + 2), 0)); + emit(c, usse_limm(treg(c, d + 3), 0x3f800000)); +} + +static void emit_sop2(struct comp *c, struct usse_reg packed, struct usse_reg t1, + struct usse_reg t2); + +static void +output(struct comp *c) +{ + struct scratch s = { 0 }; + unsigned base; + + if (!c->have_colour[0] && !c->have_colour[1] && !c->have_colour[2] && !c->have_colour[3]) { + /* a colour mask of nothing (nir_lower_blend took the output away), + * or a shader that writes no colour (depth alone, M35): o0 keeps the + * tile's colour, as it came in (M23) */ + emit(c, USSE_NOP_END); + return; + } + base = c->out_base >= 0 ? (unsigned)c->out_base : block(c, 4, 2); + for (unsigned i = 0; i < 4; i++) { + struct operand o = c->colour[i]; + + if (!c->have_colour[i]) { + o.is_const = true; + o.c = i == 3 ? 1.0f : 0.0f; + o.u = f32_bits(o.c); + } + /* (made where it goes already) */ + if (!o.is_const && !o.neg && !o.abs && c->colour_id[i] == (int)o.id && + c->loc[o.id].bank == USSE_TEMP && c->loc[o.id].num == treg(c, base + i).num) + continue; + move_into(c, treg(c, base + i), o, &s); + scratch_give_back(c, &s); + } + if (c->logicop >= 0) { + logic_output(c, base); + return; + } + if (c->kill >= 0) { + /* discarded: the pixel keeps the colour its tile holds (o0, as the + * blending reads it) -- every draw is a translucent object, shaded in + * order. The hardware's own way, iOS's c00_discard (a punch-through + * pass, two phases, `p1? KILL`), does not work here yet (M19). */ + unsigned d = block(c, 4, 2); + + /* (the booleans or'ed: 0.0 or 1.0, as the F32 tests below take it) */ + emit(c, usse_vbw_imm(USSE_VBW_AND, treg(c, c->kill), treg(c, c->kill), 0x3f80, 16)); + emit(c, usse_fmov(treg(c, c->kill + 1), treg(c, c->kill))); + if (c->fs->blend.rt_kind != SGX_RT_UNORM8) { + tile_read(c, d); + } else { + emit(c, usse_unpack_unorm8(treg(c, d), usse_reg(USSE_OUTPUT, 0), 0)); + emit(c, usse_unpack_unorm8(treg(c, d + 2), usse_reg(USSE_OUTPUT, 0), 2)); + } + for (unsigned i = 0; i < 4; i++) { + uint64_t w; + + usse_fmovc(&w, USSE_TEST_NE0, treg(c, base + i), treg(c, c->kill + (i & 1)), + treg(c, d + i), treg(c, base + i)); + emit(c, w); + } + } + if (c->sop2) { + struct usse_reg packed = treg(c, take(c)); + struct usse_reg t1 = c->sop2_pre_dst ? treg(c, take(c)) : packed; + struct usse_reg t2 = c->sop2_post ? treg(c, take(c)) : packed; + + emit(c, usse_pack_unorm8_to(packed, treg(c, base))); + emit_sop2(c, packed, t1, t2); + return; + } + switch (c->fs->blend.rt_kind) { + case SGX_RT_F16X4: + emit(c, usse_pack_f16(usse_reg(USSE_OUTPUT, 0), treg(c, base), 0xf) | USSE_END); + break; + case SGX_RT_F16X2: + emit(c, usse_pack_f16(usse_reg(USSE_OUTPUT, 0), treg(c, base), 0x3) | USSE_END); + break; + case SGX_RT_F32: + emit(c, usse_fmov(usse_reg(USSE_OUTPUT, 0), treg(c, base)) | USSE_END); + break; + case SGX_RT_F32X2: + emit(c, usse_pack_f32x2(usse_reg(USSE_OUTPUT, 0), treg(c, base)) | USSE_END); + break; + default: + emit(c, usse_pack_unorm8(0, treg(c, base)) | USSE_END); + } +} + +/* A blend factor as SOP2 takes it, the source being SOP2's first operand + * (src1, swapped: its second); false: not one it has (the constant's) */ +static bool +sop2_colour_factor(unsigned f, bool swapped, uint8_t *sel, uint8_t *mod) +{ + unsigned src = swapped ? USSE_SOP2_SRC2 : USSE_SOP2_SRC1; + unsigned dst = swapped ? USSE_SOP2_SRC1 : USSE_SOP2_SRC2; + + *mod = f >= PIPE_BLENDFACTOR_ZERO; + switch (f) { + case PIPE_BLENDFACTOR_ONE: *sel = USSE_SOP2_ZERO; *mod = 1; return true; + case PIPE_BLENDFACTOR_ZERO: *sel = USSE_SOP2_ZERO; *mod = 0; return true; + case PIPE_BLENDFACTOR_SRC_COLOR: case PIPE_BLENDFACTOR_INV_SRC_COLOR: + *sel = src; + return true; + case PIPE_BLENDFACTOR_SRC_ALPHA: case PIPE_BLENDFACTOR_INV_SRC_ALPHA: + *sel = src + 2; + return true; + case PIPE_BLENDFACTOR_DST_COLOR: case PIPE_BLENDFACTOR_INV_DST_COLOR: + *sel = dst; + return true; + case PIPE_BLENDFACTOR_DST_ALPHA: case PIPE_BLENDFACTOR_INV_DST_ALPHA: + *sel = dst + 2; + return true; + default: + return false; + } +} + +static bool +sop2_alpha_factor(unsigned f, bool swapped, uint8_t *sel, uint8_t *mod) +{ + unsigned src = swapped ? USSE_SOP2_A_SRC2 : USSE_SOP2_A_SRC1; + unsigned dst = swapped ? USSE_SOP2_A_SRC1 : USSE_SOP2_A_SRC2; + + *mod = f >= PIPE_BLENDFACTOR_ZERO; + switch (f) { + case PIPE_BLENDFACTOR_ONE: case PIPE_BLENDFACTOR_SRC_ALPHA_SATURATE: + *sel = USSE_SOP2_A_ZERO; *mod = 1; return true; + case PIPE_BLENDFACTOR_ZERO: *sel = USSE_SOP2_A_ZERO; *mod = 0; return true; + case PIPE_BLENDFACTOR_SRC_COLOR: case PIPE_BLENDFACTOR_INV_SRC_COLOR: + case PIPE_BLENDFACTOR_SRC_ALPHA: case PIPE_BLENDFACTOR_INV_SRC_ALPHA: + *sel = src; + return true; + case PIPE_BLENDFACTOR_DST_COLOR: case PIPE_BLENDFACTOR_INV_DST_COLOR: + case PIPE_BLENDFACTOR_DST_ALPHA: case PIPE_BLENDFACTOR_INV_DST_ALPHA: + *sel = dst; + return true; + default: + return false; + } +} + +/* (M46) A colour mask of all three of R, G and B or none of them, alpha or + * not, folded into the blending for SOP2: a channel kept is blended as the + * tile's own (ZERO, ONE -- reverse subtract keeps it too, dst x 1 - src x 0), + * and a draw not blended is ONE, ZERO. One SOP2 then, where the mask had + * the tile's colour unpacked, selected and packed in F32 (nir_lower_blend): + * PPSSPP keeps the target's alpha -- the PSP's stencil -- in most of its + * draws. False: a mask SOP2 cannot do (some of R, G, B; nothing at all is + * a program that leaves o0 as it is). */ +static bool +fold_colormask(const struct sgx_blend_key *k, struct sgx_blend_key *out) +{ + const unsigned rgb = k->colormask & 7; + const bool alpha = k->colormask & 8; + + *out = *k; + if (k->colormask == 0xf) + return true; + if ((rgb != 0 && rgb != 7) || !k->colormask) + return false; + if (!out->enable) { + out->enable = 1; + out->rgb_func = out->alpha_func = PIPE_BLEND_ADD; + out->rgb_src = out->alpha_src = PIPE_BLENDFACTOR_ONE; + out->rgb_dst = out->alpha_dst = PIPE_BLENDFACTOR_ZERO; + } + if (!rgb) { + if (out->rgb_func != PIPE_BLEND_REVERSE_SUBTRACT) + out->rgb_func = PIPE_BLEND_ADD; + out->rgb_src = PIPE_BLENDFACTOR_ZERO; + out->rgb_dst = PIPE_BLENDFACTOR_ONE; + } + if (!alpha) { + out->alpha_func = out->rgb_func == PIPE_BLEND_REVERSE_SUBTRACT ? + PIPE_BLEND_REVERSE_SUBTRACT : PIPE_BLEND_ADD; + out->alpha_src = PIPE_BLENDFACTOR_ZERO; + out->alpha_dst = PIPE_BLENDFACTOR_ONE; + } + out->colormask = 0xf; + return true; +} + +/* GL's blending as one SOP2 (M25): the colour and the tile's, 8 bits a + * channel, as iOS blends -- not F32 arithmetic on the tile's colour + * unpacked (nir_lower_blend), some 30 instructions more. Not for the + * blend colour's factors (sop2_plan's SOP2s around it, M46), a colour mask + * (but those fold_colormask() makes blending, M46), or min/max with the + * other channels' funcs not the same kind. */ +static bool +sop2_blend(const struct sgx_blend_key *k, struct usse_sop2 *f, bool *swap) +{ + static const uint8_t op[] = { + [PIPE_BLEND_ADD] = USSE_SOP2_ADD, [PIPE_BLEND_SUBTRACT] = USSE_SOP2_SUB, + [PIPE_BLEND_REVERSE_SUBTRACT] = USSE_SOP2_SUB, [PIPE_BLEND_MIN] = USSE_SOP2_MIN, + [PIPE_BLEND_MAX] = USSE_SOP2_MAX, + }; + bool rev = k->rgb_func == PIPE_BLEND_REVERSE_SUBTRACT; + unsigned rgb_src = k->rgb_src, rgb_dst = k->rgb_dst; + unsigned alpha_src = k->alpha_src, alpha_dst = k->alpha_dst; + + if (!k->enable || k->colormask != 0xf || k->rgb_func > PIPE_BLEND_MAX || + k->alpha_func > PIPE_BLEND_MAX || + (k->alpha_func == PIPE_BLEND_REVERSE_SUBTRACT) != rev || + (rev && (rgb_src == PIPE_BLENDFACTOR_SRC_ALPHA_SATURATE))) + return false; + /* min and max ignore the factors */ + if (k->rgb_func == PIPE_BLEND_MIN || k->rgb_func == PIPE_BLEND_MAX) + rgb_src = rgb_dst = PIPE_BLENDFACTOR_ONE; + if (k->alpha_func == PIPE_BLEND_MIN || k->alpha_func == PIPE_BLEND_MAX) + alpha_src = alpha_dst = PIPE_BLENDFACTOR_ONE; + *swap = rev; + memset(f, 0, sizeof(*f)); + f->cop = op[k->rgb_func]; + f->aop = op[k->alpha_func]; + if (rgb_src == PIPE_BLENDFACTOR_SRC_ALPHA_SATURATE) + f->csel1 = USSE_SOP2_SRC_ALPHA_SAT; + else if (!sop2_colour_factor(rgb_src, rev, rev ? &f->csel2 : &f->csel1, + rev ? &f->cmod2 : &f->cmod1)) + return false; + /* (swapped: the source's factor goes with src2, the tile's with src1) */ + return sop2_colour_factor(rgb_dst, rev, rev ? &f->csel1 : &f->csel2, + rev ? &f->cmod1 : &f->cmod2) && + sop2_alpha_factor(alpha_src, rev, rev ? &f->asel2 : &f->asel1, + rev ? &f->amod2 : &f->amod1) && + sop2_alpha_factor(alpha_dst, rev, rev ? &f->asel1 : &f->asel2, + rev ? &f->amod1 : &f->amod2); +} + +static bool +const_factor(unsigned f) +{ + return f == PIPE_BLENDFACTOR_CONST_COLOR || f == PIPE_BLENDFACTOR_CONST_ALPHA || + f == PIPE_BLENDFACTOR_INV_CONST_COLOR || f == PIPE_BLENDFACTOR_INV_CONST_ALPHA; +} + +/* a SOP2 that multiplies src1 by the constant factors fc (its colour) and + * fa (its alpha) -- 0: by one -- the packed blend colour being src2 */ +static void +const_mul(struct usse_sop2 *f, unsigned fc, unsigned fa) +{ + memset(f, 0, sizeof(*f)); + f->cop = f->aop = USSE_SOP2_ADD; + f->csel1 = !fc ? USSE_SOP2_ZERO : + fc == PIPE_BLENDFACTOR_CONST_COLOR || fc == PIPE_BLENDFACTOR_INV_CONST_COLOR ? + USSE_SOP2_SRC2 : USSE_SOP2_SRC2_ALPHA; + f->cmod1 = !fc || fc >= PIPE_BLENDFACTOR_ZERO; /* one, or 1 - the constant */ + f->asel1 = fa ? USSE_SOP2_A_SRC2 : USSE_SOP2_A_ZERO; + f->amod1 = !fa || fa >= PIPE_BLENDFACTOR_ZERO; + /* (src2's terms zero) */ +} + +/* the factors that read the source's alpha, colour; the tile's (an alpha + * factor's colour is its alpha) */ +static bool +reads_src_alpha(unsigned f, bool alpha) +{ + return f == PIPE_BLENDFACTOR_SRC_ALPHA || f == PIPE_BLENDFACTOR_INV_SRC_ALPHA || + (!alpha && f == PIPE_BLENDFACTOR_SRC_ALPHA_SATURATE) || + (alpha && (f == PIPE_BLENDFACTOR_SRC_COLOR || f == PIPE_BLENDFACTOR_INV_SRC_COLOR)); +} + +static bool +reads_dst_alpha(unsigned f, bool alpha) +{ + return f == PIPE_BLENDFACTOR_DST_ALPHA || f == PIPE_BLENDFACTOR_INV_DST_ALPHA || + (!alpha && f == PIPE_BLENDFACTOR_SRC_ALPHA_SATURATE) || + (alpha && (f == PIPE_BLENDFACTOR_DST_COLOR || f == PIPE_BLENDFACTOR_INV_DST_COLOR)); +} + +/* (M46) GL's blending as SOP2s, the blend colour's factors too: PPSSPP + * blends the PSP's fixed colours with them (ONE, CONSTANT_COLOR and the + * like; CONSTANT_ALPHA, ZERO for the stencil it keeps in alpha), which + * were F32 blending in the program, ~30 instructions. The blend colour is + * one sa word of RGBA bytes (the tile's order whatever the target), and a + * constant factor of the source's is a SOP2 multiplying the packed colour + * first, of the tile's one multiplying the tile into a temporary; the + * blending's then has ONE there. When the rest reads the source's alpha + * as it was, a constant alpha factor of the source's (the tile's alpha + * factor ZERO) multiplies the result's alpha after. False: what that + * cannot do (a factor reading what was multiplied), and SGX_SOP2_CONST=0. */ +static bool +sop2_plan(struct comp *c, const struct sgx_blend_key *k) +{ + struct sgx_blend_key m = *k; + bool mm_c = k->rgb_func == PIPE_BLEND_MIN || k->rgb_func == PIPE_BLEND_MAX; + bool mm_a = k->alpha_func == PIPE_BLEND_MIN || k->alpha_func == PIPE_BLEND_MAX; + unsigned cs = !mm_c && const_factor(k->rgb_src) ? k->rgb_src : 0; + unsigned cd = !mm_c && const_factor(k->rgb_dst) ? k->rgb_dst : 0; + unsigned as = !mm_a && const_factor(k->alpha_src) ? k->alpha_src : 0; + unsigned ad = !mm_a && const_factor(k->alpha_dst) ? k->alpha_dst : 0; + bool post = false; + + c->sop2_pre_src = c->sop2_pre_dst = c->sop2_post = false; + if (!cs && !cd && !as && !ad) + return sop2_blend(k, &c->sop2_factors, &c->sop2_swap); + if (!k->enable || (getenv("SGX_SOP2_CONST") && !atoi(getenv("SGX_SOP2_CONST")))) + return false; + if (cs) + m.rgb_src = PIPE_BLENDFACTOR_ONE; + if (cd) + m.rgb_dst = PIPE_BLENDFACTOR_ONE; + if (as) + m.alpha_src = PIPE_BLENDFACTOR_ONE; + if (ad) + m.alpha_dst = PIPE_BLENDFACTOR_ONE; + /* the source's colour multiplied: nothing else may read it */ + if (cs && (m.rgb_dst == PIPE_BLENDFACTOR_SRC_COLOR || + m.rgb_dst == PIPE_BLENDFACTOR_INV_SRC_COLOR)) + return false; + /* its alpha: nothing else may read that -- or, the tile's alpha factor + * ZERO, the result's alpha is multiplied after instead */ + if (as && (reads_src_alpha(m.rgb_src, false) || reads_src_alpha(m.rgb_dst, false) || + reads_src_alpha(m.alpha_dst, true))) { + if (k->alpha_dst != PIPE_BLENDFACTOR_ZERO) + return false; + post = true; + } + /* the tile's, the same */ + if (cd && (m.rgb_src == PIPE_BLENDFACTOR_DST_COLOR || + m.rgb_src == PIPE_BLENDFACTOR_INV_DST_COLOR)) + return false; + if (ad && (reads_dst_alpha(m.rgb_src, false) || reads_dst_alpha(m.rgb_dst, false) || + reads_dst_alpha(m.alpha_src, true))) + return false; + if (!sop2_blend(&m, &c->sop2_factors, &c->sop2_swap)) + return false; + if (cs || (as && !post)) { + c->sop2_pre_src = true; + const_mul(&c->sop2_src_f, cs, post ? 0 : as); + } + if (cd || ad) { + c->sop2_pre_dst = true; + const_mul(&c->sop2_dst_f, cd, ad); + } + if (post) { + c->sop2_post = true; + const_mul(&c->sop2_post_f, 0, as); + } + return true; +} + +/* (M46) the blending's SOP2s on the colour packed (and the constant's + * around them, sop2_plan), the last one the program's end; t1 and t2 + * temporaries for the tile multiplied and the result before its alpha */ +static void +emit_sop2(struct comp *c, struct usse_reg packed, struct usse_reg t1, struct usse_reg t2) +{ + struct usse_reg o0 = usse_reg(USSE_OUTPUT, 0), tile = o0; + struct usse_reg k = usse_reg(USSE_SA, c->blend_sa >= 0 ? c->blend_sa : 0); + + if (c->sop2_pre_src) + emit(c, usse_sop2(packed, packed, k, &c->sop2_src_f)); + if (c->sop2_pre_dst) { + emit(c, usse_sop2(t1, o0, k, &c->sop2_dst_f)); + tile = t1; + } + if (c->sop2_post) { + emit(c, usse_sop2(t2, c->sop2_swap ? tile : packed, c->sop2_swap ? packed : tile, + &c->sop2_factors)); + emit(c, usse_sop2(o0, t2, k, &c->sop2_post_f) | USSE_END); + } else { + emit(c, usse_sop2(o0, c->sop2_swap ? tile : packed, c->sop2_swap ? packed : tile, + &c->sop2_factors) | USSE_END); + } +} + +/* (M47) the scalar lowering's filter for a vertex shader: its dot products + * left whole (VDP), SGX_NO_VS_VEC=1 not */ +static bool is_vec_op(nir_op op); + +static bool +vec_filter(const nir_instr *instr, const void *data) +{ + const nir_alu_instr *alu; + + if (instr->type != nir_instr_type_alu) + return true; + alu = nir_instr_as_alu(instr); + return !is_dot(alu->op) && !(is_vec_op(alu->op) && alu->def.bit_size == 32); +} + +static nir_instr_filter_cb +scalar_filter(const nir_shader *s) +{ + static int off = -1; + + if (off < 0) + off = getenv("SGX_NO_VS_VEC") != NULL; + return s->info.stage == MESA_SHADER_VERTEX && !off ? vec_filter : NULL; +} + +static void +optimize(nir_shader *s) +{ + /* ifs of up to 32 instructions a side flattened (selects); bigger ones + * branch -- an unrolled loop with a break flattened whole needed 65 + * registers a pixel (M20). SGX_FLATTEN_LIMIT=n to try others. */ + const nir_opt_peephole_select_options flatten = { + .limit = getenv("SGX_FLATTEN_LIMIT") ? atoi(getenv("SGX_FLATTEN_LIMIT")) : 32, + .indirect_load_ok = true, .expensive_alu_ok = true, + .discard_ok = true, /* if (c) discard: terminate_if(c) */ + }; + bool progress; + + do { + progress = false; + NIR_PASS(progress, s, nir_lower_vars_to_ssa); + NIR_PASS(progress, s, nir_lower_alu_to_scalar, scalar_filter(s), NULL); + NIR_PASS(progress, s, nir_lower_phis_to_scalar, NULL, NULL); + NIR_PASS(progress, s, nir_opt_copy_prop); + NIR_PASS(progress, s, nir_opt_remove_phis); + NIR_PASS(progress, s, nir_opt_dce); + NIR_PASS(progress, s, nir_opt_dead_cf); + NIR_PASS(progress, s, nir_opt_cse); + NIR_PASS(progress, s, nir_opt_if, nir_opt_if_optimize_phi_true_false); + NIR_PASS(progress, s, nir_opt_peephole_select, &flatten); + NIR_PASS(progress, s, nir_opt_algebraic); + NIR_PASS(progress, s, nir_opt_constant_folding); + NIR_PASS(progress, s, nir_opt_undef); + NIR_PASS(progress, s, nir_opt_loop_unroll); + } while (progress); +} + +/* GL's blending (and colour mask) for render target 0 into the shader: + * NIR's own lowering, which reads the destination with load_output */ +/* (M43) the colour to an intensity target: R into all four channels */ +static bool +lower_intensity_target(nir_builder *b, nir_intrinsic_instr *in, void *data) +{ + nir_io_semantics sem; + nir_def *v; + + if (in->intrinsic != nir_intrinsic_store_output) + return false; + sem = nir_intrinsic_io_semantics(in); + if ((sem.location != FRAG_RESULT_COLOR && sem.location != FRAG_RESULT_DATA0) || + sem.dual_source_blend_index || nir_intrinsic_component(in)) + return false; + v = in->src[0].ssa; + b->cursor = nir_before_instr(&in->instr); + nir_src_rewrite(&in->src[0], nir_replicate(b, nir_channel(b, v, 0), 4)); + nir_intrinsic_set_write_mask(in, 0xf); + return true; +} + +/* (M43) the colour to an sRGB target: its RGB encoded on the way out (a + * store of the colour), decoded on the way in (blending's fetch of it) */ +static bool +lower_srgb_target(nir_builder *b, nir_intrinsic_instr *in, void *data) +{ + nir_io_semantics sem; + + if (in->intrinsic != nir_intrinsic_store_output && in->intrinsic != nir_intrinsic_load_output) + return false; + sem = nir_intrinsic_io_semantics(in); + if (sem.location != FRAG_RESULT_COLOR && sem.location != FRAG_RESULT_DATA0) + return false; + if (in->intrinsic == nir_intrinsic_store_output) { + nir_def *v = in->src[0].ssa; + + if (v->num_components < 3) + return false; + b->cursor = nir_before_instr(&in->instr); + nir_def *rgb = nir_format_linear_to_srgb(b, nir_channels(b, v, 0x7)); + nir_def *out = v->num_components == 4 ? + nir_vec4(b, nir_channel(b, rgb, 0), nir_channel(b, rgb, 1), + nir_channel(b, rgb, 2), nir_channel(b, v, 3)) : rgb; + + nir_src_rewrite(&in->src[0], out); + return true; + } + if (!sem.fb_fetch_output || in->def.num_components < 3) + return false; + b->cursor = nir_after_instr(&in->instr); + { + nir_def *v = &in->def; + nir_def *rgb = nir_format_srgb_to_linear(b, nir_channels(b, v, 0x7)); + nir_def *lin = v->num_components == 4 ? + nir_vec4(b, nir_channel(b, rgb, 0), nir_channel(b, rgb, 1), + nir_channel(b, rgb, 2), nir_channel(b, v, 3)) : rgb; + + nir_def_rewrite_uses_after(v, lin); + } + return true; +} + +static bool +lower_every_offset(const nir_instr *instr, const void *data) +{ + return true; +} + +/* ---- (M46) a lookup's clamp the draw finds does nothing ------------------ */ + +/* s (sign 1 or -1) into e: constants, uniform words (a constant offset), + * fneg and fadd of them -- two words at most */ +static bool +uexpr_add(nir_scalar s, int sign, struct sgx_uexpr *e, unsigned depth) +{ + s = nir_scalar_chase_movs(s); + if (depth > 4) + return false; + if (nir_scalar_is_const(s)) { + if (s.def->bit_size != 32) + return false; + e->k += sign * nir_scalar_as_float(s); + return true; + } + if (nir_scalar_is_alu(s)) { + nir_op op = nir_scalar_alu_op(s); + + if (op == nir_op_fneg) + return uexpr_add(nir_scalar_chase_alu_src(s, 0), -sign, e, depth + 1); + if (op == nir_op_fadd) + return uexpr_add(nir_scalar_chase_alu_src(s, 0), sign, e, depth + 1) && + uexpr_add(nir_scalar_chase_alu_src(s, 1), sign, e, depth + 1); + return false; + } + if (nir_scalar_is_intrinsic(s) && nir_scalar_intrinsic_op(s) == nir_intrinsic_load_uniform) { + nir_intrinsic_instr *in = nir_instr_as_intrinsic(nir_def_instr(s.def)); + unsigned w; + + if (!nir_src_is_const(in->src[0]) || in->def.bit_size != 32) + return false; + w = (nir_intrinsic_base(in) + nir_src_as_uint(in->src[0])) * 4 + s.comp; + for (unsigned i = 0; i < 2; i++) { + if (!e->s[i]) { + e->w[i] = w; + e->s[i] = sign; + return true; + } + } + } + return false; +} + +float +sgx_uexpr_eval(const struct sgx_uexpr *e, const float *u, unsigned nwords) +{ + float v = e->k; + + /* (in the order the program adds them: word 0's first) */ + for (unsigned i = 0; i < 2; i++) + if (e->s[i]) + v += (e->w[i] < nwords && u ? u[e->w[i]] : 0.0f) * e->s[i]; + return v; +} + +/* a varying's component as it comes (load_deref of a shader input): its + * gl_varying_slot and component */ +static bool +varying_scalar(nir_scalar s, uint8_t *slot, uint8_t *comp) +{ + nir_intrinsic_instr *in; + nir_deref_instr *d; + + if (!nir_scalar_is_intrinsic(s) || nir_scalar_intrinsic_op(s) != nir_intrinsic_load_deref) + return false; + in = nir_instr_as_intrinsic(nir_def_instr(s.def)); + d = nir_src_as_deref(in->src[0]); + if (!d || d->deref_type != nir_deref_type_var || !d->var || + d->var->data.mode != nir_var_shader_in || !glsl_type_is_vector_or_scalar(d->var->type) || + !glsl_type_is_float(glsl_without_array(d->var->type)) || s.def->bit_size != 32 || + d->var->data.location >= VARYING_SLOT_MAX) + return false; + *slot = d->var->data.location; + *comp = d->var->data.location_frac + s.comp; + return true; +} + +/* s as clamp(x, lo, hi) [+ off]: fmin(fmax(x, lo), hi) or fmax(fmin(x, + * hi), lo), x a varying's component, lo, hi and off uniforms' */ +static bool +clamped_coord(nir_scalar s, nir_scalar *x, uint8_t *slot, uint8_t *comp, struct sgx_uexpr *lo, + struct sgx_uexpr *hi, struct sgx_uexpr *off) +{ + nir_op outer, inner; + + memset(off, 0, sizeof(*off)); + s = nir_scalar_chase_movs(s); + if (!nir_scalar_is_alu(s)) + return false; + if (nir_scalar_alu_op(s) == nir_op_fadd) { + bool found = false; + + for (unsigned i = 0; i < 2 && !found; i++) { + nir_scalar a = nir_scalar_chase_alu_src(s, i); + + memset(off, 0, sizeof(*off)); + if (nir_scalar_is_alu(a) && + (nir_scalar_alu_op(a) == nir_op_fmin || nir_scalar_alu_op(a) == nir_op_fmax) && + uexpr_add(nir_scalar_chase_alu_src(s, !i), 1, off, 0)) { + s = nir_scalar_chase_movs(a); + found = true; + } + } + if (!found) + return false; + } + outer = nir_scalar_alu_op(s); + if (outer != nir_op_fmin && outer != nir_op_fmax) + return false; + inner = outer == nir_op_fmin ? nir_op_fmax : nir_op_fmin; + for (unsigned i = 0; i < 2; i++) { + nir_scalar in = nir_scalar_chase_movs(nir_scalar_chase_alu_src(s, i)); + nir_scalar bound = nir_scalar_chase_alu_src(s, !i); + + if (!nir_scalar_is_alu(in) || nir_scalar_alu_op(in) != inner) + continue; + for (unsigned j = 0; j < 2; j++) { + nir_scalar v = nir_scalar_chase_movs(nir_scalar_chase_alu_src(in, j)); + nir_scalar b2 = nir_scalar_chase_alu_src(in, !j); + + memset(lo, 0, sizeof(*lo)); + memset(hi, 0, sizeof(*hi)); + if (!varying_scalar(v, slot, comp)) + continue; + if (uexpr_add(outer == nir_op_fmin ? b2 : bound, 1, lo, 0) && + uexpr_add(outer == nir_op_fmin ? bound : b2, 1, hi, 0)) { + *x = v; + return true; + } + } + } + return false; +} + +/* tex as a TClampST lookup: a plain 2D one, both coordinates clamped */ +static bool +texclamp_of(nir_tex_instr *tex, struct sgx_texclamp *tc, nir_scalar x[2]) +{ + int ci = nir_tex_instr_src_index(tex, nir_tex_src_coord); + + if (tex->op != nir_texop_tex || tex->sampler_dim != GLSL_SAMPLER_DIM_2D || tex->is_array || + tex->is_shadow || ci < 0 || tex->num_srcs != 1 || tex->coord_components != 2 || + tex->texture_index != tex->sampler_index || tex->texture_index >= 8) + return false; + memset(tc, 0, sizeof(*tc)); + tc->unit = tex->texture_index; + for (unsigned c = 0; c < 2; c++) + if (!clamped_coord(nir_get_scalar(tex->src[ci].src.ssa, c), &x[c], &tc->slot[c], + &tc->comp[c], &tc->lo[c], &tc->hi[c], &tc->off[c])) + return false; + return true; +} + +/* the shader's TClampST lookup: one, its unit's only lookup */ +bool +sgx_fs_texclamp(const nir_shader *fs, struct sgx_texclamp *tc) +{ + nir_function_impl *impl = nir_shader_get_entrypoint((nir_shader *)fs); + unsigned found = 0, on_unit[8] = { 0 }; + + if (!impl || getenv("SGX_NO_TEXCLAMP_FREE")) + return false; + nir_foreach_block(block, impl) { + nir_foreach_instr(instr, block) { + nir_tex_instr *tex; + struct sgx_texclamp t; + nir_scalar x[2]; + + if (instr->type != nir_instr_type_tex) + continue; + tex = nir_instr_as_tex(instr); + if (tex->texture_index < 8) + on_unit[tex->texture_index]++; + if (!found && texclamp_of(tex, &t, x)) { + *tc = t; + found = 1; + } + } + } + return found && on_unit[tc->unit] == 1; +} + +/* (M46) the vertex shader's varying slot, component comp, as it writes it: + * one store, in a shader of one block, of an attribute's component copied + * (PPSSPP's through-mode texture coordinates). Its value at each vertex + * is the attribute's then, bit for bit */ +bool +sgx_vs_varying_attr(const nir_shader *vs, unsigned slot, unsigned comp, unsigned *attr, + unsigned *acomp) +{ + nir_function_impl *impl = nir_shader_get_entrypoint((nir_shader *)vs); + unsigned stores = 0; + bool ok = false; + + if (!impl || nir_start_block(impl) != nir_impl_last_block(impl)) + return false; + nir_foreach_block(block, impl) { + nir_foreach_instr(instr, block) { + nir_intrinsic_instr *in; + nir_deref_instr *d; + nir_variable *var; + nir_scalar v; + unsigned frac; + + if (instr->type != nir_instr_type_intrinsic) + continue; + in = nir_instr_as_intrinsic(instr); + if (in->intrinsic != nir_intrinsic_store_deref) + continue; + d = nir_src_as_deref(in->src[0]); + var = d ? nir_deref_instr_get_variable(d) : NULL; + if (!var || var->data.mode != nir_var_shader_out) + continue; + /* (an array or a block over the slot: not followed) */ + if (d->deref_type != nir_deref_type_var || !glsl_type_is_vector_or_scalar(var->type)) { + if (var->data.location <= (int)slot && + var->data.location + (int)glsl_count_attribute_slots(var->type, false) > (int)slot) + return false; + continue; + } + frac = var->data.location_frac; + if (var->data.location != (int)slot || comp < frac || + comp >= frac + glsl_get_vector_elements(var->type) || + !(nir_intrinsic_write_mask(in) >> (comp - frac) & 1)) + continue; + stores++; + v = nir_scalar_chase_movs(nir_get_scalar(in->src[1].ssa, comp - frac)); + ok = false; + if (nir_scalar_is_intrinsic(v) && nir_scalar_intrinsic_op(v) == nir_intrinsic_load_deref && + v.def->bit_size == 32) { + nir_intrinsic_instr *ld = nir_instr_as_intrinsic(nir_def_instr(v.def)); + nir_deref_instr *ldd = nir_src_as_deref(ld->src[0]); + + if (ldd && ldd->deref_type == nir_deref_type_var && ldd->var && + ldd->var->data.mode == nir_var_shader_in && + glsl_type_is_vector_or_scalar(ldd->var->type) && + glsl_type_is_float(ldd->var->type)) { + *attr = ldd->var->data.driver_location; + *acomp = ldd->var->data.location_frac + v.comp; + ok = true; + } + } + } + } + return stores == 1 && ok; +} + +/* the variant's lookup at the varying itself (sgx_blend_key.texclamp_free) */ +static bool +lower_texclamp_free(nir_shader *s, unsigned units) +{ + nir_function_impl *impl = nir_shader_get_entrypoint(s); + nir_builder b = nir_builder_create(impl); + bool progress = false; + + nir_foreach_block(block, impl) { + nir_foreach_instr(instr, block) { + nir_tex_instr *tex; + struct sgx_texclamp t; + nir_scalar x[2]; + + if (instr->type != nir_instr_type_tex) + continue; + tex = nir_instr_as_tex(instr); + if (!(units >> tex->texture_index & 1) || !texclamp_of(tex, &t, x)) + continue; + b.cursor = nir_before_instr(instr); + nir_src_rewrite(&tex->src[nir_tex_instr_src_index(tex, nir_tex_src_coord)].src, + nir_vec2(&b, nir_mov_scalar(&b, x[0]), nir_mov_scalar(&b, x[1]))); + progress = true; + } + } + return nir_progress(progress, impl, nir_metadata_control_flow); +} + +/* (M46) whether k's blending leaves the target as it is where the source + * colour is 0, on the channels written: an add or a reverse subtract onto + * the destination times one (0 times any source factor is 0) -- PPSSPP's + * blend-colour additions (God of War's GLSL19: src * const + dst) */ +static bool +blend_keeps_dst_for_zero(const struct sgx_blend_key *k) +{ + bool rgb = (k->rgb_func == PIPE_BLEND_ADD || k->rgb_func == PIPE_BLEND_REVERSE_SUBTRACT) && + k->rgb_dst == PIPE_BLENDFACTOR_ONE; + bool a = (k->alpha_func == PIPE_BLEND_ADD || k->alpha_func == PIPE_BLEND_REVERSE_SUBTRACT) && + k->alpha_dst == PIPE_BLENDFACTOR_ONE; + + return k->enable && !k->logicop && (rgb || !(k->colormask & 7)) && (a || !(k->colormask & 8)); +} + +/* (M46) Discard as a source of 0, for a blend that leaves the target as it + * is then (blend_keeps_dst_for_zero): the colour stored is 0 where a + * discard would have taken the pixel -- the same pixels, depth written as + * the emulation writes it (M19: no punch-through pass yet). The program + * has no discard left, so the SOP2 may blend it, and the tile is not read + * back for the pixels discarded (twice a layer's cost, glverts -k). Only + * the plain shape: one block, the discards before the one colour store, + * nothing else stored (SGX_KEEP_DISCARD=1: none). */ +static bool +discard_shape_ok(const nir_shader *s) +{ + nir_function_impl *impl = nir_shader_get_entrypoint((nir_shader *)s); + bool stored = false; + + if (getenv("SGX_KEEP_DISCARD") || exec_list_length(&impl->body) != 1 || + (s->info.outputs_written & ~(BITFIELD64_BIT(FRAG_RESULT_COLOR) | + BITFIELD64_BIT(FRAG_RESULT_DATA0)))) + return false; + nir_foreach_block(block, impl) { + nir_foreach_instr(instr, block) { + nir_intrinsic_instr *in; + + if (instr->type != nir_instr_type_intrinsic) + continue; + in = nir_instr_as_intrinsic(instr); + switch (in->intrinsic) { + case nir_intrinsic_terminate_if: + case nir_intrinsic_demote_if: + case nir_intrinsic_terminate: + case nir_intrinsic_demote: + if (stored) + return false; + break; + case nir_intrinsic_store_deref: + case nir_intrinsic_store_output: + if (stored) + return false; + stored = true; + break; + default: + break; + } + } + } + return stored; +} + +/* the same after nir_lower_io: the discards' conditions or'ed, the store's + * colour 0 where that is true */ +static bool +lower_discard_to_zero(nir_shader *s) +{ + nir_function_impl *impl = nir_shader_get_entrypoint(s); + nir_builder b = nir_builder_create(impl); + nir_intrinsic_instr *store = NULL; + nir_def *kill = NULL; + + nir_foreach_block(block, impl) { + nir_foreach_instr_safe(instr, block) { + nir_intrinsic_instr *in; + + if (instr->type != nir_instr_type_intrinsic) + continue; + in = nir_instr_as_intrinsic(instr); + if (in->intrinsic == nir_intrinsic_store_output) { + store = in; + continue; + } + if (in->intrinsic != nir_intrinsic_terminate_if && + in->intrinsic != nir_intrinsic_demote_if && + in->intrinsic != nir_intrinsic_terminate && in->intrinsic != nir_intrinsic_demote) + continue; + b.cursor = nir_before_instr(instr); + { + nir_def *cond = in->intrinsic == nir_intrinsic_terminate_if || + in->intrinsic == nir_intrinsic_demote_if ? + in->src[0].ssa : nir_imm_true(&b); + + kill = kill ? nir_ior(&b, kill, cond) : cond; + } + nir_instr_remove(instr); + } + } + if (!store || !kill) + return false; + b.cursor = nir_before_instr(&store->instr); + { + nir_def *v = store->src[0].ssa; + + nir_src_rewrite(&store->src[0], + nir_bcsel(&b, kill, nir_imm_zero(&b, v->num_components, v->bit_size), v)); + } + s->info.fs.uses_discard = false; + return nir_progress(true, impl, nir_metadata_control_flow); +} + +static void +lower_blend(nir_shader *s, const struct sgx_blend_key *k) +{ + nir_lower_blend_options o = { .scalar_blend_const = true }; + + /* (floats: not clamped, M43) */ + o.rt[0].format = k->rt_kind == SGX_RT_F16X4 ? PIPE_FORMAT_R16G16B16A16_FLOAT : + k->rt_kind == SGX_RT_F16X2 ? PIPE_FORMAT_R16G16_FLOAT : + k->rt_kind == SGX_RT_F32 ? PIPE_FORMAT_R32_FLOAT : + k->rt_kind == SGX_RT_F32X2 ? PIPE_FORMAT_R32G32_FLOAT : + k->rt_srgb ? PIPE_FORMAT_B8G8R8A8_SRGB : PIPE_FORMAT_B8G8R8A8_UNORM; + o.rt[0].colormask = k->colormask; + if (k->enable) { + o.rt[0].rgb.func = k->rgb_func; + o.rt[0].rgb.src_factor = k->rgb_src; + o.rt[0].rgb.dst_factor = k->rgb_dst; + o.rt[0].alpha.func = k->alpha_func; + o.rt[0].alpha.src_factor = k->alpha_src; + o.rt[0].alpha.dst_factor = k->alpha_dst; + } else { + o.rt[0].rgb.func = o.rt[0].alpha.func = PIPE_BLEND_ADD; + o.rt[0].rgb.src_factor = o.rt[0].alpha.src_factor = PIPE_BLENDFACTOR_ONE; + o.rt[0].rgb.dst_factor = o.rt[0].alpha.dst_factor = PIPE_BLENDFACTOR_ZERO; + } + NIR_PASS(_, s, nir_lower_blend, &o); +} + +/* (M46) a vertex shader's varyings made straight into their output + * registers: a component stored once, by a store of the program's one + * block, of a value an fadd, fmul, fmin, fmax, ffma or fsat makes (V32NMAD + * and FMAD, which write either lane of an output) and nothing else reads -- + * not the position's, nor a varying the vertex side does more to (M39). + * define() puts it there; the store has nothing to move. + * SGX_VS_OUT_MOVES=1: as before */ +static void +plan_vs_outputs(struct comp *c, nir_function_impl *impl) +{ + unsigned *stores; + + if (getenv("SGX_VS_OUT_MOVES") || exec_list_length(&impl->body) != 1 || + !(c->vs_out = calloc(c->nvalues, sizeof(*c->vs_out))) || + !(stores = calloc(c->nvalues, sizeof(*stores)))) + return; + for (int pass = 0; pass < 2; pass++) { + nir_foreach_block(block, impl) { + nir_foreach_instr(instr, block) { + nir_intrinsic_instr *in; + unsigned loc, mask, comp; + + if (instr->type != nir_instr_type_intrinsic) + continue; + in = nir_instr_as_intrinsic(instr); + if (in->intrinsic != nir_intrinsic_store_output) + continue; + loc = nir_intrinsic_io_semantics(in).location + nir_src_as_uint(*nir_get_io_offset_src(in)); + mask = nir_intrinsic_write_mask(in); + comp = nir_intrinsic_component(in); + for (unsigned i = 0; i < in->src[0].ssa->num_components; i++) { + nir_scalar sc = nir_scalar_chase_movs(nir_get_scalar(in->src[0].ssa, i)); + struct operand o = resolve(nir_get_scalar(in->src[0].ssa, i)); + int k = -1; + nir_op op; + + if (!(mask & 1 << i) || comp + i >= 4 || o.is_const) + continue; + /* (pass 0 counts the stores of each value) */ + if (!pass) { + stores[o.id]++; + continue; + } + /* (the varying the fragment shader reads as it is; one it + * reads moved too -- SGX_FIX_SHIFT -- vertex_output() makes + * from there) */ + for (unsigned j = 0; j < c->nvaryings; j++) + if (c->varying_slot[j] == loc && !(c->vary_fix && c->vary_fix[j])) + k = k < 0 ? (int)(1 + j) : -2; + if (k <= 0 || o.neg || o.abs || + stores[o.id] != 1 || !nir_scalar_is_alu(sc) || + o.id != sc.def->index * 4 + sc.comp || !list_is_singular(&sc.def->uses)) + continue; + op = nir_scalar_alu_op(sc); + /* (M47: a vector instruction's components, each its own) */ + if (sc.def->num_components != 1 && !is_vec_op(op)) + continue; + if (op != nir_op_fadd && op != nir_op_fmul && op != nir_op_fmin && + op != nir_op_fmax && op != nir_op_ffma && op != nir_op_fsat && !is_dot(op)) + continue; + /* (its one use the store's, or a vec only the store reads) */ + { + nir_src *use = list_first_entry(&sc.def->uses, nir_src, use_link); + nir_instr *u = nir_src_is_if(use) ? NULL : nir_src_use_instr(use); + + if (u != instr && !(u && u->type == nir_instr_type_alu && + (nir_op_is_vec(nir_instr_as_alu(u)->op) || + nir_instr_as_alu(u)->op == nir_op_mov) && + &nir_instr_as_alu(u)->def == in->src[0].ssa && + list_is_singular(&in->src[0].ssa->uses))) + continue; + } + c->vs_out[o.id] = 4 * k + comp + i + 1; + } + } + } + } + free(stores); +} + +/* (M47) the vectors a vertex program's dot products read that are values + * made one by one -- a vector times a matrix's results times the next + * matrix, a normal made unit length -- made in registers in a row + * (struct vgroup): a dot product of them loads them into an internal + * register with one instruction, not one a component. Only values made by + * instructions that write any register (V32NMAD, FMAD, VDP; INT32 VMOV's + * selects), each in one group, none bound for an output */ +static bool +groupable(nir_scalar sc) +{ + if (!nir_scalar_is_alu(sc) || sc.def->num_components != 1 || sc.def->bit_size != 32) + return false; + switch (nir_scalar_alu_op(sc)) { + case nir_op_fadd: case nir_op_fmul: case nir_op_ffma: case nir_op_fmin: case nir_op_fmax: + case nir_op_fsat: case nir_op_fdot2: case nir_op_fdot3: case nir_op_fdot4: case nir_op_fdph: + case nir_op_b32csel: + return true; + default: + return false; + } +} + +static void +plan_groups(struct comp *c, nir_function_impl *impl) +{ + if (!c->vec || getenv("SGX_NO_VGROUPS") || + !(c->group_of = malloc(c->nvalues * sizeof(*c->group_of)))) + return; + for (unsigned i = 0; i < c->nvalues; i++) + c->group_of[i] = -1; + nir_foreach_block(block, impl) { + nir_foreach_instr(instr, block) { + nir_alu_instr *alu; + + if (instr->type != nir_instr_type_alu || !is_dot(nir_instr_as_alu(instr)->op)) + continue; + alu = nir_instr_as_alu(instr); + for (unsigned i = 0; i < 2; i++) { + unsigned n = nir_ssa_alu_instr_src_components(alu, i), ids[4], mask = 0, nm = 0; + bool ok = true; + + for (unsigned k = 0; k < n && ok; k++) { + nir_scalar sc = nir_scalar_chase_movs(nir_get_scalar(alu->src[i].src.ssa, + alu->src[i].swizzle[k])); + struct operand o = resolve(nir_get_scalar(alu->src[i].src.ssa, + alu->src[i].swizzle[k])); + + if (o.is_const) + continue; + ok = groupable(sc) && !o.neg && !o.abs && o.id == sc.def->index * 4 + sc.comp && + c->group_of[o.id] < 0 && !(c->vs_out && c->vs_out[o.id]); + for (unsigned j = 0; j < k && ok; j++) + ok = !(mask & 1u << j) || ids[j] != o.id; + ids[k] = o.id; + mask |= 1u << k; + nm++; + } + if (!ok || nm < 2 || !(c->vgroups = realloc(c->vgroups, (c->nvgroups + 1) * + sizeof(*c->vgroups)))) + continue; + c->vgroups[c->nvgroups] = (struct vgroup){ .base = -1, .n = n, .mask = mask }; + u_foreach_bit(k, mask) + c->group_of[ids[k]] = c->nvgroups * 4 + k; + c->nvgroups++; + } + } + } +} + +/* A vertex's outputs into o0.. -- the position, then the varyings, four + * words each, as the TA state's vertex size says -- and out to the tiler. + * What the shader does not write is 0, w 1; the varyings it does are there + * already. */ +#define USSE_EMIT_VERTEX_END 0xfb275000a0200000ull +#define USSE_PHAS_BRANCHES 0xfa44270000000000ull + +/* the position's x and y as a x + b w, a and b the draw's (the TA's clip + * rectangle, sgx_draw.c: a_x, a_y, b_x, b_y from an even sa word) -- (M47) + * both at once: t = w (b_x, b_y), then (x, y) (a_x, a_y) + t (VMAD2) where x + * and y are a register pair; else a lane at a time (M46: x a + t, an FMAD; + * SGX_VS_OUT_MOVES=1 a product and a sum) */ +static void +position_xy(struct comp *c, const struct operand *ov, struct scratch *s) +{ + static int moves = -1; + struct usse_reg t, w, a = usse_reg(USSE_SA, c->vs->clip_sa); + unsigned l; + int b; + + if (moves < 0) + moves = getenv("SGX_VS_OUT_MOVES") != NULL; + w = get(c, ov[3], TAKES_ALL, s); + l = w.bank == USSE_INTERNAL ? w.num & 3 : w.bank == USSE_SPECIAL ? 0 : w.num & 1; + if ((b = block_try(c, 2, 2)) < 0) { + /* (no pair free: w b a lane at a time) */ + unsigned t0 = scratch_take(c, s), t1 = scratch_take(c, s); + + emit(c, usse_fop(USSE_NMAD_MUL, treg(c, t0), w, usse_reg(USSE_SA, c->vs->clip_sa + 2))); + emit(c, usse_fop(USSE_NMAD_MUL, treg(c, t1), w, usse_reg(USSE_SA, c->vs->clip_sa + 3))); + for (unsigned i = 0; i < 2; i++) { + struct usse_reg u = treg(c, scratch_take(c, s)); + + emit(c, usse_fop(USSE_NMAD_MUL, u, get(c, ov[i], TAKES_ALL, s), + usse_reg(USSE_SA, c->vs->clip_sa + i))); + emit(c, usse_fop(USSE_NMAD_ADD, usse_reg(USSE_OUTPUT, i), u, treg(c, i ? t1 : t0))); + } + scratch_give_back(c, s); + return; + } + assert(s->n + 2 <= ARRAY_SIZE(s->reg)); + s->reg[s->n++] = b; + s->reg[s->n++] = b + 1; + t = treg(c, b); + emit(c, usse_fop_ex(USSE_NMAD_MUL, t, 3, w, USSE_SW(l, l, l, l), + usse_reg(USSE_SA, c->vs->clip_sa + 2), USSE_SW2_XYZW)); + if (!moves && pair_ok(c, ov, false, false) && !ov[0].is_const && !same_operand(&ov[0], &ov[1]) && + (op_reg(c, &ov[0]).bank == USSE_TEMP || op_reg(c, &ov[0]).bank == USSE_PA)) { + emit(c, usse_fmad_ex(usse_reg(USSE_OUTPUT, 0), 3, op_reg(c, &ov[0]), 4, a, 4, t, 4)); + scratch_give_back(c, s); + return; + } + for (unsigned i = 0; i < 2; i++) { + struct usse_reg ai = usse_reg(USSE_SA, c->vs->clip_sa + i), ti = treg(c, b + i), u; + + if (!moves && !ov[i].neg) { + emit(c, usse_fmad(usse_reg(USSE_OUTPUT, i), get(c, ov[i], TAKES_ABS | TAKES_LANE_Y, s), + ai, ti)); + continue; + } + u = treg(c, scratch_take(c, s)); + emit(c, usse_fop(USSE_NMAD_MUL, u, get(c, ov[i], TAKES_ALL, s), ai)); + emit(c, usse_fop(USSE_NMAD_ADD, usse_reg(USSE_OUTPUT, i), u, ti)); + } + scratch_give_back(c, s); +} + +static void +vertex_output(struct comp *c) +{ + struct scratch s = { 0 }; + + if (!c->have_vout[0][0] || !c->have_vout[0][1] || !c->have_vout[0][3]) { + fail(c, "no position written"); + return; + } + for (unsigned k = 0, nscaled = 0; k <= c->nvaryings; k++) { + unsigned fix = k && c->vary_fix ? c->vary_fix[k - 1] : 0; + struct operand ov[4]; + bool skip[4]; + + for (unsigned i = 0; i < 4; i++) { + /* (M39) a lookup's varying: the divisor where the PDS divides */ + unsigned from = SGX_FIX_DIV(fix) && i == SGX_PROJ_DIV ? SGX_FIX_DIV(fix) : i; + /* (M46) a lookup's coordinates moved into x and y */ + if (i < 2 && SGX_FIX_SHIFT_OF(fix)) + from = SGX_FIX_SHIFT_OF(fix) + i; + ov[i] = c->vout[k][from]; + skip[i] = k && c->have_vout[k][i] && !fix; + if (!c->have_vout[k][from]) { + ov[i].is_const = true; + ov[i].c = from == 3 ? 1.0f : 0.0f; + ov[i].u = f32_bits(ov[i].c); + } + } + if (k == 0) + position_xy(c, ov, &s); + for (unsigned i = k ? 0 : 2; i < 4; i++) { + struct operand *o = &ov[i]; + + if (skip[i]) + continue; + if (i < 2 && (fix & SGX_FIX_SCALE)) { + /* x and y times a rectangle texture's 1 / width, 1 / height */ + emit(c, usse_fop(USSE_NMAD_MUL, usse_reg(USSE_OUTPUT, 4 * k + i), + get(c, *o, TAKES_ALL, &s), + usse_reg(USSE_SA, c->vs->fix_sa + 2 * nscaled + i))); + } else if (!(i & 1) && i + 1 < 4 && !skip[i + 1] && + !(i + 1 < 2 && (fix & SGX_FIX_SCALE)) && pair_ok(c, o, false, true) && + !o[0].is_const && !o[0].abs && !same_operand(&o[0], &o[1])) { + /* (M47) two in a register pair: one move */ + emit(c, usse_fmov2(usse_reg(USSE_OUTPUT, 4 * k + i), op_reg(c, o))); + i++; + } else { + move_into(c, usse_reg(USSE_OUTPUT, 4 * k + i), *o, &s); + } + scratch_give_back(c, &s); + } + nscaled += !!(fix & SGX_FIX_SCALE); + } + emit(c, USSE_EMIT_VERTEX_END); +} + +/* (M47) sqrt(a) == 0 as a == 0 (the same for every a, NaN and -0 too): + * GLSL's length(v) == 0.0, PPSSPP's normalizeOr001 */ +static bool +lower_sqrt_tests(nir_builder *b, nir_alu_instr *alu, void *data) +{ + if ((alu->op == nir_op_feq || alu->op == nir_op_fneu) && alu->def.num_components == 1) { + for (unsigned i = 0; i < 2; i++) { + nir_scalar z = nir_get_scalar(alu->src[1 - i].src.ssa, alu->src[1 - i].swizzle[0]); + nir_scalar q = nir_scalar_chase_movs(nir_get_scalar(alu->src[i].src.ssa, + alu->src[i].swizzle[0])); + + if (nir_scalar_is_const(z) && nir_scalar_as_float(z) == 0.0 && nir_scalar_is_alu(q) && + nir_scalar_alu_op(q) == nir_op_fsqrt && q.def->num_components == 1) { + nir_scalar a = nir_scalar_chase_alu_src(q, 0); + + b->cursor = nir_before_instr(&alu->instr); + nir_src_rewrite(&alu->src[i].src, nir_mov_scalar(b, a)); + alu->src[i].swizzle[0] = 0; + return true; + } + } + } + return false; +} + +/* (M47) the square roots left as 1 / rsq(a), the code alu() makes of them, + * where the rsq of a normalize() of the same vector is the one CSE keeps + * -- after the last algebraic pass (which makes rcp(rsq(a)) sqrt(a) again) */ +static bool +lower_fsqrt(nir_builder *b, nir_alu_instr *alu, void *data) +{ + if (alu->op != nir_op_fsqrt || alu->def.bit_size != 32) + return false; + b->cursor = nir_before_instr(&alu->instr); + nir_def_replace(&alu->def, nir_frcp(b, nir_frsq(b, nir_ssa_for_alu_src(b, alu, 0)))); + return true; +} + +/* (Mesa 27) the vertex shaders' fused products and sums are fmad: what the + * code below calls ffma, FMAD (fma_), vec2 ones kept by scalar_filter -- + * after each late algebraic pass (nir_opt_algebraic would split an fmad) */ +static bool +fmad_to_ffma(nir_builder *b, nir_alu_instr *alu, void *data) +{ + if (alu->op != nir_op_fmad) + return false; + alu->op = nir_op_ffma; + return true; +} + +/* A uniform's constant offset into its base (until M44 nir_lower_int_to_float + * made the integer constants floats, an offset of 1 among them -- 0x3f800000: + * a matrix's second column read as word 4261412864) */ +static bool +fold_uniform_offset(nir_builder *b, nir_intrinsic_instr *in, void *data) +{ + if (in->intrinsic != nir_intrinsic_load_uniform || !nir_src_is_const(in->src[0]) || + !nir_src_as_uint(in->src[0])) + return false; + b->cursor = nir_before_instr(&in->instr); + nir_intrinsic_set_base(in, nir_intrinsic_base(in) + nir_src_as_uint(in->src[0])); + nir_src_rewrite(&in->src[0], nir_imm_int(b, 0)); + return true; +} + +/* ftrunc (GLSL's trunc(); int(x) until M44, made by nir_lower_int_to_float) + * as its sign times floor(|x|), floor y as y - fract y -- |x| a little + * larger first, by 2^-13 of itself (1/16 at most): a whole number that + * comes a bit short is that number still. A varying that is 24 at every + * vertex comes 23.9995 into a viewport of 128 x 112 (dEQP's div cases, + * glvary; M31). f2i32 does the same (float_to_int()) */ +static bool +lower_ftrunc(nir_builder *b, nir_alu_instr *alu, void *data) +{ + nir_def *x, *a, *f; + + if (alu->op != nir_op_ftrunc) + return false; + b->cursor = nir_before_instr(&alu->instr); + x = nir_ssa_for_alu_src(b, alu, 0); + a = nir_fabs(b, x); + a = nir_fadd(b, a, nir_fmin(b, nir_fmul_imm(b, a, 1.0 / (1 << 13)), nir_imm_float(b, 0.0625f))); + f = nir_fadd(b, a, nir_fneg(b, nir_ffract(b, a))); + nir_def_replace(&alu->def, nir_bcsel(b, nir_flt_imm(b, x, 0.0), nir_fneg(b, f), f)); + return true; +} + +/* gl_FrontFacing as 0 < its sign, which intrinsic() makes */ +static bool +lower_front_face(nir_builder *b, nir_intrinsic_instr *in, void *data) +{ + if (in->intrinsic != nir_intrinsic_load_front_face) + return false; + b->cursor = nir_before_instr(&in->instr); + nir_def_replace(&in->def, nir_flt(b, nir_imm_float(b, 0.0f), nir_load_front_face_fsign(b))); + return true; +} + +/* A branch (iOS's c04_loop_break: `p0? br +21`, `br -21`): relative, in + * instructions from itself, under an extended predicate (0 always, 1 p0, + * 5 !p0) */ +#define USSE_BR 0xf800004000000000ull + +static void +branch_to(struct comp *c, unsigned at, unsigned target) +{ + uint64_t *w = util_dynarray_element(&c->code, uint64_t, at); + + *w = (*w & ~0xfffffull) | ((uint32_t)(target - at) & 0xfffff); +} + +static unsigned +branch(struct comp *c, unsigned pred) +{ + unsigned at = util_dynarray_num_elements(&c->code, uint64_t); + + /* (pixels run together: taken when all of them take it -- bit 20, + * Vita3K's all_inst; any_inst, bit 21, did the same with branches + * that go alike, M33) */ + emit(c, USSE_BR | (uint64_t)pred << 56 | (!c->vs && !c->divergent ? 1ull << 20 : 0)); + c->branches = true; + return at; +} + +static unsigned +here(struct comp *c) +{ + return util_dynarray_num_elements(&c->code, uint64_t); +} + +static void +instruction(struct comp *c, nir_instr *instr, struct util_dynarray *breaks, unsigned head) +{ + struct scratch sc = { 0 }; + + switch (instr->type) { + case nir_instr_type_alu: + alu(c, nir_instr_as_alu(instr), &sc); + break; + case nir_instr_type_intrinsic: + intrinsic(c, nir_instr_as_intrinsic(instr)); + break; + case nir_instr_type_tex: + texture(c, nir_instr_as_tex(instr), &sc); + break; + case nir_instr_type_load_const: + case nir_instr_type_undef: + break; + case nir_instr_type_jump: + switch (nir_instr_as_jump(instr)->type) { + case nir_jump_break: + if (breaks) { + unsigned at = branch(c, 0); + + util_dynarray_append(breaks, at); + break; + } + FALLTHROUGH; + case nir_jump_continue: + if (breaks) { + branch_to(c, branch(c, 0), head); + break; + } + FALLTHROUGH; + default: + fail(c, "a jump out of no loop"); + break; + } + break; + default: + fail(c, "no such instructions yet"); + break; + } + scratch_give_back(c, &sc); +} + +/* What one walk over the shader's control flow does: number the + * instructions (each def's, each loop's span), note what each reads (the + * liveness), or make the code. The three number alike: an instruction, an + * if's test and a loop's end marker an index each. */ +enum walk_pass { WALK_NUMBER, WALK_USES, WALK_CODE }; + +static void +walk(struct comp *c, struct exec_list *list, enum walk_pass pass, int *index, + struct util_dynarray *breaks, unsigned head) +{ + foreach_list_typed(nir_cf_node, node, node, list) { + if (c->failed) + return; + switch (node->type) { + case nir_cf_node_block: + nir_foreach_instr(instr, nir_cf_node_as_block(node)) { + nir_def *def = nir_instr_def(instr); + + if (pass == WALK_NUMBER && def) + c->def_at[def->index] = *index; + else if (pass == WALK_USES) + for_each_read(c, instr, note_use, *index); + else if (pass == WALK_CODE) { + instruction(c, instr, breaks, head); + for_each_read(c, instr, release, *index); + } + (*index)++; + if (c->failed) + return; + } + break; + case nir_cf_node_if: { + /* the test -- p0 = cond's bits are 0 (a boolean is 0.0 or 1.0 + * here), then `p0? br`, as iOS's branches have it -- past the + * then-list where it fails; the else-list past the then-list's + * end */ + nir_if *nif = nir_cf_node_as_if(node); + struct operand cond = resolve(nir_get_scalar(nif->condition.ssa, 0)); + int at = (*index)++; + unsigned to_else = 0, to_end = 0; + + if (pass == WALK_USES) + note_use(c, cond, at); + if (pass == WALK_CODE) { + struct scratch sc = { 0 }; + + emit(c, usse_vtst_bits(0, get(c, cond, TAKES_LANE_Y | TAKES_SA, &sc), true)); + scratch_give_back(c, &sc); + release(c, cond, at); + to_else = branch(c, 1); + } + c->depth++; + walk(c, &nif->then_list, pass, index, breaks, head); + if (pass == WALK_CODE && !exec_list_is_empty(&nif->else_list) && + !nir_cf_list_is_empty_block(&nif->else_list)) + to_end = branch(c, 0); + if (pass == WALK_CODE) + branch_to(c, to_else, here(c)); + walk(c, &nif->else_list, pass, index, breaks, head); + if (pass == WALK_CODE && to_end) + branch_to(c, to_end, here(c)); + c->depth--; + break; + } + case nir_cf_node_loop: { + /* the body, a branch back to its start; a break past it */ + nir_loop *loop = nir_cf_node_as_loop(node); + unsigned k = c->nloops++, start_code = here(c); + struct util_dynarray mine; + int start = *index, end; + + if (nir_loop_has_continue_construct(loop)) { + fail(c, "a loop with a continue construct"); + return; + } + /* (a loop's span is k-th in the order the loops start, the same + * in every pass: an inner loop's after its outer one's -- taken + * at the end, the outer loop had the inner one's span, and what + * it reads lived to the inner loop's end, M31) */ + if (pass == WALK_NUMBER) { + struct loop_span span = { start, -1 }; + + util_dynarray_append(&c->loops, span); + } + if (pass == WALK_USES) { + if (c->nactive == ARRAY_SIZE(c->active)) { + fail(c, "loops nested too deep"); + return; + } + c->active[c->nactive++] = *util_dynarray_element(&c->loops, struct loop_span, k); + } + util_dynarray_init(&mine, NULL); + c->depth++; + walk(c, &loop->body, pass, index, &mine, start_code); + c->depth--; + end = (*index)++; + if (pass == WALK_NUMBER) + util_dynarray_element(&c->loops, struct loop_span, k)->end = end; + if (pass == WALK_USES) + c->nactive--; + if (pass == WALK_CODE) { + branch_to(c, branch(c, 0), start_code); + util_dynarray_foreach(&mine, unsigned, at) + branch_to(c, *at, here(c)); + /* what was kept alive for the loop */ + for (unsigned id = 0; id < c->nvalues; id++) + if (c->last_use[id] == end && c->owned[id]) { + give_back(c, c->loc[id].num - (c->vs ? c->pa_base : 0)); + c->owned[id] = false; + } + } + util_dynarray_fini(&mine); + break; + } + default: + fail(c, "no such control flow"); + return; + } + } +} + +/* NIR to instructions, after the opening PHAS, for either stage: the + * shader lowered to scalar float arithmetic, its ifs flattened where they + * can be, what is left of them and the loops as branches (M20), its values + * given temporaries in the order NIR has them. False (c->failed, c->why) + * when it cannot be. */ +/* A vertex program's start (M26): each attribute the fetch put in pa4n.. + * as it is in memory made four floats -- bytes unpacked (the top two + * first, the word they come from last), the components the format does + * not have 0, 0, 1 */ +static void +vs_prologue(struct comp *c) +{ + for (unsigned a = 0; a < c->nattrs; a++) { + unsigned kind = SGX_ATTR_KIND(c->attr[a]), n = SGX_ATTR_COMPS(c->attr[a]); + struct usse_reg r = usse_reg(USSE_PA, 4 * a); + + if (kind == SGX_ATTR_CONST) + continue; + if (kind == SGX_ATTR_U8N) { + if (n > 2) + emit(c, usse_unpack_unorm8(usse_reg(USSE_PA, 4 * a + 2), r, 2)); + emit(c, usse_unpack_unorm8(r, r, 0)); + } + for (unsigned i = n; i < 4; i++) + emit(c, usse_limm(usse_reg(USSE_PA, 4 * a + i), f32_bits(i == 3 ? 1.0f : 0.0f))); + } +} + +struct latest { + nir_block *block; + nir_instr *instr; +}; + +static bool +note_latest(nir_src *src, void *data) +{ + struct latest *l = data; + nir_instr *d = nir_def_instr(src->ssa); + + if (d->block == l->block && (!l->instr || d->index > l->instr->index)) + l->instr = d; + return true; +} + +/* instr up to just after the last of what it reads in its block (or of + * after, when that is later) -- the block's start when it reads nothing of + * the block's */ +static void +hoist(nir_function_impl *impl, nir_instr *instr, nir_instr *after) +{ + struct latest l = { instr->block, after }; + nir_block *b = instr->block; + + nir_foreach_src(instr, note_latest, &l); + nir_instr_remove(instr); + if (l.instr) + nir_instr_insert_after(l.instr, instr); + else + nir_instr_insert(nir_before_block_after_phis(b), instr); + nir_index_instrs(impl); +} + +/* A vertex shader's outputs stored as soon as their values are there: the + * GLSL compiler stores them all at the end, and every value for them was + * alive until then -- eight vec4 varyings took more temporaries than there + * are (glvary, M30). A store stays after the ones before it to the same + * output. */ +static void +store_outputs_early(nir_shader *s) +{ + nir_function_impl *impl = nir_shader_get_entrypoint(s); + + nir_foreach_block(b, impl) + nir_foreach_instr(instr, b) + if (instr->type == nir_instr_type_intrinsic && + nir_instr_as_intrinsic(instr)->intrinsic == nir_intrinsic_load_output) + return; /* (an output read back: left as it is) */ + nir_index_instrs(impl); + nir_foreach_block(b, impl) { + nir_foreach_instr_safe(instr, b) { + nir_intrinsic_instr *in; + nir_instr *vec, *after = NULL; + + if (instr->type != nir_instr_type_intrinsic) + continue; + in = nir_instr_as_intrinsic(instr); + if (in->intrinsic != nir_intrinsic_store_output) + continue; + for (nir_instr *p = nir_instr_prev(instr); p && !after; p = nir_instr_prev(p)) + if (p->type == nir_instr_type_intrinsic && + nir_instr_as_intrinsic(p)->intrinsic == nir_intrinsic_store_output && + nir_intrinsic_base(nir_instr_as_intrinsic(p)) == nir_intrinsic_base(in)) + after = p; + /* (the vec4 the value is made into first, when it is the store's + * alone) */ + vec = nir_def_instr(in->src[0].ssa); + if (vec->block == b && vec->type == nir_instr_type_alu && + nir_op_is_vec(nir_instr_as_alu(vec)->op) && list_is_singular(&in->src[0].ssa->uses)) + hoist(impl, vec, NULL); + hoist(impl, instr, after); + } + } +} + +/* ---- a colour of four F16 at once (M38, M46) ------------------------------ + * + * iOS's SDL sprite (corpus s00, s03, s11): the colour iterated and the + * texel fetched as F16 by the PDS, two registers each (four F16 a 64-bit + * register), then `mul.f16 pa0.xyzw, pa2.xyzw, pa0.xyzw`, `pck.u8.f16`, + * the SOP2 that blends -- four instructions where the general way takes + * nine (texels unpacked to F32, a channel an instruction). A pixel's cost + * is its instructions (M34). + * + * (M46) Any tree of fmul, fadd, fsub, fmin, fmax, ffma, fsat and fneg over + * the varyings (any of their channels), the PDS's texels, constants and + * uniforms, a tree for each channel: the four channels worked out + * together -- one instruction for the channels that do the same operation + * (a write mask for the others), a channel that only passes a value on + * padded to the others' operation (times 1, plus 0). The constants 0, 1, + * 2 and 0.5 are src1's swizzle's own (Vita3K's SwizzleChannel); others go + * into the program's sa pool as F16 pairs; a uniform's vec4 is packed to + * F16 once. PPSSPP's texture times colour, doubled (God of War's + * commonest program), 11 instructions in F32 -> 4. + * + * Taken when nothing else is in the program: no discard, branch, TA + * colour, gl_FragCoord, lookup but the PDS's, blending in the program or + * logic op. The colour goes to 8 bits: F16's 11 bits of mantissa are + * what mediump's are, and enough for highp's colour too. */ +#define F16_SEL_0 4 /* src1's swizzle's constants */ +#define F16_SEL_1 5 +#define F16_SEL_2 6 +#define F16_SEL_H 7 +#define F16_NO_SEL 0xff +#define F16_MAX_MADE 96 +#define F16_MAX_CODE 48 + +/* four F16: lane i is lane sw[i] (0..3) of the pair reg, or src1's + * constant sw[i] (F16_SEL_*) */ +struct f16o { + struct usse_reg reg; + uint8_t sw[4]; + bool neg; +}; + +struct f16g { + struct comp *c; + unsigned ntemp; /* temporary pairs: treg(c, 2 k) */ + struct { + nir_def *def; + uint8_t comp, pair, lane; + } made[F16_MAX_MADE]; /* the values worked out, where */ + unsigned nmade; + struct { + unsigned word; /* a uniform vec4's first sa word */ + struct usse_reg reg; /* its four F16 */ + } packed[8]; + unsigned npacked; + /* (M46) the F32 values of lookups' coordinates worked out, where; the + * odd half of a pair taken for them, or -1 */ + struct { + nir_def *def; + uint8_t comp; + struct usse_reg reg; + } f32made[16]; + unsigned nf32made; + int f32_spare; + bool failed; + /* (M50) a lookup's coordinates or a kill's comparison being worked out: + * what F32 cannot make (a texel, a varying iterated as F16, the colour's + * arithmetic of them) the colour's tree makes in F16, then unpacked -- + * of a texel, and of no varying but the colour's own (colour_inputs: a + * texture coordinate keeps F32's precision, or the program is not F16) */ + bool chain; + unsigned colour_inputs; +}; + +/* src2's swizzles, Vita3K's table (usse-dis.py's VEC4_STD) but its last, + * xyz1 */ +static const uint8_t f16_sw2[15][4] = { + { 0, 0, 0, 0 }, { 1, 1, 1, 1 }, { 2, 2, 2, 2 }, { 3, 3, 3, 3 }, + { 0, 1, 2, 3 }, { 1, 2, 3, 3 }, { 0, 1, 2, 2 }, { 0, 0, 1, 2 }, + { 0, 1, 0, 1 }, { 0, 1, 3, 2 }, { 2, 0, 1, 3 }, { 2, 3, 2, 3 }, + { 1, 2, 0, 2 }, { 0, 0, 1, 1 }, { 0, 2, 3, 3 }, +}; +static const uint8_t f16_xyzw[4] = { 0, 1, 2, 3 }; + +static unsigned fs_sa_end(const struct comp *c); + +static unsigned +f16_temp(struct f16g *g) +{ + if (2 * (g->ntemp + 1) > MAX_TEMPS) + g->failed = true; + return g->ntemp++; +} + +static struct usse_reg +f16_reg(struct f16g *g, unsigned pair) +{ + return treg(g->c, 2 * pair); +} + +static uint8_t +f16_const_sel(uint32_t bits) +{ + switch (bits) { + case 0x00000000: return F16_SEL_0; + case 0x3f800000: return F16_SEL_1; + case 0x40000000: return F16_SEL_2; + case 0x3f000000: return F16_SEL_H; + default: return F16_NO_SEL; + } +} + +/* an F16 pair in the program's sa pool (plan_constants()'s): its word */ +static int +f16_pool(struct comp *c, const uint16_t h[4]) +{ + uint32_t lo = h[0] | (uint32_t)h[1] << 16, hi = h[2] | (uint32_t)h[3] << 16; + unsigned k; + + for (k = 0; k < c->nkconst; k++) + if (!(c->kconst_derived >> k & 1) && c->kconst[2 * k] == lo && c->kconst[2 * k + 1] == hi) + return c->kconst_sa + 2 * k; + if (k == SGX_FS_MAX_KCONST || c->kconst_sa + 2 * (k + 1) > 128) + return -1; + c->kconst[2 * k] = lo; + c->kconst[2 * k + 1] = hi; + c->nkconst++; + return c->kconst_sa + 2 * k; +} + +/* (M46) a pair of the constant pool that the draw works out from the sa + * words before it (sgx_fs_derived): its first word, or -1 when the pool is + * full. SGX_NO_DERIVED=1: none, the program works them out. */ +static int +f16_derived(struct comp *c, unsigned kind, unsigned a, bool neg_a, unsigned b, bool neg_b) +{ + unsigned k = c->nkconst; + + if (getenv("SGX_NO_DERIVED")) + return -1; + for (unsigned i = 0; i < c->nderived; i++) { + const struct sgx_fs_derived *d = &c->derived[i]; + + if (d->kind == kind && d->a == a && d->b == b && d->neg_a == neg_a && d->neg_b == neg_b) + return c->kconst_sa + 2 * d->pair; + } + if (k == SGX_FS_MAX_KCONST || c->kconst_sa + 2 * (k + 1) > 128 || + c->nderived == SGX_FS_MAX_DERIVED) + return -1; + c->kconst[2 * k] = c->kconst[2 * k + 1] = 0; + c->kconst_derived |= 1u << k; + c->nkconst++; + c->derived[c->nderived++] = (struct sgx_fs_derived){ kind, k, a, b, neg_a, neg_b }; + return c->kconst_sa + 2 * k; +} + +/* whether sa word w is a uniform's, or the first of a pair the draw works + * out -- what a derived pair may be made of */ +static bool +f16_derivable(const struct comp *c, struct usse_reg r) +{ + if (r.bank != USSE_SA || r.abs) + return false; + if (r.num < c->sa_uniforms) + return true; + for (unsigned i = 0; i < c->nderived; i++) + if (r.num == c->kconst_sa + 2 * c->derived[i].pair && + c->derived[i].kind != SGX_DERIVED_F16) + return true; + return false; +} + +/* a uniform's vec4 (from sa word w0) as F16: a pair of the pool the draw + * packs (M46) -- else packed by the program, for every pixel, once */ +static bool +f16_uniform(struct f16g *g, unsigned w0, struct usse_reg *r) +{ + unsigned p; + int w; + + for (unsigned k = 0; k < g->npacked; k++) + if (g->packed[k].word == w0) { + *r = g->packed[k].reg; + return true; + } + if (g->npacked == ARRAY_SIZE(g->packed)) + return false; + if ((w = f16_derived(g->c, SGX_DERIVED_F16, w0, false, 0, false)) >= 0) { + *r = usse_reg(USSE_SA, w); + } else { + p = f16_temp(g); + emit(g->c, usse_pack_f16(f16_reg(g, p), usse_reg(USSE_SA, w0), 0xf)); + *r = f16_reg(g, p); + } + g->packed[g->npacked].word = w0; + g->packed[g->npacked++].reg = *r; + return true; +} + +enum f16_kind { F16K_NONE, F16K_REG, F16K_CONST, F16K_UNIFORM, F16K_ALU }; + +struct f16leaf { + enum f16_kind kind; + nir_scalar s; + struct usse_reg reg; /* REG: the pair, lane its lane */ + uint8_t lane; + uint32_t bits; /* CONST */ + unsigned word; /* UNIFORM: its sa word */ + nir_op op; /* ALU */ +}; + +static struct f16leaf +f16_leaf(struct f16g *g, nir_scalar s) +{ + struct comp *c = g->c; + struct f16leaf l = { .kind = F16K_NONE }; + + s = nir_scalar_chase_movs(s); + l.s = s; + for (unsigned k = 0; k < g->nmade; k++) + if (g->made[k].def == s.def && g->made[k].comp == s.comp) { + l.kind = F16K_REG; + l.reg = f16_reg(g, g->made[k].pair); + l.lane = g->made[k].lane; + return l; + } + if (nir_scalar_is_const(s)) { + l.kind = F16K_CONST; + l.bits = (uint32_t)nir_scalar_as_uint(s); + return l; + } + if (nir_scalar_is_alu(s)) { + l.kind = F16K_ALU; + l.op = nir_scalar_alu_op(s); + return l; + } + if (nir_def_instr(s.def)->type == nir_instr_type_tex) { + for (unsigned k = 0; k < c->nfetch; k++) + if (&c->fetch[k]->instr == nir_def_instr(s.def) && s.comp < 4) { + l.kind = F16K_REG; + l.reg = usse_reg(USSE_PA, c->fetch_pa + 2 * k); + l.lane = s.comp; + } + return l; + } + if (nir_scalar_is_intrinsic(s)) { + nir_intrinsic_instr *in = nir_def_as_intrinsic(s.def); + + if (in->intrinsic == nir_intrinsic_load_input) { + int slot = input_slot(in); + unsigned comp = nir_intrinsic_component(in) + s.comp; + + /* (not a varying iterated F32 for a lookup's coordinates, M46) */ + if (slot >= 0 && c->input_of_slot[slot] >= 0 && comp < 4 && + !(c->in_f32 >> c->input_of_slot[slot] & 1)) { + l.kind = F16K_REG; + l.reg = usse_reg(USSE_PA, c->in_pa[c->input_of_slot[slot]]); + l.lane = comp; + } + } else if (in->intrinsic == nir_intrinsic_load_uniform && nir_src_is_const(in->src[0])) { + unsigned at = (nir_intrinsic_base(in) + nir_src_as_uint(in->src[0])) * 4 + s.comp; + + if (at < c->sa_uniforms) { + l.kind = F16K_UNIFORM; + l.word = at; + } + } + } + return l; +} + +/* the table's swizzle for o as src2 on the lanes in mask, or -1 */ +static int +f16_sw2_of(const struct f16o *o, unsigned mask) +{ + if (o->neg) + return -1; + for (unsigned k = 0; k < ARRAY_SIZE(f16_sw2); k++) { + bool ok = true; + + for (unsigned i = 0; i < 4 && ok; i++) + ok = !(mask & 1u << i) || o->sw[i] == f16_sw2[k][i]; + if (ok) + return k; + } + return -1; +} + +static bool f16_operand_x(struct f16g *g, const nir_scalar *s, const uint8_t *csel, + unsigned mask, struct f16o *o, bool into); + +static bool +f16_operand(struct f16g *g, const nir_scalar *s, const uint8_t *csel, unsigned mask, + struct f16o *o) +{ + return f16_operand_x(g, s, csel, mask, o, true); +} + +/* pair's lanes in mask = o's lanes: o times 1 */ +static bool +f16_move(struct f16g *g, const struct f16o *o, unsigned mask, unsigned pair) +{ + static const uint16_t ones[4] = { 0x3c00, 0x3c00, 0x3c00, 0x3c00 }; + struct usse_reg src1 = o->reg; + int k = f16_sw2_of(o, mask), w; + + if (k >= 0) { + /* 1 (src1's constants) times o */ + const uint8_t one[4] = { F16_SEL_1, F16_SEL_1, F16_SEL_1, F16_SEL_1 }; + + emit(g->c, usse_hop_ex(USSE_NMAD_MUL, f16_reg(g, pair), mask, usse_reg(USSE_PA, 0), + one[0] | one[1] << 3 | one[2] << 6 | one[3] << 9, o->reg, k)); + return true; + } + /* o (src1, as it is) times a pair of ones from the pool */ + if ((w = f16_pool(g->c, ones)) < 0) + return false; + src1.neg = o->neg; + emit(g->c, usse_hop_ex(USSE_NMAD_MUL, f16_reg(g, pair), mask, src1, + o->sw[0] | o->sw[1] << 3 | o->sw[2] << 6 | o->sw[3] << 9, + usse_reg(USSE_SA, w), 4)); + return true; +} + +/* pair's lanes in mask = a op b: b as src2 if the table has its swizzle, + * else a (the operations are commutative), else b moved first */ +static bool +f16_emit(struct f16g *g, enum usse_nmad_op op, unsigned pair, unsigned mask, struct f16o a, + struct f16o b) +{ + int k = f16_sw2_of(&b, mask); + + if (k < 0 && (k = f16_sw2_of(&a, mask)) >= 0) { + struct f16o t = a; + + a = b; + b = t; + } + if (k < 0) { + unsigned p = f16_temp(g); + + if (!f16_move(g, &b, mask, p)) + return false; + b.reg = f16_reg(g, p); + memcpy(b.sw, f16_xyzw, 4); + b.neg = false; + k = 4; + } + a.reg.neg = a.neg; + emit(g->c, usse_hop_ex(op, f16_reg(g, pair), mask, a.reg, + a.sw[0] | a.sw[1] << 3 | a.sw[2] << 6 | a.sw[3] << 9, b.reg, k)); + return !g->failed; +} + +static enum usse_nmad_op +f16_nmad(nir_op op) +{ + switch (op) { + case nir_op_fmul: return USSE_NMAD_MUL; + case nir_op_fmin: return USSE_NMAD_MIN; + case nir_op_fmax: return USSE_NMAD_MAX; + default: return USSE_NMAD_ADD; /* fadd, fsub (b negated) */ + } +} + +static bool +f16_alu_ok(nir_op op) +{ + return op == nir_op_fmul || op == nir_op_fadd || op == nir_op_fsub || op == nir_op_fmin || + op == nir_op_fmax || op == nir_op_ffma || op == nir_op_fsat || op == nir_op_fneg; +} + +/* what works a lane out, for grouping lanes: an operation, or -1 for a + * value as it is (a leaf, or a constant forced) */ +static int +f16_key(const struct f16leaf *l, const uint8_t *csel, unsigned i) +{ + if ((csel && csel[i] != F16_NO_SEL) || l[i].kind != F16K_ALU || l[i].op == nir_op_fneg) + return -1; + return l[i].op; +} + +static void +f16_remember(struct f16g *g, nir_scalar s, unsigned pair, unsigned lane) +{ + if (g->nmade < F16_MAX_MADE) { + g->made[g->nmade].def = s.def; + g->made[g->nmade].comp = s.comp; + g->made[g->nmade].pair = pair; + g->made[g->nmade++].lane = lane; + } +} + +/* pair's lanes in mask = s's (csel: lanes that are a constant of src1's + * swizzle instead) */ +static bool +f16_into(struct f16g *g, const nir_scalar *s, const uint8_t *csel, unsigned mask, unsigned pair) +{ + struct f16leaf l[4]; + unsigned todo = mask; + + for (unsigned i = 0; i < 4; i++) + if ((mask & 1u << i) && !(csel && csel[i] != F16_NO_SEL)) { + l[i] = f16_leaf(g, s[i]); + if (l[i].kind == F16K_NONE || (l[i].kind == F16K_ALU && !f16_alu_ok(l[i].op))) + return false; + } + + /* (padding) lanes whose value is what the other lanes' fmul or fadd + * takes as an operand: times 1, plus 0, the same instruction */ + for (unsigned i = 0; i < 4 && todo; i++) { + int key = (todo & 1u << i) ? f16_key(l, csel, i) : -2; + unsigned xs = 0, rs = 0; + + if (key != nir_op_fmul && key != nir_op_fadd) + continue; + for (unsigned j = 0; j < 4; j++) { + if (!(todo & 1u << j)) + continue; + if (f16_key(l, csel, j) == key) + xs |= 1u << j; + else + rs |= 1u << j; + } + for (unsigned p = 0; p < 2 && rs; p++) { + nir_scalar a[4], b[4], *mine = p ? b : a; + uint8_t ca[4], cb[4], *other = p ? ca : cb; + struct f16leaf op0 = { .kind = F16K_NONE }; + bool fits = true; + struct f16o oa, ob; + + /* the X lanes' operand p: alike (the same operation, or the same + * pair), and each other lane the same kind of thing */ + u_foreach_bit(j, xs) { + struct f16leaf t = f16_leaf(g, nir_scalar_chase_alu_src(l[j].s, p)); + + if (op0.kind == F16K_NONE) + op0 = t; + fits &= t.kind == op0.kind && (t.kind != F16K_ALU || t.op == op0.op) && + (t.kind != F16K_REG || (t.reg.bank == op0.reg.bank && t.reg.num == op0.reg.num)); + } + u_foreach_bit(j, rs) + fits &= csel && csel[j] != F16_NO_SEL ? false : + l[j].kind == op0.kind && (l[j].kind != F16K_ALU || l[j].op == op0.op) && + (l[j].kind != F16K_REG || (l[j].reg.bank == op0.reg.bank && + l[j].reg.num == op0.reg.num)); + if (!fits || op0.kind == F16K_NONE || op0.kind == F16K_CONST) + continue; + memset(ca, F16_NO_SEL, 4); + memset(cb, F16_NO_SEL, 4); + u_foreach_bit(j, xs) { + a[j] = nir_scalar_chase_alu_src(l[j].s, 0); + b[j] = nir_scalar_chase_alu_src(l[j].s, 1); + } + u_foreach_bit(j, rs) { + mine[j] = l[j].s; + other[j] = key == nir_op_fmul ? F16_SEL_1 : F16_SEL_0; + } + if (!f16_operand(g, a, ca, xs | rs, &oa) || !f16_operand(g, b, cb, xs | rs, &ob) || + !f16_emit(g, f16_nmad(key), pair, xs | rs, oa, ob)) + return false; + u_foreach_bit(j, xs | rs) + f16_remember(g, l[j].s, pair, j); + todo &= ~(xs | rs); + break; + } + } + + while (todo) { + unsigned i = ffs(todo) - 1, group = 0; + int key = f16_key(l, csel, i); + + for (unsigned j = 0; j < 4; j++) + if ((todo & 1u << j) && f16_key(l, csel, j) == key) + group |= 1u << j; + todo &= ~group; + + if (key == nir_op_fmul || key == nir_op_fadd || key == nir_op_fsub || + key == nir_op_fmin || key == nir_op_fmax || key == nir_op_ffma) { + nir_scalar a[4], b[4], d[4]; + struct f16o oa, ob, od; + unsigned t = pair; + + uint8_t cb[4]; + bool promoted = false; + + u_foreach_bit(j, group) { + a[j] = nir_scalar_chase_alu_src(l[j].s, 0); + b[j] = nir_scalar_chase_alu_src(l[j].s, 1); + if (key == nir_op_ffma) + d[j] = nir_scalar_chase_alu_src(l[j].s, 2); + } + /* (M46) lanes whose own value is what the others' operand pi is + * (the same operation): times 1 (plus 0) here, their value that + * operand's lane -- God of War's (p * t).rgb * fix with (p * t).a: + * p * t once for the four lanes, then times fix.xyz1 (src1's + * constant), where each operand taken lane by lane needed two + * moves. SGX_F16_NO_PROMOTE=1: as before */ + if ((key == nir_op_fmul || key == nir_op_fadd) && !getenv("SGX_F16_NO_PROMOTE")) { + for (unsigned pi = 0; pi < 2 && !promoted; pi++) { + nir_scalar pa_[4], pb_[4]; + unsigned xs = 0, ys = 0; + struct f16o probe; + + u_foreach_bit(j, group) { + struct f16leaf in = f16_leaf(g, nir_scalar_chase_alu_src(l[j].s, pi)); + + if (in.kind == F16K_ALU && in.op == key) + xs |= 1u << j; + else + ys |= 1u << j; + } + if (!xs || !ys) + continue; + memset(cb, F16_NO_SEL, 4); + u_foreach_bit(j, xs) { + pa_[j] = nir_scalar_chase_alu_src(l[j].s, pi); + pb_[j] = nir_scalar_chase_alu_src(l[j].s, 1 - pi); + } + u_foreach_bit(j, ys) { + pa_[j] = pb_[j] = l[j].s; + cb[j] = key == nir_op_fmul ? F16_SEL_1 : F16_SEL_0; + } + /* (only when the other operand is one as it is) */ + if (!f16_operand_x(g, pb_, cb, group, &probe, false)) + continue; + memcpy(a, pa_, sizeof(a)); + memcpy(b, pb_, sizeof(b)); + promoted = true; + } + } + if (key == nir_op_ffma) + t = f16_temp(g); + if (!f16_operand(g, a, NULL, group, &oa) || + !f16_operand(g, b, promoted ? cb : NULL, group, &ob)) + return false; + if (key == nir_op_fsub) + ob.neg = !ob.neg; + if (!f16_emit(g, f16_nmad(key == nir_op_ffma ? nir_op_fmul : key), t, group, oa, ob)) + return false; + if (key == nir_op_ffma) { + struct f16o ot = { .reg = f16_reg(g, t) }; + + memcpy(ot.sw, f16_xyzw, 4); + if (!f16_operand(g, d, NULL, group, &od) || + !f16_emit(g, USSE_NMAD_ADD, pair, group, ot, od)) + return false; + } + } else if (key == nir_op_fsat) { + nir_scalar a[4]; + struct f16o oa, zero = { .reg = usse_reg(USSE_PA, 0) }, one = zero, self; + + u_foreach_bit(j, group) + a[j] = nir_scalar_chase_alu_src(l[j].s, 0); + memset(zero.sw, F16_SEL_0, 4); + memset(one.sw, F16_SEL_1, 4); + self.reg = f16_reg(g, pair); + memcpy(self.sw, f16_xyzw, 4); + self.neg = false; + if (!f16_operand(g, a, NULL, group, &oa) || + !f16_emit(g, USSE_NMAD_MAX, pair, group, zero, oa) || + !f16_emit(g, USSE_NMAD_MIN, pair, group, one, self)) + return false; + } else { + /* values as they are (leaves, negated ones, constants): moved, the + * lanes one operand can hold together (else f16_operand would + * come back here with the same lanes) */ + while (group) { + unsigned sub = 1u << (ffs(group) - 1); + struct f16o o; + + u_foreach_bit(j, group & ~sub) + if (f16_operand_x(g, s, csel, sub | 1u << j, &o, false)) + sub |= 1u << j; + if (!f16_operand_x(g, s, csel, sub, &o, util_bitcount(sub) == 1) || + !f16_move(g, &o, sub, pair)) + return false; + group &= ~sub; + } + continue; + } + u_foreach_bit(j, group) + f16_remember(g, l[j].s, pair, j); + } + return !g->failed; +} + +/* the lanes in mask of s as one operand: a pair as it is, through a + * swizzle (and src1's constants), negated -- or worked out into a pair of + * its own */ +static bool +f16_operand_x(struct f16g *g, const nir_scalar *s, const uint8_t *csel, unsigned mask, + struct f16o *o, bool into) +{ + struct f16leaf l[4]; + struct usse_reg reg = usse_reg(USSE_PA, 0); + uint16_t h[4] = { 0 }; + bool have = false, single = true, pool = false, neg = true, any = false; + unsigned p; + + memset(o, 0, sizeof(*o)); + for (unsigned i = 0; i < 4; i++) { + if (!(mask & 1u << i)) + continue; + if (csel && csel[i] != F16_NO_SEL) { + o->sw[i] = csel[i]; + neg = false; + continue; + } + l[i] = f16_leaf(g, s[i]); + if (l[i].kind == F16K_NONE) + return false; + any = true; + neg &= l[i].kind == F16K_ALU && l[i].op == nir_op_fneg; + } + /* every lane negated: what they negate, negated */ + if (any && neg) { + nir_scalar t[4]; + + for (unsigned i = 0; i < 4; i++) + if (mask & 1u << i) + t[i] = nir_scalar_chase_alu_src(l[i].s, 0); + if (!f16_operand_x(g, t, NULL, mask, o, into)) + return false; + o->neg = !o->neg; + return true; + } + for (unsigned i = 0; i < 4 && single; i++) { + struct usse_reg r; + + if (!(mask & 1u << i) || (csel && csel[i] != F16_NO_SEL)) + continue; + switch (l[i].kind) { + case F16K_REG: + case F16K_UNIFORM: + if (l[i].kind == F16K_UNIFORM) { + if (!f16_uniform(g, l[i].word & ~3u, &r)) + return false; + o->sw[i] = l[i].word & 3; + } else { + r = l[i].reg; + o->sw[i] = l[i].lane; + } + single &= !have || (reg.bank == r.bank && reg.num == r.num); + reg = r; + have = true; + break; + case F16K_CONST: + o->sw[i] = f16_const_sel(l[i].bits); + if (o->sw[i] == F16_NO_SEL) { + float f = uif(l[i].bits); + + h[i] = _mesa_float_to_half(f); + pool = true; + } + break; + default: + single = false; + break; + } + } + if (single && pool && !have) { + /* constants alone: those not src1's in a pair of the pool */ + int w = f16_pool(g->c, h); + + if (w < 0) + return false; + reg = usse_reg(USSE_SA, w); + for (unsigned i = 0; i < 4; i++) + if ((mask & 1u << i) && o->sw[i] == F16_NO_SEL) + o->sw[i] = i; + have = true; + pool = false; + } + if (single && !pool) { + o->reg = reg; + return true; + } + if (!into) + return false; + p = f16_temp(g); + if (!f16_into(g, s, csel, mask, p)) + return false; + o->reg = f16_reg(g, p); + memcpy(o->sw, f16_xyzw, 4); + o->neg = false; + return true; +} + +/* (M46) A lookup an F16 program makes itself, at coordinates it works out + * (PPSSPP's TClampST programs clamp them to a texture's rectangle: 23 + * instructions in F32, its texture times colour 11 of them): the + * coordinates in F32 into a pair, the texel four F16 into another as the + * PDS's are -- a plain 2D lookup of a texture of 8-bit channels. */ +static bool +f16_lookup_ok(const struct comp *c, const nir_tex_instr *tex) +{ + int coord = nir_tex_instr_src_index(tex, nir_tex_src_coord); + + for (unsigned i = 0; i < tex->num_srcs; i++) + if (tex->src[i].src_type != nir_tex_src_coord) + return false; + return tex->op == nir_texop_tex && tex->sampler_dim == GLSL_SAMPLER_DIM_2D && + !tex->is_shadow && !tex->is_array && coord >= 0 && + tex->src[coord].src.ssa->num_components == 2 && tex->texture_index < MAX_UNITS && + c->slot_of_unit[tex->texture_index] >= 0 && + !((c->fs->blend.tex_f16 | c->fs->blend.tex_depth) >> tex->texture_index & 1); +} + +/* the varyings a coordinate of such a lookup reads, marked to be iterated + * as F32 (in_f32) -- false if it reads anything but varyings, uniforms, + * constants (M50: the pool's) and fadd, fmul, fmin, fmax and fneg of them */ +static bool +f16_coord_inputs(struct comp *c, nir_scalar s, unsigned depth) +{ + s = nir_scalar_chase_movs(s); + if (depth > 8) + return false; + if (nir_scalar_is_const(s)) + return true; + if (nir_scalar_is_alu(s)) { + nir_op op = nir_scalar_alu_op(s); + + if (op != nir_op_fadd && op != nir_op_fmul && op != nir_op_fmin && op != nir_op_fmax && + op != nir_op_fneg) + return false; + for (unsigned i = 0; i < nir_op_infos[op].num_inputs; i++) + if (!f16_coord_inputs(c, nir_scalar_chase_alu_src(s, i), depth + 1)) + return false; + return true; + } + if (nir_scalar_is_intrinsic(s)) { + nir_intrinsic_instr *in = nir_def_as_intrinsic(s.def); + + if (in->intrinsic == nir_intrinsic_load_input) { + int slot = input_slot(in); + + if (slot < 0 || c->input_of_slot[slot] < 0) + return false; + c->in_f32 |= 1u << c->input_of_slot[slot]; + return true; + } + return in->intrinsic == nir_intrinsic_load_uniform && nir_src_is_const(in->src[0]); + } + return false; +} + +/* an F32 temporary: the halves of the pairs f16_temp() hands out */ +static struct usse_reg +f16_f32_temp(struct f16g *g) +{ + unsigned p; + + if (g->f32_spare >= 0) { + struct usse_reg r = treg(g->c, g->f32_spare); + + g->f32_spare = -1; + return r; + } + p = f16_temp(g); + g->f32_spare = 2 * p + 1; + return treg(g->c, 2 * p); +} + +/* (M50) an F32 constant in a pair of the pool, in the lane asked for (x the + * pair's first word, y its second): the other operand's of a VTSTMSK */ +static bool +f16_f32_const(struct comp *c, uint32_t bits, unsigned lane, struct usse_reg *out) +{ + uint16_t h[4] = { 0 }; + int w; + + h[2 * lane] = bits & 0xffff; + h[2 * lane + 1] = bits >> 16; + if ((w = f16_pool(c, h)) < 0) + return false; + *out = usse_reg(USSE_SA, w + lane); + return true; +} + +/* (M50) whether F32 can make s alone: constants, uniforms, varyings marked + * F32 and fadd, fmul, ffma, fmin, fmax, fneg of them */ +static bool +f16_f32_able(struct comp *c, nir_scalar s, unsigned depth) +{ + s = nir_scalar_chase_movs(s); + if (depth > 8) + return false; + if (nir_scalar_is_const(s)) + return true; + if (nir_scalar_is_alu(s)) { + nir_op op = nir_scalar_alu_op(s); + + if (op != nir_op_fadd && op != nir_op_fmul && op != nir_op_ffma && op != nir_op_fmin && + op != nir_op_fmax && op != nir_op_fneg) + return false; + for (unsigned i = 0; i < nir_op_infos[op].num_inputs; i++) + if (!f16_f32_able(c, nir_scalar_chase_alu_src(s, i), depth + 1)) + return false; + return true; + } + if (nir_scalar_is_intrinsic(s)) { + nir_intrinsic_instr *in = nir_def_as_intrinsic(s.def); + + if (in->intrinsic == nir_intrinsic_load_input) { + int slot = input_slot(in); + + return slot >= 0 && c->input_of_slot[slot] >= 0 && + (c->in_f32 >> c->input_of_slot[slot] & 1); + } + return in->intrinsic == nir_intrinsic_load_uniform && nir_src_is_const(in->src[0]); + } + return false; +} + +/* (M50) the varyings (a mask of input indices) s reads, a lookup's + * coordinates not looked into (the lookup a value of its own) */ +static unsigned +f16_tree_inputs(const struct comp *c, nir_scalar s, unsigned depth) +{ + unsigned m = 0; + + s = nir_scalar_chase_movs(s); + if (depth > 12) + return ~0u; + if (nir_scalar_is_alu(s)) { + nir_op op = nir_scalar_alu_op(s); + + for (unsigned i = 0; i < nir_op_infos[op].num_inputs; i++) + m |= f16_tree_inputs(c, nir_scalar_chase_alu_src(s, i), depth + 1); + } else if (nir_scalar_is_intrinsic(s)) { + nir_intrinsic_instr *in = nir_def_as_intrinsic(s.def); + int slot; + + if (in->intrinsic == nir_intrinsic_load_input && + (slot = input_slot(in)) >= 0 && c->input_of_slot[slot] >= 0) + m |= 1u << c->input_of_slot[slot]; + } + return m; +} + +/* (M50) whether s reads a texel (a lookup's, the PDS's or the program's): + * a value only such may come to F32 from F16 */ +static bool +f16_has_texel(const struct comp *c, nir_scalar s, unsigned depth) +{ + s = nir_scalar_chase_movs(s); + if (depth > 8) + return false; + if (nir_def_instr(s.def)->type == nir_instr_type_tex) + return true; + if (nir_scalar_is_alu(s)) { + nir_op op = nir_scalar_alu_op(s); + + for (unsigned i = 0; i < nir_op_infos[op].num_inputs; i++) + if (f16_has_texel(c, nir_scalar_chase_alu_src(s, i), depth + 1)) + return true; + } + return false; +} + +/* (M50) s made by the colour's tree in F16 (where it is already, or worked + * out into a pair's lane), unpacked to F32 into a pair of its own: *out + * the half that holds it */ +static bool +f16_to_f32(struct f16g *g, nir_scalar s, struct usse_reg *out) +{ + nir_scalar v[4] = { s, s, s, s }; + struct f16o o; + unsigned lane, p; + + if (!f16_operand(g, v, NULL, 0x1, &o) || o.neg || o.sw[0] > 3 || o.reg.bank == USSE_SA || + (o.reg.num & 1)) + return false; + lane = o.sw[0]; + p = f16_temp(g); + emit(g->c, usse_unpack_f16(f16_reg(g, p), o.reg, lane & 2)); + *out = treg(g->c, 2 * p + (lane & 1)); + return true; +} + +/* s's F32 value, part of a lookup's coordinates, in *out: a varying + * f16_coord_inputs() marked (its four F32 in pa), a uniform (sa), or + * fadd, fmul, fmin, fmax of such values -- an fneg the operand's + * negation -- each operation worked out once, into a temporary of its own + * or, at the root, into *dest (the lookup's coordinate registers: no move + * after). False on anything else. */ +static bool +f16_coord(struct f16g *g, nir_scalar s, const struct usse_reg *dest, struct usse_reg *out) +{ + struct comp *c = g->c; + struct usse_reg r; + + s = nir_scalar_chase_movs(s); + /* (M50) a constant: the pool's */ + if (nir_scalar_is_const(s)) { + if (!f16_f32_const(c, (uint32_t)nir_scalar_as_uint(s), 0, &r)) + return false; + goto have; + } + /* (M50) in a chain: what F32 cannot make, F16's -- an operation + * F32 can do with a constant or uniform among its operands stays F32 + * (the coordinate's precision), the rest unpacked */ + if (g->chain && !f16_f32_able(c, s, 0)) { + bool f32op = false; + + if (nir_scalar_is_alu(s)) { + nir_op op = nir_scalar_alu_op(s); + + if (op == nir_op_fadd || op == nir_op_fmul || op == nir_op_ffma || + op == nir_op_fmin || op == nir_op_fmax || op == nir_op_fneg) + for (unsigned i = 0; i < nir_op_infos[op].num_inputs; i++) + f32op |= f16_f32_able(c, nir_scalar_chase_alu_src(s, i), 0); + } + if (!f32op) { + if (!f16_has_texel(c, s, 0) || (f16_tree_inputs(c, s, 0) & ~g->colour_inputs)) + return false; + for (unsigned k = 0; k < g->nf32made; k++) + if (g->f32made[k].def == s.def && g->f32made[k].comp == s.comp) { + r = g->f32made[k].reg; + goto have; + } + if (!f16_to_f32(g, s, &r)) + return false; + if (g->nf32made < ARRAY_SIZE(g->f32made)) { + g->f32made[g->nf32made].def = s.def; + g->f32made[g->nf32made].comp = s.comp; + g->f32made[g->nf32made++].reg = r; + } + goto have; + } + } + if (nir_scalar_is_alu(s)) { + nir_op op = nir_scalar_alu_op(s); + enum usse_nmad_op nop; + struct usse_reg a, b, t, d; + + if (op == nir_op_ffma) { + struct usse_reg m; + + for (unsigned k = 0; k < g->nf32made; k++) + if (g->f32made[k].def == s.def && g->f32made[k].comp == s.comp) { + r = g->f32made[k].reg; + goto have; + } + if (!f16_coord(g, nir_scalar_chase_alu_src(s, 0), NULL, &a) || + !f16_coord(g, nir_scalar_chase_alu_src(s, 1), NULL, &b) || + !f16_coord(g, nir_scalar_chase_alu_src(s, 2), NULL, &m) || a.neg || b.neg || m.neg) + return false; + /* (src0 a temporary or primary attribute, absolute only) */ + if (a.bank != USSE_TEMP && a.bank != USSE_PA) { + t = a; + a = b; + b = t; + } + if (a.bank != USSE_TEMP && a.bank != USSE_PA) { + t = f16_f32_temp(g); + emit(c, usse_fop(USSE_NMAD_MUL, t, a, b)); + d = dest ? *dest : f16_f32_temp(g); + emit(c, usse_fop(USSE_NMAD_ADD, d, t, m)); + } else { + d = dest ? *dest : f16_f32_temp(g); + emit(c, usse_fmad(d, a, b, m)); + } + if (g->nf32made < ARRAY_SIZE(g->f32made)) { + g->f32made[g->nf32made].def = s.def; + g->f32made[g->nf32made].comp = s.comp; + g->f32made[g->nf32made++].reg = d; + } + *out = d; + return true; + } + if (op == nir_op_fneg) { + if (dest || !f16_coord(g, nir_scalar_chase_alu_src(s, 0), NULL, out)) + return false; + out->neg = !out->neg; + return true; + } + for (unsigned k = 0; k < g->nf32made; k++) + if (g->f32made[k].def == s.def && g->f32made[k].comp == s.comp) { + r = g->f32made[k].reg; + goto have; + } + switch (op) { + case nir_op_fadd: nop = USSE_NMAD_ADD; break; + case nir_op_fmul: nop = USSE_NMAD_MUL; break; + case nir_op_fmin: nop = USSE_NMAD_MIN; break; + case nir_op_fmax: nop = USSE_NMAD_MAX; break; + default: return false; + } + if (!f16_coord(g, nir_scalar_chase_alu_src(s, 0), NULL, &a) || + !f16_coord(g, nir_scalar_chase_alu_src(s, 1), NULL, &b)) + return false; + /* the second source takes no negation: swap (all four commute), and + * a product of two negations is the product (binary()'s) */ + if (b.neg && !a.neg) { + t = a; + a = b; + b = t; + } + if (nop == USSE_NMAD_MUL && a.neg && b.neg) + a.neg = b.neg = false; + /* (the same for every pixel -- of uniforms, PPSSPP's size less half + * a texel: a pair the draw works out) */ + if (f16_derivable(c, a) && f16_derivable(c, b)) { + static const uint8_t kinds[] = { + [USSE_NMAD_ADD] = SGX_DERIVED_ADD, [USSE_NMAD_MUL] = SGX_DERIVED_MUL, + [USSE_NMAD_MIN] = SGX_DERIVED_MIN, [USSE_NMAD_MAX] = SGX_DERIVED_MAX, + }; + int w = f16_derived(c, kinds[nop], a.num, a.neg, b.num, b.neg); + + if (w >= 0) { + r = usse_reg(USSE_SA, w); + if (g->nf32made < ARRAY_SIZE(g->f32made)) { + g->f32made[g->nf32made].def = s.def; + g->f32made[g->nf32made].comp = s.comp; + g->f32made[g->nf32made++].reg = r; + } + goto have; + } + } + if (b.neg) + return false; + d = dest ? *dest : f16_f32_temp(g); + emit(c, usse_fop(nop, d, a, b)); + if (g->nf32made < ARRAY_SIZE(g->f32made)) { + g->f32made[g->nf32made].def = s.def; + g->f32made[g->nf32made].comp = s.comp; + g->f32made[g->nf32made++].reg = d; + } + *out = d; + return true; + } + if (!nir_scalar_is_intrinsic(s)) + return false; + { + nir_intrinsic_instr *in = nir_def_as_intrinsic(s.def); + + if (in->intrinsic == nir_intrinsic_load_input) { + int slot = input_slot(in); + unsigned comp = nir_intrinsic_component(in) + s.comp; + + if (slot < 0 || c->input_of_slot[slot] < 0 || comp >= 4 || + !(c->in_f32 >> c->input_of_slot[slot] & 1)) + return false; + r = usse_reg(USSE_PA, c->in_pa[c->input_of_slot[slot]] + comp); + } else if (in->intrinsic == nir_intrinsic_load_uniform && nir_src_is_const(in->src[0])) { + unsigned at = (nir_intrinsic_base(in) + nir_src_as_uint(in->src[0])) * 4 + s.comp; + + if (at >= c->sa_uniforms) + return false; + r = usse_reg(USSE_SA, at); + } else { + return false; + } + } +have: + if (dest) { + emit(c, usse_fmov(*dest, r)); + r = *dest; + } + *out = r; + return true; +} + +/* (M50) a kill's condition -- lower_discard_to_zero's: flt, fge, feq, fneu + * of F32 values (f16_coord's, in a chain), ior, iand and inot of such -- as + * VTSTMSK's mask, ~0 where it holds: *out, a register of a pair of its own */ +static bool +f16_cond(struct f16g *g, nir_scalar s, struct usse_reg *out, unsigned depth) +{ + static const enum usse_cmp swapped[] = { USSE_CMP_GT, USSE_CMP_GE, USSE_CMP_EQ, USSE_CMP_NE, + USSE_CMP_LE, USSE_CMP_LT }; + struct comp *c = g->c; + struct usse_reg a, b; + nir_scalar sa, sb, t; + enum usse_cmp cmp; + bool ok, chain = g->chain; + unsigned p; + nir_op op; + + s = nir_scalar_chase_movs(s); + if (depth > 4 || !nir_scalar_is_alu(s)) + return false; + op = nir_scalar_alu_op(s); + if (op == nir_op_ior || op == nir_op_iand) { + if (!f16_cond(g, nir_scalar_chase_alu_src(s, 0), &a, depth + 1) || + !f16_cond(g, nir_scalar_chase_alu_src(s, 1), &b, depth + 1)) + return false; + p = f16_temp(g); + *out = f16_reg(g, p); + emit(c, usse_vbw(op == nir_op_ior ? USSE_VBW_OR : USSE_VBW_AND, *out, a, b, false)); + return true; + } + if (op == nir_op_inot) { + if (!f16_cond(g, nir_scalar_chase_alu_src(s, 0), &a, depth + 1)) + return false; + p = f16_temp(g); + *out = f16_reg(g, p); + emit(c, usse_vbw(USSE_VBW_XOR, *out, a, USSE_ALL_ONES, false)); + return true; + } + switch (op) { + case nir_op_flt32: cmp = USSE_CMP_LT; break; + case nir_op_fge32: cmp = USSE_CMP_GE; break; + case nir_op_feq32: cmp = USSE_CMP_EQ; break; + case nir_op_fneu32: cmp = USSE_CMP_NE; break; + default: return false; + } + sa = nir_scalar_chase_movs(nir_scalar_chase_alu_src(s, 0)); + sb = nir_scalar_chase_movs(nir_scalar_chase_alu_src(s, 1)); + /* (a constant as src2, in src1's lane; 0 the hardware's c0) */ + if (nir_scalar_is_const(sa)) { + if (nir_scalar_is_const(sb)) + return false; + t = sa; + sa = sb; + sb = t; + cmp = swapped[cmp]; + } + g->chain = true; + ok = f16_coord(g, sa, NULL, &a); + g->chain = chain; + if (!ok) + return false; + if (nir_scalar_is_const(sb)) { + uint32_t bits = (uint32_t)nir_scalar_as_uint(sb); + + if (!(bits & 0x7fffffffu)) + b = USSE_ZERO; + else if (!f16_f32_const(c, bits, a.num & 1, &b)) + return false; + } else { + g->chain = true; + ok = f16_coord(g, sb, NULL, &b); + g->chain = chain; + if (!ok || b.neg) + return false; + if ((b.num & 1) != (a.num & 1)) { + struct usse_reg m = treg(c, 2 * f16_temp(g) + (a.num & 1)); + + emit(c, usse_fmov(m, b)); + b = m; + } + } + p = f16_temp(g); + emit(c, usse_vtstmsk_f32(f16_reg(g, p), a, b, cmp)); + *out = treg(c, 2 * p + (a.num & 1)); + return true; +} + +static bool +f16_colour(struct comp *c, nir_function_impl *impl) +{ + nir_intrinsic_instr *out = NULL; + struct usse_reg o0 = usse_reg(USSE_OUTPUT, 0), colour; + struct f16g g = { .c = c, .f32_spare = -1 }; + nir_tex_instr *lookups[4]; + bool chained[4] = { false }; + unsigned nlookups = 0, nplain = 0, pa = 0, high = 0; + nir_scalar s[4], kill = { 0 }; + uint8_t kill_one[4]; + bool has_kill = false; + struct f16o col; + + if (getenv("SGX_NO_F16") || c->vs || c->kills || c->ncolours || c->logicop >= 0 || + c->fs->blend.rt_kind != SGX_RT_UNORM8 || c->fs->blend.rt_srgb || + c->fs->blend.rt_intensity || c->ubuf || exec_list_length(&impl->body) != 1) + return false; + nir_foreach_block(block, impl) { + nir_foreach_instr(instr, block) { + if (instr->type == nir_instr_type_intrinsic) { + nir_intrinsic_instr *in = nir_instr_as_intrinsic(instr); + + if (in->intrinsic == nir_intrinsic_store_output) { + if (out || nir_intrinsic_component(in) || nir_intrinsic_write_mask(in) != 0xf || + in->src[0].ssa->num_components != 4) + return false; + out = in; + } else if (in->intrinsic != nir_intrinsic_load_input && + in->intrinsic != nir_intrinsic_load_uniform) { + return false; + } + } else if (instr->type == nir_instr_type_tex) { + /* (M46) or a lookup at coordinates the program works out + * (SGX_NO_F16_SMP=1: not in F16) */ + if (!is_fetch(c, instr) && + (getenv("SGX_NO_F16_SMP") || nlookups == ARRAY_SIZE(lookups) || + !f16_lookup_ok(c, nir_instr_as_tex(instr)))) + return false; + if (!is_fetch(c, instr)) + lookups[nlookups++] = nir_instr_as_tex(instr); + } else if (instr->type != nir_instr_type_alu && + instr->type != nir_instr_type_load_const) { + return false; + } + } + } + if (!out) + return false; + for (unsigned i = 0; i < c->ninputs; i++) + if (c->fs->input_slot[i] == VARYING_SLOT_POS) + return false; + /* (M46) the varyings the lookups' coordinates read iterated as F32 -- + * those only: the colour's leaves refuse them (f16_leaf()). (M50) A + * lookup at coordinates worked out from a texel (PPSSPP's alpha test's + * table, at the colour's alpha) is chained: made after the others, its + * coordinates in F32 from the colour's tree (SGX_NO_F16_CHAIN=1: not in + * F16) */ + c->in_f32 = 0; + for (unsigned k = 0; k < nlookups; k++) { + int ci = nir_tex_instr_src_index(lookups[k], nir_tex_src_coord); + unsigned before = c->in_f32; + + for (unsigned i = 0; i < 2 && !chained[k]; i++) + if (!f16_coord_inputs(c, nir_get_scalar(lookups[k]->src[ci].src.ssa, i), 0)) { + if (getenv("SGX_NO_F16_CHAIN")) { + c->in_f32 = 0; + return false; + } + c->in_f32 = before; + chained[k] = true; + } + nplain += !chained[k]; + } + /* (M50) the colour stored 0 where a discard would take the pixel + * (lower_discard_to_zero's bcsel, each channel the same condition; a + * channel of 1, b2f(inot(the condition)) by then, the constant 1 of + * src1's swizzle): the colour, then VTSTMSK's mask of the condition + * taken out of it */ + memset(kill_one, F16_NO_SEL, sizeof(kill_one)); + for (unsigned i = 0; i < 4; i++) { + nir_scalar v = nir_scalar_chase_movs(nir_get_scalar(out->src[0].ssa, i)); + nir_scalar k, z; + + s[i] = v; + has_kill = false; + if (!nir_scalar_is_alu(v)) + break; + if (nir_scalar_alu_op(v) == nir_op_b2f32) { + k = nir_scalar_chase_movs(nir_scalar_chase_alu_src(v, 0)); + if (!nir_scalar_is_alu(k) || nir_scalar_alu_op(k) != nir_op_inot) + break; + k = nir_scalar_chase_movs(nir_scalar_chase_alu_src(k, 0)); + kill_one[i] = F16_SEL_1; + } else if (nir_scalar_alu_op(v) == nir_op_bcsel || + nir_scalar_alu_op(v) == nir_op_b32csel) { + k = nir_scalar_chase_movs(nir_scalar_chase_alu_src(v, 0)); + z = nir_scalar_chase_movs(nir_scalar_chase_alu_src(v, 1)); + if (!nir_scalar_is_const(z) || nir_scalar_as_uint(z)) + break; + } else { + break; + } + if (i && (k.def != kill.def || k.comp != kill.comp)) + break; + kill = k; + has_kill = true; + } + if (!has_kill) + memset(kill_one, F16_NO_SEL, sizeof(kill_one)); + else if (kill_one[0] == F16_SEL_1 && kill_one[1] == F16_SEL_1 && kill_one[2] == F16_SEL_1 && + kill_one[3] == F16_SEL_1) + return false; + /* (the varyings the colour reads: those a chain may take in F16 -- none + * when the colour's tree is too deep to tell) */ + for (unsigned i = 0; i < 4; i++) { + unsigned m = 0; + + if (!has_kill) + m = f16_tree_inputs(c, nir_get_scalar(out->src[0].ssa, i), 0); + else if (kill_one[i] != F16_SEL_1) + m = f16_tree_inputs(c, nir_scalar_chase_alu_src(s[i], 2), 0); + g.colour_inputs |= m == ~0u ? 0 : m; + } + if (has_kill && getenv("SGX_NO_F16_KILL")) + return false; + + /* the code: the inputs in pa, two registers each (four an F32 one), the + * texels after them, two each; the pool's pairs after the program's + * other sa words */ + for (unsigned i = 0; i < c->ninputs; i++) { + c->in_pa[i] = pa; + pa += c->in_f32 >> i & 1 ? 4 : 2; + } + c->fetch_pa = pa; + c->nkconst = 0; + c->kconst_sa = align(fs_sa_end(c), 2); + util_dynarray_init(&c->code, NULL); + emit(c, USSE_PHAS); + /* (M46) the program's own lookups first: each coordinate worked out + * into its register of a pair, then SMP's texel four F16 into another + * pair -- a value of the colour's tree as the PDS's texels are. The + * texels' pairs first: what the coordinates took is the tree's again + * after the last SMP (it has the coordinates by then, as the F32 way's + * scratch registers) -- 18 temporaries a pixel were 10 */ + for (unsigned k = 0; k < nlookups; k++) + f16_temp(&g); + /* the plain lookups (pass 0), their texels in the first pairs; then + * (M50) the chained ones, their texels in the pairs after those, once + * the plain ones' coordinates' pairs are the tree's again -- in the + * order the program has them (a chained one's coordinates may read one + * before it) */ + for (unsigned pass = 0, n = 0, m = nplain; pass < 2; pass++) + for (unsigned k = 0; k < nlookups; k++) { + nir_tex_instr *tex = lookups[k]; + int ci = nir_tex_instr_src_index(tex, nir_tex_src_coord); + unsigned cp, tp; + struct usse_reg r; + + if (chained[k] != (pass == 1)) + continue; + if (pass == 1 && m == nplain && nplain) { + high = MAX2(high, g.ntemp); + g.ntemp = nlookups; + g.f32_spare = -1; + g.nf32made = 0; + g.npacked = 0; + } + tp = pass ? m++ : n++; + cp = f16_temp(&g); + g.chain = pass == 1; + for (unsigned i = 0; i < 2; i++) { + struct usse_reg d = treg(c, 2 * cp + i); + + if (!f16_coord(&g, nir_get_scalar(tex->src[ci].src.ssa, i), &d, &r)) { + g.chain = false; + goto fail; + } + } + g.chain = false; + emit(c, usse_smp2d(USSE_SMP_F16, USSE_SMP_COORD_F32, f16_reg(&g, tp), treg(c, 2 * cp), + usse_reg(USSE_SA, c->sampler_sa + 4 * c->slot_of_unit[tex->texture_index]), + USSE_SMP_NONE, treg(c, 0))); + emit(c, USSE_WDF0); + /* (0..1: the texture's state word 3 bit 31, as the PDS's F16 lookups + * have it (smp_norm, the draw's) -- without it the sampler hands an + * 8-bit channel back as its integer value, as for F32 (texture()). + * SGX_F16_SMP_SCALE=1: times F16's 1/255 instead, which takes 255 to + * 1.0 exactly) */ + if (!getenv("SGX_F16_SMP_SCALE")) { + c->smp_norm |= 1u << c->slot_of_unit[tex->texture_index]; + } else { + uint16_t h = _mesa_float_to_half(1.0f / 255.0f); + const uint16_t k255[4] = { h, h, h, h }; + int w = f16_pool(c, k255); + + if (w < 0) + goto fail; + emit(c, usse_hop(USSE_NMAD_MUL, f16_reg(&g, tp), f16_reg(&g, tp), usse_reg(USSE_SA, w))); + } + for (unsigned i = 0; i < 4; i++) { + if (g.nmade == F16_MAX_MADE) + goto fail; + g.made[g.nmade].def = &tex->def; + g.made[g.nmade].comp = i; + g.made[g.nmade].pair = tp; + g.made[g.nmade++].lane = i; + } + c->smp = true; + } + /* the coordinates' pairs the colour's tree's: what a chain made in them + * forgotten (made again where the colour needs it) */ + if (nlookups) { + high = MAX2(high, g.ntemp); + g.ntemp = nlookups; + g.f32_spare = -1; + g.nf32made = 0; + g.npacked = 0; + for (unsigned k = 0; k < g.nmade;) { + if (g.made[k].pair >= nlookups) + g.made[k] = g.made[--g.nmade]; + else + k++; + } + } + /* the colour: the kill's bcsel's third operand (or 1), or the store's + * value */ + for (unsigned i = 0; i < 4; i++) + s[i] = !has_kill ? nir_get_scalar(out->src[0].ssa, i) : + kill_one[i] == F16_SEL_1 ? s[i] : nir_scalar_chase_alu_src(s[i], 2); + if (!f16_operand(&g, s, has_kill ? kill_one : NULL, 0xf, &col)) + goto fail; + if (col.neg || memcmp(col.sw, f16_xyzw, 4) || col.reg.bank == USSE_SA || + (has_kill && col.reg.bank != USSE_TEMP)) { + unsigned p = f16_temp(&g); + + if (!f16_move(&g, &col, 0xf, p)) + goto fail; + col.reg = f16_reg(&g, p); + } + /* (M50) 0 where the kill holds: the colour's two words and not its mask, + * in place (a temporary of its own by now, read by the pack alone) */ + if (has_kill) { + struct usse_reg m, lo = col.reg, hi = col.reg; + + if (!f16_cond(&g, kill, &m, 0)) + goto fail; + hi.num++; + emit(c, usse_vbw(USSE_VBW_AND, lo, lo, m, true)); + emit(c, usse_vbw(USSE_VBW_AND, hi, hi, m, true)); + } + if (g.failed || util_dynarray_num_elements(&c->code, uint64_t) > F16_MAX_CODE) + goto fail; + colour = col.reg; + if (c->sop2) { + struct usse_reg packed = f16_reg(&g, f16_temp(&g)); + struct usse_reg t1 = c->sop2_pre_dst ? f16_reg(&g, f16_temp(&g)) : packed; + struct usse_reg t2 = c->sop2_post ? f16_reg(&g, f16_temp(&g)) : packed; + + emit(c, usse_pack_unorm8_f16(packed, colour)); + c->f16_out_at = util_dynarray_num_elements(&c->code, uint64_t); + emit_sop2(c, packed, t1, t2); + } else { + c->f16_out_at = util_dynarray_num_elements(&c->code, uint64_t); + emit(c, usse_pack_unorm8_f16(o0, colour) | USSE_END); + } + if (g.failed) + goto fail; + c->top = MAX2(c->top, 2 * MAX2(g.ntemp, high)); + c->f16 = true; + return true; +fail: + util_dynarray_fini(&c->code); + c->nkconst = 0; + c->nderived = 0; + c->kconst_derived = 0; + c->in_f32 = 0; + c->smp_norm = 0; + c->smp = false; + return false; +} + +/* where a fragment program's sa words end: the uniforms, the textures' + * state words, their scales and sizes, the blend colour */ +static unsigned +fs_sa_end(const struct comp *c) +{ + return c->blend_sa >= 0 ? c->blend_sa + 4 : + c->sizes ? c->size_sa + SGX_FS_SIZE_WORDS * c->nsamplers : + c->scales ? c->scale_sa + 2 * c->nsamplers : + c->nsamplers ? c->sampler_sa + 4 * c->nsamplers : c->nuniforms; +} + +/* (M46) the constants a fragment program's ALU operations read, into sa + * after its other words (SGX_FS_MAX_KCONST at most, while sa has room): a + * LIMM before each use took a third of PPSSPP's programs (God of War's + * `2.0`, a saturate's 0 and 1). SGX_NO_KPOOL=1: none. */ +static void +plan_constants(struct comp *c, nir_function_impl *impl) +{ + unsigned end = align(fs_sa_end(c), 2); + + c->nkconst = 0; + if (getenv("SGX_NO_KPOOL")) + return; + nir_foreach_block(block, impl) { + nir_foreach_instr(instr, block) { + nir_alu_instr *alu; + uint32_t want[4]; + unsigned n = 0; + + if (instr->type != nir_instr_type_alu) + continue; + alu = nir_instr_as_alu(instr); + if (alu->op == nir_op_fsat) { + want[n++] = f32_bits(0.0f); + want[n++] = f32_bits(1.0f); + } + for (unsigned i = 0; i < nir_op_infos[alu->op].num_inputs && n < 4; i++) { + struct operand o; + + if (alu->src[i].src.ssa->bit_size != 32) + continue; + o = alu_operand(alu, i); + if (o.is_const) + want[n++] = o.u; + } + for (unsigned j = 0; j < n; j++) { + unsigned k = 0; + + while (k < c->nkconst && (c->kconst[2 * k] != want[j] || c->kconst[2 * k + 1])) + k++; + if (k == c->nkconst && k < SGX_FS_MAX_KCONST && end + 2 * (k + 1) <= 128) { + c->kconst[2 * k] = want[j]; + c->kconst[2 * k + 1] = 0; + c->nkconst++; + } + } + } + } + c->kconst_sa = end; +} + +/* (M46) a colour channel saturated just before it is stored into a target + * of bytes: the pack to them clamps (pck.u8.f32, pck.u8.f16) -- the max and + * min, and their constants, for nothing */ +static void +drop_output_sat(nir_function_impl *impl) +{ + nir_foreach_block(block, impl) { + nir_foreach_instr(instr, block) { + nir_intrinsic_instr *st; + nir_alu_instr *vec; + unsigned loc; + + if (instr->type != nir_instr_type_intrinsic) + continue; + st = nir_instr_as_intrinsic(instr); + if (st->intrinsic != nir_intrinsic_store_output) + continue; + loc = nir_intrinsic_io_semantics(st).location; + if ((loc != FRAG_RESULT_COLOR && loc != FRAG_RESULT_DATA0) || + nir_def_instr(st->src[0].ssa)->type != nir_instr_type_alu) + continue; + vec = nir_instr_as_alu(nir_def_instr(st->src[0].ssa)); + if (!nir_op_is_vec(vec->op) || !list_is_singular(&vec->def.uses)) + continue; + for (unsigned i = 0; i < nir_op_infos[vec->op].num_inputs; i++) { + nir_def *d = vec->src[i].src.ssa; + nir_alu_instr *sat; + + if (nir_def_instr(d)->type != nir_instr_type_alu) + continue; + sat = nir_instr_as_alu(nir_def_instr(d)); + if (sat->op != nir_op_fsat || sat->def.num_components != 1 || + !list_is_singular(&d->uses)) + continue; + vec->src[i].swizzle[0] = sat->src[0].swizzle[0]; + nir_src_rewrite(&vec->src[i].src, sat->src[0].src.ssa); + } + } + } +} + +/* s a varying's component made an integer -- f2i32 of it (or of its + * ftrunc, the same): which varying (its slot) and component */ +static bool +int_of_varying(nir_scalar s, int *slot, unsigned *comp) +{ + nir_intrinsic_instr *in; + + s = nir_scalar_chase_movs(s); + if (!nir_scalar_is_alu(s) || nir_scalar_alu_op(s) != nir_op_f2i32) + return false; + s = nir_scalar_chase_movs(nir_scalar_chase_alu_src(s, 0)); + if (nir_scalar_is_alu(s) && nir_scalar_alu_op(s) == nir_op_ftrunc) + s = nir_scalar_chase_movs(nir_scalar_chase_alu_src(s, 0)); + if (!nir_scalar_is_intrinsic(s) || + (in = nir_def_as_intrinsic(s.def))->intrinsic != nir_intrinsic_load_input || + (*slot = input_slot(in)) < 0) + return false; + *comp = nir_intrinsic_component(in) + s.comp; + return true; +} + +/* (M46) u_blitter's copies are texelFetch at a varying made an integer: + * the source's texel coordinates, x + 0.5 at pixel centres -- and a + * nearest lookup at the varying itself is the same texel (u_blitter only + * fetches so with a nearest sampler, of a view of one level; the level, + * the varying's w, is 0 for a 2D texture: get_texcoords). So a + * rectangle lookup at the varying times the texture's scale, which + * lower_fetch_coords() gives the PDS (M39): the copy's program 95 + * instructions -> 2. Internal shaders only (gallium's TGSI ones, marked + * so by sgx_create_shader_state); SGX_COPY_TXF=1: as they are. */ +static bool +txf_as_lookup(nir_builder *b, nir_instr *instr, void *data) +{ + nir_scalar xy[2]; + nir_tex_instr *tex; + int coord, lod, slot[3]; + unsigned comp[3]; + nir_def *at; + + if (instr->type != nir_instr_type_tex) + return false; + tex = nir_instr_as_tex(instr); + coord = nir_tex_instr_src_index(tex, nir_tex_src_coord); + lod = nir_tex_instr_src_index(tex, nir_tex_src_lod); + if (tex->op != nir_texop_txf || tex->sampler_dim != GLSL_SAMPLER_DIM_2D || tex->is_array || + tex->is_shadow || coord < 0 || tex->coord_components != 2 || + nir_alu_type_get_base_type(tex->dest_type) != nir_type_float || + tex->num_srcs != (lod >= 0 ? 2u : 1u)) + return false; + for (unsigned i = 0; i < 2; i++) + if (!int_of_varying(nir_get_scalar(tex->src[coord].src.ssa, i), &slot[i], &comp[i]) || + slot[i] != slot[0] || comp[i] != i) + return false; + /* (level 0: a constant, or the same varying's w as u_blitter has it) */ + if (lod >= 0 && !(nir_src_is_const(tex->src[lod].src) && !nir_src_as_uint(tex->src[lod].src)) && + !(int_of_varying(nir_get_scalar(tex->src[lod].src.ssa, 0), &slot[2], &comp[2]) && + slot[2] == slot[0] && comp[2] == 3)) + return false; + /* (the varying's x and y themselves) */ + for (unsigned i = 0; i < 2; i++) { + nir_scalar s = nir_scalar_chase_movs(nir_get_scalar(tex->src[coord].src.ssa, i)); + + s = nir_scalar_chase_movs(nir_scalar_chase_alu_src(s, 0)); + if (nir_scalar_is_alu(s) && nir_scalar_alu_op(s) == nir_op_ftrunc) + s = nir_scalar_chase_movs(nir_scalar_chase_alu_src(s, 0)); + xy[i] = s; + } + b->cursor = nir_before_instr(instr); + at = nir_vec2(b, nir_channel(b, xy[0].def, xy[0].comp), nir_channel(b, xy[1].def, xy[1].comp)); + at = nir_fmul(b, at, nir_load_texture_scale(b, 32, nir_imm_int(b, tex->texture_index))); + if (lod >= 0) + nir_tex_instr_remove_src(tex, lod); + coord = nir_tex_instr_src_index(tex, nir_tex_src_coord); + nir_src_rewrite(&tex->src[coord].src, at); + tex->op = nir_texop_tex; + tex->sampler_dim = GLSL_SAMPLER_DIM_RECT; + tex->sampler_index = tex->texture_index; + return true; +} + +static bool +translate(struct comp *c, nir_shader *s) +{ + nir_function_impl *impl; + unsigned n; + int index; + bool progress; + + optimize(s); + if (c->fs && s->info.internal && !getenv("SGX_COPY_TXF")) { + bool done = false; + + NIR_PASS(done, s, nir_shader_instructions_pass, txf_as_lookup, nir_metadata_control_flow, + NULL); + if (done) + optimize(s); + } + NIR_PASS(_, s, nir_shader_intrinsics_pass, fold_uniform_offset, nir_metadata_control_flow, + NULL); + if (!getenv("SGX_KEEP_SQRT")) + NIR_PASS(_, s, nir_shader_alu_pass, lower_sqrt_tests, nir_metadata_control_flow, NULL); + /* (M44) the integers the hardware's: divisions exact (nir_lower_idiv, + * the high halves of its products from 16-bit ones: nir_lower_alu), + * booleans 0 and ~0 */ + NIR_PASS(_, s, nir_lower_idiv, &(nir_lower_idiv_options){ .allow_fp16 = false }); + NIR_PASS(_, s, nir_lower_alu); + NIR_PASS(_, s, nir_shader_alu_pass, lower_ftrunc, nir_metadata_control_flow, NULL); + NIR_PASS(_, s, nir_opt_algebraic); + /* (late's lowerings before the booleans are words: roundEven's bcsel of + * an feq, its ffloor for the rules above) */ + NIR_PASS(_, s, nir_opt_algebraic_late); + do { + progress = false; + NIR_PASS(progress, s, nir_opt_algebraic); /* (ffloor, then its fsub) */ + } while (progress); + NIR_PASS(_, s, nir_opt_constant_folding); + NIR_PASS(_, s, nir_lower_bool_to_int32); + NIR_PASS(_, s, nir_opt_algebraic_late); + NIR_PASS(_, s, nir_shader_alu_pass, fmad_to_ffma, nir_metadata_all, NULL); + NIR_PASS(_, s, nir_lower_alu_to_scalar, scalar_filter(s), NULL); + NIR_PASS(_, s, nir_opt_copy_prop); + /* (M46) a vertex shader's products and sums fused (the dot products' + * too, which the scalar lowering just made): FMAD (fma_), its options' + * float_mul_add32 fuse bit */ + if (c->vs && (s->options->float_mul_add32 & nir_float_muladd_support_fuse)) { + NIR_PASS(_, s, nir_opt_algebraic_late); + NIR_PASS(_, s, nir_shader_alu_pass, fmad_to_ffma, nir_metadata_all, NULL); + NIR_PASS(_, s, nir_opt_copy_prop); + NIR_PASS(_, s, nir_opt_dce); + } + /* (M46) saturates the target's pack does anyway */ + if (c->fs && c->fs->blend.rt_kind == SGX_RT_UNORM8 && !c->fs->blend.rt_srgb && + !c->fs->blend.rt_intensity && !getenv("SGX_KEEP_SAT")) + drop_output_sat(nir_shader_get_entrypoint(s)); + if (!getenv("SGX_KEEP_SQRT")) + NIR_PASS(_, s, nir_shader_alu_pass, lower_fsqrt, nir_metadata_control_flow, NULL); + NIR_PASS(_, s, nir_opt_cse); + NIR_PASS(_, s, nir_opt_dce); + if (c->vs) + store_outputs_early(s); + /* values made just before their first use, in their block (M35): a + * value takes a register pair here, 32 of them, and the GLSL compiler's + * order had piglit's varying-packing vertex shaders make all 32 sums of + * a uniform first and use them after -- more than the temporaries hold. + * (nir_schedule's least-pressure order made its fragment shader worse: + * 32 comparisons first, then the chain that reads them.) NIR moves ALU + * operations with one source that is not a constant. */ + if (!c->keep_order) + NIR_PASS(_, s, nir_opt_move, nir_move_const_undef | nir_move_load_uniform | + nir_move_load_input | nir_move_comparisons | nir_move_alu); + + impl = nir_shader_get_entrypoint(s); + if (!c->vs && exec_list_length(&impl->body) != 1) { + /* what a loop does not change, out of it -- then whether any if + * (a loop's breaks among them) differs between pixels (M33) */ + NIR_PASS(_, s, nir_opt_licm, NULL); + nir_divergence_analysis(s); + nir_foreach_block(block, impl) { + nir_if *nif = nir_block_get_following_if(block); + + c->divergent |= nif && nir_src_is_divergent(&nif->condition); + } + /* the A6's rev 2.1.3: a loop whose branches go alike for all pixels, + * run the pixels-together way (PHAS mode 0, BR's all_inst), left its + * body out (glfs loop_uniform and array_loop: 0 where the loop + * should add, flight mesa1); each pixel on its own (mode 1) is + * right there, as the divergent loops showed */ + if (sgx_compiler_pixels_apart) + c->divergent = true; + } + if (c->fs) + lower_fetch_coords(c, s, impl); + /* control flow left: the phis' webs registers */ + if (exec_list_length(&impl->body) != 1) + NIR_PASS(_, s, nir_convert_from_ssa, true, false); + nir_index_ssa_defs(impl); + /* (one more: c->spare, M47) */ + c->nvalues = n = impl->ssa_alloc * 4 + 1; + c->spare = n - 1; + c->loc = calloc(n, sizeof(*c->loc)); + c->owned = calloc(n, sizeof(*c->owned)); + c->last_use = malloc(n * sizeof(*c->last_use)); + c->def_at = calloc(impl->ssa_alloc, sizeof(*c->def_at)); + if (!c->loc || !c->owned || !c->last_use || !c->def_at) { + fail(c, "out of memory"); + return false; + } + for (unsigned i = 0; i < n; i++) + c->last_use[i] = -1; + util_dynarray_init(&c->loops, NULL); + c->nir = s; + c->range = _mesa_pointer_hash_table_create(NULL); + + /* SGX_DEBUG_NIR=1: the shader as the compiler takes it */ + if (getenv("SGX_DEBUG_NIR")) + nir_print_shader(s, stderr); + if (c->fs) + plan_inputs(c, impl); + scan(c, impl); + if (c->failed) + return false; + /* M38: a colour of four F16 at once -- the whole program */ + if (c->fs && f16_colour(c, impl)) + return true; + if (c->fs) + plan_constants(c, impl); + + /* the numbering, the liveness, then the code, in the same order */ + index = 0; + c->nloops = 0; + walk(c, &impl->body, WALK_NUMBER, &index, NULL, 0); + index = 0; + c->nloops = 0; + walk(c, &impl->body, WALK_USES, &index, NULL, 0); + + util_dynarray_init(&c->code, NULL); + emit(c, USSE_PHAS); + /* the colour's registers first, and which values go into them: those + * an ALU instruction makes, each into one place (M34) */ + c->out_base = -1; + for (unsigned i = 0; i < 4; i++) + c->colour_id[i] = -1; + if (!c->vs) { + nir_foreach_block(block, impl) + nir_foreach_instr(instr, block) { + nir_intrinsic_instr *in; + + if (instr->type != nir_instr_type_intrinsic) + continue; + in = nir_instr_as_intrinsic(instr); + if (in->intrinsic != nir_intrinsic_store_output || block->cf_node.parent != &impl->cf_node) + continue; + for (unsigned i = 0; i < in->src[0].ssa->num_components; i++) { + unsigned comp = nir_intrinsic_component(in) + i; + struct operand o = resolve(nir_get_scalar(in->src[0].ssa, i)); + bool taken = false; + + nir_scalar sc = nir_scalar_chase_movs(nir_get_scalar(in->src[0].ssa, i)); + + /* (the value an ALU instruction makes, define()'s) */ + /* (V32NMAD's: the others' encodings take an even + * destination -- compares, selects, RCP -- and two of the + * four are odd) */ + if (comp >= 4 || !(nir_intrinsic_write_mask(in) & 1 << i) || o.is_const || o.neg || + o.abs || !nir_scalar_is_alu(sc) || + (nir_scalar_alu_op(sc) != nir_op_fmul && nir_scalar_alu_op(sc) != nir_op_fadd && + nir_scalar_alu_op(sc) != nir_op_fmin && nir_scalar_alu_op(sc) != nir_op_fmax) || + (unsigned)o.id != sc.def->index * 4 + sc.comp || sc.def->num_components != 1) + continue; + for (unsigned k = 0; k < 4; k++) + taken |= c->colour_id[k] == (int)o.id; + if (!taken) + c->colour_id[comp] = o.id; + } + } + } + if (c->kills) { + c->kill = block(c, 2, 2); + emit(c, usse_limm(treg(c, c->kill), 0)); + } + if (c->vs) { + plan_vs_outputs(c, impl); + vs_prologue(c); + } + /* (M47) the internal registers in a program of one block (the spans' + * code runs in order) */ + c->vec = c->vs && scalar_filter(s) && exec_list_length(&impl->body) == 1; + util_dynarray_init(&c->ispans, NULL); + plan_groups(c, impl); + /* (comparisons of two lanes in one: a program of one block) */ + if (exec_list_length(&impl->body) == 1 && !getenv("SGX_NO_CMP_PAIRS")) + c->premade = calloc(impl->ssa_alloc, sizeof(*c->premade)); + index = 0; + c->nloops = 0; + walk(c, &impl->body, WALK_CODE, &index, NULL, 0); + if (c->vec) + ireg_nosched(c); + /* a program that branches: PHAS mode 1, as iOS's c04_loop_break has, + * its pixels each on its own -- mode 0, the pixels together, when its + * branches go alike for all of them (M33) */ + if (c->branches) + *util_dynarray_element(&c->code, uint64_t, 0) = + !c->vs && !c->divergent ? USSE_PHAS : USSE_PHAS_BRANCHES; + return !c->failed; +} + +static struct sgx_fs * +compile_fs(const nir_shader *fs, const struct sgx_blend_key *blend, char *why, + unsigned why_size, bool keep_order) +{ + struct comp c = { .keep_order = keep_order }; + bool blending = blend && (blend->enable || blend->colormask != 0xf || blend->rt_srgb || + blend->rt_intensity); + nir_shader *s; + unsigned out_at; + bool discard_zero; + + c.why = why; + c.kill = -1; + c.logicop = -1; + c.why_size = why_size; + why[0] = 0; + if (!(c.fs = CALLOC_STRUCT(sgx_fs))) + return NULL; + for (unsigned i = 0; i < ARRAY_SIZE(c.input_of_slot); i++) + c.input_of_slot[i] = c.colour_of_slot[i] = -1; + + for (unsigned i = 0; i < ARRAY_SIZE(c.slot_of_unit); i++) + c.slot_of_unit[i] = -1; + c.blend_sa = -1; + c.scale_sa = -1; + c.size_sa = -1; + if (blend) + c.fs->blend = *blend; + else + c.fs->blend.colormask = 0xf; + /* (discard keeps the tile's colour as the colour: blended again, not + * kept, M19 -- unless it can be a source of 0 for this blending, M46: + * lower_discard_to_zero) */ + discard_zero = blending && fs->info.fs.uses_discard && blend_keeps_dst_for_zero(blend) && + discard_shape_ok(fs); + if (blending && (!fs->info.fs.uses_discard || discard_zero) && !blend->logicop && + blend->rt_kind == SGX_RT_UNORM8 && !blend->rt_srgb && !blend->rt_intensity && + !getenv("SGX_NO_SOP2")) { + struct sgx_blend_key folded; + + /* (M46: the colour mask too, SGX_SOP2_MASK=0 not) */ + if ((blend->colormask == 0xf || (!getenv("SGX_SOP2_MASK") || atoi(getenv("SGX_SOP2_MASK")))) && + fold_colormask(blend, &folded) && sop2_plan(&c, &folded)) { + c.sop2 = true; + c.fs->sop2 = true; + blending = false; + /* (the blend colour packed: placed with the textures' words) */ + if (c.sop2_pre_src || c.sop2_pre_dst || c.sop2_post) { + c.blend_sa = 0; + c.fs->blend_packed = true; + } + } + } + /* a logic op instead of the blending, and the colour mask with it: on + * the bytes, in output() (nir_lower_blend's are integer operations, + * which the compiler has not) */ + if (blend && blend->logicop && blend->rt_kind == SGX_RT_UNORM8) { + c.logicop = blend->logicop - 1; + blending = false; + } + + s = nir_shader_clone(NULL, fs); + /* (M46) a clamp the draw found does nothing: the lookup at the varying, + * the PDS's (the clamp's arithmetic dead after) */ + if (blend && blend->texclamp_free && lower_texclamp_free(s, blend->texclamp_free)) { + NIR_PASS(_, s, nir_opt_copy_prop); + NIR_PASS(_, s, nir_opt_dce); + } + /* the flat-shaded colours: the TA's (M37) -- GL's flat shading. Not + * other varyings: the linker makes one flat whose value is the same at + * every vertex (piglit's glsl-sin: a uniform's sine), and the TA's + * colours are bytes; a varying the same everywhere comes out so smooth */ + nir_foreach_shader_in_variable(var, s) { + if (var->data.interpolation != INTERP_MODE_FLAT || + (var->data.location != VARYING_SLOT_COL0 && var->data.location != VARYING_SLOT_COL1 && + var->data.location != VARYING_SLOT_BFC0 && var->data.location != VARYING_SLOT_BFC1)) + continue; + for (unsigned i = 0; i < glsl_count_attribute_slots(var->type, false); i++) + if (var->data.location + i < VARYING_SLOT_MAX) + c.flat[var->data.location + i] = true; + } + if (blending) + NIR_PASS(_, s, nir_lower_fragcolor, 1); + NIR_PASS(_, s, nir_lower_io, nir_var_shader_in | nir_var_shader_out | nir_var_uniform, + type_size_vec4, 0); + if (discard_zero && !lower_discard_to_zero(s)) { + fail(&c, "a discard as a source of 0 did not take"); + goto out; + } + if (blending) + lower_blend(s, blend); + /* (M43) an sRGB target: the colour encoded as it goes out, the tile's + * decoded as blending reads it (nir_lower_blend leaves both to us) */ + if (blend && blend->rt_srgb) + NIR_PASS(_, s, nir_shader_intrinsics_pass, lower_srgb_target, nir_metadata_control_flow, + NULL); + /* (M43) an intensity target keeps R in all four: blending later in the + * same render reads its alpha as the intensity, as GL has it (the + * background loads it R R R R too) */ + if (blend && blend->rt_intensity) + NIR_PASS(_, s, nir_shader_intrinsics_pass, lower_intensity_target, + nir_metadata_control_flow, NULL); + { + /* (rectangle textures: the state tracker scales their coordinates + * already -- caps.texrect off -- and leaves the dimension Rect) */ + /* (M44) textureGrad as textureLod, offsets as coordinates, sizes at + * level 0 shifted: all built on textureSize (texture_size()) */ + nir_lower_tex_options tex = { + .lower_txp = ~0u, .lower_1d = true, .lower_txd = true, .lower_txs_lod = true, + .lower_txf_offset = true, .lower_offset_filter = lower_every_offset, + }; + + /* the linear sampler reads B G R A: other orders swizzled back -- + * and a view's swizzle on what that gives (M43) */ + for (unsigned u = 0; blend && u < 8; u++) { + uint8_t base[4]; + + if (!((blend->tex_swap | blend->tex_x8 | blend->tex_swz) >> u & 1)) + continue; + base[0] = blend->tex_swap >> u & 1 ? 2 : 0; + base[1] = 1; + base[2] = blend->tex_swap >> u & 1 ? 0 : 2; + base[3] = blend->tex_x8 >> u & 1 ? PIPE_SWIZZLE_1 : 3; + tex.swizzle_result |= 1u << u; + for (unsigned c = 0; c < 4; c++) { + unsigned v = blend->tex_swz >> u & 1 ? blend->tex_swizzle[u][c] : c; + + tex.swizzles[u][c] = v <= PIPE_SWIZZLE_W ? base[v] : v; + } + } + if (blend) + tex.lower_srgb = blend->tex_srgb; + /* shadow samplers: the depth compared in the program (M37: iOS's + * m07 -- the reference clamped, `tex - ref >= 0`); one not compared + * by its sampler state (or before a variant says) passes */ + { + enum compare_func func[8]; + nir_lower_tex_shadow_swizzle swz[8]; + + for (unsigned u = 0; u < 8; u++) { + bool on = blend && (blend->tex_shadow >> u & 1); + + func[u] = on ? blend->shadow_func[u] : COMPARE_FUNC_ALWAYS; + swz[u] = on ? (nir_lower_tex_shadow_swizzle){ + blend->depth_swizzle[u][0], blend->depth_swizzle[u][1], + blend->depth_swizzle[u][2], blend->depth_swizzle[u][3] } : + (nir_lower_tex_shadow_swizzle){ + PIPE_SWIZZLE_X, PIPE_SWIZZLE_X, PIPE_SWIZZLE_X, PIPE_SWIZZLE_1 }; + } + NIR_PASS(_, s, nir_lower_tex_shadow, 8, func, swz, true); + } + NIR_PASS(_, s, nir_lower_tex, &tex); + } + /* the facing bit is set for triangles anticlockwise in the target, row + * 0 at the top -- gallium's sense (glcull, M19) */ + c.front_when_set = blend && blend->front_ccw; + NIR_PASS(_, s, nir_shader_intrinsics_pass, lower_front_face, nir_metadata_control_flow, NULL); + if (!translate(&c, s)) + goto out; + /* (an F16 program's output is written by now: M46, f16_out_at) */ + out_at = c.f16 ? c.f16_out_at : util_dynarray_num_elements(&c.code, uint64_t); + if (!c.f16) + output(&c); + if (c.failed) + goto out; + /* a pixel's registers, primary attributes and temporaries: 65 (an + * unrolled loop's) hung the GPU; 64 is what the temporaries alone may + * take */ + if (align(4 * c.ninputs + c.ncolours + c.nfetch, 4) + c.top > 64) { + fail(&c, "%u registers a pixel", align(4 * c.ninputs + c.ncolours + c.nfetch, 4) + c.top); + goto out; + } + c.fs->prog.f16 = c.f16; + c.fs->prog.in_f32 = c.f16 ? c.in_f32 : 0; + c.fs->smp_norm = c.f16 ? c.smp_norm : 0; + + c.fs->prog.ncode = util_dynarray_num_elements(&c.code, uint64_t); + c.fs->prog.code = MALLOC(c.fs->prog.ncode * sizeof(uint64_t)); + if (!c.fs->prog.code) { + fail(&c, "out of memory"); + goto out; + } + memcpy(c.fs->prog.code, util_dynarray_begin(&c.code), c.fs->prog.ncode * sizeof(uint64_t)); + /* A program that samples runs every instruction for the pixels around + * the triangle too (skipinv, bit 55, clear -- as iOS's dependent reads + * have it, corpus t01 and t07): the sampler takes its level of detail + * from the coordinates of the 2x2 block, and a neighbour that skipped + * the moves into them handed it garbage (gltex linear: point sampling + * along the diagonal seam). But not the writes of the output: those + * pixels' tiles would take them too -- blended twice along each shared + * edge, in 2x2 blocks (weston's panel, M16). */ + /* And a program that branches the same (iOS's c04_loop_break): the + * pixels around the triangle skipped the tests of a loop's condition and + * took its branches on a predicate left from before -- round the loop + * for ever, now and then (M20). */ + /* (and a program with derivatives: the pixels around the triangle in + * its 2x2 blocks are what DSX and DSY read, glflow -- M33) */ + /* (the PDS's lookups take theirs from the iterated coordinates: as + * iOS's t00, the program keeps skipinv) */ + if (c.smp || c.branches || c.derivatives) + for (unsigned i = 0; i < out_at; i++) + c.fs->prog.code[i] &= ~(1ull << 55); + c.fs->prog.ntemps = c.top; + /* SGX_LDR_PROBE=word,...: the program those words, WDF0, then r0 into + * o0 as it is (finding VLDST, M32) */ + if (getenv("SGX_LDR_PROBE")) { + const char *e = getenv("SGX_LDR_PROBE"); + unsigned n = 0; + + c.fs->prog.code = REALLOC(c.fs->prog.code, 0, 32 * sizeof(uint64_t)); + c.fs->prog.code[n++] = USSE_PHAS; + while (*e && n < 28) { + char *end; + + c.fs->prog.code[n++] = strtoull(e, &end, 16); + e = *end == ',' ? end + 1 : end; + } + c.fs->prog.code[n++] = USSE_WDF0; + c.fs->prog.code[n++] = usse_fmov(usse_reg(USSE_OUTPUT, 0), + usse_reg(USSE_TEMP, getenv("SGX_LDR_OUT") ? + atoi(getenv("SGX_LDR_OUT")) : 0)) | USSE_END; + c.fs->prog.ncode = n; + c.fs->prog.ntemps = MAX2(c.fs->prog.ntemps, 8); + mesa_logi("sgx: SGX_LDR_PROBE: %u words, samplers' state at sa%u", n, c.sampler_sa); + /* (M44) SGX_LDR_PROBE_BRANCHES=1: run them as a program whose pixels + * each go their own way (PHAS mode 1, M20) */ + if (getenv("SGX_LDR_PROBE_BRANCHES")) { + c.fs->prog.code[0] = USSE_PHAS_BRANCHES; + c.branches = c.divergent = true; + } + } + c.fs->prog.branches = c.branches && c.divergent; + c.fs->prog.ninputs = c.ninputs + c.ncolours; + c.fs->prog.ncolours = c.ncolours; + c.fs->prog.nvaryings = c.ncolours; + for (unsigned j = 0; j < c.ncolours; j++) { + c.fs->input_slot[c.ninputs + j] = c.colour_slot[j]; + c.fs->varying_slot[j] = c.colour_slot[j]; + c.fs->prog.iter_src[c.ninputs + j] = j; + } + for (unsigned i = 0; i < c.ninputs; i++) { + if (c.fs->input_slot[i] == VARYING_SLOT_POS) { + c.fs->prog.iter_src[i] = SGX_ITERATE_POSITION; + continue; + } + c.fs->varying_slot[c.fs->prog.nvaryings] = c.fs->input_slot[i]; + c.fs->prog.iter_src[i] = c.fs->prog.nvaryings++; + } + /* the lookups' varyings, those not iterated after the rest */ + for (unsigned k = 0; k < c.nfetch; k++) { + unsigned v = 0; + + /* (a shifted lookup's a varying of its own, M46) */ + while (v < c.fs->prog.nvaryings && + (c.fs->varying_slot[v] != c.fetch_slot[k] || + SGX_FIX_SHIFT_OF(c.fs->vary_fix[v]) != SGX_FIX_SHIFT_OF(c.fetch_fix[k]))) + v++; + if (v == SGX_FRAME_MAX_VARYINGS) { + fail(&c, "more than %u varyings", SGX_FRAME_MAX_VARYINGS); + goto out; + } + if (v == c.fs->prog.nvaryings) + c.fs->varying_slot[c.fs->prog.nvaryings++] = c.fetch_slot[k]; + c.fs->prog.fetch_src[k] = v; + c.fs->prog.fetch_sa[k] = c.sampler_sa + 4 * c.slot_of_unit[c.fetch[k]->texture_index]; + /* (M39) what the vertex side does to the varying, the PDS's kind */ + if (SGX_FIX_DIV(c.fetch_fix[k])) + c.fs->prog.fetch_proj |= 1u << k; + if (c.fetch_fix[k]) { + c.fs->vary_fix[v] = c.fetch_fix[k]; + c.fs->vary_unit[v] = c.fetch[k]->texture_index; + } + } + c.fs->prog.nfetch = c.nfetch; + c.fs->nuniforms = c.sa_uniforms; + c.fs->prog.nubuf = c.ubuf ? c.uwords : 0; + c.fs->prog.ubuf_sa = c.ubuf_sa; + c.fs->prog.ubo_mask = c.ubo_mask; + for (unsigned k = 0; k < SGX_FRAME_MAX_UBOS; k++) + c.fs->prog.ubo_sa[k] = c.ubo_mask >> k & 1 ? c.ubo_sa[k] : 0; + c.fs->nsamplers = c.nsamplers; + c.fs->sampler_sa = c.sampler_sa; + c.fs->prog.nsa = fs_sa_end(&c); + /* (M46) the constant pool after them */ + if (c.nkconst) { + c.fs->prog.nsa = c.kconst_sa + 2 * c.nkconst; + c.fs->kconst_sa = c.kconst_sa; + c.fs->nkconst = c.nkconst; + memcpy(c.fs->kconst, c.kconst, 2 * c.nkconst * sizeof(uint32_t)); + c.fs->nderived = c.nderived; + memcpy(c.fs->derived, c.derived, c.nderived * sizeof(c.derived[0])); + } + c.fs->blend_sa = c.blend_sa; + c.fs->scale_sa = c.scale_sa; + c.fs->size_sa = c.size_sa; + +out: + util_dynarray_fini(&c.code); + free(c.loc); + free(c.owned); + free(c.last_use); + free(c.def_at); + free(c.vs_out); + util_dynarray_fini(&c.loops); + util_dynarray_fini(&c.ispans); + free(c.vgroups); + free(c.group_of); + free(c.premade); + if (c.range) + _mesa_hash_table_destroy(c.range, NULL); + ralloc_free(s); + if (c.failed) { + sgx_fs_destroy(c.fs); + return NULL; + } + return c.fs; +} + +unsigned +sgx_vs_attr_count(const nir_shader *vs) +{ + unsigned n = 0; + + nir_foreach_shader_in_variable(var, vs) + n = MAX2(n, var->data.driver_location + glsl_count_attribute_slots(var->type, true)); + return MIN2(n, SGX_VS_MAX_ATTRIBS); +} + +static struct sgx_vs * +compile_vs(const nir_shader *vs, const unsigned *varying_slot, unsigned nvaryings, + const uint8_t *attr, const uint8_t *fix, char *why, unsigned why_size, + bool keep_order) +{ + struct comp c = { .keep_order = keep_order }; + unsigned out_at, nattr = sgx_vs_attr_count(vs); + nir_shader *s; + + c.why = why; + c.kill = -1; + c.logicop = -1; + c.why_size = why_size; + why[0] = 0; + if (nvaryings > SGX_FRAME_MAX_VARYINGS || !(c.vs = CALLOC_STRUCT(sgx_vs))) + return NULL; + for (unsigned i = 0; i < ARRAY_SIZE(c.slot_of_unit); i++) + c.slot_of_unit[i] = -1; + c.blend_sa = -1; + c.scale_sa = -1; + c.size_sa = -1; + c.varying_slot = varying_slot; + c.nvaryings = nvaryings; + memcpy(c.vs->varying_slot, varying_slot, nvaryings * sizeof(*varying_slot)); + c.vs->nvaryings = nvaryings; + if (fix) + memcpy(c.vs->vary_fix, fix, nvaryings); + c.vary_fix = c.vs->vary_fix; + /* (past what the shader declares: constants, never read) */ + for (unsigned a = 0; a < SGX_VS_MAX_ATTRIBS; a++) + c.vs->attr[a] = a < nattr ? attr[a] : SGX_ATTR(SGX_ATTR_CONST, 4); + memset(c.vs->attr_sa, 0xff, sizeof(c.vs->attr_sa)); + c.attr = c.vs->attr; + + s = nir_shader_clone(NULL, vs); + NIR_PASS(_, s, nir_lower_io, nir_var_shader_in | nir_var_shader_out | nir_var_uniform, + type_size_vec4, 0); + if (getenv("SGX_DEBUG_VS_NIR")) + nir_print_shader(s, stderr); + if (!translate(&c, s)) + goto out; + /* the draw's four words for the position, after the uniforms, then two + * for each varying it scales (M39) */ + c.nuniforms = align(c.nuniforms, 2); + c.vs->clip_sa = c.nuniforms; + c.nuniforms += 4; + c.vs->fix_sa = c.nuniforms; + for (unsigned k = 0; k < nvaryings; k++) + c.nuniforms += c.vary_fix[k] & SGX_FIX_SCALE ? 2 : 0; + if (c.nuniforms > 128) { + fail(&c, "uniforms past word 128"); + goto out; + } + /* SGX_VS_PAD=N (M46, a measurement): N moves more a vertex, into a + * temporary of their own -- what a vertex program's instruction costs */ + { + static int pad = -1; + + if (pad < 0) + pad = getenv("SGX_VS_PAD") ? atoi(getenv("SGX_VS_PAD")) : 0; + /* (M47) SGX_VS_PAD_KIND: the instruction -- mov (VMOV, one lane), + * movns (with nosched), mad (V32NMAD, one lane), mad2 (VMAD2, two), + * add4 (V32NMAD into i0, four), vdp (dp4 of i0), vmad (mad4 into + * i0) -- the last three with nosched */ + if (pad > 0) { + const char *k = getenv("SGX_VS_PAD_KIND") ? getenv("SGX_VS_PAD_KIND") : "mov"; + unsigned t = block(&c, 4, 2); + struct usse_reg r = treg(&c, t); + + for (int i = 0; i < pad && !c.failed; i++) { + uint64_t w; + + if (!strcmp(k, "mad")) + w = usse_fop(USSE_NMAD_ADD, r, r, r); + else if (!strcmp(k, "mad2")) + w = usse_fmad_ex(r, 3, r, 4, r, 4, r, 4); + else if (!strcmp(k, "add4")) + w = usse_fop_ex(USSE_NMAD_ADD, usse_ireg(0, 0), 0xf, r, USSE_SW(0, 1, 2, 3), + USSE_ZERO, USSE_SW2_X); + else if (!strcmp(k, "vdp")) + w = usse_vdp(r, 1, true, r, USSE_SW(0, 1, 2, 3), 0, USSE_SW2_XYZW); + else if (!strcmp(k, "vmad")) + w = usse_vmad(usse_ireg(0, 0), 0xf, 0, USSE_SW2_XYZW, r, USSE_SW2_XYZW, 0, + USSE_SW2_XYZW, false); + else + w = usse_fmov(r, r); + if (strcmp(k, "mov") && strcmp(k, "mad") && strcmp(k, "mad2")) + usse_nosched(&w); + emit(&c, w); + } + } + } + out_at = util_dynarray_num_elements(&c.code, uint64_t); + vertex_output(&c); + if (c.failed) + goto out; + /* branches: skipinv clear but on the vertex's output, as a pixel + * program's (M20, M22) */ + if (c.branches) + for (unsigned i = 0; i < out_at; i++) + *util_dynarray_element(&c.code, uint64_t, i) &= ~(1ull << 55); + + c.vs->ncode = util_dynarray_num_elements(&c.code, uint64_t); + c.vs->code = MALLOC(c.vs->ncode * sizeof(uint64_t)); + if (!c.vs->code) { + fail(&c, "out of memory"); + goto out; + } + memcpy(c.vs->code, util_dynarray_begin(&c.code), c.vs->ncode * sizeof(uint64_t)); + /* a vertex's registers, attributes and temporaries (pa): a pixel's + * bound (M20) */ + if (4 * MAX2(c.nattrs, 1) + c.top > 64) { + fail(&c, "%u registers a vertex", 4 * MAX2(c.nattrs, 1) + c.top); + goto out; + } + c.vs->ntemps = c.top; + c.vs->branches = c.branches; + c.vs->nattrs = MAX2(c.nattrs, 1); + c.vs->nuniforms = c.nuniforms; + c.vs->nubuf = c.ubuf ? c.uwords : 0; + c.vs->ubuf_sa = c.ubuf_sa; + c.vs->ubo_mask = c.ubo_mask; + for (unsigned k = 0; k < SGX_FRAME_MAX_UBOS; k++) + c.vs->ubo_sa[k] = c.ubo_mask >> k & 1 ? c.ubo_sa[k] : 0; + +out: + util_dynarray_fini(&c.code); + free(c.loc); + free(c.owned); + free(c.last_use); + free(c.def_at); + free(c.vs_out); + util_dynarray_fini(&c.loops); + util_dynarray_fini(&c.ispans); + free(c.vgroups); + free(c.group_of); + free(c.premade); + if (c.range) + _mesa_hash_table_destroy(c.range, NULL); + ralloc_free(s); + if (c.failed) { + sgx_vs_destroy(c.vs); + return NULL; + } + return c.vs; +} + +void +sgx_vs_destroy(struct sgx_vs *vs) +{ + if (!vs) + return; + FREE(vs->code); + FREE(vs); +} + +void +sgx_fs_destroy(struct sgx_fs *fs) +{ + if (!fs) + return; + FREE(fs->prog.code); + FREE(fs); +} + +/* Short of registers, the shader compiled again in NIR's own order: values + * made just before their use keep fewer alive as a rule, not always + * (dEQP's tmp_array.vec3_dynamic_write_dynamic_read_fragment came to 67 + * registers a pixel with them, 64 without -- M36) */ +static bool +short_of_registers(const char *why) +{ + return strstr(why, "registers a pixel") || strstr(why, "temporaries hold"); +} + +struct sgx_fs * +sgx_compile_fs(const nir_shader *fs, const struct sgx_blend_key *blend, char *why, + unsigned why_size) +{ + struct sgx_fs *f = compile_fs(fs, blend, why, why_size, false); + + if (!f && short_of_registers(why)) + f = compile_fs(fs, blend, why, why_size, true); + return f; +} + +struct sgx_vs * +sgx_compile_vs(const nir_shader *vs, const unsigned *varying_slot, unsigned nvaryings, + const uint8_t *attr, const uint8_t *fix, char *why, unsigned why_size) +{ + struct sgx_vs *v = compile_vs(vs, varying_slot, nvaryings, attr, fix, why, why_size, false); + + if (!v && short_of_registers(why)) + v = compile_vs(vs, varying_slot, nvaryings, attr, fix, why, why_size, true); + return v; +} diff --git a/src/gallium/drivers/sgx/sgx_compiler.h b/src/gallium/drivers/sgx/sgx_compiler.h new file mode 100644 index 00000000000..d763c87f87d --- /dev/null +++ b/src/gallium/drivers/sgx/sgx_compiler.h @@ -0,0 +1,243 @@ +/* + * Copyright 2026 Project Cascadia + * SPDX-License-Identifier: MIT + * + * The shader compiler, NIR to USSE (docs/research/p105-mesa.md, M13c). So + * far fragment shaders only, and of them the ones that are one block of + * float arithmetic once NIR has unrolled loops and turned ifs into + * selects: varyings, uniforms, constants, the ALU, comparisons, selects, + * 2D texture lookups. Discard, gl_FragCoord and real control flow are not + * there yet; + * a shader that needs them is not compiled, and the draw falls back to M13a + * (sgx_draw.c reads its colour). + */ +#ifndef SGX_COMPILER_H +#define SGX_COMPILER_H + +#include + +#include "sgx_frame.h" + +struct nir_shader; + +/* What a variant of a fragment shader is compiled for. GL's blending for + * render target 0, as the shader does it (M14): equations and factors + * (pipe_blend_func, pipe_blendfactor), the colour mask, or a logic op + * (M37). And the texture units sampled linear (sgx_resource_linear(), + * M16) from memory in R G B A order (red and blue swapped back), and with + * no alpha; those whose texels + * are sRGB, decoded after the lookup (GL 2.1's EXT_texture_sRGB: no gamma + * of the sampler's found, M35). All zero but colormask 0xf: nothing + * done. */ +struct sgx_blend_key { + uint8_t enable; + uint8_t rgb_func, rgb_src, rgb_dst; + uint8_t alpha_func, alpha_src, alpha_dst; + uint8_t colormask; + uint8_t tex_swap, tex_x8, tex_srgb; + uint8_t front_ccw; /* gallium's, for gl_FrontFacing (0 when not read) */ + uint8_t logicop; /* pipe_logicop + 1; 0: none (M37: iOS's are the program's) */ + /* (M37) the units whose texture is depth -- its texel F32, raw, as d, + * 0, 0, 1 through its view's swizzle (GL's depth texture modes) -- and + * of those the ones compared (shadow samplers: in the program, as iOS's + * m07; nir_lower_tex_shadow), each one's func */ + uint8_t tex_depth, tex_shadow; + uint8_t shadow_func[8]; + uint8_t depth_swizzle[8][4]; + /* (M43) the other units whose view swizzles the texel (EXT_texture_swizzle, + * GL 3.3): pipe_swizzle each, after the texture unit's own order */ + uint8_t tex_swz; + uint8_t tex_swizzle[8][4]; + /* (M43) the units whose copy is half floats (sgx_resource_copy_f16): + * sampled as F32, not as bytes; not by the PDS */ + uint8_t tex_f16; + /* (M43) what the target's tile holds (enum sgx_rt_kind: RGBA bytes, + * half floats, F32): the colour packed so, the tile read back so */ + uint8_t rt_kind; + uint8_t rt_srgb; /* (M43) the target's bytes sRGB: encoded, decoded to blend */ + uint8_t rt_intensity; /* (M43) an intensity target: the colour R R R R in the tile */ + /* (M46) the units whose lookup's clamp (sgx_texclamp) the draw found to + * do nothing: the lookup at the varying itself */ + uint8_t texclamp_free; +}; + +/* (M46) A lookup at coordinates clamped to a rectangle of its texture and + * moved -- PPSSPP's TClampST: clamp(v, u_texclamp.zw, u_texclamp.xy - + * u_texclamp.zw) + u_texclampoff, v a varying's x and y -- which takes the + * lookup off the PDS. Each of lo, hi and off is k + s[0] * word w[0] + s[1] + * * word w[1] of the uniforms (s 0: no word). A draw whose offset is 0 and + * whose v never leaves [lo, hi] -- or leaves it only where the sampler's + * clamp to the edge gives the same texel -- has the variant without it + * (sgx_blend_key.texclamp_free). */ +struct sgx_uexpr { + float k; + uint16_t w[2]; + int8_t s[2]; +}; +struct sgx_texclamp { + uint8_t unit; + uint8_t slot[2], comp[2]; /* each coordinate's varying: gl_varying_slot, component */ + struct sgx_uexpr lo[2], hi[2], off[2]; +}; +bool sgx_fs_texclamp(const struct nir_shader *fs, struct sgx_texclamp *tc); +float sgx_uexpr_eval(const struct sgx_uexpr *e, const float *u, unsigned nwords); +/* (M46) a vertex shader's varying component as a copy of an attribute's: + * the attribute (driver_location: the vertex element) and its component */ +bool sgx_vs_varying_attr(const struct nir_shader *vs, unsigned slot, unsigned comp, + unsigned *attr, unsigned *acomp); + +#define SGX_FS_MAX_SAMPLERS 8 + +/* (M39) what the vertex side does to a varying that only the PDS's + * lookups read, so that its x and y are what the texture unit takes: x + * and y times a rectangle texture's 1 / width, 1 / height + * (SGX_FIX_SCALE; the texture unit's in vary_unit[]), and the divisor of + * a projective lookup -- the program's z or w (SGX_FIX_DIV_Z, _W) -- + * into w, which the PDS's projective lookup divides by (glproj: not z; + * iOS's s08 has a vec3's z there, its vertex program putting it in w). */ +#define SGX_FIX_SCALE 0x10 +#define SGX_FIX_DIV_Z 0x02 +#define SGX_FIX_DIV_W 0x03 +#define SGX_FIX_DIV(f) ((f) & 3) +/* (M46) a lookup at a varying's y and z, or z and w -- where the linker + * packed the coordinates after a float (PPSSPP's fog factor), which the + * PDS cannot fetch: a varying of its own, components n and n + 1 of the + * other moved into its x and y by the vertex side */ +#define SGX_FIX_SHIFT(n) ((n) << 2) +#define SGX_FIX_SHIFT_OF(f) ((f) >> 2 & 3) +#define SGX_PROJ_DIV 3 /* the component the PDS divides x and y by */ + +/* A compiled fragment shader. Its secondary attributes (prog.nsa words) + * are constant buffer 0's words 0..nuniforms, then from sampler_sa four + * state words for each texture it samples, sampler_unit[i] the unit of the + * i-th, then (scale_sa) two words for each, 1 / its width and height, if a + * rectangle texture is sampled (M35), then (size_sa, M44) eight words for + * each if it asks a size or fetches a texel -- its base level's width, + * height (integers), its levels, 0, then 1 / width, 1 / height, 0.5 / + * width, 0.5 / height -- then (blend_sa, if the blending reads it) the + * blend colour. */ +#define SGX_FS_SIZE_WORDS 8 +#define SGX_FS_MAX_KCONST 16 + +/* (M46) A pair of the constant pool that the draw works out from the sa + * words before it (the uniforms, the pool's pairs before it): what the + * program would work out the same for every pixel -- an F32 sum, product, + * min or max of two words (each maybe negated), the second word 0; or the + * four words from a as four F16 (a uniform vec4 an F16 program reads) */ +enum sgx_derived_kind { + SGX_DERIVED_ADD, SGX_DERIVED_MUL, SGX_DERIVED_MIN, SGX_DERIVED_MAX, SGX_DERIVED_F16, +}; +struct sgx_fs_derived { + uint8_t kind, pair, a, b; + bool neg_a, neg_b; +}; +#define SGX_FS_MAX_DERIVED 8 + +struct sgx_fs { + struct sgx_pixel_program prog; + unsigned input_slot[SGX_FRAME_MAX_VARYINGS]; /* gl_varying_slot, input i */ + /* the varyings the vertex side hands over, in the layout's order + * (prog.nvaryings): the inputs' but gl_FragCoord, then those only the + * PDS's lookups read (M35) */ + unsigned varying_slot[SGX_FRAME_MAX_VARYINGS]; + unsigned nuniforms, nsamplers, sampler_sa; + unsigned sampler_unit[SGX_FS_MAX_SAMPLERS]; + int blend_sa; /* -1: no blend colour */ + bool blend_packed; /* (M46) it as one word of RGBA bytes, SOP2's constant */ + int scale_sa; /* -1, or each texture's 1 / width, 1 / height (rectangles) */ + int size_sa; /* -1, or each texture's size words (M44) */ + struct sgx_blend_key blend; /* what it was compiled for */ + bool sop2; /* (M46) blended (or masked) by one SOP2, as iOS does */ + /* (M46) its constants, nkconst pairs of sa words from kconst_sa (an F32 + * and 0, or four F16): the draw writes them with the uniforms */ + uint32_t kconst[2 * SGX_FS_MAX_KCONST]; + unsigned nkconst, kconst_sa; + /* (M46) the texture slots the program samples itself as F16: the draw + * sets their state word 3's bit 31 (0..1, as the PDS's F16 lookups) */ + uint8_t smp_norm; + /* (M46) the pool's pairs the draw works out, in order */ + struct sgx_fs_derived derived[SGX_FS_MAX_DERIVED]; + unsigned nderived; + /* (M39) each varying's SGX_FIX_*, in varying_slot[]'s order */ + uint8_t vary_fix[SGX_FRAME_MAX_VARYINGS]; + uint8_t vary_unit[SGX_FRAME_MAX_VARYINGS]; +}; + + +/* A compiled vertex shader (docs/research/p105-mesa.md, M18): attribute n + * (vertex element n) in pa4n.. as attr[n] says, uniforms (constant buffer + * 0's words) in sa0.., the position and then the varyings varying_slot[] + * -- the fragment shader's inputs, in its order -- out through o0.. to the + * tiler. */ +#define SGX_VS_MAX_ATTRIBS 16 + +/* How an attribute comes (M26), SGX_ATTR(kind, components): the vertex + * fetch puts its words in pa4n.. as they are in memory, and the program + * makes them four floats first, the components missing 0, 0, 1 */ +enum sgx_attr_kind { + SGX_ATTR_F32, /* n F32 words */ + SGX_ATTR_U8N, /* one word, n unsigned normalized bytes */ + SGX_ATTR_CONST, /* not fetched: four F32 words in sa, from attr_sa[n] */ +}; +#define SGX_ATTR(kind, n) ((kind) << 4 | (n)) +#define SGX_ATTR_KIND(a) ((a) >> 4) +#define SGX_ATTR_COMPS(a) ((a) & 0xf) + +/* the words the fetch reads for one */ +static inline unsigned +sgx_attr_words(uint8_t a) +{ + return SGX_ATTR_KIND(a) == SGX_ATTR_F32 ? SGX_ATTR_COMPS(a) : 1; +} + +struct sgx_vs { + uint64_t *code; + unsigned ncode, ntemps; + unsigned nattrs, nuniforms; + /* what it was compiled for: each attribute's SGX_ATTR (four words to + * compare) and, a constant's it reads, its sa words (0xff: none) */ + union { + uint8_t attr[SGX_VS_MAX_ATTRIBS]; + uint32_t attr_words[SGX_VS_MAX_ATTRIBS / 4]; + }; + uint8_t attr_sa[SGX_VS_MAX_ATTRIBS]; + /* the uniform words a, b for x and for y, x' = a x + b w: the TA clips + * where the draw wants (sgx_draw.c) */ + unsigned clip_sa; + /* uniform words in memory after the nuniforms of sa (M32), their + * address less 4 in sa word ubuf_sa -- as a pixel program's */ + unsigned nubuf, ubuf_sa; + /* (M43) its uniform buffers, as a pixel program's (ubo_mask, ubo_sa) */ + uint16_t ubo_mask; + uint8_t ubo_sa[SGX_FRAME_MAX_UBOS]; + unsigned varying_slot[SGX_FRAME_MAX_VARYINGS]; + unsigned nvaryings; + /* (M39) the fragment shader's SGX_FIX_* for each varying, and from sa + * word fix_sa two words for each one SGX_FIX_SCALE, the draw's */ + uint8_t vary_fix[SGX_FRAME_MAX_VARYINGS]; + unsigned fix_sa; + bool branches; /* the code branches (M22) */ + uint32_t code_va; /* where the frame put it */ +}; + +/* the attributes (vertex elements) a vertex shader reads, all told */ +unsigned sgx_vs_attr_count(const struct nir_shader *vs); +/* attr: an SGX_ATTR for each of the sgx_vs_attr_count() attributes; fix: + * each varying's SGX_FIX_* (sgx_fs.vary_fix), NULL none */ +struct sgx_vs *sgx_compile_vs(const struct nir_shader *vs, const unsigned *varying_slot, + unsigned nvaryings, const uint8_t *attr, const uint8_t *fix, + char *why, unsigned why_size); +void sgx_vs_destroy(struct sgx_vs *vs); + +/* fs is not changed; blend NULL for none. NULL, and why in why[], when + * it cannot be compiled (yet). */ +/* every pixel program that branches runs its pixels each on its own (PHAS + * mode 1), never together: the A6's (sgx_screen.c; SGX_PIXELS_TOGETHER=1 + * on it, SGX_PIXELS_APART=1 on the A5, for a test) */ +extern bool sgx_compiler_pixels_apart; + +struct sgx_fs *sgx_compile_fs(const struct nir_shader *fs, const struct sgx_blend_key *blend, + char *why, unsigned why_size); +void sgx_fs_destroy(struct sgx_fs *fs); + +#endif diff --git a/src/gallium/drivers/sgx/sgx_context.c b/src/gallium/drivers/sgx/sgx_context.c new file mode 100644 index 00000000000..d463103ad42 --- /dev/null +++ b/src/gallium/drivers/sgx/sgx_context.c @@ -0,0 +1,1327 @@ +/* + * Copyright 2026 Project Cascadia + * SPDX-License-Identifier: MIT + * + * The context. Draws go through sgx_draw.c (M13a: vertex shaders on the + * CPU in the draw module, triangles on the GPU through the template frame), + * which is handed the state it uses; the rest is kept for later. A clear + * of a whole render target the template frame can render into is a render + * on the GPU; every other clear, copy and blit is done by the CPU through + * the buffers' mappings, which wait for the renders using them. + */ +#include "sgx_context.h" + +#include +#include +#include + +#include "compiler/nir/nir.h" +#include "draw/draw_context.h" +#include "nir/tgsi_to_nir.h" +#include "util/u_blitter.h" +#include "util/format/u_format.h" +#include "util/log.h" +#include "util/os_time.h" +#include "util/ralloc.h" +#include "util/u_debug.h" +#include "util/u_framebuffer.h" +#include "util/u_helpers.h" +#include "util/u_inlines.h" +#include "util/u_memory.h" +#include "util/u_surface.h" +#include "util/u_upload_mgr.h" + +#include "sgx_compiler.h" +#include "sgx_device.h" +#include "sgx_draw.h" +#include "sgx_frame.h" +#include "sgx_resource.h" +#include "sgx_screen.h" + +/* ---- fences ------------------------------------------------------------- */ + +static void +sgx_fence_reference_hook(struct pipe_screen *pscreen, struct pipe_fence_handle **ptr, + struct pipe_fence_handle *fence) +{ + sgx_fence_reference((struct sgx_fence **)ptr, (struct sgx_fence *)fence); +} + +static bool +sgx_fence_finish(struct pipe_screen *pscreen, struct pipe_context *pctx, + struct pipe_fence_handle *fence, uint64_t timeout) +{ + return sgx_fence_wait((struct sgx_fence *)fence, timeout); +} + +/* native fence fds (EGL_ANDROID_native_fence_sync): sync files of the + * syncobjs -- what lets a KMS client (SDL) commit a flip without waiting + * for the render, the kernel waiting for it instead (M25) */ +static int +sgx_fence_get_fd(struct pipe_screen *pscreen, struct pipe_fence_handle *fence) +{ + return sgx_fence_export((struct sgx_fence *)fence); +} + +static void +sgx_create_fence_fd(struct pipe_context *pctx, struct pipe_fence_handle **fence, int fd, + enum pipe_fd_type type) +{ + *fence = type == PIPE_FD_TYPE_NATIVE_SYNC ? + (struct pipe_fence_handle *)sgx_fence_import(&sgx_screen(pctx->screen)->dev, fd) : + NULL; +} + +/* the next submit waits for it on the GPU (a copy of its syncobj's fence: + * the submit lets go of it) */ +static void +sgx_fence_server_sync(struct pipe_context *pctx, struct pipe_fence_handle *fence, uint64_t value) +{ + struct sgx_device *dev = &sgx_screen(pctx->screen)->dev; + struct sgx_fence *f = (struct sgx_fence *)fence; + struct sgx_fence *copy = NULL; + int fd; + + sgx_trace_mark("server sync"); + sgx_batch_flush(sgx_context(pctx)); + /* (a binary syncobj's fence copied through a sync file) */ + if (dev->nwait_syncs < ARRAY_SIZE(dev->wait_syncs) && (fd = sgx_fence_export(f)) >= 0) { + copy = sgx_fence_import(dev, fd); + close(fd); + } + if (!copy) { + sgx_fence_wait(f, OS_TIMEOUT_INFINITE); + return; + } + /* the syncobj is the submit's to destroy */ + dev->wait_syncs[dev->nwait_syncs++] = copy->syncobj; + copy->syncobj = 0; + FREE(copy); +} + +void +sgx_context_screen_init(struct sgx_screen *screen) +{ + screen->base.fence_reference = sgx_fence_reference_hook; + screen->base.fence_finish = sgx_fence_finish; + screen->base.fence_get_fd = sgx_fence_get_fd; +} + +/* Renders are submitted as they are made, so a flush only hands out the + * last one's fence. */ +static void +sgx_flush(struct pipe_context *pctx, struct pipe_fence_handle **fence, unsigned flags) +{ + struct sgx_context *ctx = sgx_context(pctx); + struct sgx_fence *f = NULL; + + sgx_trace_mark(flags & PIPE_FLUSH_END_OF_FRAME ? "flush, end of frame" : "flush"); + sgx_batch_flush(ctx); + /* (SGX_DEBUG=fps,flushes: every flush a frame -- the X server's glamor, + * which never swaps) */ + if (ctx->debug_fps && ((flags & PIPE_FLUSH_END_OF_FRAME) || ctx->debug_flushes)) { + struct timespec ts; + int64_t now = os_time_get_nano(), cpu; + + clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &ts); + cpu = ts.tv_sec * 1000000000ll + ts.tv_nsec; + + ctx->stat_swap = now; + ctx->stat_swap_cpu = cpu; + if (!ctx->stat_t0) { + ctx->stat_t0 = now; + ctx->stat_cpu0 = cpu; + } else if (++ctx->stat_frames, now - ctx->stat_t0 >= 2000000000ll) { + double s = (now - ctx->stat_t0) / 1e9; + + mesa_logi("sgx: %.1f fps at %ux%u (viewport %.0fx%.0f), %.1f renders and %.1f draws a frame, %.0f%% CPU, " + "%.0f%% waiting for the GPU", ctx->stat_frames / s, ctx->fb.width, ctx->fb.height, + fabsf(ctx->viewport.scale[0]) * 2, fabsf(ctx->viewport.scale[1]) * 2, + (double)ctx->stat_renders / ctx->stat_frames, + (double)ctx->stat_draws / ctx->stat_frames, + 100.0 * (cpu - ctx->stat_cpu0) / (now - ctx->stat_t0), + 100.0 * sgx_fence_waited / (now - ctx->stat_t0)); + sgx_fence_waited = 0; + mesa_logi("sgx: a frame's buffers made %.1f, mapped %.1f, waited for %.1f; submits %.1f " + "(%.2f ms in the kernel, %.0f buffers each)", + (double)sgx_ioctls[SGX_IOCTL_CREATE] / ctx->stat_frames, + (double)sgx_ioctls[SGX_IOCTL_MMAP] / ctx->stat_frames, + (double)sgx_ioctls[SGX_IOCTL_WAIT] / ctx->stat_frames, + (double)sgx_ioctls[SGX_IOCTL_SUBMIT] / ctx->stat_frames, + sgx_submit_ns / 1e6 / ctx->stat_frames, + sgx_ioctls[SGX_IOCTL_SUBMIT] ? + (double)sgx_submit_handles / sgx_ioctls[SGX_IOCTL_SUBMIT] : 0.0); + sgx_submit_ns = 0; + sgx_submit_handles = 0; + memset(sgx_ioctls, 0, sizeof(sgx_ioctls)); + mesa_logi("sgx: a frame's draws: %.1f merged into the last, %.1f rendered with the " + "last one's state", (double)sgx_stat_merged / ctx->stat_frames, + (double)sgx_stat_same / ctx->stat_frames); + sgx_stat_same = sgx_stat_verts = sgx_stat_tex_changes = sgx_stat_merged = 0; + mesa_logi("sgx: a frame's uploads: %.0f KB straight into the GPU copy (%.1f ms), " + "%.0f KB into the CPU copy, %.0f KB copied on, %.0f KB read back; " + "%.0f KB mapped as the GPU copy (%.0f KB a fresh one)", + sgx_stat_up[SGX_UP_DIRECT] / 1024.0 / ctx->stat_frames, + sgx_stat_up_ns / 1e6 / ctx->stat_frames, + sgx_stat_up[SGX_UP_CPU] / 1024.0 / ctx->stat_frames, + sgx_stat_up[SGX_UP_ON] / 1024.0 / ctx->stat_frames, + sgx_stat_up[SGX_UP_BACK] / 1024.0 / ctx->stat_frames, + sgx_stat_up[SGX_UP_MAPPED] / 1024.0 / ctx->stat_frames, + sgx_stat_up[SGX_UP_RENAMED] / 1024.0 / ctx->stat_frames); + memset(sgx_stat_up, 0, sizeof(sgx_stat_up)); + sgx_stat_up_ns = 0; + if (ctx->debug_sync) + mesa_logi("sgx: %.1f ms a render on the GPU", ctx->stat_gpu / 1e6 / ctx->stat_renders); + ctx->stat_gpu = 0; + mesa_logi("sgx: %.1f ms a frame between its end and the next one's first draw " + "(%.1f ms of it CPU)", ctx->stat_between / 1e6 / ctx->stat_frames, + ctx->stat_between_cpu / 1e6 / ctx->stat_frames); + ctx->stat_between = ctx->stat_between_cpu = 0; + if (ctx->stat_clamp_free || ctx->stat_clamp_kept) + mesa_logi("sgx: a frame's clamped lookups: %.1f draws without the clamp, %.1f with " + "it (%.3f ms telling)", (double)ctx->stat_clamp_free / ctx->stat_frames, + (double)ctx->stat_clamp_kept / ctx->stat_frames, + ctx->stat_clamp_ns / 1e6 / ctx->stat_frames); + ctx->stat_clamp_free = ctx->stat_clamp_kept = 0; + ctx->stat_clamp_ns = 0; + sgx_batch_why(ctx); + ctx->stat_frames = ctx->stat_renders = ctx->stat_draws = 0; + ctx->stat_t0 = now; + ctx->stat_cpu0 = cpu; + } + } + if (!fence) + return; + if (ctx->last) + sgx_fence_reference(&f, ctx->last); + else + f = sgx_fence_create(&sgx_screen(pctx->screen)->dev, true); + sgx_fence_reference((struct sgx_fence **)fence, NULL); + *fence = (struct pipe_fence_handle *)f; +} + +/* ---- occlusion queries (M37) --------------------------------------------- + * + * iOS's m29: ISP state A bit 14 makes the ISP count the samples a draw + * passes, into the visibility buffer the 3D block's first two words name + * (the kext's from GL's payload words 42 and 43), a word for each core. No + * bit picks one of several counts (bits 15..23 tried: the object's type, + * the depth test), so a render goes at each begin and end, and each render + * a query was active in has a buffer of its own: the query's result is + * theirs added up. */ +static void +query_fold(struct sgx_query *q, unsigned i) +{ + struct sgx_bo *bo = q->bo[i]; + const uint32_t *w = (const uint32_t *)bo->map; + + sgx_bo_wait(bo, -1); + /* a third core's count stays 0 on the A5's two (the buffer is zeroed) */ + q->samples += w[0] + w[SGX_VIS_CORE_STRIDE / 4] + w[2 * SGX_VIS_CORE_STRIDE / 4]; + sgx_bo_destroy(bo); +} + +void +sgx_query_add(struct sgx_query *q, struct sgx_bo *bo) +{ + /* (a query over many renders: the oldest read now) */ + if (q->nbo == SGX_QUERY_BUFS) { + query_fold(q, 0); + memmove(q->bo, q->bo + 1, --q->nbo * sizeof(q->bo[0])); + } + q->bo[q->nbo++] = bo; +} + +static void +query_release(struct sgx_query *q) +{ + for (unsigned i = 0; i < q->nbo; i++) + sgx_bo_destroy(q->bo[i]); + q->nbo = 0; + sgx_fence_reference(&q->last, NULL); +} + +static struct pipe_query * +sgx_create_query(struct pipe_context *pctx, unsigned type, unsigned index) +{ + struct sgx_query *q; + + if (type != PIPE_QUERY_OCCLUSION_COUNTER && type != PIPE_QUERY_OCCLUSION_PREDICATE && + type != PIPE_QUERY_OCCLUSION_PREDICATE_CONSERVATIVE && type != PIPE_QUERY_TIMESTAMP && + type != PIPE_QUERY_TIME_ELAPSED) + return NULL; + if (!(q = CALLOC_STRUCT(sgx_query))) + return NULL; + q->type = type; + return (struct pipe_query *)q; +} + +static void +sgx_destroy_query(struct pipe_context *pctx, struct pipe_query *pq) +{ + struct sgx_context *ctx = sgx_context(pctx); + struct sgx_query *q = (struct sgx_query *)pq; + + if (ctx->query == q) { + sgx_batch_flush(ctx); + ctx->query = NULL; + } + query_release(q); + sgx_fence_reference(&q->begin_fence, NULL); + FREE(q); +} + +static bool +timer_query(const struct sgx_query *q) +{ + return q->type == PIPE_QUERY_TIMESTAMP || q->type == PIPE_QUERY_TIME_ELAPSED; +} + +/* the GPU's time at a point of the stream: when the render before it was + * done, or when the point was reached, if later (an idle GPU) */ +static uint64_t +gpu_time(struct sgx_fence *f, uint64_t cpu) +{ + return MAX2(f ? sgx_fence_signal_time(f) : 0, cpu); +} + +static bool +sgx_begin_query(struct pipe_context *pctx, struct pipe_query *pq) +{ + struct sgx_context *ctx = sgx_context(pctx); + struct sgx_query *q = (struct sgx_query *)pq; + + sgx_batch_flush(ctx); + if (timer_query(q)) { + sgx_fence_reference(&q->begin_fence, ctx->last); + q->begin_cpu = os_time_get_nano(); + return true; + } + query_release(q); + q->samples = 0; + ctx->query = q; + return true; +} + +static bool +sgx_end_query(struct pipe_context *pctx, struct pipe_query *pq) +{ + struct sgx_context *ctx = sgx_context(pctx); + + sgx_batch_flush(ctx); + if (ctx->query == (struct sgx_query *)pq) + ctx->query = NULL; + sgx_fence_reference(&((struct sgx_query *)pq)->last, ctx->last); + ((struct sgx_query *)pq)->end_cpu = os_time_get_nano(); + return true; +} + +static bool +sgx_get_query_result(struct pipe_context *pctx, struct pipe_query *pq, bool wait, + union pipe_query_result *result) +{ + struct sgx_query *q = (struct sgx_query *)pq; + + if (q->last && !sgx_fence_wait(q->last, wait ? OS_TIMEOUT_INFINITE : 0)) + return false; + if (timer_query(q)) { + uint64_t end = gpu_time(q->last, q->end_cpu); + + if (q->type == PIPE_QUERY_TIMESTAMP) + result->u64 = end; + else + result->u64 = end - MIN2(end, gpu_time(q->begin_fence, q->begin_cpu)); + return true; + } + for (unsigned i = 0; i < q->nbo; i++) + if (!wait && !sgx_bo_idle(q->bo[i])) + return false; + for (unsigned i = 0; i < q->nbo; i++) + query_fold(q, i); + q->nbo = 0; + if (q->type == PIPE_QUERY_OCCLUSION_COUNTER) + result->u64 = q->samples; + else + result->b = q->samples != 0; + return true; +} + +static void +sgx_set_active_query_state(struct pipe_context *pctx, bool enable) +{ + sgx_context(pctx)->queries_off = !enable; +} + +/* ---- conditional rendering (M43: NV_conditional_render) ----------------- */ + +static void +sgx_render_condition(struct pipe_context *pctx, struct pipe_query *query, bool condition, + enum pipe_render_cond_flag mode) +{ + struct sgx_context *ctx = sgx_context(pctx); + + ctx->cond_query = query; + ctx->cond_condition = condition; + ctx->cond_mode = mode; +} + +/* Rendering goes ahead when the query's result (samples passed, or any) + * differs from the condition -- gallium's rule; a result not there yet, a + * mode that does not wait: ahead too, as GL allows */ +bool +sgx_render_condition_ok(struct sgx_context *ctx) +{ + union pipe_query_result r; + bool wait, value; + + if (!ctx->cond_query) + return true; + wait = ctx->cond_mode == PIPE_RENDER_COND_WAIT || + ctx->cond_mode == PIPE_RENDER_COND_BY_REGION_WAIT; + if (!sgx_get_query_result(&ctx->base, ctx->cond_query, wait, &r)) + return true; + value = ((struct sgx_query *)ctx->cond_query)->type == PIPE_QUERY_OCCLUSION_COUNTER ? + r.u64 != 0 : r.b; + return value != ctx->cond_condition; +} + +/* ---- clears ------------------------------------------------------------- */ + +/* The whole of a render target, on the GPU; false if the frame cannot */ +static bool +sgx_clear_gpu(struct sgx_context *ctx, struct pipe_surface *surf, + const union pipe_color_union *color) +{ + struct sgx_screen *screen = sgx_screen(ctx->base.screen); + struct sgx_resource *rt = sgx_resource(surf->texture); + struct sgx_fence *done; + int ret; + + const struct sgx_frame_target t = { rt, 0, 0 }; + + /* (the frame's own clear packs RGBA8: half floats' targets clear with + * a quad, M43) */ + if (!screen->frame || surf->level || surf->first_layer || + sgx_frame_rt_kind(surf->format) != SGX_RT_UNORM8 || util_format_is_srgb(surf->format) || + !sgx_frame_can_render(screen->frame, &t)) + return false; + if (!(done = sgx_fence_create(&screen->dev, false))) + return false; + simple_mtx_lock(&screen->frame_lock); + ret = sgx_frame_clear(screen->frame, rt, color->f, done); + simple_mtx_unlock(&screen->frame_lock); + if (!ret) { + sgx_fence_reference(&ctx->last, done); + rt->seq++; + rt->gpu_written = true; + } + sgx_fence_reference(&done, NULL); + return !ret; +} + +static void +sgx_clear(struct pipe_context *pctx, unsigned buffers, uint32_t color_clear_mask, + uint8_t stencil_clear_mask, const struct pipe_scissor_state *scissor, + const union pipe_color_union *color, double depth, unsigned stencil) +{ + struct sgx_context *ctx = sgx_context(pctx); + struct pipe_resource *zs = ctx->fb.zsbuf.texture; + unsigned x = scissor ? scissor->minx : 0, y = scissor ? scissor->miny : 0; + unsigned w = scissor ? scissor->maxx - scissor->minx : ctx->fb.width; + unsigned h = scissor ? scissor->maxy - scissor->miny : ctx->fb.height; + bool cd = (buffers & PIPE_CLEAR_DEPTH) && zs; + bool cs = (buffers & PIPE_CLEAR_STENCIL) && zs && + util_format_has_stencil(util_format_description(zs->format)); + /* (a framebuffer smaller than its depth buffer, M43: only the area they + * share is cleared -- a quad, not the render's start for all of it) */ + bool zs_whole = zs && ctx->fb.width >= u_minify(zs->width0, ctx->fb.zsbuf.level) && + ctx->fb.height >= u_minify(zs->height0, ctx->fb.zsbuf.level); + + /* (M43) under a render condition that says no: nothing */ + if (!sgx_render_condition_ok(ctx)) + return; + /* depth and stencil first (the colour's quad would end a render's + * start): at a render's start, all of the target, the depth the render + * starts at and its stencil 0 for free; else a quad in the render (M24) */ + if ((cd || cs) && !ctx->batch.ndraws && !scissor && zs_whole) { + if (cd) { + ctx->batch.depth_clear = depth; + ctx->batch.zs_cleared = true; + } + if (cs && (stencil & stencil_clear_mask & 0xff)) + sgx_zs_clear(ctx, false, 0, true, stencil, stencil_clear_mask, NULL); + } else if (cd || cs) { + sgx_zs_clear(ctx, cd, depth, cs, stencil, stencil_clear_mask, scissor); + } + for (unsigned i = 0; i < ctx->fb.nr_cbufs; i++) { + struct pipe_surface *surf = &ctx->fb.cbufs[i]; + + if (!(buffers & (PIPE_CLEAR_COLOR0 << i)) || !surf->texture) + continue; + /* four channel bits per draw buffer: all of them, a quad in the + * render (M25) */ + if (i == 0 && ((color_clear_mask >> (4 * i)) & 0xf) == 0xf && + sgx_colour_clear(ctx, color, scissor)) + continue; + /* else the render ends (what was drawn comes first) */ + sgx_batch_flush(ctx); + if (!scissor && ((color_clear_mask >> (4 * i)) & 0xf) == 0xf && + ctx->fb.width >= u_minify(surf->texture->width0, surf->level) && + ctx->fb.height >= u_minify(surf->texture->height0, surf->level) && + sgx_clear_gpu(ctx, surf, color)) + continue; + util_clear_render_target(pctx, surf, color, x, y, w, h); + } +} + +static void +sgx_clear_render_target(struct pipe_context *pctx, struct pipe_surface *dst, + const union pipe_color_union *color, unsigned x, unsigned y, + unsigned w, unsigned h, bool render_condition_enabled) +{ + if (render_condition_enabled && !sgx_render_condition_ok(sgx_context(pctx))) + return; + sgx_batch_flush(sgx_context(pctx)); + if (!x && !y && w == dst->texture->width0 && h == dst->texture->height0 && + sgx_clear_gpu(sgx_context(pctx), dst, color)) + return; + util_clear_render_target(pctx, dst, color, x, y, w, h); +} + +static void +sgx_clear_depth_stencil(struct pipe_context *pctx, struct pipe_surface *dst, + unsigned flags, double depth, unsigned stencil, unsigned x, + unsigned y, unsigned w, unsigned h, bool render_condition_enabled) +{ + if (render_condition_enabled && !sgx_render_condition_ok(sgx_context(pctx))) + return; + sgx_batch_flush(sgx_context(pctx)); + util_clear_depth_stencil(pctx, dst, flags, depth, stencil, x, y, w, h); +} + +/* ---- copies and blits, by the CPU --------------------------------------- */ + +/* A blit the copy cannot do -- another format, a scale, a flip -- by the + * CPU, a texel at a time through util_format's floats (glCopyTexImage's + * from a B8G8R8A8 target into an RGB texture, say: M28). As + * glBlitFramebuffer wants it (M43): each destination pixel's centre taken + * back into the source, nearest or between the four texels around it + * (clamped to the source's edges), none written whose centre falls outside + * the source or the scissor; depth and stencil nearest; blended with the + * source's alpha when asked. Colour, or depth and stencil, at a time. */ +static bool +cpu_blit(struct pipe_context *pctx, const struct pipe_blit_info *info) +{ + const struct pipe_box *sb = &info->src.box, *db = &info->dst.box; + struct pipe_resource *sres = info->src.resource, *dres = info->dst.resource; + bool zs = info->mask & PIPE_MASK_ZS; + bool linear = !zs && info->filter == PIPE_TEX_FILTER_LINEAR; + int sw = u_minify(sres->width0, info->src.level), sh = u_minify(sres->height0, info->src.level); + int dw = u_minify(dres->width0, info->dst.level), dh = u_minify(dres->height0, info->dst.level); + int x0 = MAX2(MIN2(db->x, db->x + db->width), 0), x1 = MIN2(MAX2(db->x, db->x + db->width), dw); + int y0 = MAX2(MIN2(db->y, db->y + db->height), 0), y1 = MIN2(MAX2(db->y, db->y + db->height), dh); + struct pipe_transfer *st, *dt; + struct pipe_box sbox, dbox; + const uint8_t *src; + uint8_t *dst; + float *in0, *in1, *out; + uint8_t *s8, *d8; + bool ok; + + if (!info->mask || (zs && (info->mask & PIPE_MASK_RGBA)) || + (zs && (!util_format_is_depth_or_stencil(info->src.format) || + !util_format_is_depth_or_stencil(info->dst.format))) || + (!zs && (util_format_is_depth_or_stencil(info->src.format) || + util_format_is_depth_or_stencil(info->dst.format)))) + return false; + if (util_format_is_compressed(info->dst.format) || util_format_is_compressed(info->src.format) || + sb->depth != 1 || db->depth != 1 || !sb->width || !sb->height || !db->width || + !db->height) + return false; + if (info->scissor_enable) { + x0 = MAX2(x0, (int)info->scissor.minx); + x1 = MIN2(x1, (int)info->scissor.maxx); + y0 = MAX2(y0, (int)info->scissor.miny); + y1 = MIN2(y1, (int)info->scissor.maxy); + } + if (x0 >= x1 || y0 >= y1) + return true; + + /* the source's whole level (a box may reach past it), the destination's + * pixels to write, read too (what is not written stays) */ + u_box_2d_zslice(0, 0, sb->z, sw, sh, &sbox); + u_box_2d_zslice(x0, y0, db->z, x1 - x0, y1 - y0, &dbox); + src = pctx->texture_map(pctx, sres, info->src.level, PIPE_MAP_READ, &sbox, &st); + if (!src) + return false; + dst = pctx->texture_map(pctx, dres, info->dst.level, PIPE_MAP_READ_WRITE, &dbox, &dt); + if (!dst) { + pctx->texture_unmap(pctx, st); + return false; + } + in0 = MALLOC(4 * sw * sizeof(float)); + in1 = MALLOC(4 * sw * sizeof(float)); + out = MALLOC(4 * (x1 - x0) * sizeof(float)); + s8 = MALLOC(sw); + d8 = MALLOC(x1 - x0); + ok = in0 && in1 && out && s8 && d8; + for (int y = y0; ok && y < y1; y++) { + /* the destination row's centre in the source, and its rows */ + float fy = sb->y + (y + 0.5f - db->y) * sb->height / (float)db->height; + uint8_t *drow = dst + (y - y0) * dt->stride; + int r0, r1; + float wy = 0; + + if (fy < 0 || fy >= sh) + continue; + if (linear) { + r0 = (int)floorf(fy - 0.5f); + wy = fy - 0.5f - r0; + r1 = CLAMP(r0 + 1, 0, sh - 1); + r0 = CLAMP(r0, 0, sh - 1); + } else { + r0 = r1 = (int)fy; + } + if (zs) { + if (info->mask & PIPE_MASK_Z) { + util_format_unpack_z_float(info->src.format, in0, src + r0 * st->stride, sw); + util_format_unpack_z_float(info->dst.format, out, drow, x1 - x0); + } + if (info->mask & PIPE_MASK_S) { + util_format_unpack_s_8uint(info->src.format, s8, src + r0 * st->stride, sw); + util_format_unpack_s_8uint(info->dst.format, d8, drow, x1 - x0); + } + } else { + util_format_unpack_rgba(info->src.format, in0, src + r0 * st->stride, sw); + if (linear) + util_format_unpack_rgba(info->src.format, in1, src + r1 * st->stride, sw); + util_format_unpack_rgba(info->dst.format, out, drow, x1 - x0); + } + for (int x = x0; x < x1; x++) { + float fx = sb->x + (x + 0.5f - db->x) * sb->width / (float)db->width; + float *o = out + 4 * (x - x0), texel[4]; + int c0, c1; + + if (fx < 0 || fx >= sw) + continue; + if (zs) { + c0 = (int)fx; + if (info->mask & PIPE_MASK_Z) + out[x - x0] = in0[c0]; + if (info->mask & PIPE_MASK_S) + d8[x - x0] = s8[c0]; + continue; + } + if (linear) { + float wx; + + c0 = (int)floorf(fx - 0.5f); + wx = fx - 0.5f - c0; + c1 = CLAMP(c0 + 1, 0, sw - 1); + c0 = CLAMP(c0, 0, sw - 1); + for (unsigned c = 0; c < 4; c++) { + float t = in0[4 * c0 + c] + (in0[4 * c1 + c] - in0[4 * c0 + c]) * wx; + float b = in1[4 * c0 + c] + (in1[4 * c1 + c] - in1[4 * c0 + c]) * wx; + + texel[c] = t + (b - t) * wy; + } + } else { + memcpy(texel, in0 + 4 * (int)fx, sizeof(texel)); + } + for (unsigned c = 0; c < 4; c++) { + if (!(info->mask & (PIPE_MASK_R << c))) + continue; + o[c] = info->alpha_blend ? texel[c] * texel[3] + o[c] * (1 - texel[3]) : texel[c]; + } + } + if (zs) { + if ((info->mask & PIPE_MASK_Z) && + util_format_has_depth(util_format_description(info->dst.format))) + util_format_pack_z_float(info->dst.format, drow, out, x1 - x0); + if ((info->mask & PIPE_MASK_S) && + util_format_has_stencil(util_format_description(info->dst.format))) + util_format_pack_s_8uint(info->dst.format, drow, d8, x1 - x0); + } else { + util_format_pack_rgba(info->dst.format, drow, out, x1 - x0); + } + } + FREE(in0); + FREE(in1); + FREE(out); + FREE(s8); + FREE(d8); + pctx->texture_unmap(pctx, dt); + pctx->texture_unmap(pctx, st); + return ok; +} + +/* ---- copies and blits, by the GPU (M46) ---------------------------------- */ + +/* What u_blitter binds of its own, kept to be bound again after */ +static void +blitter_save(struct sgx_context *ctx) +{ + struct blitter_context *b = ctx->blitter; + unsigned nviews = 0, nsamplers = 0; + + for (unsigned i = 0; i < ARRAY_SIZE(ctx->fs_views) && i < PIPE_MAX_SAMPLERS; i++) + if (ctx->fs_views[i]) + nviews = i + 1; + for (unsigned i = 0; i < PIPE_MAX_SAMPLERS; i++) + if (ctx->fs_samplers[i]) + nsamplers = i + 1; + util_blitter_save_vertex_buffers(b, ctx->vb, util_last_bit(ctx->vb_mask)); + util_blitter_save_vertex_elements(b, (void *)ctx->velems); + util_blitter_save_vertex_shader(b, ctx->vs); + util_blitter_save_fragment_shader(b, ctx->fs); + util_blitter_save_rasterizer(b, (void *)ctx->rast); + util_blitter_save_blend(b, (void *)ctx->blend); + util_blitter_save_depth_stencil_alpha(b, (void *)ctx->dsa); + util_blitter_save_stencil_ref(b, &ctx->stencil_ref); + util_blitter_save_viewport(b, &ctx->viewport); + util_blitter_save_scissor(b, &ctx->scissor); + util_blitter_save_framebuffer(b, &ctx->fb); + util_blitter_save_fragment_sampler_states(b, nsamplers, (void **)ctx->fs_samplers); + util_blitter_save_fragment_sampler_views(b, nviews, ctx->fs_views); + util_blitter_save_fragment_constant_buffer_slot(b, &ctx->cb[1]); + util_blitter_save_sample_mask(b, ~0u, 0); + util_blitter_save_render_condition(b, ctx->cond_query, ctx->cond_condition, ctx->cond_mode); +} + +/* SGX_DEBUG=copies: each copy and blit, and whose it is */ +static bool +debug_copies(void) +{ + static int on = -1; + + if (on < 0) + on = getenv("SGX_DEBUG") && strstr(getenv("SGX_DEBUG"), "copies"); + return on; +} + +/* Whether a copy from src to dst is the GPU's: colour both, two + * dimensional, a target the frame can render into -- and a source the GPU + * wrote (a render's target, PPSSPP's framebuffers): the CPU would wait + * for the GPU to read it, and the GPU's copy is a render that waits for + * nothing. SGX_GPU_COPY=0: every copy the CPU's, as before. */ +static bool +gpu_copy(struct sgx_context *ctx, struct pipe_resource *dst, struct pipe_resource *src) +{ + struct sgx_screen *screen = sgx_screen(ctx->base.screen); + static int on = -1; + + if (on < 0) + on = debug_get_bool_option("SGX_GPU_COPY", true); + if (!on || !ctx->blitter || !screen->frame || !dst || !src || + dst->target == PIPE_BUFFER || src->target == PIPE_BUFFER || + (dst->target != PIPE_TEXTURE_2D && dst->target != PIPE_TEXTURE_RECT) || + (src->target != PIPE_TEXTURE_2D && src->target != PIPE_TEXTURE_RECT) || + util_format_is_depth_or_stencil(dst->format) || + util_format_is_depth_or_stencil(src->format) || + dst->nr_samples > 1 || src->nr_samples > 1 || + !ctx->base.screen->is_format_supported(ctx->base.screen, dst->format, PIPE_TEXTURE_2D, + 0, 0, PIPE_BIND_RENDER_TARGET)) + return false; + return sgx_resource(src)->gpu_written; +} + +static void +sgx_resource_copy_region(struct pipe_context *pctx, struct pipe_resource *dst, + unsigned dst_level, unsigned dstx, unsigned dsty, unsigned dstz, + struct pipe_resource *src, unsigned src_level, + const struct pipe_box *src_box) +{ + struct sgx_context *ctx = sgx_context(pctx); + bool gpu = src_box->depth == 1 && gpu_copy(ctx, dst, src) && + util_blitter_is_copy_supported(ctx->blitter, dst, src); + + if (debug_copies()) + mesa_logi("sgx: a copy of %dx%d from %s %ux%u level %u to %s %ux%u level %u: %s", + src_box->width, src_box->height, util_format_short_name(src->format), + src->width0, src->height0, src_level, util_format_short_name(dst->format), + dst->width0, dst->height0, dst_level, gpu ? "the GPU" : "the CPU"); + if (gpu) { + blitter_save(ctx); + util_blitter_copy_texture(ctx->blitter, dst, dst_level, dstx, dsty, dstz, src, src_level, + src_box); + return; + } + util_resource_copy_region(pctx, dst, dst_level, dstx, dsty, dstz, src, src_level, src_box); +} + +static void +sgx_blit(struct pipe_context *pctx, const struct pipe_blit_info *info) +{ + struct sgx_context *ctx = sgx_context(pctx); + struct pipe_blit_info part = *info; + + if (info->render_condition_enable && !sgx_render_condition_ok(sgx_context(pctx))) + return; + if (util_try_blit_via_copy_region(pctx, info, false)) + return; + /* (M46) colour by the GPU, as a copy is (depth and stencil stay the + * CPU's: the depth buffer lives in the ZLS's layout). A render + * condition was looked at above; u_blitter keeps it for its draw. */ + if (!(info->mask & PIPE_MASK_ZS) && !info->alpha_blend && + gpu_copy(ctx, info->dst.resource, info->src.resource) && + info->src.box.depth == 1 && info->dst.box.depth == 1 && + util_blitter_is_blit_supported(ctx->blitter, info)) { + if (debug_copies()) + mesa_logi("sgx: a blit of %dx%d to %dx%d (%s to %s): the GPU", info->src.box.width, + info->src.box.height, info->dst.box.width, info->dst.box.height, + util_format_short_name(info->src.format), + util_format_short_name(info->dst.format)); + blitter_save(ctx); + util_blitter_blit(ctx->blitter, info, NULL); + return; + } + /* colour, then depth and stencil (M43: glBlitFramebuffer's mask may + * have both) */ + part.mask = info->mask & PIPE_MASK_RGBA; + if (part.mask && !cpu_blit(pctx, &part)) + mesa_logw_once("sgx: a colour blit not done (format %s to %s)", + util_format_short_name(info->src.format), + util_format_short_name(info->dst.format)); + part.mask = info->mask & PIPE_MASK_ZS; + if (part.mask && !cpu_blit(pctx, &part)) + mesa_logw_once("sgx: a depth or stencil blit not done (format %s to %s)", + util_format_short_name(info->src.format), + util_format_short_name(info->dst.format)); +} + +static void +sgx_flush_resource(struct pipe_context *pctx, struct pipe_resource *prsc) +{ + if (sgx_batch_uses(sgx_context(pctx), prsc)) + sgx_batch_flush(sgx_context(pctx)); +} + +/* ---- state, kept for later ---------------------------------------------- */ + +static void * +sgx_create_copy(const void *state, size_t size) +{ + void *copy = MALLOC(size); + + if (copy) + memcpy(copy, state, size); + return copy; +} + +static void * +sgx_create_blend_state(struct pipe_context *pctx, const struct pipe_blend_state *s) +{ + return sgx_create_copy(s, sizeof(*s)); +} + +static void * +sgx_create_dsa_state(struct pipe_context *pctx, + const struct pipe_depth_stencil_alpha_state *s) +{ + return sgx_create_copy(s, sizeof(*s)); +} + +static void * +sgx_create_rs_state(struct pipe_context *pctx, const struct pipe_rasterizer_state *s) +{ + struct pipe_rasterizer_state *r = sgx_create_copy(s, sizeof(*s)); + + /* lines of width 1 too through the draw module's wide line stage (made + * triangles: all the TA takes from us), which takes width 1 for a line + * to leave alone (M24) */ + if (r && r->line_width == 1.0f) + r->line_width = 1.0f + 1.0f / 1024; + /* polygon offset's unit: 24-bit depth's (sgx_draw_init) is a bit or two + * of the tiles' F32 depth, lost between the draw module's z and the + * ISP's interpolated one; four of them are not (dEQP's displacement + * cases pass from two; SGX_OFFSET_SCALE) */ + if (r) + r->offset_units *= SGX_OFFSET_SCALE; + return r; +} + +static void * +sgx_create_sampler_state(struct pipe_context *pctx, const struct pipe_sampler_state *s) +{ + return sgx_create_copy(s, sizeof(*s)); +} + +static void * +sgx_create_vertex_elements(struct pipe_context *pctx, unsigned count, + const struct pipe_vertex_element *e) +{ + struct sgx_vertex_elements *ve = CALLOC_STRUCT(sgx_vertex_elements); + + if (!ve) + return NULL; + ve->count = MIN2(count, PIPE_MAX_ATTRIBS); + memcpy(ve->e, e, ve->count * sizeof(*e)); + for (unsigned i = 0; i < ve->count; i++) + ve->attr[i] = sgx_attr_of_format(e[i].src_format); + return ve; +} + +static void +sgx_bind_vertex_elements(struct pipe_context *pctx, void *state) +{ + struct sgx_vertex_elements *ve = state; + + sgx_context(pctx)->velems = ve; + if (ve) + draw_set_vertex_elements(sgx_context(pctx)->draw, ve->count, ve->e); +} + +/* The state tracker hands over its NIR, which the shader keeps (the + * compiler, M13, will take it from there). For now a vertex shader also + * goes to the draw module, which runs it on the CPU (a copy: it is turned + * into TGSI and freed), and a fragment shader's colour is read off it. */ +static void * +sgx_create_shader_state(struct pipe_context *pctx, const struct pipe_shader_state *s) +{ + struct sgx_context *ctx = sgx_context(pctx); + struct sgx_shader *sh = CALLOC_STRUCT(sgx_shader); + struct pipe_shader_state from_tgsi; + + if (!sh) + return NULL; + /* (M46) u_blitter's shaders come as TGSI: made NIR, as the state + * tracker's are */ + if (s->type == PIPE_SHADER_IR_TGSI && s->tokens) { + from_tgsi = *s; + from_tgsi.type = PIPE_SHADER_IR_NIR; + from_tgsi.ir.nir = tgsi_to_nir(s->tokens, pctx->screen, false); + if (!from_tgsi.ir.nir) + return sh; + /* (gallium's own: the compiler may take their texelFetch for a + * lookup, txf_as_lookup) */ + from_tgsi.ir.nir->info.internal = true; + s = &from_tgsi; + } + if (s->type != PIPE_SHADER_IR_NIR) + return sh; + sh->nir = s->ir.nir; + if (sh->nir->info.stage == MESA_SHADER_VERTEX) + sh->vs_nattrs = sgx_vs_attr_count(sh->nir); + if (sh->nir->info.stage == MESA_SHADER_VERTEX && ctx->draw) { + struct pipe_shader_state copy = *s; + + copy.ir.nir = nir_shader_clone(NULL, sh->nir); + sh->draw = draw_create_vertex_shader(ctx->draw, ©); + if (!sh->draw) + mesa_logw("sgx: the draw module did not take a vertex shader"); + } else if (sh->nir->info.stage == MESA_SHADER_FRAGMENT) { + char why[128]; + + /* the draw module's wide point stage reads it (only scans it) */ + if (ctx->draw) + sh->draw_fs = draw_create_fragment_shader(ctx->draw, s); + + sgx_fs_colour_analyse(sh->nir, &sh->colour); + sh->has_texclamp = sgx_fs_texclamp(sh->nir, &sh->texclamp); + /* SGX_DEBUG=each (M46): the shader as it comes, named as the draws + * name it */ + if (ctx->debug_each) { + mesa_logi("sgx: each: fragment shader %p (%s):", (void *)sh, + sh->nir->info.name ? sh->nir->info.name : "?"); + nir_print_shader(sh->nir, stderr); + } + /* SGX_NOCOMPILE=1: M13a's way only */ + if (!debug_get_bool_option("SGX_NOCOMPILE", false)) { + sh->compiled = sgx_compile_fs(sh->nir, NULL, why, sizeof(why)); + if (!sh->compiled) + mesa_logw("sgx: a fragment shader not compiled (%s): its colour is worked " + "out per vertex", why); + else if (ctx->debug_draw || debug_get_bool_option("SGX_DEBUG_SHADER", false)) { + mesa_logi("sgx: a fragment shader compiled: %u instructions, %u temps, " + "%u inputs, %u sa words, %u textures", sh->compiled->prog.ncode, + sh->compiled->prog.ntemps, sh->compiled->prog.ninputs, + sh->compiled->prog.nsa, sh->compiled->nsamplers); + /* SGX_DEBUG_SHADER=1: the code, for tools/iosgpu/usse-dis.py words */ + for (unsigned i = 0; debug_get_bool_option("SGX_DEBUG_SHADER", false) && + i < sh->compiled->prog.ncode; i++) + mesa_logi("sgx: %016llx", (unsigned long long)sh->compiled->prog.code[i]); + } + } + } + return sh; +} + +static void +sgx_delete_shader_state(struct pipe_context *pctx, void *state) +{ + struct sgx_context *ctx = sgx_context(pctx); + struct sgx_shader *sh = state; + + if (ctx->vs == sh) + ctx->vs = NULL; + if (ctx->draw_vs == sh) { + draw_bind_vertex_shader(ctx->draw, NULL); + ctx->draw_vs = NULL; + } + if (sh->draw) + draw_delete_vertex_shader(ctx->draw, sh->draw); + if (ctx->fs == sh) { + ctx->fs = NULL; + if (ctx->draw) + draw_bind_fragment_shader(ctx->draw, NULL); + } + if (sh->draw_fs) + draw_delete_fragment_shader(ctx->draw, sh->draw_fs); + /* its programs live until the gathered draws, which may use them, are + * rendered; then their places in GPU memory are free once the render is + * done (st deletes the last program at the next glUseProgram: no flush + * in the middle of a frame, M24) */ + sgx_batch_bury_fs(ctx, sh->compiled); + for (unsigned i = 0; i < sh->nvariants; i++) + sgx_batch_bury_fs(ctx, sh->variant[i]); + for (unsigned i = 0; i < sh->nvs; i++) + sgx_batch_bury_vs(ctx, sh->vs_variant[i]); + ralloc_free(sh->nir); + FREE(sh); +} + +/* (M46: the draw module gets it only when a draw goes its way -- binding + * one there parses it again, tgsi_exec's arrays allocated anew, ~6 KB a + * bind, which musl maps and unmaps: once a draw in God of War) */ +static void +sgx_bind_vs_state(struct pipe_context *pctx, void *state) +{ + sgx_context(pctx)->vs = state; +} + +static void +sgx_bind_fs_state(struct pipe_context *pctx, void *state) +{ + struct sgx_context *ctx = sgx_context(pctx); + struct sgx_shader *sh = state; + + ctx->fs = sh; + if (ctx->draw) + draw_bind_fragment_shader(ctx->draw, sh ? sh->draw_fs : NULL); +} + +static void +sgx_bind_rs_state(struct pipe_context *pctx, void *state) +{ + struct sgx_context *ctx = sgx_context(pctx); + + /* the draw module first: its flush binds the state it had again (its + * wide point and line stages restore it), and that must not be the + * one the GPU's vertex side then goes by */ + if (ctx->draw && state) + draw_set_rasterizer_state(ctx->draw, state, state); + ctx->rast = state; + /* (M43) depth clamping as the program's state has it: the draw + * module's wide line and point stages bind one of their own for their + * triangles, with depth clipping and clamping both off */ + if (state) { + const struct pipe_rasterizer_state *r = state; + + if (r->depth_clip_near || r->depth_clip_far || r->depth_clamp) + ctx->depth_clamp = r->depth_clamp; + } +} + +static void +sgx_bind_state(struct pipe_context *pctx, void *state) +{ +} + +static void +sgx_delete_state(struct pipe_context *pctx, void *state) +{ + FREE(state); +} + +static void +sgx_bind_sampler_states(struct pipe_context *pctx, mesa_shader_stage shader, + unsigned start, unsigned count, void **states) +{ + struct sgx_context *ctx = sgx_context(pctx); + + if (shader != MESA_SHADER_FRAGMENT) + return; + for (unsigned i = 0; i < count && start + i < PIPE_MAX_SAMPLERS; i++) + ctx->fs_samplers[start + i] = states ? states[i] : NULL; +} + +static struct pipe_sampler_view * +sgx_create_sampler_view(struct pipe_context *pctx, struct pipe_resource *prsc, + const struct pipe_sampler_view *templ) +{ + struct pipe_sampler_view *view = CALLOC_STRUCT(pipe_sampler_view); + + if (!view) + return NULL; + *view = *templ; + view->texture = NULL; + pipe_resource_reference(&view->texture, prsc); + pipe_reference_init(&view->reference, 1); + view->context = pctx; + return view; +} + +static void +sgx_sampler_view_destroy(struct pipe_context *pctx, struct pipe_sampler_view *view) +{ + pipe_resource_reference(&view->texture, NULL); + FREE(view); +} + +static void +sgx_set_sampler_views(struct pipe_context *pctx, mesa_shader_stage shader, + unsigned start, unsigned count, unsigned unbind_trailing, + struct pipe_sampler_view **views) +{ + struct sgx_context *ctx = sgx_context(pctx); + + if (shader != MESA_SHADER_FRAGMENT) + return; + for (unsigned i = 0; i < count + unbind_trailing; i++) + if (start + i < PIPE_MAX_SHADER_SAMPLER_VIEWS) + pipe_sampler_view_reference(&ctx->fs_views[start + i], + views && i < count ? views[i] : NULL); +} + +static void +sgx_set_framebuffer_state(struct pipe_context *pctx, + const struct pipe_framebuffer_state *fb) +{ + struct sgx_context *ctx = sgx_context(pctx); + + if (!util_framebuffer_state_equal(&ctx->fb, fb)) + sgx_batch_flush(ctx); + util_copy_framebuffer_state(&ctx->fb, fb); +} + +static void +sgx_set_blend_color(struct pipe_context *pctx, const struct pipe_blend_color *c) +{ + sgx_context(pctx)->blend_color = *c; +} + +static void +sgx_bind_blend_state(struct pipe_context *pctx, void *state) +{ + sgx_context(pctx)->blend = state; +} + +static void +sgx_bind_dsa_state(struct pipe_context *pctx, void *state) +{ + sgx_context(pctx)->dsa = state; +} + +static void +sgx_set_clip_state(struct pipe_context *pctx, const struct pipe_clip_state *c) +{ + struct sgx_context *ctx = sgx_context(pctx); + + if (ctx->draw) + draw_set_clip_state(ctx->draw, c); +} + +/* buffer 0 of the vertex and the fragment shader: read at draw time */ +static void +sgx_set_constant_buffer(struct pipe_context *pctx, mesa_shader_stage shader, + uint index, const struct pipe_constant_buffer *cb) +{ + struct sgx_context *ctx = sgx_context(pctx); + + if (index == 0 && (shader == MESA_SHADER_VERTEX || shader == MESA_SHADER_FRAGMENT)) + util_copy_constant_buffer(&ctx->cb[shader == MESA_SHADER_FRAGMENT], cb); + else if (index < SGX_FRAME_MAX_UBOS && + (shader == MESA_SHADER_VERTEX || shader == MESA_SHADER_FRAGMENT)) + util_copy_constant_buffer(&ctx->ubo[shader == MESA_SHADER_FRAGMENT][index], cb); +} + +static void +sgx_set_polygon_stipple(struct pipe_context *pctx, const struct pipe_poly_stipple *s) +{ +} + +static void +sgx_set_sample_mask(struct pipe_context *pctx, unsigned mask) +{ +} + +static void +sgx_set_scissor_states(struct pipe_context *pctx, unsigned start, unsigned count, + const struct pipe_scissor_state *s) +{ + if (start == 0 && count) + sgx_context(pctx)->scissor = s[0]; +} + +static void +sgx_set_stencil_ref(struct pipe_context *pctx, const struct pipe_stencil_ref ref) +{ + sgx_context(pctx)->stencil_ref = ref; +} + +static void +sgx_set_viewport_states(struct pipe_context *pctx, unsigned start, unsigned count, + const struct pipe_viewport_state *v) +{ + struct sgx_context *ctx = sgx_context(pctx); + + if (start == 0 && count) + ctx->viewport = v[0]; + if (ctx->draw) + draw_set_viewport_states(ctx->draw, start, count, v); +} + +static void +sgx_set_vertex_buffers(struct pipe_context *pctx, unsigned count, + const struct pipe_vertex_buffer *buffers) +{ + struct sgx_context *ctx = sgx_context(pctx); + + /* the draw module takes references of its own; then ours takes over the + * ones the state tracker hands in */ + if (ctx->draw) + draw_set_vertex_buffers(ctx->draw, count, buffers); + util_set_vertex_buffers_mask(ctx->vb, &ctx->vb_mask, buffers, count); +} + +static void +sgx_texture_barrier(struct pipe_context *pctx, unsigned flags) +{ +} + +static void +sgx_memory_barrier(struct pipe_context *pctx, unsigned flags) +{ +} + +static enum pipe_reset_status +sgx_get_device_reset_status(struct pipe_context *pctx) +{ + return PIPE_NO_RESET; +} + +/* ---- the context -------------------------------------------------------- */ + +static void +sgx_context_destroy(struct pipe_context *pctx) +{ + struct sgx_context *ctx = sgx_context(pctx); + + /* (its states and shaders are deleted through the context: first) */ + if (ctx->blitter) + util_blitter_destroy(ctx->blitter); + sgx_draw_fini(ctx); + for (unsigned i = 0; i < ARRAY_SIZE(ctx->fs_views); i++) + pipe_sampler_view_reference(&ctx->fs_views[i], NULL); + util_unreference_framebuffer_state(&ctx->fb); + util_set_vertex_buffers_mask(ctx->vb, &ctx->vb_mask, NULL, 0); + for (unsigned i = 0; i < ARRAY_SIZE(ctx->cb); i++) + pipe_resource_reference(&ctx->cb[i].buffer, NULL); + for (unsigned i = 0; i < 2; i++) + for (unsigned k = 0; k < SGX_FRAME_MAX_UBOS; k++) + pipe_resource_reference(&ctx->ubo[i][k].buffer, NULL); + if (pctx->stream_uploader) + u_upload_destroy(pctx->stream_uploader); + sgx_fence_reference(&ctx->last, NULL); + pipe_resource_reference(&ctx->no_colour, NULL); + slab_destroy_child(&ctx->transfer_pool); + FREE(ctx); +} + +struct pipe_context * +sgx_context_create(struct pipe_screen *pscreen, void *priv, unsigned flags) +{ + struct sgx_screen *screen = sgx_screen(pscreen); + struct sgx_context *ctx = CALLOC_STRUCT(sgx_context); + struct pipe_context *p; + + if (!ctx) + return NULL; + ctx->batch.depth_clear = 1.0f; + p = &ctx->base; + p->screen = pscreen; + p->priv = priv; + slab_create_child(&ctx->transfer_pool, &screen->transfer_pool); + + p->destroy = sgx_context_destroy; + p->create_fence_fd = sgx_create_fence_fd; + p->fence_server_sync = sgx_fence_server_sync; + p->flush = sgx_flush; + p->clear = sgx_clear; + p->clear_render_target = sgx_clear_render_target; + p->clear_depth_stencil = sgx_clear_depth_stencil; + p->clear_texture = util_clear_texture_sw; + p->resource_copy_region = sgx_resource_copy_region; + p->blit = sgx_blit; + p->flush_resource = sgx_flush_resource; + p->draw_vbo = sgx_draw_vbo; + ctx->debug_draw = debug_get_bool_option("SGX_DEBUG_DRAW", false); + ctx->debug_fps = getenv("SGX_DEBUG") && strstr(getenv("SGX_DEBUG"), "fps"); + ctx->debug_flushes = getenv("SGX_DEBUG") && strstr(getenv("SGX_DEBUG"), "flushes"); + ctx->debug_sync = getenv("SGX_DEBUG") && strstr(getenv("SGX_DEBUG"), "sync"); + ctx->debug_each = getenv("SGX_DEBUG") && strstr(getenv("SGX_DEBUG"), "each"); + p->texture_barrier = sgx_texture_barrier; + p->memory_barrier = sgx_memory_barrier; + p->get_device_reset_status = sgx_get_device_reset_status; + p->create_query = sgx_create_query; + p->destroy_query = sgx_destroy_query; + p->begin_query = sgx_begin_query; + p->end_query = sgx_end_query; + p->get_query_result = sgx_get_query_result; + p->render_condition = sgx_render_condition; + p->set_active_query_state = sgx_set_active_query_state; + p->resource_release = u_default_resource_release; + + p->create_blend_state = sgx_create_blend_state; + p->bind_blend_state = sgx_bind_blend_state; + p->delete_blend_state = sgx_delete_state; + p->create_depth_stencil_alpha_state = sgx_create_dsa_state; + p->bind_depth_stencil_alpha_state = sgx_bind_dsa_state; + p->delete_depth_stencil_alpha_state = sgx_delete_state; + p->create_rasterizer_state = sgx_create_rs_state; + p->bind_rasterizer_state = sgx_bind_rs_state; + p->delete_rasterizer_state = sgx_delete_state; + p->create_sampler_state = sgx_create_sampler_state; + p->bind_sampler_states = sgx_bind_sampler_states; + p->delete_sampler_state = sgx_delete_state; + p->create_vertex_elements_state = sgx_create_vertex_elements; + p->bind_vertex_elements_state = sgx_bind_vertex_elements; + p->delete_vertex_elements_state = sgx_delete_state; + p->create_vs_state = sgx_create_shader_state; + p->bind_vs_state = sgx_bind_vs_state; + p->delete_vs_state = sgx_delete_shader_state; + p->create_fs_state = sgx_create_shader_state; + p->bind_fs_state = sgx_bind_fs_state; + p->delete_fs_state = sgx_delete_shader_state; + p->create_sampler_view = sgx_create_sampler_view; + p->sampler_view_destroy = sgx_sampler_view_destroy; + p->sampler_view_release = u_default_sampler_view_release; + p->set_sampler_views = sgx_set_sampler_views; + p->set_framebuffer_state = sgx_set_framebuffer_state; + p->set_blend_color = sgx_set_blend_color; + p->set_clip_state = sgx_set_clip_state; + p->set_constant_buffer = sgx_set_constant_buffer; + p->set_polygon_stipple = sgx_set_polygon_stipple; + p->set_sample_mask = sgx_set_sample_mask; + p->set_scissor_states = sgx_set_scissor_states; + p->set_stencil_ref = sgx_set_stencil_ref; + p->set_viewport_states = sgx_set_viewport_states; + p->set_vertex_buffers = sgx_set_vertex_buffers; + sgx_resource_context_init(p); + + /* after the hooks: the draw module looks at them */ + if (!sgx_draw_init(ctx)) + mesa_logw("sgx: no draw module: draws are dropped"); + + p->stream_uploader = u_upload_create_default(p); + if (!p->stream_uploader) { + sgx_context_destroy(p); + return NULL; + } + p->const_uploader = p->stream_uploader; + /* (M46) copies and blits on the GPU -- without it, the CPU's */ + ctx->blitter = util_blitter_create(p); + if (!ctx->blitter) + mesa_logw("sgx: no u_blitter: copies and blits by the CPU"); + return p; +} diff --git a/src/gallium/drivers/sgx/sgx_context.h b/src/gallium/drivers/sgx/sgx_context.h new file mode 100644 index 00000000000..2d2ad11c456 --- /dev/null +++ b/src/gallium/drivers/sgx/sgx_context.h @@ -0,0 +1,300 @@ +/* + * Copyright 2026 Project Cascadia + * SPDX-License-Identifier: MIT + */ +#ifndef SGX_CONTEXT_H +#define SGX_CONTEXT_H + +#include "pipe/p_context.h" +#include "util/u_debug.h" +#include "pipe/p_state.h" +#include "util/slab.h" + +#include "sgx_compiler.h" +#include "sgx_device.h" +#include "sgx_draw.h" +#include "sgx_frame.h" + +struct draw_context; +struct draw_stage; +struct draw_vertex_shader; +struct sgx_fence; +struct sgx_screen; +struct vbuf_render; + +struct sgx_shader { + struct nir_shader *nir; + struct draw_vertex_shader *draw; /* a vertex shader's, on the CPU */ + struct draw_fragment_shader *draw_fs; /* a fragment shader's, for the draw module's + point and line stages (M24) */ + struct sgx_fs_colour colour; /* a fragment shader's colour */ + struct sgx_fs *compiled; /* a fragment shader, compiled (M13c) */ + struct sgx_fs *variant[8]; /* and again for blend states (M14) */ + unsigned nvariants; + struct sgx_vs *vs_variant[8]; /* a vertex shader on the GPU, for the varyings + a fragment shader reads (M18) and the + attributes' formats (M26) */ + unsigned nvs; + unsigned vs_nattrs; /* the attributes it reads (sgx_vs_attr_count) */ + bool vs_failed; /* it cannot be compiled: the draw module's */ + /* (M46) a fragment shader's TClampST lookup (sgx_fs_texclamp), if it has one */ + bool has_texclamp; + struct sgx_texclamp texclamp; +}; + +/* Draws gathered into one render until something needs it done + * (sgx_draw.c: sgx_batch_flush): a flush, a map of what it writes or + * reads, another target, a clear, a full batch. */ +struct sgx_batch_draw { + struct sgx_frame_layout l; + /* its vertices: the draw module's, floats from first in verts; a + * vertex shader's the CPU made one stream (M26), at vdata_va in one of + * the batch's vertex chunks (M42) -- or none, the fetch reading the + * application's buffers */ + unsigned first, nverts; + uint32_t vdata_va; + struct sgx_pixel_program prog; /* a copy, uploaded */ + bool compiled; + unsigned sa; /* its secondary attributes, from word sa */ + struct sgx_frame_state st; + struct sgx_vs *vs; /* its vertex shader on the GPU (M18), or NULL */ + unsigned vs_sa; /* its uniforms, from word vs_sa in sa */ + unsigned idx, nidx; /* its indices, from idx in the batch's */ + uint32_t idx_va; /* (M46) or in a buffer's GPU copy, there */ + /* a vertex shader's (M26): where the fetch reads each attribute of + * vertex 0, the stride, the vertices drawn (nidx of them when it has + * indices, else 0, 1, 2, ...), the largest index */ + uint32_t base[SGX_VS_MAX_ATTRIBS]; + unsigned stride, count, max_index; + bool repacked; +}; + +/* An occlusion query (M37): the renders made while it was active, each + * with a visibility buffer of its own -- the samples its draws passed, a + * word a core (sgx_frame_render's vis) -- and what those read already came + * to. A render goes at each begin and end: the ISP has one count. */ +#define SGX_QUERY_BUFS 16 +struct sgx_query { + unsigned type; /* PIPE_QUERY_OCCLUSION_* */ + struct sgx_bo *bo[SGX_QUERY_BUFS]; + unsigned nbo; + uint64_t samples; + /* the last render made before its end: its result is there when every + * render before is done, its own or not (piglit's occlusion_query_order: + * a query with no draws after others) */ + struct sgx_fence *last; + /* (M43) TIMESTAMP and TIME_ELAPSED: the render before each end (and its + * call's time), the GPU's time there the later of the two */ + struct sgx_fence *begin_fence; + uint64_t begin_cpu, end_cpu; +}; + +/* a render's visibility buffer for q, busy with it (sgx_batch_flush) */ +void sgx_query_add(struct sgx_query *q, struct sgx_bo *bo); +/* whether rendering goes ahead under the render condition (M43) */ +bool sgx_render_condition_ok(struct sgx_context *ctx); + +#define SGX_BATCH_VCHUNKS 40 +#define SGX_BATCH_VCHUNK (256u << 10) + +struct sgx_batch { + struct pipe_resource *rt; /* referenced */ + unsigned rt_level, rt_layer; /* its level and face (M29) */ + unsigned w, h; /* its area (M43: sgx_frame_target) */ + struct sgx_batch_draw draw[SGX_FRAME_MAX_DRAWS]; + struct sgx_frame_draw fdraw[SGX_FRAME_MAX_DRAWS]; /* (sgx_batch_flush's) */ + unsigned ndraws; + unsigned seq; /* this one's number, counted from 1 */ + float depth_clear; /* what the render's depth starts at */ + struct pipe_resource *zs; /* the depth buffer, referenced (M24) */ + unsigned zs_level, zs_layer; /* its level and layer (M43) */ + bool zs_cleared; /* its depth cleared at the render's start */ + bool zs_read, zs_written; /* a draw tests depth, writes it */ + bool counted; /* a draw's samples counted (M37) */ + bool blit; /* (SGX_DEBUG=sync) u_blitter's draws in it */ + float *verts; + unsigned nfloats, maxfloats; + /* vertex shaders' vertices made one stream (M26), written there by + * gpu_vs_draw straight into GPU memory (M42: once, not copied twice + * more) -- chunks from the buffer cache, listed for the render and busy + * with it; vat the next byte in the last; nbytes all of them told */ + struct sgx_bo *vchunk[SGX_BATCH_VCHUNKS]; + unsigned nvchunks; + uint32_t vat; + unsigned nbytes; + uint32_t *sa; + unsigned nsa, maxsa; + uint16_t *idx; + unsigned nidx, maxidx; + struct pipe_resource *tex[SGX_FRAME_MAX_HANDLES]; /* sampled, referenced */ + /* the buffer each was sampled from (its copy then, M37: a copy remade + * while draws read the old one is a new buffer -- the same texture + * twice), referenced, and busy with the render once it is made */ + struct sgx_bo *tex_bo[SGX_FRAME_MAX_HANDLES]; + unsigned ntex; + uint64_t tex_bytes; /* the memory they hold (SGX_BATCH_TEX_BYTES) */ + /* the buffers the render lists for the kernel -- the textures' copies, + * then buffers' (M26: their GPU copies, referenced in bos[], stamped + * with seq) -- SGX_FRAME_MAX_HANDLES at most all told */ + uint32_t handles[SGX_FRAME_MAX_HANDLES]; + struct sgx_bo *bos[SGX_FRAME_MAX_HANDLES]; + unsigned nbos; + /* programs deleted while draws here may use them: retired from the + * frame and freed at the flush (M24) */ + struct sgx_vs **dead_vs; + unsigned ndead_vs; + struct sgx_fs **dead_fs; + unsigned ndead_fs; +}; + +struct sgx_vertex_elements { + unsigned count; + struct pipe_vertex_element e[PIPE_MAX_ATTRIBS]; + uint8_t attr[PIPE_MAX_ATTRIBS]; /* how the fetch reads each: an SGX_ATTR, 0 if + it cannot (M26) */ +}; + +/* M26: a vertex shader's draw on its way into the batch (sgx_draw.c, + * gpu_vs_draw to submit): its attributes' addresses for vertex 0 -- in + * buffers' GPU copies (bos[]), or offsets in a vertex of the nverts the CPU + * made one stream in vdata -- one stride; the vertices drawn, count of + * them: from indices[] when indexed, else 0, 1, 2, ... */ +struct sgx_vtx { + uint32_t base[SGX_VS_MAX_ATTRIBS]; + unsigned stride; + bool repacked; + unsigned nverts; + unsigned count, max_index; + bool indexed; + /* (M46) its indices where they are: their address in the index buffer's + * GPU copy (0: ctx->indices, copied into the render) */ + uint32_t idx_va; + /* the buffers the draw reads: its attributes', and (M43) its uniform + * buffers', both stages' */ + struct sgx_bo *bos[SGX_VS_MAX_ATTRIBS + 2 * SGX_FRAME_MAX_UBOS + 1]; /* (+1: M46's index buffer) */ + unsigned nbos; + /* repacked (M42): where the stream was written -- the batch's chunk + * vchunk (referenced), vdata for the CPU, vdata_va for the GPU -- when + * the batch was number vseq (a flush since: written again, there) */ + struct sgx_bo *vchunk; + uint8_t *vdata; + uint32_t vdata_va; + unsigned vseq; +}; + +struct sgx_context { + struct pipe_context base; + /* (M46) copies and blits on the GPU: u_blitter's quads */ + struct blitter_context *blitter; + struct slab_child_pool transfer_pool; + struct pipe_framebuffer_state fb; + struct pipe_vertex_buffer vb[PIPE_MAX_ATTRIBS]; + uint32_t vb_mask; + struct pipe_constant_buffer cb[2]; /* buffer 0: the vertex, fragment shader's */ + /* (M43) the uniform buffers, 1..15, of the vertex and fragment shader */ + struct pipe_constant_buffer ubo[2][SGX_FRAME_MAX_UBOS]; + struct sgx_shader *vs, *fs; + /* (M46) the vertex shader bound in the draw module: bound only when a + * draw goes that way (sgx_draw_vbo) */ + struct sgx_shader *draw_vs; + /* blending, depth (M14) */ + const struct pipe_blend_state *blend; + const struct pipe_depth_stencil_alpha_state *dsa; + struct pipe_blend_color blend_color; + struct sgx_fs *draw_fs; /* this draw's fragment shader (sgx_draw.c) */ + /* the fragment shader's textures (M14) */ + const struct pipe_sampler_state *fs_samplers[PIPE_MAX_SAMPLERS]; + struct pipe_sampler_view *fs_views[PIPE_MAX_SHADER_SAMPLER_VIEWS]; + struct sgx_fence *last; /* the last render this context submitted */ + /* a framebuffer of depth and stencil alone: the colour the tiles end in + * goes here (M35), the depth buffer's size */ + struct pipe_resource *no_colour; + + /* draws (sgx_draw.c): the draw module, its back end, and the vertices + * gathered for the template frame */ + struct draw_context *draw; + struct draw_stage *vbuf; + struct vbuf_render *render; + struct sgx_frame_layout layout; /* of verts, for the bound shaders */ + float *verts; + unsigned nverts, maxfloats; + /* M18: the vertex shader on the GPU -- its vertices (M26: vtx; M42: a + * stream the CPU makes in the batch's vertex chunks), the triangles + * indices into them, its uniforms */ + struct sgx_vs *gpu_vs; + struct sgx_vtx vtx; + uint16_t *indices; + unsigned maxindices; + uint32_t vs_sa[128 + SGX_UBUF_MAX]; /* (sa's, then the uniforms in memory, M32) */ + const struct pipe_rasterizer_state *rast; + const struct sgx_vertex_elements *velems; + struct pipe_viewport_state viewport; + bool depth_clamp; /* the program's rasterizer state's (M43) */ + struct pipe_scissor_state scissor; + struct pipe_stencil_ref stencil_ref; + struct sgx_pixel_program clear_prog; /* writes nothing: sgx_zs_clear() */ + struct sgx_pixel_program colour_prog; /* o0 = sa0: sgx_colour_clear() */ + uint64_t colour_code[2]; + /* (M43) the colour clear's program for each kind of float tile */ + struct sgx_pixel_program colour_float_prog[SGX_RT_F32X2 + 1]; + uint64_t colour_float_code[SGX_RT_F32X2 + 1][2]; + struct sgx_batch batch; + struct sgx_query *query; /* the active occlusion query (M37) */ + bool queries_off; /* (set_active_query_state: meta ops) */ + /* (M43) conditional rendering (NV_conditional_render): the query whose + * result decides, render_condition()'s condition and mode */ + struct pipe_query *cond_query; + bool cond_condition; + enum pipe_render_cond_flag cond_mode; + const float *fs_constants; + unsigned fs_constants_size; /* bytes */ + bool warned_fs, debug_draw; + /* SGX_DEBUG=fps: frames (swaps), renders and draws counted, and said + * every two seconds */ + bool debug_fps, debug_sync, debug_flushes; + /* SGX_DEBUG=each (M46): every draw a render of its own, said with its + * pixel program (with sync: each one's time on the GPU) */ + bool debug_each; + unsigned stat_frames, stat_renders, stat_draws; + int64_t stat_t0, stat_cpu0, stat_gpu; + int64_t stat_swap, stat_between; /* the last frame's end; to the next draw */ + int64_t stat_swap_cpu, stat_between_cpu; + /* (M46) draws of a TClampST shader with its clamp left out, with it + * kept; the CPU time telling */ + unsigned stat_clamp_free, stat_clamp_kept; + int64_t stat_clamp_ns; +}; + +static inline struct sgx_context * +sgx_context(struct pipe_context *p) +{ + return (struct sgx_context *)p; +} + +/* what the rasterizer state's polygon offset units are times GL's, for + * the draw module (sgx_create_rs_state): 4, or with the ISP's offset + * (SGX_ISP_OFFSET=1, M37) 16 -- its unit, 32 of 24-bit depth's at depths + * 0.5..1, the draw module doubling it -- the same on both vertex paths */ +static inline float +sgx_offset_scale(void) +{ + static int isp = -1; + + if (isp < 0) + isp = debug_get_bool_option("SGX_ISP_OFFSET", false); + return isp ? 16.0f : 4.0f; +} +#define SGX_OFFSET_SCALE sgx_offset_scale() + +/* whether the gathered draws read bo (a buffer's GPU copy, M26) */ +static inline bool +sgx_batch_reads(const struct sgx_context *ctx, const struct sgx_bo *bo) +{ + return ctx->batch.ndraws && bo->batch_ctx == ctx && bo->batch_seq == ctx->batch.seq; +} + +struct pipe_context *sgx_context_create(struct pipe_screen *pscreen, void *priv, + unsigned flags); +void sgx_context_screen_init(struct sgx_screen *screen); + +#endif diff --git a/src/gallium/drivers/sgx/sgx_device.c b/src/gallium/drivers/sgx/sgx_device.c new file mode 100644 index 00000000000..8565e03d6d9 --- /dev/null +++ b/src/gallium/drivers/sgx/sgx_device.c @@ -0,0 +1,566 @@ +/* + * Copyright 2026 Project Cascadia + * SPDX-License-Identifier: MIT + */ +#include "sgx_device.h" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "drm-uapi/apple_sgx_drm.h" +#include "util/hash_table.h" +#include "util/log.h" +#include "util/macros.h" +#include "util/os_time.h" +#include "util/u_math.h" +#include "util/u_memory.h" + +#if defined(__arm__) +#include +#endif + +uint64_t +sgx_device_param(struct sgx_device *dev, uint32_t param) +{ + struct drm_apple_sgx_get_param p = { .param = param }; + + if (drmIoctl(dev->fd, DRM_IOCTL_APPLE_SGX_GET_PARAM, &p)) + return 0; + return p.value; +} + +bool +sgx_device_init(struct sgx_device *dev, int fd) +{ + dev->fd = fd; + /* 2: GEM_INFO, for buffers that come as dma-bufs; 3: the kernel's + * parameter buffer, the TA's heap */ + dev->uapi = sgx_device_param(dev, APPLE_SGX_PARAM_UAPI_VERSION); + if (dev->uapi < 1 || dev->uapi > 3) { + mesa_loge("sgx: the kernel's render node interface is version %u, not 1 to 3", + dev->uapi); + return false; + } + dev->bo_flags = sgx_device_param(dev, APPLE_SGX_PARAM_BO_FLAGS); + dev->core_id = sgx_device_param(dev, APPLE_SGX_PARAM_CORE_ID); + dev->core_rev = sgx_device_param(dev, APPLE_SGX_PARAM_CORE_REVISION); + dev->num_cores = sgx_device_param(dev, APPLE_SGX_PARAM_NUM_CORES); + /* the A6's SGX543MP3 is revision 2.1.3, the A5's MP2 1.2.2: the kernel + * loads each one's own microkernel, and the render target data, the 3D + * block and iOS's payload are laid out as each one's kext has them */ + dev->rc2 = (dev->core_rev >> 16 & 0xff) >= 2; + dev->va_start = sgx_device_param(dev, APPLE_SGX_PARAM_VA_START); + dev->va_end = sgx_device_param(dev, APPLE_SGX_PARAM_VA_END); + dev->code_base = sgx_device_param(dev, APPLE_SGX_PARAM_CODE_BASE); + dev->code_va_start = sgx_device_param(dev, APPLE_SGX_PARAM_CODE_VA_START); + dev->code_va_end = sgx_device_param(dev, APPLE_SGX_PARAM_CODE_VA_END); + dev->fb_va = sgx_device_param(dev, APPLE_SGX_PARAM_FB_VA); + dev->fb_width = sgx_device_param(dev, APPLE_SGX_PARAM_FB_WIDTH); + dev->fb_height = sgx_device_param(dev, APPLE_SGX_PARAM_FB_HEIGHT); + dev->fb_stride = sgx_device_param(dev, APPLE_SGX_PARAM_FB_STRIDE); + dev->untiled_next = UINT32_MAX; + simple_mtx_init(&dev->bo_lock, mtx_plain); + simple_mtx_init(&dev->cache_lock, mtx_plain); + list_inithead(&dev->cache); + if (!(dev->bos = _mesa_hash_table_u64_create(NULL))) + return false; + if (!sgx_device_param(dev, APPLE_SGX_PARAM_UKERNEL_UP)) + mesa_logw("sgx: the GPU's microkernel is not running (dmesg | grep apple-sgx)"); + return true; +} + +static void close_bo(struct sgx_bo *bo); + +void +sgx_device_fini(struct sgx_device *dev) +{ + list_for_each_entry_safe(struct sgx_bo, bo, &dev->cache, cache_link) + close_bo(bo); + _mesa_hash_table_u64_destroy(dev->bos); + simple_mtx_destroy(&dev->cache_lock); + simple_mtx_destroy(&dev->bo_lock); +} + +/* SGX_NOCC=1: every buffer mapped for the GPU without the cache-consistent + * bit -- the CPU writes them write-combined, past any cache, and a GPU read + * that goes through one could see an older line (mesa/frame-bisect tries + * it) */ +static uint32_t +extra_bo_flags(void) +{ + static int flags = -1; + + if (flags < 0) + flags = getenv("SGX_NOCC") && atoi(getenv("SGX_NOCC")) ? + APPLE_SGX_BO_NOT_CACHE_CONSISTENT : 0; + return flags; +} + +/* The BIF's first tiled window (the kernel's apple_sgx.h): what the GPU + * writes from here up the CPU reads back scrambled, in 256-byte x 16-line + * tiles. Kernels before 2026-10-04 gave out addresses from its top down + * (docs/research/p105-mesa.md, M13a); a buffer put there is made again + * below it, at an address of our own -- next fit, from where the last one + * went. */ +#define SGX_TILED_VA_START 0xe0000000u + +static struct sgx_bo * +untiled_bo(struct sgx_device *dev, uint32_t size, uint32_t flags) +{ + uint32_t step = size >= 0x10000 ? 0x10000 : 0x1000; + uint32_t top = (SGX_TILED_VA_START - align(size, 0x1000) - 0x1000) & ~(step - 1); + uint32_t bottom = MAX2(dev->va_start, dev->code_va_end); + uint32_t va = MIN2(dev->untiled_next, top) & ~(step - 1); + + for (unsigned wrapped = 0; wrapped < 2; wrapped++, va = top) { + for (; va >= bottom && va <= top; va -= step) { + struct sgx_bo *bo = sgx_bo_create(dev, size, flags | APPLE_SGX_BO_FIXED_VA, va); + + if (bo) { + dev->untiled_next = va - 0x1000; + return bo; + } + if (errno != EEXIST) + return NULL; + } + } + mesa_loge("sgx: no room for %u bytes below the tiled window", size); + return NULL; +} + +struct sgx_bo * +sgx_bo_create(struct sgx_device *dev, uint32_t size, uint32_t flags, uint32_t va) +{ + struct drm_apple_sgx_gem_create c = { + .size = size, .flags = flags | extra_bo_flags(), .va = va, + }; + struct sgx_bo *bo; + + /* a fixed address that is taken (EEXIST) is the caller's to report */ + sgx_ioctls[SGX_IOCTL_CREATE]++; + if (drmIoctl(dev->fd, DRM_IOCTL_APPLE_SGX_GEM_CREATE, &c)) { + if (errno != EEXIST) + mesa_loge("sgx: GEM_CREATE %u bytes: %s", size, strerror(errno)); + return NULL; + } + if (!(flags & APPLE_SGX_BO_FIXED_VA) && c.va + size > SGX_TILED_VA_START) { + struct drm_gem_close cl = { .handle = c.handle }; + + drmIoctl(dev->fd, DRM_IOCTL_GEM_CLOSE, &cl); + return untiled_bo(dev, size, flags); + } + bo = CALLOC_STRUCT(sgx_bo); + if (!bo) { + struct drm_gem_close cl = { .handle = c.handle }; + + drmIoctl(dev->fd, DRM_IOCTL_GEM_CLOSE, &cl); + return NULL; + } + bo->dev = dev; + bo->handle = c.handle; + bo->va = c.va; + bo->size = (size + 0xfff) & ~0xfffu; + simple_mtx_lock(&dev->bo_lock); + _mesa_hash_table_u64_insert(dev->bos, bo->handle, bo); + simple_mtx_unlock(&dev->bo_lock); + return bo; +} + +struct sgx_bo * +sgx_bo_import(struct sgx_device *dev, uint32_t handle) +{ + struct drm_apple_sgx_gem_info info = { .handle = handle }; + struct sgx_bo *bo; + + simple_mtx_lock(&dev->bo_lock); + if ((bo = _mesa_hash_table_u64_search(dev->bos, handle))) { + bo->refs++; + simple_mtx_unlock(&dev->bo_lock); + return bo; + } + if (dev->uapi < 2 || drmIoctl(dev->fd, DRM_IOCTL_APPLE_SGX_GEM_INFO, &info) || + !(bo = CALLOC_STRUCT(sgx_bo))) { + struct drm_gem_close cl = { .handle = handle }; + + simple_mtx_unlock(&dev->bo_lock); + mesa_logw_once("sgx: a buffer from elsewhere (a dma-buf) cannot be used%s", + dev->uapi < 2 ? ": the kernel has no GEM_INFO (before 2026-10-08)" : ""); + drmIoctl(dev->fd, DRM_IOCTL_GEM_CLOSE, &cl); + return NULL; + } + bo->dev = dev; + bo->handle = handle; + bo->va = info.va; + bo->size = info.size; + _mesa_hash_table_u64_insert(dev->bos, handle, bo); + simple_mtx_unlock(&dev->bo_lock); + return bo; +} + +void * +sgx_bo_map(struct sgx_bo *bo) +{ + struct drm_apple_sgx_gem_mmap_offset m = { .handle = bo->handle }; + void *p; + + if (bo->map) + return bo->map; + sgx_ioctls[SGX_IOCTL_MMAP]++; + if (drmIoctl(bo->dev->fd, DRM_IOCTL_APPLE_SGX_GEM_MMAP_OFFSET, &m)) + return NULL; + p = mmap(NULL, bo->size, PROT_READ | PROT_WRITE, MAP_SHARED, bo->dev->fd, + (off_t)m.offset); + if (p == MAP_FAILED) + return NULL; + bo->map = p; + return p; +} + +static void +close_bo(struct sgx_bo *bo) +{ + struct drm_gem_close cl = { .handle = bo->handle }; + + simple_mtx_lock(&bo->dev->bo_lock); + _mesa_hash_table_u64_remove(bo->dev->bos, bo->handle); + simple_mtx_unlock(&bo->dev->bo_lock); + if (bo->map) + munmap(bo->map, bo->size); + sgx_fence_reference(&bo->busy, NULL); + drmIoctl(bo->dev->fd, DRM_IOCTL_GEM_CLOSE, &cl); + FREE(bo); +} + +/* The cache (M26): what it keeps all told, and for how long */ +#define CACHE_MAX_BYTES (32u << 20) +#define CACHE_MAX_AGE_NS (2ll * 1000 * 1000 * 1000) + +/* the cache's buffers kept too long, or past its size, closed (under + * cache_lock) */ +static void +cache_trim(struct sgx_device *dev, int64_t now) +{ + list_for_each_entry_safe(struct sgx_bo, bo, &dev->cache, cache_link) { + if (dev->cache_size <= CACHE_MAX_BYTES && now - bo->freed < CACHE_MAX_AGE_NS) + break; + list_del(&bo->cache_link); + dev->cache_size -= bo->size; + close_bo(bo); + } +} + +void +sgx_bo_destroy(struct sgx_bo *bo) +{ + if (!bo) + return; + simple_mtx_lock(&bo->dev->bo_lock); + if (bo->refs) { + bo->refs--; + simple_mtx_unlock(&bo->dev->bo_lock); + return; + } + simple_mtx_unlock(&bo->dev->bo_lock); + if (bo->cached) { + struct sgx_device *dev = bo->dev; + + simple_mtx_lock(&dev->cache_lock); + bo->freed = os_time_get_nano(); + bo->batch_ctx = NULL; + list_addtail(&bo->cache_link, &dev->cache); + dev->cache_size += bo->size; + cache_trim(dev, bo->freed); + simple_mtx_unlock(&dev->cache_lock); + return; + } + close_bo(bo); +} + +void +sgx_bo_set_busy(struct sgx_bo *bo, struct sgx_fence *done) +{ + simple_mtx_lock(&bo->dev->bo_lock); + sgx_fence_reference(&bo->busy, done); + simple_mtx_unlock(&bo->dev->bo_lock); +} + +bool +sgx_bo_idle(struct sgx_bo *bo) +{ + struct sgx_fence *f = NULL; + bool idle; + + simple_mtx_lock(&bo->dev->bo_lock); + sgx_fence_reference(&f, bo->busy); + simple_mtx_unlock(&bo->dev->bo_lock); + idle = !f || sgx_fence_wait(f, 0); + sgx_fence_reference(&f, NULL); + return idle; +} + +void +sgx_bo_ref(struct sgx_bo *bo) +{ + simple_mtx_lock(&bo->dev->bo_lock); + bo->refs++; + simple_mtx_unlock(&bo->dev->bo_lock); +} + +/* sizes in classes, an eighth of the next power of two apart (whole pages + * up to 64 KiB): what a cached buffer of one class can be used for again */ +static uint32_t +cache_class(uint32_t size) +{ + size = align(MAX2(size, 1), 4096); + return size <= 0x10000 ? util_next_power_of_two(size) : + align(size, util_next_power_of_two(size) / 8); +} + +struct sgx_bo * +sgx_bo_cache_get(struct sgx_device *dev, uint32_t size) +{ + struct sgx_bo *found = NULL; + unsigned tries = 0; + + size = cache_class(size); + simple_mtx_lock(&dev->cache_lock); + cache_trim(dev, os_time_get_nano()); + /* the oldest of the size first: the likeliest to be idle (two looked + * at, an ioctl each) */ + list_for_each_entry(struct sgx_bo, bo, &dev->cache, cache_link) { + if (bo->size != size) + continue; + if (sgx_bo_idle(bo)) { + found = bo; + list_del(&bo->cache_link); + dev->cache_size -= bo->size; + break; + } + if (++tries == 2) + break; + } + simple_mtx_unlock(&dev->cache_lock); + if (found) + return found; + if (!(found = sgx_bo_create(dev, size, 0, 0))) + return NULL; + if (!sgx_bo_map(found)) { + sgx_bo_destroy(found); + return NULL; + } + found->cached = true; + return found; +} + +bool +sgx_bo_wait(struct sgx_bo *bo, int64_t timeout_ns) +{ + struct drm_apple_sgx_gem_wait w = { + .handle = bo->handle, + .timeout_ns = timeout_ns < 0 ? INT64_MAX : + timeout_ns ? os_time_get_absolute_timeout(timeout_ns) : 0, + }; + + sgx_ioctls[SGX_IOCTL_WAIT]++; + return !drmIoctl(bo->dev->fd, DRM_IOCTL_APPLE_SGX_GEM_WAIT, &w); +} + +struct sgx_fence * +sgx_fence_create(struct sgx_device *dev, bool signalled) +{ + struct sgx_fence *f = CALLOC_STRUCT(sgx_fence); + + if (!f) + return NULL; + if (drmSyncobjCreate(dev->fd, signalled ? DRM_SYNCOBJ_CREATE_SIGNALED : 0, + &f->syncobj)) { + FREE(f); + return NULL; + } + pipe_reference_init(&f->reference, 1); + f->dev = dev; + return f; +} + +void +sgx_fence_reference(struct sgx_fence **ptr, struct sgx_fence *f) +{ + struct sgx_fence *old = *ptr; + + if (pipe_reference(old ? &old->reference : NULL, f ? &f->reference : NULL)) { + drmSyncobjDestroy(old->dev->fd, old->syncobj); + FREE(old); + } + *ptr = f; +} + +/* the time spent waiting for fences, all told, and the ioctls by kind + * (SGX_DEBUG=fps) */ +int64_t sgx_fence_waited; +unsigned sgx_ioctls[SGX_IOCTL_KINDS]; +unsigned sgx_stat_same, sgx_stat_verts, sgx_stat_tex_changes, sgx_stat_merged; +uint64_t sgx_stat_up[SGX_UP_KINDS]; +int64_t sgx_stat_up_ns; +int64_t sgx_submit_ns; +uint64_t sgx_submit_handles; + +uint64_t +sgx_fence_signal_time(struct sgx_fence *f) +{ + struct sync_fence_info fi[4] = { 0 }; + struct sync_file_info info = { + .num_fences = 4, + .sync_fence_info = (uint64_t)(uintptr_t)fi, + }; + uint64_t t = 0; + int fd = -1; + + if (!f || drmSyncobjExportSyncFile(f->dev->fd, f->syncobj, &fd)) + return 0; + if (!ioctl(fd, SYNC_IOC_FILE_INFO, &info) && info.status == 1) + for (unsigned i = 0; i < MIN2(info.num_fences, 4); i++) + t = MAX2(t, fi[i].timestamp_ns); + close(fd); + return t; +} + +bool +sgx_fence_wait(struct sgx_fence *f, uint64_t timeout_ns) +{ + static int trace = -1; + int64_t abs = timeout_ns == OS_TIMEOUT_INFINITE ? INT64_MAX : + os_time_get_absolute_timeout(timeout_ns), t0 = os_time_get_nano(); + bool done = !drmSyncobjWait(f->dev->fd, &f->syncobj, 1, abs, + DRM_SYNCOBJ_WAIT_FLAGS_WAIT_FOR_SUBMIT, NULL); + + sgx_fence_waited += os_time_get_nano() - t0; + /* SGX_TRACE_WAITS: who waited a millisecond or more */ + if (trace < 0) + trace = getenv("SGX_TRACE_WAITS") != NULL; + if (trace && os_time_get_nano() - t0 > 1000000) { + Dl_info di; + void *ra = __builtin_return_address(0); + + if (dladdr(ra, &di)) + mesa_logi("sgx: waited %.1f ms for a fence, from %s+0x%lx", (os_time_get_nano() - t0) / 1e6, + di.dli_sname ? di.dli_sname : "?", (unsigned long)((char *)ra - (char *)di.dli_fbase)); + } + return done; +} + +/* SGX_CC: SGXMKIF_CC_* for every kick, on top of the MMU invalidation the + * kernel adds after mapping changes -- 8 (INVAL_DATA) has the microkernel + * drop the GPU's data caches, which know addresses, not buffers + * (mesa/frame-bisect tries it) */ +static uint32_t +submit_cache_control(void) +{ + static int cc = -1; + + if (cc < 0) + cc = getenv("SGX_CC") ? strtoul(getenv("SGX_CC"), NULL, 0) & 0xff : 0; + return cc; +} + +int +sgx_submit(struct sgx_device *dev, const uint32_t *cmd, uint32_t pb_va, + uint32_t details_handle, uint32_t details_offset, + const uint32_t *handles, unsigned count, struct sgx_fence *done) +{ + struct drm_apple_sgx_submit s = { + .cache_control = submit_cache_control(), + .cmd = (uintptr_t)cmd, + .cmd_size = cmd[0], + .pb_va = pb_va, + .details_handle = details_handle, + .details_offset = details_offset, + .bo_handles = (uintptr_t)handles, + .bo_handle_count = count, + .out_sync = done ? done->syncobj : 0, + .in_syncs = (uintptr_t)dev->wait_syncs, + .in_sync_count = dev->nwait_syncs, + }; + int ret = 0; + + sgx_ioctls[SGX_IOCTL_SUBMIT]++; + int64_t t0 = os_time_get_nano(); + int r = drmIoctl(dev->fd, DRM_IOCTL_APPLE_SGX_SUBMIT, &s); + + sgx_submit_ns += os_time_get_nano() - t0; + sgx_submit_handles += count; + if (r) { + mesa_loge("sgx: SUBMIT: %s", strerror(errno)); + ret = -errno; + } + for (unsigned i = 0; i < dev->nwait_syncs; i++) + drmSyncobjDestroy(dev->fd, dev->wait_syncs[i]); + dev->nwait_syncs = 0; + return ret; +} + +#if defined(__arm__) +__attribute__((target("fpu=neon"))) void +sgx_copy(void *dst, const void *src, size_t n) +{ + uint8_t *d = dst; + const uint8_t *s = src; + + for (; n >= 64; n -= 64, d += 64, s += 64) { + __builtin_prefetch(s + 128); + __builtin_prefetch(s + 160); + vst1q_u8_x4(d, vld1q_u8_x4(s)); + } + memcpy(d, s, n); +} +#else +void +sgx_copy(void *dst, const void *src, size_t n) +{ + memcpy(dst, src, n); +} +#endif + +void +sgx_trace_mark(const char *what) +{ + static int on = -1; + static int64_t last; + int64_t now; + + if (on < 0) + on = getenv("SGX_TRACE") && atoi(getenv("SGX_TRACE")); + if (!on) + return; + now = os_time_get_nano(); + mesa_logi("sgx: mark %8.3f (+%7.3f ms) %s", (now / 1000000) % 100000 / 1000.0, + last ? (now - last) / 1e6 : 0.0, what); + last = now; +} + +int +sgx_fence_export(struct sgx_fence *f) +{ + int fd = -1; + + if (drmSyncobjExportSyncFile(f->dev->fd, f->syncobj, &fd)) + return -1; + return fd; +} + +struct sgx_fence * +sgx_fence_import(struct sgx_device *dev, int fd) +{ + struct sgx_fence *f = sgx_fence_create(dev, false); + + if (f && drmSyncobjImportSyncFile(dev->fd, f->syncobj, fd)) + sgx_fence_reference(&f, NULL); + return f; +} diff --git a/src/gallium/drivers/sgx/sgx_device.h b/src/gallium/drivers/sgx/sgx_device.h new file mode 100644 index 00000000000..be9cfb945f0 --- /dev/null +++ b/src/gallium/drivers/sgx/sgx_device.h @@ -0,0 +1,150 @@ +/* + * Copyright 2026 Project Cascadia + * SPDX-License-Identifier: MIT + * + * The render node (include/drm-uapi/apple_sgx_drm.h), thinly: what the + * kernel reports, buffers, submits, fences. + */ +#ifndef SGX_DEVICE_H +#define SGX_DEVICE_H + +#include +#include + +#include "util/list.h" +#include "util/simple_mtx.h" +#include "util/u_inlines.h" + +struct hash_table_u64; + +struct sgx_device { + int fd; + uint32_t uapi, core_id, core_rev, num_cores; + bool rc2; /* the A6 (S5L8950X, rev 2.x): its kext's render target layout */ + uint32_t bo_flags; /* the APPLE_SGX_BO_* flags the kernel takes (0: before SCANOUT) */ + uint32_t va_start, va_end; + uint32_t code_base, code_va_start, code_va_end; + uint32_t fb_va, fb_width, fb_height, fb_stride; + uint32_t untiled_next; /* sgx_bo_create, on kernels that pick tiled addresses */ + + /* every buffer object by its handle: a dma-buf of ours imported again + * comes back as the same handle, and has to be the same sgx_bo */ + simple_mtx_t bo_lock; + struct hash_table_u64 *bos; + + /* fences the next submit waits for on the GPU (fence_server_sync: a + * compositor's or the display's, through sync files) */ + uint32_t wait_syncs[16]; + unsigned nwait_syncs; + + /* buffer objects of buffers no resource holds any more, kept to be + * used again once no render reads them (M26: a vertex buffer made anew + * each frame cost an ioctl and the pages cleared and cleaned), oldest + * first */ + simple_mtx_t cache_lock; + struct list_head cache; + uint64_t cache_size; +}; + +struct sgx_bo { + struct sgx_device *dev; + uint32_t handle; + uint32_t va; /* its GPU address */ + uint32_t size; + uint8_t *map; /* write-combined; NULL until sgx_bo_map() */ + unsigned refs; /* references besides the first (sgx_bo_ref(), imports); under bo_lock */ + /* a buffer's (sgx_bo_cache_get()): back into the cache when the last + * reference goes, when it went there, its place in it */ + bool cached; + int64_t freed; + struct list_head cache_link; + /* the gathered draws that read it, if they are not rendered yet: their + * context and batch number (sgx_draw.c) */ + const void *batch_ctx; + unsigned batch_seq; + /* a cached one's: the last render that listed it (under bo_lock) */ + struct sgx_fence *busy; +}; + +/* A fence: one syncobj, signalled when the render it was given to is done + * (or created signalled). */ +struct sgx_fence { + struct pipe_reference reference; + struct sgx_device *dev; + uint32_t syncobj; +}; + +/* (M43) when f was signalled, CLOCK_MONOTONIC ns (the kernel's dma-fence + * timestamp, through a sync file); 0 if not yet or not known */ +uint64_t sgx_fence_signal_time(struct sgx_fence *f); + +bool sgx_device_init(struct sgx_device *dev, int fd); +void sgx_device_fini(struct sgx_device *dev); +uint64_t sgx_device_param(struct sgx_device *dev, uint32_t param); + +/* flags: APPLE_SGX_BO_*; va only with APPLE_SGX_BO_FIXED_VA */ +struct sgx_bo *sgx_bo_create(struct sgx_device *dev, uint32_t size, uint32_t flags, + uint32_t va); +/* a handle on this device (from a dma-buf, say): its buffer object, the + * one there is already if the handle has one (another reference to it); + * NULL on a kernel without GEM_INFO */ +struct sgx_bo *sgx_bo_import(struct sgx_device *dev, uint32_t handle); +/* drops a reference: the last one closes the handle (or puts a cached one + * back in the cache) */ +void sgx_bo_destroy(struct sgx_bo *bo); +void sgx_bo_ref(struct sgx_bo *bo); +/* a cached buffer object (sgx_bo_cache_get) listed by the render done + * signals, and whether the last one that listed it is done -- without the + * kernel's GEM_WAIT, whose zero timeout waits a jiffy for a busy one */ +void sgx_bo_set_busy(struct sgx_bo *bo, struct sgx_fence *done); +bool sgx_bo_idle(struct sgx_bo *bo); +/* A mapped buffer object of at least size bytes for a buffer resource: the + * cache's oldest of its size that no render reads any more, or a new one */ +struct sgx_bo *sgx_bo_cache_get(struct sgx_device *dev, uint32_t size); +void *sgx_bo_map(struct sgx_bo *bo); +/* until no render that listed it is running (timeout_ns < 0: however long + * it takes); false on timeout */ +bool sgx_bo_wait(struct sgx_bo *bo, int64_t timeout_ns); + +struct sgx_fence *sgx_fence_create(struct sgx_device *dev, bool signalled); +void sgx_fence_reference(struct sgx_fence **ptr, struct sgx_fence *f); +bool sgx_fence_wait(struct sgx_fence *f, uint64_t timeout_ns); +/* a sync file of the fence (-1: none), and a fence from one */ +int sgx_fence_export(struct sgx_fence *f); +struct sgx_fence *sgx_fence_import(struct sgx_device *dev, int fd); +extern int64_t sgx_fence_waited; +/* SGX_TRACE=1: a line with the time since the last mark */ +void sgx_trace_mark(const char *what); +/* (M46) memcpy for big copies -- a buffer's bytes into its GPU copy, a + * draw's vertices into the render's memory: musl's ARM memcpy has no + * preloads (taken out for older cores), and where the L2 does not + * prefetch either (the mini's tree; the K93's turns it on) each 32-byte + * line it reads waits for memory: 255 MB/s for 3 MB. 64 bytes a round + * through NEON, with PLDs four and five lines ahead: 820 MB/s into + * write-combined memory (~710 for memcpy with the L2 prefetching; reading + * write-combined memory stays ~240 MB/s whatever does it). */ +void sgx_copy(void *dst, const void *src, size_t n); +enum { SGX_IOCTL_CREATE, SGX_IOCTL_MMAP, SGX_IOCTL_WAIT, SGX_IOCTL_SUBMIT, SGX_IOCTL_KINDS }; +extern unsigned sgx_ioctls[SGX_IOCTL_KINDS]; +/* SGX_DEBUG=fps: draws whose state was the last one's, vertices, textures */ +extern unsigned sgx_stat_same, sgx_stat_verts, sgx_stat_tex_changes, sgx_stat_merged; +/* SGX_DEBUG=fps (M46): bytes of buffer uploads -- glBufferSubData's + * straight into the GPU copy, into the CPU copy, the CPU copy's copied on + * into the GPU's for a draw, read back from the GPU copy; maps that were + * the GPU copy itself, and of those the ones a fresh copy took (a render + * read the last) -- and the time the first took */ +enum { SGX_UP_DIRECT, SGX_UP_CPU, SGX_UP_ON, SGX_UP_BACK, SGX_UP_MAPPED, SGX_UP_RENAMED, + SGX_UP_KINDS }; +extern uint64_t sgx_stat_up[SGX_UP_KINDS]; +extern int64_t sgx_stat_up_ns; +/* SGX_DEBUG=fps (M46): the time in the submit ioctl, the buffers it lists */ +extern int64_t sgx_submit_ns; +extern uint64_t sgx_submit_handles; + +/* One render. handles[] lists every buffer it touches (the render + * details' among them); done is signalled when its 3D pass is over. */ +int sgx_submit(struct sgx_device *dev, const uint32_t *cmd, uint32_t pb_va, + uint32_t details_handle, uint32_t details_offset, + const uint32_t *handles, unsigned count, struct sgx_fence *done); + +#endif diff --git a/src/gallium/drivers/sgx/sgx_draw.c b/src/gallium/drivers/sgx/sgx_draw.c new file mode 100644 index 00000000000..afdbbb315f2 --- /dev/null +++ b/src/gallium/drivers/sgx/sgx_draw.c @@ -0,0 +1,3445 @@ +/* + * Copyright 2026 Project Cascadia + * SPDX-License-Identifier: MIT + * + * Draws, for now (docs/research/p105-mesa.md, M13a). The vertex shader + * runs on the CPU, in Gallium's draw module (tgsi_exec, as i915 has it): + * it also clips, culls and turns lines and points into triangles. The + * triangles are drawn on the GPU through the template frame, whose programs + * give each pixel the colour interpolated between its triangle's vertices. + * So the fragment shader is not run but read: one whose colour is, channel + * by channel, a constant or a component of a varying or of a uniform is + * drawn right, the colour worked out per vertex here; any other is drawn + * in grey, with a warning once. The vertices go to the GPU as the frame's + * vertex side takes them (M13b): the position, then the colour as a + * varying. Only render targets the frame can fill + * are drawn into (B8G8R8A8, up to 4096 x 4096: M10); depth, stencil, blending, + * scissors and colour masks are not applied yet. Each draw is a render. + */ +#include "sgx_draw.h" + +#include +#include +#include +#include +#include +#include + +#include "compiler/glsl_types.h" +#include "compiler/nir/nir.h" +#include "draw/draw_context.h" +#include "draw/draw_vbuf.h" +#include "draw/draw_vertex.h" +#include "tgsi/tgsi_from_mesa.h" +#include "util/format/u_format.h" +#include "util/format_srgb.h" +#include "util/half_float.h" +#include "util/log.h" +#include "util/os_time.h" +#include "util/u_blitter.h" +#include "util/u_debug.h" +#include "util/u_dump.h" +#include "util/u_inlines.h" +#include "util/u_math.h" +#include "util/u_memory.h" +#include "util/u_prim.h" + +#include "sgx_compiler.h" +#include "sgx_context.h" +#include "sgx_device.h" +#include "sgx_frame.h" +#include "sgx_resource.h" +#include "sgx_screen.h" +#include "sgx_usse.h" + +/* ---- the fragment shader's colour --------------------------------------- */ + +static unsigned +type_size_vec4(const struct glsl_type *type, bool bindless) +{ + return glsl_count_attribute_slots(type, false); +} + +/* where one channel of the colour comes from; false if from anything else */ +static bool +colour_source(nir_scalar s, struct sgx_fs_colour *c, unsigned i) +{ + nir_intrinsic_instr *in; + nir_src *offset; + + s = nir_scalar_chase_movs(s); + if (nir_scalar_is_const(s)) { + c->ch[i].src = SGX_SRC_CONST; + c->ch[i].value = s.def->bit_size == 32 ? nir_scalar_as_float(s) : 0; + return s.def->bit_size == 32; + } + if (!(in = nir_scalar_as_intrinsic(s))) + return false; + switch (in->intrinsic) { + case nir_intrinsic_load_input: + case nir_intrinsic_load_interpolated_input: + offset = nir_get_io_offset_src(in); + if (!offset || !nir_src_is_const(*offset)) + return false; + c->ch[i].src = SGX_SRC_VARYING; + c->ch[i].slot = nir_intrinsic_io_semantics(in).location + nir_src_as_uint(*offset); + c->ch[i].comp = nir_intrinsic_component(in) + s.comp; + return true; + case nir_intrinsic_load_uniform: + /* vec4 slots (the screen does not pack uniforms) */ + if (!nir_src_is_const(in->src[0])) + return false; + c->ch[i].src = SGX_SRC_UNIFORM; + c->ch[i].slot = (nir_intrinsic_base(in) + nir_src_as_uint(in->src[0])) * 4 + s.comp; + return true; + case nir_intrinsic_load_ubo: + /* bytes, buffer 0 */ + if (!nir_src_is_const(in->src[0]) || nir_src_as_uint(in->src[0]) || + !nir_src_is_const(in->src[1])) + return false; + c->ch[i].src = SGX_SRC_UNIFORM; + c->ch[i].slot = nir_src_as_uint(in->src[1]) / 4 + s.comp; + return true; + default: + return false; + } +} + +void +sgx_fs_colour_analyse(const struct nir_shader *fs, struct sgx_fs_colour *out) +{ + nir_shader *nir = nir_shader_clone(NULL, fs); + bool have[4] = { false }; + + memset(out, 0, sizeof(*out)); + NIR_PASS(_, nir, nir_lower_io, nir_var_shader_in | nir_var_shader_out | nir_var_uniform, + type_size_vec4, 0); + NIR_PASS(_, nir, nir_opt_copy_prop); + NIR_PASS(_, nir, nir_opt_constant_folding); + NIR_PASS(_, nir, nir_opt_dce); + + out->ok = true; + nir_foreach_function_impl(impl, nir) { + nir_foreach_block(block, impl) { + nir_foreach_instr(instr, block) { + nir_intrinsic_instr *in; + unsigned loc, mask, comp; + + if (instr->type != nir_instr_type_intrinsic) + continue; + in = nir_instr_as_intrinsic(instr); + if (in->intrinsic == nir_intrinsic_terminate || + in->intrinsic == nir_intrinsic_terminate_if || + in->intrinsic == nir_intrinsic_demote || + in->intrinsic == nir_intrinsic_demote_if) { + out->ok = false; /* discard */ + continue; + } + if (in->intrinsic != nir_intrinsic_store_output) + continue; + loc = nir_intrinsic_io_semantics(in).location; + if (loc != FRAG_RESULT_COLOR && loc != FRAG_RESULT_DATA0) + continue; + if (block->cf_node.parent->type != nir_cf_node_function) + out->ok = false; /* inside control flow: not one value */ + mask = nir_intrinsic_write_mask(in); + comp = nir_intrinsic_component(in); + for (unsigned i = 0; i < in->src[0].ssa->num_components; i++) { + if (!(mask & 1 << i) || comp + i >= 4) + continue; + out->ok &= colour_source(nir_get_scalar(in->src[0].ssa, i), out, comp + i); + have[comp + i] = true; + } + } + } + } + for (unsigned i = 0; i < 4; i++) { + if (!have[i]) { + out->ch[i].src = SGX_SRC_CONST; + out->ch[i].value = i == 3 ? 1.0f : 0.0f; + } + } + ralloc_free(nir); +} + +/* ---- the draw module's back end ----------------------------------------- */ + +/* what the draw module hands over for each vertex: the position (window + * coordinates), then each varying the colour reads, four floats each */ +struct sgx_render { + struct vbuf_render base; + struct sgx_context *ctx; + struct vertex_info vinfo; + unsigned varying[4]; /* the varyings, by gl_varying_slot */ + unsigned nvarying; + enum mesa_prim prim; + uint8_t *vertices; /* the draw module's, vertex_size each */ + unsigned vertex_size, capacity; +}; + +static struct sgx_render * +sgx_render(struct vbuf_render *r) +{ + return (struct sgx_render *)r; +} + +static const struct vertex_info * +render_vertex_info(struct vbuf_render *r) +{ + return &sgx_render(r)->vinfo; +} + +static bool +render_allocate(struct vbuf_render *r, uint16_t vertex_size, uint16_t n) +{ + struct sgx_render *sr = sgx_render(r); + unsigned need = (unsigned)vertex_size * n; + + if (need > sr->capacity) { + uint8_t *p = REALLOC(sr->vertices, sr->capacity, need); + + if (!p) + return false; + sr->vertices = p; + sr->capacity = need; + } + sr->vertex_size = vertex_size; + return true; +} + +static void * +render_map(struct vbuf_render *r) +{ + return sgx_render(r)->vertices; +} + +static void +render_unmap(struct vbuf_render *r, uint16_t min_index, uint16_t max_index) +{ +} + +static void +render_set_primitive(struct vbuf_render *r, enum mesa_prim prim) +{ + sgx_render(r)->prim = prim; +} + +static void +render_set_view_index(struct vbuf_render *r, unsigned view_index) +{ +} + +/* (M39) unit's texture's 1 / width, 1 / height: a rectangle texture's + * coordinates scaled as the sampler takes them */ +static void +fix_scale(struct sgx_context *ctx, unsigned unit, float *scale) +{ + struct pipe_sampler_view *view = unit < ARRAY_SIZE(ctx->fs_views) ? ctx->fs_views[unit] : NULL; + + /* (the view's first level: M46's copies of one, a rectangle's only) */ + if (view && view->texture) { + scale[0] = 1.0f / u_minify(view->texture->width0, view->u.tex.first_level); + scale[1] = 1.0f / u_minify(view->texture->height0, view->u.tex.first_level); + } else { + scale[0] = scale[1] = 1; + } +} + +/* What the vertex side does to the varyings the PDS's lookups alone read + * (M39, sgx_fs.vary_fix): x and y scaled, the divisor where the PDS's + * projective lookup divides. v: the varyings, four floats each. */ +static void +fix_varyings(struct sgx_context *ctx, const struct sgx_fs *fs, unsigned n, float *v) +{ + for (unsigned k = 0; k < n; k++, v += 4) { + unsigned fix = fs->vary_fix[k]; + + if (fix & SGX_FIX_SCALE) { + float scale[2]; + + fix_scale(ctx, fs->vary_unit[k], scale); + v[0] *= scale[0]; + v[1] *= scale[1]; + } + if (SGX_FIX_DIV(fix) && SGX_FIX_DIV(fix) != SGX_PROJ_DIV) + v[SGX_PROJ_DIV] = v[SGX_FIX_DIV(fix)]; + /* (M46) a lookup's coordinates moved into x and y */ + if (SGX_FIX_SHIFT_OF(fix)) { + v[0] = v[SGX_FIX_SHIFT_OF(fix)]; + v[1] = v[SGX_FIX_SHIFT_OF(fix) + 1]; + } + } +} + +/* one vertex, as the frame's vertex side takes it: x y over the target, z + * 0, w 1, then the varyings -- the colour, and with SGX_DRAW_LAYOUT the + * fillers around it */ +static void +emit_vertex(struct sgx_render *sr, const float *in, float *out) +{ + struct sgx_context *ctx = sr->ctx; + const struct sgx_fs_colour *c = ctx->fs ? &ctx->fs->colour : NULL; + const float *cb = ctx->fs_constants; + const struct sgx_frame_layout *l = &ctx->layout; + + /* clip coordinates, as a vertex shader would hand them to the TA (it + * divides by w, and interpolates the varyings with it): the draw + * module's window coordinates back to -1..1 -- z too, the frame's + * viewport takes it to depth as z / 2 + 1 / 2 -- times w, which the + * draw module keeps as 1 / w */ + float w = in[3] > 0 ? 1 / in[3] : 1; + + out[0] = (in[0] * 2 / ctx->fb.width - 1) * w; + out[1] = (in[1] * 2 / ctx->fb.height - 1) * w; + out[2] = (in[2] * 2 - 1) * w; + out[3] = w; + if (ctx->draw_fs) { + /* the program's inputs, as the draw module has them */ + memcpy(out + 4, in + 4, 4 * l->nvaryings * sizeof(float)); + fix_varyings(ctx, ctx->draw_fs, l->nvaryings, out + 4); + return; + } + for (unsigned k = 0; k < l->nvaryings; k++) { + /* a filler: a colour the checks would notice */ + out[4 + 4 * k + 0] = 1; + out[4 + 4 * k + 1] = 0; + out[4 + 4 * k + 2] = 1; + out[4 + 4 * k + 3] = (k + 1) / 16.0f; + } + out += 4 + 4 * l->colour; + for (unsigned i = 0; i < 4; i++) { + float v = 0.5f; + + if (c && c->ok) { + switch (c->ch[i].src) { + case SGX_SRC_CONST: + v = c->ch[i].value; + break; + case SGX_SRC_UNIFORM: + v = cb && c->ch[i].slot < ctx->fs_constants_size / 4 ? cb[c->ch[i].slot] : 0; + break; + case SGX_SRC_VARYING: + v = 0; + for (unsigned k = 0; k < sr->nvarying; k++) + if (sr->varying[k] == c->ch[i].slot) + v = in[4 + 4 * k + c->ch[i].comp]; + break; + } + } + out[i] = CLAMP(v, 0.0f, 1.0f); + } +} + +static void +render_vertex(struct sgx_render *sr, const float *in) +{ + struct sgx_context *ctx = sr->ctx; + unsigned vf = sgx_frame_vertex_floats(&ctx->layout); + + if ((ctx->nverts + 1) * vf > ctx->maxfloats) { + unsigned n = MAX2(ctx->maxfloats * 2, 3 * 256 * vf); + float *p = REALLOC(ctx->verts, ctx->maxfloats * sizeof(float), n * sizeof(float)); + + if (!p) + return; + ctx->verts = p; + ctx->maxfloats = n; + } + /* the triangles as the draw module wound them: the TA culls nothing + * (state word 18, M18), and gl_FrontFacing reads the winding */ + emit_vertex(sr, in, ctx->verts + ctx->nverts++ * vf); +} + +/* (M43) ARB_depth_clamp: a triangle's depth clamped to the depth range, + * the near and far planes clipping nothing (the draw module's z clipping + * is off with them). The ISP clamps no depth (gloffset --clamp, M38), so + * the triangle is cut where its depth crosses an end of the range -- a + * line across it on the screen, window z being linear there -- and the + * parts past the ends drawn at the end's depth, a fan each: exactly the + * clamped depths. A new vertex's varyings are perspective-correct (1 / w + * and v / w linear on the screen); with flat shading every vertex has the + * provoking one's colours. Without depth clamping the same keeps depth in + * 0..1 (the draw module's polygon offset may take it past). */ +#define CLAMP_FLOATS (4 + 4 * 16) +#define CLAMP_MAX_VERTS 6 + +struct clamp_poly { + float v[CLAMP_MAX_VERTS][CLAMP_FLOATS]; + unsigned n; +}; + +/* the part of in on one side of window z = zc: below (z <= zc) or not */ +static void +clamp_cut(const struct clamp_poly *in, unsigned nf, float zc, bool below, struct clamp_poly *out) +{ + out->n = 0; + for (unsigned i = 0; i < in->n; i++) { + const float *a = in->v[i], *b = in->v[(i + 1) % in->n]; + bool ain = below ? a[2] <= zc : a[2] >= zc, bin = below ? b[2] <= zc : b[2] >= zc; + + if (ain && out->n < CLAMP_MAX_VERTS) + memcpy(out->v[out->n++], a, nf * sizeof(float)); + if (ain != bin && out->n < CLAMP_MAX_VERTS) { + float t = (zc - a[2]) / (b[2] - a[2]), *o = out->v[out->n++]; + float q = a[3] + t * (b[3] - a[3]); + + o[0] = a[0] + t * (b[0] - a[0]); + o[1] = a[1] + t * (b[1] - a[1]); + o[2] = zc; + o[3] = q; + for (unsigned k = 4; k < nf; k++) + o[k] = q != 0 ? (a[k] * a[3] + t * (b[k] * b[3] - a[k] * a[3])) / q : a[k]; + } + } +} + +static void +clamp_emit(struct sgx_render *sr, struct clamp_poly *p, unsigned nf, const float *flat, + unsigned nflat, bool at, float z) +{ + for (unsigned i = 0; i < p->n; i++) { + if (at) + p->v[i][2] = z; + if (flat) + memcpy(p->v[i] + 4, flat + 4, nflat * sizeof(float)); + } + for (unsigned i = 1; i + 1 < p->n; i++) { + render_vertex(sr, p->v[0]); + render_vertex(sr, p->v[i]); + render_vertex(sr, p->v[i + 1]); + } +} + +static void +render_triangle(struct sgx_render *sr, unsigned i0, unsigned i1, unsigned i2) +{ + struct sgx_context *ctx = sr->ctx; + const struct pipe_rasterizer_state *r = ctx->rast; + const float *v[3] = { + (const float *)(sr->vertices + i0 * sr->vertex_size), + (const float *)(sr->vertices + i1 * sr->vertex_size), + (const float *)(sr->vertices + i2 * sr->vertex_size), + }; + unsigned nf = sr->vertex_size / sizeof(float); + + if (r && nf <= CLAMP_FLOATS) { + float n = ctx->viewport.translate[2] - (r->clip_halfz ? 0 : ctx->viewport.scale[2]); + float f = ctx->viewport.translate[2] + ctx->viewport.scale[2]; + float lo = ctx->depth_clamp ? CLAMP(MIN2(n, f), 0.0f, 1.0f) : 0; + float hi = ctx->depth_clamp ? CLAMP(MAX2(n, f), 0.0f, 1.0f) : 1; + + if (v[0][2] < lo || v[1][2] < lo || v[2][2] < lo || + v[0][2] > hi || v[1][2] > hi || v[2][2] > hi) { + struct clamp_poly t = { .n = 3 }, part, rest; + /* (the TA's flat colours: the layout's first ncolours varyings, + * from the triangle's last vertex) */ + const float *flat = r->flatshade && ctx->layout.ncolours ? v[2] : NULL; + unsigned nflat = MIN2(4 * ctx->layout.ncolours, nf - 4); + + for (unsigned i = 0; i < 3; i++) + memcpy(t.v[i], v[i], nf * sizeof(float)); + clamp_cut(&t, nf, lo, true, &part); + clamp_emit(sr, &part, nf, flat, nflat, true, lo); + clamp_cut(&t, nf, lo, false, &rest); + clamp_cut(&rest, nf, hi, false, &part); + clamp_emit(sr, &part, nf, flat, nflat, true, hi); + clamp_cut(&rest, nf, hi, true, &part); + clamp_emit(sr, &part, nf, flat, nflat, false, 0); + return; + } + } + for (unsigned i = 0; i < 3; i++) + render_vertex(sr, v[i]); +} + +static uint32_t isp_offset(const struct pipe_rasterizer_state *r); + +/* (M37) flat colours from a triangle's first vertex (ARB_provoking_vertex): + * the TSP takes its last one's whatever state word 18 says (gldesk), so + * each triangle is turned round to end with it -- the winding the same */ +static bool +flat_first(const struct sgx_context *ctx) +{ + return ctx->draw_fs && ctx->draw_fs->prog.ncolours && ctx->rast && + ctx->rast->flatshade_first; +} + +/* the i-th vertex of a list of triangles, turned (b, c, a) or not */ +static inline unsigned +turned(unsigned i, bool turn) +{ + return turn ? i - i % 3 + (i % 3 + 1) % 3 : i; +} + +static void +render_draw_elements(struct vbuf_render *r, const uint16_t *indices, unsigned n) +{ + struct sgx_render *sr = sgx_render(r); + bool turn = flat_first(sr->ctx); + + if (sr->prim != MESA_PRIM_TRIANGLES) { + mesa_logw_once("sgx: %s left over by the draw module: dropped", + u_prim_name(sr->prim)); + return; + } + for (unsigned i = 0; i + 2 < n; i += 3) + render_triangle(sr, indices[turned(i, turn)], indices[turned(i + 1, turn)], + indices[turned(i + 2, turn)]); +} + +static void +render_draw_arrays(struct vbuf_render *r, unsigned start, unsigned n) +{ + struct sgx_render *sr = sgx_render(r); + bool turn = flat_first(sr->ctx); + + if (sr->prim != MESA_PRIM_TRIANGLES) { + mesa_logw_once("sgx: %s left over by the draw module: dropped", + u_prim_name(sr->prim)); + return; + } + for (unsigned i = 0; i + 2 < n; i += 3) + render_triangle(sr, start + turned(i, turn), start + turned(i + 1, turn), + start + turned(i + 2, turn)); +} + +static void +render_release(struct vbuf_render *r) +{ +} + +static void +render_destroy(struct vbuf_render *r) +{ + FREE(sgx_render(r)->vertices); + FREE(r); +} + +static bool +render_need_pipeline(const struct vbuf_render *r, const struct pipe_rasterizer_state *rast, + unsigned prim) +{ + return true; /* everything as triangles, one by one */ +} + +/* One varying of the draw module's output vertex, four floats, named as + * nir_to_tgsi names the vertex shader's outputs: VARn is GENERIC n (no + * shift here), the rest as TGSI has them */ +static void +emit_varying(struct sgx_context *ctx, struct vertex_info *vinfo, unsigned slot) +{ + unsigned name, index; + int out; + + if (slot >= VARYING_SLOT_VAR0 && slot < VARYING_SLOT_PATCH0) { + name = TGSI_SEMANTIC_GENERIC; + index = slot - VARYING_SLOT_VAR0; + } else { + tgsi_get_gl_varying_semantic(slot, true, &name, &index); + } + out = draw_find_shader_output(ctx->draw, name, index); + draw_emit_vertex_attr(vinfo, EMIT_4F, out); + if (ctx->debug_draw && out < 0) + mesa_logi("sgx: the fragment shader reads varying slot %u (TGSI %u %u), which the " + "vertex shader does not write", slot, name, index); +} + +/* What goes to the GPU: the position and the colour, as a varying. + * SGX_DRAW_LAYOUT=N[,K][,f32] (a test of the frame's vertex side) makes + * that N varyings, the colour the K-th (the last by default), F32 or + * not, the rest fillers. */ +static struct sgx_frame_layout +draw_layout(void) +{ + static struct sgx_frame_layout l; + static bool parsed; + + if (!parsed) { + const char *env = getenv("SGX_DRAW_LAYOUT"); + char *e; + + l.nvaryings = 1; + if (env && *env) { + l.nvaryings = CLAMP(strtoul(env, &e, 0), 1, SGX_FRAME_MAX_VARYINGS); + l.colour = l.nvaryings - 1; + if (*e == ',' && e[1] >= '0' && e[1] <= '9') + l.colour = MIN2(strtoul(e + 1, &e, 0), l.nvaryings - 1); + if (strstr(env, "f32")) + l.f32 = 1u << l.colour; + mesa_logi("sgx: SGX_DRAW_LAYOUT: %u varyings, the colour the %u-th%s", + l.nvaryings, l.colour, l.f32 ? ", F32" : ""); + } + parsed = true; + } + return l; +} + +/* The vertex layout for the bound shaders: the position, then the varyings + * the fragment colour reads (as the vertex shader's outputs are named) */ +static void +update_vertex_info(struct sgx_context *ctx) +{ + struct sgx_render *sr = sgx_render(ctx->render); + const struct sgx_fs_colour *c = ctx->fs ? &ctx->fs->colour : NULL; + struct vertex_info *vinfo = &sr->vinfo; + + memset(vinfo, 0, sizeof(*vinfo)); + sr->nvarying = 0; + draw_emit_vertex_attr(vinfo, EMIT_4F, + draw_find_shader_output(ctx->draw, TGSI_SEMANTIC_POSITION, 0)); + if (ctx->draw_fs) { + /* a compiled fragment shader: its inputs, in its order, all F32 */ + const struct sgx_fs *fs = ctx->draw_fs; + + for (unsigned i = 0; i < fs->prog.nvaryings; i++) + emit_varying(ctx, vinfo, fs->varying_slot[i]); + draw_compute_vertex_size(vinfo); + ctx->layout.nvaryings = fs->prog.nvaryings; + ctx->layout.f32 = (1u << fs->prog.nvaryings) - 1; + ctx->layout.colour = 0; + ctx->layout.ncolours = fs->prog.ncolours; + return; + } + for (unsigned i = 0; c && c->ok && i < 4; i++) { + unsigned k; + + if (c->ch[i].src != SGX_SRC_VARYING) + continue; + for (k = 0; k < sr->nvarying && sr->varying[k] != c->ch[i].slot; k++) + ; + if (k < sr->nvarying) + continue; + sr->varying[sr->nvarying++] = c->ch[i].slot; + emit_varying(ctx, vinfo, c->ch[i].slot); + } + draw_compute_vertex_size(vinfo); + + ctx->layout = draw_layout(); +} + +bool +sgx_draw_init(struct sgx_context *ctx) +{ + struct sgx_render *sr = CALLOC_STRUCT(sgx_render); + + if (!sr) + return false; + sr->ctx = ctx; + sr->base.max_indices = 16 * 1024; + sr->base.max_vertex_buffer_bytes = 1024 * 1024; + sr->base.need_pipeline = render_need_pipeline; + sr->base.get_vertex_info = render_vertex_info; + sr->base.allocate_vertices = render_allocate; + sr->base.map_vertices = render_map; + sr->base.unmap_vertices = render_unmap; + sr->base.set_primitive = render_set_primitive; + sr->base.set_view_index = render_set_view_index; + sr->base.draw_elements = render_draw_elements; + sr->base.draw_arrays = render_draw_arrays; + sr->base.release_vertices = render_release; + sr->base.destroy = render_destroy; + ctx->render = &sr->base; + + if (!(ctx->draw = draw_create_no_llvm(&ctx->base))) { + render_destroy(&sr->base); + ctx->render = NULL; + return false; + } + ctx->vbuf = draw_vbuf_stage(ctx->draw, ctx->render); + if (!ctx->vbuf) + return false; + draw_set_rasterize_stage(ctx->draw, ctx->vbuf); + draw_set_render(ctx->draw, ctx->render); + /* lines and points as triangles, whatever their width */ + draw_wide_line_threshold(ctx->draw, 0.0f); + draw_wide_point_threshold(ctx->draw, 0.0f); + draw_enable_line_stipple(ctx->draw, false); + draw_enable_point_sprites(ctx->draw, false); + /* polygon offset's unit: a 24-bit depth buffer's (times four, the + * rasterizer state's copy) -- the tiles hold depth as F32 whatever the + * depth buffer's format (M23), and the draw module's unit for that is + * a bit of it, too fine to survive */ + draw_set_zs_format(ctx->draw, PIPE_FORMAT_Z24X8_UNORM); + return true; +} + +void +sgx_draw_fini(struct sgx_context *ctx) +{ + if (ctx->draw) + draw_destroy(ctx->draw); + else if (ctx->render) + render_destroy(ctx->render); + ctx->draw = NULL; + ctx->render = NULL; + sgx_batch_flush(ctx); + if (ctx->clear_prog.code_va || ctx->colour_prog.code_va) { + struct sgx_screen *screen = sgx_screen(ctx->base.screen); + + simple_mtx_lock(&screen->frame_lock); + sgx_frame_retire(screen->frame, &ctx->clear_prog); + sgx_frame_retire(screen->frame, &ctx->colour_prog); + simple_mtx_unlock(&screen->frame_lock); + } + free(ctx->batch.dead_vs); + free(ctx->batch.dead_fs); + free(ctx->batch.verts); + free(ctx->batch.sa); + free(ctx->batch.idx); + ctx->batch.verts = NULL; + ctx->batch.sa = NULL; + ctx->batch.idx = NULL; + /* (vertex chunks no draw used: the flush above had none to make) */ + for (unsigned i = 0; i < ctx->batch.nvchunks; i++) + sgx_bo_destroy(ctx->batch.vchunk[i]); + ctx->batch.nvchunks = ctx->batch.vat = 0; + sgx_bo_destroy(ctx->vtx.vchunk); + ctx->vtx.vchunk = NULL; + FREE(ctx->verts); + free(ctx->indices); + ctx->verts = NULL; + ctx->indices = NULL; + ctx->nverts = ctx->maxfloats = ctx->maxindices = 0; +} + +/* ---- draw_vbo ----------------------------------------------------------- */ + +static bool texclamp_does_nothing(struct sgx_context *ctx, const struct pipe_draw_info *info, + const struct pipe_draw_start_count_bias *draws, + unsigned num_draws); + +/* The fragment shader as this draw runs it: compiled with the bound blend + * state folded in (a variant made at the first draw that needs it), or + * NULL for M13a's way. */ +static struct sgx_fs * +fs_for_draw(struct sgx_context *ctx, const struct pipe_draw_info *info, + const struct pipe_draw_start_count_bias *draws, unsigned num_draws) +{ + struct sgx_shader *sh = ctx->fs; + const struct pipe_rt_blend_state *rt = ctx->blend ? &ctx->blend->rt[0] : NULL; + struct sgx_blend_key key = { .colormask = 0xf }; + struct sgx_fs *fs; + char why[128]; + + if (!sh || !sh->compiled) + return NULL; + if (rt) { + key.colormask = rt->colormask; + if (rt->blend_enable) { + key.enable = 1; + key.rgb_func = rt->rgb_func; + key.rgb_src = rt->rgb_src_factor; + key.rgb_dst = rt->rgb_dst_factor; + key.alpha_func = rt->alpha_func; + key.alpha_src = rt->alpha_src_factor; + key.alpha_dst = rt->alpha_dst_factor; + /* a target without alpha (RG8, R8, BGRX8): its alpha is 1 + * (gallium's rule; M43 -- the background load of RG8 leaves 0) */ + if (ctx->fb.nr_cbufs && ctx->fb.cbufs[0].texture && + !util_format_has_alpha(ctx->fb.cbufs[0].format)) { + uint8_t *f[4] = { &key.rgb_src, &key.rgb_dst, &key.alpha_src, &key.alpha_dst }; + + for (unsigned i = 0; i < 4; i++) { + if (*f[i] == PIPE_BLENDFACTOR_DST_ALPHA) + *f[i] = PIPE_BLENDFACTOR_ONE; + else if (*f[i] == PIPE_BLENDFACTOR_INV_DST_ALPHA || + *f[i] == PIPE_BLENDFACTOR_SRC_ALPHA_SATURATE) + *f[i] = PIPE_BLENDFACTOR_ZERO; + } + } + } + } + /* GL's logic ops: the program's too, on the colour and the tile's as + * bytes (iOS's es1 e03..e10) */ + if (ctx->blend && ctx->blend->logicop_enable) + key.logicop = ctx->blend->logicop_func + 1; + /* (textures sampled linear in other orders than B G R A, M16: their + * swizzle in the state words since M37, as a copy's) sRGB textures, + * depth ones -- the shader's, not its compiled form's (a shadow lookup + * compared ALWAYS is a constant there) */ + for (unsigned unit = 0; unit < 8; unit++) { + struct pipe_sampler_view *view = ctx->fs_views[unit]; + + if (!BITSET_TEST(sh->nir->info.textures_used, unit)) + continue; + + if (unit < 8 && view && util_format_is_srgb(view->format)) + key.tex_srgb |= 1u << unit; + if (unit < 8 && view && sgx_resource_copy_f16(view->texture)) + key.tex_f16 |= 1u << unit; + if (unit < 8 && view && util_format_is_depth_or_stencil(view->texture->format)) { + const struct pipe_sampler_state *ss = unit < PIPE_MAX_SAMPLERS ? + ctx->fs_samplers[unit] : NULL; + + key.tex_depth |= 1u << unit; + key.depth_swizzle[unit][0] = view->swizzle_r; + key.depth_swizzle[unit][1] = view->swizzle_g; + key.depth_swizzle[unit][2] = view->swizzle_b; + key.depth_swizzle[unit][3] = view->swizzle_a; + if (ss && ss->compare_mode == PIPE_TEX_COMPARE_R_TO_TEXTURE) { + key.tex_shadow |= 1u << unit; + key.shadow_func[unit] = ss->compare_func; + } + } else if (unit < 8 && view) { + /* a view's swizzle (M43): the program's, on the texel -- on the + * format's own first (M45: R8's, RG8's, sgx_resource_swizzle) */ + const uint8_t v[4] = { view->swizzle_r, view->swizzle_g, view->swizzle_b, + view->swizzle_a }; + uint8_t f[4] = { PIPE_SWIZZLE_X, PIPE_SWIZZLE_Y, PIPE_SWIZZLE_Z, PIPE_SWIZZLE_W }; + bool own = sgx_resource_swizzle(view->texture, f); + + if (own || v[0] != PIPE_SWIZZLE_X || v[1] != PIPE_SWIZZLE_Y || + v[2] != PIPE_SWIZZLE_Z || v[3] != PIPE_SWIZZLE_W) { + key.tex_swz |= 1u << unit; + for (unsigned c = 0; c < 4; c++) + key.tex_swizzle[unit][c] = v[c] <= PIPE_SWIZZLE_W ? f[v[c]] : v[c]; + } + } + } + /* (M43) what the target's tile holds */ + if (ctx->fb.nr_cbufs && ctx->fb.cbufs[0].texture) { + key.rt_kind = sgx_frame_rt_kind(ctx->fb.cbufs[0].format); + key.rt_srgb = util_format_is_srgb(ctx->fb.cbufs[0].format); + key.rt_intensity = util_format_is_intensity(ctx->fb.cbufs[0].format); + } + /* gl_FrontFacing: which winding is the front */ + if (ctx->rast && ctx->rast->front_ccw && + BITSET_TEST(sh->nir->info.system_values_read, SYSTEM_VALUE_FRONT_FACE)) + key.front_ccw = 1; + /* (M46) a TClampST lookup whose clamp does nothing in this draw: the + * PDS's, at the varying */ + if (sh->has_texclamp) { + int64_t t0 = os_time_get_nano(); + static const char *off_file = (const char *)-1; + static int64_t off_at; + static bool off; + + /* SGX_TEXCLAMP_OFF_FILE=path: every clamp kept while that file is + * there (looked for once a second) -- the two compared in one run */ + if (off_file == (const char *)-1) + off_file = getenv("SGX_TEXCLAMP_OFF_FILE"); + if (off_file && t0 - off_at > 1000000000ll) { + off_at = t0; + off = access(off_file, F_OK) == 0; + } + if (!(off_file && off) && texclamp_does_nothing(ctx, info, draws, num_draws)) { + key.texclamp_free = 1u << sh->texclamp.unit; + ctx->stat_clamp_free++; + } else { + ctx->stat_clamp_kept++; + } + ctx->stat_clamp_ns += os_time_get_nano() - t0; + } + if (!key.enable && key.colormask == 0xf && !key.tex_swap && !key.tex_x8 && !key.tex_srgb && + !key.front_ccw && !key.logicop && !key.tex_depth && !key.tex_swz && !key.tex_f16 && + !key.rt_kind && !key.rt_srgb && !key.rt_intensity && !key.texclamp_free) + return sh->compiled; + /* (the key is bytes, no padding) */ + for (unsigned i = 0; i < sh->nvariants; i++) + if (!memcmp(&sh->variant[i]->blend, &key, sizeof(key))) + return sh->variant[i]; + if (!(fs = sgx_compile_fs(sh->nir, &key, why, sizeof(why)))) { + mesa_logw_once("sgx: a variant of a fragment shader (blending, texture orders) " + "not compiled (%s): drawn without it", why); + return sh->compiled; + } + if (debug_get_bool_option("SGX_DEBUG_SHADER", false)) { + mesa_logi("sgx: a fragment shader's variant (blend %u %u/%u/%u %u/%u/%u, mask %x): " + "%u instructions, %u temps", key.enable, key.rgb_func, key.rgb_src, key.rgb_dst, + key.alpha_func, key.alpha_src, key.alpha_dst, key.colormask, fs->prog.ncode, + fs->prog.ntemps); + for (unsigned i = 0; i < fs->prog.ncode; i++) + mesa_logi("sgx: %016llx", (unsigned long long)fs->prog.code[i]); + } + if (sh->nvariants == ARRAY_SIZE(sh->variant)) { + sgx_batch_bury_fs(ctx, sh->variant[0]); + memmove(sh->variant, sh->variant + 1, (ARRAY_SIZE(sh->variant) - 1) * sizeof(fs)); + sh->nvariants--; + } + sh->variant[sh->nvariants++] = fs; + return fs; +} + +/* (M46: the CPU reads the bytes [lo, hi) of it, its CPU copy made those + * of the GPU's first) */ +static const void * +map_buffer_range(struct pipe_resource *prsc, size_t *size, uint32_t lo, uint32_t hi) +{ + struct sgx_resource *res = sgx_resource(prsc); + uint8_t *map; + + if (!res) + return NULL; + sgx_buffer_fresh_range(res, lo, hi); + if (!(map = res->data ? res->data : res->bo ? sgx_bo_map(res->bo) : NULL)) + return NULL; + /* (a buffer's CPU copy: no render writes it, M26) */ + *size = prsc->width0; + return map; +} + +static const void * +map_buffer(struct pipe_resource *prsc, size_t *size) +{ + return map_buffer_range(prsc, size, 0, ~0u); +} + +/* (M46) the bytes [lo, hi) of a vertex or index buffer as the CPU reads + * them in place (sgx_buffer_read_in_place: PPSSPP's push buffers are the + * GPU copy itself, write-combined) -- the pointer is byte 0's */ +static const uint8_t * +read_in_place(const struct pipe_vertex_buffer *vb, struct pipe_resource *res, uint64_t lo, + uint64_t hi) +{ + if (vb && vb->is_user_buffer) + return vb->buffer.user; + if (!res || hi > res->width0) + return NULL; + return sgx_buffer_read_in_place(sgx_resource(res), lo, hi); +} + +/* (M46) the smallest and largest index of a draw (the restart index + * aside), read 256 at a time out of the buffer: 1, or 0 if it has none, -1 + * if they cannot be read */ +static int +index_bounds(const struct pipe_draw_info *info, const struct pipe_draw_start_count_bias *d, + uint32_t *mn, uint32_t *mx) +{ + unsigned isz = info->index_size; + const uint8_t *idx; + + if (info->index_bounds_valid) { + *mn = info->min_index; + *mx = info->max_index; + return *mn <= *mx; + } + if (info->has_user_indices) + idx = info->index.user; + else if (!(idx = read_in_place(NULL, info->index.resource, (uint64_t)d->start * isz, + (uint64_t)(d->start + d->count) * isz))) + return -1; + if (!idx) + return -1; + idx += (size_t)d->start * isz; + *mn = ~0u; + *mx = 0; + for (unsigned k = 0; k < d->count; k += 256) { + unsigned n = MIN2(256, d->count - k); + uint32_t chunk[256]; + + /* (a copy first: write-combined memory read in bursts) */ + memcpy(chunk, idx + (size_t)k * isz, n * isz); + for (unsigned j = 0; j < n; j++) { + uint32_t x = isz == 2 ? ((const uint16_t *)chunk)[j] : + isz == 1 ? ((const uint8_t *)chunk)[j] : chunk[j]; + + if (info->primitive_restart && x == info->restart_index) + continue; + *mn = MIN2(*mn, x); + *mx = MAX2(*mx, x); + } + } + return *mn <= *mx; +} + +/* (M46) the smallest and largest of the bound vertex shader's varyings + * tc->slot[c], tc->comp[c] (the coordinates with need[c]) over the draws' + * vertices: each a copy of an attribute's component (sgx_vs_varying_attr), + * read where it is -- for an indexed draw over the vertices from its + * smallest index to its largest. What a pixel gets is a mix of its + * triangle's vertices' values, inside these. false if that cannot be told */ +static bool +varying_ranges(struct sgx_context *ctx, const struct pipe_draw_info *info, + const struct pipe_draw_start_count_bias *draws, unsigned num_draws, + const struct sgx_texclamp *tc, const bool need[2], float lo[2], float hi[2]) +{ + const struct sgx_vertex_elements *ve = ctx->velems; + const struct pipe_vertex_element *e[2] = { NULL, NULL }; + unsigned attr[2] = { 0, 0 }, acomp[2] = { 0, 0 }, read = 0; + bool f32[2] = { false, false }; + + if (!ctx->vs || !ctx->vs->nir || !ve) + return false; + for (unsigned c = 0; c < 2; c++) { + lo[c] = INFINITY; + hi[c] = -INFINITY; + if (!need[c]) + continue; + if (!sgx_vs_varying_attr(ctx->vs->nir, tc->slot[c], tc->comp[c], &attr[c], &acomp[c]) || + attr[c] >= ve->count || acomp[c] > 3) + return false; + e[c] = &ve->e[attr[c]]; + if (e[c]->instance_divisor || !(ctx->vb_mask & 1u << e[c]->vertex_buffer_index)) + return false; + f32[c] = (e[c]->src_format == PIPE_FORMAT_R32_FLOAT || + e[c]->src_format == PIPE_FORMAT_R32G32_FLOAT || + e[c]->src_format == PIPE_FORMAT_R32G32B32_FLOAT || + e[c]->src_format == PIPE_FORMAT_R32G32B32A32_FLOAT) && + acomp[c] < util_format_get_nr_components(e[c]->src_format); + } + for (unsigned i = 0; i < num_draws; i++) { + const struct pipe_draw_start_count_bias *d = &draws[i]; + int64_t first, last; + + if (!d->count) + continue; + if (info->index_size) { + uint32_t mn, mx; + + int got = index_bounds(info, d, &mn, &mx); + + if (got < 0) + return false; + if (!got) + continue; + first = (int64_t)mn + d->index_bias; + last = (int64_t)mx + d->index_bias; + } else { + first = d->start; + last = (int64_t)d->start + d->count - 1; + } + /* (a few thousand vertices at most: they are read through the CPU) */ + if (first < 0 || last < first || last - first >= 16384 || (read += last - first + 1) > 32768) + return false; + for (unsigned c = 0; c < 2; c++) { + const struct pipe_vertex_buffer *vb; + unsigned fsize, both; + uint64_t at0, at1; + const uint8_t *p; + + if (!e[c]) + continue; + /* (both from one attribute: one pass) */ + if (c == 1 && e[0] && e[0] == e[1]) + continue; + both = c == 0 && e[1] == e[0]; + vb = &ctx->vb[e[c]->vertex_buffer_index]; + fsize = util_format_get_blocksize(e[c]->src_format); + at0 = vb->buffer_offset + e[c]->src_offset + (uint64_t)first * e[c]->src_stride; + at1 = vb->buffer_offset + e[c]->src_offset + (uint64_t)last * e[c]->src_stride + fsize; + if (!(p = read_in_place(vb, vb->is_user_buffer ? NULL : vb->buffer.resource, at0, at1))) + return false; + p += at0; + for (int64_t v = 0; v <= last - first; v++) { + const uint8_t *q = p + v * e[c]->src_stride; + float x[2]; + + if (f32[c] && (!both || f32[1])) { + memcpy(&x[0], q + acomp[c] * 4, 4); + if (both) + memcpy(&x[1], q + acomp[1] * 4, 4); + } else { + float t[4]; + + util_format_unpack_rgba(e[c]->src_format, t, q, 1); + x[0] = t[acomp[c]]; + x[1] = both ? t[acomp[1]] : 0.0f; + } + for (unsigned k = 0; k <= both; k++) { + unsigned to = both ? k : c; + + if (!isfinite(x[k])) + return false; + lo[to] = MIN2(lo[to], x[k]); + hi[to] = MAX2(hi[to], x[k]); + } + } + } + } + for (unsigned c = 0; c < 2; c++) + if (need[c] && !(lo[c] <= hi[c])) + return false; + return true; +} + +static bool +texclamp_says(bool free, const char *why, float a, float b) +{ + static int debug = -1; + + /* SGX_DEBUG_TEXCLAMP=1: each draw's answer, and why */ + if (debug < 0) + debug = debug_get_bool_option("SGX_DEBUG_TEXCLAMP", false); + if (debug) + mesa_logi("sgx: texclamp: %s (%s %g %g)", free ? "left out" : "kept", why, a, b); + return free; +} + +static bool +texclamp_does_nothing(struct sgx_context *ctx, const struct pipe_draw_info *info, + const struct pipe_draw_start_count_bias *draws, unsigned num_draws) +{ + const struct sgx_texclamp *tc = &ctx->fs->texclamp; + const struct pipe_sampler_view *view = ctx->fs_views[tc->unit]; + const struct pipe_sampler_state *ss = ctx->fs_samplers[tc->unit]; + const float *u = ctx->fs_constants; + unsigned nw = ctx->fs_constants_size / 4, level; + bool lo_edge[2], hi_edge[2]; + float lo[2], hi[2]; + + if (!view || !ss || !view->texture || view->target != PIPE_TEXTURE_2D || + ss->unnormalized_coords || ss->max_anisotropy > 1 || + ss->min_img_filter != ss->mag_img_filter || + (ss->min_mip_filter != PIPE_TEX_MIPFILTER_NONE && + view->u.tex.first_level != MIN2(view->u.tex.last_level, view->texture->last_level))) + return texclamp_says(false, "the sampler", 0, 0); + level = view->u.tex.first_level; + for (unsigned c = 0; c < 2; c++) { + unsigned n = c ? u_minify(view->texture->height0, level) : + u_minify(view->texture->width0, level); + bool edge = (c ? ss->wrap_t : ss->wrap_s) == PIPE_TEX_WRAP_CLAMP_TO_EDGE; + /* (a ten-thousandth of a texel: PPSSPP's half a texel is 1 / n * 0.5 + * in floats) */ + double half = 0.5 / n, tol = 1e-4 / n; + + lo[c] = sgx_uexpr_eval(&tc->lo[c], u, nw); + hi[c] = sgx_uexpr_eval(&tc->hi[c], u, nw); + if (sgx_uexpr_eval(&tc->off[c], u, nw) != 0.0f || !(lo[c] <= hi[c]) || !n) + return texclamp_says(false, "an offset, or lo > hi", sgx_uexpr_eval(&tc->off[c], u, nw), + hi[c] - lo[c]); + lo_edge[c] = edge && lo[c] <= half + tol; + hi_edge[c] = edge && hi[c] >= 1.0 - half - tol; + } + { + bool need[2] = { !(lo_edge[0] && hi_edge[0]), !(lo_edge[1] && hi_edge[1]) }; + float vlo[2], vhi[2]; + + if ((need[0] || need[1]) && + !varying_ranges(ctx, info, draws, num_draws, tc, need, vlo, vhi)) + return texclamp_says(false, "the varying not read", need[0], need[1]); + for (unsigned c = 0; c < 2; c++) + if (need[c] && ((!lo_edge[c] && vlo[c] < lo[c]) || (!hi_edge[c] && vhi[c] > hi[c]))) + return texclamp_says(false, c ? "y outside" : "x outside", vlo[c], vhi[c]); + } + return texclamp_says(true, "x and y", lo_edge[0] * 2 + hi_edge[0], lo_edge[1] * 2 + hi_edge[1]); +} + +/* ---- gathering draws into renders (M14) -------------------------------- */ + +bool +sgx_batch_uses(struct sgx_context *ctx, struct pipe_resource *p) +{ + struct sgx_batch *b = &ctx->batch; + + if (!b->ndraws || !p) + return false; + if (b->rt == p || b->zs == p) + return true; + for (unsigned i = 0; i < b->ntex; i++) + if (b->tex[i] == p) + return true; + return false; +} + +static bool zs_quad(struct sgx_context *ctx, const struct pipe_scissor_state *sc, float d, + const struct sgx_frame_state *st, bool flush); +static bool quad(struct sgx_context *ctx, const struct pipe_scissor_state *sc, float d, + const struct sgx_frame_state *st, struct sgx_pixel_program *prog, + const uint32_t *sa, unsigned nsa, bool flush); + +/* the buried programs: retired from the frame (their places free once the + * renders submitted so far are done), then freed */ +static void +bury(struct sgx_context *ctx) +{ + struct sgx_screen *screen = sgx_screen(ctx->base.screen); + struct sgx_batch *b = &ctx->batch; + + if (!b->ndead_vs && !b->ndead_fs) + return; + simple_mtx_lock(&screen->frame_lock); + for (unsigned i = 0; screen->frame && i < b->ndead_vs; i++) + sgx_frame_retire_vs(screen->frame, b->dead_vs[i]); + for (unsigned i = 0; screen->frame && i < b->ndead_fs; i++) + sgx_frame_retire(screen->frame, &b->dead_fs[i]->prog); + simple_mtx_unlock(&screen->frame_lock); + for (unsigned i = 0; i < b->ndead_vs; i++) + sgx_vs_destroy(b->dead_vs[i]); + for (unsigned i = 0; i < b->ndead_fs; i++) + sgx_fs_destroy(b->dead_fs[i]); + b->ndead_vs = b->ndead_fs = 0; +} + +void +sgx_batch_bury_fs(struct sgx_context *ctx, struct sgx_fs *fs) +{ + struct sgx_batch *b = &ctx->batch; + struct sgx_fs **d; + + if (!fs) + return; + if (!(d = realloc(b->dead_fs, (b->ndead_fs + 1) * sizeof(*d)))) { + sgx_batch_flush(ctx); + sgx_fs_destroy(fs); /* its places stay taken */ + return; + } + b->dead_fs = d; + d[b->ndead_fs++] = fs; + if (!b->ndraws) + bury(ctx); +} + +void +sgx_batch_bury_vs(struct sgx_context *ctx, struct sgx_vs *vs) +{ + struct sgx_batch *b = &ctx->batch; + struct sgx_vs **d; + + if (!vs) + return; + if (!(d = realloc(b->dead_vs, (b->ndead_vs + 1) * sizeof(*d)))) { + sgx_batch_flush(ctx); + sgx_vs_destroy(vs); /* its places stay taken */ + return; + } + b->dead_vs = d; + d[b->ndead_vs++] = vs; + if (!b->ndraws) + bury(ctx); +} + +static struct { const char *file; int line; unsigned n; } why[16]; + +/* what a draw found the render out of, when it was made for want of room + * (SGX_DEBUG=fps: "renders from", M42) */ +enum { ROOM_DRAWS, ROOM_HANDLES, ROOM_TEXTURES, ROOM_BYTES, ROOM_N }; +static unsigned room_why[ROOM_N]; + +static bool +no_room(unsigned what) +{ + room_why[what]++; + return true; +} + +/* what kept a draw from being merged into the last one (SGX_DEBUG=fps: + * "not merged", M42) */ +enum { MERGE_PROGRAM, MERGE_TEXTURES, MERGE_FS_SA, MERGE_LAYOUT, MERGE_STATE, MERGE_VS_SA, + MERGE_VERTICES, MERGE_PRIMS, MERGE_ROOM, MERGE_N }; +static const char *const merge_names[MERGE_N] = { + "programs", "textures", "pixel constants", "layout", "state", "vertex constants", + "vertices", "primitives", "room", +}; +static unsigned merge_why[MERGE_N]; + +static bool +no_merge(unsigned what) +{ + merge_why[what]++; + return false; +} + +/* SGX_TRACE=1: a thread waits for each render and says how long it took + * from its kick, and how long since the last one ended (debugging speed) */ +#include +static struct { struct sgx_fence *f; int64_t kick; } trace_q[64]; +static unsigned trace_head, trace_tail; +static pthread_mutex_t trace_lock = PTHREAD_MUTEX_INITIALIZER; +static pthread_cond_t trace_cond = PTHREAD_COND_INITIALIZER; + +static void * +trace_thread(void *arg) +{ + int64_t last_done = 0; + + for (;;) { + struct sgx_fence *f; + int64_t kick, done; + + pthread_mutex_lock(&trace_lock); + while (trace_head == trace_tail) + pthread_cond_wait(&trace_cond, &trace_lock); + f = trace_q[trace_tail % 64].f; + kick = trace_q[trace_tail % 64].kick; + trace_tail++; + pthread_mutex_unlock(&trace_lock); + sgx_fence_wait(f, OS_TIMEOUT_INFINITE); + done = os_time_get_nano(); + sgx_trace_mark("(render done)"); + mesa_logi("sgx: trace: render done %.1f ms after its kick, %.1f ms after the last; " + "kicked %.1f ms after the last ended", (done - kick) / 1e6, + last_done ? (done - last_done) / 1e6 : 0, last_done ? (kick - last_done) / 1e6 : 0); + last_done = done; + sgx_fence_reference(&f, NULL); + } + return NULL; +} + +static void +trace_kick(struct sgx_fence *fence) +{ + static int on = -1; + static pthread_t thread; + + if (on < 0) { + on = getenv("SGX_TRACE") && atoi(getenv("SGX_TRACE")); + if (on) + pthread_create(&thread, NULL, trace_thread, NULL); + } + if (!on) + return; + pthread_mutex_lock(&trace_lock); + if (trace_head - trace_tail < 64) { + trace_q[trace_head % 64].f = NULL; + sgx_fence_reference(&trace_q[trace_head % 64].f, fence); + trace_q[trace_head % 64].kick = os_time_get_nano(); + trace_head++; + pthread_cond_signal(&trace_cond); + } + pthread_mutex_unlock(&trace_lock); +} + +/* the renders since the last call, by where they were flushed from */ +void +sgx_batch_why(struct sgx_context *ctx) +{ + char s[512]; + unsigned n = 0; + + s[0] = 0; + for (unsigned i = 0; i < ARRAY_SIZE(why) && why[i].file; i++) { + n += snprintf(s + n, sizeof(s) - MIN2(n, sizeof(s)), " %s:%d %u", + strrchr(why[i].file, '/') ? strrchr(why[i].file, '/') + 1 : why[i].file, + why[i].line, why[i].n); + why[i].n = 0; + } + if (room_why[ROOM_DRAWS] + room_why[ROOM_HANDLES] + room_why[ROOM_TEXTURES] + room_why[ROOM_BYTES]) + snprintf(s + n, sizeof(s) - MIN2(n, sizeof(s)), + " (no room for: draws %u, buffers %u, textures %u, bytes %u)", + room_why[ROOM_DRAWS], room_why[ROOM_HANDLES], room_why[ROOM_TEXTURES], + room_why[ROOM_BYTES]); + memset(room_why, 0, sizeof(room_why)); + mesa_logi("sgx: renders from%s", s); + n = 0; + s[0] = 0; + for (unsigned i = 0; i < MERGE_N; i++) { + if (merge_why[i]) + n += snprintf(s + n, sizeof(s) - MIN2(n, sizeof(s)), "%s %s %u", n ? "," : "", + merge_names[i], merge_why[i]); + merge_why[i] = 0; + } + if (n) + mesa_logi("sgx: draws not merged, for their:%s", s); +} + +void +sgx_batch_flush_at(struct sgx_context *ctx, const char *file, int line) +{ + struct sgx_screen *screen = sgx_screen(ctx->base.screen); + struct sgx_batch *b = &ctx->batch; + struct sgx_frame_draw *d = b->fdraw; + struct sgx_resource *zs = b->zs ? sgx_resource(b->zs) : NULL; + struct sgx_zls *zt = zs ? sgx_resource_zls(zs, b->zs_level, b->zs_layer) : NULL; + struct sgx_frame_zls zls = { 0 }; + struct sgx_bo *vis = NULL; + struct sgx_fence *fence; + int ret = -ENOMEM; + + if (!b->ndraws) { + /* a depth clear no draw came after: the depth buffer's own, noted + * for the next render of it or a map (M43: a level cleared, then + * the framebuffer changed to the next -- the clear was lost) */ + if (b->zs_cleared && ctx->fb.zsbuf.texture) { + struct sgx_zls *z = sgx_resource_zls(sgx_resource(ctx->fb.zsbuf.texture), + ctx->fb.zsbuf.level, ctx->fb.zsbuf.first_layer); + + if (z) { + z->cleared = true; + z->clear = b->depth_clear; + } + b->zs_cleared = false; + } + b->blit = false; + bury(ctx); + return; + } + /* the depth buffer's tiles in memory (M24): stored at the render's end + * when a draw (or a clear's quad) writes depth, loaded at its start when + * there is something there, no clear came first and a draw reads or + * writes depth. SGX_ZLS=0: never (depth lives in the tiles only) */ + if (zt && b->zs->width0 && debug_get_bool_option("SGX_ZLS", true)) { + unsigned zw = u_minify(b->zs->width0, b->zs_level), zh = u_minify(b->zs->height0, b->zs_level); + bool store, load; + + /* a clear no draw used is only noted: the next render starts from + * it instead of loading */ + if (zt->cleared && !b->zs_cleared) { + b->zs_cleared = true; + b->depth_clear = zt->clear; + } + zt->cleared = false; + store = b->zs_written; + load = zt->valid && !b->zs_cleared && (store || b->zs_read); + if (b->zs_cleared && !store) { + zt->cleared = true; + zt->clear = b->depth_clear; + } + + /* (the level's own, M43) */ + if ((load || store) && !zt->bo) { + zt->bo = sgx_bo_create(&screen->dev, + sgx_frame_zls_size(zw, zh, sgx_zls_format(b->zs->format)), 0, 0); + zt->valid = false; + load = false; + } + if ((load || store) && zt->bo) { + zls.bo = zt->bo; + zls.w = zw; + zls.load = load; + zls.store = store; + zls.stencil = util_format_has_stencil(util_format_description(b->zs->format)); + zls.format = sgx_zls_format(b->zs->format); + } + } + /* a render that starts from a clear stores only the tiles it draws in: + * a quad that draws nothing (depth NEVER) over the target puts every + * tile in it, all stored at the clear's depth */ + if (zls.store && !zls.load) { + const struct sgx_frame_state never = { .depth_func = PIPE_FUNC_NEVER }; + + zs_quad(ctx, NULL, 0.5f, &never, false); + } + for (unsigned i = 0; i < b->ndraws; i++) { + const struct sgx_batch_draw *bd = &b->draw[i]; + + d[i] = (struct sgx_frame_draw){ + .l = bd->l, .nverts = bd->nverts, + .prog = bd->compiled ? &bd->prog : NULL, .sa = b->sa + bd->sa, .st = bd->st, + .vs = bd->vs, .vs_sa = b->sa + bd->vs_sa, + .base = bd->base, .stride = bd->stride, .count = bd->count, + .indices = bd->nidx ? b->idx + bd->idx : NULL, .idx_va = bd->idx_va, + }; + if (!bd->vs) + d[i].verts = b->verts + bd->first; + else if (bd->repacked) + d[i].vdata_va = bd->vdata_va; + } + /* the buffers to list: the textures', the buffers', the vertex chunks' + * (M42) */ + for (unsigned i = 0; i < b->nbos; i++) + b->handles[b->ntex + i] = b->bos[i]->handle; + for (unsigned i = 0; i < b->nvchunks; i++) + b->handles[b->ntex + b->nbos + i] = b->vchunk[i]->handle; + /* an occlusion query's draws among them (M37): a visibility buffer of + * the render's, zeroed, for the query to read */ + if (b->counted && ctx->query && (vis = sgx_bo_cache_get(&screen->dev, SGX_VIS_SIZE))) + memset(vis->map, 0, SGX_VIS_SIZE); + if ((fence = sgx_fence_create(&screen->dev, false))) { + simple_mtx_lock(&screen->frame_lock); + const struct sgx_frame_target t = { sgx_resource(b->rt), b->rt_level, b->rt_layer, + b->w, b->h }; + + ret = sgx_frame_render(screen->frame, &t, d, b->ndraws, b->handles, + b->ntex + b->nbos + b->nvchunks, b->depth_clear, + zls.bo ? &zls : NULL, vis, fence); + simple_mtx_unlock(&screen->frame_lock); + } + if (vis && !ret) { + sgx_bo_set_busy(vis, fence); + sgx_query_add(ctx->query, vis); + } else { + sgx_bo_destroy(vis); + } + b->counted = false; + if (!ret && ctx->debug_fps) { + unsigned i; + + for (i = 0; i < ARRAY_SIZE(why) - 1 && why[i].file && + (why[i].line != line || strcmp(why[i].file, file)); i++) + ; + why[i].file = file; + why[i].line = line; + why[i].n++; + } + /* SGX_DEBUG=fps,sync: each render waited for, its time on the GPU said */ + if (!ret && ctx->debug_sync) { + int64_t t0 = os_time_get_nano(); + + sgx_fence_wait(fence, OS_TIMEOUT_INFINITE); + ctx->stat_gpu += os_time_get_nano() - t0; + /* (M46: what it drew into, and what made it) */ + if (!ctx->debug_fps) + mesa_logi("sgx: a render of %u draws: %.2f ms on the GPU -- %ux%u %s%s%s%s, from %s:%d", + b->ndraws, (os_time_get_nano() - t0) / 1e6, b->w, b->h, + util_format_short_name(b->rt->format), zls.load ? ", depth loaded" : "", + zls.store ? ", depth stored" : "", b->blit ? ", u_blitter's" : "", file, line); + } + if (!ret) { + sgx_trace_mark("kicked"); + trace_kick(fence); + } + if (!ret) { + ctx->stat_renders++; + sgx_fence_reference(&ctx->last, fence); + sgx_resource(b->rt)->seq++; + sgx_resource(b->rt)->gpu_written = true; + /* (M45: a target's buffer from the cache goes back to it busy, as a + * texture's does) */ + sgx_bo_set_busy(sgx_resource(b->rt)->bo, ctx->last); + if (zls.store) { + zt->valid = true; + zs->seq++; /* (a depth texture's copy made again, M37) */ + } + } else { + mesa_logw("sgx: a render of %u draws failed (%d)", b->ndraws, ret); + } + sgx_fence_reference(&fence, NULL); + pipe_resource_reference(&b->rt, NULL); + pipe_resource_reference(&b->zs, NULL); + b->zs_cleared = b->zs_read = b->zs_written = false; + b->blit = false; + for (unsigned i = 0; i < b->ntex; i++) { + pipe_resource_reference(&b->tex[i], NULL); + if (!ret) + sgx_bo_set_busy(b->tex_bo[i], ctx->last); + sgx_bo_destroy(b->tex_bo[i]); + b->tex_bo[i] = NULL; + } + /* (the kernel keeps the buffers for the render) */ + for (unsigned i = 0; i < b->nbos; i++) { + if (!ret) + sgx_bo_set_busy(b->bos[i], ctx->last); + sgx_bo_destroy(b->bos[i]); + } + /* the vertex chunks back to the cache, busy with the render (a stream + * written for a draw not added yet keeps its chunk: sgx_vtx.vchunk) */ + for (unsigned i = 0; i < b->nvchunks; i++) { + if (!ret) + sgx_bo_set_busy(b->vchunk[i], ctx->last); + sgx_bo_destroy(b->vchunk[i]); + } + b->nvchunks = b->vat = 0; + b->ndraws = b->ntex = b->nbos = b->nfloats = b->nbytes = b->nsa = b->nidx = 0; + b->tex_bytes = 0; + b->seq++; + bury(ctx); +} + +static bool +grow(void **p, unsigned *max, unsigned want, unsigned size) +{ + unsigned n; + void *q; + + if (want <= *max) + return true; + n = MAX2(want, *max * 2); + if (!(q = realloc(*p, (size_t)n * size))) + return false; + *p = q; + *max = n; + return true; +} + +/* Where a draw's pixels may go: its viewport (a vertex shader's draw; the + * draw module clips to it itself), the scissor, the target. The TA clips + * to a guard band 1.5 times its viewport -- exactly, found drawing past + * the edges of viewports of all sizes -- so it gets that rectangle shrunk + * 1.5 times, and the vertices x' = a x + b w (ab: a, b for x, then y) to + * land where they did through the draw's viewport (t, s). false when + * nothing is left. */ +static bool +clip_to(struct sgx_context *ctx, bool vs, struct sgx_frame_state *st, float ab[4]) +{ + float lo[2] = { 0, 0 }, hi[2] = { ctx->fb.width, ctx->fb.height }, t[2], s[2]; + + for (unsigned i = 0; i < 2; i++) { + if (vs) { + t[i] = ctx->viewport.translate[i]; + s[i] = ctx->viewport.scale[i]; + lo[i] = MAX2(lo[i], t[i] - fabsf(s[i])); + hi[i] = MIN2(hi[i], t[i] + fabsf(s[i])); + } else { + /* the draw module's vertices: over the target's whole viewport */ + t[i] = s[i] = hi[i] / 2; + } + } + if (ctx->rast && ctx->rast->scissor) { + lo[0] = MAX2(lo[0], ctx->scissor.minx); + hi[0] = MIN2(hi[0], ctx->scissor.maxx); + lo[1] = MAX2(lo[1], ctx->scissor.miny); + hi[1] = MIN2(hi[1], ctx->scissor.maxy); + } + /* SGX_CLIP_TINY=1 (M46, a measurement): every draw clipped to 8 x 8 + * pixels -- its vertices all shaded and clipped as before, next to no + * pixels: what a render's vertex side and fixed cost are */ + { + static int tiny = -1; + + if (tiny < 0) + tiny = debug_get_bool_option("SGX_CLIP_TINY", false); + if (tiny) { + hi[0] = MIN2(hi[0], lo[0] + 8); + hi[1] = MIN2(hi[1], lo[1] + 8); + } + } + if (!(lo[0] < hi[0] && lo[1] < hi[1])) + return false; + for (unsigned i = 0; i < 2; i++) { + float c = (lo[i] + hi[i]) / 2, h = (hi[i] - lo[i]) / 3; + + st->translate[i] = c; + st->scale[i] = h; + ab[2 * i] = s[i] / h; + ab[2 * i + 1] = (t[i] - c) / h; + } + /* depth as the viewport has it; the draw module's z through 0.5 z + 0.5 */ + st->translate[2] = vs ? ctx->viewport.translate[2] : 0.5f; + st->scale[2] = vs ? ctx->viewport.scale[2] : 0.5f; + st->viewport = true; + return true; +} + +/* the framebuffer's colour target as the frame takes it: its level and + * face (M29) */ +static bool +fb_target(struct sgx_context *ctx, struct sgx_frame_target *t) +{ + struct pipe_surface *surf = &ctx->fb.cbufs[0]; + struct pipe_resource *zs = ctx->fb.zsbuf.texture; + + if (ctx->fb.nr_cbufs >= 1 && surf->texture) { + *t = (struct sgx_frame_target){ sgx_resource(surf->texture), surf->level, + surf->first_layer, ctx->fb.width, ctx->fb.height }; + return true; + } + /* depth and stencil alone (a shadow map, M35): the render still ends + * its tiles' colour somewhere -- a target of the depth buffer's size + * nobody reads */ + if (!zs) + return false; + if (!ctx->no_colour || ctx->no_colour->width0 != zs->width0 || + ctx->no_colour->height0 != zs->height0) { + const struct pipe_resource templ = { + .target = PIPE_TEXTURE_2D, .format = PIPE_FORMAT_B8G8R8A8_UNORM, + .width0 = zs->width0, .height0 = zs->height0, .depth0 = 1, .array_size = 1, + .bind = PIPE_BIND_RENDER_TARGET, + }; + + sgx_batch_flush(ctx); + pipe_resource_reference(&ctx->no_colour, NULL); + ctx->no_colour = ctx->base.screen->resource_create(ctx->base.screen, &templ); + if (!ctx->no_colour) + return false; + } + *t = (struct sgx_frame_target){ sgx_resource(ctx->no_colour), 0, 0, ctx->fb.width, + ctx->fb.height }; + return true; +} + +/* whether the gathered draws go elsewhere than t */ +static bool +batch_elsewhere(const struct sgx_batch *b, const struct sgx_frame_target *t) +{ + return b->ndraws && (b->rt != &t->res->base || b->rt_level != t->level || + b->rt_layer != t->layer || b->w != t->w || b->h != t->h); +} + +/* the gathered render's target and depth buffer, at its first draw */ +static void +batch_start(struct sgx_context *ctx, const struct sgx_frame_target *t) +{ + struct sgx_batch *b = &ctx->batch; + + pipe_resource_reference(&b->rt, &t->res->base); + b->rt_level = t->level; + b->rt_layer = t->layer; + b->w = t->w; + b->h = t->h; + pipe_resource_reference(&b->zs, ctx->fb.zsbuf.texture); + b->zs_level = ctx->fb.zsbuf.level; + b->zs_layer = ctx->fb.zsbuf.first_layer; +} + +/* the vertices and indices gathered, in bytes (SGX_FRAME_MAX_BYTES) */ +static unsigned +batch_bytes(const struct sgx_batch *b) +{ + return b->nfloats * sizeof(float) + b->nbytes + 2 * b->nidx; +} + +/* The memory a texture holds, its content and the sampler's copy. A + * render's textures stay referenced until it is made, so past + * SGX_BATCH_TEX_BYTES of them it goes first: a program making, drawing + * with and deleting textures (piglit's streaming-texture-leak: 5000 of 4 + * MiB) kept them all for one render, and the kernel's pages ran out (M35). + * Only what the render alone keeps counts (M42): SuperTux 0.7.0's menu + * samples ~100 MiB of textures it keeps a frame, three renders when they + * all counted. */ +#define SGX_BATCH_TEX_BYTES (48u << 20) + +/* the render's entry for texture p as it is sampled now -- its copy then + * -- or b->ntex */ +static unsigned +tex_entry(const struct sgx_batch *b, struct pipe_resource *p) +{ + unsigned k; + + for (k = 0; k < b->ntex && (b->tex[k] != p || b->tex_bo[k] != sgx_resource(p)->sampled); k++) + ; + return k; +} + +static uint64_t +tex_bytes(struct pipe_resource *p) +{ + struct sgx_resource *r = sgx_resource(p); + + return (r->bo ? r->bo->size : 0) + (r->tw ? r->tw->size : 0); +} + +/* the memory of the render's textures that only the render keeps: those + * deleted since (its reference the last) and copies an upload replaced */ +static uint64_t +dead_tex_bytes(const struct sgx_batch *b) +{ + uint64_t n = 0; + + for (unsigned k = 0; k < b->ntex; k++) { + if (p_atomic_read(&b->tex[k]->reference.count) == 1) + n += tex_bytes(b->tex[k]); + else if (b->tex_bo[k] != sgx_resource(b->tex[k])->sampled) + n += b->tex_bo[k]->size; + } + return n; +} + +/* whether these textures fit in the render with the ones it has (one + * draw's alone always do, and a draw adding none) */ +static bool +tex_room(struct sgx_context *ctx, struct pipe_resource **tex, unsigned ntex) +{ + struct sgx_batch *b = &ctx->batch; + uint64_t n = b->tex_bytes; + + for (unsigned i = 0; i < ntex; i++) + if (tex_entry(b, tex[i]) == b->ntex) + n += tex_bytes(tex[i]); + return !b->ndraws || n == b->tex_bytes || n <= SGX_BATCH_TEX_BYTES || + dead_tex_bytes(b) <= SGX_BATCH_TEX_BYTES; +} + +/* how many more buffers the render would list for the kernel with these + * textures and buffers' GPU copies (M26) besides its own */ +static unsigned +more_handles(struct sgx_context *ctx, struct pipe_resource **tex, unsigned ntex, + struct sgx_bo **bos, unsigned nbos) +{ + struct sgx_batch *b = &ctx->batch; + unsigned n = 0; + + for (unsigned i = 0; i < ntex; i++) + n += tex_entry(b, tex[i]) == b->ntex; + for (unsigned i = 0; i < nbos; i++) + n += bos[i]->batch_ctx != ctx || bos[i]->batch_seq != b->seq; + return n; +} + +/* the textures and buffers' GPU copies listed for the render, referenced + * (more_handles() said there is room) */ +static void +add_handles(struct sgx_context *ctx, struct pipe_resource **tex, unsigned ntex, + struct sgx_bo **bos, unsigned nbos) +{ + struct sgx_batch *b = &ctx->batch; + + for (unsigned i = 0; i < ntex; i++) { + struct sgx_bo *bo = sgx_resource(tex[i])->sampled; + + if (tex_entry(b, tex[i]) == b->ntex) { + b->tex_bytes += tex_bytes(tex[i]); + pipe_resource_reference(&b->tex[b->ntex], tex[i]); + sgx_bo_ref(bo); + /* (stamped: sgx_batch_reads() says the copy is the render's) */ + bo->batch_ctx = ctx; + bo->batch_seq = b->seq; + b->tex_bo[b->ntex] = bo; + b->handles[b->ntex++] = bo->handle; + } + } + for (unsigned i = 0; i < nbos; i++) { + if (bos[i]->batch_ctx == ctx && bos[i]->batch_seq == b->seq) + continue; + sgx_bo_ref(bos[i]); + bos[i]->batch_ctx = ctx; + bos[i]->batch_seq = b->seq; + b->bos[b->nbos++] = bos[i]; + } +} + +/* what a draw does to the depth buffer's tiles, noted for the render */ +static void +note_zs(struct sgx_context *ctx, const struct sgx_frame_state *st) +{ + struct sgx_batch *b = &ctx->batch; + + /* (and an occlusion query's draw: the render counts, M37) */ + b->counted |= st->count; + if (!ctx->fb.zsbuf.texture) + return; + b->zs_written |= st->depth_write || (st->stencil_on && (st->stencil & 0xff)); + b->zs_read |= (st->depth_func != PIPE_FUNC_ALWAYS && st->depth_func != PIPE_FUNC_NEVER) || + st->stencil_on; +} + +/* ---- a vertex shader's stream straight into GPU memory (M42) ----------- + * + * SDL's sprites are the CPU's stream: their vertices went into a buffer of + * the context's, then the batch's, then the render's memory -- three copies + * of every vertex, a sixth of SuperTux's CPU in its menu's heavy scene + * (memcpy-who). gpu_vs_draw now writes the stream once, into the batch's + * vertex chunks (GPU memory from the buffer cache), and the render reads it + * there. */ + +/* the batch's vertex chunks no render took (a flush of no draws) */ +static void +drop_vchunks(struct sgx_batch *b) +{ + for (unsigned i = 0; i < b->nvchunks; i++) + sgx_bo_destroy(b->vchunk[i]); + b->nvchunks = b->vat = 0; +} + +/* Room for n bytes of the stream after the batch's vertices (a new chunk + * when the last has none): the CPU's address to write it at, noted in + * ctx->vtx with its chunk referenced -- a flush before the draw is added + * hands that chunk to the render, and vtx_commit() copies the stream on. + * Right after them, dword aligned only: a draw merged into the last one + * needs its vertices to follow the last one's (aligned to 16, SDL's 120 + * bytes a quad left a gap and nothing merged) */ +static uint8_t * +vtx_reserve(struct sgx_context *ctx, unsigned n) +{ + struct sgx_screen *screen = sgx_screen(ctx->base.screen); + struct sgx_batch *b = &ctx->batch; + struct sgx_vtx *v = &ctx->vtx; + struct sgx_bo *bo = b->nvchunks ? b->vchunk[b->nvchunks - 1] : NULL; + uint32_t at = align(b->vat, 4); + + if (!bo || at + n > bo->size) { + if (b->nvchunks == SGX_BATCH_VCHUNKS || + b->ntex + b->nbos + b->nvchunks >= SGX_FRAME_MAX_HANDLES) { + sgx_batch_flush(ctx); + drop_vchunks(b); + } + if (!(bo = sgx_bo_cache_get(&screen->dev, MAX2(n, SGX_BATCH_VCHUNK)))) + return NULL; + b->vchunk[b->nvchunks++] = bo; + at = 0; + } + sgx_bo_ref(bo); + sgx_bo_destroy(v->vchunk); + v->vchunk = bo; + v->vdata = bo->map + at; + v->vdata_va = bo->va + at; + v->vseq = b->seq; + return v->vdata; +} + +/* The n bytes written at ctx->vtx's room made the batch's: their address + * for the GPU (0: no room). Written for a batch flushed since, they are + * copied into this one's chunks first (once a render, at most). */ +static uint32_t +vtx_commit(struct sgx_context *ctx, unsigned n) +{ + struct sgx_batch *b = &ctx->batch; + struct sgx_vtx *v = &ctx->vtx; + + if (!v->vchunk) + return 0; + if (v->vseq != b->seq || !b->nvchunks || b->vchunk[b->nvchunks - 1] != v->vchunk) { + struct sgx_bo *old = v->vchunk; + const uint8_t *src = v->vdata; + uint8_t *dst; + + sgx_bo_ref(old); + dst = vtx_reserve(ctx, n); + if (dst) + memcpy(dst, src, n); + sgx_bo_destroy(old); + if (!dst) + return 0; + } + b->vat = v->vdata_va - v->vchunk->va + n; + b->nbytes += n; + return v->vdata_va; +} + +/* A vertex shader's draw (ctx->vtx) added to the last one gathered when + * that has the same state exactly -- the same programs, uniforms (its + * constant attributes among them), textures, layout and ISP state: SDL + * draws a tile a draw, a frame's thousand of them alike (M25) -- and its + * vertices follow on from the last one's: true if it was. */ +static bool +merge_vs_draw(struct sgx_context *ctx, struct sgx_vs *vs, const struct sgx_fs *fs, + const uint32_t *sa, unsigned nsa, const struct sgx_frame_state *st) +{ + struct sgx_screen *screen = sgx_screen(ctx->base.screen); + struct sgx_batch *b = &ctx->batch; + struct sgx_vtx *v = &ctx->vtx; + unsigned nvsa = vs->nuniforms + vs->nubuf, at = 0; + unsigned nbytes = v->repacked ? v->nverts * v->stride : 0, nidx = v->indexed ? v->count : 0; + struct sgx_batch_draw *p; + bool found = false; + + if (!b->ndraws) + return false; + p = &b->draw[b->ndraws - 1]; + if (p->vs != vs || p->compiled != (fs != NULL) || p->repacked != v->repacked || + p->stride != v->stride || + (fs && (p->prog.code_va != fs->prog.code_va || p->prog.pds_va != fs->prog.pds_va))) + return no_merge(MERGE_PROGRAM); + if (fs && !sgx_words_equal(b->sa + p->sa, sa, nsa)) { + unsigned t0 = fs->sampler_sa, t1 = fs->sampler_sa + 4 * fs->nsamplers; + + /* (only the textures' words: another texture) */ + return no_merge(fs->nsamplers && t1 <= nsa && sgx_words_equal(b->sa + p->sa, sa, t0) && + sgx_words_equal(b->sa + p->sa + t1, sa + t1, nsa - t1) ? + MERGE_TEXTURES : MERGE_FS_SA); + } + if (p->l.nvaryings != ctx->layout.nvaryings || p->l.f32 != ctx->layout.f32 || + p->l.colour != ctx->layout.colour || p->l.ncolours != ctx->layout.ncolours) + return no_merge(MERGE_LAYOUT); + if (!sgx_frame_state_equal(&p->st, st)) + return no_merge(MERGE_STATE); + if (p->vs_sa + nvsa > b->nsa || !sgx_words_equal(b->sa + p->vs_sa, ctx->vs_sa, nvsa)) + return no_merge(MERGE_VS_SA); + + /* where its vertex 0 is among the last draw's vertices: right after + * them (the CPU's stream), or where its attributes' addresses say -- + * the same number of vertices on for each */ + if (v->repacked) { + if (v->vseq != b->seq || p->vdata_va + p->nverts * p->stride != v->vdata_va) + return no_merge(MERGE_VERTICES); + at = p->nverts; + } else { + for (unsigned a = 0; a < vs->nattrs; a++) { + uint32_t d = v->base[a] - p->base[a]; + + if (SGX_ATTR_KIND(vs->attr[a]) == SGX_ATTR_CONST) + continue; + if (!found) { + if (!v->stride || d % v->stride) + return no_merge(MERGE_VERTICES); + at = d / v->stride; + found = true; + } else if (d != at * v->stride) { + return no_merge(MERGE_VERTICES); + } + } + } + /* and its triangles: a list on from the last draw's, or indices after + * its indices (not those in a buffer, M46) */ + if (v->idx_va || p->idx_va) + return no_merge(MERGE_PRIMS); + if (!v->indexed && !p->nidx) { + if (at != p->count || p->count + v->count > sgx_frame_list_max(screen->frame)) + return no_merge(MERGE_PRIMS); + } else if (v->indexed && p->nidx) { + if (p->idx + p->nidx != b->nidx || at + v->max_index > 0xffff) + return no_merge(MERGE_PRIMS); + } else { + return no_merge(MERGE_PRIMS); + } + if (batch_bytes(b) + nbytes + 2 * nidx > SGX_FRAME_MAX_BYTES || + b->ntex + b->nbos + b->nvchunks + more_handles(ctx, NULL, 0, v->bos, v->nbos) > + SGX_FRAME_MAX_HANDLES || + !grow((void **)&b->idx, &b->maxidx, b->nidx + nidx, sizeof(uint16_t))) + return no_merge(MERGE_ROOM); + + add_handles(ctx, NULL, 0, v->bos, v->nbos); + for (unsigned i = 0; i < nidx; i++) + b->idx[b->nidx + i] = ctx->indices[i] + at; + p->nidx += nidx; + b->nidx += nidx; + p->max_index = MAX2(p->max_index, at + v->max_index); + /* (right after the last draw's in its chunk: nothing to copy) */ + if (nbytes) + vtx_commit(ctx, nbytes); + p->nverts += v->repacked ? v->nverts : 0; + p->count += v->count; + return true; +} + +/* A vertex shader's draw (ctx->vtx) into the gathered render: merged into + * the last draw, or a draw of its own */ +static void +add_vs_draw(struct sgx_context *ctx, struct sgx_vs *vs, const struct sgx_fs *fs, + const uint32_t *sa, unsigned nsa, struct pipe_resource **tex, + const struct sgx_frame_target *t, const struct sgx_frame_state *st) +{ + struct sgx_screen *screen = sgx_screen(ctx->base.screen); + struct sgx_batch *b = &ctx->batch; + struct sgx_vtx *v = &ctx->vtx; + unsigned nvsa = vs->nuniforms + vs->nubuf, nidx = v->indexed && !v->idx_va ? v->count : 0; + unsigned nbytes = v->repacked ? v->nverts * v->stride : 0, ntex = fs ? fs->nsamplers : 0; + uint32_t vdata_va = 0; + struct sgx_batch_draw *bd; + + if (merge_vs_draw(ctx, vs, fs, sa, nsa, st)) { + sgx_stat_merged++; + return; + } + /* room in this render: a draw, its vertices, indices, textures and + * buffers */ + if ((b->ndraws == sgx_frame_max_draws(screen->frame) && no_room(ROOM_DRAWS)) || + (b->ntex + b->nbos + b->nvchunks + 1 + more_handles(ctx, tex, ntex, v->bos, v->nbos) > + SGX_FRAME_MAX_HANDLES && no_room(ROOM_HANDLES)) || + (!tex_room(ctx, tex, ntex) && no_room(ROOM_TEXTURES)) || + (batch_bytes(b) + nbytes + 2 * nidx > SGX_FRAME_MAX_BYTES && no_room(ROOM_BYTES))) { + sgx_batch_flush(ctx); + if (nbytes + 2 * nidx > SGX_FRAME_MAX_BYTES || + more_handles(ctx, tex, ntex, v->bos, v->nbos) > SGX_FRAME_MAX_HANDLES) { + mesa_logw_once("sgx: a draw larger than a render takes: dropped"); + return; + } + } + if (!grow((void **)&b->sa, &b->maxsa, b->nsa + nsa + nvsa, sizeof(uint32_t)) || + !grow((void **)&b->idx, &b->maxidx, b->nidx + nidx, sizeof(uint16_t))) + return; + /* the stream where gpu_vs_draw wrote it (copied on if a flush came + * between: before the render's start below) */ + if (nbytes && !(vdata_va = vtx_commit(ctx, nbytes))) { + mesa_logw_once("sgx: no memory for a draw's vertices: dropped"); + return; + } + if (!b->ndraws) + batch_start(ctx, t); + /* from now on sampled linear: decided before any draw samples it */ + t->res->gpu_written = true; + add_handles(ctx, tex, ntex, v->bos, v->nbos); + note_zs(ctx, st); + + bd = &b->draw[b->ndraws++]; + bd->l = ctx->layout; + bd->vdata_va = vdata_va; + bd->nverts = v->repacked ? v->nverts : 0; + bd->compiled = fs != NULL; + if (fs) + bd->prog = fs->prog; + bd->sa = b->nsa; + bd->st = *st; + bd->vs = vs; + bd->vs_sa = b->nsa + nsa; + bd->idx = b->nidx; + bd->nidx = nidx; + bd->idx_va = v->idx_va; + memcpy(bd->base, v->base, sizeof(bd->base)); + bd->stride = v->stride; + bd->count = v->count; + bd->max_index = v->max_index; + bd->repacked = v->repacked; + memcpy(b->sa + b->nsa, sa, nsa * sizeof(uint32_t)); + memcpy(b->sa + b->nsa + nsa, ctx->vs_sa, nvsa * sizeof(uint32_t)); + memcpy(b->idx + b->nidx, ctx->indices, nidx * sizeof(uint16_t)); + b->nsa += nsa + nvsa; + b->nidx += nidx; +} + +/* One draw added to the gathered render: the draw module's triangles + * (ctx->verts, ctx->nverts), in pieces when they are more than one draw of + * a render takes -- or, with ctx->gpu_vs, a vertex shader's (ctx->vtx) */ +/* (M43) A stage's uniform buffers (ARB_uniform_buffer_object): each one + * the program reads made the GPU's (its copy, M26), its address less 4 in + * the program's sa word for it, the buffer added to bos (once). False if + * one is not there: the draw goes without. */ +static bool +ubo_words(struct sgx_context *ctx, unsigned stage, uint16_t mask, const uint8_t *ubo_sa, + uint32_t *sa, struct sgx_bo **bos, unsigned *nbos) +{ + u_foreach_bit(k, mask) { + const struct pipe_constant_buffer *u = &ctx->ubo[stage][k]; + struct sgx_bo *bo; + unsigned i; + + if (!u->buffer || !(bo = sgx_buffer_bo(ctx, sgx_resource(u->buffer), u->buffer_offset, + u->buffer_offset + u->buffer_size))) + return false; + sa[ubo_sa[k]] = bo->va + u->buffer_offset - 4; + for (i = 0; i < *nbos && bos[i] != bo; i++) + ; + if (i == *nbos) + bos[(*nbos)++] = bo; + } + return true; +} + +/* (M46) Whether a draw is opaque to the ISP: a compiled pixel program + * that reads nothing of what the tile holds -- not blended, every channel + * written, no logic op, no discard (M19's keeps the tile's colour), no + * framebuffer fetch. The ISP then removes what is hidden and shades each + * pixel once, where a translucent draw is shaded wherever it covers. + * SGX_OPAQUE=0: every draw translucent, as before. */ +static bool +opaque_draw(const struct sgx_context *ctx, const struct sgx_fs *fs) +{ + static int on = -1; + const struct sgx_shader *sh = ctx->fs; + + if (on < 0) + on = debug_get_bool_option("SGX_OPAQUE", true); + if (!on || !fs || !sh || !sh->nir) + return false; + if (fs->blend.enable || fs->blend.colormask != 0xf || fs->blend.logicop || + fs->blend.rt_srgb || fs->blend.rt_intensity) + return false; + return !sh->nir->info.fs.uses_discard && !sh->nir->info.fs.uses_fbfetch_output; +} + +static void +submit(struct sgx_context *ctx) +{ + struct sgx_screen *screen = sgx_screen(ctx->base.screen); + struct sgx_batch *b = &ctx->batch; + struct pipe_surface *surf = &ctx->fb.cbufs[0]; + struct sgx_resource *rt = surf->texture ? sgx_resource(surf->texture) : NULL; + struct sgx_fs *fs = ctx->draw_fs; + /* (sa's 128 words, then those of the uniforms in memory, M32) */ + uint32_t sa[128 + SGX_UBUF_MAX]; + struct pipe_resource *tex[SGX_FS_MAX_SAMPLERS]; + struct sgx_vs *vs = ctx->gpu_vs; + unsigned vf = sgx_frame_vertex_floats(&ctx->layout); + unsigned nsa = fs ? fs->prog.nsa + fs->prog.nubuf : 0; + unsigned max, done = 0, npass = 1; + uint32_t face_stencil[2]; + struct sgx_bo *fs_bos[SGX_FRAME_MAX_UBOS]; + unsigned nfs_bos = 0; + bool two_sided = false; + struct sgx_frame_state pass[2]; + struct sgx_frame_target target; + float ab[4]; + struct sgx_frame_state st = { + .depth_func = ctx->dsa && ctx->dsa->depth_enabled ? ctx->dsa->depth_func : PIPE_FUNC_ALWAYS, + .depth_write = ctx->dsa && ctx->dsa->depth_enabled && ctx->dsa->depth_writemask, + /* an occlusion query's samples (M37) */ + .count = ctx->query && !ctx->queries_off, + }; + + /* the stencil test (M23): ISP state B -- compare in 27:25 (as the depth + * compare, gallium's order), the ops on stencil fail, depth fail and + * pass in 24:22, 21:19, 18:16, the compare mask in 15:8 and the write + * mask in 7:0 -- the reference in ISP state A's low byte */ + if (ctx->dsa && ctx->dsa->stencil[0].enabled && ctx->fb.zsbuf.texture && + util_format_has_stencil(util_format_description(ctx->fb.zsbuf.texture->format))) { + /* gallium's ops in the order of the hardware's: keep, zero, replace, + * incr, decr, invert, incr wrap, decr wrap */ + static const uint8_t op[8] = { + [PIPE_STENCIL_OP_KEEP] = 0, [PIPE_STENCIL_OP_ZERO] = 1, + [PIPE_STENCIL_OP_REPLACE] = 2, [PIPE_STENCIL_OP_INCR] = 3, + [PIPE_STENCIL_OP_DECR] = 4, [PIPE_STENCIL_OP_INVERT] = 5, + [PIPE_STENCIL_OP_INCR_WRAP] = 6, [PIPE_STENCIL_OP_DECR_WRAP] = 7, + }; + + for (unsigned f = 0; f < 2; f++) { + const struct pipe_stencil_state *s = &ctx->dsa->stencil[f && ctx->dsa->stencil[1].enabled]; + + face_stencil[f] = (uint32_t)(s->func & 7) << 25 | (uint32_t)op[s->fail_op & 7] << 22 | + (uint32_t)op[s->zfail_op & 7] << 19 | + (uint32_t)op[s->zpass_op & 7] << 16 | (uint32_t)s->valuemask << 8 | + s->writemask; + } + st.stencil_on = true; + st.stencil = face_stencil[0]; + st.stencil_ref = ctx->stencil_ref.ref_value[0]; + two_sided = face_stencil[1] != face_stencil[0] || + (ctx->dsa->stencil[1].enabled && + ctx->stencil_ref.ref_value[1] != ctx->stencil_ref.ref_value[0]); + } + + if (vs ? !ctx->vtx.count : !ctx->nverts) + return; + if (!clip_to(ctx, vs, &st, ab)) { + ctx->nverts = 0; + return; + } + if (vs) { + const struct pipe_rasterizer_state *r = ctx->rast; + + /* (M47: a_x, a_y, b_x, b_y -- pairs the program reads two at a + * time, from an even word) */ + const float abp[4] = { ab[0], ab[2], ab[1], ab[3] }; + + memcpy(ctx->vs_sa + vs->clip_sa, abp, sizeof(abp)); + /* gallium's anticlockwise is the target's, row 0 at the top: the + * TA's; the back faces are what the front ones are not */ + if (r->cull_face == PIPE_FACE_BACK) + st.cull = r->front_ccw ? SGX_CULL_CW : SGX_CULL_CCW; + else if (r->cull_face == PIPE_FACE_FRONT) + st.cull = r->front_ccw ? SGX_CULL_CCW : SGX_CULL_CW; + } + /* polygon offset (M37): the ISP's on the GPU's vertex path (the draw + * module offsets its vertices itself) */ + if (vs && isp_offset(ctx->rast) != ~0u) + st.offset = isp_offset(ctx->rast); + /* flat shading (M37): iOS's word (the first vertex's colours by the + * triangles turned round: flat_first()) */ + if (fs && fs->prog.ncolours) + st.flat = SGX_FLAT_LAST; + st.opaque = opaque_draw(ctx, fs); + if (ctx->debug_draw && !vs) { + mesa_logi("sgx: %u triangles; the first:", ctx->nverts / 3); + for (unsigned i = 0; i < MIN2(ctx->nverts, 3); i++) { + const float *v = ctx->verts + i * vf; + const float *c = v + 4 + 4 * ctx->layout.colour; + + mesa_logi("sgx: x %8.4f y %8.4f z %8.4f colour %.3f %.3f %.3f %.3f", + v[0], v[1], v[2], c[0], c[1], c[2], c[3]); + } + } + if (!screen->frame) { + mesa_logw_once("sgx: no template frame (./cascadia a5 dev gpu installs it): draws are dropped"); + ctx->nverts = 0; + return; + } + if (!fb_target(ctx, &target) || !sgx_frame_can_render(screen->frame, &target)) { + mesa_logw_once("sgx: draws only go into the B8G8R8A8 targets the template frame " + "can fill (up to 4096 x 4096); others are dropped"); + ctx->nverts = 0; + return; + } + if (batch_elsewhere(b, &target)) + sgx_batch_flush(ctx); + + /* SGX_FRAME=packvertex, packpixel: the pack's sides, a render a draw, + * M13a's colour (debugging only) */ + if (!vs && (sgx_frame_options() & (SGX_FRAME_PACKVTX | SGX_FRAME_PACKPIX)) && rt && + !surf->level && !surf->first_layer) { + sgx_batch_flush(ctx); + max = sgx_frame_max_vertices(screen->frame, &ctx->layout); + for (done = 0; done < ctx->nverts; done += max) { + unsigned n = MIN2(ctx->nverts - done, max); + struct sgx_fence *fence = sgx_fence_create(&screen->dev, false); + + if (!fence) + break; + simple_mtx_lock(&screen->frame_lock); + if (!sgx_frame_draw(screen->frame, rt, &ctx->layout, ctx->verts + done * vf, n, + NULL, NULL, NULL, 0, &st, fence)) { + sgx_fence_reference(&ctx->last, fence); + rt->seq++; + rt->gpu_written = true; + } + simple_mtx_unlock(&screen->frame_lock); + sgx_fence_reference(&fence, NULL); + } + ctx->nverts = 0; + return; + } + + /* the draw module's vertices through the clip rectangle's x' = a x + b w */ + if (!vs) + for (unsigned i = 0; i < ctx->nverts; i++) { + float *v = ctx->verts + i * vf; + + v[0] = ab[0] * v[0] + ab[1] * v[3]; + v[1] = ab[2] * v[1] + ab[3] * v[3]; + } + + /* a compiled fragment shader's secondary attributes: its uniforms, + * then the state words of each texture it samples, the blend colour */ + if (fs) { + unsigned n = MIN2(fs->nuniforms, ctx->fs_constants_size / 4); + + memset(sa, 0, nsa * sizeof(uint32_t)); + if (ctx->fs_constants) + memcpy(sa, ctx->fs_constants, n * sizeof(float)); + /* the uniforms past sa's, all of them in memory after it (M32) */ + if (fs->prog.nubuf && ctx->fs_constants) + memcpy(sa + fs->prog.nsa, ctx->fs_constants, + MIN2(fs->prog.nubuf, ctx->fs_constants_size / 4) * sizeof(float)); + /* (M43) its uniform buffers */ + if (fs->prog.ubo_mask && + !ubo_words(ctx, 1, fs->prog.ubo_mask, fs->prog.ubo_sa, sa, fs_bos, &nfs_bos)) { + mesa_logw_once("sgx: a uniform buffer the fragment shader reads is not bound: the " + "draw dropped"); + ctx->nverts = 0; + return; + } + for (unsigned i = 0; i < fs->nsamplers; i++) { + unsigned unit = fs->sampler_unit[i]; + struct pipe_sampler_view *view = unit < ARRAY_SIZE(ctx->fs_views) ? + ctx->fs_views[unit] : NULL; + struct sgx_resource *t = view ? sgx_resource(view->texture) : NULL; + const struct pipe_sampler_state *ss = unit < PIPE_MAX_SAMPLERS ? + ctx->fs_samplers[unit] : NULL; + + /* the target itself: what was gathered goes first (a copy made + * again while draws read the old one is a new buffer, M37) */ + if (t && &t->base == b->rt) + sgx_batch_flush(ctx); + if (!t || !sgx_resource_texture(ctx, t, view, ss, sa + fs->sampler_sa + 4 * i)) { + mesa_logw_once("sgx: a draw samples a texture unit with nothing it can " + "sample bound: dropped"); + ctx->nverts = 0; + return; + } + tex[i] = &t->base; + /* (M46) sampled as F16 by the program itself: 0..1 */ + if (fs->smp_norm >> i & 1) + sa[fs->sampler_sa + 4 * i + 3] |= 0x80000000u; + if (fs->scale_sa >= 0) { + float scale[2] = { 1.0f / u_minify(t->base.width0, view->u.tex.first_level), + 1.0f / u_minify(t->base.height0, view->u.tex.first_level) }; + + memcpy(sa + fs->scale_sa + 2 * i, scale, sizeof(scale)); + } + if (fs->size_sa >= 0) { + /* (M44) textureSize, texelFetch: the view's base level, the + * sampler's level 0 (sgx_compiler.h, SGX_FS_SIZE_WORDS) */ + unsigned first = view->u.tex.first_level; + unsigned w = u_minify(t->base.width0, first); + unsigned h = t->base.target == PIPE_TEXTURE_1D ? 1 : u_minify(t->base.height0, first); + uint32_t *z = sa + fs->size_sa + SGX_FS_SIZE_WORDS * i; + float f[4] = { 1.0f / w, 1.0f / h, 0.5f / w, 0.5f / h }; + + z[0] = w; + z[1] = h; + z[2] = view->u.tex.last_level - first + 1; + z[3] = 0; + memcpy(z + 4, f, sizeof(f)); + } + } + if (fs->blend_sa >= 0 && fs->blend_packed) { + /* (M46) SOP2's: RGBA bytes, as the tile holds them */ + uint32_t w = 0; + + for (unsigned i = 0; i < 4; i++) + w |= (uint32_t)lroundf(CLAMP(ctx->blend_color.color[i], 0.0f, 1.0f) * 255.0f) + << (8 * i); + sa[fs->blend_sa] = w; + } else if (fs->blend_sa >= 0) { + memcpy(sa + fs->blend_sa, ctx->blend_color.color, 4 * sizeof(float)); + } + /* (M46) its constants, and the pairs worked out from the uniforms + * (sgx_fs_derived: in order, each from words before it) */ + for (unsigned k = 0; k < 2 * fs->nkconst; k++) + sa[fs->kconst_sa + k] = fs->kconst[k]; + for (unsigned k = 0; k < fs->nderived; k++) { + const struct sgx_fs_derived *d = &fs->derived[k]; + uint32_t *w = sa + fs->kconst_sa + 2 * d->pair; + + if (d->kind == SGX_DERIVED_F16) { + w[0] = _mesa_float_to_half(uif(sa[d->a])) | + (uint32_t)_mesa_float_to_half(uif(sa[d->a + 1])) << 16; + w[1] = _mesa_float_to_half(uif(sa[d->a + 2])) | + (uint32_t)_mesa_float_to_half(uif(sa[d->a + 3])) << 16; + } else { + float a = d->neg_a ? -uif(sa[d->a]) : uif(sa[d->a]); + float bv = d->neg_b ? -uif(sa[d->b]) : uif(sa[d->b]); + + w[0] = fui(d->kind == SGX_DERIVED_ADD ? a + bv : + d->kind == SGX_DERIVED_MUL ? a * bv : + d->kind == SGX_DERIVED_MIN ? fminf(a, bv) : fmaxf(a, bv)); + w[1] = 0; + } + } + simple_mtx_lock(&screen->frame_lock); + if (sgx_frame_upload(screen->frame, &fs->prog) || + (vs && sgx_frame_upload_vs(screen->frame, vs))) { + simple_mtx_unlock(&screen->frame_lock); + ctx->nverts = 0; + return; + } + simple_mtx_unlock(&screen->frame_lock); + } + + /* two-sided stencil: the front faces with theirs, then the back ones + * with theirs -- a pass each, the TA culling the other faces (the + * draw module has culled what the rasterizer state does) */ + pass[0] = st; + if (two_sided) { + const struct pipe_rasterizer_state *r = ctx->rast; + uint8_t back = r->front_ccw ? SGX_CULL_CW : SGX_CULL_CCW; + uint8_t front = r->front_ccw ? SGX_CULL_CCW : SGX_CULL_CW; + + npass = 0; + if (r->cull_face != PIPE_FACE_FRONT) { + pass[npass] = st; + pass[npass++].cull = back; + } + if (r->cull_face != PIPE_FACE_BACK) { + pass[npass] = st; + pass[npass].cull = front; + pass[npass].stencil = face_stencil[1]; + pass[npass++].stencil_ref = ctx->stencil_ref.ref_value[1]; + } + } + + { + /* (M43) the fragment shader's uniform buffers with the draw's */ + struct sgx_vtx *v = &ctx->vtx; + + for (unsigned i = 0; vs && i < nfs_bos; i++) { + unsigned j; + + for (j = 0; j < v->nbos && v->bos[j] != fs_bos[i]; j++) + ; + if (j == v->nbos && v->nbos < ARRAY_SIZE(v->bos)) + v->bos[v->nbos++] = fs_bos[i]; + } + } + for (unsigned k = 0; vs && k < npass; k++) + add_vs_draw(ctx, vs, fs, sa, nsa, tex, &target, &pass[k]); + + max = sgx_frame_max_vertices(screen->frame, &ctx->layout); + for (unsigned k = 0; !vs && k < npass; k++) + for (done = 0, st = pass[k]; done < ctx->nverts;) { + unsigned n = MIN2(ctx->nverts - done, max), ntex = fs ? fs->nsamplers : 0; + struct sgx_batch_draw *bd; + + /* room in this render: a draw, its vertices, its textures */ + if ((b->ndraws == sgx_frame_max_draws(screen->frame) && no_room(ROOM_DRAWS)) || + (b->ntex + b->nbos + b->nvchunks + more_handles(ctx, tex, ntex, fs_bos, nfs_bos) > + SGX_FRAME_MAX_HANDLES && no_room(ROOM_HANDLES)) || + (!tex_room(ctx, tex, ntex) && no_room(ROOM_TEXTURES)) || + (batch_bytes(b) + n * vf * sizeof(float) > SGX_FRAME_MAX_BYTES && no_room(ROOM_BYTES))) + sgx_batch_flush(ctx); + if (!grow((void **)&b->verts, &b->maxfloats, b->nfloats + n * vf, sizeof(float)) || + !grow((void **)&b->sa, &b->maxsa, b->nsa + nsa, sizeof(uint32_t))) + break; + if (!b->ndraws) + batch_start(ctx, &target); + /* from now on sampled linear: decided before any draw samples it */ + target.res->gpu_written = true; + add_handles(ctx, tex, ntex, fs_bos, nfs_bos); + note_zs(ctx, &st); + bd = &b->draw[b->ndraws++]; + memset(bd, 0, sizeof(*bd)); + bd->l = ctx->layout; + bd->first = b->nfloats; + bd->nverts = n; + bd->compiled = fs != NULL; + if (fs) + bd->prog = fs->prog; + bd->sa = b->nsa; + bd->st = st; + bd->vs_sa = b->nsa + nsa; + bd->idx = b->nidx; + memcpy(b->verts + b->nfloats, ctx->verts + done * vf, n * vf * sizeof(float)); + memcpy(b->sa + b->nsa, sa, nsa * sizeof(uint32_t)); + b->nfloats += n * vf; + b->nsa += nsa; + done += n; + } + ctx->nverts = 0; +} + +/* A quad over the rectangle sc (all of the target: NULL) at the depth d, + * its pixel program prog with sa[0..nsa) in its secondary attributes, the + * ISP doing what st says; false when there is no room in the render (and + * room is not to be made: flush false) */ +static bool +quad(struct sgx_context *ctx, const struct pipe_scissor_state *sc, float d, + const struct sgx_frame_state *st, struct sgx_pixel_program *prog, const uint32_t *sa, + unsigned nsa, bool flush) +{ + static const struct sgx_frame_layout l = { .nvaryings = 1, .f32 = 1, .colour = 0 }; + struct sgx_screen *screen = sgx_screen(ctx->base.screen); + struct sgx_batch *b = &ctx->batch; + unsigned vf = sgx_frame_vertex_floats(&l); + /* the rectangle in clip space, through the target's whole viewport (rows + * from the first: gallium's framebuffer space), at the depth d */ + float x0 = sc ? 2.0f * sc->minx / ctx->fb.width - 1 : -1; + float x1 = sc ? 2.0f * sc->maxx / ctx->fb.width - 1 : 1; + float y0 = sc ? 2.0f * sc->miny / ctx->fb.height - 1 : -1; + float y1 = sc ? 2.0f * sc->maxy / ctx->fb.height - 1 : 1; + float z = 2 * d - 1; + /* x y z w, then the varying nobody reads */ + const float quad[6][8] = { + { x0, y0, z, 1 }, { x1, y0, z, 1 }, { x1, y1, z, 1 }, + { x0, y0, z, 1 }, { x1, y1, z, 1 }, { x0, y1, z, 1 }, + }; + struct sgx_frame_target target; + struct sgx_batch_draw *bd; + int ret; + + if (!ctx->fb.width || !ctx->fb.height || !fb_target(ctx, &target) || + !sgx_frame_can_render(screen->frame, &target)) + return false; + if (batch_elsewhere(b, &target)) { + if (!flush) + return false; + sgx_batch_flush(ctx); + } + simple_mtx_lock(&screen->frame_lock); + ret = sgx_frame_upload(screen->frame, prog); + simple_mtx_unlock(&screen->frame_lock); + if (ret) + return false; + if (b->ndraws == sgx_frame_max_draws(screen->frame) || + batch_bytes(b) + sizeof(quad) > SGX_FRAME_MAX_BYTES) { + if (!flush) + return false; + sgx_batch_flush(ctx); + } + if (!grow((void **)&b->verts, &b->maxfloats, b->nfloats + 6 * vf, sizeof(float)) || + !grow((void **)&b->sa, &b->maxsa, b->nsa + nsa, sizeof(uint32_t))) + return false; + if (!b->ndraws) + batch_start(ctx, &target); + target.res->gpu_written = true; + bd = &b->draw[b->ndraws++]; + memset(bd, 0, sizeof(*bd)); + bd->l = l; + bd->first = b->nfloats; + bd->nverts = 6; + bd->compiled = true; + bd->prog = *prog; + bd->sa = b->nsa; + memcpy(b->sa + b->nsa, sa, nsa * sizeof(uint32_t)); + b->nsa += nsa; + bd->vs_sa = b->nsa; + bd->idx = b->nidx; + bd->st = *st; + b->zs_written |= st->depth_write || (st->stencil_on && (st->stencil & 0xff)); + memcpy(b->verts + b->nfloats, quad, sizeof(quad)); + b->nfloats += 6 * vf; + return true; +} + +/* a quad whose pixel program writes nothing (o0 keeps the tile's colour) */ +static bool +zs_quad(struct sgx_context *ctx, const struct pipe_scissor_state *sc, float d, + const struct sgx_frame_state *st, bool flush) +{ + static const uint64_t nothing[2] = { 0xfa44070000000000ull, 0xf804014000000000ull }; + + if (!ctx->clear_prog.code) { + ctx->clear_prog.code = (uint64_t *)nothing; + ctx->clear_prog.ncode = 2; + ctx->clear_prog.ninputs = 1; + ctx->clear_prog.nvaryings = 1; + } + return quad(ctx, sc, d, st, &ctx->clear_prog, NULL, 0, flush); +} + +/* A colour clear (all four channels) in the render, a quad over the + * rectangle whose program puts the colour, packed, in o0 (`or o0, sa0, + * #0`) -- not a render of its own, which waited for the last one to be + * done and ended the gathered draws (M25) */ +bool +sgx_colour_clear(struct sgx_context *ctx, const union pipe_color_union *color, + const struct pipe_scissor_state *sc) +{ + const struct sgx_frame_state st = { .depth_func = PIPE_FUNC_ALWAYS }; + uint32_t packed = 0; + + if (!ctx->colour_prog.code) { + ctx->colour_code[0] = USSE_PHAS; + ctx->colour_code[1] = usse_vbw_or(usse_reg(USSE_OUTPUT, 0), usse_reg(USSE_SA, 0), 0) | + USSE_END; + ctx->colour_prog.code = ctx->colour_code; + ctx->colour_prog.ncode = 2; + ctx->colour_prog.ninputs = 1; + ctx->colour_prog.nvaryings = 1; + ctx->colour_prog.nsa = 1; + } + /* (M43) a target of floats: the colour's four F32 from sa, packed as + * the tile holds it by one instruction (two moves of raw words, o0 then + * o1, left o1 unwritten): a program for each kind of tile */ + if (ctx->fb.nr_cbufs && ctx->fb.cbufs[0].texture && + sgx_frame_rt_kind(ctx->fb.cbufs[0].format) != SGX_RT_UNORM8) { + enum sgx_rt_kind k = sgx_frame_rt_kind(ctx->fb.cbufs[0].format); + struct sgx_pixel_program *prog = &ctx->colour_float_prog[k]; + uint64_t *code = ctx->colour_float_code[k]; + struct usse_reg o0 = usse_reg(USSE_OUTPUT, 0), sa0 = usse_reg(USSE_SA, 0); + + if (!prog->code) { + code[0] = USSE_PHAS; + code[1] = (k == SGX_RT_F16X4 ? usse_pack_f16(o0, sa0, 0xf) : + k == SGX_RT_F16X2 ? usse_pack_f16(o0, sa0, 0x3) : + k == SGX_RT_F32X2 ? usse_pack_f32x2(o0, sa0) : + usse_vbw_or(o0, sa0, 0)) | USSE_END; + prog->code = code; + prog->ncode = 2; + prog->ninputs = 1; + prog->nvaryings = 1; + prog->nsa = 4; + } + return quad(ctx, sc, 0.5f, &st, prog, (const uint32_t *)color->f, 4, true); + } + /* (an sRGB target's colour encoded, M43: what GL's clear writes there) */ + for (unsigned i = 0; i < 4; i++) + packed |= (uint32_t)(i < 3 && ctx->fb.nr_cbufs && ctx->fb.cbufs[0].texture && + util_format_is_srgb(ctx->fb.cbufs[0].format) ? + util_format_linear_float_to_srgb_8unorm(color->f[i]) : + float_to_ubyte(color->f[i])) << 8 * i; + return quad(ctx, sc, 0.5f, &st, &ctx->colour_prog, &packed, 1, true); +} + +/* A render starts at the last depth clear's value and stencil 0 (or from + * memory, M24) -- no register for another stencil was found. So a clear + * inside a render, a scissored one, or one to another stencil, is a quad + * over the cleared rectangle at the cleared depth: depth ALWAYS (written if + * cleared), stencil ALWAYS, REPLACE by value through mask (if cleared). */ +void +sgx_zs_clear(struct sgx_context *ctx, bool depth, float d, bool stencil, unsigned value, + unsigned mask, const struct pipe_scissor_state *sc) +{ + const struct sgx_frame_state st = { + .depth_func = PIPE_FUNC_ALWAYS, + .depth_write = depth, + .stencil_on = stencil, + .stencil = 7u << 25 | 2u << 22 | 2u << 19 | 2u << 16 | 0xffu << 8 | (mask & 0xff), + .stencil_ref = value, + }; + + zs_quad(ctx, sc, depth ? d : 0.5f, &st, true); +} + +/* ---- the vertex shader on the GPU (M18) --------------------------------- */ + +uint8_t +sgx_attr_of_format(enum pipe_format format) +{ + switch (format) { + case PIPE_FORMAT_R32_FLOAT: return SGX_ATTR(SGX_ATTR_F32, 1); + case PIPE_FORMAT_R32G32_FLOAT: return SGX_ATTR(SGX_ATTR_F32, 2); + case PIPE_FORMAT_R32G32B32_FLOAT: return SGX_ATTR(SGX_ATTR_F32, 3); + case PIPE_FORMAT_R32G32B32A32_FLOAT: return SGX_ATTR(SGX_ATTR_F32, 4); + case PIPE_FORMAT_R8_UNORM: return SGX_ATTR(SGX_ATTR_U8N, 1); + case PIPE_FORMAT_R8G8_UNORM: return SGX_ATTR(SGX_ATTR_U8N, 2); + case PIPE_FORMAT_R8G8B8_UNORM: return SGX_ATTR(SGX_ATTR_U8N, 3); + case PIPE_FORMAT_R8G8B8A8_UNORM: return SGX_ATTR(SGX_ATTR_U8N, 4); + default: return 0; + } +} + +/* The vertex shader for the bound fragment shader's varyings and the + * attributes' formats (attr): compiled once for each; NULL when it cannot + * be (the draw module's way then) */ +static struct sgx_vs * +vs_for_draw(struct sgx_context *ctx, const struct sgx_fs *fs, const uint8_t *attr) +{ + struct sgx_shader *sh = ctx->vs; + unsigned slot[SGX_FRAME_MAX_VARYINGS], n = 0; + union { + uint8_t b[SGX_VS_MAX_ATTRIBS]; + uint32_t w[SGX_VS_MAX_ATTRIBS / 4]; + } key; + struct sgx_vs *vs; + char why[128]; + + if (!sh || !sh->nir || sh->vs_failed) + return NULL; + for (unsigned i = 0; i < fs->prog.nvaryings; i++) + slot[n++] = fs->varying_slot[i]; + /* (as sgx_compile_vs fills it in) */ + for (unsigned a = 0; a < SGX_VS_MAX_ATTRIBS; a++) + key.b[a] = a < sh->vs_nattrs ? attr[a] : SGX_ATTR(SGX_ATTR_CONST, 4); + /* (and what it does to the varyings the PDS's lookups alone read, M39) */ + for (unsigned i = 0; i < sh->nvs; i++) + if (sh->vs_variant[i]->nvaryings == n && + sgx_words_equal(sh->vs_variant[i]->varying_slot, slot, n) && + sgx_words_equal(sh->vs_variant[i]->attr_words, key.w, ARRAY_SIZE(key.w)) && + !memcmp(sh->vs_variant[i]->vary_fix, fs->vary_fix, n)) + return sh->vs_variant[i]; + if (!(vs = sgx_compile_vs(sh->nir, slot, n, attr, fs->vary_fix, why, sizeof(why)))) { + mesa_logw("sgx: a vertex shader not compiled (%s): run on the CPU", why); + sh->vs_failed = true; + return NULL; + } + if (debug_get_bool_option("SGX_DEBUG_SHADER", false)) { + mesa_logi("sgx: a vertex shader: %u instructions, %u temps, %u attributes, %u " + "uniform words", vs->ncode, vs->ntemps, vs->nattrs, vs->nuniforms); + for (unsigned i = 0; i < vs->ncode; i++) + mesa_logi("sgx: %016llx", (unsigned long long)vs->code[i]); + } + if (sh->nvs == ARRAY_SIZE(sh->vs_variant)) { + sgx_batch_bury_vs(ctx, sh->vs_variant[0]); + memmove(sh->vs_variant, sh->vs_variant + 1, (ARRAY_SIZE(sh->vs_variant) - 1) * sizeof(vs)); + sh->nvs--; + } + sh->vs_variant[sh->nvs++] = vs; + return vs; +} + +static bool +index_at(const void *indices, unsigned size, unsigned i, unsigned *out) +{ + switch (size) { + case 1: *out = ((const uint8_t *)indices)[i]; return true; + case 2: *out = ((const uint16_t *)indices)[i]; return true; + case 4: *out = ((const uint32_t *)indices)[i]; return true; + default: return false; + } +} + +/* GL's polygon offset as the ISP's (state word 2, M37): whole factors and + * units, -16..15 each (units GL's, the ISP's unit its r -- iOS's); 0 none, + * ~0u one it does not do. Not unless SGX_ISP_OFFSET=1: the ISP does not + * clamp the depth it offsets to 0..1 (gloffset --clamp, every bit of the + * state words near flipped), and dEQP's result_depth_clamp and + * factor_1_slope cases want it -- the draw module's offset it is, its + * vertices' depth clamped. */ +static uint32_t +isp_offset(const struct pipe_rasterizer_state *r) +{ + float u = r ? r->offset_units / SGX_OFFSET_SCALE : 0, f = r ? r->offset_scale : 0; + + if (!r || !r->offset_tri || (u == 0.0f && f == 0.0f)) + return 0; + if (SGX_OFFSET_SCALE != 16.0f || u != rintf(u) || f != rintf(f) || u < -16 || u > 15 || f < -16 || f > 15 || + r->offset_clamp != 0.0f) + return ~0u; + return ((uint32_t)(int)f & 0x1f) << 21 | ((uint32_t)(int)u & 0x1f) << 16; +} + +/* What the GPU's vertex side does not do yet: then the draw module's way */ +static bool +gpu_vs_can_draw(struct sgx_context *ctx, const struct pipe_draw_info *info) +{ + const struct pipe_rasterizer_state *r = ctx->rast; + static int off = -1; + + if (off < 0) + off = debug_get_bool_option("SGX_CPU_VS", false); + if (off || !ctx->draw_fs || !r || !ctx->velems || !ctx->vs || !ctx->vs->nir) + return false; + if (info->mode != MESA_PRIM_TRIANGLES && info->mode != MESA_PRIM_TRIANGLE_STRIP && + info->mode != MESA_PRIM_TRIANGLE_FAN) + return false; + /* (instances, restarts and depth clamping: the draw module's, M43) */ + if (info->primitive_restart || info->instance_count != 1 || info->start_instance || + r->depth_clamp || !r->depth_clip_near || !r->depth_clip_far || + r->cull_face == PIPE_FACE_FRONT_AND_BACK || + r->fill_front != PIPE_POLYGON_MODE_FILL || r->fill_back != PIPE_POLYGON_MODE_FILL || + r->clip_plane_enable || + /* polygon offset the ISP has not: the draw module's */ + isp_offset(r) == ~0u) + return false; + return true; +} + +/* One draw with the vertex shader on the GPU (M18, M26). Its vertices + * are fetched from the application's buffers as they are when every + * attribute the shader reads from memory is in a format the fetch takes + * (sgx_attr_of_format), in a buffer, 4-byte aligned, and all have one + * stride (the PDS fetch has one for all, M26) -- else the CPU makes them + * one stream, in the formats the fetch takes or F32. Attributes with a + * stride of 0 are constants, the shader's sa words. The triangles go as + * a list of vertices, or indices (strips and fans made lists). False: + * not done, the caller's way. */ +static bool +gpu_vs_draw(struct sgx_context *ctx, const struct pipe_draw_info *info, + const struct pipe_draw_start_count_bias *draw) +{ + const struct sgx_vertex_elements *ve = ctx->velems; + struct sgx_shader *sh = ctx->vs; + struct sgx_vtx *v = &ctx->vtx; + struct sgx_screen *screen = sgx_screen(ctx->base.screen); + const uint8_t *src[SGX_VS_MAX_ATTRIBS]; + uint8_t *vdata = NULL; + struct sgx_resource *res[SGX_VS_MAX_ATTRIBS]; + uint32_t off[SGX_VS_MAX_ATTRIBS]; + uint8_t attr[SGX_VS_MAX_ATTRIBS]; + const void *indices = NULL; + struct sgx_vs *vs; + unsigned nattrs = sh->vs_nattrs, stride = 0, ntri, lo = ~0u, hi = 0, vtx0; + int bias = info->index_size ? draw->index_bias : 0; + static int repack = -1; + bool direct, buffer_indices; + struct sgx_bo *ibo = NULL; + + /* SGX_REPACK=1: every draw's vertices made one stream by the CPU */ + if (repack < 0) + repack = debug_get_bool_option("SGX_REPACK", false); + direct = !repack; + + ntri = info->mode == MESA_PRIM_TRIANGLES ? draw->count / 3 : + draw->count >= 3 ? draw->count - 2 : 0; + if (!ntri) + return true; + + /* each attribute: where vertex 0 of the buffer has it, how it comes */ + for (unsigned a = nattrs; a < SGX_VS_MAX_ATTRIBS; a++) { + src[a] = NULL; + attr[a] = SGX_ATTR(SGX_ATTR_CONST, 4); + } + for (unsigned a = 0; a < nattrs; a++) { + const struct pipe_vertex_element *e = a < ve->count ? &ve->e[a] : NULL; + const struct pipe_vertex_buffer *vb = + e && (ctx->vb_mask & 1u << e->vertex_buffer_index) ? &ctx->vb[e->vertex_buffer_index] : + NULL; + + src[a] = NULL; + res[a] = NULL; + if (vb && vb->is_user_buffer) { + src[a] = vb->buffer.user; + } else if (vb && vb->buffer.resource) { + res[a] = sgx_resource(vb->buffer.resource); + src[a] = res[a]->data; + } + if (src[a]) { + off[a] = vb->buffer_offset + e->src_offset; + src[a] += off[a]; + } + /* (no instancing here: gpu_vs_can_draw) */ + if (!src[a] || !e->src_stride || e->instance_divisor) { + attr[a] = SGX_ATTR(SGX_ATTR_CONST, 4); + continue; + } + attr[a] = ve->attr[a]; + if (!attr[a] || !res[a] || !res[a]->data || (off[a] & 3) || (e->src_stride & 3) || + (stride && e->src_stride != stride)) + direct = false; + stride = e->src_stride; + } + + /* (M46) indices of 16 bits in a buffer, a list, every attribute fetched + * where it is: the VDM reads them in the buffer's GPU copy as they are + * -- no scan for their range (16 bits cannot pass 0xffff), no copy into + * the render; at any even address (glbuffer's "indexed 26": an odd + * first index, as PPSSPP's 2-byte aligned uploads have them). + * SGX_INDEX_COPY=1: copied as before. */ + v->idx_va = 0; + { + static int copy = -1; + + if (copy < 0) + copy = getenv("SGX_INDEX_COPY") && atoi(getenv("SGX_INDEX_COPY")); + buffer_indices = !copy && direct && info->index_size == 2 && !info->has_user_indices && + info->index.resource && info->mode == MESA_PRIM_TRIANGLES && + !flat_first(ctx) && draw->count >= 3; + } + /* the vertices the draw reads */ + if (buffer_indices) { + lo = 0; + hi = 0xffff; + } else if (info->index_size) { + size_t size; + + indices = info->has_user_indices ? info->index.user : + map_buffer_range(info->index.resource, &size, draw->start * info->index_size, + (draw->start + draw->count) * info->index_size); + if (!indices) + return false; + indices = (const uint8_t *)indices + draw->start * info->index_size; + for (unsigned i = 0; i < draw->count; i++) { + unsigned x; + + if (!index_at(indices, info->index_size, i, &x)) + return false; + lo = MIN2(lo, x); + hi = MAX2(hi, x); + } + } else { + lo = draw->start; + hi = draw->start + draw->count - 1; + } + /* indices go to the GPU as they are, or less the first vertex the + * draw reads: 16 bits (a draw of more vertices, or more than the + * render's room for a stream of them, is the draw module's, which + * draws it in pieces) */ + if (direct && info->index_size && hi > 0xffff) + direct = false; + if (hi - lo > 0xffff) + return false; + if (!direct) + for (unsigned a = 0; a < nattrs; a++) + if (!attr[a]) + attr[a] = SGX_ATTR(SGX_ATTR_F32, 4); + if (!(vs = vs_for_draw(ctx, ctx->draw_fs, attr))) + return false; + + /* vertex 0: the draw's first (the list's start, or index 0 as it is), + * or the first it reads (the CPU's stream) */ + vtx0 = direct ? (info->index_size ? 0 : draw->start) : lo; + + /* the triangles */ + v->count = 3 * ntri; + v->max_index = hi - vtx0; + v->indexed = info->index_size || info->mode != MESA_PRIM_TRIANGLES || + v->count > sgx_frame_list_max(screen->frame) || flat_first(ctx); + if (buffer_indices) { + if (!(ibo = sgx_buffer_bo(ctx, sgx_resource(info->index.resource), 2 * draw->start, + 2 * (draw->start + draw->count)))) + return false; + v->idx_va = ibo->va + 2 * draw->start; + } else if (v->indexed) { + if (v->count > ctx->maxindices) { + uint16_t *p = realloc(ctx->indices, v->count * sizeof(uint16_t)); + + if (!p) + return false; + ctx->indices = p; + ctx->maxindices = v->count; + } + for (unsigned t = 0; t < ntri; t++) { + unsigned k[3], x = 0; + + if (info->mode == MESA_PRIM_TRIANGLES) { + k[0] = 3 * t, k[1] = 3 * t + 1, k[2] = 3 * t + 2; + } else if (info->mode == MESA_PRIM_TRIANGLE_STRIP) { + /* every other triangle the other way round, as GL turns them */ + k[0] = t + (t & 1), k[1] = t + 1 - (t & 1), k[2] = t + 2; + } else { + k[0] = 0, k[1] = t + 1, k[2] = t + 2; + } + /* the first vertex's colours (ARB_provoking_vertex's: a strip's + * triangle t takes vertex t's, a fan's vertex t + 1's) last */ + if (flat_first(ctx)) { + unsigned p = info->mode == MESA_PRIM_TRIANGLES || + (info->mode == MESA_PRIM_TRIANGLE_STRIP && !(t & 1)) ? 0 : 1; + unsigned a = k[(p + 1) % 3], b = k[(p + 2) % 3], c = k[p]; + + k[0] = a, k[1] = b, k[2] = c; + } + for (unsigned i = 0; i < 3; i++) { + if (indices) + index_at(indices, info->index_size, k[i], &x); + else + x = draw->start + k[i]; + ctx->indices[3 * t + i] = x - vtx0; + } + } + } + + /* the attributes: where the fetch finds them */ + v->nbos = 0; + if (direct) { + v->repacked = false; + v->stride = stride; + for (unsigned a = 0; a < vs->nattrs; a++) { + struct sgx_bo *bo; + unsigned i; + + if (SGX_ATTR_KIND(vs->attr[a]) == SGX_ATTR_CONST) + continue; + /* (the bytes it reads: vertices lo..hi) */ + if (!(bo = sgx_buffer_bo(ctx, res[a], off[a] + (lo + bias) * stride, + off[a] + (hi + bias) * stride + 4 * sgx_attr_words(vs->attr[a])))) + return false; + v->base[a] = bo->va + off[a] + (vtx0 + bias) * stride; + for (i = 0; i < v->nbos && v->bos[i] != bo; i++) + ; + if (i == v->nbos) + v->bos[v->nbos++] = bo; + } + /* (M46) and the index buffer's, its indices read there */ + if (ibo) { + unsigned i; + + for (i = 0; i < v->nbos && v->bos[i] != ibo; i++) + ; + if (i == v->nbos) + v->bos[v->nbos++] = ibo; + } + } else { + unsigned n = hi - lo + 1, at = 0; + + v->repacked = true; + v->nverts = n; + for (unsigned a = 0; a < vs->nattrs; a++) + if (SGX_ATTR_KIND(vs->attr[a]) != SGX_ATTR_CONST) { + v->base[a] = at; + at += 4 * sgx_attr_words(vs->attr[a]); + } + v->stride = MAX2(at, 4); + /* (M42: written once, into the batch's GPU memory) */ + if (n * v->stride > SGX_FRAME_MAX_BYTES || !(vdata = vtx_reserve(ctx, n * v->stride))) + return false; + /* (M46) the CPU reads the buffers' copies here */ + for (unsigned a = 0; a < nattrs; a++) + if (res[a]) + sgx_buffer_fresh(res[a]); + /* the attributes one array of the application's laid out as the + * stream is -- SDL's x y, r g b a, u v at stride 32 (M34): the + * vertices in one copy */ + { + const uint8_t *first = NULL; + bool whole = true; + + for (unsigned a = 0; a < vs->nattrs && whole; a++) { + const struct pipe_vertex_element *e = &ve->e[a]; + + if (SGX_ATTR_KIND(vs->attr[a]) == SGX_ATTR_CONST) + continue; + if (!first) + first = src[a] - v->base[a]; + whole = vs->attr[a] == ve->attr[a] && e->src_stride == v->stride && + src[a] == first + v->base[a] && + util_format_get_blocksize(e->src_format) == 4 * sgx_attr_words(vs->attr[a]); + } + if (whole && first) { + sgx_copy(vdata, first + (lo + bias) * v->stride, n * v->stride); + goto copied; + } + } + for (unsigned a = 0; a < vs->nattrs; a++) { + const struct pipe_vertex_element *e = &ve->e[a]; + const uint8_t *in; + uint8_t *out = vdata + v->base[a]; + unsigned size; + + if (SGX_ATTR_KIND(vs->attr[a]) == SGX_ATTR_CONST) + continue; + in = src[a] + (lo + bias) * e->src_stride; + if (vs->attr[a] == ve->attr[a]) { + /* as it is: its bytes (a word for RGB8, the fourth zero) */ + size = util_format_get_blocksize(e->src_format); + for (unsigned i = 0; i < n; i++, in += e->src_stride, out += v->stride) { + memset(out, 0, 4 * sgx_attr_words(vs->attr[a])); + memcpy(out, in, size); + } + } else { + for (unsigned i = 0; i < n; i++, in += e->src_stride, out += v->stride) + util_format_unpack_rgba(e->src_format, (float *)out, in, 1); + } + } + copied:; + } + + /* its uniforms: constant buffer 0's words, then the constant + * attributes' */ + if (vs->nuniforms) { + const struct pipe_constant_buffer *cb = &ctx->cb[0]; + const uint8_t *p = cb->user_buffer; + size_t size; + + if (!p && cb->buffer && (p = map_buffer(cb->buffer, &size))) + p += cb->buffer_offset; + unsigned n = p ? MIN2(vs->nuniforms * 4, cb->buffer_size) : 0; + + if (p) + memcpy(ctx->vs_sa, p, n); + memset((uint8_t *)ctx->vs_sa + n, 0, vs->nuniforms * 4 - n); + /* those past sa's, all of them in memory after it (M32) */ + if (vs->nubuf) { + unsigned m = p ? MIN2(vs->nubuf * 4, cb->buffer_size) : 0; + + if (p) + memcpy(ctx->vs_sa + vs->nuniforms, p, m); + memset((uint8_t *)(ctx->vs_sa + vs->nuniforms) + m, 0, vs->nubuf * 4 - m); + } + } + /* (M43) its uniform buffers: their addresses, the buffers the draw's + * (one not bound: the draw module's way, which reads them mapped) */ + if (vs->ubo_mask && !ubo_words(ctx, 0, vs->ubo_mask, vs->ubo_sa, ctx->vs_sa, v->bos, &v->nbos)) + return false; + /* (M39) a rectangle texture's 1 / width, 1 / height for each varying + * whose x and y the vertex side scales */ + for (unsigned k = 0, n = 0; k < vs->nvaryings; k++) { + if (!(vs->vary_fix[k] & SGX_FIX_SCALE)) + continue; + fix_scale(ctx, ctx->draw_fs->vary_unit[k], (float *)ctx->vs_sa + vs->fix_sa + 2 * n++); + } + for (unsigned a = 0; a < vs->nattrs; a++) { + float *c = (float *)ctx->vs_sa + vs->attr_sa[a]; + + if (SGX_ATTR_KIND(vs->attr[a]) != SGX_ATTR_CONST || vs->attr_sa[a] == 0xff) + continue; + if (src[a]) { + if (res[a]) + sgx_buffer_fresh(res[a]); /* (M46) */ + util_format_unpack_rgba(ve->e[a].src_format, c, src[a], 1); + } else { + c[0] = c[1] = c[2] = 0; + c[3] = 1; + } + } + + if (ctx->debug_draw) { + mesa_logi("sgx: a vertex shader's draw: %u vertices%s, %s, stride %u, %u buffers", + v->count, v->indexed ? " indexed" : "", v->repacked ? "repacked" : "direct", + v->stride, v->nbos); + for (unsigned a = 0; a < vs->nattrs; a++) + mesa_logi("sgx: attribute %u: %02x at 0x%08x", a, vs->attr[a], v->base[a]); + } + ctx->layout.nvaryings = vs->nvaryings; + ctx->layout.f32 = (1u << vs->nvaryings) - 1; + ctx->layout.colour = 0; + ctx->layout.ncolours = ctx->draw_fs ? ctx->draw_fs->prog.ncolours : 0; + ctx->gpu_vs = vs; + submit(ctx); + ctx->gpu_vs = NULL; + v->count = 0; + return true; +} + +/* SGX_DEBUG=each: on -- or, with SGX_EACH_FILE=path, while that file is + * there (looked for once a second): a game taken to the scene at its own + * speed first */ +static bool +each_on(struct sgx_context *ctx) +{ + static const char *path; + static int checked = -1; + static int64_t at; + static bool on; + int64_t now; + + if (!ctx->debug_each) + return false; + if (checked < 0) { + path = getenv("SGX_EACH_FILE"); + checked = 1; + } + if (!path) + return true; + now = os_time_get_nano(); + if (now - at > 1000000000ll) { + at = now; + on = access(path, F_OK) == 0; + } + return on; +} + +/* (M46) whether the bound fragment shader's name (sgx_create_shader_state's: + * GLSL41...) is one of LIST's, NAME[,NAME...] */ +static bool +fs_named(const struct sgx_context *ctx, const char *list) +{ + const char *n, *p = list; + size_t len; + + if (!list || !ctx->fs || !ctx->fs->nir || !ctx->fs->nir->info.name) + return false; + n = ctx->fs->nir->info.name; + len = strlen(n); + while ((p = strstr(p, n))) { + if ((p == list || p[-1] == ',') && (p[len] == ',' || !p[len])) + return true; + p += len; + } + return false; +} + +/* SGX_DEBUG=each with SGX_EACH_VERTS=N (M46): a triangle list of N indices + * or vertices, its first attribute (PPSSPP's position) read back -- the + * triangles' extent, their areas summed (against the extent's: how many + * times they cover it) and the first few -- what a costly draw draws */ +static void +each_verts(struct sgx_context *ctx, const struct pipe_draw_info *info, + const struct pipe_draw_start_count_bias *draw) +{ + static int want = -1; + const struct sgx_vertex_elements *ve = ctx->velems; + const struct pipe_vertex_element *e; + const struct pipe_vertex_buffer *vb; + const uint8_t *base, *idx = NULL; + float x0 = 1e30f, y0 = 1e30f, x1 = -1e30f, y1 = -1e30f, area = 0, small = 0; + unsigned ntri = 0; + size_t size; + + static const char *want_fs = (const char *)-1; + + if (want < 0) + want = getenv("SGX_EACH_VERTS") ? atoi(getenv("SGX_EACH_VERTS")) : 0; + if (want_fs == (const char *)-1) + want_fs = getenv("SGX_EACH_VERTS_FS"); + /* (or SGX_EACH_VERTS_FS=NAME[,NAME...]: every draw with those fragment + * shaders, its attributes' extents and the shader's uniforms too) */ + if (want_fs ? !fs_named(ctx, want_fs) : !want || draw->count != (unsigned)want) + return; + if (info->mode != MESA_PRIM_TRIANGLES || !ve || !ve->count) + return; + e = &ve->e[0]; + if (!(ctx->vb_mask & 1u << e->vertex_buffer_index)) + return; + vb = &ctx->vb[e->vertex_buffer_index]; + if (vb->is_user_buffer) + base = vb->buffer.user; + else if (!(base = map_buffer(vb->buffer.resource, &size))) + return; + base += vb->buffer_offset + e->src_offset; + if (info->index_size) { + if (info->has_user_indices) + idx = info->index.user; + else if (!(idx = map_buffer(info->index.resource, &size))) + return; + idx += draw->start * info->index_size; + } + for (unsigned t = 0; t + 2 < draw->count; t += 3, ntri++) { + float p[3][4]; + float a; + + for (unsigned k = 0; k < 3; k++) { + unsigned x = t + k; + + if (idx) + x = info->index_size == 2 ? ((const uint16_t *)idx)[x] : + info->index_size == 1 ? idx[x] : ((const uint32_t *)idx)[x]; + x += info->index_size ? draw->index_bias : draw->start; + util_format_unpack_rgba(e->src_format, p[k], base + x * e->src_stride, 1); + x0 = MIN2(x0, p[k][0]); + x1 = MAX2(x1, p[k][0]); + y0 = MIN2(y0, p[k][1]); + y1 = MAX2(y1, p[k][1]); + } + a = fabsf((p[1][0] - p[0][0]) * (p[2][1] - p[0][1]) - + (p[2][0] - p[0][0]) * (p[1][1] - p[0][1])) / 2; + area += a; + small += a < 1.0f; + if (ntri < 6) + mesa_logi("sgx: each: verts: triangle %u: (%.2f %.2f %.3f %.2f) (%.2f %.2f %.3f %.2f) " + "(%.2f %.2f %.3f %.2f)", ntri, p[0][0], p[0][1], p[0][2], p[0][3], p[1][0], + p[1][1], p[1][2], p[1][3], p[2][0], p[2][1], p[2][2], p[2][3]); + } + mesa_logi("sgx: each: verts: %u triangles (%s, stride %u), x %.2f..%.2f, y %.2f..%.2f, " + "their areas %.1f (%.2f times the extent's), %.0f under one unit", + ntri, util_format_short_name(e->src_format), e->src_stride, x0, x1, y0, y1, area, + (x1 - x0) * (y1 - y0) > 0 ? area / ((x1 - x0) * (y1 - y0)) : 0.0f, small); + /* every attribute's extent over the draw's vertices, and the fragment + * shader's uniforms (whether PPSSPP's TClampST clamp does anything) */ + for (unsigned a = 0; a < ve->count && a < 8; a++) { + const struct pipe_vertex_element *ea = &ve->e[a]; + const struct pipe_vertex_buffer *vba; + const uint8_t *ba; + float lo[4] = { 1e30f, 1e30f, 1e30f, 1e30f }, hi[4] = { -1e30f, -1e30f, -1e30f, -1e30f }; + + if (!(ctx->vb_mask & 1u << ea->vertex_buffer_index)) + continue; + vba = &ctx->vb[ea->vertex_buffer_index]; + if (vba->is_user_buffer) + ba = vba->buffer.user; + else if (!(ba = map_buffer(vba->buffer.resource, &size))) + continue; + ba += vba->buffer_offset + ea->src_offset; + for (unsigned t = 0; t < draw->count; t++) { + unsigned x = t; + float q[4]; + + if (idx) + x = info->index_size == 2 ? ((const uint16_t *)idx)[x] : + info->index_size == 1 ? idx[x] : ((const uint32_t *)idx)[x]; + x += info->index_size ? draw->index_bias : draw->start; + util_format_unpack_rgba(ea->src_format, q, ba + x * ea->src_stride, 1); + for (unsigned k = 0; k < 4; k++) { + lo[k] = MIN2(lo[k], q[k]); + hi[k] = MAX2(hi[k], q[k]); + } + } + mesa_logi("sgx: each: verts: attribute %u (%s): %.5f..%.5f %.5f..%.5f %.5f..%.5f " + "%.5f..%.5f", a, util_format_short_name(ea->src_format), lo[0], hi[0], lo[1], + hi[1], lo[2], hi[2], lo[3], hi[3]); + } + if (ctx->fs_constants) { + char buf[800] = ""; + unsigned n = MIN2(40, ctx->fs_constants_size / 4), at = 0; + + for (unsigned i = 0; i < n && at < sizeof(buf) - 16; i++) + at += snprintf(buf + at, sizeof(buf) - at, " %.6f", ctx->fs_constants[i]); + mesa_logi("sgx: each: verts: uniforms%s", buf); + if (ctx->fs && ctx->fs->nir) { + nir_foreach_uniform_variable(var, ctx->fs->nir) + mesa_logi("sgx: each: verts: uniform %s at %u", var->name, + var->data.driver_location); + } + } +} + +/* SGX_DEBUG=each (M46): the draw just gathered, a render of its own -- what + * it was (its fragment shader as sgx_create_shader_state named it, its + * pixel program), and with sync the render's time on the GPU after it */ +static void +each_draw(struct sgx_context *ctx, const struct pipe_draw_info *info, + const struct pipe_draw_start_count_bias *draws, unsigned num_draws, bool gpu_vs) +{ + const struct sgx_fs *fs = ctx->draw_fs; + const struct pipe_rt_blend_state *rt = ctx->blend ? &ctx->blend->rt[0] : NULL; + unsigned n = 0; + char eq[160] = ""; + + for (unsigned i = 0; i < num_draws; i++) { + n += draws[i].count; + each_verts(ctx, info, &draws[i]); + } + /* (the equation, F32's or SOP2's) */ + if (rt && rt->blend_enable) + snprintf(eq, sizeof(eq), " [%s %s %s | a %s %s %s]", + util_str_blend_func(rt->rgb_func, true), + util_str_blend_factor(rt->rgb_src_factor, true), + util_str_blend_factor(rt->rgb_dst_factor, true), + util_str_blend_func(rt->alpha_func, true), + util_str_blend_factor(rt->alpha_src_factor, true), + util_str_blend_factor(rt->alpha_dst_factor, true)); + mesa_logi("sgx: each: into %ux%u %p: %u %s, %s; fragment shader %p%s: %u instructions, " + "mask %x, %u temps, %u inputs, %u textures (%u by the PDS), %u sa words%s%s%s; " + "blend %s%s, depth %s%s", + ctx->fb.width, ctx->fb.height, + ctx->fb.nr_cbufs ? (void *)ctx->fb.cbufs[0].texture : NULL, + n, info->index_size ? "indices" : "vertices", + gpu_vs ? "the GPU's vertex side" : "the draw module", (void *)ctx->fs, + ctx->fs && ctx->fs->nir && ctx->fs->nir->info.fs.uses_discard ? " (discards)" : "", + fs ? fs->prog.ncode : 0, rt ? rt->colormask : 0xf, fs ? fs->prog.ntemps : 0, + fs ? fs->prog.ninputs : 0, + fs ? fs->nsamplers : 0, fs ? fs->prog.nfetch : 0, fs ? fs->prog.nsa : 0, + fs && fs->prog.nubuf ? " (+ memory)" : "", fs && fs->prog.branches ? ", branches" : "", + fs && fs->prog.f16 ? ", F16" : "", + rt && rt->blend_enable ? (fs && fs->sop2 ? "on (SOP2)" : "on (F32)") : + opaque_draw(ctx, fs) ? "off (opaque)" : fs && fs->sop2 ? "off (SOP2)" : "off", eq, + ctx->dsa && ctx->dsa->depth_enabled ? + (ctx->dsa->depth_writemask ? "tested, written" : "tested") : "off", + ctx->dsa && ctx->dsa->stencil[0].enabled ? ", stencil" : ""); + /* (the vertex program, a GPU one's size) */ + if (gpu_vs && ctx->batch.ndraws && ctx->batch.draw[ctx->batch.ndraws - 1].vs) + mesa_logi("sgx: each: vertex program %u instructions, %u temps", + ctx->batch.draw[ctx->batch.ndraws - 1].vs->ncode, + ctx->batch.draw[ctx->batch.ndraws - 1].vs->ntemps); + sgx_batch_flush(ctx); +} + +void +sgx_draw_vbo(struct pipe_context *pctx, const struct pipe_draw_info *info, + unsigned drawid_offset, const struct pipe_draw_indirect_info *indirect, + const struct pipe_draw_start_count_bias *draws, unsigned num_draws) +{ + struct sgx_context *ctx = sgx_context(pctx); + struct draw_context *draw = ctx->draw; + const void *indices = NULL; + unsigned i; + + if (indirect || !draw || !ctx->vs || !ctx->vs->draw) + return; + /* (M43) under a render condition that says no: nothing */ + if (!sgx_render_condition_ok(ctx)) + return; + /* (M46) SGX_SKIP_FS=NAME[,NAME...]: draws with those fragment shaders + * (sgx_create_shader_state's names, GLSL41...) left out -- what they cost + * in a render of many draws, which a render a draw cannot say (each one + * pays a render's own cost). SGX_SKIP_FILE=path: the names in that file + * (read again once a second; none while it is not there) */ + { + static const char *skip = (const char *)-1, *path; + static char names[256]; + static int64_t at; + + if (skip == (const char *)-1) { + skip = getenv("SGX_SKIP_FS"); + path = getenv("SGX_SKIP_FILE"); + } + if (path && os_time_get_nano() - at > 1000000000ll) { + FILE *f = fopen(path, "r"); + size_t n = f ? fread(names, 1, sizeof(names) - 1, f) : 0; + + at = os_time_get_nano(); + if (f) + fclose(f); + while (n && (names[n - 1] == '\n' || names[n - 1] == ' ')) + n--; + names[n] = 0; + skip = n ? names : NULL; + } + if (fs_named(ctx, skip)) + return; + } + ctx->stat_draws += num_draws; + if (ctx->blitter && ctx->blitter->running) + ctx->batch.blit = true; + if (ctx->stat_swap) { + struct timespec ts; + + sgx_trace_mark("first draw"); + clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &ts); + ctx->stat_between += os_time_get_nano() - ctx->stat_swap; + ctx->stat_between_cpu += ts.tv_sec * 1000000000ll + ts.tv_nsec - ctx->stat_swap_cpu; + ctx->stat_swap = 0; + } + /* the fragment shader's constants (the vertex shader's: gpu_vs_draw's, + * or the draw module's below) -- before its variant is chosen, which + * may read them (M46: texclamp_does_nothing) */ + { + const struct pipe_constant_buffer *cb = &ctx->cb[1]; + const uint8_t *p = cb->user_buffer; + + if (!p && cb->buffer) { + size_t whole; + + p = map_buffer(cb->buffer, &whole); + if (p) + p += cb->buffer_offset; + } + ctx->fs_constants = (const float *)p; + ctx->fs_constants_size = p ? cb->buffer_size : 0; + } + ctx->draw_fs = fs_for_draw(ctx, info, draws, num_draws); + if (ctx->fs && !ctx->fs->compiled && !ctx->fs->colour.ok && !ctx->warned_fs) { + mesa_logw("sgx: a fragment shader whose colour is not a varying, a constant or a " + "uniform per channel: drawn grey (M13a)"); + ctx->warned_fs = true; + } + + + /* the vertex shader on the GPU, where it can be (M18) */ + if (gpu_vs_can_draw(ctx, info)) { + for (i = 0; i < num_draws; i++) + if (!gpu_vs_draw(ctx, info, &draws[i])) + break; + if (i == num_draws) { + if (each_on(ctx)) + each_draw(ctx, info, draws, num_draws, true); + return; + } + draws += i; + num_draws -= i; + } + + /* (M46) the vertex shader the draw module runs, bound now */ + if (ctx->draw_vs != ctx->vs) { + draw_bind_vertex_shader(draw, ctx->vs ? ctx->vs->draw : NULL); + ctx->draw_vs = ctx->vs; + } + /* the draw module's way: its buffers mapped for it */ + for (i = 0; i < PIPE_MAX_ATTRIBS; i++) { + const struct pipe_vertex_buffer *vb = &ctx->vb[i]; + const void *p = NULL; + size_t size = ~(size_t)0; + + if (!(ctx->vb_mask & 1u << i)) + continue; + if (vb->is_user_buffer) + p = vb->buffer.user; + else if (vb->buffer.resource) + p = map_buffer(vb->buffer.resource, &size); + draw_set_mapped_vertex_buffer(draw, i, p, size); + } + if (info->index_size) { + size_t size = ~(size_t)0; + + indices = info->has_user_indices ? info->index.user : + map_buffer(info->index.resource, &size); + draw_set_indexes(draw, indices, info->index_size, size); + } + { + const struct pipe_constant_buffer *cb = &ctx->cb[0]; + const uint8_t *p = cb->user_buffer; + + if (!p && cb->buffer) { + size_t whole; + + p = map_buffer(cb->buffer, &whole); + if (p) + p += cb->buffer_offset; + } + draw_set_mapped_constant_buffer(draw, MESA_SHADER_VERTEX, 0, p, p ? cb->buffer_size : 0); + } + /* (M43) and its uniform buffers, mapped */ + for (unsigned k = 1; k < SGX_FRAME_MAX_UBOS; k++) { + const struct pipe_constant_buffer *u = &ctx->ubo[0][k]; + const uint8_t *p = u->user_buffer; + + if (!p && u->buffer) { + size_t whole; + + p = map_buffer(u->buffer, &whole); + if (p) + p += u->buffer_offset; + } + draw_set_mapped_constant_buffer(draw, MESA_SHADER_VERTEX, k, p, p ? u->buffer_size : 0); + } + + update_vertex_info(ctx); + draw_vbo(draw, info, drawid_offset, NULL, draws, num_draws, 0); + draw_flush(draw); + + for (i = 0; i < PIPE_MAX_ATTRIBS; i++) + if (ctx->vb_mask & 1u << i) + draw_set_mapped_vertex_buffer(draw, i, NULL, 0); + if (indices) + draw_set_indexes(draw, NULL, 0, 0); + + submit(ctx); + if (each_on(ctx)) + each_draw(ctx, info, draws, num_draws, false); +} diff --git a/src/gallium/drivers/sgx/sgx_draw.h b/src/gallium/drivers/sgx/sgx_draw.h new file mode 100644 index 00000000000..c9060a0b332 --- /dev/null +++ b/src/gallium/drivers/sgx/sgx_draw.h @@ -0,0 +1,74 @@ +/* + * Copyright 2026 Project Cascadia + * SPDX-License-Identifier: MIT + * + * Draws, for now (docs/research/p105-mesa.md, M13a): vertex shaders on the + * CPU in Gallium's draw module, triangles on the GPU through the template + * frame (sgx_frame.h), the fragment colour worked out per vertex. + */ +#ifndef SGX_DRAW_H +#define SGX_DRAW_H + +#include + +#include "pipe/p_state.h" + +struct nir_shader; +struct sgx_context; +struct sgx_fs; +struct sgx_vs; + +/* Where each channel of a fragment shader's colour comes from: the + * template frame's programs interpolate a colour between the vertices, so + * a shader can be drawn when every channel is a constant, a component of a + * varying or a component of a uniform. */ +enum sgx_colour_src { + SGX_SRC_CONST, + SGX_SRC_VARYING, /* slot: gl_varying_slot */ + SGX_SRC_UNIFORM, /* slot: the float's index in constant buffer 0 */ +}; + +struct sgx_fs_colour { + bool ok; + struct { + enum sgx_colour_src src; + unsigned slot, comp; + float value; + } ch[4]; +}; + +/* reads fs (it is not changed) */ +void sgx_fs_colour_analyse(const struct nir_shader *fs, struct sgx_fs_colour *out); + +/* the gathered draws rendered now (nothing if there are none) */ +void sgx_batch_flush_at(struct sgx_context *ctx, const char *file, int line); +/* (where from: SGX_DEBUG=fps counts the renders by it) */ +#define sgx_batch_flush(ctx) sgx_batch_flush_at(ctx, __FILE__, __LINE__) +void sgx_batch_why(struct sgx_context *ctx); +/* a program gone from its shader: retired and freed at the next flush + * (or now, when nothing is gathered) */ +void sgx_batch_bury_fs(struct sgx_context *ctx, struct sgx_fs *fs); +void sgx_batch_bury_vs(struct sgx_context *ctx, struct sgx_vs *vs); +/* depth (to d) and/or stencil (to value, through mask) cleared within the + * render, over sc or all of the target: a quad that writes nothing but + * them (M23, M24) */ +struct pipe_scissor_state; +bool sgx_colour_clear(struct sgx_context *ctx, const union pipe_color_union *color, + const struct pipe_scissor_state *sc); +void sgx_zs_clear(struct sgx_context *ctx, bool depth, float d, bool stencil, unsigned value, + unsigned mask, const struct pipe_scissor_state *sc); +/* whether the gathered draws write or read p */ +bool sgx_batch_uses(struct sgx_context *ctx, struct pipe_resource *p); + +/* how the vertex fetch reads a vertex element's format: an SGX_ATTR, or 0 + * when it cannot as it is (M26) */ +uint8_t sgx_attr_of_format(enum pipe_format format); + +bool sgx_draw_init(struct sgx_context *ctx); +void sgx_draw_fini(struct sgx_context *ctx); + +void sgx_draw_vbo(struct pipe_context *pctx, const struct pipe_draw_info *info, + unsigned drawid_offset, const struct pipe_draw_indirect_info *indirect, + const struct pipe_draw_start_count_bias *draws, unsigned num_draws); + +#endif diff --git a/src/gallium/drivers/sgx/sgx_frame.c b/src/gallium/drivers/sgx/sgx_frame.c new file mode 100644 index 00000000000..e5319bca895 --- /dev/null +++ b/src/gallium/drivers/sgx/sgx_frame.c @@ -0,0 +1,2709 @@ +/* + * Copyright 2026 Project Cascadia + * SPDX-License-Identifier: MIT + * + * One full-screen quad through sgx2d's template frame. How the pieces were + * found is docs/research/p105-gpu.md (M4-M8); the frame is sgx2d's + * (tools/sgx/lib/sgx2d.c), cut down to one draw, with two programs of our + * own: + * + * - the end-of-tile program, which loads the pixel back end's six state + * words and emits: in the pack it writes the framebuffer, here one is + * written for each render target (format word 0x00110000 = linear, + * B8G8R8A8 from the shader's RGBA; the address; the line stride in + * pixels / 2 - 1; 0; 0; the size); + * - a pixel program that replaces the tile's colour instead of blending + * with it: the pack's texel x colour (SOP2M, into pa0), then o0 = pa0, + * which is the pack's background program's own instruction. + * + * Draws have a vertex side of our own (M13b): a vertex fetch PDS program + * and a vertex program for each number of varyings, iOS's shape (the + * corpus's v* cases), and the TA state words that describe the varyings. + * + * They go in the pack's code page, in the 1 KiB below its first program, + * where the pack's own programs are known to run. The 3D pass's event + * program names the end-of-tile program in its data (word 2), and the + * background object reloads every tile from a linear descriptor (the 3D + * PDS block +0x130): both are pointed at the render target before each + * render. + * + * Render targets of any size (M10): the render target data -- what the + * kext computes for a size, sgx_rt.c -- are ours, one set for each size a + * render goes to (rt_set()), and the words that hold the size are written + * for each render: the TA command's, the state's tile bounds and viewport, + * the stream end's tiles. The pack's own set, for the screen's size, is + * left unused (SGX_FRAME=packrt takes it). + * + * SGX_FRAME swaps pieces for the pack's, or moves them, to find on the + * device which one is wrong when a clear is (sgx_frame.h). + */ +#include "sgx_frame.h" + +#include +#include +#include +#include +#include + +#include "drm-uapi/apple_sgx_drm.h" +#include "util/log.h" +#include "util/os_time.h" +#include "util/u_call_once.h" +#include "util/u_math.h" +#include "util/u_memory.h" +#include "util/vma.h" + +#include "sgx_compiler.h" +#include "sgx_device.h" +#include "sgx_resource.h" +#include "sgx_rt.h" +#include "sgx_template.h" +#include "sgx_usse.h" + +/* the EXT window, as sgx2d uses it */ +#define EXT_TEX_END 0x280000 +#define EXT_VB 0x280000 +#define EXT_FRAME 0x3c0000 +#define PACK_VTX_FLOATS 8 /* the pack's vertex: r g b a u v x y */ + +#define MAX_PACK_BOS 48 + +/* our programs: the replace program, the iterated-colour pixel programs + * (F16 and F32), the vertex programs (one for each number of varyings, + * 0..8: 52 instructions), then one end-of-tile program (11) a slot */ +#define ITER_PROG 0x20 +#define ITER_PROG_F32 0x30 +#define VERTEX_PROGS 0x40 +/* (M43) the background's program for targets of four half floats: + * iOS's m28 pixel program, the texel's four F16 from pa0 into o0, o1 */ +#define BG64_PROG 0x1e0 +/* and of two F32: both registers moved by one VPCK F32 (an F16 move might + * not keep F32's bits) */ +#define BG64F32_PROG 0x1f0 +#define PROGS_SIZE 0x200 +#define EOT_SLOT 0x58 +#define MAX_EOT 256 +#define CODE_BO_SIZE (PROGS_SIZE + MAX_EOT * EOT_SLOT) +/* in the EXT window after the white texture's block: the iterated-colour + * pixel program's PDS, one for each varying (F16, F32), and the vertex + * fetch, one for each number of varyings */ +#define EXT_ITER_PDS 0x100 +#define ITER_PDS_SIZE 0x20 +#define EXT_FETCH_PDS 0x400 +#define FETCH_PDS_SIZE 0x100 +/* our pixel programs' PDS programs (M13c), one slot each, never reused */ +#define EXT_PROG_PDS 0x1000 +#define EXT_PROG_PDS_END 0x80000 +#define PROG_PDS_SLOT 0x80 +/* per render, in the frame's part of the EXT window: the secondary + * attributes' loader and the words it loads (uniforms, texture states) */ +#define FRAME_UNI_PDS 0xf00 +#define FRAME_UNIFORMS 0x1000 +/* a draw's whole state: the words the state program DMAs to the tiler + * (its control word says 21 -- the template's block is 20 long, and the + * 21st, which varyings are F16, came from whatever followed: zeros in a + * buffer of its own, M27) */ +#define STATE_WORDS 21 +/* a gathered render's draws (sgx_frame_render), in its own memory (M27): + * the whole state, then its state program */ +#define DRAW_PROG 0x80 +/* the uniforms' loader after the words */ +#define UNIFORM_LOADER_AT(nsa) align(4 * (nsa), 16) +/* M27: a render's own memory comes in chunks of at least this */ +#define ARENA_CHUNK (256u << 10) +#define ARENA_MAX 128 +/* M27: the gathered renders queued at most, the oldest waited for before + * another goes (the CPU ahead of the GPU by that much, no more) */ +#define MAX_QUEUED 3 +/* the code of our programs: a buffer of its own in the code zone, a + * program's place free again once the renders that ran it are done */ +#define HEAP_SIZE (256 << 10) + +/* A retired program's places, free once fence (the last render when it + * was retired) is done */ +struct retired { + uint32_t code_va, code_size, pds_va, pds_size; + struct sgx_fence *fence; +}; + +/* the pack's code page is at code base + 0x1000 (rpack.py), its first + * program at +0x400 (programs.py) */ +#define PAGE_OFFSET 0x1000 +#define PAGE_FREE 0x400 + +/* A DOUTU (and a PHAS) names a program by its index from the code base: + * 20 bits of 8-byte instructions, 8 MiB. Kernels before 2026-10-04 made + * the code zone 16 MiB and gave out its top first, out of reach; with + * SGX_FRAME=codebo the buffer goes at an address of our own choosing, just + * above the pack's. */ +#define CODE_REACH (8u << 20) + +/* the GL window's 3D PDS block, where frame.py puts it */ +#define PDS_DEFAULT 0x98956000u + +/* The render target data for each size a render goes to (M10, sgx_rt.c): + * a buffer each, in a slot of the TA's heap -- the state buffer has to be + * within 256 MiB above its base, and the kernel picks addresses far above + * -- clear of the pack's windows; the least recently used is dropped when + * the slots run out. 4 MiB holds a 4096 x 4096 target's. */ +#define RT_SLOT_VA 0x89000000u +#define RT_SLOT_SIZE (4u << 20) +#define MAX_RT_SETS 12 +/* the pack's 3D register block, copied for each size */ +#define BLOCK_SIZE 0x1000 + +enum { T_FULL, T_FULLPROG, T_DELTA, T_DELTAPROG, T_FETCH, T_TEX, T_NUM }; +static const char *tmpl_names[T_NUM] = { + "tmpl_full", "tmpl_fullprog", "tmpl_delta", "tmpl_deltaprog", "tmpl_fetch", "tmpl_tex", +}; + +/* USSE words, from tools/sgx/usse.py (assembled byte-identical to iOS's) */ +#define USSE_PHAS 0xfa44070000000000ull +#define USSE_EMIT_PIXEL 0xfb24000003200082ull +#define USSE_SOP2M_MOD 0x90807982a0000140ull /* r = texel * vertex colour */ +#define USSE_SOP2_REPLACE 0x8184080190000000ull /* o0 = pa0 * (1 - 0) + o0 * 0, end */ +#define USSE_MOV_O0_PA0 0x50850009a0000000ull /* o0 = pa0, end (the pack's bg_reload) */ +#define USSE_PCK_O0_PA0 0x40850a3da01d8000ull /* pck.u8.f16 o0, pa0 scale, end (iOS's) */ +#define USSE_PCK_O0_PA0_F32 0x40840c3da01d8002ull /* pck.u8.f32 o0, pa0, pa2 scale, end */ +#define USSE_SMLSI_INC1 0xfa10000001010101ull /* repeats: every register + 1 */ +#define USSE_EMIT_VERTEX 0xfb275000a0200000ull /* o0.. to the tiler, end */ + +/* The pixel side iOS's GL driver builds for gl_FragColor = v, a mediump + * vec4 varying (docs/research/p105-mesa.md, M11): a PDS program that + * starts the pixel program (doutu row 0) after iterating the varying into + * pa0..pa1 as F16 (07040c12: two registers, control word 3), and the + * control word: F16 (29:28 = 2), the last iterate (25), four components + * (23:22 = 3), varying 1 (15:12) -- the pack's vertex program writes + * (u, v) as varying 0, the colour as varying 1. */ +#define PDS_DOUTU_ROW0_ITER 0x070001b5u +#define PDS_ITERATE_2REG_W3 0x07040c12u +#define PDS_ITERATE_4REG_W3 0x07040c32u +#define PDS_END 0xaf000000u +#define ITERATE_F16_VEC4 0x2fc0000fu /* | varying << 12 */ +#define ITERATE_F32_VEC4 0x0fc0000fu +#define ITERATE_F32_VEC4_MORE 0x0dc0000fu /* not the last iterate (bit 25 clear) */ +#define PDS_DMA_ROW0 0x07018113u /* DMA: address and control in row 0 */ +#define PDS_DOUTU_ROW1_AFTER 0x070401a5u /* then the program in row 1 */ + +/* The iterate DOUT for the control word at data word d, into size (0x02, + * 0x12, 0x32: one, two, four registers) -- the formula fits every one in + * the corpus (v05's eight: 07040c12 ... 070c2b12); the registers follow + * one another from pa0. */ +static uint32_t +pds_iterate(unsigned d, unsigned size) +{ + return 0x07000000u | ((d + 2) >> 2) << 18 | d << 10 | ((d + 1) & 3) << 8 | size; +} +#define ITER_TEMPS 6 + +/* The PDS's texture lookups (M35; the 2026-10-10 corpus, s02 and s04): an + * iterate DOUT whose control word sends a varying's x and y to the + * texture unit -- no iterate into the registers (15:12 = 0xf), the + * varying in 3:0, 2D (10:8 = 1), the last lookup's bit 11 -- then a + * texture DOUT with the texture's four state words at data word s (even), + * the texel as it is (four bytes, one register) after the iterated inputs. + * The data word 1 of a program that has them: bit 3 (iOS: 0x0a, 0x0e with + * iterates besides). */ +#define FETCH_CONTROL_2D 0x0c00f100u /* | varying, | FETCH_LAST */ +#define FETCH_CONTROL_PROJ 0x0c00f200u /* x and y divided (iOS's s08: 0c00fa00) */ +#define FETCH_LAST 0x800u +#define FETCH_SIZE_RAW 0x02u +#define PDS_FLAGS_FETCH 8u + +/* SGX_ITER_XOR=mask: bits flipped in every iterate's control word (finding + * what the rest of them do) */ +static uint32_t +iter_xor(void) +{ + static int64_t x = -1; + + if (x < 0) + x = getenv("SGX_ITER_XOR") ? strtoul(getenv("SGX_ITER_XOR"), NULL, 0) : 0; + return x; +} + +/* Input i's iterate (M37): a varying's four F32 into four registers, or + * one of the TA's colours (iter_src < ncolours: TSP varying 10, 11) into + * one, its bytes as o0's (iOS's es1 e00: control 0x0fc0a00f, DOUT size + * 0x02), shaded flat -- bit 26 clear (e01's 0x0bc0a00f). The others' + * TSP varyings are the layout's less the colours. */ +static uint32_t +iterate_control(const struct sgx_pixel_program *p, unsigned i) +{ + unsigned v = p->iter_src[i]; + uint32_t w = i == p->ninputs - 1 ? ITERATE_F32_VEC4 : ITERATE_F32_VEC4_MORE; + + /* (M38) as F16: format 2 (iOS's e20, s00: 2fc0x00f) -- unless the + * program works out a lookup's coordinates from it (M46: in_f32) */ + if (p->f16 && !(p->in_f32 >> i & 1)) + w |= 2u << 28; + + if (v == SGX_ITERATE_POSITION) + w |= v << 12; + else if (v < p->ncolours) + w = (w & ~(1u << 26)) | (10 + v) << 12; + else + w |= (v - p->ncolours) << 12; + return w ^ iter_xor(); +} + +static void layout_words(uint32_t *full, const struct sgx_frame_layout *l); + +static bool +iterates_colour(const struct sgx_pixel_program *p, unsigned i) +{ + return p->iter_src[i] != SGX_ITERATE_POSITION && p->iter_src[i] < p->ncolours; +} + +/* whether input i is iterated as F16 (M38; M46: not the coordinates an + * F16 program works out a lookup from) */ +static bool +iterates_f16(const struct sgx_pixel_program *p, unsigned i) +{ + return p->f16 && !(p->in_f32 >> i & 1); +} + +/* the primary attributes the PDS fills: four an input, one a colour, one a + * texel -- two each as F16 (M38) */ +static unsigned +pixel_pa(const struct sgx_pixel_program *p) +{ + unsigned n = p->f16 ? 2 * p->nfetch : p->nfetch; + + for (unsigned i = 0; i < p->ninputs; i++) + n += iterates_f16(p, i) ? 2 : iterates_colour(p, i) ? 1 : 4; + return n; +} + +/* input i's iterate DOUT's size: four registers, one a colour, two F16 */ +static unsigned +iterate_size(const struct sgx_pixel_program *p, unsigned i) +{ + return iterates_f16(p, i) ? 0x12 : iterates_colour(p, i) ? 0x02 : 0x32; +} + +static uint32_t +pds_texture(unsigned s) +{ + return 0x07000000u | ((s + 2) >> 2) << 18 | s << 10 | 0x004; +} +/* the pack's colour, for draws through its vertex side */ +#define PACK_COLOUR_VARYING 1 + +/* The vertex fetch (pds.py's vertex_fetch(), iOS's for the v* cases): the + * index, then attribute n from data row n -- the address, the first primary + * attribute << 8 | words - 1, the stride (row 0's) -- then the vertex + * program, its DOUTU in the row after (predicate 3). */ +#define PDS_FETCH_INDEX 0x67800072u + +static uint32_t +pds_fetch_attr(unsigned row) +{ + return 0x2f0091a3u | (4 * row + 1) << 16; +} + +static uint32_t +pds_doutu_vertex(unsigned row) +{ + return 3u << 24 | row << 18 | 0x1f5; +} + +/* The VDM word after the vertex fetch's address, as iOS's captures have + * it: 0x03800202 for one vec4 attribute (logs/ios/depth), 0x05800403 for + * two (tmpl/vcolor), 0x07800604 for three (mod, the pack's) -- read as the + * attributes (bits 26:25), the primary attributes the vertex program gets + * (11:7) and the fetch's data rows (6:0). M13b; SGX_FETCH=word + * overrides it. */ +static uint32_t +vdm_fetch_word(unsigned nvaryings) +{ + static int64_t forced = -2; + + if (forced == -2) + forced = getenv("SGX_FETCH") ? (int64_t)strtoul(getenv("SGX_FETCH"), NULL, 0) : -1; + if (forced >= 0) + return forced; + return (1 + nvaryings) << 25 | 0x01800000u | (4 + 4 * nvaryings) << 7 | (nvaryings + 2); +} + +/* The bits 31:28 of the VDM word with the vertex fetch's address: the + * vertices a vertex task takes, less one -- as many as their outputs (the + * position and nvaryings vec4s) fit in 128 words of the output buffer, 16 + * at most. iOS has 15 for two vec4s, 9 for three, 2 for nine (the + * corpus's v07, v04, v05); with more the vertices' outputs overlap, and + * in some tiles whole triangles take other vertices' varyings (M30). + * SGX_FETCH_TAG=n overrides it. */ +static unsigned +vdm_fetch_tag(unsigned nvaryings) +{ + static int forced = -2; + + if (forced == -2) + forced = getenv("SGX_FETCH_TAG") ? (int)strtoul(getenv("SGX_FETCH_TAG"), NULL, 0) : -1; + return forced >= 0 ? forced : MIN2(16, 128 / (4 + 4 * nvaryings)) - 1; +} +static const uint64_t usse_dummy_load[3] = { + 0x488b0281a00c0000ull, 0xe9a30084a0000000ull, 0xf920000000000000ull, +}; + +/* VMOV.f32 o[dst..] <- pa[src..], two words a repeat (registers counted + * in pairs: 3 is o6), up to four repeats (usse.py's vmov_f32) */ +static uint64_t +usse_vmov_f32(unsigned dst, unsigned src, unsigned repeat) +{ + return 0x3880052183000000ull | (uint64_t)(repeat - 1) << 44 | (uint64_t)dst << 18 | + (uint64_t)src << 6; +} + +/* LIMM rN <- imm (bank 0, the temporaries) */ +static uint64_t +usse_limm_r(unsigned reg, uint32_t imm) +{ + return 0xfca0000000000000ull | (uint64_t)(reg & 0x7f) << 21 | + (uint64_t)((imm >> 26) & 0x3f) << 44 | (uint64_t)((imm >> 21) & 0x1f) << 36 | + (imm & 0x1fffff); +} + +struct sgx_eot { + uint32_t va, w, h, stride; /* the render target it writes */ + /* (M43) its format: the pixel back end's word, a pixel's bytes, and the + * background object's load of it as a texture's format and swizzle */ + uint32_t pbe, bytes, bg_fmt, bg_swizzle; + enum sgx_rt_kind kind; +}; + +/* The render target formats (M43). The pixel back end's format words are + * GXM's colour formats (SceGxmColorFormat: the base format in bits 31:28 + * and 24:23 -- U8 0x80800000, U8U8 0xb0800000 -- its swizzle in 21:20) + * with bit 16 set, as all of iOS's captures have it (m25..m28: 8888 + * 0x00110000, 565 0x34110000, 4444 0x54110000, 5551 0x44110000, half + * floats 0x07010000). Bit 26 there is GXM's tiled surface (each 32 x 32 + * tile's pixels one after another: glfmt's half quad landed in whole + * rows); linear here, the pixel's size the format's. The tile holds the + * program's colour as RGBA bytes whatever the target, and the PBE takes + * the target's channels from it (R, then G); the background object loads + * the target's texels back into the same places, alpha 1 where the target + * has none. SGX_PBE_, SGX_BG_ (format << 8 | swizzle): to try + * others. */ +static struct { + enum pipe_format format; + const char *name; + uint32_t pbe, bytes, bg_fmt, bg_swizzle; + enum sgx_rt_kind kind; +} rt_fmts[] = { + { PIPE_FORMAT_B8G8R8A8_UNORM, "BGRA8", 0x00110000, 4, 0x0c, 1, SGX_RT_UNORM8 }, + { PIPE_FORMAT_B8G8R8X8_UNORM, "BGRX8", 0x00110000, 4, 0x0c, 1, SGX_RT_UNORM8 }, + /* (M43) sRGB: the same bytes, the program encodes them (and decodes + * the tile's for blending: sgx_blend_key's rt_srgb); and R G B A in + * memory, GXM's ABGR */ + { PIPE_FORMAT_B8G8R8A8_SRGB, "BGRA8S", 0x00110000, 4, 0x0c, 1, SGX_RT_UNORM8 }, + { PIPE_FORMAT_B8G8R8X8_SRGB, "BGRX8S", 0x00110000, 4, 0x0c, 1, SGX_RT_UNORM8 }, + { PIPE_FORMAT_R8G8B8A8_UNORM, "RGBA8", 0x00010000, 4, 0x0c, 0, SGX_RT_UNORM8 }, + { PIPE_FORMAT_R8G8B8A8_SRGB, "RGBA8S", 0x00010000, 4, 0x0c, 0, SGX_RT_UNORM8 }, + /* U8, R; L8's 1RRR */ + { PIPE_FORMAT_R8_UNORM, "R8", 0x80810000, 1, 0x00, 5, SGX_RT_UNORM8 }, + /* U8U8, GR */ + { PIPE_FORMAT_R8G8_UNORM, "RG8", 0xb0810000, 2, 0x07, 0, SGX_RT_UNORM8 }, + /* GL's intensity, luminance, luminance alpha and alpha targets (M43: + * Mesa's RGBA stand-in for them blends with the alpha drawn, not the + * intensity's or 1): loaded RRRR, 1RRR, GRRR (the sampler's + * swizzles, 3 found from L8's 5 and A8's 6), R000; LA8 written R + * then A (GXM's U8U8 AR), A8 its A (U8, swizzle 1) */ + { PIPE_FORMAT_I8_UNORM, "I8", 0x80810000, 1, 0x00, 3, SGX_RT_UNORM8 }, + { PIPE_FORMAT_L8_UNORM, "L8", 0x80810000, 1, 0x00, 5, SGX_RT_UNORM8 }, + { PIPE_FORMAT_L8A8_UNORM, "LA8", 0xb0b10000, 2, 0x07, 2, SGX_RT_UNORM8 }, + { PIPE_FORMAT_A8_UNORM, "A8", 0x80910000, 1, 0x00, 6, SGX_RT_UNORM8 }, + /* F16F16F16F16 (iOS's m28 word less the tiled bit), loaded as the + * texture F16F16F16F16 handed back as F16 */ + { PIPE_FORMAT_R16G16B16A16_FLOAT, "RGBA16F", 0x01010000, 8, 0x1b, 0, SGX_RT_F16X4 }, + /* (GL's RGB16F: no alpha, so blending takes the target's as 1) */ + { PIPE_FORMAT_R16G16B16X16_FLOAT, "RGBX16F", 0x01010000, 8, 0x1b, 0, SGX_RT_F16X4 }, + /* F16F16 and F16, loaded raw (the tile's own bits) */ + { PIPE_FORMAT_R16G16_FLOAT, "RG16F", 0x00810000, 4, 0x11, 0, SGX_RT_F16X2 }, + { PIPE_FORMAT_R16_FLOAT, "R16F", 0xf0010000, 2, 0x0b, 0, SGX_RT_F16X2 }, + /* F32, raw both ways; F32F32, two registers */ + { PIPE_FORMAT_R32_FLOAT, "R32F", 0x10810000, 4, 0x12, 0, SGX_RT_F32 }, + { PIPE_FORMAT_R32G32_FLOAT, "RG32F", 0x11010000, 8, 0x1e, 0, SGX_RT_F32X2 }, + /* F11F11F10 (APPLE_color_buffer_packed_float): the PBE packs the + * tile's four F16 with bit 25 (iOS's m28 had it too; without it the + * PBE wrote o0's bits as they are -- for F16F16F16F16 either way); + * loaded as the texture handed back as F16 */ + { PIPE_FORMAT_R11G11B10_FLOAT, "R11G11B10F", 0x23010000, 4, 0x1a, 0, SGX_RT_F16X4 }, +}; + +/* the table as SGX_PBE_ and SGX_BG_ change it, once (M45: the + * names were made and looked up at every draw, sgx_frame_rt_kind()) */ +static void +rt_fmts_env(void) +{ + for (unsigned i = 0; i < ARRAY_SIZE(rt_fmts); i++) { + char name[32]; + const char *e; + + snprintf(name, sizeof(name), "SGX_PBE_%s", rt_fmts[i].name); + if ((e = getenv(name))) + rt_fmts[i].pbe = strtoul(e, NULL, 0); + snprintf(name, sizeof(name), "SGX_BG_%s", rt_fmts[i].name); + if ((e = getenv(name))) { + rt_fmts[i].bg_fmt = strtoul(e, NULL, 0) >> 8 & 0x1f; + rt_fmts[i].bg_swizzle = strtoul(e, NULL, 0) & 7; + } + } +} + +static bool +rt_format(enum pipe_format format, struct sgx_eot *to) +{ + static util_once_flag once = UTIL_ONCE_FLAG_INIT; + + util_call_once(&once, rt_fmts_env); + for (unsigned i = 0; i < ARRAY_SIZE(rt_fmts); i++) { + if (rt_fmts[i].format != format) + continue; + to->pbe = rt_fmts[i].pbe; + to->bytes = rt_fmts[i].bytes; + to->bg_fmt = rt_fmts[i].bg_fmt; + to->bg_swizzle = rt_fmts[i].bg_swizzle; + to->kind = rt_fmts[i].kind; + return true; + } + return false; +} + +struct rt_set { + struct sgx_rt rt; + struct sgx_bo *bo; /* the buffers, then the 3D block */ + uint32_t va[SGX_RT_NBUF], blk_va; + uint64_t used; + struct sgx_fence *fence; /* the last render that used it */ +}; + +/* M27: a render's own memory -- its stream, the draws' state, uniforms, + * fetches, vertices and indices, its copies of the frame's words a render + * sets -- in chunks from the device's cache of buffer objects, which hands + * them out again once the render is done (sgx_bo_set_busy; the kernel keeps + * them for the render) */ +struct arena { + struct sgx_bo *bo[ARENA_MAX]; + unsigned n; + uint32_t at; /* in the last chunk */ +}; + +struct sgx_frame { + struct sgx_device *dev; + struct sgx_bo *bo[MAX_PACK_BOS]; + unsigned nbo; + uint32_t handles[MAX_PACK_BOS + 3]; + + uint32_t kick[3]; /* PB descriptor, render details, TA command */ + uint32_t w, h; + uint32_t consts0, idx, idx_count, vdm, vdm_size, ext, ext_size, heap, heap_size, pds; + unsigned max_draws; /* in a gathered render */ + uint32_t fetch_tag, fetch_word; + uint32_t tail[8]; + unsigned ntail; + uint32_t term; /* the tiles' bounds in the stream's terminate PDS data */ + struct rt_set rts[MAX_RT_SETS]; + uint64_t rt_clock; + struct rt_set *rt_last; /* (M46) the last render's */ + + /* M17: the frame built here (sgx_template.c), in buffers where the + * kernel puts them, rendered with the kernel's parameter buffer -- or the + * pack's, at its addresses (SGX_FRAME=pack, kernels before UAPI 3) */ + bool built; + uint32_t pack_pb; /* built, with the pack's parameter buffer */ + uint32_t cmd_tmpl[SGX_TMPL_CMD_SIZE / 4]; /* the TA command, render target aside */ + uint32_t blk_tmpl[SGX_TMPL_BLOCK_MAX / 4]; /* the 3D block's GL words */ + uint8_t *tmpl; + int toff[T_NUM], tsize[T_NUM]; + uint64_t code_base_expected; + + /* ours: the replace program at code_va, end-of-tile programs after it */ + struct sgx_bo *code; /* their own buffer: SGX_FRAME=codebo only */ + uint32_t code_va; + uint8_t *code_map; + unsigned nhandles; /* the pack's buffers (and ours); then the target */ + struct sgx_eot eot[MAX_EOT]; + struct sgx_fence *eot_fence[MAX_EOT]; /* the last render each slot's program ran in */ + unsigned neot, max_eot, eot_slot; /* eot_slot: the render's */ + struct arena arena; + struct sgx_fence *queued[MAX_QUEUED]; /* the last gathered renders, round in turn */ + unsigned nqueued; + uint32_t texblock; /* the white texture's block, replace program */ + uint32_t iter_pds; /* the iterated-colour pixel program's PDS, per varying */ + uint32_t fetch_pds; /* the vertex fetch, per number of varyings */ + struct sgx_bo *code_heap; /* our programs' code */ + uint32_t empty_prog; + /* where our programs' code (in code_heap) and PDS programs (in the EXT + * window) go; a retired program's places, with the last render then, + * are free again when it is done (struct retired) */ + struct util_vma_heap code_vma, pds_vma; + struct retired *retired; + unsigned nretired, maxretired; + uint32_t vdmbuf[10 * SGX_FRAME_MAX_DRAWS + 32]; /* a gathered render's stream */ + uint32_t vertex_prog[SGX_FRAME_MAX_VARYINGS + 1]; + struct sgx_fence *last; /* the last render through the frame */ + char *dir; /* the pack: loaded again after a render hangs */ + uint64_t timeouts; /* the kernel's count of renders that did */ + bool vma_ready; + bool debug; /* SGX_DEBUG=frame: say what each render is */ + bool debug_state; /* SGX_DEBUG=state: each draw's state words */ + unsigned opts; /* SGX_FRAME */ +}; + +unsigned +sgx_frame_options(void) +{ + static const struct { const char *name; unsigned bit; } names[] = { + { "fb", SGX_FRAME_FB }, { "blend", SGX_FRAME_BLEND }, + { "screen", SGX_FRAME_SCREEN }, { "codebo", SGX_FRAME_CODEBO }, + { "sop2", SGX_FRAME_SOP2 }, { "align", SGX_FRAME_ALIGN }, + { "packpixel", SGX_FRAME_PACKPIX }, { "packvertex", SGX_FRAME_PACKVTX }, + { "packrt", SGX_FRAME_PACKRT }, { "pack", SGX_FRAME_PACK }, { "built", SGX_FRAME_BUILT }, + }; + static int opts = -1; + const char *env = getenv("SGX_FRAME"); + unsigned o = 0; + + if (opts >= 0) + return opts; + while (env && *env) { + size_t n = strcspn(env, ","); + unsigned i; + + for (i = 0; i < ARRAY_SIZE(names); i++) + if (n == strlen(names[i].name) && !strncmp(env, names[i].name, n)) { + o |= names[i].bit; + break; + } + if (n && i == ARRAY_SIZE(names)) + mesa_logw("sgx: SGX_FRAME: no such switch \"%.*s\"", (int)n, env); + env += n + (env[n] == ','); + } + opts = o; + return o; +} + +/* M27: a gathered render's own copies of the frame's words a render sets + * -- the 3D pass's PDS block (the end of tile's DOUTU at +8, the + * background's descriptor at +0x130) and the stream's end (the tiles at + * +0x10) -- so it need not wait for the last render; the TA command, the + * 3D block (a copy too) and the stream's tail point at them. + * With the built frame only, and not for SGX_FRAME=fb, packrt (the + * pack's). */ +struct own { + uint32_t pds, term; +}; + +/* n bytes of the render's own memory, at *va, aligned to al (a power of + * two); NULL if there is none */ +static uint8_t * +arena_alloc(struct sgx_frame *f, uint32_t n, uint32_t al, uint32_t *va) +{ + struct arena *a = &f->arena; + struct sgx_bo *bo = a->n ? a->bo[a->n - 1] : NULL; + uint32_t at = align(a->at, al); + + if (!bo || at + n > bo->size) { + if (a->n == ARENA_MAX || !(bo = sgx_bo_cache_get(f->dev, MAX2(n, ARENA_CHUNK)))) + return NULL; + a->bo[a->n++] = bo; + at = 0; + } + a->at = at + n; + *va = bo->va + at; + return bo->map + at; +} + +/* n bytes from p into the render's own memory; its address (0: none) */ +static uint32_t +arena_put(struct sgx_frame *f, const void *p, uint32_t n, uint32_t al) +{ + uint32_t va; + uint8_t *dst = arena_alloc(f, n, al, &va); + + if (!dst) + return 0; + sgx_copy(dst, p, n); + return va; +} + +/* the render's memory given back: the cache takes it again once the + * render is done */ +static void +arena_release(struct sgx_frame *f) +{ + for (unsigned i = 0; i < f->arena.n; i++) + sgx_bo_destroy(f->arena.bo[i]); + f->arena.n = f->arena.at = 0; +} + +static uint32_t +p27(uint32_t a) /* a PDS data pointer */ +{ + return 0x10000000 | ((a >> 4) & 0x07ffffff); +} + +static uint32_t +vdm4(uint32_t tag, uint32_t a) +{ + return tag << 28 | a >> 4; +} + + +static uint32_t +doutu(struct sgx_frame *f, uint32_t va) /* USE code base 3 */ +{ + return ((va - f->dev->code_base) / 8) << 4 | 3; +} + +/* State word 5's secondary attributes: their count - 1 in bits 21:13, a + * multiple of 32 -- 31 in all of iOS's states (0x3e000); an sa past 32 + * read nothing with that, and 32 itself (33 registers) hangs the GPU + * (M21). (A vertex program's are in its VDM word, in fours.) */ +static uint32_t +sa_field(unsigned nsa) +{ + return (align(MAX2(nsa, 1), 32) - 1) << 13; +} + +/* State word 5 for a pixel program: the registers a pixel takes, primary + * attributes and temporaries, in fours (bits 31:27) -- the temporaries + * from a four after the primary attributes (a texel the PDS fetched after + * the inputs, M35: one primary attribute and 27 temporaries counted as + * 28 registers, not 32, and the temporaries ran into the next pixel's + * texel, which read 0); bits 26:23 as iOS has + * them for 2, 3 and 4 fours, 12 / fours (M13b), but 1 past 12 -- 0 there + * and the program reads 0 for its inputs (M30); its secondary attributes + * (sa_field) */ +static uint32_t +pixel_word5(const struct sgx_pixel_program *pix) +{ + unsigned fours = DIV_ROUND_UP(pixel_pa(pix), 4) + DIV_ROUND_UP(pix->ntemps, 4); + + return fours << 27 | (fours > 1 ? MAX2(12 / fours, 1) : 0) << 23 | sa_field(pix->nsa); +} + +/* A loader of n words (128 at most) at va into sa0..: a DMA, data row + * {address, words - 1, 0, 0}, then the empty program -- iOS's form. Its + * words into out, its data rows returned. (A pixel program has as many sa + * as its state word 5 says: sa_field().) */ +#define UNIFORM_LOADER_MAX 12 + +static unsigned +uniform_loader(struct sgx_frame *f, uint32_t va, unsigned n, uint32_t *out) +{ + const uint32_t loader[UNIFORM_LOADER_MAX] = { + va, n - 1, 0, 0, doutu(f, f->empty_prog), 2, 0, 0, + PDS_DMA_ROW0, PDS_DOUTU_ROW1_AFTER, PDS_END, 0, + }; + + memcpy(out, loader, sizeof(loader)); + return 2; +} + +/* the stream's terminate PDS program (the tail's tag 6 word, in the + * pack's buffers) holds the last tile across (31:16) and down (15:0) in + * its data's +0x10 */ +static uint32_t +term_tiles(unsigned w, unsigned h) +{ + return (DIV_ROUND_UP(w, 32) - 1) << 16 | (DIV_ROUND_UP(h, 32) - 1); +} + +static uint8_t * +cpu_at(struct sgx_frame *f, uint32_t va, uint32_t n, unsigned *which) +{ + for (unsigned i = 0; i < f->nbo; i++) { + struct sgx_bo *bo = f->bo[i]; + + if (va >= bo->va && va - bo->va + n <= bo->size) { + if (which) + *which = i; + return (uint8_t *)bo->map + (va - bo->va); + } + } + return NULL; +} + +static bool +put(struct sgx_frame *f, uint32_t va, const void *p, uint32_t n) +{ + uint8_t *dst = cpu_at(f, va, n, NULL); + + if (!dst) + return false; + memcpy(dst, p, n); + return true; +} + +static bool +load_file(const char *dir, const char *name, uint8_t **buf, size_t *len) +{ + char path[512]; + FILE *fp; + long n; + + *buf = NULL; + *len = 0; + snprintf(path, sizeof(path), "%s/%s", dir, name); + if (!(fp = fopen(path, "rb"))) + return false; + fseek(fp, 0, SEEK_END); + n = ftell(fp); + fseek(fp, 0, SEEK_SET); + *buf = malloc(n > 0 ? n : 1); + *len = *buf ? fread(*buf, 1, n, fp) : 0; + fclose(fp); + return *buf && *len == (size_t)n; +} + +static unsigned +parse_words(const char *p, uint32_t *out, unsigned max) +{ + unsigned n = 0; + + while (n < max && *p) { + char *e; + uint32_t v = strtoul(p, &e, 0); + + if (e == p) + break; + out[n++] = v; + p = e; + } + return n; +} + +static bool +map_window(struct sgx_frame *f, uint32_t va, uint32_t size) +{ + struct sgx_bo *bo; + + if (f->nbo == MAX_PACK_BOS) + return false; + bo = sgx_bo_create(f->dev, size, APPLE_SGX_BO_FIXED_VA, va); + if (!bo && errno == EEXIST) + mesa_logw("sgx: GPU 0x%08x is taken (another client of the template " + "frame, or memory debugfs mapped there)", va); + if (!bo || !sgx_bo_map(bo)) { + sgx_bo_destroy(bo); + return false; + } + f->handles[f->nbo] = bo->handle; + f->bo[f->nbo++] = bo; + return true; +} + +/* the pack's contents ("img" lines) into its buffers: when the frame is + * made, and again after a render hung (it leaves the parameter buffer and + * the render target data half-used) */ +static bool +load_images(struct sgx_frame *f) +{ + char path[512], line[512], key[64], a[64], b[64]; + bool ok = true; + size_t len; + FILE *fp; + + /* a built frame has nothing a render changes but the parameter buffer, + * and that is the kernel's (which writes it again after a restart) -- + * or the pack's, SGX_FRAME=built on an older kernel */ + if (f->built && !f->pack_pb) + return true; + + snprintf(path, sizeof(path), "%s/pack.txt", f->dir); + if (!(fp = fopen(path, "r"))) + return false; + while (ok && fgets(line, sizeof(line), fp)) { + uint8_t *img = NULL; + + if (sscanf(line, "%63s %63s %63s", key, a, b) < 3 || strcmp(key, "img") || + (f->built && strtoul(a, 0, 0) != f->pack_pb)) + continue; + ok = load_file(f->dir, b, &img, &len) && put(f, strtoul(a, 0, 0), img, len); + free(img); + if (!ok) + mesa_logw("sgx: %s/%s is missing or larger than its buffer", f->dir, b); + } + fclose(fp); + return ok; +} + +/* pack.txt, the way sgx2d_open() reads it (two passes there: buffers before + * the microkernel's boot, contents after; the render node needs no boot) */ +static bool +load_pack(struct sgx_frame *f, const char *dir) +{ + char path[512], line[512], key[64], a[64], b[64]; + uint32_t poke_value = 0; + bool ok = true; + size_t len; + FILE *fp; + + snprintf(path, sizeof(path), "%s/pack.txt", dir); + if (!(fp = fopen(path, "r"))) { + mesa_logw("sgx: no template frame at %s (./cascadia a5 dev gpu installs it); " + "clears go through the CPU", path); + return false; + } + f->pds = PDS_DEFAULT; + while (ok && fgets(line, sizeof(line), fp)) { + int n = sscanf(line, "%63s %63s %63s", key, a, b); + + if (n < 2) + continue; + if (!strcmp(key, "map")) + ok = map_window(f, strtoul(a, 0, 0), strtoul(b, 0, 0)); + else if (!strcmp(key, "kick")) + parse_words(line + 4, f->kick, 3); + else if (!strcmp(key, "screen")) { + f->w = atoi(a); + f->h = atoi(b); + } else if (!strcmp(key, "consts0")) + f->consts0 = strtoul(a, 0, 0); + else if (!strcmp(key, "idx")) { + f->idx = strtoul(a, 0, 0); + f->idx_count = n == 3 ? strtoul(b, 0, 0) : 6; /* indices 0, 1, ... */ + } + else if (!strcmp(key, "vdm")) { + f->vdm = strtoul(a, 0, 0); + f->vdm_size = strtoul(b, 0, 0); + } else if (!strcmp(key, "ext")) { + f->ext = strtoul(a, 0, 0); + f->ext_size = strtoul(b, 0, 0); + f->max_draws = SGX_FRAME_MAX_DRAWS; + } else if (!strcmp(key, "texheap")) { + f->heap = strtoul(a, 0, 0); + f->heap_size = strtoul(b, 0, 0); + } else if (!strcmp(key, "pds")) + f->pds = strtoul(a, 0, 0); + else if (!strcmp(key, "fetch")) { + f->fetch_tag = strtoul(a, 0, 0); + f->fetch_word = strtoul(b, 0, 0); + } else if (!strcmp(key, "tail")) + f->ntail = parse_words(line + 4, f->tail, 8); + else if (!strcmp(key, "poke") && n == 3) + poke_value = strtoul(b, 0, 0); + else + for (unsigned i = 0; i < T_NUM; i++) + if (!strcmp(key, tmpl_names[i])) { + f->toff[i] = atoi(a); + f->tsize[i] = atoi(b); + } + } + if (ok && poke_value != f->dev->code_base >> 6) { + mesa_logw("sgx: %s was built for code base 0x%x, the kernel's is 0x%x -- " + "./cascadia a5 dev gpu rebuilds it", dir, poke_value << 6, f->dev->code_base); + ok = false; + } + fclose(fp); + ok = ok && load_images(f); + if (ok && !load_file(dir, "tmpl.bin", &f->tmpl, &len)) + ok = false; + if (ok && (!f->w || !f->h || !f->vdm || !f->ext || !f->heap || !f->kick[2] || + !f->tsize[T_FULL] || !f->tsize[T_FETCH] || !f->tsize[T_TEX] || + f->tsize[T_TEX] > 64 || !cpu_at(f, f->pds, 0x140, NULL))) { + mesa_logw("sgx: %s/pack.txt lacks pieces of the frame", dir); + ok = false; + } + return ok; +} + +/* ---- M17: the frame built here ----------------------------------------- */ + +/* the frame's own buffers, where the kernel puts them */ +#define BUILT_PROG 0x80 /* a program a slot, in its code buffer */ +#define BUILT_PDS 0x0 /* in the GL buffer: the PDS block, */ +#define BUILT_STATE 0x400 /* the state area, */ +#define BUILT_WHITE 0xc00 /* the white texture, */ +#define BUILT_IDX 0x1000 /* the index buffer */ +#define BUILT_GL_SIZE (BUILT_IDX + SGX_TMPL_IDX_COUNT * 2) +#define BUILT_VDM_SIZE 0x1000 /* the template's own draws' stream */ +#define BUILT_EXT_SIZE 0x400000 /* the pack's 4 MiB */ + +static struct sgx_bo * +new_bo(struct sgx_frame *f, uint32_t size, uint32_t flags) +{ + struct sgx_bo *bo; + + if (f->nbo == MAX_PACK_BOS) + return NULL; + bo = sgx_bo_create(f->dev, size, flags, 0); + if (!bo || !sgx_bo_map(bo)) { + sgx_bo_destroy(bo); + return NULL; + } + memset(bo->map, 0, size); + f->handles[f->nbo] = bo->handle; + f->bo[f->nbo++] = bo; + return bo; +} + +/* The one piece from elsewhere: the GL driver's event program for the 3D + * pass (pds.py's event_program(), from the IPSW), as the pack has it at the + * start of its PDS block -- three programs and a word of it are ours. */ +static bool +event_template(const char *dir, uint32_t ev[SGX_TMPL_EVENT_WORDS]) +{ + char path[512], line[512], key[64], a[64], b[64]; + uint32_t pds = PDS_DEFAULT; + bool ok = false; + uint8_t *img; + size_t len; + FILE *fp; + + snprintf(path, sizeof(path), "%s/pack.txt", dir); + if (!(fp = fopen(path, "r"))) + return false; + while (fgets(line, sizeof(line), fp)) + if (sscanf(line, "%63s %63s", key, a) == 2 && !strcmp(key, "pds")) + pds = strtoul(a, 0, 0); + rewind(fp); + while (!ok && fgets(line, sizeof(line), fp)) { + if (sscanf(line, "%63s %63s %63s", key, a, b) < 3 || strcmp(key, "img") || + strtoul(a, 0, 0) != pds || !load_file(dir, b, &img, &len)) + continue; + if (len >= SGX_TMPL_EVENT_WORDS * 4) { + memcpy(ev, img, SGX_TMPL_EVENT_WORDS * 4); + ok = true; + } + free(img); + } + fclose(fp); + return ok; +} + +/* SGX_FRAME=built on a kernel without a parameter buffer of its own: the + * pack's, at its address (the first of pack.txt's kick words) */ +static bool +pack_pb(struct sgx_frame *f, const char *dir) +{ + char path[512], line[512], key[64], a[64], b[64]; + uint32_t kick[3] = { 0 }, size = 0; + FILE *fp; + + snprintf(path, sizeof(path), "%s/pack.txt", dir); + if (!(fp = fopen(path, "r"))) + return false; + while (fgets(line, sizeof(line), fp)) + if (!strncmp(line, "kick ", 5)) + parse_words(line + 4, kick, 3); + rewind(fp); + while (fgets(line, sizeof(line), fp)) + if (sscanf(line, "%63s %63s %63s", key, a, b) == 3 && !strcmp(key, "map") && + strtoul(a, 0, 0) == kick[0]) + size = strtoul(b, 0, 0); + fclose(fp); + if (!kick[0] || !size || !map_window(f, kick[0], size)) + return false; + f->pack_pb = f->kick[0] = f->cmd_tmpl[0x28 / 4] = kick[0]; + return load_images(f); +} + +static bool +build_frame(struct sgx_frame *f, const char *dir) +{ + struct sgx_device *dev = f->dev; + uint32_t ev[SGX_TMPL_EVENT_WORDS], *pds, *state; + struct sgx_bo *prog, *gl, *vdm, *ext; + struct sgx_tmpl t = { 0 }; + static const struct { int which, off, size; } blocks[T_NUM] = { + [T_FULL] = { 1, 0xe0, 0x50 }, [T_FULLPROG] = { 1, 0x140, 0x2c }, + [T_DELTA] = { 1, 0x3c0, 0x20 }, [T_DELTAPROG] = { 1, 0x3e0, 0x2c }, + [T_FETCH] = { 1, 0x180, 0x58 }, [T_TEX] = { 0, 0x160, 0x30 }, + }; + unsigned at = 0; + + f->built = true; + if (!event_template(dir, ev)) { + mesa_logw("sgx: no 3D event program in %s (./cascadia a5 dev gpu installs it)", dir); + return false; + } + if (!(prog = new_bo(f, 0x1000, APPLE_SGX_BO_USSE_CODE)) || + !(gl = new_bo(f, BUILT_GL_SIZE, 0)) || !(vdm = new_bo(f, BUILT_VDM_SIZE, 0)) || + !(ext = new_bo(f, BUILT_EXT_SIZE, 0))) + return false; + + /* the programs, a slot each */ + t.code_base = dev->code_base; + for (unsigned p = 0; p < SGX_TP_N; p++) { + uint64_t code[SGX_TMPL_PROG_MAX]; + unsigned n; + + t.prog[p] = prog->va + p * BUILT_PROG; + n = sgx_tmpl_program(p, (t.prog[p] - dev->code_base) / 8, code); + memcpy(prog->map + p * BUILT_PROG, code, n * 8); + } + /* until a render says, the end of tile and the frame's pixel blocks do + * nothing; the background reads the screen */ + t.eot = t.pixel = t.prog[SGX_TP_EMPTY_A]; + t.pds = gl->va + BUILT_PDS; + t.state = gl->va + BUILT_STATE; + t.idx = gl->va + BUILT_IDX; + t.tex0 = t.tex1 = gl->va + BUILT_WHITE; + t.fb = dev->fb_va ? dev->fb_va : 0x90000000u; + t.fb_w = dev->fb_width ? dev->fb_width : 768; + t.fb_h = dev->fb_height ? dev->fb_height : 1024; + t.fb_stride = dev->fb_stride ? dev->fb_stride / 4 : t.fb_w; + t.w = t.fb_w; + t.h = t.fb_h; + t.rc2 = dev->rc2; + + pds = (uint32_t *)(gl->map + BUILT_PDS); + state = (uint32_t *)(gl->map + BUILT_STATE); + sgx_tmpl_pds(&t, ev, pds); + sgx_tmpl_state(&t, state); + for (unsigned i = 0; i < SGX_TMPL_IDX_COUNT; i++) + ((uint16_t *)(gl->map + BUILT_IDX))[i] = i; + sgx_tmpl_tail(&t, f->tail); + f->ntail = 5; + sgx_tmpl_ta_cmd(&t, vdm->va, 0, f->cmd_tmpl); + f->cmd_tmpl[0x28 / 4] = sgx_device_param(dev, APPLE_SGX_PARAM_PB_VA); + /* SGX_PACK_PB=1: the pack's on any kernel (to tell the kernel's apart) */ + if ((dev->uapi < 3 || getenv("SGX_PACK_PB")) && !pack_pb(f, dir)) + return false; + sgx_tmpl_block3d(&t, f->blk_tmpl); + + /* the blocks draws are made from */ + if (!(f->tmpl = CALLOC(T_NUM, 0x80))) + return false; + for (unsigned i = 0; i < T_NUM; i++) { + f->toff[i] = at; + f->tsize[i] = blocks[i].size; + memcpy(f->tmpl + at, (blocks[i].which ? state : pds) + blocks[i].off / 4, + blocks[i].size); + at += 0x80; + } + + f->w = t.w; + f->h = t.h; + f->kick[0] = f->pack_pb; + f->kick[1] = f->kick[2] = 0; + f->consts0 = t.state + 0xa0; + f->idx = t.idx; + f->idx_count = SGX_TMPL_IDX_COUNT; + f->vdm = vdm->va; + f->vdm_size = BUILT_VDM_SIZE; + f->max_draws = SGX_FRAME_MAX_DRAWS; + f->ext = ext->va; + f->ext_size = BUILT_EXT_SIZE; + f->heap = gl->va + BUILT_WHITE; + f->heap_size = 0x400; + f->pds = t.pds; + f->fetch_tag = 9; + f->fetch_word = 0x07800604; + return true; +} + +/* The buffer for our programs: the lowest free 64 KiB step above the + * pack's windows in the code zone, within a DOUTU's reach */ +static struct sgx_bo * +code_bo(struct sgx_frame *f, uint32_t size) +{ + struct sgx_device *dev = f->dev; + uint32_t lo = MAX2(dev->code_va_start, dev->code_base); + uint32_t hi = MIN2(dev->code_va_end, dev->code_base + CODE_REACH); + + /* a built frame takes the kernel's pick: the code zone is within reach */ + if (f->built) { + struct sgx_bo *bo = sgx_bo_create(dev, size, APPLE_SGX_BO_USSE_CODE, 0); + + if (bo && sgx_bo_map(bo)) + return bo; + sgx_bo_destroy(bo); + return NULL; + } + for (uint32_t va = align(lo, 0x10000); va + size <= hi; va += 0x10000) { + struct sgx_bo *bo; + bool clear = true; + + /* a page of space around the pack's windows, as the kernel leaves */ + for (unsigned i = 0; i < f->nbo && clear; i++) + clear = va + size + 4096 <= f->bo[i]->va || + va >= f->bo[i]->va + f->bo[i]->size + 4096; + if (!clear) + continue; + bo = sgx_bo_create(dev, size, APPLE_SGX_BO_USSE_CODE | APPLE_SGX_BO_FIXED_VA, va); + if (bo && sgx_bo_map(bo)) + return bo; + sgx_bo_destroy(bo); + if (bo || errno != EEXIST) + return NULL; + } + mesa_logw("sgx: no room for programs within 8 MiB of the code base 0x%08x", + dev->code_base); + return NULL; +} + +/* The vertex program for n varyings: the position and the varyings, as + * the vertex fetch put them in pa0.., to the outputs in the same order -- + * iOS's for gl_Position = p; v = a (the corpus's v00_vec4, there with the + * attributes the other way round) -- then to the tiler */ +static unsigned +vertex_program(uint64_t *p, unsigned nvaryings) +{ + unsigned n = 0, pairs = 2 * (1 + nvaryings); + + p[n++] = USSE_PHAS; + p[n++] = USSE_SMLSI_INC1; + for (unsigned i = 0; i < pairs; i += 4) + p[n++] = usse_vmov_f32(i, i, MIN2(4, pairs - i)); + p[n++] = USSE_EMIT_VERTEX; + return n; +} + +/* the vertex fetch for n varyings: one attribute a vec4, from the vertices + * at vb */ +static unsigned +fetch_program(struct sgx_frame *f, uint32_t *p, unsigned nvaryings, uint32_t vb) +{ + unsigned n = 0, rows = 1 + nvaryings; + + for (unsigned i = 0; i < rows; i++) { + p[n++] = vb + 16 * i; + p[n++] = 4 * i << 8 | 3; + p[n++] = i ? 0 : 16 * rows; + p[n++] = 0; + } + p[n++] = doutu(f, f->vertex_prog[nvaryings]); + p[n++] = 0; + p[n++] = 0; + p[n++] = 0; + p[n++] = PDS_FETCH_INDEX; + for (unsigned i = 0; i < rows; i++) + p[n++] = pds_fetch_attr(i); + p[n++] = pds_doutu_vertex(rows); + p[n++] = PDS_END; + return n; +} + +static uint32_t +iter_pds_at(struct sgx_frame *f, unsigned varying, bool f32) +{ + return f->iter_pds + (2 * varying + f32) * ITER_PDS_SIZE; +} + +/* Our pieces into the pack's buffers (again after load_images): the + * replace program, a 4x4 white texture at the start of the texel heap, and + * its block (word 0 the pixel program, 5 the size, log2, 6 the address); + * the iterated-colour pixel programs and their PDS; the vertex programs + * and their fetches. End-of-tile programs are written as targets come. */ +static bool +put_ours(struct sgx_frame *f) +{ + const uint64_t replace[3] = { + USSE_PHAS, USSE_SOP2M_MOD, + f->opts & SGX_FRAME_SOP2 ? USSE_SOP2_REPLACE : USSE_MOV_O0_PA0, + }; + const uint64_t iterated[2] = { USSE_PHAS, USSE_PCK_O0_PA0 }; + const uint64_t iterated_f32[2] = { USSE_PHAS, USSE_PCK_O0_PA0_F32 }; + uint32_t white[16], blk[16], pds[FETCH_PDS_SIZE / 4]; + unsigned at = VERTEX_PROGS; + bool ok; + + memcpy(f->code_map, replace, sizeof(replace)); + memcpy(f->code_map + ITER_PROG, iterated, sizeof(iterated)); + memcpy(f->code_map + ITER_PROG_F32, iterated_f32, sizeof(iterated_f32)); + { + /* PHAS; mov.f16 o0.xyzw, pa0.xyzw, end (iOS's m28) */ + const uint64_t bg64[2] = { USSE_PHAS, 0x3884042185000000ull }; + const uint64_t bg64f32[2] = { + USSE_PHAS, usse_pack_f32x2(usse_reg(USSE_OUTPUT, 0), usse_reg(USSE_PA, 0)) | USSE_END, + }; + + memcpy(f->code_map + BG64_PROG, bg64, sizeof(bg64)); + memcpy(f->code_map + BG64F32_PROG, bg64f32, sizeof(bg64f32)); + } + for (unsigned n = 0; n <= SGX_FRAME_MAX_VARYINGS; n++) { + uint64_t prog[8]; + unsigned len = vertex_program(prog, n); + + f->vertex_prog[n] = f->code_va + at; + memcpy(f->code_map + at, prog, len * 8); + at += len * 8; + } + assert(at <= PROGS_SIZE); + f->neot = 0; + memset(white, 0xff, sizeof(white)); + memcpy(blk, f->tmpl + f->toff[T_TEX], f->tsize[T_TEX]); + if (!(f->opts & SGX_FRAME_BLEND)) + blk[0] = doutu(f, f->code_va); + blk[5] = 0x0c000000 | 2 << 16 | 2; + blk[6] = f->heap; + f->texblock = f->ext; + ok = put(f, f->heap, white, sizeof(white)) && put(f, f->texblock, blk, f->tsize[T_TEX]); + + f->iter_pds = f->ext + EXT_ITER_PDS; + for (unsigned v = 0; v < SGX_FRAME_MAX_VARYINGS; v++) { + for (unsigned f32 = 0; f32 < 2; f32++) { + const uint32_t p[8] = { + doutu(f, f->code_va + (f32 ? ITER_PROG_F32 : ITER_PROG)), ITER_TEMPS, 0, + (f32 ? ITERATE_F32_VEC4 : ITERATE_F16_VEC4) | v << 12, + PDS_DOUTU_ROW0_ITER, f32 ? PDS_ITERATE_4REG_W3 : PDS_ITERATE_2REG_W3, PDS_END, 0, + }; + + ok = ok && put(f, iter_pds_at(f, v, f32), p, sizeof(p)); + } + } + f->fetch_pds = f->ext + EXT_FETCH_PDS; + for (unsigned n = 0; n <= SGX_FRAME_MAX_VARYINGS; n++) { + unsigned len = fetch_program(f, pds, n, f->ext + EXT_VB); + + assert(len * 4 <= FETCH_PDS_SIZE); + ok = ok && put(f, f->fetch_pds + n * FETCH_PDS_SIZE, pds, len * 4); + } + return ok; +} + +struct sgx_frame * +sgx_frame_create(struct sgx_device *dev, const char *dir) +{ + struct sgx_frame *f = CALLOC_STRUCT(sgx_frame); + uint32_t page; + uint8_t *at; + bool pack; + + if (!f) + return NULL; + f->dev = dev; + f->debug = getenv("SGX_DEBUG") && strstr(getenv("SGX_DEBUG"), "frame"); + f->debug_state = getenv("SGX_DEBUG") && strstr(getenv("SGX_DEBUG"), "state"); + f->opts = sgx_frame_options(); + /* the frame built here, unless the kernel is too old for it (no + * parameter buffer of its own, UAPI 3) or the pack's pieces are asked + * for */ + pack = (dev->uapi < 3 && !(f->opts & SGX_FRAME_BUILT)) || + (f->opts & (SGX_FRAME_PACK | SGX_FRAME_FB | SGX_FRAME_BLEND | SGX_FRAME_PACKPIX | + SGX_FRAME_PACKRT)); + if (!(f->dir = strdup(dir)) || !(pack ? load_pack(f, dir) : build_frame(f, dir))) + goto fail; + f->timeouts = sgx_device_param(dev, APPLE_SGX_PARAM_RENDERS_TIMED_OUT); + f->nhandles = f->nbo; + + /* where the stream's end holds the pack's tiles, for other sizes' */ + for (unsigned i = 0; i < f->ntail; i++) { + uint32_t va = (f->tail[i] & 0x0fffffff) << 4; + uint32_t *w = (uint32_t *)cpu_at(f, va + 0x10, 4, NULL); + + if (f->tail[i] >> 28 == 6 && w && *w == term_tiles(f->w, f->h)) + f->term = va + 0x10; + } + if (!f->term) + mesa_logw("sgx: the pack's stream end has not got its tiles where they were " + "found; renders at its size only"); + + /* where our programs go: the free start of the pack's code page, or a + * buffer of their own */ + page = dev->code_base + PAGE_OFFSET; + at = f->built ? NULL : cpu_at(f, page, PAGE_FREE, NULL); + if (!(f->opts & SGX_FRAME_CODEBO) && at) { + for (unsigned i = 0; i < PAGE_FREE && at; i++) + if (at[i]) + at = NULL; + if (!at) + mesa_logw("sgx: the pack's code page has something below its first " + "program; ours go in a buffer of their own"); + } + if (!(f->opts & SGX_FRAME_CODEBO) && at) { + f->code_va = page; + f->code_map = at; + f->max_eot = (PAGE_FREE - PROGS_SIZE) / EOT_SLOT; + } else { + if (!(f->code = code_bo(f, align(CODE_BO_SIZE, 4096)))) + goto fail; + f->code_va = f->code->va; + f->code_map = f->code->map; + f->max_eot = MAX_EOT; + f->handles[f->nhandles++] = f->code->handle; + } + if (!put_ours(f)) + goto fail; + + /* the code of our pixel programs, after an empty program (the uniform + * loader's) */ + if (!(f->code_heap = code_bo(f, HEAP_SIZE))) + goto fail; + ((uint64_t *)f->code_heap->map)[0] = USSE_PHAS; + ((uint64_t *)f->code_heap->map)[1] = 0xf804014000000000ull; /* nop, end */ + f->empty_prog = f->code_heap->va; + util_vma_heap_init(&f->code_vma, f->code_heap->va + 0x40, HEAP_SIZE - 0x40); + f->code_vma.alloc_high = false; + util_vma_heap_init(&f->pds_vma, f->ext + EXT_PROG_PDS, EXT_PROG_PDS_END - EXT_PROG_PDS); + f->pds_vma.alloc_high = false; + f->vma_ready = true; + f->handles[f->nhandles++] = f->code_heap->handle; + if (f->built) + mesa_logi("sgx: template frame built at 0x%08x (PDS); the parameter buffer " + "%s", f->pds, f->pack_pb ? "the pack's" : "the kernel's"); + else + mesa_logi("sgx: template frame %ux%u from %s", f->w, f->h, dir); + return f; + +fail: + sgx_frame_destroy(f); + return NULL; +} + +static void +drop_rt_sets(struct sgx_frame *f) +{ + for (unsigned i = 0; i < MAX_RT_SETS; i++) { + sgx_fence_reference(&f->rts[i].fence, NULL); + sgx_bo_destroy(f->rts[i].bo); + f->rts[i].bo = NULL; + } + f->rt_last = NULL; +} + +void +sgx_frame_finish(struct sgx_frame *f) +{ + if (f && f->last) + sgx_fence_wait(f->last, OS_TIMEOUT_INFINITE); +} + +void +sgx_frame_destroy(struct sgx_frame *f) +{ + if (!f) + return; + if (f->last) { + sgx_fence_wait(f->last, OS_TIMEOUT_INFINITE); + sgx_fence_reference(&f->last, NULL); + } + for (unsigned i = 0; i < f->nretired; i++) + sgx_fence_reference(&f->retired[i].fence, NULL); + free(f->retired); + if (f->vma_ready) { + util_vma_heap_finish(&f->code_vma); + util_vma_heap_finish(&f->pds_vma); + } + sgx_bo_destroy(f->code); + sgx_bo_destroy(f->code_heap); + drop_rt_sets(f); + arena_release(f); + for (unsigned i = 0; i < MAX_EOT; i++) + sgx_fence_reference(&f->eot_fence[i], NULL); + for (unsigned i = 0; i < MAX_QUEUED; i++) + sgx_fence_reference(&f->queued[i], NULL); + for (unsigned i = 0; i < f->nbo; i++) + sgx_bo_destroy(f->bo[i]); + free(f->tmpl); + free(f->dir); + FREE(f); +} + +/* where a target's pixels are: its level's and layer's */ +enum sgx_rt_kind +sgx_frame_rt_kind(enum pipe_format format) +{ + struct sgx_eot to = { 0 }; + + return rt_format(format, &to) ? to.kind : SGX_RT_UNORM8; +} + +static struct sgx_eot +target_eot(const struct sgx_frame_target *t) +{ + const struct sgx_resource *r = t->res; + unsigned w = u_minify(r->base.width0, t->level), h = u_minify(r->base.height0, t->level); + struct sgx_eot to = { + .va = r->bo->va + r->offset[t->level] + t->layer * r->layer_size[t->level], + .w = t->w ? MIN2(t->w, w) : w, .h = t->h ? MIN2(t->h, h) : h, + .stride = r->stride[t->level], + }; + + if (!rt_format(r->base.format, &to)) + rt_format(PIPE_FORMAT_B8G8R8A8_UNORM, &to); + return to; +} + +static bool own_copies(const struct sgx_frame *f); + +bool +sgx_frame_can_render(struct sgx_frame *f, const struct sgx_frame_target *t) +{ + const struct pipe_resource *p = &t->res->base; + struct sgx_eot to; + + if (!f || !t->res->bo || t->level > p->last_level || t->layer >= p->array_size || + (p->target != PIPE_TEXTURE_2D && p->target != PIPE_TEXTURE_CUBE && + p->target != PIPE_TEXTURE_RECT && p->target != PIPE_TEXTURE_1D) || + !rt_format(p->format, &(struct sgx_eot){ 0 }) || p->nr_samples > 1) + return false; + /* (the background of half floats is patched into a render's own copy + * of the PDS block) */ + if (sgx_frame_rt_kind(p->format) != SGX_RT_UNORM8 && !own_copies(f)) + return false; + to = target_eot(t); + return to.w <= SGX_RT_MAX_SIZE && to.h <= SGX_RT_MAX_SIZE && + ((to.w == f->w && to.h == f->h) || (f->term && !(f->opts & SGX_FRAME_PACKRT))) && + !(to.va & 63) && !(to.stride & 15); +} + +/* The render target data for a w x h target: made the first time a render + * goes to that size -- the buffers as sgx_rt.c fills them, the pack's 3D + * block with the size's words -- and kept. A slot taken over: its buffers + * stay with the renders that use them (the kernel's reference), but at a + * fixed address (kernels before UAPI 3) the new ones go where they are -- + * once those renders are done. (M46) Never the last render's: the kernel + * may run two renders at once (apple_sgx.inflight=2), the next one's TA + * while the last one's 3D pass reads its region headers -- a second set + * of the size then, the two taken in turn. */ +static struct rt_set * +rt_set(struct sgx_frame *f, unsigned w, unsigned h) +{ + struct rt_set *s = NULL; + const uint32_t *cmd = f->built ? f->cmd_tmpl : + (const uint32_t *)cpu_at(f, f->kick[2], APPLE_SGX_TA_CMD_MIN, NULL); + const uint8_t *blk = f->built ? (const uint8_t *)f->blk_tmpl : + cmd ? cpu_at(f, cmd[0x50 / 4], BLOCK_SIZE, NULL) : NULL; + uint32_t va, size = 0; + unsigned slot; + + { + struct rt_set *same = NULL; + + for (unsigned i = 0; i < MAX_RT_SETS; i++) { + struct rt_set *t = &f->rts[i]; + + if (t == f->rt_last) + continue; + if (t->bo && t->rt.w == w && t->rt.h == h && (!same || t->used < same->used)) + same = t; + if (!s || (s->bo && (!t->bo || t->used < s->used))) + s = t; + } + if (same) { + same->used = ++f->rt_clock; + f->rt_last = same; + return same; + } + } + if (!s) + return NULL; + slot = s - f->rts; + if (s->fence && f->dev->uapi < 3) + sgx_fence_wait(s->fence, OS_TIMEOUT_INFINITE); + sgx_fence_reference(&s->fence, NULL); + sgx_bo_destroy(s->bo); + s->bo = NULL; + if (!blk || !sgx_rt_layout_rc2(&s->rt, w, h, MAX2(f->dev->num_cores, 1), f->dev->rc2)) + return NULL; + for (unsigned i = 0; i < SGX_RT_NBUF; i++) + size += align(s->rt.size[i], 4096); + size += BLOCK_SIZE; + if (size > RT_SLOT_SIZE) + return NULL; + /* a slot of our own in the TA's heap; the kernel's pick on a kernel + * that has one (UAPI 3, M17) */ + va = RT_SLOT_VA + slot * RT_SLOT_SIZE; + s->bo = f->dev->uapi >= 3 ? + sgx_bo_create(f->dev, size, APPLE_SGX_BO_TA_HEAP, 0) : + sgx_bo_create(f->dev, size, APPLE_SGX_BO_FIXED_VA, va); + if (s->bo) + va = s->bo->va; + size = 0; + for (unsigned i = 0; i < SGX_RT_NBUF; i++) { + s->va[i] = va + size; + size += align(s->rt.size[i], 4096); + } + s->blk_va = va + size; + size += BLOCK_SIZE; + if (!s->bo || !sgx_bo_map(s->bo)) { + mesa_logw("sgx: no render target data for %ux%u at 0x%08x (%u bytes)", w, h, va, size); + sgx_bo_destroy(s->bo); + s->bo = NULL; + return NULL; + } + sgx_rt_fill(&s->rt, s->va, (uint32_t *)(s->bo->map + (s->va[SGX_RT_DETAILS] - va)), + (uint32_t *)(s->bo->map + (s->va[SGX_RT_STATE] - va))); + memset(s->bo->map + (s->blk_va - va), 0, BLOCK_SIZE); + memcpy(s->bo->map + (s->blk_va - va), blk, + f->built ? SGX_RT_BLOCK_SIZE(f->dev->rc2) : BLOCK_SIZE); + sgx_rt_block3d(&s->rt, s->va, (uint32_t *)(s->bo->map + (s->blk_va - va))); + s->used = ++f->rt_clock; + f->rt_last = s; + if (f->debug) + mesa_logi("sgx: render target data for %ux%u at 0x%08x: details 0x%08x, 3D block " + "0x%08x, %u bytes", w, h, va, s->va[SGX_RT_DETAILS], s->blk_va, size); + return s; +} + +/* The state words that hold the target's size: the tiles the TA bins into + * (words 7 and 8: the last tile across and down) and the viewport (9..14: + * translate and scale for x, y and z -- half the width twice, half the + * height twice for the whole target, as iOS's captures of other sizes have + * them, logs/ios/size; the order from glcull, M18) */ +static void +state_size(uint32_t *full, unsigned w, unsigned h) +{ + float hw = w / 2.0f, hh = h / 2.0f; + + full[7] = (full[7] & ~0xfffu) | (DIV_ROUND_UP(w, 32) - 1); + full[8] = (full[8] & ~0xfffu) | (DIV_ROUND_UP(h, 32) - 1); + memcpy(&full[9], &hw, 4); + memcpy(&full[10], &hw, 4); + memcpy(&full[11], &hh, 4); + memcpy(&full[12], &hh, 4); +} + +uint32_t +sgx_frame_zls_size(unsigned w, unsigned h, enum sgx_zls_format format) +{ + return 2 * DIV_ROUND_UP(w, 64) * DIV_ROUND_UP(h, 32) * (format == SGX_ZLS_F32S8 ? 5120 : 4096); +} + +/* ZLSCTL (register 0x480), from iOS's depth capture (0x0015100c, a store) + * and flipping its bits (M23, M24): bit 2 stores the tiles' depth, 17 their + * stencil (16 with it); 14 loads depth (1 with it), 13 stencil; the format + * stored in bits 25:24, loaded in 22:21 -- 0 F32, 1 24-bit with stencil in + * the top byte, 2 16-bit, 3 F32 and stencil in 5 bytes (M43); bits 10:4 + * the rows of tiles in twos less 1 (tile x, y at (x + y * 2 * (v + 1)) * + * 4 KiB, 5 KiB in format 3); 12 and 18 needed. Tiles a render draws + * nothing in are neither loaded nor stored. SGX_ZLS_CTL=value: another + * (the extent put in). (vitasdk's GXM depth/stencil formats read as + * these bits: S8D24 0x01266000, D16 0x02444000, DF32M 0x00044000 and + * DF32M_S8 0x00066000, the last with a stencil surface of its own. Format + * 0 with the stencil bits and a stencil buffer at the 3D block's +0x78, + * +0x7c -- registers 0x48c, 0x490, iOS's payload word 32, 0 there -- + * neither stored nor loaded the stencil, as an offset from the ZLS base + * or an address.) */ +static uint32_t +zls_ctl(const struct sgx_frame_zls *zls) +{ + const char *e = getenv("SGX_ZLS_CTL"); + uint32_t ctl = 0x00151000; + + ctl |= (uint32_t)zls->format << 24 | (uint32_t)zls->format << 21; + if (zls->store) + ctl |= 0xc | (zls->stencil ? 0x20000 : 0); + if (zls->load) + ctl |= 0x4002 | (zls->stencil ? 0x2000 : 0); + if (e) + ctl = strtoul(e, NULL, 0); + return (ctl & ~(0x7fu << 4)) | (DIV_ROUND_UP(zls->w, 64) - 1) << 4; +} + +/* The render: the pack's TA command with the target's render target data + * (or the pack's own, SGX_FRAME=packrt), its parameter buffer, and the + * buffers -- the frame's, the target, the render target data, what the + * draws read besides */ +static int +kick(struct sgx_frame *f, const struct sgx_frame_target *t, float depth, + const struct sgx_frame_zls *zls, struct sgx_bo *vis, const uint32_t *handles, + unsigned nhandles, uint32_t vdm, const struct own *o, struct sgx_fence *done) +{ + struct sgx_eot to = target_eot(t); + uint32_t hs[MAX_PACK_BOS + 3 + 2 + 1 + 1 + SGX_FRAME_MAX_HANDLES + ARENA_MAX]; + uint32_t cmd[APPLE_SGX_TA_CMD_MAX / 4]; + const uint32_t *pack = f->built ? f->cmd_tmpl : + (const uint32_t *)cpu_at(f, f->kick[2], APPLE_SGX_TA_CMD_MIN, NULL); + unsigned n = f->nhandles, det_bo; + uint32_t det_handle, det_offset; + struct rt_set *s = NULL; + uint8_t *blk; + int ret; + + if (!pack || pack[0] > sizeof(cmd) || + (!f->built && !cpu_at(f, f->kick[2], pack[0], NULL)) || + n + 3 + nhandles + f->arena.n > ARRAY_SIZE(hs)) + return -EINVAL; + memcpy(cmd, pack, pack[0]); + memcpy(hs, f->handles, n * sizeof(uint32_t)); + hs[n++] = t->res->bo->handle; + if (f->opts & SGX_FRAME_PACKRT) { + if (!cpu_at(f, f->kick[1], 0xa8, &det_bo)) + return -EFAULT; + det_handle = f->bo[det_bo]->handle; + det_offset = f->kick[1] - f->bo[det_bo]->va; + blk = cpu_at(f, cmd[0x50 / 4] + 0x80, 4, NULL); + } else { + uint32_t blk_va; + + if (!(s = rt_set(f, to.w, to.h))) + return -ENOMEM; + blk_va = s->blk_va; + blk = s->bo->map + (s->blk_va - s->bo->va); + /* a gathered render's own copy of the 3D block, its event and pixel + * PDS programs the render's (M27); the TA command's background + * program and stream too */ + if (o) { + const unsigned bs = SGX_RT_BLOCK_SIZE(f->dev->rc2); + uint8_t *b = arena_alloc(f, bs, 64, &blk_va); + + if (!b) + return -ENOMEM; + memcpy(b, blk, bs); + blk = b; + ((uint32_t *)blk)[sgx_rt_blk_off(f->dev->rc2, 0x98) / 4] = o->pds; + ((uint32_t *)blk)[sgx_rt_blk_off(f->dev->rc2, 0xfc) / 4] = o->pds; + } + sgx_rt_ta_cmd(&s->rt, s->va, blk_va, cmd); + if (o) { + cmd[0x08 / 4] = (o->pds + 0x100 - 0x80000000u) >> 4; + cmd[0x10 / 4] = p27(o->pds + 0x120); + } + det_handle = hs[n++] = s->bo->handle; + det_offset = s->va[SGX_RT_DETAILS] - s->bo->va; + blk += 0x80; + } + /* the depth the tiles start at: register 0x4b8, the 3D block's +0x80 + * (1.0 as the kext sets it, M4) */ + if (!blk) + return -EFAULT; + memcpy(blk, &depth, 4); + /* the depth buffer (M24), where the kext puts a GL depth attachment's + * payload words (logs/ios/depth, rtemu.py): the ZLS base at +0x14 (1 MiB + * aligned, BIF_ZLS_REQ_BASE), ZLSCTL at +0x6c, the load and store + * offsets from the base at +0x70, +0x74 */ + { + uint32_t *b = (uint32_t *)(blk - 0x80), base = zls ? zls->bo->va & ~0xfffffu : 0; + + /* (M43) a target of half floats: two output registers a pixel -- the + * one word of the 3D block iOS's kext sets apart for m28's target + * (its builder 0x80bf5eec run on m25's and m28's payloads, rtemu.py: + * payload word 34) */ + b[0x4c / 4] = sgx_rt_kind_64(sgx_frame_rt_kind(t->res->base.format)); + b[0x14 / 4] = base; + b[0x6c / 4] = zls ? zls_ctl(zls) : 0; + b[0x70 / 4] = zls ? zls->bo->va - base : 0; + b[0x74 / 4] = zls ? zls->bo->va - base : 0; + if (zls) + hs[n++] = zls->bo->handle; + } + /* the visibility buffer (M37): what iOS's GL hands the kext as payload + * words 42 and 43 (m29), the 3D block's first two words -- core 0's + * count at the buffer, core 1's SGX_VIS_CORE_STRIDE further */ + if (vis) { + uint32_t *b = (uint32_t *)(blk - 0x80); + + for (unsigned c = 0; c < MIN2(f->dev->num_cores, 3); c++) + b[c] = vis->va + c * SGX_VIS_CORE_STRIDE; + hs[n++] = vis->handle; + } + /* the stream: the render's own (M27), or the frame's */ + if (vdm) + cmd[0xd4 / 4] = vdm; + /* SGX_CMD=off:xor[,...]: the TA command's words flipped (finding them) */ + { + static uint32_t xo[APPLE_SGX_TA_CMD_MAX / 4]; + static int parsed; + + if (!parsed) { + const char *e = getenv("SGX_CMD"); + + parsed = 1; + while (e && *e) { + char *t; + unsigned o = strtoul(e, &t, 0); + + if (*t != ':' || o >= APPLE_SGX_TA_CMD_MAX) + break; + xo[o / 4] ^= strtoul(t + 1, &t, 0); + e = *t == ',' ? t + 1 : t; + } + } + for (unsigned i = 0; i < cmd[0] / 4; i++) + cmd[i] ^= xo[i]; + } + /* SGX_BLK=off:xor[,...]: the 3D block's words flipped (finding them) */ + { + static uint32_t xo[0x160 / 4]; + static int parsed; + + if (!parsed) { + const char *e = getenv("SGX_BLK"); + + parsed = 1; + while (e && *e) { + char *t; + unsigned o = strtoul(e, &t, 0); + + if (*t != ':' || o >= 0x160) + break; + xo[o / 4] ^= strtoul(t + 1, &t, 0); + e = *t == ',' ? t + 1 : t; + } + } + for (unsigned i = 0; i < 0x160 / 4; i++) + ((uint32_t *)(blk - 0x80))[i] ^= xo[i]; + } + if (getenv("SGX_DEBUG") && strstr(getenv("SGX_DEBUG"), "cmd")) { + for (unsigned i = 0; i < cmd[0] / 4; i++) + fprintf(stderr, "%s%03x:%08x", i % 8 ? " " : "\nsgx: cmd ", 4 * i, cmd[i]); + for (unsigned i = 0; i < 0x160 / 4; i++) + fprintf(stderr, "%s%03x:%08x", i % 8 ? " " : "\nsgx: blk ", 4 * i, + ((uint32_t *)(blk - 0x80))[i]); + fprintf(stderr, "\n"); + } + memcpy(hs + n, handles, nhandles * sizeof(uint32_t)); + n += nhandles; + for (unsigned i = 0; i < f->arena.n; i++) + hs[n++] = f->arena.bo[i]->handle; + /* each buffer once: the kernel takes each one's reservation lock and + * refuses a buffer listed twice (EALREADY: the whole render dropped) -- + * a draw that samples the render's own target lists the target among + * its textures too (PPSSPP's bloom without its copies, M48) */ + for (unsigned i = 0; i < n; i++) + for (unsigned j = i + 1; j < n; j++) + if (hs[j] == hs[i]) + hs[j--] = hs[--n]; + if (f->debug) + mesa_logi("sgx: kick: PB 0x%08x, details 0x%08x (%s), 3D block 0x%08x, TA command " + "%u bytes, %u buffers", f->kick[0], cmd[0x54 / 4], + s ? "ours" : "the pack's", cmd[0x50 / 4], cmd[0], n); + ret = sgx_submit(f->dev, cmd, f->kick[0], det_handle, det_offset, hs, n, done); + if (!ret) { + sgx_fence_reference(&f->last, done); + sgx_fence_reference(&f->eot_fence[f->eot_slot], done); + if (s) + sgx_fence_reference(&s->fence, done); + } + return ret; +} + +/* The end-of-tile program for a target: written once per target, in a + * slot of its own (f->eot_slot says which, for the render's fence). When + * the slots run out (seven in the pack's page) the oldest is written over, + * once the last render that ran it is done -- the USSE may still have the + * old program in its cache. */ +static uint32_t +eot_program(struct sgx_frame *f, const struct sgx_eot *want) +{ + const uint32_t pbe[6] = { + want->pbe, want->va, want->stride / want->bytes / 2 - 1, 0, 0, + (want->h - 1) << 12 | (want->w - 1), + }; + uint64_t prog[11]; + unsigned i, slot; + + for (i = 0; i < MIN2(f->neot, f->max_eot); i++) + if (!memcmp(&f->eot[i], want, sizeof(*want))) { + f->eot_slot = i; + return f->code_va + PROGS_SIZE + i * EOT_SLOT; + } + slot = f->neot++ % f->max_eot; + if (f->neot == f->max_eot + 1) + mesa_logw("sgx: more render targets than end-of-tile slots (%u); old ones are " + "written over", f->max_eot); + if (f->eot_fence[slot]) + sgx_fence_wait(f->eot_fence[slot], OS_TIMEOUT_INFINITE); + f->eot[slot] = *want; + f->eot_slot = slot; + + prog[0] = USSE_PHAS; + memcpy(&prog[1], usse_dummy_load, sizeof(usse_dummy_load)); + for (i = 0; i < 6; i++) + prog[4 + i] = usse_limm_r(i, pbe[i]); + prog[10] = USSE_EMIT_PIXEL; + memcpy(f->code_map + PROGS_SIZE + slot * EOT_SLOT, prog, sizeof(prog)); + return f->code_va + PROGS_SIZE + slot * EOT_SLOT; +} + +/* two triangles over the whole target, the pack's vertices */ +static void +quad(float *v, const float rgba[4]) +{ + static const float corner[4][2] = { { 0, 0 }, { 1, 0 }, { 1, 1 }, { 0, 1 } }; + static const int order[6] = { 0, 1, 2, 0, 2, 3 }; + + for (unsigned i = 0; i < 6; i++, v += PACK_VTX_FLOATS) { + const float *c = corner[order[i]]; + + memcpy(v, rgba, 4 * sizeof(float)); + v[4] = c[0]; + v[5] = c[1]; + v[6] = c[0] * 2 - 1; + v[7] = c[1] * 2 - 1; + } +} + +static unsigned +max_vertices(struct sgx_frame *f, unsigned stride) +{ + unsigned n = MIN2(f->idx_count, (EXT_FRAME - EXT_VB) / stride); + + return n - n % 3; +} + +unsigned +sgx_frame_max_vertices(struct sgx_frame *f, const struct sgx_frame_layout *l) +{ + /* the pack's vertices (SGX_FRAME=packvertex) are never larger */ + return max_vertices(f, sgx_frame_vertex_floats(l) * sizeof(float)); +} + +/* the retired programs' places whose renders are done (all of them: + * after waiting for the last render) back into the heaps */ +static void +reclaim(struct sgx_frame *f, bool all) +{ + unsigned n = 0; + + for (unsigned i = 0; i < f->nretired; i++) { + struct retired *r = &f->retired[i]; + + if (all || !r->fence || sgx_fence_wait(r->fence, 0)) { + util_vma_heap_free(&f->code_vma, r->code_va, r->code_size); + if (r->pds_size) + util_vma_heap_free(&f->pds_vma, r->pds_va, r->pds_size); + sgx_fence_reference(&r->fence, NULL); + } else { + f->retired[n++] = *r; + } + } + f->nretired = n; +} + +/* a program's code and PDS places, the retired ones' taken back first if + * need be (waiting for the last render, at worst); false: no room */ +static bool +place_program(struct sgx_frame *f, uint32_t code_size, uint32_t pds_size, + uint32_t *code_va, uint32_t *pds_va) +{ + for (unsigned attempt = 0; attempt < 3; attempt++) { + if (attempt == 1) + reclaim(f, false); + if (attempt == 2) { + if (!f->nretired) + break; + if (f->last) + sgx_fence_wait(f->last, OS_TIMEOUT_INFINITE); + reclaim(f, true); + } + *code_va = util_vma_heap_alloc(&f->code_vma, code_size, 64); + if (!*code_va) + continue; + *pds_va = pds_size ? util_vma_heap_alloc(&f->pds_vma, pds_size, PROG_PDS_SLOT) : 0; + if (*pds_va || !pds_size) + return true; + util_vma_heap_free(&f->code_vma, *code_va, code_size); + } + return false; +} + +static void +retire(struct sgx_frame *f, uint32_t code_va, uint32_t code_size, uint32_t pds_va, + uint32_t pds_size) +{ + struct retired *r; + + if (f->nretired == f->maxretired) { + unsigned max = MAX2(16, 2 * f->maxretired); + + if (!(r = realloc(f->retired, max * sizeof(*r)))) { + /* nowhere to keep it: the places stay taken */ + mesa_logw_once("sgx: out of memory for a retired program: its place is lost"); + return; + } + f->retired = r; + f->maxretired = max; + } + r = &f->retired[f->nretired++]; + *r = (struct retired){ code_va, code_size, pds_va, pds_size, NULL }; + sgx_fence_reference(&r->fence, f->last); +} + +void +sgx_frame_retire(struct sgx_frame *f, struct sgx_pixel_program *p) +{ + if (!p->code_va) + return; + retire(f, p->code_va, align(p->ncode * 8, 64), p->pds_va, PROG_PDS_SLOT); + p->code_va = p->pds_va = 0; +} + +void +sgx_frame_retire_vs(struct sgx_frame *f, struct sgx_vs *vs) +{ + if (!vs->code_va) + return; + retire(f, vs->code_va, align(vs->ncode * 8, 64), 0, 0); + vs->code_va = 0; +} + +/* A pixel program into GPU memory, at its first draw: the code into the + * heap, and its PDS program -- start the program, then iterate each input + * (F32, four registers; iOS's shape, the corpus's v04 and v05) -- into the + * EXT window, until it is retired (sgx_frame_retire). */ +static int +upload(struct sgx_frame *f, struct sgx_pixel_program *p) +{ + uint32_t pds[PROG_PDS_SLOT / 4], size = p->ncode * 8, code_va, pds_va; + unsigned n = 0, data; + + if (p->code_va) + return 0; + if (p->ninputs > SGX_FRAME_MAX_VARYINGS || + !place_program(f, align(size, 64), PROG_PDS_SLOT, &code_va, &pds_va)) { + mesa_logw("sgx: no room for another pixel program"); + return -ENOSPC; + } + memcpy((uint8_t *)f->code_heap->map + (code_va - f->code_heap->va), p->code, size); + p->code_va = code_va; + + pds[n++] = doutu(f, p->code_va); + /* (bit 0 for a program that branches: iOS's c04_loop_break has 3 where + * the rest have 2) */ + pds[n++] = (p->ninputs ? ITER_TEMPS : 2) | p->branches; + pds[n++] = 0; + for (unsigned i = 0; i < p->ninputs; i++) + pds[n++] = iterate_control(p, i); + while (n % 4) + pds[n++] = 0; + data = n; + pds[n++] = PDS_DOUTU_ROW0_ITER; + for (unsigned i = 0; i < p->ninputs; i++) + pds[n++] = pds_iterate(3 + i, iterate_size(p, i)); + pds[n++] = PDS_END; + p->pds_va = pds_va; + p->pds_rows = data / 4; + return put(f, p->pds_va, pds, n * 4) ? 0 : -EFAULT; +} + +/* A vertex shader's code into GPU memory, at its first draw (its fetch is + * each draw's: vs_fetch()) */ +int +sgx_frame_upload_vs(struct sgx_frame *f, struct sgx_vs *vs) +{ + uint32_t size = vs->ncode * 8, code_va, pds_va; + + if (vs->code_va) + return 0; + if (vs->nattrs > SGX_VS_MAX_ATTRIBS || + !place_program(f, align(size, 64), 0, &code_va, &pds_va)) { + mesa_logw("sgx: no room for another vertex program"); + return -ENOSPC; + } + memcpy((uint8_t *)f->code_heap->map + (code_va - f->code_heap->va), vs->code, size); + vs->code_va = code_va; + return 0; +} + +/* A draw's vertex fetch (M26), into words[]: a DMA row for each attribute + * the shader takes from memory -- {address of vertex 0's, first pa << 8 | + * words - 1, the stride (row 0's only: one for the whole fetch), 0} -- + * then the program (DOUTU; bit 0 of its second word for a program that + * branches: without it, a loop whose count differs between vertices came + * out wrong, M22); then the index fetch, each row's, the program started + * (iOS's shape, the corpus's x cases). The DOUTU's temporaries are none: + * the program's scratch is primary attributes after the vertex's, which the + * VDM's fetch word counts in (vs_fetch_word()). Returns its data rows. */ +static unsigned +vs_fetch(struct sgx_frame *f, const struct sgx_frame_draw *d, uint32_t vb, uint32_t *words, + unsigned *nwords) +{ + const struct sgx_vs *vs = d->vs; + unsigned n = 0, rows = 0; + + for (unsigned a = 0; a < vs->nattrs; a++) { + if (SGX_ATTR_KIND(vs->attr[a]) == SGX_ATTR_CONST) + continue; + words[n++] = vb + d->base[a]; + words[n++] = 4 * a << 8 | (sgx_attr_words(vs->attr[a]) - 1); + words[n++] = rows ? 0 : d->stride; + words[n++] = 0; + rows++; + } + /* (no attribute from memory: a word read into pa0, which is attribute + * 0's and never read) */ + if (!rows) { + words[n++] = f->ext; + words[n++] = 0; + words[n++] = 0; + words[n++] = 0; + rows++; + } + words[n++] = doutu(f, vs->code_va); + words[n++] = vs->branches; + words[n++] = 0; + words[n++] = 0; + words[n++] = PDS_FETCH_INDEX; + for (unsigned r = 0; r < rows; r++) + words[n++] = pds_fetch_attr(r); + words[n++] = pds_doutu_vertex(rows); + words[n++] = PDS_END; + *nwords = n; + return rows + 1; +} + +/* The VDM's word after a vertex shader's fetch: the vec4s the vertex hands + * the tiler, the position and the varyings (bits 25 and up -- what M13b + * read as attributes: with its copying programs they were as many), the + * registers the program takes -- the attributes' four words each, then its + * temporaries -- and the fetch's data rows */ +static uint32_t +vs_fetch_word(const struct sgx_vs *vs, unsigned rows) +{ + unsigned regs = align(4 * vs->nattrs + vs->ntemps, 4); + + return (1 + vs->nvaryings) << 25 | 0x01800000u | regs << 7 | rows; +} + +static int render(struct sgx_frame *f, struct sgx_resource *rt, + const struct sgx_frame_layout *l, const float *verts, unsigned nverts, + bool iterated, struct sgx_pixel_program *prog, const uint32_t *sa, + const uint32_t *handles, unsigned nhandles, + const struct sgx_frame_state *st, struct sgx_fence *done); + +/* a clear: the pack's vertex and pixel sides, as M12 proved them */ +int +sgx_frame_clear(struct sgx_frame *f, struct sgx_resource *rt, const float rgba[4], + struct sgx_fence *done) +{ + float verts[6 * PACK_VTX_FLOATS]; + + quad(verts, rgba); + return render(f, rt, NULL, verts, 6, false, NULL, NULL, NULL, 0, NULL, done); +} + +int +sgx_frame_draw(struct sgx_frame *f, struct sgx_resource *rt, const struct sgx_frame_layout *l, + const float *verts, unsigned nverts, struct sgx_pixel_program *prog, + const uint32_t *sa, const uint32_t *handles, unsigned nhandles, + const struct sgx_frame_state *st, struct sgx_fence *done) +{ + unsigned vf = sgx_frame_vertex_floats(l); + float *pack; + int ret; + + if (l->nvaryings > SGX_FRAME_MAX_VARYINGS || + (prog ? l->nvaryings != prog->nvaryings : l->colour >= l->nvaryings)) + return -EINVAL; + if (prog) + return render(f, rt, l, verts, nverts, true, prog, sa, handles, nhandles, st, done); + if (!(f->opts & (SGX_FRAME_PACKVTX | SGX_FRAME_PACKPIX))) + return render(f, rt, l, verts, nverts, true, NULL, NULL, NULL, 0, st, done); + + /* through the pack's vertex side: r g b a (the colour) u v x y */ + if (!(pack = malloc(nverts * PACK_VTX_FLOATS * sizeof(float)))) + return -ENOMEM; + for (unsigned i = 0; i < nverts; i++) { + const float *in = verts + i * vf; + float *out = pack + i * PACK_VTX_FLOATS; + + memcpy(out, in + 4 + 4 * l->colour, 4 * sizeof(float)); + out[4] = out[5] = 0; + out[6] = in[0]; + out[7] = in[1]; + } + ret = render(f, rt, NULL, pack, nverts, !(f->opts & SGX_FRAME_PACKPIX), NULL, NULL, NULL, + 0, st, done); + free(pack); + return ret; +} + +static bool +own_copies(const struct sgx_frame *f) +{ + return f->built && f->term && !(f->opts & (SGX_FRAME_FB | SGX_FRAME_PACKRT)); +} + +/* What every render starts with: the pack again after a hang, and the end + * of tile and background aimed at the target (or, with SGX_FRAME=screen, + * the framebuffer) -- into the render's own copies (o), or into the + * frame's words once the last render is done (the frame's buffers are its + * until then). */ +static int +begin_render(struct sgx_frame *f, const struct sgx_frame_target *t, struct sgx_eot *out_to, + uint32_t *out_eot, uint32_t bg[4], struct own *o) +{ + struct sgx_eot to = target_eot(t); + uint32_t eot, d0, tiles = term_tiles(to.w, to.h); + uint64_t timeouts; + + if (!o) { + sgx_trace_mark("begin_render wait"); + if (f->last && !sgx_fence_wait(f->last, 5ull * 1000 * 1000 * 1000)) + mesa_logw("sgx: the last render through the template frame is still running"); + sgx_trace_mark("begin_render waited"); + } + + /* a render that hung (this process's or another's) leaves the parameter + * buffer and the render target data half-used: the pack again */ + timeouts = sgx_device_param(f->dev, APPLE_SGX_PARAM_RENDERS_TIMED_OUT); + if (timeouts != f->timeouts) { + mesa_logw("sgx: a render timed out (%llu so far); the template frame is " + "loaded again", (unsigned long long)timeouts); + f->timeouts = timeouts; + if (f->last) + sgx_fence_wait(f->last, 5ull * 1000 * 1000 * 1000); + if (!load_images(f) || !put_ours(f)) + return -EFAULT; + drop_rt_sets(f); + } + + /* where tiles go, and what they start as: the render target (or, with + * SGX_FRAME=screen, the framebuffer) */ + if (f->opts & SGX_FRAME_SCREEN) { + /* where the pack's own end of tile writes, if the kernel does not say */ + to.va = f->dev->fb_va ? f->dev->fb_va : 0x90000000u; + to.stride = f->dev->fb_stride ? f->dev->fb_stride : f->w * 4; + rt_format(PIPE_FORMAT_B8G8R8A8_UNORM, &to); + } + eot = eot_program(f, &to); + bg[0] = (to.stride / 4 / 4 - 2) << 16 | 0x0e90; + bg[1] = 0xc0000000 | to.bg_fmt << 24 | (to.w - 1) << 12 | (to.h - 1); + /* (M43) four half floats: handed back as F16, two registers (R11G11B10F + * too: the tile's F16) */ + if (to.kind == SGX_RT_F16X4) + bg[3] |= 0x80000000u; + bg[2] = to.va; + bg[3] = to.bg_swizzle << 28; + d0 = doutu(f, eot); + + if (o) { + const uint8_t *pds = cpu_at(f, f->pds, SGX_TMPL_PDS_SIZE, NULL); + const uint8_t *term = cpu_at(f, f->term - 0x10, 0x60, NULL); + uint32_t *p, *t; + + if (!pds || !term || !(p = (uint32_t *)arena_alloc(f, SGX_TMPL_PDS_SIZE, 64, &o->pds)) || + !(t = (uint32_t *)arena_alloc(f, 0x60, 64, &o->term))) + return -ENOMEM; + memcpy(p, pds, SGX_TMPL_PDS_SIZE); + p[8 / 4] = d0; + memcpy(p + 0x130 / 4, bg, 4 * sizeof(uint32_t)); + /* (M43) the background of four half floats: its texel into two + * registers (iOS's F16 lookups: iterate size 0x52, texture DOUT kind + * 0x024) and our program moving both into o0, o1 */ + if (to.kind == SGX_RT_F16X4) { + p[0x120 / 4] = doutu(f, f->code_va + BG64_PROG); + p[0x144 / 4] = (p[0x144 / 4] & ~0xffu) | 0x52; + p[0x148 / 4] = (p[0x148 / 4] & ~0xfffu) | 0x024; + } else if (to.kind == SGX_RT_F32X2) { + /* (two F32 raw: two registers, iterate size 0x12) */ + p[0x120 / 4] = doutu(f, f->code_va + BG64F32_PROG); + p[0x144 / 4] = (p[0x144 / 4] & ~0xffu) | 0x12; + } + memcpy(t, term, 0x60); + t[0x10 / 4] = tiles; + } else { + /* the tiles the stream's end covers: the target's */ + if (f->term && !put(f, f->term, &tiles, 4)) + return -EFAULT; + if (!(f->opts & SGX_FRAME_FB) && + (!put(f, f->pds + 8, &d0, 4) || !put(f, f->pds + 0x130, bg, 4 * sizeof(uint32_t)))) + return -EFAULT; + } + + *out_to = to; + *out_eot = eot; + return 0; +} + +/* A render through the frame: with l, our vertex side (M13b) and verts + * laid out as it says; without, the pack's, verts r g b a u v x y. The + * pixel side is the iterated colour (l's colour varying, or the pack's) or + * the pack's texel x colour. */ +static int +render(struct sgx_frame *f, struct sgx_resource *rt, const struct sgx_frame_layout *l, + const float *verts, unsigned nverts, bool iterated, struct sgx_pixel_program *pix, + const uint32_t *sa, const uint32_t *handles, unsigned nhandles, + const struct sgx_frame_state *st, struct sgx_fence *done) +{ + const struct sgx_frame_target t = { rt, 0, 0 }; + uint32_t vdm[32] = { 0 }, full[32], prog[16], fetch[32], bg[4], *v = vdm; + uint32_t frame = f->ext + EXT_FRAME, vb = f->ext + EXT_VB, d0, p0, fb, eot, fetch_word; + unsigned stride = l ? sgx_frame_vertex_floats(l) * sizeof(float) : + PACK_VTX_FLOATS * sizeof(float); + unsigned colour = l ? l->colour : PACK_COLOUR_VARYING; + bool f32 = l && (l->f32 >> l->colour & 1); + uint32_t uni_pds = f->ext + EXT_FRAME + FRAME_UNI_PDS; + uint32_t uni = f->ext + EXT_FRAME + FRAME_UNIFORMS; + struct sgx_eot to; + unsigned i; + int ret; + + if (!sgx_frame_can_render(f, &t) || f->tsize[T_FULL] > STATE_WORDS * 4 || + f->tsize[T_FULLPROG] > (int)sizeof(prog) || f->tsize[T_FETCH] > (int)sizeof(fetch) || + !nverts || nverts % 3 || nverts > max_vertices(f, stride)) + return -EINVAL; + + if ((ret = begin_render(f, &t, &to, &eot, bg, NULL))) + return ret; + + /* draw 0: the whole state, the white texture with the replace program */ + memset(full, 0, sizeof(full)); + memcpy(full, f->tmpl + f->toff[T_FULL], f->tsize[T_FULL]); + state_size(full, to.w, to.h); + /* the pixel program's PDS: tag (bits 31:27) its data size in rows */ + full[6] = iterated ? 1u << 27 | (iter_pds_at(f, colour, f32) >> 4 & 0x07ffffff) : + p27(f->texblock); + if (st) { + /* ISP state B: the depth compare in bits 24:22, bit 20 set when depth + * is not written (iOS's depth capture, M5) */ + full[1] = (full[1] & ~(7u << 22 | 1u << 20)) | (uint32_t)(st->depth_func & 7) << 22 | + (st->depth_write ? 0 : 1u << 20); + } + if (pix) { + /* our pixel program: its PDS (word 6), how many registers a pixel + * takes (word 5) and its secondary attributes in sa0.. (word 4: a + * DMA, then the empty program) */ + /* (uniforms in memory and the PDS's lookups only through + * draw_state(), M32, M35) */ + if (pix->nubuf || pix->nfetch) + return -EINVAL; + if ((ret = upload(f, pix))) + return ret; + full[6] = pix->pds_rows << 27 | (pix->pds_va >> 4 & 0x07ffffff); + full[5] = pixel_word5(pix); + if (pix->nsa) { + uint32_t loader[UNIFORM_LOADER_MAX]; + unsigned rows = uniform_loader(f, uni, pix->nsa, loader); + + if (pix->nsa > 128 || !put(f, uni, sa, pix->nsa * 4) || + !put(f, uni_pds, loader, sizeof(loader))) + return -EFAULT; + full[4] = rows << 27 | (uni_pds >> 4 & 0x07ffffff); + } + } + if (l) + layout_words(full, l); + d0 = frame; + memcpy(prog, f->tmpl + f->toff[T_FULLPROG], f->tsize[T_FULLPROG]); + prog[0] = d0; + p0 = (frame + STATE_WORDS * 4 + 0x3f) & ~0x3fu; + if (!put(f, d0, full, STATE_WORDS * 4) || !put(f, p0, prog, f->tsize[T_FULLPROG]) || + !put(f, vb, verts, nverts * stride)) + return -EFAULT; + if (l) { + fb = f->fetch_pds + l->nvaryings * FETCH_PDS_SIZE; + fetch_word = vdm_fetch_word(l->nvaryings); + } else { + memcpy(fetch, f->tmpl + f->toff[T_FETCH], f->tsize[T_FETCH]); + fetch[0] = vb; /* r g b a */ + fetch[4] = vb + 16; /* u v */ + fetch[8] = vb + 24; /* x y */ + fb = (p0 + f->tsize[T_FULLPROG] + 0x3f) & ~0x3fu; + fetch_word = f->fetch_word; + if (!put(f, fb, fetch, f->tsize[T_FETCH])) + return -EFAULT; + } + + /* the draw: index count, the index buffer (0, 1, 2, ...) */ + *v++ = vdm4(4, f->consts0); *v++ = 0x1000e102; + *v++ = vdm4(4, p0); *v++ = 0x12022206; + *v++ = 0x81c00000 | nverts; *v++ = f->idx; *v++ = 0x70000000; *v++ = 0x003fffff; + *v++ = vdm4(l ? vdm_fetch_tag(l->nvaryings) : f->fetch_tag, fb); *v++ = fetch_word; + for (i = 0; i < f->ntail; i++) + *v++ = f->tail[i]; + if (!put(f, f->vdm, vdm, (v - vdm) * 4)) + return -EFAULT; + + if (f->debug) { + const float *c = l ? verts + 4 + 4 * l->colour : verts, *pos = l ? verts : verts + 6; + + mesa_logi("sgx: %u vertices into %ux%u at 0x%08x (stride %u); the first's colour " + "%.3f %.3f %.3f %.3f, position %.3f %.3f", nverts, to.w, to.h, rt->bo->va, + rt->stride[0], c[0], c[1], c[2], c[3], pos[0], pos[1]); + if (l) + mesa_logi("sgx: vertex side: ours, %u varyings (F32 mask 0x%x), the colour " + "varying %u; program 0x%08x, state words 16 %08x 19 %08x 20 %08x, " + "fetch word %08x", l->nvaryings, l->f32, l->colour, + f->vertex_prog[l->nvaryings], full[16], full[19], full[20], fetch_word); + else + mesa_logi("sgx: vertex side: the pack's"); + mesa_logi("sgx: SGX_FRAME=%s; our programs at 0x%08x (%s)", + getenv("SGX_FRAME") ? getenv("SGX_FRAME") : "", f->code_va, + f->code ? "a buffer of their own" : "the pack's code page"); + if (f->opts & SGX_FRAME_FB) + mesa_logi("sgx: the pack's end of tile and background: to the screen"); + else + mesa_logi("sgx: end of tile at 0x%08x (DOUTU 0x%08x) to 0x%08x, background " + "%08x %08x %08x %08x", eot, doutu(f, eot), to.va, bg[0], bg[1], bg[2], bg[3]); + if (pix) + mesa_logi("sgx: pixel program: compiled, %u instructions at 0x%08x, %u temps, " + "%u inputs, %u sa words; its PDS at 0x%08x (%u rows), state words 4 " + "%08x 5 %08x 6 %08x", pix->ncode, pix->code_va, pix->ntemps, + pix->ninputs, pix->nsa, pix->pds_va, pix->pds_rows, full[4], + full[5], full[6]); + else if (iterated) + mesa_logi("sgx: pixel program: varying %u iterated as %s and packed (iOS's); " + "its PDS at 0x%08x (state word 6 0x%08x), the program at 0x%08x", + colour, f32 ? "F32" : "F16", iter_pds_at(f, colour, f32), full[6], + f->code_va + (f32 ? ITER_PROG_F32 : ITER_PROG)); + else + mesa_logi("sgx: pixel program: %s (texture block 0x%08x word 0 = 0x%08x)", + f->opts & SGX_FRAME_BLEND ? "the pack's" : + f->opts & SGX_FRAME_SOP2 ? "replace by SOP2" : "replace by MOV", + f->texblock, *(uint32_t *)cpu_at(f, f->texblock, 4, NULL)); + mesa_logi("sgx: state 0x%08x, its program 0x%08x, vertex fetch 0x%08x, vertices 0x%08x", + d0, p0, fb, vb); + for (i = 0; i < (unsigned)(v - vdm); i += 5) + mesa_logi("sgx: VDM +%02x: %08x %08x %08x %08x %08x", i * 4, vdm[i], vdm[i + 1], + vdm[i + 2], vdm[i + 3], vdm[i + 4]); + } + return kick(f, &t, 1.0f, NULL, NULL, handles, nhandles, 0, NULL, done); +} + +int +sgx_frame_upload(struct sgx_frame *f, struct sgx_pixel_program *p) +{ + return upload(f, p); +} + +unsigned +sgx_frame_list_max(const struct sgx_frame *f) +{ + return f->idx_count - f->idx_count % 3; +} + +unsigned +sgx_frame_max_draws(const struct sgx_frame *f) +{ + return f->max_draws; +} + +/* The layout's words of a draw's state: the vertex's size in words + * (16, bits 31:24), the TA's colours (16: bit 11 the base, 10 the offset + * colour -- iOS's es1 e00, e20), three bits each of the other varyings, 111 + * for four components (19), a bit each of those kept as F16 (20) */ +static void +layout_words(uint32_t *full, const struct sgx_frame_layout *l) +{ + unsigned ng = l->nvaryings - l->ncolours; + + full[16] = (4 + 4 * l->nvaryings) << 24 | (full[16] & 0x00fff3ff) | + (l->ncolours > 0 ? 1u << 11 : 0) | (l->ncolours > 1 ? 1u << 10 : 0); + full[19] = 0; + for (unsigned i = 0; i < ng; i++) + full[19] |= 7u << 3 * i; + full[20] = (~l->f32 >> l->ncolours) & ((1u << ng) - 1); +} + +/* SGX_STATE=word:mask[,word:mask...] flips bits of every draw's state + * words, to find what they do */ +static void +state_xor(uint32_t *full) +{ + static uint32_t mask[21]; + static int parsed; + + if (!parsed) { + const char *s = getenv("SGX_STATE"); + + parsed = 1; + while (s && *s) { + char *e; + unsigned w = strtoul(s, &e, 0); + + if (*e != ':' || w >= 21) + break; + mask[w] ^= strtoul(e + 1, &e, 0); + s = *e == ',' ? e + 1 : e; + } + } + for (unsigned i = 0; i < 21; i++) + full[i] ^= mask[i]; +} + +/* n words of secondary attributes into the render's memory, the nmem + * words of uniforms in memory after them (M32; sa word slot their address + * less 4: VLDST adds 4), and their loader after that: the loader's address + * (*rows its data rows), 0 if there is no room */ +static uint32_t +arena_uniforms(struct sgx_frame *f, const uint32_t *words, unsigned n, unsigned nmem, + unsigned slot, unsigned *rows) +{ + uint32_t loader[UNIFORM_LOADER_MAX], va, at = UNIFORM_LOADER_AT(n + nmem); + uint8_t *p = n <= 128 && nmem <= SGX_UBUF_MAX && (!nmem || slot < n) ? + arena_alloc(f, at + sizeof(loader), 16, &va) : NULL; + + if (!p) + return 0; + *rows = uniform_loader(f, va, n, loader); + memcpy(p, words, (n + nmem) * 4); + if (nmem) + ((uint32_t *)p)[slot] = va + 4 * n - 4; + memcpy(p + at, loader, sizeof(loader)); + return va + at; +} + +/* A pixel program's PDS program with its texture lookups (M35), the + * draw's: its data -- the program to start, then the inputs' iterates' + * control words (as upload() has them), then each lookup's control word + * and the texture's state words (from the draw's sa words) -- and the + * DOUTs, into the render's memory. Its address (*rows its data rows), 0 + * if there is no room. */ +static uint32_t +fetch_pds(struct sgx_frame *f, const struct sgx_pixel_program *p, const uint32_t *sa, + unsigned *rows) +{ + uint32_t pds[64], *dst, va; + unsigned n = 0, data, ctrl[SGX_FRAME_MAX_FETCH], state[SGX_FRAME_MAX_FETCH]; + + if (p->nfetch > SGX_FRAME_MAX_FETCH || p->ninputs > SGX_FRAME_MAX_VARYINGS) + return 0; + pds[n++] = doutu(f, p->code_va); + pds[n++] = (p->ninputs ? ITER_TEMPS : 2) | PDS_FLAGS_FETCH | p->branches; + pds[n++] = 0; + for (unsigned i = 0; i < p->ninputs; i++) + pds[n++] = iterate_control(p, i); + for (unsigned k = 0; k < p->nfetch; k++) { + ctrl[k] = n; + pds[n++] = (p->fetch_proj >> k & 1 ? FETCH_CONTROL_PROJ : FETCH_CONTROL_2D) | + (k == p->nfetch - 1 ? FETCH_LAST : 0) | (p->fetch_src[k] - p->ncolours); + if (n & 1) + pds[n++] = 0; + state[k] = n; + memcpy(pds + n, sa + p->fetch_sa[k], 4 * sizeof(uint32_t)); + /* (M38) the texel F16: state word 3's bit 31, as iOS's s00 */ + if (p->f16) + pds[n + 3] |= 0x80000000u; + n += 4; + } + while (n % 4) + pds[n++] = 0; + data = n; + pds[n++] = PDS_DOUTU_ROW0_ITER; + for (unsigned i = 0; i < p->ninputs; i++) + pds[n++] = pds_iterate(3 + i, iterate_size(p, i)); + /* (an F16 texel: iOS's 07040c52 and the texture DOUT of kind 024) */ + for (unsigned k = 0; k < p->nfetch; k++) { + pds[n++] = pds_iterate(ctrl[k], p->f16 ? 0x52 : FETCH_SIZE_RAW); + pds[n++] = pds_texture(state[k]) | (p->f16 ? 0x020 : 0); + } + pds[n++] = PDS_END; + if (!(dst = (uint32_t *)arena_alloc(f, n * 4, 16, &va))) + return 0; + memcpy(dst, pds, n * 4); + *rows = data / 4; + return va; +} + +/* A draw's whole state for our vertex side, its secondary attributes' + * loader and words into the render's memory */ +static int +draw_state(struct sgx_frame *f, const struct sgx_frame_draw *d, const struct sgx_eot *to, + uint32_t *full) +{ + const struct sgx_frame_layout *l = &d->l; + const struct sgx_pixel_program *pix = d->prog; + bool f32 = !pix && (l->f32 >> l->colour & 1); + + memset(full, 0, STATE_WORDS * 4); + memcpy(full, f->tmpl + f->toff[T_FULL], f->tsize[T_FULL]); + state_size(full, to->w, to->h); + /* ISP state B: the depth compare in bits 24:22, bit 20 set when depth + * is not written */ + full[1] = (full[1] & ~(7u << 22 | 1u << 20 | 1u << 14)) | (uint32_t)(d->st.depth_func & 7) << 22 | + (d->st.depth_write ? 0 : 1u << 20) | (d->st.count ? 1u << 14 : 0); + /* the pass type, bits 27:25 (M46): opaque 0, translucent 1 (the + * template's) */ + if (d->st.opaque) + full[1] &= ~(7u << 25); + full[18] = (full[18] & ~3u) | d->st.cull; + full[2] = (full[2] & ~(0x3ffu << 16)) | d->st.offset; + if (d->st.stencil_on) { + full[3] = d->st.stencil; + full[1] = (full[1] & ~0xffu) | d->st.stencil_ref; + } + /* the viewport: words 9..14, translate and scale for x, y and z */ + if (d->st.viewport) + for (unsigned i = 0; i < 3; i++) { + memcpy(&full[9 + 2 * i], &d->st.translate[i], 4); + memcpy(&full[10 + 2 * i], &d->st.scale[i], 4); + } + if (pix) { + if (!pix->code_va || pix->nsa > 128) + return -EINVAL; + full[6] = pix->pds_rows << 27 | (pix->pds_va >> 4 & 0x07ffffff); + if (pix->nfetch) { + unsigned rows; + uint32_t pds = fetch_pds(f, pix, d->sa, &rows); + + if (!pds) + return -ENOMEM; + full[6] = rows << 27 | (pds >> 4 & 0x07ffffff); + } + full[5] = pixel_word5(pix); + if (pix->nsa) { + unsigned rows; + uint32_t loader = arena_uniforms(f, d->sa, pix->nsa, pix->nubuf, pix->ubuf_sa, &rows); + + if (!loader) + return -ENOMEM; + full[4] = rows << 27 | (loader >> 4 & 0x07ffffff); + } + } else { + if (l->colour >= l->nvaryings) + return -EINVAL; + full[6] = 1u << 27 | (iter_pds_at(f, l->colour, f32) >> 4 & 0x07ffffff); + } + layout_words(full, l); + /* flat shading (M37): the provoking vertex (iOS's es1 e01: 3) */ + full[18] = (full[18] & ~(3u << 17)) | (uint32_t)d->st.flat << 17; + state_xor(full); + if (f->debug_state) { + fprintf(stderr, "sgx: state"); + for (unsigned i = 0; i < 21; i++) + fprintf(stderr, " %u:%08x", i, full[i]); + fprintf(stderr, "\n"); + } + return 0; +} + +/* the same state words a draw would write as the one before it: its + * pixel program, secondary attributes (uniforms, textures), layout and the + * ISP's state (M25: SDL's tiles, a texture atlas's, come in runs) */ +static bool +same_state(const struct sgx_frame_draw *a, const struct sgx_frame_draw *b) +{ + if (!a->prog != !b->prog || a->vs != b->vs || a->l.nvaryings != b->l.nvaryings || + a->l.f32 != b->l.f32 || a->l.colour != b->l.colour || a->l.ncolours != b->l.ncolours) + return false; + if (a->prog && (a->prog->code_va != b->prog->code_va || a->prog->pds_va != b->prog->pds_va || + a->prog->nsa != b->prog->nsa || + !sgx_words_equal(a->sa, b->sa, a->prog->nsa))) + return false; + return sgx_frame_state_equal(&a->st, &b->st); +} + +int +sgx_frame_render(struct sgx_frame *f, const struct sgx_frame_target *t, + const struct sgx_frame_draw *draws, unsigned n, const uint32_t *handles, + unsigned nhandles, float depth_clear, const struct sgx_frame_zls *zls, + struct sgx_bo *vis, struct sgx_fence *done) +{ + uint32_t full[32], prog[16], bg[4], eot, *v = f->vdmbuf, state_at = 0, ub_at = 0, vdm; + unsigned total = 0, ub_rows = 0; + struct own own, *o = own_copies(f) ? &own : NULL; + struct sgx_eot to; + int ret; + + if (!sgx_frame_can_render(f, t) || !n || n > f->max_draws || + f->tsize[T_FULL] > STATE_WORDS * 4 || f->tsize[T_FULLPROG] > (int)sizeof(prog) || + nhandles > SGX_FRAME_MAX_HANDLES) + return -EINVAL; + arena_release(f); + if (f->queued[f->nqueued % MAX_QUEUED]) { + sgx_trace_mark("render queue full: wait"); + sgx_fence_wait(f->queued[f->nqueued % MAX_QUEUED], OS_TIMEOUT_INFINITE); + } + if ((ret = begin_render(f, t, &to, &eot, bg, o))) + goto out; + + ret = -ENOMEM; + for (unsigned k = 0; k < n; k++) { + const struct sgx_frame_draw *d = &draws[k]; + uint32_t idx_va, count, vb = 0, fetch, words[4 * (SGX_VS_MAX_ATTRIBS + 1) + 32]; + unsigned nwords, rows; + + count = d->vs ? d->count : d->nverts; + if (!count || count % 3 || d->l.nvaryings > SGX_FRAME_MAX_VARYINGS || + (d->prog && d->l.nvaryings != d->prog->nvaryings) || + (d->vs && (!d->vs->code_va || d->vs->nvaryings != d->l.nvaryings)) || + (!d->indices && !d->idx_va && count > sgx_frame_list_max(f))) { + ret = -EINVAL; + goto out; + } + /* the vertices: the draw module's, or a vertex shader's the CPU made + * one stream, into the render's memory (M26: else the fetch reads + * them where they are) */ + if (d->vs && d->vdata_va) { + vb = d->vdata_va; /* (M42: written there, by the caller) */ + } else if (!d->vs || d->vdata) { + unsigned size = d->vs ? d->nverts * d->stride : + d->nverts * sgx_frame_vertex_floats(&d->l) * sizeof(float); + + if (!(vb = arena_put(f, d->vs ? (const void *)d->vdata : d->verts, size, 16))) + goto out; + } + /* the triangles: the draw's indices, or the frame's 0, 1, 2, ... (from + * the draw's vertex 0) */ + idx_va = d->idx_va ? d->idx_va : + d->indices ? arena_put(f, d->indices, 2 * count, 16) : f->idx; + if (!idx_va) + goto out; + /* the state: the last draw's again when it is the same */ + if (!k || !same_state(&draws[k - 1], d)) { + uint8_t *slot; + + if ((ret = draw_state(f, d, &to, full))) + goto out; + ret = -ENOMEM; + if (!(slot = arena_alloc(f, DRAW_PROG + f->tsize[T_FULLPROG], 64, &state_at))) + goto out; + memcpy(prog, f->tmpl + f->toff[T_FULLPROG], f->tsize[T_FULLPROG]); + prog[0] = state_at; + memcpy(slot, full, STATE_WORDS * 4); + memcpy(slot + DRAW_PROG, prog, f->tsize[T_FULLPROG]); + } else { + sgx_stat_same++; + } + /* the vertex side's constants (a vertex shader's uniforms: its loader, + * the words in fours -- the corpus's x00, x02), the state, the draw + * (count, indices), the vertex fetch */ + if (d->vs && d->vs->nuniforms) { + /* (the last draw's again when the same) */ + if (!k || !draws[k - 1].vs || draws[k - 1].vs->nuniforms != d->vs->nuniforms || + draws[k - 1].vs->nubuf != d->vs->nubuf || + !sgx_words_equal(draws[k - 1].vs_sa, d->vs_sa, d->vs->nuniforms + d->vs->nubuf)) { + if (!(ub_at = arena_uniforms(f, d->vs_sa, d->vs->nuniforms, d->vs->nubuf, + d->vs->ubuf_sa, &ub_rows))) + goto out; + } + /* (the data rows in 31:27, as the state's PDS pointers have them) */ + *v++ = vdm4(4, ub_at); + *v++ = ub_rows << 27 | 0x0000e100 | DIV_ROUND_UP(d->vs->nuniforms, 4); + } else { + *v++ = vdm4(4, f->consts0); *v++ = 0x1000e102; + } + *v++ = vdm4(4, state_at + DRAW_PROG); *v++ = 0x12022206; + *v++ = 0x81c00000 | count; *v++ = idx_va; + *v++ = 0x70000000; *v++ = 0x003fffff; + if (d->vs) { + rows = vs_fetch(f, d, vb, words, &nwords); + } else { + nwords = fetch_program(f, words, d->l.nvaryings, vb); + rows = 0; + } + assert(nwords <= ARRAY_SIZE(words)); + if (!(fetch = arena_put(f, words, nwords * 4, 16))) + goto out; + *v++ = vdm4(vdm_fetch_tag(d->vs ? d->vs->nvaryings : d->l.nvaryings), fetch); + *v++ = d->vs ? vs_fetch_word(d->vs, rows) : vdm_fetch_word(d->l.nvaryings); + if (f->debug) { + char line[512]; + unsigned m = 0; + + for (unsigned i = 0; i < nwords && m < sizeof(line) - 10; i++) + m += snprintf(line + m, sizeof(line) - m, " %08x", words[i]); + mesa_logi("sgx: draw %u: %u vertices, %u varyings, ISP B %08x, state 4 %08x " + "5 %08x 6 %08x, %s; fetch at 0x%08x:%s", k, count, d->l.nvaryings, + full[1], full[4], full[5], full[6], + d->prog ? "compiled pixels" : "iterated colour", fetch, line); + } + total += count; + } + /* the stream's end; its terminate program the render's copy */ + for (unsigned i = 0; i < f->ntail; i++) + *v++ = o && f->tail[i] >> 28 == 6 && (f->tail[i] & 0x0fffffff) << 4 == f->term - 0x10 ? + vdm4(6, o->term) : f->tail[i]; + /* the stream, in the render's memory (the VDM reads ahead: clear of + * its end by 512 bytes, sgx2d, M6) */ + { + uint8_t *p = arena_alloc(f, (v - f->vdmbuf) * 4 + 512, 64, &vdm); + + if (!p) + goto out; + memcpy(p, f->vdmbuf, (v - f->vdmbuf) * 4); + } + + if (f->debug) + mesa_logi("sgx: a render of %u draws, %u vertices, into %ux%u %s at 0x%08x (end of tile " + "0x%08x, PBE 0x%08x), its own memory %u chunks%s", n, total, to.w, to.h, + util_format_short_name(t->res->base.format), to.va, eot, to.pbe, f->arena.n, + o ? "" : " (the frame's words: after the last render)"); + ret = kick(f, t, depth_clear, zls, vis, handles, nhandles, vdm, o, done); + if (!ret) { + sgx_fence_reference(&f->queued[f->nqueued++ % MAX_QUEUED], done); + for (unsigned i = 0; i < f->arena.n; i++) + sgx_bo_set_busy(f->arena.bo[i], done); + } +out: + arena_release(f); + return ret; +} diff --git a/src/gallium/drivers/sgx/sgx_frame.h b/src/gallium/drivers/sgx/sgx_frame.h new file mode 100644 index 00000000000..d9a97aad874 --- /dev/null +++ b/src/gallium/drivers/sgx/sgx_frame.h @@ -0,0 +1,361 @@ +/* + * Copyright 2026 Project Cascadia + * SPDX-License-Identifier: MIT + * + * The template frame (docs/research/p105-mesa.md, M12): until the driver + * builds renders of its own, it borrows sgx2d's pack (tools/sgx/rpack.py) + * -- iOS's render target data for the full screen, the state blocks and + * USSE programs of a textured quad. A clear is the pack's quad as it is + * (texel x colour with a white texture). A draw has a vertex side of our + * own (M13b: vertex fetch, vertex program, the state words that describe + * the varyings) and iOS's pixel side for gl_FragColor = v (M13a). + */ +#ifndef SGX_FRAME_H +#define SGX_FRAME_H + +#include "util/format/u_formats.h" +#include +#include + +/* (M43) the constant buffers a stage may have: 0 the uniforms, 1..15 + * uniform buffers */ +#define SGX_FRAME_MAX_UBOS 16 + +struct sgx_device; +struct sgx_fence; +struct sgx_resource; + +struct sgx_frame; + +/* SGX_FRAME=a,b,...: pieces of the frame swapped for the pack's, or moved, + * to find on the device which one is wrong (docs/research/p105-mesa.md, + * M12; mesa/frame-bisect runs them all) */ +enum { + SGX_FRAME_FB = 1 << 0, /* "fb": the pack's end of tile and background (the screen) */ + SGX_FRAME_BLEND = 1 << 1, /* "blend": the pack's pixel program, texel x colour blended */ + SGX_FRAME_SCREEN = 1 << 2, /* "screen": ours, aimed at the framebuffer, not the target */ + SGX_FRAME_CODEBO = 1 << 3, /* "codebo": our programs in a buffer of their own */ + SGX_FRAME_SOP2 = 1 << 4, /* "sop2": replace by SOP2 (cmod1, amod1), not MOV */ + SGX_FRAME_ALIGN = 1 << 5, /* "align": render targets at 1 MiB-aligned addresses */ + SGX_FRAME_PACKPIX = 1 << 6, /* "packpixel": draws through the pack's pixel side too + (and its vertex side, which that needs) */ + SGX_FRAME_PACKVTX = 1 << 7, /* "packvertex": draws through the pack's vertex side */ + SGX_FRAME_PACKRT = 1 << 8, /* "packrt": the pack's render target data (its size only) */ + SGX_FRAME_PACK = 1 << 9, /* "pack": the pack's buffers, at its addresses, as before + M17 (one process at a time); fb, blend, packpixel and + packrt need it */ + SGX_FRAME_BUILT = 1 << 10, /* "built": the frame built on a kernel before UAPI 3 too, + with the pack's parameter buffer */ +}; +unsigned sgx_frame_options(void); + +/* Loads the pack in packdir into buffers at the GPU addresses it was built + * for; NULL (and a message) if there is none or the addresses are taken. */ +struct sgx_frame *sgx_frame_create(struct sgx_device *dev, const char *packdir); +void sgx_frame_destroy(struct sgx_frame *f); + +/* A render's target: a level and a layer (a cube map's face) of a + * resource (M29), and the render's area from its top left when not all of + * it (w, h; 0: the level's) -- a framebuffer whose attachments differ in + * size renders over what they have in common (M43) */ +struct sgx_frame_target { + struct sgx_resource *res; + unsigned level, layer; + unsigned w, h; +}; + +/* Whether a render through the frame can fill this surface: B8G8R8A8 or + * B8G8R8X8, up to 4096 x 4096 (M10: the render target data for each size + * are ours, sgx_rt.c), any level or face of a 2D texture or cube map. */ +bool sgx_frame_can_render(struct sgx_frame *f, const struct sgx_frame_target *t); + + +/* (M43) What a render target's tile holds for each pixel: the program's + * colour as RGBA bytes (o0); four half floats (o0, o1: R G, B A); two half + * floats (o0: R G); an F32 (o0: R); two F32 (o0, o1: R G) */ +enum sgx_rt_kind { SGX_RT_UNORM8, SGX_RT_F16X4, SGX_RT_F16X2, SGX_RT_F32, SGX_RT_F32X2 }; +enum sgx_rt_kind sgx_frame_rt_kind(enum pipe_format format); + +/* whether the tile holds 64 bits a pixel (o0 and o1) */ +static inline bool +sgx_rt_kind_64(enum sgx_rt_kind k) +{ + return k == SGX_RT_F16X4 || k == SGX_RT_F32X2; +} + +/* The whole of rt set to rgba, on the GPU; done is signalled when it is. + * One render at a time: the caller serialises (sgx_screen.frame_lock). */ +int sgx_frame_clear(struct sgx_frame *f, struct sgx_resource *rt, const float rgba[4], + struct sgx_fence *done); + +/* A vertex as a draw hands it over (M13b): the position, x y z w -- x and y + * in [-1, 1] over the whole target, -1 being its first row and column (z + * and w are not used yet: 0 and 1) -- then nvaryings varyings of four + * floats each. Each is kept for the pixels as F16, or as F32 if its bit in + * f32 is set; varying colour is the pixel's colour, interpolated between + * the vertices and packed to 8 bits a channel, the way iOS's GL driver + * colours gl_FragColor = v (the corpus's v00_vec4 and v07_highp). */ +#define SGX_FRAME_MAX_VARYINGS 8 +/* the iterate source of the pixel's position, window coordinates in F32 + * (iOS's gl_FragCoord: corpus v08, control word 0x0fc0d00f) */ +#define SGX_ITERATE_POSITION 13 +/* texture lookups the PDS makes for a pixel program (M35) */ +#define SGX_FRAME_MAX_FETCH 4 + +/* (M37) the first ncolours varyings (two at most) are the TA's colours: + * flat-shaded ones (iOS's es1 e01: the base colour, TSP varying 10, and + * the offset colour, 11 -- the only ones the TSP shades flat), each after + * the position in the vertex as the others are */ +struct sgx_frame_layout { + unsigned nvaryings; + unsigned f32; + unsigned colour; + unsigned ncolours; +}; + +static inline unsigned +sgx_frame_vertex_floats(const struct sgx_frame_layout *l) +{ + return 4 * (1 + l->nvaryings); +} + +/* A pixel program of our own (M13c, sgx_compiler.c): its USSE code, the + * temporaries it uses, the varyings it reads -- F32 vec4s the PDS iterates + * into pa0.., varying i of the layout into pa4i -- and how many words of + * secondary attributes it reads from sa0.. (uniforms, texture states: the + * draw hands them over). The frame puts the code and its PDS program in + * GPU memory at the first draw, once, and keeps where in code_va, pds_va. */ +/* the uniform words a program may have in memory (M32): constant buffer + * 0's, as the screen says them -- a vertex shader's 265 vec4s (M43) */ +#define SGX_UBUF_MAX (265 * 4) + +struct sgx_pixel_program { + uint64_t *code; + unsigned ncode; + unsigned ntemps; + unsigned ninputs; + /* what the PDS iterates for each input: varying n of the layout, or + * SGX_ITERATE_POSITION (gl_FragCoord); nvaryings of the layout's */ + uint8_t iter_src[SGX_FRAME_MAX_VARYINGS]; + unsigned nvaryings; + /* (M37) the layout's first ncolours varyings are the TA's colours: an + * input iterating one of them (iter_src < ncolours) takes one register, + * its bytes as o0's, after the inputs of four (the inputs' last) */ + unsigned ncolours; + unsigned nsa; + /* uniform words in memory after the nsa (M32): the draw's words go on + * with them, and sa word ubuf_sa has their address less 4 */ + unsigned nubuf, ubuf_sa; + /* (M43) the uniform buffers it reads (ARB_uniform_buffer_object: bit k + * for buffer k, 1..15), each one's address less 4 in sa word ubo_sa[k] */ + uint16_t ubo_mask; + uint8_t ubo_sa[SGX_FRAME_MAX_UBOS]; + /* lookups the PDS makes before the program runs (M35): texture k's + * texel, as it is (four bytes), into the primary attribute after the + * inputs' (pa4 ninputs + k), the coordinates varying fetch_src[k]'s x + * and y, the texture's four state words sa words fetch_sa[k].. (the + * draw's) -- the PDS program then the draw's own */ + unsigned nfetch; + uint8_t fetch_src[SGX_FRAME_MAX_FETCH]; + uint8_t fetch_sa[SGX_FRAME_MAX_FETCH]; + uint8_t fetch_proj; /* (M39) lookup k projective: bit k (iOS's s08) */ + uint32_t code_va, pds_va; + unsigned pds_rows; + bool branches; /* its pixels each on its own: the code branches, not + * alike for all (M20, M33) */ + /* (M38) its inputs iterated and its lookups' texels fetched as F16, two + * registers each (iOS's SDL sprite, corpus s00) */ + bool f16; + /* (M46) of an F16 program's inputs, those iterated as F32 all the same + * (bit i, four registers): the coordinates of lookups the program makes + * itself, worked out in F32 */ + uint8_t in_f32; +}; + +/* Triangles into rt, over what it holds (each tile starts as the target's + * pixels): nverts vertices laid out as l says, three a triangle, as many + * as sgx_frame_max_vertices() a render. With prog, the pixels are its + * (l has its inputs, all F32), with sa[0..prog->nsa) in sa0..; without, + * they are l's colour varying. handles: buffers the render reads besides + * the frame's and rt (textures, at most SGX_FRAME_MAX_HANDLES), for the + * kernel to keep. */ +#define SGX_FRAME_MAX_HANDLES 256 +/* What the ISP does with a draw's pixels (M14): the depth test (a + * pipe_compare_func; ALWAYS when GL's test is off) and whether it writes + * depth. */ +struct sgx_frame_state { + uint8_t depth_func; + bool depth_write; + /* the TA's viewport (M18): scale and translate, x y z, as gallium's; + * else the target's whole, depth 0..1 (the draw module's vertices) */ + bool viewport; + float scale[3], translate[3]; + uint8_t cull; /* SGX_CULL_* */ + /* the stencil test (M23): ISP state B's word (state word 3; else the + * template's, ALWAYS and KEEP) and the reference (state word 1's low + * byte) */ + bool stencil_on; + uint32_t stencil; + uint8_t stencil_ref; + /* (M37) flat shading of the layout's colours: state word 18 bits 18:17 + * as iOS's (es1 e01: 3) -- the TSP takes a triangle's last vertex's + * colours with any value (gldesk: the first vertex's by turning the + * triangle round, sgx_draw.c) -- 0 when none */ + uint8_t flat; + /* (M37) polygon offset, the ISP's: state word 2 bits 25:21 the slope's + * factor, 20:16 the units, each a signed 5-bit integer (iOS's es1 e19, + * gloffset --probe); a unit is 32 of 24-bit depth's at depths 0.5..1 + * (a power of two smaller below: floating point) */ + uint32_t offset; + /* (M37) the samples that pass counted: an occlusion query's draw (ISP + * state A bit 14, iOS's m29; bit 18 would count only whether any did) */ + bool count; + /* (M46) the ISP's opaque pass type (state word 1 bits 27:25 0, as + * iOS's opaque draws have it): hidden surface removal, only the pixels + * seen shaded -- for a pixel program that reads nothing of the tile's + * colour. Else translucent (bit 25, sgx2d's), shaded in order. */ + bool opaque; +}; +#define SGX_FLAT_LAST 3 +/* the TA's culling (state word 18, bits 1:0): the triangles clockwise or + * anticlockwise in the target, row 0 at the top (M18) */ +#define SGX_CULL_NONE 0 +#define SGX_CULL_CW 1 +#define SGX_CULL_CCW 2 + +int sgx_frame_draw(struct sgx_frame *f, struct sgx_resource *rt, + const struct sgx_frame_layout *l, const float *verts, unsigned nverts, + struct sgx_pixel_program *prog, const uint32_t *sa, + const uint32_t *handles, unsigned nhandles, + const struct sgx_frame_state *st, struct sgx_fence *done); + +/* waits for the last render through the frame */ +void sgx_frame_finish(struct sgx_frame *f); + +/* One draw of a render (M14: draws are gathered into renders): vertices + * laid out as l says, the pixels prog's (uploaded with sgx_frame_upload, + * reading sa) or, without, l's colour iterated; what the ISP does. */ +struct sgx_vs; + +/* With vs (M18: the vertex shader on the GPU), l is the varyings it hands + * the pixels, vs_sa its uniforms, and its vertex fetch reads attribute n of + * vertex i at base[n] + i x stride (M26: one stride for all) -- addresses + * in the application's buffers, or, with vdata (nverts vertices the CPU + * made one stream), offsets into a vertex there -- or with vdata_va, the + * stream already in GPU memory there (M42: the caller lists its buffer + * among the render's). It draws count + * vertices: indices[0..count) from vertex 0, or 0, 1, 2, ... without + * (count at most sgx_frame_list_max()). */ +struct sgx_frame_draw { + struct sgx_frame_layout l; + const float *verts; + unsigned nverts; + const struct sgx_pixel_program *prog; + const uint32_t *sa; + struct sgx_frame_state st; + struct sgx_vs *vs; + const uint32_t *vs_sa; + const uint8_t *vdata; + uint32_t vdata_va; + const uint32_t *base; + unsigned stride, count; + const uint16_t *indices; + uint32_t idx_va; /* (M46) the indices at this address instead */ +}; +#define SGX_FRAME_MAX_DRAWS 2048 +unsigned sgx_frame_max_draws(const struct sgx_frame *f); + +/* the same ISP state and viewport (field by field: padding) */ +static inline bool +sgx_frame_state_equal(const struct sgx_frame_state *x, const struct sgx_frame_state *y) +{ + return x->depth_func == y->depth_func && x->depth_write == y->depth_write && + x->viewport == y->viewport && x->cull == y->cull && + x->stencil_on == y->stencil_on && x->stencil == y->stencil && + x->stencil_ref == y->stencil_ref && x->flat == y->flat && x->offset == y->offset && + x->count == y->count && x->opaque == y->opaque && + (!x->viewport || (x->scale[0] == y->scale[0] && x->scale[1] == y->scale[1] && + x->scale[2] == y->scale[2] && x->translate[0] == y->translate[0] && + x->translate[1] == y->translate[1] && + x->translate[2] == y->translate[2])); +} + +/* the most vertices a draw takes without indices */ +unsigned sgx_frame_list_max(const struct sgx_frame *f); + +/* n 32-bit words the same (musl's memcmp goes a byte at a time) */ +static inline bool +sgx_words_equal(const uint32_t *a, const uint32_t *b, unsigned n) +{ + for (unsigned i = 0; i < n; i++) + if (a[i] != b[i]) + return false; + return true; +} +/* the vertices and indices a render's draws take, all told, in bytes (its + * own memory grows as they need: a bound, not a size) */ +#define SGX_FRAME_MAX_BYTES (8u << 20) + +/* the program's code and PDS into GPU memory, once (sgx_frame_draw does it + * itself) */ +int sgx_frame_upload(struct sgx_frame *f, struct sgx_pixel_program *p); +/* a vertex shader's code, once */ +int sgx_frame_upload_vs(struct sgx_frame *f, struct sgx_vs *vs); +/* a program no render to be submitted from now on runs: its places free + * again once the renders already submitted are done (and it is to be + * uploaded again if drawn after all) */ +void sgx_frame_retire(struct sgx_frame *f, struct sgx_pixel_program *p); +void sgx_frame_retire_vs(struct sgx_frame *f, struct sgx_vs *vs); +/* How the ISP keeps depth and stencil in memory: ZLSCTL's formats (bits + * 25:24 stored, 22:21 loaded) */ +enum sgx_zls_format { + SGX_ZLS_F32 = 0, /* F32 depth alone, 4 bytes a pixel */ + SGX_ZLS_D24S8 = 1, /* 24-bit depth, the stencil in the top byte */ + /* (M43) F32 depth and the stencil, 5 bytes a pixel: the stencil, then + * the depth as a key that sorts as an integer, most significant byte + * first, in a stream each 16 bytes of which are stored reversed + * (sgx_resource.c) */ + SGX_ZLS_F32S8 = 3, +}; + +static inline enum sgx_zls_format +sgx_zls_format(enum pipe_format f) +{ + return f == PIPE_FORMAT_Z32_FLOAT_S8X24_UINT ? SGX_ZLS_F32S8 : + f == PIPE_FORMAT_Z24_UNORM_S8_UINT ? SGX_ZLS_D24S8 : SGX_ZLS_F32; +} + +/* The depth buffer a render loads its tiles' depth from, stores it to, or + * both (M24, the ISP's z load/store): 32 x 32 tiles, 4 KiB each (5 KiB + * with SGX_ZLS_F32S8), rows of tiles an even number long + * (sgx_frame_zls_size()) */ +struct sgx_frame_zls { + struct sgx_bo *bo; + unsigned w; /* the depth buffer's width, pixels */ + bool load; /* else the tiles start at depth_clear */ + bool store; + bool stencil; /* stencil too */ + enum sgx_zls_format format; +}; +uint32_t sgx_frame_zls_size(unsigned w, unsigned h, enum sgx_zls_format format); + +/* n draws (at most SGX_FRAME_MAX_DRAWS) in one render into t, in order, + * over what it holds: the depth test holds across them, from depth_clear + * -- or from zls, when it loads. zls NULL: no depth buffer. What the + * render reads besides rt and the frame's buffers -- its stream, the + * draws' state, vertices and indices -- goes in memory of its own (M27): + * it need not wait for the renders before it. */ +/* (M37) vis: where the ISP counts the samples that pass of the draws whose + * state says so (an occlusion query's), or NULL -- a word for each core, + * SGX_VIS_CORE_STRIDE apart, the buffer zeroed beforehand */ +#define SGX_VIS_CORE_STRIDE 0x640 +#define SGX_VIS_SIZE (2 * SGX_VIS_CORE_STRIDE + 4) /* up to three cores (the A6's) */ +int sgx_frame_render(struct sgx_frame *f, const struct sgx_frame_target *t, + const struct sgx_frame_draw *draws, unsigned n, const uint32_t *handles, + unsigned nhandles, float depth_clear, const struct sgx_frame_zls *zls, + struct sgx_bo *vis, struct sgx_fence *done); +/* the most vertices a draw module draw (l) takes: sgx_frame_draw's, and a + * gathered render's without indices */ +unsigned sgx_frame_max_vertices(struct sgx_frame *f, const struct sgx_frame_layout *l); + +#endif diff --git a/src/gallium/drivers/sgx/sgx_resource.c b/src/gallium/drivers/sgx/sgx_resource.c new file mode 100644 index 00000000000..a7df01e7127 --- /dev/null +++ b/src/gallium/drivers/sgx/sgx_resource.c @@ -0,0 +1,1441 @@ +/* + * Copyright 2026 Project Cascadia + * SPDX-License-Identifier: MIT + * + * Resources: one buffer object each, linear, mapped write-combined on the + * CPU side; maps wait for the renders that use the buffer. + */ +#include "sgx_resource.h" + +#include +#include +#include +#include +#include +#include + +#include "drm-uapi/apple_sgx_drm.h" +#include "drm-uapi/drm_fourcc.h" +#include "frontend/winsys_handle.h" +#include "util/format/u_format.h" +#include "util/half_float.h" +#include "util/log.h" +#include "util/u_inlines.h" +#include "util/u_math.h" +#include "util/u_memory.h" +#include "util/os_time.h" + +#include "sgx_context.h" +#include "sgx_device.h" +#include "sgx_draw.h" +#include "sgx_frame.h" +#include "sgx_screen.h" + +/* SGX_FRAME=align: a render target at a 1 MiB-aligned address of our own + * choosing (0xc0000000 up), to tell whether the pixel back end or the + * background object want more than a page's alignment */ +static struct sgx_bo * +aligned_bo(struct sgx_device *dev, uint32_t size) +{ + for (uint32_t va = 0xc0000000u; va + size <= 0xe0000000u; va += 1u << 20) { + struct sgx_bo *bo = sgx_bo_create(dev, size, APPLE_SGX_BO_FIXED_VA, va); + + if (bo || errno != EEXIST) + return bo; + } + return NULL; +} + +static struct pipe_resource * +sgx_resource_create(struct pipe_screen *pscreen, const struct pipe_resource *templ) +{ + struct sgx_screen *screen = sgx_screen(pscreen); + struct sgx_resource *res = CALLOC_STRUCT(sgx_resource); + uint32_t size = 0; + + if (!res) + return NULL; + res->base = *templ; + res->base.screen = pscreen; + pipe_reference_init(&res->base.reference, 1); + + if (templ->target == PIPE_BUFFER) { + size = templ->width0; + } else { + for (unsigned l = 0; l <= templ->last_level; l++) { + unsigned w = u_minify(templ->width0, l), h = u_minify(templ->height0, l); + unsigned layers = templ->target == PIPE_TEXTURE_3D ? + u_minify(templ->depth0, l) : templ->array_size; + + res->stride[l] = align(util_format_get_stride(templ->format, w), 64); + res->layer_size[l] = res->stride[l] * util_format_get_nblocksy(templ->format, h); + res->offset[l] = align(size, 64); + size = res->offset[l] + res->layer_size[l] * layers; + } + } + + /* a buffer: CPU memory, which maps read and write without waiting + * (M25); the GPU's copy is made when a draw reads it (M26: + * sgx_buffer_bo). 64-byte aligned: GL's MIN_MAP_BUFFER_ALIGNMENT + * (musl's malloc gives 16; piglit's map_invalidate cases pass or fail + * with where the heap is) */ + if (templ->target == PIPE_BUFFER) { + simple_mtx_init(&res->dirty_lock, mtx_plain); + if (!(res->data = align_malloc(MAX2(size, 1), 64))) { + FREE(res); + return NULL; + } + return &res->base; + } + size = align(MAX2(size, 1), 4096); + if ((templ->bind & PIPE_BIND_RENDER_TARGET) && templ->target != PIPE_BUFFER && + (sgx_frame_options() & SGX_FRAME_ALIGN)) + res->bo = aligned_bo(&screen->dev, size); + /* (M45) a texture or a target of this process's alone from the cache, + * as buffers' GPU copies are (M26): glamor makes one for every pixmap, + * and a new buffer is the kernel's pages cleared and cleaned out of the + * CPU's cache -- 190 of them a terminal opened, 15% of Xorg's time. Its + * content is no one's (GL's new texture is undefined). Not one to be + * shared (sgx_resource_get_handle takes it out of the cache's hands + * later), nor depth: its tiles are buffers of their own */ + if (!res->bo && + !(templ->bind & (PIPE_BIND_SHARED | PIPE_BIND_SCANOUT | PIPE_BIND_DISPLAY_TARGET)) && + !util_format_is_depth_or_stencil(templ->format)) + res->bo = sgx_bo_cache_get(&screen->dev, size); + /* one the screen may show (M49), where the kernel has the flag: it makes + * the buffer contiguous when it is the screen's size, and KMS points the + * display at it instead of copying it (DRI3's back buffers, GBM's + * scanout buffers) */ + if (!res->bo) + res->bo = sgx_bo_create(&screen->dev, size, + templ->bind & PIPE_BIND_SCANOUT ? + screen->dev.bo_flags & APPLE_SGX_BO_SCANOUT : 0, 0); + if (!res->bo) { + FREE(res); + return NULL; + } + return &res->base; +} + +static void +sgx_resource_destroy(struct pipe_screen *pscreen, struct pipe_resource *prsc) +{ + struct sgx_resource *res = sgx_resource(prsc); + + /* a render still using it holds the kernel's reference */ + sgx_bo_destroy(res->tw); + FREE(res->tw_cpu); + for (unsigned i = 0; i < res->nzls; i++) + sgx_bo_destroy(res->zls[i].bo); + FREE(res->zls); + sgx_bo_destroy(res->bo); + if (res->data) + simple_mtx_destroy(&res->dirty_lock); + align_free(res->data); + FREE(res); +} + +static bool +sgx_resource_get_handle(struct pipe_screen *pscreen, struct pipe_context *pctx, + struct pipe_resource *prsc, struct winsys_handle *handle, + unsigned usage) +{ + struct sgx_resource *res = sgx_resource(prsc); + int fd; + + if (prsc->target == PIPE_BUFFER || !res->bo) + return false; + /* (M45) another process's too from now on: closed when it goes, not + * handed to another resource by the cache */ + res->bo->cached = false; + handle->stride = res->stride[0]; + handle->offset = 0; + handle->modifier = DRM_FORMAT_MOD_LINEAR; + switch (handle->type) { + case WINSYS_HANDLE_TYPE_KMS: + handle->handle = res->bo->handle; + res->external = true; + return true; + case WINSYS_HANDLE_TYPE_FD: + if (drmPrimeHandleToFD(res->bo->dev->fd, res->bo->handle, DRM_CLOEXEC | DRM_RDWR, &fd)) + return false; + handle->handle = fd; + res->external = true; + return true; + default: + return false; + } +} + +/* A dma-buf (or a handle on this device) as a texture or a render target: + * linear, its stride and offset as given. */ +static struct pipe_resource * +sgx_resource_from_handle(struct pipe_screen *pscreen, const struct pipe_resource *templ, + struct winsys_handle *whandle, unsigned usage) +{ + struct sgx_screen *screen = sgx_screen(pscreen); + struct sgx_device *dev = &screen->dev; + struct sgx_resource *res; + uint32_t handle; + + if ((templ->target != PIPE_TEXTURE_2D && templ->target != PIPE_TEXTURE_RECT) || + templ->last_level || templ->array_size > 1 || whandle->plane || + (whandle->modifier != DRM_FORMAT_MOD_INVALID && + whandle->modifier != DRM_FORMAT_MOD_LINEAR)) + return NULL; + switch (whandle->type) { + case WINSYS_HANDLE_TYPE_FD: + if (drmPrimeFDToHandle(dev->fd, whandle->handle, &handle)) + return NULL; + break; + case WINSYS_HANDLE_TYPE_KMS: + handle = whandle->handle; + break; + default: + return NULL; + } + if (!(res = CALLOC_STRUCT(sgx_resource))) + return NULL; + res->base = *templ; + res->base.screen = pscreen; + pipe_reference_init(&res->base.reference, 1); + res->stride[0] = whandle->stride; + res->offset[0] = whandle->offset; + res->layer_size[0] = whandle->stride * util_format_get_nblocksy(templ->format, + templ->height0); + res->external = true; + if (!(res->bo = sgx_bo_import(dev, handle)) || + (uint64_t)res->offset[0] + res->layer_size[0] > res->bo->size) { + sgx_bo_destroy(res->bo); + FREE(res); + return NULL; + } + return &res->base; +} + +/* Morton order, y in the even bits (the layout iOS's GL driver uploads); a + * rectangle is a row (or column) of such squares, the side of the shorter + * edge, one after another (docs/research/p105-gpu.md, M7). By tables + * (M37): x's bits spread to the odd places, y's to the even ones, for the + * square's side -- not a loop and two divisions a texel. */ +struct twiddle { + uint32_t *mx, *my; /* the side's entries each */ + unsigned shift; /* log2 of the side */ + bool wide; /* the squares go along x */ +}; + +static bool +twiddle_init(struct twiddle *t, unsigned w, unsigned h) +{ + unsigned m = MIN2(w, h); + + t->shift = util_logbase2(m); + t->wide = w >= h; + if (!(t->mx = MALLOC(2 * m * sizeof(uint32_t)))) + return false; + t->my = t->mx + m; + for (unsigned v = 0; v < m; v++) { + t->mx[v] = t->my[v] = 0; + for (unsigned b = 0; (1u << b) < m; b++) { + t->mx[v] |= ((v >> b) & 1) << (2 * b + 1); + t->my[v] |= ((v >> b) & 1) << (2 * b); + } + } + return true; +} + +static inline uint32_t +twiddle_at(const struct twiddle *t, unsigned x, unsigned y) +{ + unsigned mask = (1u << t->shift) - 1; + + return ((t->wide ? x : y) >> t->shift << 2 * t->shift) + t->mx[x & mask] + t->my[y & mask]; +} + +/* a row of the texture's content as 8-bit RGBA -- depth as F32 (M37: the + * sampler's F32 format, iOS's m04..m08 read it raw and compare in the + * program; the program makes it d, d, d, 1) */ +static void +unpack_row(enum pipe_format format, const uint8_t *line, unsigned w, uint32_t *row) +{ + if (util_format_is_depth_or_stencil(format)) { + util_format_unpack_z_float(format, (float *)row, line, w); + } else { + /* (sRGB as the bytes are: the program decodes them, or not, as the + * view says) */ + util_format_unpack_rgba_8unorm_rect(util_format_linear(format), (uint8_t *)row, w * 4, + line, 0, w, 1); + } +} + +/* The copy the sampler reads, made again from the linear content: every + * level of every face (a cube map's six, in GL's order), one after another, + * each RGBA8 in Morton order at its own size padded to powers of two -- + * iOS's layout (a 64x64's levels at +0, +0x4000, +0x5000, ..., + * p105-gpu.md's mipmap transfers); a cube map's faces each as far apart as + * a whole chain down to 1 x 1, whatever levels it has, rounded up to 2 KiB + * once level 0 is 512 bytes or more (glmip --probe, RGBA8: 4 x 4 faces 21 + * texels apart, 8 x 8 85, 16 x 16 512, 32 x 32 1536, 64 x 64 5632; Vita3K's + * texture cache has the same rules for the same GPU -- M43: in bytes, as + * one-byte and eight-byte texels' cube maps showed). A 2D texture's size not a power of two is + * padded, the last column and row repeated: the sampler takes the size as + * it is (sgx_resource_texture), the padding is its memory's layout. A cube + * map's is scaled up to one, the nearest texel (GXM's arbitrary cube map, + * type 7, read past the copy here and hung the renders): a direction cannot + * be scaled to a part of a face. + * + * M37: made in cached memory and copied over in one go (Morton order's + * scattered stores into a write-combined map were most of the time); into + * a new buffer from the cache when a render may still read the old one -- + * gathered or running -- the old one left to it (the batch references it), + * not waiting for the GPU to be idle. A texture of one level written in + * boxes of it since (glamor's glyphs, a game's streamed sprites) keeps its + * copy's shadow, tw_cpu: only the box is made again there, and the range of + * the copy it falls in copied over. */ +/* M37: formats the sampler reads as they are in memory -- iOS's corpus + * m10..m19, the words of PS Vita's SceGxmTexture: the base format in word 1 + * bits 28:24, the swizzle in word 3 bits 30:28 (named from the top bits + * down: ABGR is R in the low byte). Their texels are twiddled as they are, + * 1, 2 or 4 bytes; the sampler hands each back as the four bytes an RGBA8 + * texel's are, in the same order (iOS's program for 565 and 4444 is `or o0, + * pa0`). 0: not one of them -- made RGBA8 by util_format. SGX_TEX_NATIVE=0: + * none. */ +static unsigned +native_format(const struct pipe_resource *p, uint32_t *fmt, uint32_t *swizzle) +{ + static int on = -1; + + if (on < 0) + on = !getenv("SGX_TEX_NATIVE") || atoi(getenv("SGX_TEX_NATIVE")); + *fmt = 0x0c; + *swizzle = 0; + if (!on) + return 0; + switch (util_format_linear(p->format)) { + case PIPE_FORMAT_R8G8B8A8_UNORM: *fmt = 0x0c; *swizzle = 0; return 4; /* ABGR */ + case PIPE_FORMAT_B8G8R8A8_UNORM: *fmt = 0x0c; *swizzle = 1; return 4; /* ARGB */ + case PIPE_FORMAT_R8G8B8X8_UNORM: *fmt = 0x0c; *swizzle = 4; return 4; /* 1BGR: iOS's RGB8 */ + case PIPE_FORMAT_B8G8R8X8_UNORM: *fmt = 0x0c; *swizzle = 5; return 4; /* 1RGB */ + case PIPE_FORMAT_B5G6R5_UNORM: *fmt = 0x05; *swizzle = 5; return 2; /* 1RGB: iOS's 565 */ + case PIPE_FORMAT_B4G4R4A4_UNORM: *fmt = 0x02; *swizzle = 1; return 2; /* ARGB */ + case PIPE_FORMAT_B5G5R5A1_UNORM: *fmt = 0x04; *swizzle = 1; return 2; /* ARGB */ + case PIPE_FORMAT_L8_UNORM: *fmt = 0x00; *swizzle = 5; return 1; /* 1RRR: iOS's L8 */ + case PIPE_FORMAT_A8_UNORM: *fmt = 0x00; *swizzle = 6; return 1; /* R000: A8 */ + case PIPE_FORMAT_I8_UNORM: *fmt = 0x00; *swizzle = 3; return 1; /* RRRR: I8 (M43) */ + case PIPE_FORMAT_L8A8_UNORM: *fmt = 0x07; *swizzle = 2; return 2; /* GRRR: LA8 */ + /* (M45) R8, RG8 -- glamor's a8 pixmaps, every mask XFCE's programs + * draw with: RRRR and GRRR, the rest the program's (sgx_resource_swizzle) */ + case PIPE_FORMAT_R8_UNORM: *fmt = 0x00; *swizzle = 3; return 1; + case PIPE_FORMAT_R8G8_UNORM: *fmt = 0x07; *swizzle = 2; return 2; + default: return 0; + } +} + +/* (M45) What the program makes of the sampler's texel for p, as a + * pipe_swizzle each of R G B A, where the sampler's own swizzles cannot give + * GL's: U8 and U8U8 have none with a 1 for alpha and zeros besides (GXM's + * SWIZZLE1 and SWIZZLE2 lists, whose numbers native_format's are) -- R8's X 0 + * 0 1 of RRRR, RG8's X W 0 1 of GRRR. false: the texel as it comes. */ +bool +sgx_resource_swizzle(const struct pipe_resource *p, uint8_t swz[4]) +{ + uint32_t fmt, swizzle; + + if (!native_format(p, &fmt, &swizzle)) + return false; + switch (util_format_linear(p->format)) { + case PIPE_FORMAT_R8_UNORM: + swz[0] = PIPE_SWIZZLE_X, swz[1] = PIPE_SWIZZLE_0, swz[2] = PIPE_SWIZZLE_0; + swz[3] = PIPE_SWIZZLE_1; + return true; + case PIPE_FORMAT_R8G8_UNORM: + swz[0] = PIPE_SWIZZLE_X, swz[1] = PIPE_SWIZZLE_W, swz[2] = PIPE_SWIZZLE_0; + swz[3] = PIPE_SWIZZLE_1; + return true; + default: + return false; + } +} + +/* Whether a format the sampler has not is copied as four half floats + * (GXM's F16F16F16F16, 0x1b, which it filters) instead of RGBA8 (M43): + * floats, signed and wider than 8-bit channels, the packed float and shared + * exponent formats -- ARB_texture_float, EXT_texture_snorm and the rest of + * GL 3.0's. Its texels come back F32 (sgx_blend_key's tex_f16). */ +bool +sgx_resource_copy_f16(const struct pipe_resource *p) +{ + const struct util_format_description *desc = util_format_description(p->format); + uint32_t fmt, swizzle; + + if (!desc || util_format_is_depth_or_stencil(p->format) || + util_format_is_pure_integer(p->format) || util_format_is_compressed(p->format) || + native_format(p, &fmt, &swizzle)) + return false; + if (p->format == PIPE_FORMAT_R11G11B10_FLOAT || p->format == PIPE_FORMAT_R9G9B9E5_FLOAT) + return true; + for (unsigned c = 0; c < desc->nr_channels; c++) + if (desc->channel[c].type == UTIL_FORMAT_TYPE_FLOAT || + desc->channel[c].type == UTIL_FORMAT_TYPE_SIGNED || desc->channel[c].size > 8) + return true; + return false; +} + +/* the texel bytes of res's copy: its own, half floats' or RGBA8's */ +static unsigned +copy_bytes(const struct sgx_resource *res) +{ + uint32_t fmt, swizzle; + unsigned b = native_format(&res->base, &fmt, &swizzle); + + return b ? b : sgx_resource_copy_f16(&res->base) ? 8 : 4; +} + +/* a row of a format the copy holds as half floats: R, G, B, A each */ +static void +unpack_row_f16(enum pipe_format format, const uint8_t *line, unsigned w, uint32_t *row) +{ + float rgba[4 * 64]; + + for (unsigned x = 0; x < w; x += 64) { + unsigned n = MIN2(w - x, 64); + + util_format_unpack_rgba(format, rgba, line + x * util_format_get_blocksize(format), n); + for (unsigned i = 0; i < 4 * n; i++) + ((uint16_t *)row)[4 * x + i] = _mesa_float_to_half(rgba[i]); + } +} + +/* Rows y0..y1, columns x0..x1 of a level of the copy, from the linear + * content: the texels as they are (native, b bytes) or made RGBA8 (row: a + * row's worth of room) */ +static void +copy_level(const struct sgx_resource *res, unsigned level, unsigned face_layer, uint8_t *dst, + unsigned dw, unsigned dh, bool scale, unsigned x0, unsigned y0, unsigned x1, + unsigned y1, uint32_t *row, const struct twiddle *t) +{ + const struct pipe_resource *p = &res->base; + unsigned lw = u_minify(p->width0, level), lh = u_minify(p->height0, level); + const uint8_t *src = (const uint8_t *)res->bo->map + res->offset[level] + + face_layer * res->layer_size[level]; + uint32_t fmt, swizzle; + unsigned native = native_format(p, &fmt, &swizzle); + bool f16 = !native && sgx_resource_copy_f16(p); + unsigned out = native ? native : f16 ? 8 : 4; + /* the columns of content the box reads (padding: the last one) */ + unsigned cx0 = scale ? 0 : MIN2(x0, lw - 1), cx1 = scale ? lw : MAX2(MIN2(x1, lw), cx0 + 1); + unsigned bytes = util_format_get_blocksize(p->format); + + for (unsigned y = y0; y < y1; y++) { + unsigned sy = scale ? (2 * y + 1) * lh / (2 * dh) : MIN2(y, lh - 1); + const uint8_t *line = src + sy * res->stride[level]; + + /* padding: the last column and row repeated (a bilinear lookup at + * the edge reads it) */ +#define SX(x) ((scale ? (2 * (x) + 1) * lw / (2 * dw) : MIN2((x), lw - 1)) - cx0) + /* (the row read in one go: the linear content is mapped + * write-combined, word by word reads of it were slower than the + * unpacking) */ + if (native) + memcpy(row, line + cx0 * bytes, (cx1 - cx0) * bytes); + else if (f16) + unpack_row_f16(p->format, line + cx0 * bytes, cx1 - cx0, row); + else + unpack_row(p->format, line + cx0 * bytes, cx1 - cx0, row); + switch (out) { + case 1: + for (unsigned x = x0; x < x1; x++) + dst[twiddle_at(t, x, y)] = ((const uint8_t *)row)[SX(x)]; + break; + case 2: + for (unsigned x = x0; x < x1; x++) + ((uint16_t *)dst)[twiddle_at(t, x, y)] = ((const uint16_t *)row)[SX(x)]; + break; + case 8: + for (unsigned x = x0; x < x1; x++) + ((uint64_t *)dst)[twiddle_at(t, x, y)] = ((const uint64_t *)row)[SX(x)]; + break; + default: + for (unsigned x = x0; x < x1; x++) + ((uint32_t *)dst)[twiddle_at(t, x, y)] = row[SX(x)]; + break; + } +#undef SX + } +} + +static bool zs_to_linear(struct sgx_resource *res, unsigned level, unsigned layer); + +static bool +copy_texture(struct sgx_context *ctx, struct sgx_resource *res, unsigned first) +{ + struct sgx_screen *screen = sgx_screen(res->base.screen); + struct pipe_resource *p = &res->base; + unsigned w = u_minify(p->width0, first), h = u_minify(p->height0, first); + unsigned tw = util_next_power_of_two(w), th = util_next_power_of_two(h); + unsigned faces = p->target == PIPE_TEXTURE_CUBE ? 6 : 1; + unsigned levels = p->last_level + 1 - first; + unsigned b = copy_bytes(res); + bool scale = faces > 1 && (tw != w || th != h); + bool same = res->tw && res->tw_w == tw && res->tw_h == th && res->tw_levels == levels && + res->tw_first == first; + /* boxes of level 0 alone written since the copy was made */ + bool boxed = same && faces == 1 && levels == 1 && !first && + !util_format_is_compressed(p->format) && res->tw_writes && + res->tw_writes == res->seq - res->tw_seq; + uint32_t size = 0, face = 0, lo = 0, hi, *row; + unsigned x0 = 0, y0 = 0, x1 = tw, y1 = th; + uint8_t *out; + struct twiddle t; + bool fresh, partial; + + for (unsigned l = 0; l < levels; l++) + size += MAX2(tw >> l, 1) * MAX2(th >> l, 1) * b; + for (unsigned l = 0; faces > 1 && (tw >> l || th >> l); l++) + face += MAX2(tw >> l, 1) * MAX2(th >> l, 1) * b; + /* (M43: a face 2 KiB aligned when level 0's is 512 bytes or more -- + * 16 x 16 of four-byte texels, 8 x 8 of eight, 32 x 32 of one: dEQP's + * random_teximage2d.cube_7, an 8 x 8 cube map of half floats) */ + if (faces > 1 && tw * th * b >= 512) + face = align(face, 2048); + if (faces > 1) + size = 5 * face + size; + hi = size; + if (!same || (!boxed && res->tw_cpu)) { + FREE(res->tw_cpu); + res->tw_cpu = NULL; + } + /* the first box written: from now on a shadow of the copy */ + partial = boxed && res->tw_cpu; + if (boxed && !res->tw_cpu) + res->tw_cpu = MALLOC(size); + if (partial) { + /* (the padding of the box's last column and row too) */ + x0 = res->tw_x0; + y0 = res->tw_y0; + x1 = res->tw_x1 >= w ? tw : res->tw_x1; + y1 = res->tw_y1 >= h ? th : res->tw_y1; + } + /* a new copy, or the old one again if no render reads it -- or if a + * small box of a big copy changed: then the renders that read it go + * first and are waited for, cheaper than copying all of it over (64 + * boxes of 16 x 16 into 1024 x 1024: 1.2 s the other way, glupload) */ + if (partial && same && size >= (512u << 10) && res->tw_cpu) { + unsigned bw = (x1 - x0) * (y1 - y0) * b * 4; + + if (bw <= size / 8) { + if (sgx_batch_reads(ctx, res->tw)) + sgx_batch_flush(ctx); + if (!sgx_bo_idle(res->tw)) + sgx_bo_wait(res->tw, -1); + } + } + fresh = !same || sgx_batch_reads(ctx, res->tw) || !sgx_bo_idle(res->tw); + if (fresh) { + struct sgx_bo *bo = sgx_bo_cache_get(&screen->dev, size); + + if (!bo) + return false; + sgx_bo_destroy(res->tw); + res->tw = bo; + res->tw_w = tw; + res->tw_h = th; + res->tw_levels = levels; + res->tw_first = first; + } + out = res->tw_cpu ? res->tw_cpu : MALLOC(size); + row = MALLOC(MAX2(tw, 1) * 8); + if (!out || !row || !sgx_bo_map(res->bo)) { + if (out != res->tw_cpu) + FREE(out); + FREE(row); + return false; + } + /* what the GPU wrote into the texture, done first -- a depth buffer's + * from the ISP's tiles (M37: a shadow map) */ + if (res->gpu_written || res->external) + sgx_bo_wait(res->bo, -1); + for (unsigned i = 0; util_format_is_depth_or_stencil(p->format) && i < res->nzls; i++) + if (res->zls[i].valid || res->zls[i].cleared) + zs_to_linear(res, i / p->array_size, i % p->array_size); + for (unsigned f = 0; f < faces; f++) { + uint8_t *dst = out + f * face; + + for (unsigned l = 0; l < levels; l++) { + unsigned dw = MAX2(tw >> l, 1), dh = MAX2(th >> l, 1); + + if (!twiddle_init(&t, dw, dh)) { + if (out != res->tw_cpu) + FREE(out); + FREE(row); + return false; + } + if (partial) { + copy_level(res, first + l, f, dst, dw, dh, scale, x0, y0, x1, y1, row, &t); + lo = twiddle_at(&t, x0, y0) * b; + hi = (twiddle_at(&t, x1 - 1, y1 - 1) + 1) * b; + } else { + copy_level(res, first + l, f, dst, dw, dh, scale, 0, 0, dw, dh, row, &t); + } + FREE(t.mx); + dst += dw * dh * b; + } + } + FREE(row); + /* a new buffer takes all of it; the old one the range the box is in */ + if (fresh) + lo = 0, hi = size; + memcpy((uint8_t *)res->tw->map + lo, out + lo, hi - lo); + if (out != res->tw_cpu) + FREE(out); + /* SGX_TEX_PROBE=1: a cube map's copy holds each texel's own index + * instead (finding the layout: glmip --probe) */ + if (faces > 1 && b == 4 && getenv("SGX_TEX_PROBE")) + for (uint32_t i = 0; i < size / 4; i++) + ((uint32_t *)res->tw->map)[i] = 0xff000000u | i; + /* SGX_DEBUG=copies: each copy made, what of it and why */ + { + static int on = -1; + + if (on < 0) + on = getenv("SGX_DEBUG") && strstr(getenv("SGX_DEBUG"), "copies"); + if (on) + mesa_logi("sgx: copy %p %s %ux%u l%u: %s, %s buffer, %u bytes (%u writes, seq +%u%s%s)", + (void *)res, util_format_short_name(p->format), w, h, levels, + partial ? "a box" : "all", fresh ? "a new" : "the same", hi - lo, + res->tw_writes, res->seq - res->tw_seq, res->gpu_written ? ", GPU-written" : "", + same ? "" : ", new size"); + } + res->tw_seq = res->seq; + res->tw_writes = 0; + return true; +} + +/* a wrap mode as the sampler takes it: 0 repeat, 1 mirrored, 2 clamped */ +static uint32_t +wrap_bits(unsigned wrap) +{ + return wrap == PIPE_TEX_WRAP_REPEAT ? 0 : wrap == PIPE_TEX_WRAP_MIRROR_REPEAT ? 1 : 2; +} + +/* The sampler's half of the state's word 0. Wrap: t in bits 5:3, s in + * 8:6 (iOS's for CLAMP_TO_EDGE on both axes is 0x90, the corpus's t* cases; + * the axes and mirroring found with a texture drawn three times over, M24). + * Filters, found by flipping bits under gltex: bits 13:12 the + * magnification filter, 11:10 the minification one, 0 point and 1 (or 2) + * bilinear -- 3 samples as point again; bit 9 the linear mip filter, a + * level and the next mixed (glmip, M28: the nearest level without it). + * Whether there is mipmapping at all is the last level's field + * (sgx_resource_texture). */ +static uint32_t +sampler_bits(const struct pipe_sampler_state *ss) +{ + if (!ss) + return 0; + return wrap_bits(ss->wrap_t) << 3 | wrap_bits(ss->wrap_s) << 6 | + (ss->min_mip_filter == PIPE_TEX_MIPFILTER_LINEAR ? 1u << 9 : 0) | + (ss->min_img_filter == PIPE_TEX_FILTER_LINEAR ? 1u << 10 : 0) | + (ss->mag_img_filter == PIPE_TEX_FILTER_LINEAR ? 1u << 12 : 0); +} + +bool +sgx_resource_linear(const struct sgx_resource *res, const struct pipe_sampler_state *ss) +{ + const struct pipe_resource *p = &res->base; + static int force = -1; + uint32_t fmt, swizzle; + + if (force < 0) + force = getenv("SGX_LINEAR_TEX") ? atoi(getenv("SGX_LINEAR_TEX")) : 2; + /* SGX_LINEAR_TEX=0: never, 1: whenever it can */ + if (force == 0 || !native_format(p, &fmt, &swizzle) || p->last_level || + p->array_size > 1 || (res->stride[0] & 15) || res->stride[0] < 32 || + ((res->offset[0] + res->bo->va) & 15) || + (p->target != PIPE_TEXTURE_2D && p->target != PIPE_TEXTURE_RECT)) + return false; + /* (a size not a power of two is twiddled too, M28: the minification + * filter is lost here) -- and, M37, one sampled with the nearest texel + * whether minified or magnified, clamped both ways: nothing is lost + * then (dEQP's nearest_linear_clamp_*_npot, piglit's texwrap 2d with + * repeat and mirror went wrong linear), and no copy is made (glamor's + * masks, a new texture of the window's size at every step of a window + * dragged, were copied once each) */ + return force == 1 || res->external || res->gpu_written || + (ss && ss->min_img_filter == PIPE_TEX_FILTER_NEAREST && + ss->mag_img_filter == PIPE_TEX_FILTER_NEAREST && + wrap_bits(ss->wrap_s) == 2 && wrap_bits(ss->wrap_t) == 2); +} + +/* The levels a lookup through view with ss may take (M35): from *first + * to *last. The sampler's own are from its copy's level 0 to the last + * level in word 0, so GL's base and maximum levels and its LOD clamps are + * the copy's: it starts at the base level -- or, with a minimum LOD m, m + * levels further (the sampler's LOD, worked out from that level's size, is + * then GL's less m, and its level 0 GL's level m: max(lambda, m)) -- and + * the last level is the maximum level's or the maximum LOD's. Exact for + * whole numbers. */ +static void +sampled_levels(const struct sgx_resource *res, const struct pipe_sampler_view *view, + const struct pipe_sampler_state *ss, unsigned *first, unsigned *last) +{ + unsigned base = view ? MIN2(view->u.tex.first_level, res->base.last_level) : 0; + unsigned top = view ? CLAMP(view->u.tex.last_level, base, res->base.last_level) : + res->base.last_level; + + *first = *last = base; + if (!ss || ss->min_mip_filter == PIPE_TEX_MIPFILTER_NONE) + return; + if (ss->max_lod < (float)(top - base)) + top = base + (unsigned)MAX2(ss->max_lod, 0.0f); + *last = top; + if (ss->min_lod > 0) + *first = MIN2(base + (unsigned)ceilf(ss->min_lod), top); +} + +bool +sgx_resource_texture(struct sgx_context *ctx, struct sgx_resource *res, + const struct pipe_sampler_view *view, + const struct pipe_sampler_state *ss, uint32_t words[4]) +{ + struct pipe_resource *p = &res->base; + + if ((p->target != PIPE_TEXTURE_1D && p->target != PIPE_TEXTURE_2D && + p->target != PIPE_TEXTURE_RECT && p->target != PIPE_TEXTURE_CUBE) || + p->array_size != (p->target == PIPE_TEXTURE_CUBE ? 6 : 1) || !p->width0 || !p->height0) + return false; + if (sgx_resource_linear(res, ss)) { + uint32_t fmt, swizzle; + + /* the 2D engine's way (apple_sgx_hw.c, blt_tex: iOS's for an + * IOSurface): the content itself, its stride in 16 bytes less 2; + * bits 11:9 all set, or the rows come out skewed -- every other value + * of the three was tried (gltex), and the minification filter they + * are for twiddled textures is lost: point sampling. Type 6 (GXM's + * linear strided), the format and its swizzle as a copy's (M37: the + * sampler reads B G R A by swizzle 1, ARGB, not by itself) */ + native_format(p, &fmt, &swizzle); + words[0] = (res->stride[0] / 16 - 2) << 16 | (sampler_bits(ss) & ~0xe00u) | 7u << 9; + words[1] = 6u << 29 | fmt << 24 | (p->width0 - 1) << 12 | (p->height0 - 1); + words[2] = res->bo->va + res->offset[0]; + words[3] = swizzle << 28; + res->sampled = res->bo; + } else { + bool cube = p->target == PIPE_TEXTURE_CUBE; + unsigned first, last, w, h; + uint32_t fmt, swizzle; + int bias; + + sampled_levels(res, view, ss, &first, &last); + if ((!res->tw || res->tw_seq != res->seq || res->tw_first != first) && + !copy_texture(ctx, res, first)) + return false; + w = u_minify(p->width0, first); + h = u_minify(p->height0, first); + /* bits 20:17 the last level the sampler goes down to (iOS's 4 x 4 + * cube map, one level, has 0; glmip): with no mip filter, level 0's + * alone; bits 26:21 the LOD bias in eighths, 31 none (iOS's corpus: + * 39 for 1.0, 43 for 1.5 -- Vita3K's SceGxmTexture, the same words) */ + bias = 31 + (ss ? (int)lroundf(ss->lod_bias * 8) : 0); + words[0] = (uint32_t)CLAMP(bias, 0, 63) << 21 | + MIN2(last - first, res->tw_levels - 1) << 17 | sampler_bits(ss); + /* word 1: the type in bits 31:29 (0 twiddled, 2 a cube map -- iOS's + * t04, 0x4c020002 -- 5 twiddled of any size, 6 strided: GXM's + * SceGxmTextureType), the format in 28:24, the size: log2 w in 19:16 + * and log2 h in 3:0, or w - 1 in 23:12 and h - 1 in 11:0 */ + native_format(p, &fmt, &swizzle); + /* (M43) a copy of half floats, R G B A: swizzle ABGR */ + if (sgx_resource_copy_f16(p)) { + fmt = 0x1b; + swizzle = 0; + } + /* depth: F32 (0x12), its one channel raw; nearest -- the sampler + * filters no F32 (iOS has no OES_texture_float_linear) */ + if (util_format_is_depth_or_stencil(p->format)) { + fmt = 0x12; + swizzle = 0; + words[0] &= ~(1u << 9 | 3u << 10 | 3u << 12); + } + if (cube || (util_is_power_of_two_nonzero(w) && util_is_power_of_two_nonzero(h))) + words[1] = (cube ? 2u << 29 : 0) | fmt << 24 | + util_logbase2(res->tw_w) << 16 | util_logbase2(res->tw_h); + else + words[1] = 5u << 29 | fmt << 24 | (w - 1) << 12 | (h - 1); + words[2] = res->tw->va; + words[3] = swizzle << 28; + res->sampled = res->tw; + } + /* SGX_TEX_WORDn=mask: bits of word n flipped, to find what they do */ + { + static int64_t flip[4] = { -1, -1, -1, -1 }; + + for (unsigned i = 0; i < 4; i++) { + char name[16]; + + if (flip[i] < 0) { + snprintf(name, sizeof(name), "SGX_TEX_WORD%u", i); + flip[i] = getenv(name) ? strtoul(getenv(name), NULL, 0) : 0; + } + words[i] ^= (uint32_t)flip[i]; + } + } + return true; +} + +void +sgx_resource_screen_init(struct sgx_screen *screen) +{ + screen->base.resource_create = sgx_resource_create; + screen->base.resource_destroy = sgx_resource_destroy; + screen->base.resource_get_handle = sgx_resource_get_handle; + screen->base.resource_from_handle = sgx_resource_from_handle; +} + +/* ---- a depth/stencil buffer's content for the CPU (M35) ------------------- + * + * Depth and stencil live in the render's tiles, and in memory only as the + * ISP stores them (M24, res->zls): 32 x 32 pixels a tile, row by row, 4 + * bytes a pixel -- F32 depth alone, or 24-bit depth with the stencil in the + * top byte -- tile (x, y) at (x + y * S) * 4 KiB, S two tiles for every 64 + * pixels of the width (the level's). F32 depth with stencil (M43, + * SGX_ZLS_F32S8): 5 bytes a pixel, 5 KiB a tile, each row of 32 a stream + * of 160 bytes -- for each pixel the stencil, then the depth's bits as a + * key that sorts as an integer (a positive float's sign bit flipped, a + * negative one's every bit), most significant byte first -- each 16 bytes + * of which are stored reversed (found from a pattern of known depths and + * stencils, every pixel of a 256 x 256 buffer). A map of a level's layer + * brings the resource's own linear copy of it, in its format, up to date + * from them (or from a clear no render has done yet); an unmap that wrote + * puts it back, for the next render to load. */ +struct sgx_zls * +sgx_resource_zls(struct sgx_resource *res, unsigned level, unsigned layer) +{ + unsigned n = (res->base.last_level + 1) * res->base.array_size; + + if (level > res->base.last_level || layer >= res->base.array_size) + return NULL; + if (!res->zls) { + if (!(res->zls = CALLOC(n, sizeof(*res->zls)))) + return NULL; + res->nzls = n; + } + return &res->zls[level * res->base.array_size + layer]; +} + +static uint32_t * +zls_texel(const struct sgx_zls *zls, unsigned w, unsigned x, unsigned y) +{ + unsigned s = 2 * DIV_ROUND_UP(w, 64); + + return (uint32_t *)((uint8_t *)zls->bo->map + (x / 32 + y / 32 * s) * 4096) + + (y % 32) * 32 + x % 32; +} + +/* (M43) an SGX_ZLS_F32S8 pixel's byte i (0 the stencil, 1..4 the key) */ +static uint8_t * +zls_f32s8_byte(const struct sgx_zls *zls, unsigned w, unsigned x, unsigned y, unsigned i) +{ + unsigned s = 2 * DIV_ROUND_UP(w, 64), at = 5 * (x % 32) + i; + + return zls->bo->map + (x / 32 + y / 32 * s) * 5120 + (y % 32) * 160 + (at & ~15u) + + 15 - at % 16; +} + +/* pixel (x, y)'s depth and stencil as the ISP stored them in format f */ +static void +zls_get(const struct sgx_zls *zls, enum sgx_zls_format f, unsigned w, unsigned x, unsigned y, + float *z, uint8_t *st) +{ + uint32_t wd; + + if (f == SGX_ZLS_F32S8) { + uint32_t key = 0; + + for (unsigned i = 1; i <= 4; i++) + key = key << 8 | *zls_f32s8_byte(zls, w, x, y, i); + wd = key & 0x80000000u ? key ^ 0x80000000u : ~key; + memcpy(z, &wd, 4); + *st = *zls_f32s8_byte(zls, w, x, y, 0); + return; + } + wd = *zls_texel(zls, w, x, y); + if (f == SGX_ZLS_D24S8) { + *z = (wd & 0xffffff) / 16777215.0f; + *st = wd >> 24; + } else { + memcpy(z, &wd, 4); + *st = 0; + } +} + +static void +zls_put(const struct sgx_zls *zls, enum sgx_zls_format f, unsigned w, unsigned x, unsigned y, + float z, uint8_t st) +{ + uint32_t wd; + + if (f == SGX_ZLS_F32S8) { + uint32_t key; + + memcpy(&wd, &z, 4); + key = wd & 0x80000000u ? ~wd : wd ^ 0x80000000u; + *zls_f32s8_byte(zls, w, x, y, 0) = st; + for (unsigned i = 1; i <= 4; i++) + *zls_f32s8_byte(zls, w, x, y, i) = key >> (32 - 8 * i); + return; + } + if (f == SGX_ZLS_D24S8) { + /* (in doubles: 1.0 in floats came to 2^24, a carry into the + * stencil) */ + wd = (uint32_t)st << 24 | (uint32_t)(CLAMP(z, 0.0f, 1.0f) * 16777215.0 + 0.5); + } else { + memcpy(&wd, &z, 4); + } + *zls_texel(zls, w, x, y) = wd; +} + +static bool +zs_to_linear(struct sgx_resource *res, unsigned level, unsigned layer) +{ + struct pipe_resource *p = &res->base; + struct sgx_zls *zls = sgx_resource_zls(res, level, layer); + unsigned w = u_minify(p->width0, level), h = u_minify(p->height0, level); + bool stencil = util_format_has_stencil(util_format_description(p->format)); + bool depth = util_format_has_depth(util_format_description(p->format)); + bool tiles = zls && zls->bo && zls->valid && sgx_bo_map(zls->bo); + enum sgx_zls_format f = sgx_zls_format(p->format); + uint8_t *map = sgx_bo_map(res->bo); + float *z = MALLOC(w * sizeof(float)); + uint8_t *st = MALLOC(w); + + if (!map || !z || !st || !zls) { + FREE(z); + FREE(st); + return false; + } + /* (never stored nor cleared: the copy is what there is) */ + if (!tiles && !zls->cleared) { + FREE(z); + FREE(st); + return true; + } + if (tiles) + sgx_bo_wait(zls->bo, -1); + for (unsigned y = 0; y < h; y++) { + uint8_t *row = map + res->offset[level] + layer * res->layer_size[level] + + y * res->stride[level]; + + for (unsigned x = 0; x < w; x++) { + z[x] = 0; + st[x] = 0; + if (tiles) + zls_get(zls, f, w, x, y, &z[x], &st[x]); + if (zls->cleared) + z[x] = zls->clear; + } + if (depth) + util_format_pack_z_float(p->format, row, z, w); + if (stencil) + util_format_pack_s_8uint(p->format, row, st, w); + } + FREE(z); + FREE(st); + return true; +} + +static void +linear_to_zs(struct sgx_screen *screen, struct sgx_resource *res, unsigned level, + unsigned layer) +{ + struct pipe_resource *p = &res->base; + struct sgx_zls *zls = sgx_resource_zls(res, level, layer); + unsigned lw = u_minify(p->width0, level), lh = u_minify(p->height0, level); + bool stencil = util_format_has_stencil(util_format_description(p->format)); + bool depth = util_format_has_depth(util_format_description(p->format)); + enum sgx_zls_format f = sgx_zls_format(p->format); + uint8_t *map = sgx_bo_map(res->bo); + float *z = MALLOC(lw * sizeof(float)); + uint8_t *st = MALLOC(lw); + + if (zls && !zls->bo) { + zls->bo = sgx_bo_create(&screen->dev, sgx_frame_zls_size(lw, lh, f), 0, 0); + zls->valid = false; + } + if (map && z && st && zls && zls->bo && sgx_bo_map(zls->bo)) { + sgx_bo_wait(zls->bo, -1); + for (unsigned y = 0; y < lh; y++) { + const uint8_t *row = map + res->offset[level] + layer * res->layer_size[level] + + y * res->stride[level]; + + if (depth) + util_format_unpack_z_float(p->format, z, row, lw); + if (stencil) + util_format_unpack_s_8uint(p->format, st, row, lw); + for (unsigned x = 0; x < lw; x++) + zls_put(zls, f, lw, x, y, depth ? z[x] : 0, stencil ? st[x] : 0); + } + zls->valid = true; + zls->cleared = false; + } + FREE(z); + FREE(st); +} + +/* (M46) data's bytes that only the GPU copy has made the CPU's again (the + * buffer's dirty_lock held): a read of write-combined memory, slow, and + * only for a buffer written by sgx_buffer_subdata that the CPU then reads */ +static void +buffer_fresh_locked(struct sgx_resource *res) +{ + if (res->stale_lo < res->stale_hi && res->bo && res->data) { + memcpy(res->data + res->stale_lo, (const uint8_t *)res->bo->map + res->stale_lo, + res->stale_hi - res->stale_lo); + sgx_stat_up[SGX_UP_BACK] += res->stale_hi - res->stale_lo; + } + res->stale_lo = res->stale_hi = 0; +} + +void +sgx_buffer_fresh(struct sgx_resource *res) +{ + if (res->base.target != PIPE_BUFFER || res->stale_lo >= res->stale_hi) + return; + simple_mtx_lock(&res->dirty_lock); + buffer_fresh_locked(res); + simple_mtx_unlock(&res->dirty_lock); +} + +const uint8_t * +sgx_buffer_read_in_place(struct sgx_resource *res, uint32_t lo, uint32_t hi) +{ + const uint8_t *p; + + if (res->base.target != PIPE_BUFFER || lo > hi || hi > res->base.width0) + return NULL; + simple_mtx_lock(&res->dirty_lock); + if (res->stale_lo < res->stale_hi && lo < res->stale_hi && hi > res->stale_lo && + lo >= res->stale_lo && hi <= res->stale_hi && res->bo && + (res->bo->map || sgx_bo_map(res->bo))) { + p = res->bo->map; + simple_mtx_unlock(&res->dirty_lock); + return p; + } + simple_mtx_unlock(&res->dirty_lock); + /* (only partly behind: those bytes made the CPU's) */ + sgx_buffer_fresh_range(res, lo, hi); + return res->data ? res->data : res->bo ? sgx_bo_map(res->bo) : NULL; +} + +void +sgx_buffer_fresh_range(struct sgx_resource *res, uint32_t lo, uint32_t hi) +{ + if (res->base.target != PIPE_BUFFER || res->stale_lo >= res->stale_hi) + return; + simple_mtx_lock(&res->dirty_lock); + if (lo <= res->stale_lo && hi >= res->stale_hi) { + buffer_fresh_locked(res); + } else { + /* (the rest stays behind: copied again later, the same bytes) */ + lo = MAX2(lo, res->stale_lo); + hi = MIN2(hi, res->stale_hi); + if (lo < hi && res->bo && res->data) { + memcpy(res->data + lo, (const uint8_t *)res->bo->map + lo, hi - lo); + sgx_stat_up[SGX_UP_BACK] += hi - lo; + } + } + simple_mtx_unlock(&res->dirty_lock); +} + +/* (M46) a map that is to write a buffer's new content, its old content + * discarded (GL_MAP_INVALIDATE_BUFFER_BIT; glBufferData's and a whole + * buffer's glBufferSubData too, through u_default_buffer_subdata): the + * buffer's GPU copy itself, mapped -- the application writes where the GPU + * reads. A copy a render reads, gathered or running, is left to it and a + * fresh one taken from the cache: PPSSPP maps its push buffers at a frame's + * end, right after the draws that read them, and its emulator thread + * writes the next frame's vertices and indices there -- 1.75 MB a frame + * the GL thread copied before (glBufferSubData: sgx_buffer_subdata). The + * CPU copy is behind by the box then (stale_lo, stale_hi); what it has + * besides was discarded with the rest. A vertex or index buffer (not + * constants: the CPU reads those for every draw), mapped by one thread at a + * time (not glthread's maps nor persistent ones: a draw takes what those + * wrote from the CPU copy as it goes), 4 KiB or more of it. The GPU copy's + * map, or NULL: the CPU copy then, as before. SGX_DIRECT_MAP=0: never. */ +static uint8_t * +buffer_map_direct(struct sgx_context *ctx, struct sgx_resource *res, unsigned usage, + const struct pipe_box *box) +{ + struct sgx_screen *screen = sgx_screen(ctx->base.screen); + const unsigned want = PIPE_MAP_WRITE | PIPE_MAP_DISCARD_WHOLE_RESOURCE; + uint32_t lo = box->x, hi = box->x + box->width; + static int on = -1; + struct sgx_bo *bo; + + if (on < 0) + on = !getenv("SGX_DIRECT_MAP") || atoi(getenv("SGX_DIRECT_MAP")); + if (!on || (usage & want) != want || + (usage & (PIPE_MAP_READ | PIPE_MAP_THREAD_SAFE | PIPE_MAP_PERSISTENT)) || !res->data || + (res->base.bind & PIPE_BIND_CONSTANT_BUFFER) || hi > res->base.width0 || hi - lo < 4096) + return NULL; + simple_mtx_lock(&res->dirty_lock); + if (p_atomic_read(&res->live_maps) > 0) { + simple_mtx_unlock(&res->dirty_lock); + return NULL; + } + bo = res->bo; + if (!bo || sgx_batch_reads(ctx, bo) || !sgx_bo_idle(bo)) { + /* (four bytes more, as sgx_buffer_bo's: a fetch reads whole words) */ + if (!(bo = sgx_bo_cache_get(&screen->dev, res->base.width0 + 4))) { + simple_mtx_unlock(&res->dirty_lock); + return NULL; + } + /* (the gathered draws and the kernel hold the old one for their + * renders: back to the cache after them, M26) */ + sgx_bo_destroy(res->bo); + res->bo = bo; + sgx_stat_up[SGX_UP_RENAMED] += hi - lo; + } + res->dirty_lo = res->dirty_hi = 0; + res->dirty_sync = false; + res->stale_lo = lo; + res->stale_hi = hi; + sgx_stat_up[SGX_UP_MAPPED] += hi - lo; + simple_mtx_unlock(&res->dirty_lock); + return bo->map; +} + +static void * +sgx_transfer_map(struct pipe_context *pctx, struct pipe_resource *prsc, unsigned level, + unsigned usage, const struct pipe_box *box, struct pipe_transfer **out) +{ + struct sgx_context *ctx = sgx_context(pctx); + struct sgx_resource *res = sgx_resource(prsc); + struct sgx_transfer *trans; + bool direct = false; + uint8_t *map; + + /* draws gathered but not rendered that write or read it go first, and + * renders that do -- not for a buffer: its CPU copy is no render's + * (M26: sgx_buffer_bo). Nor for a texture whose linear content no + * render reads -- sampled through its copy -- or writes (M37): it is the + * CPU's alone (glamor's glyphs went one render and a wait each). */ + if (!(usage & PIPE_MAP_UNSYNCHRONIZED) && prsc->target != PIPE_BUFFER) { + bool gpu = res->gpu_written || res->external || + util_format_is_depth_or_stencil(prsc->format) || + ctx->batch.rt == prsc || ctx->batch.zs == prsc || + sgx_batch_reads(ctx, res->bo) || !sgx_bo_idle(res->bo); + + if (gpu && sgx_batch_uses(ctx, prsc)) + sgx_batch_flush(ctx); + if (gpu && !sgx_bo_wait(res->bo, -1)) + return NULL; + } + /* a depth clear at the start of a render that has no draws yet: the + * buffer's own from now on (what the CPU reads, or writes over) */ + if (ctx->batch.zs_cleared && !ctx->batch.ndraws && ctx->fb.zsbuf.texture == prsc) { + struct sgx_zls *zls = sgx_resource_zls(res, ctx->fb.zsbuf.level, ctx->fb.zsbuf.first_layer); + + if (zls) { + zls->cleared = true; + zls->clear = ctx->batch.depth_clear; + } + ctx->batch.zs_cleared = false; + } + /* depth and stencil from the ISP's tiles, unless all of it is to be + * written (the level's layers the box takes) */ + if (util_format_is_depth_or_stencil(prsc->format) && prsc->target != PIPE_BUFFER && + !(usage & PIPE_MAP_DISCARD_WHOLE_RESOURCE) && + !((usage & PIPE_MAP_DISCARD_RANGE) && box->width == (int)u_minify(prsc->width0, level) && + box->height == (int)u_minify(prsc->height0, level))) { + for (int z = box->z; z < box->z + MAX2(box->depth, 1); z++) + if (!zs_to_linear(res, level, z)) + return NULL; + } + /* (M46) the GPU copy itself, or what only the GPU copy has the CPU's + * again first */ + if (prsc->target == PIPE_BUFFER && (map = buffer_map_direct(ctx, res, usage, box))) { + direct = true; + } else { + if (prsc->target == PIPE_BUFFER) + sgx_buffer_fresh(res); + if (!(map = res->data ? res->data : sgx_bo_map(res->bo))) + return NULL; + } + /* (a map glthread makes in the application's thread: nothing of the + * context's -- M34) */ + trans = usage & PIPE_MAP_THREAD_SAFE ? CALLOC_STRUCT(sgx_transfer) : + slab_zalloc(&ctx->transfer_pool); + if (!trans) + return NULL; + if (prsc->target == PIPE_BUFFER && (usage & (PIPE_MAP_THREAD_SAFE | PIPE_MAP_PERSISTENT))) + p_atomic_inc(&res->live_maps); + trans->direct = direct; + pipe_resource_reference(&trans->base.resource, prsc); + trans->base.level = level; + trans->base.usage = usage; + trans->base.box = *box; + *out = &trans->base; + + if (prsc->target == PIPE_BUFFER) + return map + box->x; + + trans->base.stride = res->stride[level]; + trans->base.layer_stride = res->layer_size[level]; + return map + res->offset[level] + box->z * res->layer_size[level] + + (box->y / util_format_get_blockheight(prsc->format)) * res->stride[level] + + (box->x / util_format_get_blockwidth(prsc->format)) * + util_format_get_blocksize(prsc->format); +} + +/* bytes [lo, hi) of a buffer written: what its GPU copy is behind by */ +static void +dirty_add(struct sgx_resource *res, uint32_t lo, uint32_t hi) +{ + if (res->dirty_lo >= res->dirty_hi) { + res->dirty_lo = lo; + res->dirty_hi = hi; + } else { + res->dirty_lo = MIN2(res->dirty_lo, lo); + res->dirty_hi = MAX2(res->dirty_hi, hi); + } +} + +static void +buffer_written(struct sgx_resource *res, uint32_t lo, uint32_t hi, unsigned usage) +{ + if (lo >= hi) + return; + simple_mtx_lock(&res->dirty_lock); + dirty_add(res, lo, hi); + res->dirty_sync |= !(usage & PIPE_MAP_UNSYNCHRONIZED); + simple_mtx_unlock(&res->dirty_lock); +} + +/* a map with PIPE_MAP_FLUSH_EXPLICIT wrote what it flushes (u_upload_mgr + * maps the rest of its buffer, and flushes what it handed out) */ +static void +sgx_transfer_flush_region(struct pipe_context *pctx, struct pipe_transfer *ptrans, + const struct pipe_box *box) +{ + if (ptrans->resource->target == PIPE_BUFFER && !((struct sgx_transfer *)ptrans)->direct) + buffer_written(sgx_resource(ptrans->resource), ptrans->box.x + box->x, + ptrans->box.x + box->x + box->width, ptrans->usage); +} + +static void +sgx_transfer_unmap(struct pipe_context *pctx, struct pipe_transfer *ptrans) +{ + struct sgx_context *ctx = sgx_context(pctx); + struct sgx_resource *res = sgx_resource(ptrans->resource); + + if (ptrans->usage & PIPE_MAP_WRITE) { + const struct pipe_box *box = &ptrans->box; + + res->seq++; + /* a box of level 0 of a 2D texture of one level: the copy made again + * for it alone (M37: copy_texture) */ + if (ptrans->resource->target != PIPE_BUFFER && !ptrans->level && + !ptrans->resource->last_level && ptrans->resource->array_size == 1 && + (ptrans->resource->target == PIPE_TEXTURE_2D || + ptrans->resource->target == PIPE_TEXTURE_RECT) && + !box->z && box->depth == 1 && box->width > 0 && box->height > 0) { + if (!res->tw_writes) { + res->tw_x0 = box->x; + res->tw_y0 = box->y; + res->tw_x1 = box->x + box->width; + res->tw_y1 = box->y + box->height; + } else { + res->tw_x0 = MIN2(res->tw_x0, (unsigned)box->x); + res->tw_y0 = MIN2(res->tw_y0, (unsigned)box->y); + res->tw_x1 = MAX2(res->tw_x1, (unsigned)(box->x + box->width)); + res->tw_y1 = MAX2(res->tw_y1, (unsigned)(box->y + box->height)); + } + res->tw_writes++; + } + /* (a map that was the GPU copy: written where the GPU reads, M46) */ + if (ptrans->resource->target == PIPE_BUFFER && !(ptrans->usage & PIPE_MAP_FLUSH_EXPLICIT) && + !((struct sgx_transfer *)ptrans)->direct) + buffer_written(res, ptrans->box.x, ptrans->box.x + ptrans->box.width, ptrans->usage); + if (util_format_is_depth_or_stencil(ptrans->resource->format) && + ptrans->resource->target != PIPE_BUFFER) { + for (int z = box->z; z < box->z + MAX2(box->depth, 1); z++) + linear_to_zs(sgx_screen(pctx->screen), res, ptrans->level, z); + } + } + if (ptrans->resource->target == PIPE_BUFFER && + (ptrans->usage & (PIPE_MAP_THREAD_SAFE | PIPE_MAP_PERSISTENT))) + p_atomic_dec(&res->live_maps); + + pipe_resource_reference(&ptrans->resource, NULL); + if (ptrans->usage & PIPE_MAP_THREAD_SAFE) + FREE(ptrans); + else + slab_free(&ctx->transfer_pool, ptrans); +} + +struct sgx_bo * +sgx_buffer_bo(struct sgx_context *ctx, struct sgx_resource *res, uint32_t read_lo, + uint32_t read_hi) +{ + struct sgx_screen *screen = sgx_screen(ctx->base.screen); + struct sgx_bo *bo; + uint32_t lo, hi; + + simple_mtx_lock(&res->dirty_lock); + /* mapped while it is drawn from: what the draw reads, as it is (glthread + * writes its uploads on and on, before the draws that read them) */ + if (p_atomic_read(&res->live_maps) > 0 && read_lo < MIN2(read_hi, res->base.width0)) + dirty_add(res, read_lo, MIN2(read_hi, res->base.width0)); + bo = res->bo; + lo = res->dirty_lo; + hi = res->dirty_hi; + if (bo && lo >= hi) { + simple_mtx_unlock(&res->dirty_lock); + return bo; + } + if (bo && res->dirty_sync && (sgx_batch_reads(ctx, bo) || !sgx_bo_idle(bo))) { + /* a render reads the old content: the gathered draws or the kernel + * keep the old copy for it */ + sgx_bo_destroy(bo); + res->bo = bo = NULL; + } + if (!bo) { + /* (four bytes more: a fetch reads whole words, three bytes of RGB8 + * at the end too) */ + if (!(bo = sgx_bo_cache_get(&screen->dev, res->base.width0 + 4))) { + simple_mtx_unlock(&res->dirty_lock); + return NULL; + } + res->bo = bo; + lo = 0; + hi = res->base.width0; + } + sgx_copy((uint8_t *)bo->map + lo, res->data + lo, hi - lo); + sgx_stat_up[SGX_UP_ON] += hi - lo; + res->dirty_lo = res->dirty_hi = 0; + res->dirty_sync = false; + simple_mtx_unlock(&res->dirty_lock); + return bo; +} + +/* glGenerateMipmap by the CPU (M28): each level a 2 x 2 box filter of the + * one above (one texel of it where the level above has only one across or + * down), through util_format's floats -- the blit util_gen_mipmap would + * use scales, which the driver does not */ +static bool +sgx_generate_mipmap(struct pipe_context *pctx, struct pipe_resource *prsc, + enum pipe_format format, unsigned base_level, unsigned last_level, + unsigned first_layer, unsigned last_layer) +{ + struct sgx_context *ctx = sgx_context(pctx); + struct sgx_resource *res = sgx_resource(prsc); + unsigned w = prsc->width0; + float *buf; + uint8_t *map; + + if (prsc->target == PIPE_BUFFER || prsc->target == PIPE_TEXTURE_3D || !res->bo || + util_format_is_compressed(format) || util_format_is_depth_or_stencil(format) || + util_format_is_pure_integer(format)) + return false; + /* draws that write or read it go first, and renders that do */ + if (sgx_batch_uses(ctx, prsc)) + sgx_batch_flush(ctx); + if (!sgx_bo_wait(res->bo, -1) || !(map = sgx_bo_map(res->bo)) || + !(buf = MALLOC(3 * 4 * MAX2(w, 1) * sizeof(float)))) + return false; + for (unsigned layer = first_layer; layer <= last_layer; layer++) { + for (unsigned l = base_level + 1; l <= last_level; l++) { + unsigned sw = u_minify(prsc->width0, l - 1), sh = u_minify(prsc->height0, l - 1); + unsigned dw = u_minify(prsc->width0, l), dh = u_minify(prsc->height0, l); + const uint8_t *src = map + res->offset[l - 1] + layer * res->layer_size[l - 1]; + uint8_t *dst = map + res->offset[l] + layer * res->layer_size[l]; + float *r0 = buf, *r1 = buf + 4 * w, *out = buf + 8 * w; + + for (unsigned y = 0; y < dh; y++) { + unsigned y0 = MIN2(2 * y, sh - 1), y1 = MIN2(2 * y + 1, sh - 1); + + util_format_unpack_rgba(format, r0, src + y0 * res->stride[l - 1], sw); + util_format_unpack_rgba(format, r1, src + y1 * res->stride[l - 1], sw); + for (unsigned x = 0; x < dw; x++) { + unsigned x0 = MIN2(2 * x, sw - 1), x1 = MIN2(2 * x + 1, sw - 1); + + for (unsigned c = 0; c < 4; c++) + out[4 * x + c] = (r0[4 * x0 + c] + r0[4 * x1 + c] + r1[4 * x0 + c] + + r1[4 * x1 + c]) / 4; + } + util_format_pack_rgba(format, dst + y * res->stride[l], out, dw); + } + } + } + FREE(buf); + res->seq++; + return true; +} + +/* (M46) glBufferSubData into a vertex buffer whose GPU copy no render + * reads: straight into that copy, once -- where Mesa's default wrote the CPU + * copy and the next draw copied the bytes on into the GPU's (sgx_buffer_bo): + * PPSSPP uploads every vertex of every frame, and those two copies were 90% + * of its GL thread's memcpy. The CPU copy is behind by those bytes then + * (stale_lo, stale_hi) until something maps it. Index buffers too (the + * VDM reads PPSSPP's where they are; a draw whose indices the CPU reads + * makes the copy the CPU's again first); not constant buffers (the CPU + * reads those for every draw), a buffer mapped while drawn from, or one + * without a GPU copy yet. SGX_DIRECT_SUBDATA=0: Mesa's default always. */ +static void +sgx_buffer_subdata(struct pipe_context *pctx, struct pipe_resource *prsc, unsigned usage, + unsigned offset, unsigned size, const void *data) +{ + struct sgx_context *ctx = sgx_context(pctx); + struct sgx_resource *res = sgx_resource(prsc); + static int on = -1; + + if (on < 0) + on = !getenv("SGX_DIRECT_SUBDATA") || atoi(getenv("SGX_DIRECT_SUBDATA")); + if (on && size >= 64 && res->bo && res->data && offset + size <= prsc->width0 && + !(prsc->bind & PIPE_BIND_CONSTANT_BUFFER)) { + simple_mtx_lock(&res->dirty_lock); + if (p_atomic_read(&res->live_maps) == 0 && !sgx_batch_reads(ctx, res->bo) && + sgx_bo_idle(res->bo)) { + /* what the CPU copy has that the GPU's has not, first (the next + * draw's copy, now: never both behind at once) */ + int64_t t0 = ctx->debug_fps ? os_time_get_nano() : 0; + + if (res->dirty_lo < res->dirty_hi) { + sgx_copy((uint8_t *)res->bo->map + res->dirty_lo, res->data + res->dirty_lo, + res->dirty_hi - res->dirty_lo); + sgx_stat_up[SGX_UP_ON] += res->dirty_hi - res->dirty_lo; + res->dirty_lo = res->dirty_hi = 0; + res->dirty_sync = false; + } + sgx_copy((uint8_t *)res->bo->map + offset, data, size); + sgx_stat_up[SGX_UP_DIRECT] += size; + if (t0) + sgx_stat_up_ns += os_time_get_nano() - t0; + if (res->stale_lo >= res->stale_hi) { + res->stale_lo = offset; + res->stale_hi = offset + size; + } else { + res->stale_lo = MIN2(res->stale_lo, offset); + res->stale_hi = MAX2(res->stale_hi, offset + size); + } + simple_mtx_unlock(&res->dirty_lock); + return; + } + simple_mtx_unlock(&res->dirty_lock); + } + sgx_stat_up[SGX_UP_CPU] += size; + u_default_buffer_subdata(pctx, prsc, usage, offset, size, data); +} + +void +sgx_resource_context_init(struct pipe_context *pctx) +{ + pctx->buffer_map = sgx_transfer_map; + pctx->texture_map = sgx_transfer_map; + pctx->buffer_unmap = sgx_transfer_unmap; + pctx->texture_unmap = sgx_transfer_unmap; + pctx->transfer_flush_region = sgx_transfer_flush_region; + pctx->buffer_subdata = sgx_buffer_subdata; + pctx->generate_mipmap = sgx_generate_mipmap; + pctx->texture_subdata = u_default_texture_subdata; +} diff --git a/src/gallium/drivers/sgx/sgx_resource.h b/src/gallium/drivers/sgx/sgx_resource.h new file mode 100644 index 00000000000..cf9a1bfc014 --- /dev/null +++ b/src/gallium/drivers/sgx/sgx_resource.h @@ -0,0 +1,141 @@ +/* + * Copyright 2026 Project Cascadia + * SPDX-License-Identifier: MIT + */ +#ifndef SGX_RESOURCE_H +#define SGX_RESOURCE_H + +#include "pipe/p_state.h" +#include "util/simple_mtx.h" +#include "util/u_transfer.h" + +struct sgx_bo; +struct sgx_context; +struct sgx_screen; + +/* Every resource is linear: rows of stride bytes, levels and layers one + * after another. A texture the GPU samples also gets a twiddled copy, made + * by the CPU when the linear content has changed since (seq): every level + * and face, in Morton order, padded to powers of two, as the sampler + * lays them out (M28: sgx_resource_texture) -- its texels as they are for + * the formats the sampler has (M37: native_format()), else RGBA8 -- unless + * it is sampled as it is (sgx_resource_linear()). */ +struct sgx_resource { + struct pipe_resource base; + struct sgx_bo *bo; + /* a buffer's (M26): data is the CPU's copy, what maps see; bo the + * GPU's, made at the first draw that reads the buffer from there, and + * behind data by the bytes [dirty_lo, dirty_hi) -- written since by maps + * that were synchronized too if dirty_sync */ + uint8_t *data; + uint32_t dirty_lo, dirty_hi; + bool dirty_sync; + /* (M34) the maps that stay while draws read it -- glthread's uploads, in + * the application's thread: each draw takes what it reads of data as it + * is -- and the lock the dirty bytes are under (both threads') */ + int live_maps; + simple_mtx_t dirty_lock; + /* (M46) and data behind the GPU copy by the bytes [stale_lo, stale_hi): + * written into it alone (sgx_buffer_subdata: a vertex buffer the CPU + * does not read), made the CPU's again before anything maps data (never + * both behind at once) */ + uint32_t stale_lo, stale_hi; + uint32_t stride[PIPE_MAX_TEXTURE_LEVELS]; /* bytes per row */ + uint32_t layer_size[PIPE_MAX_TEXTURE_LEVELS]; /* bytes per layer or slice */ + uint32_t offset[PIPE_MAX_TEXTURE_LEVELS]; /* of each level */ + uint32_t seq; /* bumped at every write */ + struct sgx_bo *tw; /* the twiddled copy */ + uint32_t tw_seq; /* the content it was made from */ + unsigned tw_w, tw_h; /* its size (linear: the stride's) */ + unsigned tw_levels; /* its levels (of each face, M28) */ + unsigned tw_first; /* the level its level 0 is (M35) */ + /* (M37) the writes since the copy was made, when every one of them was + * a box of level 0 of a texture of one level (tw_writes of the seq + * bumps since tw_seq): that box alone made again, in the CPU's shadow + * of the copy (tw_cpu, cached memory) and from there into the copy -- + * a new one when a render may read the old (copy on write) */ + unsigned tw_writes; + unsigned tw_x0, tw_y0, tw_x1, tw_y1; + uint8_t *tw_cpu; + struct sgx_bo *sampled; /* what the last state words point at */ + bool external; /* shared: others may write it */ + bool gpu_written; /* a render has written it */ + /* a depth buffer's tiles (M24), each level's face or layer its own + * (M43: a depth texture's levels rendered to), level * array_size + + * layer; made at their first use */ + struct sgx_zls *zls; + unsigned nzls; +}; + +static inline struct sgx_resource * +sgx_resource(struct pipe_resource *p) +{ + return (struct sgx_resource *)p; +} + +/* The ISP's tiles of one level and layer of a depth buffer, as a render + * stores them (M24) */ +struct sgx_zls { + struct sgx_bo *bo; + bool valid; /* a render has stored them */ + bool cleared; /* cleared since, to clear */ + float clear; +}; + +/* a level's layer's tiles (state made the first time, the buffer not), or + * NULL when there is no memory for the state */ +struct sgx_zls *sgx_resource_zls(struct sgx_resource *res, unsigned level, unsigned layer); + +/* whether p's copy for the sampler is four half floats (M43) */ +bool sgx_resource_copy_f16(const struct pipe_resource *p); + +/* the program's swizzle on the sampler's texel for p's format (M45: R8, + * RG8), pipe_swizzle each; false when there is none */ +bool sgx_resource_swizzle(const struct pipe_resource *p, uint8_t swz[4]); + +struct sgx_transfer { + struct pipe_transfer base; + /* (M46) a buffer's map that is its GPU copy itself (buffer_map_direct()): + * nothing to copy on at the unmap */ + bool direct; +}; + +/* Whether res is sampled as it is, linear (M16): a format the sampler has + * (native_format(), M37), one level, written by the GPU or by others (a + * render's target, a shared buffer) -- the CPU's copy would read it back + * each time -- or sampled with ss's nearest texel both ways. + * Minification is point sampling then. */ +bool sgx_resource_linear(const struct sgx_resource *res, const struct pipe_sampler_state *ss); + +/* The four state words the sampler reads for res sampled through view + * with ss (M14): the twiddled copy brought up to date first. False when + * res cannot be sampled yet (not 2D, no copy). A copy the gathered draws + * or a running render read is not written over: a new one is made (M37), + * the old one kept for them (the batch holds the buffer res->sampled). */ +bool sgx_resource_texture(struct sgx_context *ctx, struct sgx_resource *res, + const struct pipe_sampler_view *view, + const struct pipe_sampler_state *ss, uint32_t words[4]); + +/* (M46) a buffer's CPU copy brought up to date with what was written into + * its GPU copy alone: before the CPU reads data (a draw's constants, its + * vertices repacked, the draw module's) */ +void sgx_buffer_fresh(struct sgx_resource *res); +/* (M46) the same for the bytes [lo, hi) alone: a draw's indices */ +void sgx_buffer_fresh_range(struct sgx_resource *res, uint32_t lo, uint32_t hi); +/* (M46) where the CPU reads the buffer's bytes [lo, hi) as they are, in + * place (the pointer is the buffer's byte 0): the GPU copy where only it + * has them -- write-combined, slow, for a few bytes here and there -- + * else the CPU copy; NULL if neither */ +const uint8_t *sgx_buffer_read_in_place(struct sgx_resource *res, uint32_t lo, uint32_t hi); + +/* A buffer's copy for the GPU (M26), brought up to date with the CPU's + * first: written in place when no render reads it -- gathered or running + * -- or when only unsynchronized maps wrote it since, else made anew (the + * old one stays with the renders that read it). NULL if it cannot be. */ +struct sgx_bo *sgx_buffer_bo(struct sgx_context *ctx, struct sgx_resource *res, uint32_t read_lo, + uint32_t read_hi); + +void sgx_resource_screen_init(struct sgx_screen *screen); +void sgx_resource_context_init(struct pipe_context *pctx); + +#endif diff --git a/src/gallium/drivers/sgx/sgx_rt.c b/src/gallium/drivers/sgx/sgx_rt.c new file mode 100644 index 00000000000..3bb7ebf93e0 --- /dev/null +++ b/src/gallium/drivers/sgx/sgx_rt.c @@ -0,0 +1,308 @@ +/* + * Copyright 2026 Project Cascadia + * SPDX-License-Identifier: MIT + * + * Render target data (docs/research/p105-mesa.md, M10). What the kext + * does for a render target, rewritten from its behaviour: 0x80bf7aac (the + * init: tiles, the "big" flag), 0x80bf6e78 and 0x80bf6ed8 (the context + * areas), 0x80bf6fd8 (macrotiles and the buffers' sizes), 0x80bf74f4 (the + * render details and the state buffer) and 0x80bf5eec (the submit's + * payload words and 3D register block). mesa/host/rt-test.py checks every + * byte against tools/iosgpu/rtemu.py, which runs the kext's own code. + * + * The screen is cut into 32 x 32 tiles and the tiles into 2 x 2 + * macrotiles, whose sides are a multiple of 4 tiles; the TA keeps a region + * array per pixel pipe (12 bytes a tile) and tail pointers, and the CPU + * writes the render details -- where all of it is, for the microkernel -- + * and the state buffer: a full-screen object (the background's, presumably: + * vertices in 12.4 fixed point, biased by 0x4000), a tile-sized one, and a + * stream entry per region pointing at the latter. Everything is kept twice ("copies"), + * for a TA and a 3D pass in flight at once; renders here use copy 0. + * + * One sample only: the kext's multi-sample path (samples > 1: a tile of + * 16 x 16 pixels, a "big" limit of 1024) and its 4 x 4 macrotiles (an + * RT field the init sets to -1, never 2) are not here. + */ +#include "sgx_rt.h" + +#include +#include + +#define ONE 0x3f800000u /* 1.0f */ +#define COPY 0x84 /* the render details: copy 1 at +0x84 */ +#define FIRST 0x140 /* then each copy's first regions */ + +static uint32_t +align(uint32_t v, uint32_t a) +{ + return (v + a - 1) & ~(a - 1); +} + +static uint32_t +min(uint32_t a, uint32_t b) +{ + return a < b ? a : b; +} + +/* the power of two at or above v, as the kext finds it (from bit 12 down: + * v below 0x2000) */ +static uint32_t +npot(uint32_t v) +{ + uint32_t h = 0x1000; + + assert(v < 0x2000); + while (h > 1 && !(v & h)) + h >>= 1; + return h << !!((h - 1) & v); +} + +bool +sgx_rt_layout(struct sgx_rt *rt, unsigned w, unsigned h, unsigned ncores) +{ + return sgx_rt_layout_rc2(rt, w, h, ncores, false); +} + +/* The A6's kext (0x80ad426c init, 0x80ad3890 sizes, 0x80ad3da0 fill, + * 0x80ad2798 submit) makes the same layout but where noted: checked word + * by word against its own code under unicorn for 64 sizes. */ +bool +sgx_rt_layout_rc2(struct sgx_rt *rt, unsigned w, unsigned h, unsigned ncores, bool rc2) +{ + uint32_t size = 0, p; + + if (!w || !h || w > SGX_RT_MAX_SIZE || h > SGX_RT_MAX_SIZE || !ncores || + ncores > SGX_RT_MAX_CORES) + return false; + memset(rt, 0, sizeof(*rt)); + rt->w = w; + rt->h = h; + rt->ncores = ncores; + rt->rc2 = rc2; + rt->tiles_x = (w + 31) >> 5; + rt->tiles_y = (h + 31) >> 5; + rt->big = w > 2048 || h > 2048; + + /* 0x80bf6e78: the context areas, the same for every target */ + for (unsigned k = 0; k < 2; k++) { + rt->context[k] = size; + size = (size + 0x6f7) & ~0xfu; + } + for (unsigned c = 0; c < ncores; c++) { + rt->context[2 + c] = size; + size = (size + 0x17f) & ~0xffu; + rt->context[2 + SGX_RT_MAX_CORES + c] = size; + size = (size + 0xaf) & ~0x1fu; + } + rt->size[SGX_RT_CONTEXT] = size; + + /* 0x80bf6fd8: 2 x 2 macrotiles of half the tiles each way, rounded up + * to 4 */ + rt->mt_across = rt->mt_down = 2; + rt->mt_w = align((rt->tiles_x + 1) >> 1, 4); + rt->mt_h = align((rt->tiles_y + 1) >> 1, 4); + rt->regions = rt->mt_w * rt->mt_across * rt->mt_h * rt->mt_down; + rt->region_size = align(align(rt->regions * 12, 64), 4096); + p = npot(rt->mt_w * rt->mt_across); + if (npot(rt->mt_h * rt->mt_across) > p) + p = npot(rt->mt_h * rt->mt_across); + rt->tail_size = align(align(p * p * 8, 64), 4096); + rt->size[SGX_RT_REGIONS0] = rt->size[SGX_RT_REGIONS1] = rt->region_size * ncores; + rt->size[SGX_RT_TAILS] = rt->tail_size * ncores; + + size = rc2 ? FIRST - 0x20 : FIRST; + for (unsigned k = 0; k < 2; k++) { + rt->first[k] = size; + size = align(size + rt->mt_across * rt->mt_down * ncores * 4, 32); + } + rt->size[SGX_RT_DETAILS] = size; + + rt->state_clear = 0; + rt->state_tile = 0x80; + rt->state_regions = (rt->state_tile + 0xbf) & 0x380; + rt->size[SGX_RT_STATE] = rt->state_regions + ncores * rt->regions * 64 + 0x100; + if (rc2) { + /* the A6's state buffer: the full-screen object, no stream */ + rt->state_regions = 0; + rt->size[SGX_RT_STATE] = 0x180; + } + return true; +} + +/* the macrotiles' bounds, in tiles, as three fields of 10 bits (with 2 x 2 + * macrotiles all three are the first one's) */ +static uint32_t +bounds(uint32_t t) +{ + return t << 22 | t << 12 | t; +} + +void +sgx_rt_fill(const struct sgx_rt *rt, const uint32_t va[SGX_RT_NBUF], uint32_t *details, + uint32_t *state) +{ + uint32_t xmax = rt->tiles_x - 1, ymax = rt->tiles_y - 1, mt_w = rt->mt_w, mt_h = rt->mt_h; + /* the A6's entries start 8 bytes sooner (the A5's offsets below) */ + const unsigned sh = rt->rc2 ? 8 : 0; + uint32_t *s, *t, *r; + + memset(details, 0, rt->size[SGX_RT_DETAILS]); + memset(state, 0, rt->size[SGX_RT_STATE]); + + /* the render details, each copy; copy 0's tail pointers run into copy + * 1's first words, as the kext has them */ + details[0x08 / 4] = mt_w * rt->mt_across; + details[(0x1c - sh) / 4] = 2; + for (unsigned k = 0; k < 2; k++) { + uint32_t *e = details + k * COPY / 4 - sh / 4; + + e[0x2c / 4] = mt_h * mt_w >> 4; + e[0x30 / 4] = mt_h * mt_w * 12; + e[0x34 / 4] = va[SGX_RT_DETAILS] + rt->first[k]; + e[0x58 / 4] = va[SGX_RT_STATE] + rt->state_clear; + e[0x60 / 4] = va[SGX_RT_STATE] + rt->size[SGX_RT_STATE] - 0x100; + e[0x5c / 4] = va[SGX_RT_CONTEXT] + rt->context[k]; + for (unsigned c = 0; c < rt->ncores; c++) { + e[0x64 / 4 + c] = va[SGX_RT_CONTEXT] + rt->context[2 + c]; + e[0x74 / 4 + c] = va[SGX_RT_CONTEXT] + rt->context[2 + SGX_RT_MAX_CORES + c]; + e[0x84 / 4 + c] = va[SGX_RT_TAILS] + c * rt->tail_size; + } + e[0x94 / 4] = rt->tail_size; + e[0x98 / 4] = va[SGX_RT_DETAILS] + k * COPY + 0x9c - sh; + e[0x9c / 4] = 0x10; + } + + /* each macrotile's last region, as an offset into a region array (bit + * 0 set: the macrotile is on the screen); the pipes' arrays and where + * the last one ends; the last macrotile on the screen */ + for (unsigned k = 0; k < 2; k++) { + uint32_t *e = details + k * COPY / 4 - sh / 4, *first = details + rt->first[k] / 4, last = 0; + + for (uint32_t i = 0; i < rt->mt_across; i++) { + uint32_t x = min(i * mt_w + mt_w - 1, xmax), xm = x % mt_w; + + for (uint32_t j = 0; j < rt->mt_down; j++) { + uint32_t y = min(j * mt_h + mt_h - 1, ymax), ym = y % mt_h; + uint32_t n = (y - (ym & 3)) * mt_w + ((ym & 3) << 2 | (xm & 3) | (xm & ~3u) << 2) + + mt_h * rt->mt_across * (x - xm); + bool off = j * mt_h > ymax || i * mt_w > xmax; + + last = (n * 12 | off) ^ 1; + first[i * rt->mt_down + j] = last; + } + } + for (unsigned c = 0; c < rt->ncores; c++) { + e[0x38 / 4 + c] = va[SGX_RT_REGIONS0 + k] + c * rt->region_size; + e[0x48 / 4 + c] = va[SGX_RT_REGIONS0 + k] + c * rt->region_size + last; + } + for (uint32_t n = 0; n < rt->mt_across * rt->mt_down; n++) + if (first[n] & 1) + e[0x28 / 4] = n; + } + if (!rt->rc2) { + details[0x18 / 4] = rt->regions; + details[0x14 / 4] = va[SGX_RT_STATE] + rt->state_regions; + } + + /* the state buffer: the full-screen object ((0, 0), (w, 0), (0, h) at + * depth 1, at half scale on big targets) */ + s = state + rt->state_clear / 4; + s[0x0c / 4] = 0xffff0000; + s[0x18 / 4] = 0xff00ff00; + s[0x1c / 4] = ONE; + s[0x24 / 4] = 0xff0000ff; + s[0x2c / 4] = ONE; + s[0x30 / 4] = 3; + s[0x34 / 4] = 0x40000000; + s[0x38 / 4] = 0x40004000; + s[0x3c / 4] = ONE; + s[0x40 / 4] = ((rt->big ? rt->w << 19 : rt->w << 20) + 0x40000000u) | 0x4000; + s[0x44 / 4] = ONE; + s[0x48 / 4] = ((rt->big ? rt->h << 3 : rt->h << 4) + 0x4000u) | 0x40000000; + s[0x4c / 4] = ONE; + + /* the A6's has nothing more */ + if (rt->rc2) + return; + + /* a tile's object */ + t = state + rt->state_tile / 4; + t[0x04 / 4] = 0x400000; + t[0x14 / 4] = 0x820; + t[0x20 / 4] = 0x3ff03ff0; + t[0x24 / 4] = ONE; + t[0x28 / 4] = 0x3fe03ff0; + t[0x2c / 4] = ONE; + t[0x30 / 4] = 0x3ff03fe0; + t[0x34 / 4] = ONE; + + /* a stream entry for each region of each pipe, 64 bytes apart */ + r = state + rt->state_regions / 4; + for (uint32_t n = 0; n < rt->regions * rt->ncores; n++, r += 16) { + r[1] = 0x44400001; + r[2] = ((0x00800010u + rt->state_tile + va[SGX_RT_STATE]) >> 2 & 0x1ffffff) | 0x4000000; + } +} + +void +sgx_rt_block3d(const struct sgx_rt *rt, const uint32_t va[SGX_RT_NBUF], uint32_t *blk) +{ + assert(va[SGX_RT_STATE] - SGX_RT_TA_BASE < (1u << 28)); + blk[0x28 / 4] = rt->big; + for (unsigned c = 0; c < rt->ncores; c++) + blk[0x2c / 4 + c] = va[SGX_RT_REGIONS0] + c * rt->region_size; + blk[0x3c / 4] = rt->region_size; + blk[0x40 / 4] = rt->mt_w * rt->mt_h; + blk[0x44 / 4] = bounds(rt->mt_w); + blk[0x48 / 4] = bounds(rt->mt_h); + /* the state buffer from the TA's base, in 16 bytes; bits 29:24 are the + * GL driver's */ + blk[0x88 / 4] = (blk[0x88 / 4] & 0x3f000000) | (va[SGX_RT_STATE] - SGX_RT_TA_BASE) >> 4; + blk[sgx_rt_blk_off(rt->rc2, 0x10c) / 4] = va[SGX_RT_DETAILS]; + blk[sgx_rt_blk_off(rt->rc2, 0x110) / 4] = va[SGX_RT_DETAILS] + SGX_RT_DETAILS_ENTRY(rt->rc2); +} + +void +sgx_rt_payload(const struct sgx_rt *rt, const uint32_t va[SGX_RT_NBUF], uint32_t blk_va, + uint32_t *w) +{ + w[4] = bounds(rt->mt_w); + w[5] = bounds(rt->mt_h); + w[6] = (rt->tiles_y - 1) << 12 | (rt->tiles_x - 1); + w[7] = rt->mt_w * rt->mt_h; + w[8] = va[SGX_RT_TAILS]; + w[9] = rt->tail_size; + w[10] = rt->tail_size * rt->ncores; + w[11] = (0xfffff000u + (rt->h << 12)) | (rt->w - 1); + w[21] = rt->w; + w[22] = rt->h; + w[27] = va[SGX_RT_REGIONS0]; + w[28] = rt->region_size; + w[29] = rt->region_size * rt->ncores; + /* the A6's payload has two more words before these */ + w[rt->rc2 ? 53 : 51] = blk_va; + w[rt->rc2 ? 54 : 52] = va[SGX_RT_DETAILS]; + w[rt->rc2 ? 55 : 53] = va[SGX_RT_DETAILS] + SGX_RT_DETAILS_ENTRY(rt->rc2); +} + +/* as 0x80bfca20 builds it (tools/sgx/rgen.py's ta_cmd()) */ +void +sgx_rt_ta_cmd(const struct sgx_rt *rt, const uint32_t va[SGX_RT_NBUF], uint32_t blk_va, + uint32_t *cmd) +{ + uint32_t w[56]; + const unsigned b = rt->rc2 ? 53 : 51; + + sgx_rt_payload(rt, va, blk_va, w); + cmd[0x50 / 4] = w[b]; + cmd[0x54 / 4] = w[b + 1]; + cmd[0x58 / 4] = w[b + 2]; + for (unsigned i = 0; i < 4; i++) + cmd[0xc0 / 4 + i] = w[4 + i]; + for (unsigned c = 0; c < rt->ncores; c++) { + cmd[0xdc / 4 + c] = w[27] + c * w[28]; + cmd[0xec / 4 + c] = w[8] + c * w[9]; + } + cmd[0x104 / 4] = w[11]; + cmd[0x114 / 4] = rt->big; +} diff --git a/src/gallium/drivers/sgx/sgx_rt.h b/src/gallium/drivers/sgx/sgx_rt.h new file mode 100644 index 00000000000..a318b7239fd --- /dev/null +++ b/src/gallium/drivers/sgx/sgx_rt.h @@ -0,0 +1,87 @@ +/* + * Copyright 2026 Project Cascadia + * SPDX-License-Identifier: MIT + * + * Render target data (docs/research/p105-mesa.md, M10): what the kext + * computes for a render target of a size, in C -- the buffers the TA and + * the 3D pass keep their state in, what the CPU writes into them, and the + * words of the 3D register block and the TA command that point at them. + * No Mesa headers: the host test (mesa/host/rt-test.py) builds it alone. + */ +#ifndef SGX_RT_H +#define SGX_RT_H + +#include +#include + +/* the TA's requests are addressed from here: the state buffer has to be + * within 256 MiB above it (the 3D block's +0x88) */ +#define SGX_RT_TA_BASE 0x87800000u +#define SGX_RT_MAX_CORES 4 +#define SGX_RT_MAX_SIZE 4096 + +/* the buffers, in the kext's order of allocation */ +enum sgx_rt_buf { + SGX_RT_CONTEXT, /* areas the microkernel keeps, two per copy and two per core */ + SGX_RT_REGIONS0, /* the region arrays, one per core, for copy 0 */ + SGX_RT_REGIONS1, /* ... and for copy 1 */ + SGX_RT_TAILS, /* the tail pointers, per core */ + SGX_RT_DETAILS, /* the render details: two copies, then each one's first regions */ + SGX_RT_STATE, /* the state buffer: two objects, a stream entry per region */ + SGX_RT_NBUF, +}; + +struct sgx_rt { + uint32_t w, h, ncores; + bool rc2; /* the A6's kext (SGXDriver543RC2, S5L8950X) */ + uint32_t tiles_x, tiles_y; /* 32 x 32 pixels */ + bool big; /* a side over 2048 */ + uint32_t mt_w, mt_h; /* a macrotile's tiles, multiples of 4 */ + uint32_t mt_across, mt_down; /* macrotiles: 2 x 2 */ + uint32_t regions; /* the macrotiles' tiles, padded */ + uint32_t region_size, tail_size; /* bytes per core */ + uint32_t context[2 + 2 * SGX_RT_MAX_CORES]; /* offsets in SGX_RT_CONTEXT */ + uint32_t first[2]; /* each copy's first regions in the details */ + uint32_t state_clear, state_tile, state_regions; /* offsets in SGX_RT_STATE */ + uint32_t size[SGX_RT_NBUF]; /* bytes, as the kext asks for them */ +}; + +/* the layout for a W x H target, one sample, NCORES pixel pipes */ +bool sgx_rt_layout(struct sgx_rt *rt, unsigned w, unsigned h, unsigned ncores); +/* ... as the A6's kext lays it out (RC2): the render details' header 8 + * bytes shorter (entries at +0x18 and +0x9c), no per-region state stream, + * the 3D block's words from 0x8c on 4 later and from 0xfc on 8 later, + * iOS's payload 57 words (docs/a6/n42-gpu-sgx.md in linux-a9) */ +bool sgx_rt_layout_rc2(struct sgx_rt *rt, unsigned w, unsigned h, unsigned ncores, bool rc2); + +/* the 3D register block: where the A5's word at OFF is on this layout, + * and its size */ +static inline unsigned +sgx_rt_blk_off(bool rc2, unsigned off) +{ + return !rc2 || off < 0x8c ? off : off < 0xfc ? off + 4 : off + 8; +} +#define SGX_RT_BLOCK_SIZE(rc2) ((rc2) ? 0x168u : 0x160u) +/* the render details' entry 0 (entry 1 is 0x84 bytes on) */ +#define SGX_RT_DETAILS_ENTRY(rc2) ((rc2) ? 0x18u : 0x20u) + +/* what the CPU writes: the render details and the state buffer, whole + * (SGX_RT_DETAILS and SGX_RT_STATE bytes), for the buffers at VA; the + * others start as zeros */ +void sgx_rt_fill(const struct sgx_rt *rt, const uint32_t va[SGX_RT_NBUF], uint32_t *details, + uint32_t *state); + +/* the render target's words in a render's 3D register block (the rest are + * the GL driver's) */ +void sgx_rt_block3d(const struct sgx_rt *rt, const uint32_t va[SGX_RT_NBUF], uint32_t *blk); + +/* the words of iOS's render payload the kext fills in (w[n] is word n), + * with the 3D block at BLK_VA */ +void sgx_rt_payload(const struct sgx_rt *rt, const uint32_t va[SGX_RT_NBUF], uint32_t blk_va, + uint32_t *w); + +/* and the TA command's words that come from them */ +void sgx_rt_ta_cmd(const struct sgx_rt *rt, const uint32_t va[SGX_RT_NBUF], uint32_t blk_va, + uint32_t *cmd); + +#endif diff --git a/src/gallium/drivers/sgx/sgx_screen.c b/src/gallium/drivers/sgx/sgx_screen.c new file mode 100644 index 00000000000..b9c6f7b5bbb --- /dev/null +++ b/src/gallium/drivers/sgx/sgx_screen.c @@ -0,0 +1,466 @@ +/* + * Copyright 2026 Project Cascadia + * SPDX-License-Identifier: MIT + * + * The screen: what the SGX543MP2 offers to the GL state tracker. The caps + * are a GLES 2.0 part's; nothing here draws yet (docs/research/p105-mesa.md, + * M12-M14) -- clears do, through the template frame. + */ +#include "sgx_screen.h" +#include "sgx_compiler.h" + +#include + +#include "compiler/nir/nir.h" +#include "pipe/p_defines.h" +#include "util/format/u_format.h" +#include "util/log.h" +#include "util/os_time.h" +#include "util/u_debug.h" +#include "util/u_memory.h" +#include "util/u_screen.h" + +#include "sgx_context.h" +#include "sgx_frame.h" +#include "sgx_resource.h" + +static const struct nir_shader_compiler_options sgx_nir_options = { + /* (M44) integers the hardware's own (sgx_compiler.c): what it has not + * built from what it has -- the high half of a product from 16-bit + * ones (nir_lower_alu), the bit fields from shifts and masks */ + .lower_mul_high = true, + .lower_bitfield_extract = true, + .lower_bitfield_insert = true, + .lower_bitfield_reverse = true, + .lower_bit_count = true, + .lower_ifind_msb = true, + .lower_ufind_msb = true, + .lower_find_lsb = true, + .lower_isign = true, + .lower_hadd = true, + .lower_uadd_sat = true, + .lower_iadd_sat = true, + .lower_mul_2x32_64 = true, + .lower_scmp = true, + .lower_pack_half_2x16 = true, + .lower_pack_unorm_2x16 = true, + .lower_pack_snorm_2x16 = true, + .lower_pack_unorm_4x8 = true, + .lower_pack_snorm_4x8 = true, + .lower_unpack_half_2x16 = true, + .lower_unpack_unorm_2x16 = true, + .lower_unpack_snorm_2x16 = true, + .lower_unpack_unorm_4x8 = true, + .lower_unpack_snorm_4x8 = true, + .scalarize_ddx = true, + .lower_fdiv = true, + /* rectangle textures' coordinates scaled by load_texture_scale (M35) */ + .has_texture_scaling = true, + .lower_fmod = true, + .lower_fpow = true, + .lower_fsat = false, + /* the fragment compiler has ffract and builds the rest on it (M13c); + * ftrunc (int()) is sgx_compiler.c's lower_ftrunc's, after + * nir_lower_int_to_float has made its own (M31) */ + .lower_ffloor = true, + .lower_fceil = true, + .lower_ftrunc = false, + .lower_fround_even = true, + .lower_fsign = true, + .lower_sincos = true, + .lower_flrp32 = true, + /* no ffma_weak kept: products and sums apart (float_mul_add32 0, what + * lower_ffma32 was before Mesa 27) */ + .float_mul_add32 = 0, + .lower_insert_byte = true, + .lower_insert_word = true, + .lower_extract_byte = true, + .lower_extract_word = true, + .lower_uniforms_to_ubo = false, + .force_indirect_unrolling = nir_var_all, + .force_indirect_unrolling_sampler = true, + .max_unroll_iterations = 32, + .support_indirect_inputs = 0, + .support_indirect_outputs = 0, +}; + +static void +sgx_screen_destroy(struct pipe_screen *pscreen) +{ + struct sgx_screen *screen = sgx_screen(pscreen); + + sgx_frame_destroy(screen->frame); + sgx_device_fini(&screen->dev); + simple_mtx_destroy(&screen->frame_lock); + slab_destroy_parent(&screen->transfer_pool); + FREE(screen); +} + +static const char * +sgx_get_name(struct pipe_screen *pscreen) +{ + /* the A5's MP2, the A6's MP3 (the kernel counts the cores) */ + return sgx_screen(pscreen)->dev.num_cores == 3 ? "PowerVR SGX543MP3" : "PowerVR SGX543MP2"; +} + +static const char * +sgx_get_vendor(struct pipe_screen *pscreen) +{ + return "Project Cascadia"; +} + +static const char * +sgx_get_device_vendor(struct pipe_screen *pscreen) +{ + return "Imagination Technologies"; +} + +static int +sgx_get_screen_fd(struct pipe_screen *pscreen) +{ + return sgx_screen(pscreen)->dev.fd; +} + +static bool +sgx_is_format_supported(struct pipe_screen *pscreen, enum pipe_format format, + enum pipe_texture_target target, unsigned sample_count, + unsigned storage_sample_count, unsigned usage) +{ + const struct util_format_description *desc = util_format_description(format); + + if (MAX2(1, sample_count) != MAX2(1, storage_sample_count) || sample_count > 1) + return false; + switch (target) { + case PIPE_BUFFER: + case PIPE_TEXTURE_1D: /* a 2D texture one texel high (lower_1d) */ + case PIPE_TEXTURE_2D: + case PIPE_TEXTURE_RECT: + case PIPE_TEXTURE_CUBE: + break; + default: + return false; + } + /* (the packed float and shared exponent formats: sampled, as half + * floats, M43) */ + if (!desc || (desc->layout != UTIL_FORMAT_LAYOUT_PLAIN && + !((usage & ~PIPE_BIND_SAMPLER_VIEW) == 0 && + (format == PIPE_FORMAT_R11G11B10_FLOAT || + format == PIPE_FORMAT_R9G9B9E5_FLOAT)) && + !((usage & ~(PIPE_BIND_SAMPLER_VIEW | PIPE_BIND_RENDER_TARGET)) == 0 && + format == PIPE_FORMAT_R11G11B10_FLOAT))) + return false; + + /* what the pixel back end writes linear (the framebuffer's format) */ + if (usage & (PIPE_BIND_RENDER_TARGET | PIPE_BIND_DISPLAY_TARGET | + PIPE_BIND_SCANOUT | PIPE_BIND_SHARED)) { + /* (M43: R and RG of bytes too -- sgx_frame.c's rt_format; not for + * the screen) */ + if (format != PIPE_FORMAT_B8G8R8A8_UNORM && format != PIPE_FORMAT_B8G8R8X8_UNORM && + ((usage & (PIPE_BIND_DISPLAY_TARGET | PIPE_BIND_SCANOUT | PIPE_BIND_SHARED)) || + (format != PIPE_FORMAT_R8_UNORM && format != PIPE_FORMAT_R8G8_UNORM && + format != PIPE_FORMAT_I8_UNORM && format != PIPE_FORMAT_L8_UNORM && + format != PIPE_FORMAT_L8A8_UNORM && format != PIPE_FORMAT_A8_UNORM && + format != PIPE_FORMAT_R16G16B16A16_FLOAT && format != PIPE_FORMAT_R16G16_FLOAT && + format != PIPE_FORMAT_R16G16B16X16_FLOAT && + format != PIPE_FORMAT_B8G8R8A8_SRGB && format != PIPE_FORMAT_B8G8R8X8_SRGB && + format != PIPE_FORMAT_R8G8B8A8_UNORM && format != PIPE_FORMAT_R8G8B8A8_SRGB && + format != PIPE_FORMAT_R16_FLOAT && format != PIPE_FORMAT_R32_FLOAT && + format != PIPE_FORMAT_R32G32_FLOAT && format != PIPE_FORMAT_R11G11B10_FLOAT))) + return false; + } + if (usage & PIPE_BIND_DEPTH_STENCIL) { + /* (the tiles hold F32 depth whatever the format: M43's Z32F with or + * without stencil as the ISP stores them, ARB_depth_buffer_float) */ + if (format != PIPE_FORMAT_Z24_UNORM_S8_UINT && format != PIPE_FORMAT_Z16_UNORM && + format != PIPE_FORMAT_Z24X8_UNORM && format != PIPE_FORMAT_Z32_FLOAT && + format != PIPE_FORMAT_Z32_FLOAT_S8X24_UINT) + return false; + } + if (usage & PIPE_BIND_SAMPLER_VIEW) { + switch (format) { + case PIPE_FORMAT_R8G8B8A8_UNORM: + case PIPE_FORMAT_B8G8R8A8_UNORM: + case PIPE_FORMAT_B8G8R8X8_UNORM: + case PIPE_FORMAT_R8G8B8X8_UNORM: + case PIPE_FORMAT_B5G6R5_UNORM: + case PIPE_FORMAT_B4G4R4A4_UNORM: + case PIPE_FORMAT_B5G5R5A1_UNORM: + case PIPE_FORMAT_L8_UNORM: + case PIPE_FORMAT_A8_UNORM: + case PIPE_FORMAT_L8A8_UNORM: + case PIPE_FORMAT_I8_UNORM: /* (M43: U8, RRRR) */ + /* sRGB (EXT_texture_sRGB, GL 2.1): the bytes as they are, decoded + * by the program (sgx_blend_key's tex_srgb) */ + case PIPE_FORMAT_R8G8B8A8_SRGB: + case PIPE_FORMAT_B8G8R8A8_SRGB: + case PIPE_FORMAT_R8G8B8X8_SRGB: + case PIPE_FORMAT_B8G8R8X8_SRGB: + case PIPE_FORMAT_L8_SRGB: + case PIPE_FORMAT_L8A8_SRGB: + /* (M43) copied as half floats (sgx_resource_copy_f16): float, + * signed, 16-bit and the packed formats -- ARB_texture_float, + * EXT_texture_snorm, EXT_packed_float, EXT_texture_shared_exponent */ + case PIPE_FORMAT_R16_FLOAT: case PIPE_FORMAT_R16G16_FLOAT: + case PIPE_FORMAT_R16G16B16_FLOAT: case PIPE_FORMAT_R16G16B16A16_FLOAT: + case PIPE_FORMAT_R16G16B16X16_FLOAT: + case PIPE_FORMAT_A16_FLOAT: case PIPE_FORMAT_L16_FLOAT: case PIPE_FORMAT_L16A16_FLOAT: + case PIPE_FORMAT_I16_FLOAT: + case PIPE_FORMAT_R32_FLOAT: case PIPE_FORMAT_R32G32_FLOAT: + case PIPE_FORMAT_R32G32B32_FLOAT: case PIPE_FORMAT_R32G32B32A32_FLOAT: + case PIPE_FORMAT_R32G32B32X32_FLOAT: + case PIPE_FORMAT_A32_FLOAT: case PIPE_FORMAT_L32_FLOAT: case PIPE_FORMAT_L32A32_FLOAT: + case PIPE_FORMAT_I32_FLOAT: + case PIPE_FORMAT_R8_SNORM: case PIPE_FORMAT_R8G8_SNORM: case PIPE_FORMAT_R8G8B8A8_SNORM: + case PIPE_FORMAT_R8G8B8X8_SNORM: + case PIPE_FORMAT_A8_SNORM: case PIPE_FORMAT_L8_SNORM: case PIPE_FORMAT_L8A8_SNORM: + case PIPE_FORMAT_I8_SNORM: + case PIPE_FORMAT_R16_SNORM: case PIPE_FORMAT_R16G16_SNORM: + case PIPE_FORMAT_R16G16B16A16_SNORM: case PIPE_FORMAT_R16G16B16X16_SNORM: + case PIPE_FORMAT_A16_SNORM: case PIPE_FORMAT_L16_SNORM: case PIPE_FORMAT_L16A16_SNORM: + case PIPE_FORMAT_I16_SNORM: + case PIPE_FORMAT_R16_UNORM: case PIPE_FORMAT_R16G16_UNORM: + case PIPE_FORMAT_R16G16B16A16_UNORM: case PIPE_FORMAT_R16G16B16X16_UNORM: + case PIPE_FORMAT_A16_UNORM: case PIPE_FORMAT_L16_UNORM: case PIPE_FORMAT_L16A16_UNORM: + case PIPE_FORMAT_I16_UNORM: + case PIPE_FORMAT_R10G10B10A2_UNORM: case PIPE_FORMAT_B10G10R10A2_UNORM: + case PIPE_FORMAT_R10G10B10X2_UNORM: case PIPE_FORMAT_B10G10R10X2_UNORM: + case PIPE_FORMAT_R11G11B10_FLOAT: case PIPE_FORMAT_R9G9B9E5_FLOAT: + /* (and R and RG of bytes, RGBA8's copy: ARB_texture_rg's sampling) */ + case PIPE_FORMAT_R8_UNORM: case PIPE_FORMAT_R8G8_UNORM: + /* depth (GLES 2 has OES_depth_texture whatever the driver says): its + * copy F32 (M37, sgx_resource.c) */ + case PIPE_FORMAT_Z16_UNORM: + case PIPE_FORMAT_Z24X8_UNORM: + case PIPE_FORMAT_Z24_UNORM_S8_UINT: + case PIPE_FORMAT_Z32_FLOAT: + case PIPE_FORMAT_Z32_FLOAT_S8X24_UINT: + break; + default: + return false; + } + } + if (usage & PIPE_BIND_VERTEX_BUFFER) { + /* (M43: the packed 10-10-10-2 ones too -- ARB_vertex_type_2_10_10_10_rev + * -- which the fetch has not: the draw module's translate reads them, + * the vertex shader on the CPU, gpu_vs_can_draw) */ + if (!desc->is_array && format != PIPE_FORMAT_R32_FLOAT && + format != PIPE_FORMAT_R32G32_FLOAT && format != PIPE_FORMAT_R32G32B32_FLOAT && + format != PIPE_FORMAT_R32G32B32A32_FLOAT && + !(desc->nr_channels == 4 && desc->channel[0].size == 10 && + desc->channel[3].size == 2)) + return false; + } + if (usage & PIPE_BIND_INDEX_BUFFER) { + if (format != PIPE_FORMAT_R8_UINT && format != PIPE_FORMAT_R16_UINT && + format != PIPE_FORMAT_R32_UINT) + return false; + } + return true; +} + +static void +sgx_init_shader_caps(struct pipe_screen *pscreen) +{ + struct pipe_shader_caps *caps; + + caps = (struct pipe_shader_caps *)&pscreen->shader_caps[MESA_SHADER_VERTEX]; + caps->max_instructions = caps->max_alu_instructions = 16384; + caps->max_control_flow_depth = 32; + caps->max_inputs = 16; + caps->max_outputs = 10; /* position, point size, 8 varyings */ + /* OpenGL 3's 256 vec4s (1024 components, M43; GLES 2's 128 before), + * and the 8 clip planes and point size the state tracker keeps room for + * (it takes them out: M32) -- past sa's words they are in memory */ + caps->max_const_buffer0_size = (256 + 8 + 1) * 4 * sizeof(float); + /* (M43) uniform buffers 1..15, read from memory (VLDST), through an + * index too: ARB_uniform_buffer_object */ + caps->max_const_buffers = SGX_FRAME_MAX_UBOS; + caps->indirect_const_addr = true; + caps->max_temps = 64; + /* (M44) 32-bit integers, booleans 0 and ~0: the state tracker's + * NativeIntegers, its uniforms' ints as they are */ + caps->integers = true; + + caps = (struct pipe_shader_caps *)&pscreen->shader_caps[MESA_SHADER_FRAGMENT]; + caps->max_instructions = caps->max_alu_instructions = 16384; + caps->max_tex_instructions = caps->max_tex_indirections = 16384; + caps->max_control_flow_depth = 32; + caps->max_inputs = 8; + caps->max_outputs = 1; + /* 256 vec4s as the vertex shader's (64 before M43), and the alpha + * test's reference the state tracker keeps room for -- in memory past + * sa's words, as there */ + caps->max_const_buffer0_size = (256 + 1) * 4 * sizeof(float); + caps->max_const_buffers = SGX_FRAME_MAX_UBOS; + caps->indirect_const_addr = true; + caps->max_temps = 64; + caps->max_texture_samplers = caps->max_sampler_views = 8; + caps->integers = true; +} + +static void +sgx_init_screen_caps(struct pipe_screen *pscreen) +{ + struct pipe_caps *caps = (struct pipe_caps *)&pscreen->caps; + + u_init_pipe_screen_caps(pscreen, 1); + + /* GLES 2.0: ARB_texture_non_power_of_two and EXT_blend_equation_separate + * are what version.c asks for besides the shaders */ + caps->npot_textures = true; + /* rectangle textures as 2D ones, their coordinates scaled by the + * program (sgx_compiler.c, scale_sa) */ + caps->texrect = false; + caps->fragment_shader_derivatives = true; /* DSX, DSY (M33) */ + caps->generate_mipmap = true; /* by the CPU: sgx_resource.c */ + /* a buffer's map is its CPU copy, which the GPU's is brought up to date + * with at a draw, from what unmaps and flushes say was written (M26): + * nothing tells of a write through a persistent map */ + caps->buffer_map_persistent_coherent = false; + /* client arrays as they are: the CPU makes their vertices one stream + * itself (u_vbuf would copy each array into a buffer of its own first, + * and a draw's arrays would not follow the last one's) */ + caps->user_vertex_buffers = true; + /* glthread (M34): maps of buffers in the application's thread, kept + * while draws read them (sgx_resource.c) */ + caps->map_unsynchronized_thread_safe = true; + caps->allow_mapped_buffers_during_execution = true; + caps->native_fence_fd = true; + caps->blend_equation_separate = true; + caps->uma = true; + caps->max_render_targets = 1; + /* attachments of different sizes: a render over their common area, the + * depth buffer's tiles by its own size (M43: ARB_framebuffer_object) */ + caps->mixed_framebuffer_sizes = true; + /* a view's swizzle: the program's, after the lookup (M43: + * EXT_texture_swizzle; sgx_blend_key's tex_swizzle) */ + caps->texture_swizzle = true; + /* vertex colours as the program wrote them: the varyings go unclamped + * (F32 or F16), the state tracker clamps where GL says (M43: + * ARB_color_buffer_float) */ + caps->vertex_color_unclamped = true; + /* (M43) instanced draws, instanced attributes and primitive restart: + * the draw module's, the vertex shader on the CPU (gpu_vs_can_draw); + * conditional rendering: the query waited for (sgx_render_condition_ok) */ + caps->vs_instanceid = true; + caps->vertex_element_instance_divisor = true; + caps->primitive_restart = true; + caps->primitive_restart_fixed_index = true; + caps->conditional_render = true; + /* (M43) ARB_depth_clamp is not offered: the ISP clamps no depth, so a + * clamped draw was the draw module's -- its vertex shader on the CPU, + * its triangles cut at the depth range's ends (render_triangle). + * Programs that turn it on wherever it exists (PPSSPP: God of War 2% + * of its speed with it, 64% without) went many times slower than their + * own way without it, the one they take on OpenGL ES 2.0. + * SGX_DEPTH_CLAMP=1 offers it again. */ + caps->depth_clip_disable = debug_get_bool_option("SGX_DEPTH_CLAMP", false); + /* (M43) EXT_framebuffer_sRGB: a surface's format says whether the + * program encodes (sgx_blend_key's rt_srgb) */ + caps->dest_surface_srgb_control = true; + /* (M43) ARB_blend_func_extended: blending is the program's, the second + * colour another output nir_lower_blend takes in */ + caps->max_dual_source_render_targets = 1; + /* (M43) a uniform buffer's words read by VLDST: 64 KiB of them, from any + * multiple of 16 bytes */ + caps->max_constant_buffer_size = 65536; + caps->constant_buffer_offset_alignment = 16; + /* (M43) ARB_timer_query: the GPU's times are its fences' signal times + * (CLOCK_MONOTONIC, the kernel's), screen->get_timestamp the same clock */ + caps->query_timestamp = true; + caps->query_time_elapsed = true; + caps->timer_resolution = 1; + caps->max_texture_2d_size = 4096; /* iOS's on the A5; SGX_RT_MAX_SIZE */ + caps->max_texture_cube_levels = 12; + caps->max_texture_3d_levels = 0; + caps->max_texture_array_layers = 0; + caps->max_varyings = 8; + caps->fs_coord_origin_upper_left = true; + caps->fs_coord_pixel_center_half_integer = true; + caps->fs_position_is_sysval = true; + caps->fs_face_is_integer_sysval = true; + caps->texture_transfer_modes = 0; + caps->shareable_shaders = false; + caps->occlusion_query = true; /* M37: ISP state A bit 14 (sgx_context.c) */ + caps->alpha_test = false; + caps->flatshade = false; + caps->two_sided_color = false; + caps->clip_planes = 0; + caps->point_size_fixed = false; + caps->vendor_id = 0x1010; /* Imagination */ + caps->device_id = 0x0543; + caps->video_memory = 0; + caps->min_line_width = caps->min_line_width_aa = 1; + caps->min_point_size = caps->min_point_size_aa = 1; + caps->max_line_width = caps->max_line_width_aa = 16; + caps->max_point_size = caps->max_point_size_aa = 512; + caps->point_size_granularity = caps->line_width_granularity = 0.1f; + caps->max_texture_lod_bias = 15.0f; + /* (M44) GLSL 1.30: integers the hardware's own (sgx_compiler.c) -- the + * OpenGL version stays 2.1 until the rest of 3.0 is here */ + caps->glsl_feature_level = caps->glsl_feature_level_compatibility = 130; +} + +static uint64_t +sgx_get_timestamp(struct pipe_screen *pscreen) +{ + return os_time_get_nano(); +} + +struct pipe_screen * +sgx_screen_create(int fd, const struct pipe_screen_config *config, struct renderonly *ro) +{ + struct sgx_screen *screen = CALLOC_STRUCT(sgx_screen); + const char *pack; + + if (!screen) + return NULL; + if (!sgx_device_init(&screen->dev, fd)) { + FREE(screen); + return NULL; + } + + screen->base.destroy = sgx_screen_destroy; + screen->base.get_name = sgx_get_name; + screen->base.get_vendor = sgx_get_vendor; + screen->base.get_device_vendor = sgx_get_device_vendor; + screen->base.get_screen_fd = sgx_get_screen_fd; + screen->base.is_format_supported = sgx_is_format_supported; + screen->base.get_timestamp = sgx_get_timestamp; + screen->base.context_create = sgx_context_create; + for (unsigned i = 0; i <= MESA_SHADER_COMPUTE; i++) + screen->base.nir_options[i] = &sgx_nir_options; + /* (M46) vertex shaders: products and sums fused, FMAD's (sgx_compiler.c + * fma_) -- PPSSPP's transforms and lighting are dot products and sums + * of products; SGX_NO_VS_FMA=1: as the fragment shaders' */ + if (!getenv("SGX_NO_VS_FMA")) { + static struct nir_shader_compiler_options vs_options; + + vs_options = sgx_nir_options; + /* (fuse_ffma32 before Mesa 27; since then fmad, as i915, etnaviv and + * lima have it, which nir_to_tgsi takes for the draw module's MAD -- + * the compiler's own copy turns it into ffma: fmad_to_ffma) */ + vs_options.float_mul_add32 = nir_float_muladd_support_has_fmad | + nir_float_muladd_support_fuse; + screen->base.nir_options[MESA_SHADER_VERTEX] = &vs_options; + } + sgx_resource_screen_init(screen); + sgx_context_screen_init(screen); + + sgx_init_shader_caps(&screen->base); + sgx_init_screen_caps(&screen->base); + slab_create_parent(&screen->transfer_pool, sizeof(struct sgx_transfer), 16); + + simple_mtx_init(&screen->frame_lock, mtx_plain); + /* the A6's uniform branches in pixel programs (sgx_compiler.h) */ + sgx_compiler_pixels_apart = (screen->dev.rc2 && !getenv("SGX_PIXELS_TOGETHER")) || + getenv("SGX_PIXELS_APART"); + pack = getenv("SGX_PACK"); + screen->frame = sgx_frame_create(&screen->dev, pack ? pack : "/usr/local/lib/sgx2d"); + + mesa_logi("sgx: SGX543MP%u rev %u.%u.%u, %s", screen->dev.num_cores, + (screen->dev.core_rev >> 16) & 0xff, (screen->dev.core_rev >> 8) & 0xff, + screen->dev.core_rev & 0xff, + screen->frame ? "clears on the GPU" : "clears on the CPU"); + return &screen->base; +} diff --git a/src/gallium/drivers/sgx/sgx_screen.h b/src/gallium/drivers/sgx/sgx_screen.h new file mode 100644 index 00000000000..f4e7be44a22 --- /dev/null +++ b/src/gallium/drivers/sgx/sgx_screen.h @@ -0,0 +1,37 @@ +/* + * Copyright 2026 Project Cascadia + * SPDX-License-Identifier: MIT + */ +#ifndef SGX_SCREEN_H +#define SGX_SCREEN_H + +#include "pipe/p_screen.h" +#include "util/simple_mtx.h" +#include "util/slab.h" + +#include "sgx_device.h" + +struct renderonly; +struct sgx_frame; + +struct sgx_screen { + struct pipe_screen base; + struct sgx_device dev; + + /* sgx2d's template frame, for clears; NULL without one */ + struct sgx_frame *frame; + simple_mtx_t frame_lock; + + struct slab_parent_pool transfer_pool; +}; + +static inline struct sgx_screen * +sgx_screen(struct pipe_screen *p) +{ + return (struct sgx_screen *)p; +} + +struct pipe_screen *sgx_screen_create(int fd, const struct pipe_screen_config *config, + struct renderonly *ro); + +#endif diff --git a/src/gallium/drivers/sgx/sgx_template.c b/src/gallium/drivers/sgx/sgx_template.c new file mode 100644 index 00000000000..366267a502f --- /dev/null +++ b/src/gallium/drivers/sgx/sgx_template.c @@ -0,0 +1,343 @@ +/* + * Copyright 2026 Project Cascadia + * SPDX-License-Identifier: MIT + * + * The template frame, built at given addresses (docs/research/p105-mesa.md, + * M17): tools/sgx/frame.py's gl_window(), vdm_stream() and payload(), + * pds.py's program shapes, programs.py's code (as programs.py assembles it + * with usse.py), rgen.py's ta_cmd(), and the GL driver's words of the 3D + * register block as 0x80bf5eec copies them out of the render payload. + * Words whose meaning is not known keep the values GL gives them, as in + * frame.py. mesa/host/tmpl-test.py builds all of it at the pack's + * addresses and compares it with the pack. + */ +#include "sgx_template.h" +#include "sgx_rt.h" + +#include + +#define TA_BASE 0x87800000u + +/* ---- PDS programs, by shape (pds.py) ------------------------------------ */ + +#define END 0xaf000000u +#define DOUTU_ONLY 0x185u /* the program's only DOUT */ +#define DOUTU_AFTER 0x1a5u /* after DMA or attribute DOUTs */ +#define DOUTU_TEX 0x1b5u /* before the iterate and texture DOUTs that feed it */ +#define DOUTU_VERTEX 0x1f5u /* vertex programs (predicate 3) */ +#define DMA_ROW0 0x07018113u /* DMA: address and control word from data row 0 */ +#define ITERATE_W3 0x07040c12u /* iterate the coordinates, control: word 3 */ +#define ITERATE_BG 0x07000c02u /* the background object's iteration */ +#define TEXTURE_ROW1 0x07041004u /* texture fetch: the four state words of row 1 */ +#define ATTR_ROW0 0x070181a6u /* the state header's attribute DOUTs */ +#define ATTR_ROW1 0x070581a6u +#define FETCH_INDEX 0x67800072u /* vertex fetch: the index */ + +static uint32_t +pds_doutu(unsigned row, uint32_t kind, unsigned pred) +{ + return pred << 24 | row << 18 | kind; +} + +/* a program: the data words padded to rows of four, then the code */ +static unsigned +program(uint32_t *out, const uint32_t *data, unsigned ndata, const uint32_t *code, + unsigned ncode) +{ + unsigned rows = (ndata + 3) & ~3u; + + memset(out, 0, rows * 4); + memcpy(out, data, ndata * 4); + memcpy(out + rows, code, ncode * 4); + return rows + ncode; +} + +/* DMA words from src into the USSE's inputs (ctl: their count less one and + * where), then the program: state and constant loaders */ +static void +dma_then_usse(uint32_t *out, uint32_t src, uint32_t ctl, uint32_t doutu, uint32_t temps) +{ + const uint32_t data[6] = { src, ctl, 0, 0, doutu, temps }; + const uint32_t code[3] = { DMA_ROW0, pds_doutu(1, DOUTU_AFTER, 7), END }; + + program(out, data, 6, code, 3); +} + +/* a pixel program's PDS: start it, iterate the texture coordinates, fetch + * the texture (four state words) */ +static void +textured(uint32_t *out, uint32_t doutu, uint32_t temps, uint32_t iterate, const uint32_t tex[4]) +{ + const uint32_t data[8] = { doutu, temps, 0, iterate, tex[0], tex[1], tex[2], tex[3] }; + const uint32_t code[4] = { pds_doutu(0, DOUTU_TEX, 7), ITERATE_W3, TEXTURE_ROW1, END }; + + program(out, data, 8, code, 4); +} + +/* ---- USSE programs (programs.py) ---------------------------------------- */ + +#define PHAS 0xfa44070000000000ull /* a program's start, single phase */ +#define PHAS_NEXT 0xfa44000000000000ull /* | the next phase's code index */ + +/* the PDS has loaded the state words into pa0..: the dummy load every + * program that reads them starts with, the moves to o0.., out to the tiler */ +static const uint64_t state_2[] = { + PHAS, 0x488b0281a00c0000ull, 0xe9a30084a0000000ull, 0xf920000000000000ull, + 0x50811009a0000000ull, 0xfb274000a0200000ull, +}; +static const uint64_t state_4[] = { + PHAS, 0x488b0281a00c0000ull, 0xe9a30084a0000000ull, 0xf920000000000000ull, + 0x50813009a0000000ull, 0xfb274000a0200000ull, +}; +static const uint64_t state_21[] = { + PHAS, 0x488b0281a00c0000ull, 0xe9a30084a0000000ull, 0xf920000000000000ull, + 0x5081f009a0000000ull, 0x50814009a2000800ull, 0xfb274000a0200000ull, +}; +static const uint64_t bg_reload[] = { PHAS, 0x50850009a0000000ull }; /* o0 = pa0, end */ +static const uint64_t empty[] = { PHAS, 0xf804014000000000ull }; /* nop, end */ +static const uint64_t done[] = { PHAS, 0xf834800000000000ull }; /* emit the event */ +static const uint64_t eor[] = { /* r0 = r1 = 0, emit */ + PHAS, 0xfca0000000000000ull, 0xfca0000000200000ull, 0xfb26000081200000ull, +}; +/* two phases: the position completed (z 0, w 1.0 in pa10, pa11), then + * position and attributes moved to the outputs and emitted */ +static const uint64_t vertex[] = { + PHAS_NEXT, 0x488b0281a00c0000ull, 0xe9a30084a0000000ull, 0xf920000000000000ull, + 0xfca0f1c201600000ull, 0xfca4000201400000ull, + PHAS, 0xfa10000201010e01ull, 0x3880252183000080ull, 0xfa10000001010101ull, + 0x38801521830c0000ull, 0xfb275000a0200000ull, +}; +#define VERTEX_PHASE2 6 + +unsigned +sgx_tmpl_program(enum sgx_tmpl_prog p, uint32_t at, uint64_t *code) +{ + static const struct { const uint64_t *code; unsigned n; } progs[SGX_TP_N] = { +#define P(name, a) [name] = { a, sizeof(a) / sizeof(a[0]) } + P(SGX_TP_BG_RELOAD, bg_reload), P(SGX_TP_EMPTY_A, empty), P(SGX_TP_EMPTY_B, empty), + P(SGX_TP_EMPTY_C, empty), P(SGX_TP_EMPTY_D, empty), P(SGX_TP_STATE_2, state_2), + P(SGX_TP_STATE_4, state_4), P(SGX_TP_STATE_21, state_21), P(SGX_TP_DONE, done), + P(SGX_TP_EOR, eor), P(SGX_TP_VERTEX, vertex), +#undef P + }; + + memcpy(code, progs[p].code, progs[p].n * 8); + if (p == SGX_TP_VERTEX) + code[0] |= at + VERTEX_PHASE2; + return progs[p].n; +} + +uint32_t +sgx_tmpl_doutu(const struct sgx_tmpl *t, uint32_t va) +{ + return ((va - t->code_base) / 8) << 4 | 3; +} + +/* ---- the frame (frame.py) ----------------------------------------------- */ + +static uint32_t +tag5(uint32_t va) /* a PDS data pointer: bit 31 implied */ +{ + return 0x10000000 | ((va >> 4) & 0x07ffffff); +} + +static uint32_t +vdm4(uint32_t tag, uint32_t va) +{ + return tag << 28 | ((va >> 4) & 0x0fffffff); +} + +static uint32_t +f32(float x) +{ + uint32_t u; + + memcpy(&u, &x, 4); + return u; +} + +static uint32_t +last_tile(unsigned n) +{ + return (n + 31) / 32 - 1; +} + +/* the texture state of a pixel program block: iterate control, then + * {format, 0x0c << 24 | log2 w << 16 | log2 h, address, 0} */ +#define TEX_ITERATE 0x1fc01900u +#define TEX_FORMAT 0x03fe0000u +#define BG_ITERATE 0xf800u +#define TEMPS_TEXTURED 0xe +#define TEMPS_BG 0xa + +void +sgx_tmpl_pds(const struct sgx_tmpl *t, const uint32_t event[SGX_TMPL_EVENT_WORDS], + uint32_t *out) +{ + const uint32_t fb[4] = { + /* the target, linear, as the 2D engine reads it */ + (t->fb_stride / 4 - 2) << 16 | 0x0e90, 0xcc000000 | (t->fb_w - 1) << 12 | (t->fb_h - 1), + t->fb, 0x10000000, + }; + const uint32_t tex0[4] = { TEX_FORMAT, 0x0c030003, t->tex0, 0 }; + const uint32_t tex1[4] = { TEX_FORMAT, 0x0c020002, t->tex1, 0 }; + const uint32_t bg[8] = { + sgx_tmpl_doutu(t, t->prog[SGX_TP_BG_RELOAD]), TEMPS_BG, 0, BG_ITERATE, + fb[0], fb[1], fb[2], fb[3], + }; + const uint32_t bg_code[4] = { pds_doutu(0, DOUTU_ONLY, 7), ITERATE_BG, TEXTURE_ROW1, END }; + const uint32_t nothing = END; + + memset(out, 0, SGX_TMPL_PDS_SIZE); + /* the 3D pass: the GL driver's event program, its three programs -- + * end of render, end of tile, the rest -- and word 16 filled in */ + memcpy(out, event, SGX_TMPL_EVENT_WORDS * 4); + out[0] = sgx_tmpl_doutu(t, t->prog[SGX_TP_EOR]); + out[2] = sgx_tmpl_doutu(t, t->eot); + out[4] = sgx_tmpl_doutu(t, t->prog[SGX_TP_DONE]); + out[16] = 0x30000; + program(out + 0x100 / 4, NULL, 0, ¬hing, 1); + program(out + 0x120 / 4, bg, 8, bg_code, 4); + textured(out + 0x160 / 4, sgx_tmpl_doutu(t, t->pixel), TEMPS_TEXTURED, TEX_ITERATE, tex0); + dma_then_usse(out + 0x1c0 / 4, t->pds + 0x1a4, 4, + sgx_tmpl_doutu(t, t->prog[SGX_TP_EMPTY_C]), 2); + textured(out + 0x200 / 4, sgx_tmpl_doutu(t, t->pixel), TEMPS_TEXTURED, TEX_ITERATE, tex1); +} + +void +sgx_tmpl_state(const struct sgx_tmpl *t, uint32_t *out) +{ + /* the normalisation the constants' loaders DMA in: 2/255, 1/255, + * 2/65535, 1/65535 */ + const uint32_t norm[4] = { + f32(2.0f / 255), f32(1.0f / 255), f32(2.0f / 65535), f32(1.0f / 65535), + }; + const uint32_t tiles = last_tile(t->w) << 16 | last_tile(t->h); + const uint32_t header[10] = { + 0x2000, 0, 0, 0, tiles, 0x100, 0, 0, sgx_tmpl_doutu(t, t->prog[SGX_TP_STATE_2]), 0, + }; + const uint32_t header_code[6] = { + ATTR_ROW0, ATTR_ROW1, ATTR_ROW1, ATTR_ROW1, pds_doutu(2, DOUTU_AFTER, 7), END, + }; + const uint32_t tail[4] = { sgx_tmpl_doutu(t, t->prog[SGX_TP_EMPTY_A]), 2, 0, 0 }; + const uint32_t tail_code[2] = { pds_doutu(0, DOUTU_ONLY, 7), END }; + /* draw 0's whole state, 21 words: ISP state A and B (compare ALWAYS, no + * depth write, blending), the pixel program's loader, info and block, + * the tile clip, the viewport, the varyings' words */ + const uint32_t full[21] = { + 0x0000dfc7, 0x03d00300, 0x0000f000, 0x0e000000, tag5(t->pds + 0x1c0), 0x0803e000, + tag5(t->pds + 0x160), 0x80000000 | last_tile(t->w), last_tile(t->h), + f32(t->w / 2.0f), f32(t->w / 2.0f), f32(t->h / 2.0f), f32(t->h / 2.0f), + f32(0.5f), f32(0.5f), 0, 0x0a001000, f32(1e-5f), 0x00088000, 0x00000039, 0x00000003, + }; + /* a later draw's: mask 0x40 (the pixel program only), words 4..6 */ + const uint32_t delta[4] = { + 0x40, tag5(t->pds + 0x1c0), 0x0803e000, tag5(t->pds + 0x200), + }; + /* the vertex fetch: r g b a, u v, x y (f32), 32 bytes, at +0x1e0; + * control = first primary attribute << 8 | words - 1 */ + const uint32_t vb = t->state + 0x1e0; + const uint32_t fetch[16] = { + vb, 0x003, 32, 0, vb + 0x10, 0x401, 0, 0, vb + 0x18, 0x801, 0, 0, + sgx_tmpl_doutu(t, t->prog[SGX_TP_VERTEX]), 0, 0, 0, + }; + const uint32_t fetch_code[6] = { + FETCH_INDEX, 0x2f0091a3 | 1 << 16, 0x2f0091a3 | 5 << 16, 0x2f0091a3 | 9 << 16, + pds_doutu(3, DOUTU_VERTEX, 3), END, + }; + + memset(out, 0, SGX_TMPL_STATE_SIZE); + program(out, header, 10, header_code, 6); + program(out + 0x60 / 4, tail, 4, tail_code, 2); + memcpy(out + 0x78 / 4, norm, sizeof(norm)); + dma_then_usse(out + 0xa0 / 4, t->state + 0x78, 6, + sgx_tmpl_doutu(t, t->prog[SGX_TP_EMPTY_B]), 2); + memcpy(out + 0xe0 / 4, full, sizeof(full)); + dma_then_usse(out + 0x140 / 4, t->state + 0xe0, 20, + sgx_tmpl_doutu(t, t->prog[SGX_TP_STATE_21]), 0); + program(out + 0x180 / 4, fetch, 16, fetch_code, 6); + memcpy(out + 0x360 / 4, norm, sizeof(norm)); + dma_then_usse(out + 0x380 / 4, t->state + 0x360, 6, + sgx_tmpl_doutu(t, t->prog[SGX_TP_EMPTY_D]), 2); + memcpy(out + 0x3c0 / 4, delta, sizeof(delta)); + dma_then_usse(out + 0x3e0 / 4, t->state + 0x3c0, 3, + sgx_tmpl_doutu(t, t->prog[SGX_TP_STATE_4]), 0); +} + +void +sgx_tmpl_tail(const struct sgx_tmpl *t, uint32_t tail[5]) +{ + tail[0] = vdm4(4, t->state + 0x60); + tail[1] = 0x0800e100; + tail[2] = vdm4(6, t->state); + tail[3] = 0x1a022201; + tail[4] = 0xc0000000; +} + +/* rgen.py's ta_cmd(): one TA, first and last, from frame.py's payload -- + * w18..w20 the background object, w37 and w38 GL's */ +void +sgx_tmpl_ta_cmd(const struct sgx_tmpl *t, uint32_t vdm, uint32_t pb, uint32_t *c) +{ + memset(c, 0, SGX_TMPL_CMD_SIZE); + c[0x00 / 4] = SGX_TMPL_CMD_SIZE; + c[0x04 / 4] = 0x73; + c[0x08 / 4] = (t->pds + 0x100 - 0x80000000u) >> 4; /* its PDS program */ + c[0x0c / 4] = 0x0801e000; /* its info word */ + c[0x10 / 4] = tag5(t->pds + 0x120); /* its pixel program */ + c[0x14 / 4] = 0x0c000000; + c[0x20 / 4] = 1; + c[0x28 / 4] = pb; + c[0x64 / 4] = 1; + c[0xd0 / 4] = 0x400000; + c[0xd4 / 4] = vdm; + c[0xd8 / 4] = 0x1a2; + c[0xfc / 4] = 0x1e3ce508; + c[0x100 / 4] = 0x1e3ce508; + c[0x10c / 4] = 0x7fffffff; + c[0x110 / 4] = TA_BASE; + c[0x118 / 4] = 0x88; +} + +/* what 0x80bf5eec writes into the 3D register block from the payload GL + * hands the kernel (w12..w17 the 3D pass's PDS program, w23, w24, w36 GL's; + * w30..w34, w39, w42, w43 zero), and its constants */ +void +sgx_tmpl_block3d(const struct sgx_tmpl *t, uint32_t *blk) +{ + /* the A6's kext (0x80ad2798) moves the words from 0x8c on (sgx_rt.h): + * written here at the A5's offsets, then moved */ + uint32_t b[SGX_TMPL_BLOCK_SIZE / 4]; + + memset(b, 0, SGX_TMPL_BLOCK_SIZE); + b[0x10 / 4] = TA_BASE; + b[0x18 / 4] = 0x80; + b[0x1c / 4] = 0xf0000; /* 0xf0100 when w12 and w13 differ */ + b[0x24 / 4] = 0xee; + b[0x50 / 4] = 1; + b[0x54 / 4] = 0x322bcc77; /* 1e-8 */ + b[0x58 / 4] = 0x322bcc77; + b[0x80 / 4] = 0x3f800000; /* the depth tiles start at (register 0x4b8) */ + b[0x84 / 4] = 0x200 | 0x100; /* w23 | 0x100 */ + b[0x88 / 4] = 3 << 24; /* w24 << 24; the state buffer is the render target's */ + b[0x8c / 4] = 0x88; /* w36 */ + b[0x94 / 4] = 1; + b[0x98 / 4] = t->pds; /* w12: the 3D pass's pixel PDS program */ + b[0x9c / 4] = 5; /* w14: its data, in rows */ + b[0xa0 / 4] = 0x4000; /* w16: its info */ + b[0xcc / 4] = 0x2000000; + b[0xd4 / 4] = 0x2000000; + b[0xd8 / 4] = 0x200; + b[0xfc / 4] = t->pds; /* w13: the event program */ + b[0x100 / 4] = 5; /* w15 */ + b[0x104 / 4] = 0x4000; /* w17 */ + b[0x144 / 4] = 0x1800000; + + memset(blk, 0, SGX_RT_BLOCK_SIZE(t->rc2)); + for (unsigned i = 0; i < SGX_TMPL_BLOCK_SIZE / 4; i++) + blk[sgx_rt_blk_off(t->rc2, 4 * i) / 4] = b[i]; + /* the A6 GL driver's w37, new, for register 0x4cc beside w36's 0x4c8: + * GL's 0x88 like w36 (flight sgx2d1, 2026-11-29: sgx2d draws with it) */ + if (t->rc2) + blk[0x8c / 4] = 0x88; +} diff --git a/src/gallium/drivers/sgx/sgx_template.h b/src/gallium/drivers/sgx/sgx_template.h new file mode 100644 index 00000000000..f5760d92b1a --- /dev/null +++ b/src/gallium/drivers/sgx/sgx_template.h @@ -0,0 +1,81 @@ +/* + * Copyright 2026 Project Cascadia + * SPDX-License-Identifier: MIT + * + * The template frame, built (docs/research/p105-mesa.md, M17): what + * tools/sgx/frame.py, pds.py and programs.py put in sgx2d's pack, at + * addresses given -- the kernel's picks, so that every process has its + * own. No Mesa headers: the host test (mesa/host/tmpl-test.py) builds it + * at the pack's addresses and compares it with the pack, byte for byte. + */ +#ifndef SGX_TEMPLATE_H +#define SGX_TEMPLATE_H + +#include +#include + +/* the USSE programs the frame runs (programs.py) */ +enum sgx_tmpl_prog { + SGX_TP_BG_RELOAD, /* the background object: the tile as the target holds it */ + SGX_TP_EMPTY_A, /* nothing, where a PDS program needs one: the stream's tail */ + SGX_TP_EMPTY_B, /* ... the constants' loader */ + SGX_TP_EMPTY_C, /* ... the pixel program's secondary loader */ + SGX_TP_EMPTY_D, /* ... the later draws' constants */ + SGX_TP_STATE_2, /* N state words to the tiler */ + SGX_TP_STATE_4, + SGX_TP_STATE_21, + SGX_TP_DONE, /* the 3D pass's events */ + SGX_TP_EOR, + SGX_TP_VERTEX, /* the vertex shader of the frame's own vertices: r g b a u v x y */ + SGX_TP_N, +}; +#define SGX_TMPL_PROG_MAX 12 /* instructions */ +#define SGX_TMPL_EVENT_WORDS 42 /* the event program: 5 data rows, 22 instructions */ + +/* the PDS block (+0 event program, +0x100 nothing, +0x120 background, +0x160 + * and +0x200 pixel programs, +0x1c0 their secondary loader) and the state + * area (+0 the stream's tail state, +0xa0 constants, +0xe0 draw 0's state, + * +0x140 its program, +0x180 vertex fetch, +0x3c0 later draws' state) */ +#define SGX_TMPL_PDS_SIZE 0x240 +#define SGX_TMPL_STATE_SIZE 0x420 +#define SGX_TMPL_IDX_COUNT 8192 +#define SGX_TMPL_CMD_SIZE 0x120 +#define SGX_TMPL_BLOCK_SIZE 0x160 /* the A5's; the A6's is 0x168 (SGX_RT_BLOCK_SIZE) */ +#define SGX_TMPL_BLOCK_MAX 0x168 + +struct sgx_tmpl { + uint32_t code_base; /* USE code base 3 */ + uint32_t prog[SGX_TP_N]; /* where each program is */ + uint32_t eot; /* the end-of-tile program the event program names */ + uint32_t pixel; /* the pixel program of the frame's pixel blocks */ + uint32_t pds, state, idx; /* the PDS block, the state area, the index buffer */ + uint32_t tex0, tex1; /* the pixel programs' textures */ + uint32_t fb, fb_w, fb_h, fb_stride; /* the background's first target, pixels */ + unsigned w, h; /* the screen: the stream's tail covers its tiles */ + bool rc2; /* the A6's kext: its 3D block (sgx_rt.h) */ +}; + +/* a program's instructions (len returned), for it at code index 'at' (its + * address less the code base, / 8): the vertex program names its second + * phase */ +unsigned sgx_tmpl_program(enum sgx_tmpl_prog p, uint32_t at, uint64_t *code); + +/* the DOUTU word for code at va */ +uint32_t sgx_tmpl_doutu(const struct sgx_tmpl *t, uint32_t va); + +/* the PDS block, SGX_TMPL_PDS_SIZE bytes; event: the GL driver's event + * program (build/firmware/gl-event.pds, from the IPSW) */ +void sgx_tmpl_pds(const struct sgx_tmpl *t, const uint32_t event[SGX_TMPL_EVENT_WORDS], + uint32_t *out); +/* the state area, SGX_TMPL_STATE_SIZE bytes */ +void sgx_tmpl_state(const struct sgx_tmpl *t, uint32_t *out); +/* the VDM stream's end: the tail state, then the terminate word */ +void sgx_tmpl_tail(const struct sgx_tmpl *t, uint32_t tail[5]); +/* the TA command, SGX_TMPL_CMD_SIZE bytes, the render target's words left + * for sgx_rt_ta_cmd() */ +void sgx_tmpl_ta_cmd(const struct sgx_tmpl *t, uint32_t vdm, uint32_t pb, uint32_t *cmd); +/* the 3D register block's GL words, SGX_TMPL_BLOCK_SIZE bytes, the render + * target's left for sgx_rt_block3d() */ +void sgx_tmpl_block3d(const struct sgx_tmpl *t, uint32_t *blk); + +#endif diff --git a/src/gallium/drivers/sgx/sgx_usse.c b/src/gallium/drivers/sgx/sgx_usse.c new file mode 100644 index 00000000000..92da5044681 --- /dev/null +++ b/src/gallium/drivers/sgx/sgx_usse.c @@ -0,0 +1,861 @@ +/* + * Copyright 2026 Project Cascadia + * SPDX-License-Identifier: MIT + * + * The USSE encoder (sgx_usse.h). Fields are set by their bit positions; + * the names in the comments are what each field does, as iOS's programs + * show it (docs/research/p105-mesa.md, M13c). + */ +#include "sgx_usse.h" + +#include + +#include +#include + +/* v into bits hi..lo */ +static uint64_t +bits(uint64_t v, unsigned hi, unsigned lo) +{ + if (v >> (hi - lo + 1)) { + fprintf(stderr, "sgx_usse: %#llx does not fit bits %u:%u\n", (unsigned long long)v, hi, lo); + assert(!"a USSE field overflows"); + } + return v << lo; +} + +#define SKIPINV (1ull << 55) /* set on every instruction iOS's driver writes */ + +/* A source in the two-bit bank selects most operands have, with the + * extension bit beside them: temp, output, pa, sa; special in the + * extended set. */ +static void +src_bank(struct usse_reg r, unsigned *ext, unsigned *bank) +{ + switch (r.bank) { + case USSE_TEMP: *ext = 0; *bank = 0; break; + case USSE_OUTPUT: *ext = 0; *bank = 1; break; + case USSE_PA: *ext = 0; *bank = 2; break; + case USSE_SA: *ext = 0; *bank = 3; break; + case USSE_SPECIAL: *ext = 1; *bank = 1; break; + case USSE_IDX1: *ext = 1; *bank = 0; break; + case USSE_IMM: *ext = 1; *bank = 2; break; + case USSE_INTERNAL: *ext = 0; *bank = 0; break; /* the temporaries' top */ + default: assert(0); *ext = *bank = 0; break; + } +} + +/* (M44) a src0 (I32MAD2's, VMOV's test): temp, pa; output, sa extended */ +static void +src0_bank(struct usse_reg r, unsigned *ext, unsigned *bank) +{ + assert(r.bank == USSE_TEMP || r.bank == USSE_PA || r.bank == USSE_OUTPUT || + r.bank == USSE_SA || r.bank == USSE_INTERNAL); + *ext = r.bank == USSE_OUTPUT || r.bank == USSE_SA; + *bank = r.bank == USSE_PA || r.bank == USSE_SA; +} + +/* a destination: temp, output, pa; sa in the extended set */ +static void +dest_bank(struct usse_reg r, unsigned *ext, unsigned *bank) +{ + switch (r.bank) { + case USSE_TEMP: *ext = 0; *bank = 0; break; + case USSE_OUTPUT: *ext = 0; *bank = 1; break; + case USSE_PA: *ext = 0; *bank = 2; break; + case USSE_SA: *ext = 1; *bank = 0; break; + case USSE_INDEX: *ext = 1; *bank = 2; break; + case USSE_INTERNAL: *ext = 0; *bank = 0; break; + default: assert(0); *ext = *bank = 0; break; + } +} + +/* the 64-bit register a float operand names, and its lane -- (M47) an + * internal register's field is one of the six-bit fields' top four (60 + + * k), its lane any of four */ +static unsigned +pair(struct usse_reg r) +{ + if (r.bank == USSE_INTERNAL) + return 60 + (r.num >> 2); + return r.bank == USSE_SPECIAL ? r.num : r.num >> 1; +} + +static unsigned +lane(struct usse_reg r) +{ + if (r.bank == USSE_INTERNAL) + return r.num & 3; + return r.bank == USSE_SPECIAL ? 0 : r.num & 1; +} + +/* the same in a seven-bit field (VCOMP's): an internal register 124 + k */ +static unsigned +pair7(struct usse_reg r) +{ + return r.bank == USSE_INTERNAL ? 124 + (r.num >> 2) : pair(r); +} + +static unsigned +modifier(struct usse_reg r) /* none, -, |.|, -|.| */ +{ + return (unsigned)r.neg | (unsigned)r.abs << 1; +} + +uint64_t +usse_fop(enum usse_nmad_op op, struct usse_reg dest, struct usse_reg src1, + struct usse_reg src2) +{ + /* src1's swizzle: three bits a channel (x y z w 0 1 2 0.5), all four + * the lane it is in; src2's from a table, xxxx or yyyy */ + return usse_fop_sw(op, dest, src1, lane(src1) * 0x249, src2); +} + +/* (M46) V32NMAD with src1 through its swizzle sw1, three bits a channel -- + * USSE_SW_CONST(k): every channel the constant k (USSE_K_0, _1, _2, _HALF; + * src1's register is not read then, its modifiers still apply) */ +uint64_t +usse_fop_sw(enum usse_nmad_op op, struct usse_reg dest, struct usse_reg src1, unsigned sw1, + struct usse_reg src2) +{ + return usse_fop_ex(op, dest, 1u << lane(dest), src1, sw1, src2, lane(src2)); +} + +uint64_t +usse_fop_ex(enum usse_nmad_op op, struct usse_reg dest, unsigned mask, struct usse_reg src1, + unsigned sw1, struct usse_reg src2, unsigned sw2) +{ + unsigned dext, dbank, ext1, bank1, ext2, bank2; + + dest_bank(dest, &dext, &dbank); + src_bank(src1, &ext1, &bank1); + src_bank(src2, &ext2, &bank2); + assert(!src2.neg); + return bits(0x01, 63, 59) | SKIPINV | + bits(sw1 >> 10 & 3, 54, 53) | bits(dext, 51, 51) | bits(sw1 >> 9 & 1, 50, 50) | + bits(ext1, 49, 49) | bits(ext2, 48, 48) | bits(sw2, 47, 44) | + bits(mask, 42, 39) | /* the dest mask */ + bits(modifier(src1), 38, 37) | bits(src2.abs, 36, 36) | + bits(sw1 >> 7 & 3, 35, 34) | bits(dbank, 33, 32) | bits(bank1, 31, 30) | + bits(bank2, 29, 28) | bits(pair(dest), 27, 22) | bits(sw1 & 0x7f, 21, 15) | + bits(op, 14, 12) | bits(pair(src1), 11, 6) | bits(pair(src2), 5, 0); +} + +/* V16NMAD on four F16 at once (M38, iOS's SDL sprite: `mul.f16 pa0.xyzw, + * pa2.xyzw, pa0.xyzw`): the same fields as V32NMAD's, a register pair each + * operand, src1's swizzle xyzw (three bits a channel), src2's the table's + * xyzw (4), the mask all four */ +/* (M46) V16NMAD in full: dest's channels in mask (bit i channel i), src1 + * through sw1 -- three bits a channel, x y z w or the constants 0, 1, 2 and + * 0.5 (4..7, Vita3K's SwizzleChannel) -- with its negation and absolute + * value, src2 through sw2 (an index into Vita3K's table of swizzles: 4 is + * xyzw) with its absolute value */ +uint64_t +usse_hop_ex(enum usse_nmad_op op, struct usse_reg dest, unsigned mask, struct usse_reg src1, + unsigned sw1, struct usse_reg src2, unsigned sw2) +{ + unsigned dext, dbank, ext1, bank1, ext2, bank2; + + assert(!(dest.num & 1) && (src1.bank == USSE_SPECIAL || !(src1.num & 1)) && + !(src2.num & 1) && !src2.neg); + dest_bank(dest, &dext, &dbank); + src_bank(src1, &ext1, &bank1); + src_bank(src2, &ext2, &bank2); + return bits(0x02, 63, 59) | SKIPINV | + bits(sw1 >> 10 & 3, 54, 53) | bits(dext, 51, 51) | bits(sw1 >> 9 & 1, 50, 50) | + bits(ext1, 49, 49) | bits(ext2, 48, 48) | bits(sw2, 47, 44) | bits(mask, 42, 39) | + bits(modifier(src1), 38, 37) | bits(src2.abs, 36, 36) | + bits(sw1 >> 7 & 3, 35, 34) | bits(dbank, 33, 32) | bits(bank1, 31, 30) | + bits(bank2, 29, 28) | bits(pair(dest), 27, 22) | bits(sw1 & 0x7f, 21, 15) | + bits(op, 14, 12) | bits(pair(src1), 11, 6) | bits(pair(src2), 5, 0); +} + +uint64_t +usse_hop(enum usse_nmad_op op, struct usse_reg dest, struct usse_reg src1, + struct usse_reg src2) +{ + return usse_hop_ex(op, dest, 0xf, src1, 0 | 1 << 3 | 2 << 6 | 3 << 9, src2, 4); +} + +uint64_t +usse_fmad(struct usse_reg dest, struct usse_reg src0, struct usse_reg src1, + struct usse_reg src2) +{ + unsigned ext1, bank1, ext2, bank2, dext, dbank; + + /* dest and src0 without an extended bank: temp, output, pa; temp, pa + * (an internal register: the temporaries') */ + assert(dest.bank == USSE_TEMP || dest.bank == USSE_OUTPUT || dest.bank == USSE_PA || + dest.bank == USSE_INTERNAL); + assert((src0.bank == USSE_TEMP || src0.bank == USSE_PA || src0.bank == USSE_INTERNAL) && + !src0.neg); + dest_bank(dest, &dext, &dbank); + src_bank(src1, &ext1, &bank1); + src_bank(src2, &ext2, &bank2); + /* swizzles: xxxx or yyyy, from three tables that start the same way */ + return bits(0x00, 63, 59) | bits(0, 58, 58) /* F32 */ | SKIPINV | + bits(0, 53, 53) | bits(src0.abs, 50, 50) | bits(ext1, 49, 49) | bits(ext2, 48, 48) | + bits(lane(src2), 47, 45) | bits(0, 44, 44) | bits(1u << lane(dest), 42, 39) | + bits(modifier(src1), 38, 37) | bits(modifier(src2), 36, 35) | + bits(src0.bank == USSE_PA, 34, 34) | bits(dbank, 33, 32) | + bits(bank1, 31, 30) | bits(bank2, 29, 28) | bits(pair(dest), 27, 22) | + bits(lane(src1), 21, 20) | bits(lane(src0), 19, 18) | bits(pair(src0), 17, 12) | + bits(pair(src1), 11, 6) | bits(pair(src2), 5, 0); +} + +uint64_t +usse_fmad_ex(struct usse_reg dest, unsigned mask, struct usse_reg src0, unsigned sw0, + struct usse_reg src1, unsigned sw1, struct usse_reg src2, unsigned sw2) +{ + unsigned ext1, bank1, ext2, bank2, dext, dbank; + + assert(dest.bank == USSE_TEMP || dest.bank == USSE_OUTPUT || dest.bank == USSE_PA || + dest.bank == USSE_INTERNAL); + assert((src0.bank == USSE_TEMP || src0.bank == USSE_PA || src0.bank == USSE_INTERNAL) && + !src0.neg); + dest_bank(dest, &dext, &dbank); + src_bank(src1, &ext1, &bank1); + src_bank(src2, &ext2, &bank2); + return bits(0x00, 63, 59) | bits(0, 58, 58) /* F32 */ | SKIPINV | + bits(sw0 >> 2, 53, 53) | bits(src0.abs, 50, 50) | bits(ext1, 49, 49) | + bits(ext2, 48, 48) | bits(sw2, 47, 45) | bits(sw1 >> 2, 44, 44) | bits(mask, 42, 39) | + bits(modifier(src1), 38, 37) | bits(modifier(src2), 36, 35) | + bits(src0.bank == USSE_PA, 34, 34) | bits(dbank, 33, 32) | + bits(bank1, 31, 30) | bits(bank2, 29, 28) | bits(pair(dest), 27, 22) | + bits(sw1 & 3, 21, 20) | bits(sw0 & 3, 19, 18) | bits(pair(src0), 17, 12) | + bits(pair(src1), 11, 6) | bits(pair(src2), 5, 0); +} + +uint64_t +usse_fcomp(enum usse_comp_op op, struct usse_reg dest, struct usse_reg src) +{ + unsigned dext, dbank, ext, bank; + + dest_bank(dest, &dext, &dbank); + src_bank(src, &ext, &bank); + /* types 0 (F32) for dest (54:53) and source (40:39) */ + return bits(0x06, 63, 59) | SKIPINV | bits(dext, 51, 51) | bits(ext, 49, 49) | + bits(op, 42, 41) | bits(modifier(src), 38, 37) | bits(lane(src), 36, 35) | + bits(dbank, 33, 32) | bits(bank, 31, 30) | bits(pair7(dest), 27, 21) | + bits(pair7(src), 13, 7) | bits(1u << lane(dest), 3, 0); +} + +/* VMOV: kind 0 a move, 1 a conditional move; type 5 F32 */ +static uint64_t +vmov(unsigned kind, unsigned test, struct usse_reg dest, struct usse_reg src0, + struct usse_reg src1, struct usse_reg src2, unsigned swizzle) +{ + unsigned dext, dbank, ext1, bank1, ext2, bank2; + /* src0: temp, pa; output, sa extended */ + unsigned ext0 = src0.bank == USSE_OUTPUT || src0.bank == USSE_SA; + unsigned bank0 = src0.bank == USSE_PA || src0.bank == USSE_SA; + + dest_bank(dest, &dext, &dbank); + src_bank(src1, &ext1, &bank1); + src_bank(src2, &ext2, &bank2); + return bits(0x07, 63, 59) | SKIPINV | bits(test >> 1, 54, 54) | + bits(kind != 0, 53, 53) /* the swizzle on src0 too */ | bits(dext, 51, 51) | + bits(ext0, 50, 50) | bits(ext1, 49, 49) | bits(ext2, 48, 48) | bits(kind, 47, 46) | + bits(5, 42, 40) | bits(test & 1, 39, 39) | bits(swizzle, 38, 35) | + bits(bank0, 34, 34) | bits(dbank, 33, 32) | bits(bank1, 31, 30) | + bits(bank2, 29, 28) | bits(1u << lane(dest), 27, 24) | bits(pair(dest), 23, 18) | + bits(pair(src0), 17, 12) | bits(pair(src1), 11, 6) | bits(pair(src2), 5, 0); +} + +uint64_t +usse_fmov(struct usse_reg dest, struct usse_reg src) +{ + /* swizzle xxxx or yyyy: the source's lane, into the dest's */ + return vmov(0, 0, dest, usse_reg(USSE_TEMP, 0), src, usse_reg(USSE_TEMP, 0), lane(src)); +} + +uint64_t +usse_fmov2(struct usse_reg dest, struct usse_reg src) +{ + assert(!(dest.num & 1) && !(src.num & 1) && dest.bank != USSE_INTERNAL && + src.bank != USSE_INTERNAL); + /* vmov()'s word for x, its mask x and y, the swizzle xyzw */ + return (vmov(0, 0, dest, usse_reg(USSE_TEMP, 0), src, usse_reg(USSE_TEMP, 0), 4) & + ~bits(0xf, 27, 24)) | bits(3, 27, 24); +} + +bool +usse_fmovc(uint64_t *out, enum usse_test test, struct usse_reg dest, struct usse_reg src0, + struct usse_reg src1, struct usse_reg src2) +{ + /* (src0 in sa reads 0, M31) */ + if (lane(src0) != lane(src1) || lane(src1) != lane(src2) || + (src0.bank != USSE_TEMP && src0.bank != USSE_PA && src0.bank != USSE_OUTPUT)) + return false; + *out = vmov(1, test, dest, src0, src1, src2, lane(src1)); + return true; +} + +uint64_t +usse_limm(struct usse_reg dest, uint32_t value) +{ + unsigned dext, dbank; + + dest_bank(dest, &dext, &dbank); + assert(!dext); + /* the immediate: 31:26 in 49:44, 25:21 in 40:36, 20:0 in 20:0 */ + return 0xfca0000000000000ull | bits(value >> 26, 49, 44) | + bits(value >> 21 & 0x1f, 40, 36) | bits(dbank, 33, 32) | bits(dest.num, 27, 21) | + bits(value & 0x1fffff, 20, 0); +} + +uint64_t +usse_pack_unorm8(unsigned dest_o, struct usse_reg src) +{ + return usse_pack_unorm8_to(usse_reg(USSE_OUTPUT, dest_o), src); +} + +uint64_t +usse_pack_unorm8_to(struct usse_reg dest, struct usse_reg src) +{ + unsigned ext, bank, dext, dbank; + + assert(!(src.num & 1)); + src_bank(src, &ext, &bank); + dest_bank(dest, &dext, &dbank); + /* VPCK: source format 6 (F32), dest 0 (U8), mask xyzw, scale; channels + * x y z w from src (x y) and src + 2 (z w), the second source's bank + * the first's */ + return bits(0x08, 63, 59) | SKIPINV | bits(dext, 51, 51) | bits(ext, 49, 49) | + bits(ext, 48, 48) | bits(6, 43, 41) | bits(0, 40, 38) | bits(0xf, 37, 34) | + bits(dbank, 33, 32) | bits(bank, 31, 30) | bits(bank, 29, 28) | bits(dest.num, 27, 21) | + bits(3, 20, 19) | bits(1, 18, 18) | bits(1, 17, 16) | bits(2, 15, 14) | + bits(src.num >> 1, 13, 8) | bits(0, 7, 7) | bits((src.num >> 1) + 1, 6, 1); +} + +/* SGX_USSE_XOR_PACKF16 / _UNPACKF16=mask: bits flipped in those words (to + * find their encoding) */ +static uint64_t +usse_xor(const char *name) +{ + const char *e = getenv(name); + + return e ? strtoull(e, NULL, 0) : 0; +} + +/* VPCK F32 to F16 (M43): usse_pack_unorm8_to's word with dest format 5 + * (F16) and no scale -- F16 from src's pair and src + 2's, as mask says */ +static uint64_t +vpck_f32_to(unsigned fmt, struct usse_reg dest, struct usse_reg src, unsigned mask) +{ + unsigned ext, bank, dext, dbank; + + assert(!(src.num & 1)); + src_bank(src, &ext, &bank); + dest_bank(dest, &dext, &dbank); + return bits(0x08, 63, 59) | SKIPINV | bits(dext, 51, 51) | bits(ext, 49, 49) | + bits(ext, 48, 48) | bits(6, 43, 41) | bits(fmt, 40, 38) | bits(mask, 37, 34) | + bits(dbank, 33, 32) | bits(bank, 31, 30) | bits(bank, 29, 28) | + bits(dest.num, 27, 21) | bits(3, 20, 19) | bits(1, 17, 16) | bits(2, 15, 14) | + bits(src.num >> 1, 13, 8) | bits(0, 7, 7) | bits((src.num >> 1) + 1, 6, 1); +} + +uint64_t +usse_pack_f32x2(struct usse_reg dest, struct usse_reg src) +{ + return vpck_f32_to(6, dest, src, 0x3) ^ usse_xor("SGX_USSE_XOR_PACKF32"); +} + +uint64_t +usse_pack_f16(struct usse_reg dest, struct usse_reg src, unsigned mask) +{ + unsigned ext, bank, dext, dbank; + + assert(!(src.num & 1)); + src_bank(src, &ext, &bank); + dest_bank(dest, &dext, &dbank); + return (bits(0x08, 63, 59) | SKIPINV | bits(dext, 51, 51) | bits(ext, 49, 49) | + bits(ext, 48, 48) | bits(6, 43, 41) | bits(5, 40, 38) | bits(mask, 37, 34) | + bits(dbank, 33, 32) | bits(bank, 31, 30) | bits(bank, 29, 28) | + bits(dest.num, 27, 21) | bits(3, 20, 19) | bits(1, 17, 16) | bits(2, 15, 14) | + bits(src.num >> 1, 13, 8) | bits(0, 7, 7) | bits((src.num >> 1) + 1, 6, 1)) ^ + usse_xor("SGX_USSE_XOR_PACKF16"); +} + +/* VPCK F16 to F32 (M43): usse_unpack_unorm8's word with source format 5 + * (F16) and no scale -- channels chan, chan + 1 of the pair src: as for + * bytes, the select's low bit at 0, its high bit the second source's low + * bit (o1's halves are channels 2 and 3 of o0's pair, not o1's 0 and 1: + * glfmt's blend read o0 twice that way) */ +uint64_t +usse_unpack_f16(struct usse_reg dest, struct usse_reg src, unsigned chan) +{ + unsigned dext, dbank, ext, bank; + + assert(!(dest.num & 1) && !(src.num & 1) && (chan == 0 || chan == 2)); + dest_bank(dest, &dext, &dbank); + src_bank(src, &ext, &bank); + return (bits(0x08, 63, 59) | SKIPINV | bits(dext, 51, 51) | bits(ext, 49, 49) | + bits(1, 48, 48) | bits(5, 43, 41) | bits(6, 40, 38) | bits(3, 37, 34) | + bits(dbank, 33, 32) | bits(bank, 31, 30) | bits(2, 29, 28) | bits(dest.num, 27, 21) | + bits(3, 20, 19) | bits(chan + 1, 17, 16) | bits(2, 15, 14) | + bits(src.num >> 1, 13, 8) | bits(chan >> 1, 6, 1)) ^ + usse_xor("SGX_USSE_XOR_UNPACKF16"); +} + +/* VPCK from four F16 in a register pair (M38: iOS's `pck.u8.f16 o0.xyzw, + * pa0.xyzw scale`): source format 5, the channels x y z w of the one pair, + * no second source (bit 48: its bank the immediate) */ +uint64_t +usse_pack_unorm8_f16(struct usse_reg dest, struct usse_reg src) +{ + unsigned ext, bank, dext, dbank; + + assert(!(src.num & 1)); + src_bank(src, &ext, &bank); + dest_bank(dest, &dext, &dbank); + return bits(0x08, 63, 59) | SKIPINV | bits(dext, 51, 51) | bits(ext, 49, 49) | + bits(1, 48, 48) | bits(5, 43, 41) | bits(0, 40, 38) | bits(0xf, 37, 34) | + bits(dbank, 33, 32) | bits(bank, 31, 30) | bits(bank, 29, 28) | bits(dest.num, 27, 21) | + bits(3, 20, 19) | bits(1, 18, 18) | bits(1, 17, 16) | bits(2, 15, 14) | + bits(src.num >> 1, 13, 8); +} + +static uint64_t +smp(unsigned dim, enum usse_smp_out out, enum usse_smp_coord coord, struct usse_reg dest, + struct usse_reg coords, struct usse_reg state, enum usse_smp_lod mode, struct usse_reg lod) +{ + unsigned ext1, bank1, ext2 = 1, bank2 = 2, lodn = 0; /* no lod: immediate 0 */ + /* coords: temp, pa; output, sa extended */ + unsigned ext0 = coords.bank == USSE_OUTPUT || coords.bank == USSE_SA; + unsigned bank0 = coords.bank == USSE_PA || coords.bank == USSE_SA; + + assert(dest.bank == USSE_TEMP || dest.bank == USSE_PA); + assert(!(coords.num & 1) && !(state.num & 1)); + src_bank(state, &ext1, &bank1); + if (mode != USSE_SMP_NONE) { + src_bank(lod, &ext2, &bank2); + lodn = pair(lod); + } + /* skipinv clear, as iOS's sampling instructions have it; dimension + * (1 2D, 2 3D: t01, t04); data return channel 0 */ + return bits(0x1c, 63, 59) | bits(ext0, 50, 50) | bits(ext1, 49, 49) | bits(ext2, 48, 48) | + bits(out, 47, 46) | bits(dim, 43, 42) | bits(mode, 41, 40) | + bits(dest.bank == USSE_PA, 39, 39) | bits(coord, 36, 35) | bits(bank0, 34, 34) | + bits(bank1, 31, 30) | bits(bank2, 29, 28) | bits(dest.num, 27, 21) | + bits(coords.num >> 1, 20, 14) | bits(state.num >> 1, 13, 7) | bits(lodn, 6, 0); +} + +uint64_t +usse_smp2d(enum usse_smp_out out, enum usse_smp_coord coord, struct usse_reg dest, + struct usse_reg coords, struct usse_reg state, enum usse_smp_lod mode, + struct usse_reg lod) +{ + return smp(1, out, coord, dest, coords, state, mode, lod); +} + +uint64_t +usse_smp3d(enum usse_smp_out out, enum usse_smp_coord coord, struct usse_reg dest, + struct usse_reg coords, struct usse_reg state, enum usse_smp_lod mode, + struct usse_reg lod) +{ + return smp(2, out, coord, dest, coords, state, mode, lod); +} + +uint64_t +usse_unpack_unorm8(struct usse_reg dest, struct usse_reg src, unsigned chan) +{ + unsigned dext, dbank, ext, bank; + + assert(!(dest.num & 1) && (chan == 0 || chan == 2)); + dest_bank(dest, &dext, &dbank); + src_bank(src, &ext, &bank); + /* VPCK: source format 0 (U8), dest 6 (F32), mask xy, scale. A U8 source + * is named in 32-bit units (its low bit at 7). x reads channel chan -- + * the select's low bit at 0, its high bit the second source's low bit + * (an immediate here, as iOS's pck.f16.u8 has it) -- y reads chan + 1 */ + return bits(0x08, 63, 59) | SKIPINV | bits(dext, 51, 51) | bits(ext, 49, 49) | + bits(1, 48, 48) | bits(0, 43, 41) | bits(6, 40, 38) | bits(3, 37, 34) | + bits(dbank, 33, 32) | bits(bank, 31, 30) | bits(2, 29, 28) | bits(dest.num, 27, 21) | + bits(3, 20, 19) | bits(1, 18, 18) | bits(chan + 1, 17, 16) | bits(2, 15, 14) | + bits(src.num >> 1, 13, 8) | bits(src.num & 1, 7, 7) | bits(chan >> 1, 6, 1); +} + +uint64_t +usse_vtst_facing(unsigned pdst) +{ + /* iOS's word: bitwise ALU (3) op 0 (AND), src1 special 80, src2 the + * immediate 1, the zero test non-zero */ + return (0x488b0281600c2801ull & ~bits(3, 35, 34)) | bits(pdst, 35, 34); +} + +uint64_t +usse_limm_pred(struct usse_reg dest, uint32_t value, unsigned pred) +{ + return usse_limm(dest, value) | bits(pred, 43, 41); +} + +uint64_t +usse_vtst_bits(unsigned pdst, struct usse_reg src, bool eq) +{ + unsigned ext, bank; + + src_bank(src, &ext, &bank); + return (0x488b0281600c2801ull & ~(bits(3, 49, 48) | bits(3, 41, 40) | bits(3, 35, 34) | + bits(0xf, 31, 28) | bits(0x3fff, 13, 0))) | + bits(ext, 49, 49) | bits(ext, 48, 48) | bits(eq ? 1 : 2, 41, 40) | + bits(pdst, 35, 34) | bits(bank, 31, 30) | bits(bank, 29, 28) | + bits(src.num, 13, 7) | bits(src.num, 6, 0); +} + +uint64_t +usse_kill(unsigned pred) +{ + /* iOS's word less its end bit and its predicate */ + return (0xf9340426c0000280ull & ~USSE_END & ~bits(3, 42, 41)) | bits(pred, 42, 41); +} + +/* VBW's operation: Vita3K's op1 (bits 61:59) and op2 (bit 35) -- 2 and, + * or; 3 xor; 4 shl (rol with op2); 5 shr, asr (M44: each checked on the + * device, glldr --probe) */ +static uint64_t +vbw_op(enum usse_vbw_op op) +{ + static const uint8_t op1[] = { 2, 2, 3, 4, 5, 5 }, op2[] = { 0, 1, 0, 0, 0, 1 }; + + return bits(op1[op], 61, 59) | bits(op2[op], 35, 35); +} + +/* VBW with src2 the immediate (extended bank 2): its bits 15:14 at 37:36, + * 13:7 at 20:14, 6:0 at 6:0, rotated left by bits 42:38 (Vita3K's + * src2_rot) */ +uint64_t +usse_vbw_imm(enum usse_vbw_op op, struct usse_reg dest, struct usse_reg src1, unsigned imm, + unsigned rot) +{ + unsigned dext, dbank, ext, bank; + + dest_bank(dest, &dext, &dbank); + src_bank(src1, &ext, &bank); + return bits(1, 63, 62) | vbw_op(op) | SKIPINV | bits(dext, 51, 51) | bits(ext, 49, 49) | + bits(1, 48, 48) | bits(rot, 42, 38) | bits(imm >> 14, 37, 36) | bits(dbank, 33, 32) | + bits(bank, 31, 30) | bits(2, 29, 28) | bits(dest.num, 27, 21) | + bits(imm >> 7 & 0x7f, 20, 14) | bits(src1.num, 13, 7) | bits(imm & 0x7f, 6, 0); +} + +static uint64_t +vbw_logic(bool or_, struct usse_reg dest, struct usse_reg src1, unsigned imm) +{ + return usse_vbw_imm(or_ ? USSE_VBW_OR : USSE_VBW_AND, dest, src1, imm, 0); +} + +uint64_t +usse_vbw_or_rot(struct usse_reg dest, struct usse_reg src1, unsigned imm, unsigned rot) +{ + return usse_vbw_imm(USSE_VBW_OR, dest, src1, imm, rot); +} + +/* VBW, src2 a register; bit 43 inverts it (iOS's `and o0, c56, ~pa0`, `or + * o0, o0, ~o0`) */ +uint64_t +usse_vbw(enum usse_vbw_op op, struct usse_reg dest, struct usse_reg src1, struct usse_reg src2, + bool not2) +{ + unsigned dext, dbank, ext1, bank1, ext2, bank2; + + dest_bank(dest, &dext, &dbank); + src_bank(src1, &ext1, &bank1); + src_bank(src2, &ext2, &bank2); + return bits(1, 63, 62) | vbw_op(op) | SKIPINV | + bits(dext, 51, 51) | bits(ext1, 49, 49) | bits(ext2, 48, 48) | bits(not2, 43, 43) | + bits(dbank, 33, 32) | bits(bank1, 31, 30) | + bits(bank2, 29, 28) | bits(dest.num, 27, 21) | bits(src1.num, 13, 7) | + bits(src2.num, 6, 0); +} + +uint64_t +usse_pred(uint64_t w, unsigned pred) +{ + return (w & ~bits(7, 58, 56)) | bits(pred, 58, 56); +} + +/* I32MAD2 (Vita3K's i32mad2, sn 0): 11010 ppp - n ss d e r(src1 ext) + * c(src2 ext) b(src0 ext) ooo 00 i(signed) g(-src1) a(-src2) 0000 + * k(src0 bank) tt ff hh, then dest, src0, src1, src2 seven bits each */ +uint64_t +usse_imad(struct usse_reg dest, struct usse_reg src0, struct usse_reg src1, + struct usse_reg src2, bool is_signed) +{ + unsigned dext, dbank, ext0, bank0, ext1, bank1, ext2, bank2; + + dest_bank(dest, &dext, &dbank); + src0_bank(src0, &ext0, &bank0); + src_bank(src1, &ext1, &bank1); + src_bank(src2, &ext2, &bank2); + return bits(0x1a, 63, 59) | bits(dext, 51, 51) | bits(ext1, 49, 49) | bits(ext2, 48, 48) | + bits(ext0, 47, 47) | bits(is_signed, 41, 41) | bits(src1.neg, 40, 40) | + bits(src2.neg, 39, 39) | bits(bank0, 34, 34) | bits(dbank, 33, 32) | + bits(bank1, 31, 30) | bits(bank2, 29, 28) | bits(dest.num, 27, 21) | + bits(src0.num, 20, 14) | bits(src1.num, 13, 7) | bits(src2.num, 6, 0); +} + +/* VMOV of type 2 (INT32): registers in 32-bit units, six bits each */ +bool +usse_imovc(uint64_t *out, enum usse_test test, struct usse_reg dest, struct usse_reg src0, + struct usse_reg src1, struct usse_reg src2) +{ + unsigned dext, dbank, ext0, bank0, ext1, bank1, ext2, bank2; + + if (dest.num >= 64 || src0.num >= 64 || src1.num >= 64 || src2.num >= 64 || + (src0.bank != USSE_TEMP && src0.bank != USSE_PA && src0.bank != USSE_OUTPUT)) + return false; + dest_bank(dest, &dext, &dbank); + src0_bank(src0, &ext0, &bank0); + src_bank(src1, &ext1, &bank1); + src_bank(src2, &ext2, &bank2); + *out = bits(0x07, 63, 59) | SKIPINV | bits(test >> 1, 54, 54) | bits(dext, 51, 51) | + bits(ext0, 50, 50) | bits(ext1, 49, 49) | bits(ext2, 48, 48) | bits(1, 47, 46) | + bits(2, 42, 40) | bits(test & 1, 39, 39) | bits(bank0, 34, 34) | + bits(dbank, 33, 32) | bits(bank1, 31, 30) | bits(bank2, 29, 28) | + bits(1, 27, 24) | bits(dest.num, 23, 18) | bits(src0.num, 17, 12) | + bits(src1.num, 11, 6) | bits(src2.num, 5, 0); + return true; +} + +/* VTST (Vita3K's vtst): the ALU's operation (sel, op) on src1 and src2, + * its result's sign test (1 below 0) and zero test (1 zero, 2 not), both + * required (bit 39), into p; the result not written */ +static uint64_t +vtst(unsigned pdst, unsigned alu_sel, unsigned alu_op, unsigned prec, unsigned chan, + struct usse_reg src1, unsigned n1, struct usse_reg src2, unsigned n2, unsigned sign, + unsigned zero) +{ + unsigned ext1, bank1, ext2, bank2; + + src_bank(src1, &ext1, &bank1); + src_bank(src2, &ext2, &bank2); + return bits(0x09, 63, 59) | SKIPINV | bits(ext1, 49, 49) | bits(ext2, 48, 48) | + bits(prec, 47, 47) | bits(sign, 43, 42) | bits(zero, 41, 40) | + bits(1, 39, 39) | bits(chan, 38, 36) | bits(pdst, 35, 34) | bits(bank1, 31, 30) | + bits(bank2, 29, 28) | bits(alu_sel, 19, 18) | bits(alu_op, 17, 14) | + bits(n1, 13, 7) | bits(n2, 6, 0); +} + +uint64_t +usse_vtst_int(unsigned pdst, struct usse_reg src1, struct usse_reg src2, bool is_signed, bool eq) +{ + /* ALU 1, ISUB32 (14) or ISUBU32 (15) */ + return vtst(pdst, 1, is_signed ? 14 : 15, 0, 0, src1, src1.num, src2, src2.num, + eq ? 0 : 1, eq ? 1 : 0); +} + +bool +usse_vtst_f32(uint64_t *out, unsigned pdst, struct usse_reg src1, struct usse_reg src2, bool eq) +{ + /* ALU 0 at F32 precision, VSUB (14); the registers 64-bit ones, the + * channel tested their lane. Below 0 is the sign and not zero: -0 - 0 + * is -0, whose sign is set (faceforward of a -0 dot product) */ + if (lane(src1) != lane(src2)) + return false; + *out = vtst(pdst, 0, 14, 1, lane(src1), src1, pair(src1), src2, pair(src2), + eq ? 0 : 1, eq ? 1 : 2); + return true; +} + +/* VPCK of one channel, src2 the immediate 0: the channels' selects 3:2:1 + * as iOS's words have them, channel 0's (bit 0, and bit 7 for a 32-bit + * register's parity in a 16-bit source) given */ +static uint64_t +vpck1(unsigned sfmt, unsigned dfmt, unsigned mask, struct usse_reg dest, unsigned dest_n, + struct usse_reg src, unsigned src_n, unsigned sel0, unsigned sel1) +{ + unsigned ext, bank, dext, dbank; + + src_bank(src, &ext, &bank); + dest_bank(dest, &dext, &dbank); + return bits(0x08, 63, 59) | SKIPINV | bits(dext, 51, 51) | bits(ext, 49, 49) | + bits(1, 48, 48) | bits(sfmt, 43, 41) | bits(dfmt, 40, 38) | bits(mask, 37, 34) | + bits(dbank, 33, 32) | bits(bank, 31, 30) | bits(2, 29, 28) | bits(dest_n, 27, 21) | + bits(3, 20, 19) | bits(sel1, 17, 16) | bits(2, 15, 14) | bits(src_n >> 1, 13, 8) | + bits(src_n & 1, 7, 7) | bits(sel0, 0, 0); +} + +uint64_t +usse_cvt16_f32(struct usse_reg dest, struct usse_reg src, unsigned half, bool is_signed) +{ + /* S16 (4) or U16 (3) to F32 (6): src named in 32-bit units, the half + * by channel 0's select; the dest too, its first channel (mask x) the + * register named -- an odd one with mask x, not y (glldr --probe) */ + return vpck1(is_signed ? 4 : 3, 6, 1, dest, dest.num, src, src.num, half, 1); +} + +uint64_t +usse_cvt_f32_16(struct usse_reg dest, struct usse_reg src, unsigned half, bool is_signed) +{ + /* F32 (6) to S16 (4) or U16 (3): src's pair and lane (channels 0 and 1 + * both select it), the dest's half by the mask */ + return vpck1(6, is_signed ? 4 : 3, 1u << half, dest, dest.num, src, pair(src) << 1, + lane(src), lane(src)); +} + +/* VLDST: 111, op 1 (a load), no MOE expansion (with it, more than a word + * loaded nothing), src0 sa (extended bank 1), src2 the immediate 0 (not + * added), F32 words; src1 an immediate (extended bank 2) or a register */ +static uint64_t +ldr(struct usse_reg dest, unsigned base, unsigned src1_ext, unsigned src1_bank, unsigned src1, + unsigned count) +{ + assert(dest.bank == USSE_TEMP || dest.bank == USSE_PA); + assert(count >= 1 && count <= 16 && base < 128); + return bits(7, 63, 61) | bits(1, 60, 59) | SKIPINV | bits(1, 50, 50) | bits(src1_ext, 49, 49) | + bits(1, 48, 48) | bits(count - 1, 47, 44) | bits(dest.bank == USSE_PA, 39, 39) | + bits(1, 34, 34) | bits(src1_bank, 31, 30) | bits(2, 29, 28) | bits(dest.num, 27, 21) | + bits(base, 20, 14) | bits(src1, 13, 7); +} + +uint64_t +usse_ldr_imm(struct usse_reg dest, unsigned base, unsigned words, unsigned count) +{ + assert(words < 128); + return ldr(dest, base, 1, 2, words, count); +} + +uint64_t +usse_ldr_reg(struct usse_reg dest, unsigned base, struct usse_reg offset, unsigned count) +{ + unsigned ext, bank; + + src_bank(offset, &ext, &bank); + return ldr(dest, base, ext, bank, offset.num, count); +} + +uint64_t +usse_vbw_and(struct usse_reg dest, struct usse_reg src1, unsigned imm) +{ + return vbw_logic(false, dest, src1, imm); +} + +uint64_t +usse_vbw_or(struct usse_reg dest, struct usse_reg src1, unsigned imm) +{ + return vbw_logic(true, dest, src1, imm); +} + +uint64_t +usse_sop2(struct usse_reg dest, struct usse_reg src1, struct usse_reg src2, + const struct usse_sop2 *f) +{ + unsigned dext, dbank, ext1, bank1, ext2, bank2; + + dest_bank(dest, &dext, &dbank); + src_bank(src1, &ext1, &bank1); + src_bank(src2, &ext2, &bank2); + /* Vita3K's SOP2 (alu.cpp): 10000 pp c(cmod1) s n aa(asel1) d e r b + * m(cmod2) ooo(count) f(amod1) ll(asel2) ggg(csel1) hhh(csel2) i(amod2) + * tt kk jj qqqqqqq(dest) u(src1 mod) vv(cop) ww(aop) x y zzzzzzz(src1) + * AAAAAAA(src2) -- register numbers in 32-bit words */ + return bits(0x10, 63, 59) | bits(f->cmod1, 56, 56) | SKIPINV | bits(f->asel1, 53, 52) | + bits(dext, 51, 51) | bits(ext1, 49, 49) | bits(ext2, 48, 48) | + bits(f->cmod2, 47, 47) | bits(f->amod1, 43, 43) | bits(f->asel2, 42, 41) | + bits(f->csel1, 40, 38) | bits(f->csel2, 37, 35) | bits(f->amod2, 34, 34) | + bits(dbank, 33, 32) | bits(bank1, 31, 30) | bits(bank2, 29, 28) | + bits(dest.num, 27, 21) | bits(f->cop, 19, 18) | bits(f->aop, 17, 16) | + bits(src1.num, 13, 7) | bits(src2.num, 6, 0); +} + +/* (M47) VDP, Vita3K's vdp: 00011 ppp s c(clip) 0 o(dp4) d(dest ext) e(end) + * r(src1 ext) aa(increment) g(gpi0 abs) tt(repeat) n(nosched) wwww(mask) + * b(src1 neg) f(src1 abs) lll(clip plane) kk(dest bank) hh(src1 bank) + * ii(gpi0) jjjjjj(dest) zzzz(gpi0 swizzle) mmm qqq yyy xxx(src1's channels + * w z y x) uuuuuu(src1) */ +uint64_t +usse_vdp(struct usse_reg dest, unsigned mask, bool dp4, struct usse_reg src1, unsigned sw1, + unsigned gpi0, unsigned swg0) +{ + unsigned dext, dbank, ext1, bank1; + + assert(gpi0 < USSE_NINTERNAL); + dest_bank(dest, &dext, &dbank); + src_bank(src1, &ext1, &bank1); + return bits(0x03, 63, 59) | SKIPINV | bits(dp4, 52, 52) | bits(dext, 51, 51) | + bits(ext1, 49, 49) | bits(mask, 42, 39) | bits(src1.neg, 38, 38) | + bits(src1.abs, 37, 37) | bits(dbank, 33, 32) | bits(bank1, 31, 30) | + bits(gpi0, 29, 28) | bits(pair(dest), 27, 22) | bits(swg0, 21, 18) | + bits(sw1 >> 9 & 7, 17, 15) | bits(sw1 >> 6 & 7, 14, 12) | bits(sw1 >> 3 & 7, 11, 9) | + bits(sw1 & 7, 8, 6) | bits(pair(src1), 5, 0); +} + +/* (M47) VMAD, Vita3K's vmad: 00011 ppp s g(gpi1 swizzle ext) 1 o(mad4) + * d(dest ext) e(end) r(src1 ext) aa(increment) i(gpi0 abs) tt(repeat) + * n(nosched) wwww(mask) c(src1 neg) b(src1 abs) f(gpi1 neg) h(gpi1 abs) + * z(gpi0 swizzle ext) kk(dest bank) jj(src1 bank) ll(gpi0) mmmmmm(dest) + * qqqq(gpi0 swizzle) uuuu(gpi1 swizzle) vv(gpi1) x(gpi0 neg) y(src1 + * swizzle ext) AAAA(src1 swizzle) BBBBBB(src1) */ +uint64_t +usse_vmad(struct usse_reg dest, unsigned mask, unsigned gpi0, unsigned swg0, + struct usse_reg src1, unsigned sw1, unsigned gpi1, unsigned swg1, bool neg1) +{ + unsigned dext, dbank, ext1, bank1; + + assert(gpi0 < USSE_NINTERNAL && gpi1 < USSE_NINTERNAL); + dest_bank(dest, &dext, &dbank); + src_bank(src1, &ext1, &bank1); + return bits(0x03, 63, 59) | SKIPINV | bits(swg1 >> 4, 54, 54) | bits(1, 53, 53) | + bits(1, 52, 52) | bits(dext, 51, 51) | bits(ext1, 49, 49) | bits(mask, 42, 39) | + bits(src1.neg, 38, 38) | bits(src1.abs, 37, 37) | bits(neg1, 36, 36) | + bits(swg0 >> 4, 34, 34) | bits(dbank, 33, 32) | bits(bank1, 31, 30) | + bits(gpi0, 29, 28) | bits(pair(dest), 27, 22) | bits(swg0 & 15, 21, 18) | + bits(swg1 & 15, 17, 14) | bits(gpi1, 13, 12) | bits(sw1 >> 4, 10, 10) | + bits(sw1 & 15, 9, 6) | bits(pair(src1), 5, 0); +} + +uint64_t +usse_vtstmsk_f32(struct usse_reg dest, struct usse_reg src1, struct usse_reg src2, + enum usse_cmp cmp) +{ + /* the subtraction's sign test (1 below 0, 2 above), zero test (1 zero, + * 2 not), and whether both must pass (else either) */ + static const uint8_t sign[] = { 1, 1, 0, 0, 2, 2 }, zero[] = { 2, 1, 1, 2, 1, 2 }; + static const uint8_t both[] = { 1, 0, 1, 1, 0, 1 }; + unsigned dext, dbank, ext1, bank1, ext2, bank2; + + assert(!src1.abs && !src2.neg && !src2.abs); + dest_bank(dest, &dext, &dbank); + src_bank(src1, &ext1, &bank1); + src_bank(src2, &ext2, &bank2); + return bits(0x0f, 63, 59) | SKIPINV | bits(dext, 51, 51) | bits(src1.neg, 50, 50) | + bits(ext1, 49, 49) | bits(ext2, 48, 48) | bits(1, 47, 47) /* F32 */ | + bits(sign[cmp], 43, 42) | bits(zero[cmp], 41, 40) | bits(both[cmp], 39, 39) | + bits(1, 37, 36) /* mask type 1: ~0 or 0 */ | bits(dbank, 33, 32) | + bits(bank1, 31, 30) | bits(bank2, 29, 28) | bits(pair7(dest), 27, 21) | + bits(1, 20, 20) /* written back */ | bits(14, 17, 14) /* ALU 0's subtraction */ | + bits(pair7(src1), 13, 7) | bits(pair7(src2), 6, 0); +} + +bool +usse_nosched(uint64_t *w) +{ + switch (*w >> 59) { + case 0x00: /* VMAD2 */ + case 0x01: /* V32NMAD */ + case 0x02: /* V16NMAD */ + case 0x03: /* VMAD, VDP */ + case 0x06: /* VCOMP */ + case 0x07: /* VMOV */ + *w |= 1ull << 43; + return true; + case 0x08: /* VPCK */ + case 0x09: /* VTST */ + case 0x0a: /* VBW: and, or */ + case 0x0b: /* xor */ + case 0x0c: /* shl, rol */ + case 0x0d: /* shr, asr */ + case 0x0f: /* VTSTMSK */ + case 0x1a: /* I32MAD2 */ + *w |= 1ull << 54; + return true; + case 0x1f: + if ((*w >> 56) == 0xfc) { /* LIMM */ + *w |= 1ull << 54; + return true; + } + return false; + default: + return false; + } +} diff --git a/src/gallium/drivers/sgx/sgx_usse.h b/src/gallium/drivers/sgx/sgx_usse.h new file mode 100644 index 00000000000..d682aca57fa --- /dev/null +++ b/src/gallium/drivers/sgx/sgx_usse.h @@ -0,0 +1,323 @@ +/* + * Copyright 2026 Project Cascadia + * SPDX-License-Identifier: MIT + * + * An encoder for the SGX543's USSE instructions, the ones the compiler + * emits (docs/research/p105-mesa.md, M13c). Each instruction is 64 bits; + * the field positions were read off iOS's own programs (the M11 corpus) and + * are checked against them by mesa/host/usse-test.py. + * + * Registers are named in 32-bit units, as the PDS and VBW count them. The + * float instructions address 64-bit registers (a pair) and pick a lane in + * it -- x the even register, y the odd one -- through their masks and + * swizzles; the builders below take 32-bit numbers and work that out. + * + * No Mesa headers here, so the encoder can be built and tested on its own. + */ +#ifndef SGX_USSE_H +#define SGX_USSE_H + +#include +#include + +enum usse_bank { + USSE_TEMP, /* r: temporaries */ + USSE_OUTPUT, /* o: outputs */ + USSE_PA, /* pa: primary attributes (what the PDS iterated) */ + USSE_SA, /* sa: secondary attributes (uniforms) */ + USSE_SPECIAL, /* c: the hardware's constants (sources only) */ + USSE_INDEX, /* index1 (num 1), index2 (num 2): destinations only */ + USSE_IDX1, /* a source through index1: num = bank << 5 | offset (bank 0 + * temp, 1 output, 2 pa, 3 sa), 32-bit words */ + USSE_IMM, /* (M44) an integer instruction's immediate source, num + * 0..127 (I32MAD2's src1 and src2) */ + USSE_INTERNAL, /* (M47) an internal register's lane: num = 4 * register + + * lane, registers i0..i2 (F32 vec4s; the float + * instructions' fields name them as their bank's top + * temporaries). Shared by the tasks on a pipe: alive + * only across instructions with usse_nosched() */ +}; + +struct usse_reg { + uint8_t bank; /* enum usse_bank */ + uint8_t num; /* 32-bit register number */ + bool neg, abs; /* source modifiers, where the instruction has them */ +}; + +static inline struct usse_reg +usse_reg(enum usse_bank bank, unsigned num) +{ + struct usse_reg r = { (uint8_t)bank, (uint8_t)num, false, false }; + return r; +} + +#define USSE_NINTERNAL 3 /* i3's field writes nothing and reads i2 (M47) */ + +static inline struct usse_reg +usse_ireg(unsigned k, unsigned lane) +{ + struct usse_reg r = { (uint8_t)USSE_INTERNAL, (uint8_t)(4 * k + lane), false, false }; + + return r; +} + +#define USSE_END (1ull << 50) /* ends the program (not on PHAS) */ +#define USSE_PHAS 0xfa44070000000000ull +#define USSE_NOP_END 0xf804014000000000ull + +/* V32NMAD's second operation */ +enum usse_nmad_op { + USSE_NMAD_MUL, USSE_NMAD_ADD, USSE_NMAD_FRC, USSE_NMAD_DSX, + USSE_NMAD_DSY, USSE_NMAD_MIN, USSE_NMAD_MAX, USSE_NMAD_DP, +}; + +/* VCOMP's operation */ +enum usse_comp_op { USSE_COMP_RCP, USSE_COMP_RSQ, USSE_COMP_LOG2, USSE_COMP_EXP2 }; + +/* VMOV's conditional move: dest = src0 TEST 0 ? src1 : src2 */ +enum usse_test { USSE_TEST_EQ0, USSE_TEST_NE0, USSE_TEST_LT0, USSE_TEST_LE0 }; + +/* One F32 lane each: dest = op(src1, src2) (src1 may be negated and + * absolute, src2 absolute only). dest, src1, src2 any lane. */ +uint64_t usse_fop(enum usse_nmad_op op, struct usse_reg dest, struct usse_reg src1, + struct usse_reg src2); +/* (M46) src1 through a swizzle of its own: three bits a channel, x y z w + * or the constants below (Vita3K's SwizzleChannel) */ +#define USSE_K_0 4 +#define USSE_K_1 5 +#define USSE_K_2 6 +#define USSE_K_HALF 7 +#define USSE_SW_CONST(k) ((k) * 0x249) +uint64_t usse_fop_sw(enum usse_nmad_op op, struct usse_reg dest, struct usse_reg src1, + unsigned sw1, struct usse_reg src2); +/* (M47) V32NMAD in full: dest's lanes in mask (bit i lane i: an internal + * register takes all four, a 64-bit register x and y), src1 through sw1 + * (three bits a channel, as usse_fop_sw's: the four channels read src1's + * register and the three after it, an internal register's lanes), src2 + * through the swizzle table's sw2 (USSE_SW2_*: of a 64-bit register only x + * and y read anything, z and w read 0; an internal register's all four) */ +#define USSE_SW2_X 0 /* xxxx */ +#define USSE_SW2_XYZW 4 +#define USSE_SW2_ZWZW 11 +#define USSE_SW(x, y, z, w) ((x) | (y) << 3 | (z) << 6 | (w) << 9) +uint64_t usse_fop_ex(enum usse_nmad_op op, struct usse_reg dest, unsigned mask, + struct usse_reg src1, unsigned sw1, struct usse_reg src2, unsigned sw2); +/* dest = src0 * src1 + src2, F32, one lane; src0 a temporary or primary + * attribute, absolute only */ +uint64_t usse_fmad(struct usse_reg dest, struct usse_reg src0, struct usse_reg src1, + struct usse_reg src2); +/* (M47) VMAD2 in full: dest = src0 * src1 + src2 on the lanes of mask (x and + * y of a 64-bit register, an internal register's any), each source through + * its own table's swizzle -- src0: xxxx yyyy zzzz wwww xyzw yzxw xyww zwxy, + * src1: xxxx yyyy zzzz wwww xyzw xyyz yyww wyzw, src2: xxxx yyyy zzzz wwww + * xyzw xzww xxyz xyzz (indices 0..7) */ +uint64_t usse_fmad_ex(struct usse_reg dest, unsigned mask, struct usse_reg src0, unsigned sw0, + struct usse_reg src1, unsigned sw1, struct usse_reg src2, unsigned sw2); +/* (M47) VDP: dest = dot(src1, i) of three (dp3) or four (dp4) + * channels, into the lanes of mask (an internal register's, or x or y of a + * 64-bit register) -- src1 through sw1 (usse_fop_sw's channels, the + * constants 0, 1, 2, 0.5 among them; its register and the three after), + * with its negation and absolute value; the internal register through the + * swizzle table's swg0 (dp4: USSE_SW2_*, 15 xyz1; dp3: 4 xyz) */ +#define USSE_SWG_XYZ1 15 +uint64_t usse_vdp(struct usse_reg dest, unsigned mask, bool dp4, struct usse_reg src1, + unsigned sw1, unsigned gpi0, unsigned swg0); +/* (M47) VMAD: dest = i * src1 + i, four channels (mad4), each + * operand through the swizzle table (USSE_SW2_*; +16: the extended one -- + * 17 zwxy), dest's lanes in mask (an internal register's four, x and y of + * a 64-bit register); gpi1 negated with neg1 */ +#define USSE_SWX_ZWXY 17 +uint64_t usse_vmad(struct usse_reg dest, unsigned mask, unsigned gpi0, unsigned swg0, + struct usse_reg src1, unsigned sw1, unsigned gpi1, unsigned swg1, bool neg1); +/* (M47) VTSTMSK: dest = src1 CMP src2 ? ~0 : 0 (mask type 1), F32, for each + * lane of the 64-bit registers -- both of dest's lanes written; src1 may + * be negated. The comparisons IEEE's: -0 == 0, NaN unordered (only NE + * true). usse-probe.py found them (docs M47): the test is the + * subtraction's sign test and zero test, both (bit 39) or either */ +enum usse_cmp { USSE_CMP_LT, USSE_CMP_LE, USSE_CMP_EQ, USSE_CMP_NE, USSE_CMP_GE, USSE_CMP_GT }; +uint64_t usse_vtstmsk_f32(struct usse_reg dest, struct usse_reg src1, struct usse_reg src2, + enum usse_cmp cmp); +/* (M47) w with its nosched flag set: no other task runs on the pipe between + * this instruction and the next -- the internal registers, the pipe's, + * keep what this task put there (bit 43 of the vector instructions, 54 of + * VPCK, VTST, VBW, I32MAD2 and LIMM: each probed, docs M47). False when + * the instruction's flag is not known */ +bool usse_nosched(uint64_t *w); +/* dest = op(src), F32, one lane */ +uint64_t usse_fcomp(enum usse_comp_op op, struct usse_reg dest, struct usse_reg src); +/* dest = src, F32, one lane (any lanes) */ +uint64_t usse_fmov(struct usse_reg dest, struct usse_reg src); +/* (M47) dest's pair = src's pair, F32, both lanes (dest, src even) */ +uint64_t usse_fmov2(struct usse_reg dest, struct usse_reg src); +/* dest = src0 TEST 0 ? src1 : src2, F32, one lane; all four in the same + * lane (one swizzle serves them) -- false if they are not */ +bool usse_fmovc(uint64_t *out, enum usse_test test, struct usse_reg dest, + struct usse_reg src0, struct usse_reg src1, struct usse_reg src2); +/* dest = a 32-bit immediate (any bank but special) */ +uint64_t usse_limm(struct usse_reg dest, uint32_t value); +/* Texture sampling: SMP, then (before the result is read) WDF on the same + * data return channel. The texel lands in dest..: four registers as F32, + * two as F16, one raw. coords is a 64-bit register (F32: x the even + * register, y the odd one), state the texture's four state words (in sa, + * even), lod the bias or level for those modes (a register of its own). */ +enum usse_smp_out { USSE_SMP_RAW = 0, USSE_SMP_F16 = 2, USSE_SMP_F32 = 3 }; +enum usse_smp_coord { USSE_SMP_COORD_F32 = 0, USSE_SMP_COORD_F16 = 1 }; +enum usse_smp_lod { USSE_SMP_NONE, USSE_SMP_BIAS, USSE_SMP_LOD }; +uint64_t usse_smp2d(enum usse_smp_out out, enum usse_smp_coord coord, struct usse_reg dest, + struct usse_reg coords, struct usse_reg state, enum usse_smp_lod mode, + struct usse_reg lod); +/* the same with three coordinates (a cube map's direction: iOS's + * textureCube is smp3d, the corpus's t04), F32 in coords..coords + 2 */ +uint64_t usse_smp3d(enum usse_smp_out out, enum usse_smp_coord coord, struct usse_reg dest, + struct usse_reg coords, struct usse_reg state, enum usse_smp_lod mode, + struct usse_reg lod); +#define USSE_WDF0 0xf920000000000000ull /* wait for data return channel 0 */ + +/* dest, dest + 1 (F32, dest even) = channels chan, chan + 1 (0 or 2) of + * src's four 8-bit channels, scaled to [0, 1] -- the colour the tile holds, + * read out of o0 for blending. An F32 VPCK writes one 64-bit register: + * two of these make the four channels (gltex/glblend with + * SGX_DEBUG_FBFETCH: a mask of xyzw left z and w unwritten, and the first + * channel select reaches channel 2 but not 3). */ +uint64_t usse_unpack_unorm8(struct usse_reg dest, struct usse_reg src, unsigned chan); + +/* (M43) F32 channels (src, src + 1 and src + 2, src + 3; src even) as F16 + * into dest.. -- mask 0xf: four, dest and dest + 1 (a target of half + * floats' o0, o1: R G, B A); 0x3: two, dest. One instruction: o1 written + * by an instruction of its own never reached the target */ +uint64_t usse_pack_f16(struct usse_reg dest, struct usse_reg src, unsigned mask); +/* (M43) F32 channels x, y of the pair src into dest, dest + 1 at once (a + * VPCK F32 to F32): a target of two F32's o0, o1 */ +uint64_t usse_pack_f32x2(struct usse_reg dest, struct usse_reg src); +/* dest, dest + 1 (F32, dest even) = F16 channels chan, chan + 1 (0 or 2) + * of the four in src, src + 1 (src even): a target of half floats' tile, + * o0 and o1, read for blending */ +uint64_t usse_unpack_f16(struct usse_reg dest, struct usse_reg src, unsigned chan); + +/* (M38) four F16 at once, each a register pair (four F16): src1 op src2, + * channel for channel */ +uint64_t usse_hop(enum usse_nmad_op op, struct usse_reg dest, struct usse_reg src1, + struct usse_reg src2); +/* (M46) the same in full: dest's channels in mask, src1 through sw1 (three + * bits a channel: 0..3 x y z w, 4..7 the constants 0, 1, 2, 0.5) with its + * negation and absolute value, src2 through the table's swizzle sw2 (4: + * xyzw) */ +uint64_t usse_hop_ex(enum usse_nmad_op op, struct usse_reg dest, unsigned mask, + struct usse_reg src1, unsigned sw1, struct usse_reg src2, unsigned sw2); +/* dest = the four F16 of the pair src packed to 8 bits each, scaled from + * [0, 1] */ +uint64_t usse_pack_unorm8_f16(struct usse_reg dest, struct usse_reg src); + +/* o = four F32 values packed to 8 bits each, scaled from [0, 1]: + * src, src + 1 (a pair) and src + 2, src + 3; src even */ +uint64_t usse_pack_unorm8(unsigned dest_o, struct usse_reg src); +/* the same into another register (an output or a primary attribute) */ +uint64_t usse_pack_unorm8_to(struct usse_reg dest, struct usse_reg src); + +/* VTST: p = (src & src) != 0 (eq: == 0) -- the bits of a 32-bit + * register, in the form of iOS's facing test (`and(g16, #1) ne 0`): a + * boolean (0.0 or 1.0) tested. (An F32 test, src - #0 by VSUB, gave the + * wrong answers: M20.) */ +uint64_t usse_vtst_bits(unsigned pdst, struct usse_reg src, bool eq); +/* VBW, 32 bits: dest = src1 & imm or src1 | imm (imm 16 bits) -- moves of + * raw words (`or o0, sa14, #0`), the index registers (`shr index1, r0, #5`, + * iOS's c04_loop_break) */ +uint64_t usse_vbw_and(struct usse_reg dest, struct usse_reg src1, unsigned imm); +uint64_t usse_vbw_or(struct usse_reg dest, struct usse_reg src1, unsigned imm); +/* dest = src1 | (imm rotated left by rot): bits past an immediate's 16 + * (M32: an LDR offset's multiplier, 4 << 16) */ +uint64_t usse_vbw_or_rot(struct usse_reg dest, struct usse_reg src1, unsigned imm, unsigned rot); +/* VBW between two registers (M37, iOS's logic ops, es1 e03..e10): dest = + * src1 op src2, src2 inverted first with not2 (`and o0, c56, ~o0`: c56 is + * all ones). (M44) And the shifts, Vita3K's op1 4 and 5: by src2's value + * as it is -- 32 or more shifts every bit out (not taken modulo 32) */ +enum usse_vbw_op { + USSE_VBW_AND, USSE_VBW_OR, USSE_VBW_XOR, USSE_VBW_SHL, USSE_VBW_SHR, USSE_VBW_ASR, +}; +uint64_t usse_vbw(enum usse_vbw_op op, struct usse_reg dest, struct usse_reg src1, + struct usse_reg src2, bool not2); +/* (M44) the same with src2 an immediate: 16 bits rotated left by rot */ +uint64_t usse_vbw_imm(enum usse_vbw_op op, struct usse_reg dest, struct usse_reg src1, + unsigned imm, unsigned rot); +/* c56: the constant whose bits are all set; c0 is 0 (both as 32-bit + * words: VBW's, VMOV's integer moves) */ +#define USSE_ALL_ONES usse_reg(USSE_SPECIAL, 56) +#define USSE_ZERO usse_reg(USSE_SPECIAL, 0) + +/* (M44) an instruction run under an extended predicate (VBW, VMOV, VPCK, + * VTST, I32MAD2 -- bits 58:56; not LIMM's, usse_limm_pred()): 1 p0, 2 p1, + * 5 !p0, 6 !p1 */ +uint64_t usse_pred(uint64_t w, unsigned pred); + +/* (M44) I32MAD2, 32-bit integers: dest = src0 * src1 + src2, src1 and + * src2 negated by their neg, each an immediate (USSE_IMM, unsigned 0..127) + * or a register -- of src1 only the low 16 bits are multiplied, unsigned + * (0x12345 * 0x10001 is 0x2468a less 0x12345); src0 temp, pa, output or sa */ +uint64_t usse_imad(struct usse_reg dest, struct usse_reg src0, struct usse_reg src1, + struct usse_reg src2, bool is_signed); +/* (M44) VMOV of 32-bit integers (type INT32), conditional: dest = src0 + * TEST 0 ? src1 : src2, src0 tested as a signed integer (0x80000000 is + * below 0). Registers named in 32-bit units, 0..63 -- false (and no + * word) when one is past that, or src0 is not a temporary, pa or output */ +bool usse_imovc(uint64_t *out, enum usse_test test, struct usse_reg dest, + struct usse_reg src0, struct usse_reg src1, struct usse_reg src2); +/* (M44) VTST: p = src1 - src2 < 0 (lt) or == 0 (eq), as 32-bit + * integers, signed or not -- the hardware's comparison, right where the + * difference overflows (0x80000000 < 1, 0x7fffffff > -1). src2 may be an + * immediate, seven bits sign-extended (#64 is -64); src1 may not (#4 < 5 + * came out false) */ +uint64_t usse_vtst_int(unsigned pdst, struct usse_reg src1, struct usse_reg src2, + bool is_signed, bool eq); +/* (M44) VTST on F32 values: p = src1 - src2 < 0 or == 0 (-0 == 0); + * src1 and src2 in the same lane (false and no word if not) */ +bool usse_vtst_f32(uint64_t *out, unsigned pdst, struct usse_reg src1, struct usse_reg src2, + bool eq); +/* (M44) VPCK of a 16-bit half (half 0 the low one) of src, signed or not, + * to F32 in dest (any lane) */ +uint64_t usse_cvt16_f32(struct usse_reg dest, struct usse_reg src, unsigned half, bool is_signed); +/* (M44) VPCK of the F32 value src (any lane) into half `half` of dest, the + * other half kept: S16 or U16, rounded to the nearest (2.5 to 2) and + * saturated */ +uint64_t usse_cvt_f32_16(struct usse_reg dest, struct usse_reg src, unsigned half, bool is_signed); + +/* Memory loads (VLDST's, Vita3K's vldst; M32): count words in a row, from + * the address in sa word base plus an offset plus 4 bytes, into dest.. + * (temporaries or pa). The offset is an immediate in words (0..127) or a + * temporary whose high half times its low half is bytes -- (4 << 16) | + * word. WDF0 before the words are read. */ +uint64_t usse_ldr_imm(struct usse_reg dest, unsigned base, unsigned words, unsigned count); +uint64_t usse_ldr_reg(struct usse_reg dest, unsigned base, struct usse_reg offset, unsigned count); +/* KILL under a short predicate (0 always, 1 p0, 2 p1, 3 !p0): the + * instruction that ends the first phase of iOS's c00_discard, with the + * punch-through pass type in ISP state A. Not used yet: here it kills + * nothing (docs/research/p105-mesa.md, M19). */ +uint64_t usse_kill(unsigned pred); +/* VTST: p = the pixel's facing bit (bit 0 of special register g16, + * iOS's v09_frontfacing: `and(g16, #1) ne 0`) */ +uint64_t usse_vtst_facing(unsigned pdst); +/* LIMM under an extended predicate (0 none, 1 p0, 2 p1, 5 !p0, 6 !p1) */ +uint64_t usse_limm_pred(struct usse_reg dest, uint32_t value, unsigned pred); + +/* SOP2: two sources of four 8-bit channels (32-bit registers), + * colour = cop(sel1 * src1.rgb, sel2 * src2.rgb), alpha = aop(asel1 * + * src1.a, asel2 * src2.a), each factor 1 - itself with its mod -- GL's + * blending, as iOS's pixel programs do it (M8; selects from Vita3K) */ +enum { + USSE_SOP2_ZERO, /* colour selects */ + USSE_SOP2_SRC1, + USSE_SOP2_SRC2, + USSE_SOP2_SRC1_ALPHA, + USSE_SOP2_SRC2_ALPHA, + USSE_SOP2_SRC_ALPHA_SAT, +}; +enum { USSE_SOP2_A_ZERO, USSE_SOP2_A_SRC1, USSE_SOP2_A_SRC2 }; /* alpha selects */ +enum { USSE_SOP2_ADD, USSE_SOP2_SUB, USSE_SOP2_MIN, USSE_SOP2_MAX }; +struct usse_sop2 { + uint8_t csel1, cmod1, csel2, cmod2; + uint8_t asel1, amod1, asel2, amod2; + uint8_t cop, aop; +}; +uint64_t usse_sop2(struct usse_reg dest, struct usse_reg src1, struct usse_reg src2, + const struct usse_sop2 *f); + +#endif diff --git a/src/gallium/meson.build b/src/gallium/meson.build index 25e951151d4..99ecdcb8609 100644 --- a/src/gallium/meson.build +++ b/src/gallium/meson.build @@ -184,6 +184,12 @@ if with_gallium_lima else driver_lima = declare_dependency() endif +if with_gallium_sgx + subdir('winsys/sgx/drm') + subdir('drivers/sgx') +else + driver_sgx = declare_dependency() +endif if with_gallium_rocket subdir('winsys/rocket/drm') subdir('drivers/rocket') diff --git a/src/gallium/targets/dri/meson.build b/src/gallium/targets/dri/meson.build index 925c5127eea..5b59b6b4c62 100644 --- a/src/gallium/targets/dri/meson.build +++ b/src/gallium/targets/dri/meson.build @@ -61,7 +61,7 @@ libgallium_dri = shared_library( driver_kmsro, driver_v3d, driver_vc4, driver_freedreno, driver_etnaviv, driver_tegra, driver_i915, driver_svga, driver_virgl, driver_panfrost, driver_iris, driver_lima, driver_zink, driver_d3d12, - driver_asahi, driver_crocus, driver_rocket, driver_ethosu + driver_asahi, driver_crocus, driver_rocket, driver_ethosu, driver_sgx ], install : true, name_suffix : libname_suffix, diff --git a/src/gallium/targets/dril/dril_target.c b/src/gallium/targets/dril/dril_target.c index b5ba5180cbd..464245868f4 100644 --- a/src/gallium/targets/dril/dril_target.c +++ b/src/gallium/targets/dril/dril_target.c @@ -685,5 +685,6 @@ DEFINE_LOADER_DRM_ENTRYPOINT(sun4i_drm) DEFINE_LOADER_DRM_ENTRYPOINT(udl) DEFINE_LOADER_DRM_ENTRYPOINT(zynqmp_dpsub) DEFINE_LOADER_DRM_ENTRYPOINT(lima) +DEFINE_LOADER_DRM_ENTRYPOINT(apple_sgx) DEFINE_LOADER_DRM_ENTRYPOINT(d3d12) DEFINE_LOADER_DRM_ENTRYPOINT(zink) diff --git a/src/gallium/targets/dril/meson.build b/src/gallium/targets/dril/meson.build index 55f10dc7805..2b46aefe6e8 100644 --- a/src/gallium/targets/dril/meson.build +++ b/src/gallium/targets/dril/meson.build @@ -122,6 +122,7 @@ foreach d : [[with_gallium_kmsro, [ (with_gallium_radeonsi and with_amdgpu_virtio), ['virtio_gpu']], [with_gallium_lima, ['lima']], + [with_gallium_sgx, ['apple_sgx']], [with_gallium_d3d12, ['d3d12']], [with_gallium_zink, ['zink']], [with_gallium_asahi, ['asahi']]] diff --git a/src/gallium/winsys/sgx/drm/meson.build b/src/gallium/winsys/sgx/drm/meson.build new file mode 100644 index 00000000000..634794b50ec --- /dev/null +++ b/src/gallium/winsys/sgx/drm/meson.build @@ -0,0 +1,12 @@ +# Copyright 2026 Project Cascadia +# SPDX-License-Identifier: MIT + +libsgxwinsys = static_library( + 'sgxwinsys', + files('sgx_drm_winsys.c'), + include_directories : [ + inc_src, inc_include, + inc_gallium, inc_gallium_aux, inc_gallium_drivers, + ], + dependencies : idep_mesautil, +) diff --git a/src/gallium/winsys/sgx/drm/sgx_drm_public.h b/src/gallium/winsys/sgx/drm/sgx_drm_public.h new file mode 100644 index 00000000000..f66a795136b --- /dev/null +++ b/src/gallium/winsys/sgx/drm/sgx_drm_public.h @@ -0,0 +1,14 @@ +/* + * Copyright 2026 Project Cascadia + * SPDX-License-Identifier: MIT + */ +#ifndef SGX_DRM_PUBLIC_H +#define SGX_DRM_PUBLIC_H + +struct pipe_screen; +struct pipe_screen_config; + +/* The render node of drivers/gpu/drm/apple-sgx ("apple_sgx") */ +struct pipe_screen *sgx_drm_screen_create(int fd, const struct pipe_screen_config *config); + +#endif diff --git a/src/gallium/winsys/sgx/drm/sgx_drm_winsys.c b/src/gallium/winsys/sgx/drm/sgx_drm_winsys.c new file mode 100644 index 00000000000..14ebc443793 --- /dev/null +++ b/src/gallium/winsys/sgx/drm/sgx_drm_winsys.c @@ -0,0 +1,16 @@ +/* + * Copyright 2026 Project Cascadia + * SPDX-License-Identifier: MIT + */ +#include "util/os_file.h" +#include "util/u_screen.h" + +#include "sgx_drm_public.h" +#include "sgx/sgx_screen.h" + +struct pipe_screen * +sgx_drm_screen_create(int fd, const struct pipe_screen_config *config) +{ + return u_pipe_screen_lookup_or_create(os_dupfd_cloexec(fd), config, NULL, + sgx_screen_create); +} diff --git a/src/mesa/main/fbobject.c b/src/mesa/main/fbobject.c index 45d9b819130..ce9fb2c2570 100644 --- a/src/mesa/main/fbobject.c +++ b/src/mesa/main/fbobject.c @@ -924,6 +924,14 @@ gles_check_float_renderable(const struct gl_context *ctx, if (att->Texture->_IsHalfFloat && !_mesa_has_EXT_color_buffer_half_float(ctx)) return false; + /* And in OpenGL ES 2 only as RGBA: EXT_color_buffer_half_float makes + * RGBA textures of type HALF_FLOAT_OES color-renderable, not RGB ones + * (dEQP-GLES2's fbo.completeness...rgb_half_float_oes). + */ + if (att->Texture->_IsHalfFloat && att->Renderbuffer->_BaseFormat == GL_RGB && + !_mesa_is_gles3(ctx)) + return false; + const struct gl_texture_object *texObj = att->Texture; const struct gl_texture_image *texImage = texObj->Image[att->CubeMapFace][att->TextureLevel];