<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="4.4.1">Jekyll</generator><link href="https://timur.hu/feed.xml" rel="self" type="application/atom+xml" /><link href="https://timur.hu/" rel="alternate" type="text/html" /><updated>2026-08-27T14:32:05+02:00</updated><id>https://timur.hu/feed.xml</id><title type="html">Timur’s blog</title><subtitle>Engineer who prefers quality over quantity.</subtitle><author><name>Timur Kristóf</name></author><entry><title type="html">The GCN outcast - Radeon HD 7870 XT</title><link href="https://timur.hu/blog/2026/the-gcn-outcast-radeon-hd-7870-xt" rel="alternate" type="text/html" title="The GCN outcast - Radeon HD 7870 XT" /><published>2026-08-27T14:00:00+02:00</published><updated>2026-08-27T14:00:00+02:00</updated><id>https://timur.hu/blog/2026/the-gcn-outcast-radeon-hd-7870-xt</id><content type="html" xml:base="https://timur.hu/blog/2026/the-gcn-outcast-radeon-hd-7870-xt"><![CDATA[<p>AMD is known to be Linux friendly and has had an open source
driver stack for their GPUs for more than a decade.
However, there was one GPU that has always been an outcast
on Linux because it has never worked: the Radeon HD 7870 XT.
This post is about how I fixed that so that Linux gamers
can enjoy this GPU being fully functional now.</p>

<p>The Radeon HD 7870 XT is built on the GCN 1 architecture (also known as Southern Islands or SI, or GFX6).
It has a chip called “Tahiti LE” which is a variant
of the Tahiti chip that was quite high-end by 2012 standards.
Tahiti and other GCN 1 chips have been supported on Linux for more than a decade,
first by the <code class="language-plaintext highlighter-rouge">radeon</code> kernel driver and more recently by the <code class="language-plaintext highlighter-rouge">amdgpu</code> kernel driver.</p>

<p>We have every reason to assume that the 7870 XT should <em>“just work”</em>, so why doesn’t it?</p>

<h2 id="motivation">Motivation</h2>

<p>Why care whether a 15 years old GPU works today or not?</p>

<ul>
  <li>If the driver stack claims to support GCN 1, we should indeed support
all GCN 1 chips without exceptions.</li>
  <li>If there is a serious bug that prevents a GPU from working,
there is a chance the bug also affects other GPUs.
It is worth an investigation.</li>
  <li>Most importantly, it’s a good challenge to see if I can figure out
a problem like this.</li>
</ul>

<h2 id="story-time-what-is-a-harvested-cut-down-chip">Story time: what is a harvested (cut down) chip?</h2>

<p>If you look at any GPU manufacturer, they have a lot of different
products every generation, and those products use different
variants of the same few different chips. How is that possible?</p>

<p>Due to economies of scale, there is a common practice among chip makers:
they prefer to manufacture massive quantities of the same few chip instead of
a small quantity of many different kind of chips.
However, in order to have many different products,
they can configure the same chip in different ways and
sell those variants under different product names.
Today we are focusing on AMD’s old Tahiti chip,
so let’s use that as an example.
How many different products did they launch that
use the Tahiti chip and its different variants or refreshes?
We can
<a href="https://en.wikipedia.org/wiki/List_of_AMD_graphics_processing_units#Radeon_HD_7000_series">use Wikipedia</a>
to check that:</p>

<ul>
  <li>Radeon HD 7870 XT, 7950, 7970, 7990, 8950, 8970, 8990</li>
  <li>Radeon R9 280, 280X</li>
  <li>FirePro W8000, W9000, D500, D700, S9000, S9050, S10000</li>
</ul>

<p>All of those use the Tahiti chip. But what are the differences between those products?</p>

<ul>
  <li>Different target audience, eg. workstation vs. consumer</li>
  <li>Different memory configuration (memory size and bus width)</li>
  <li>Different shader and memory clock speed</li>
  <li>Different amount of compute units, render output units (aka. render backend or RB), etc.</li>
</ul>

<p>How is this achieved?</p>

<p>At the factory, each chip is examined automatically.
Due to variance in the chip manufacturing process,
not all chips end up the same, even if we do everything
to make them the same.
In practice that means there may be defects on the chip,
or maybe not all units perform up to spec.
This is the so-called <em>“silicon lottery”</em>.
The chips are then sorted according to how well
they ended up performing and that’s when the manufacturer
decides what to do with them and what product they can
be sold as.</p>

<p>There really are no bad GPUs, just incorrectly priced GPUs.
Those that are still usable but ended up less than ideal
will still be put to use:
some parts (eg. compute units) are fused off and disabled,
and the GPU is overall still functional as a weaker, cheaper GPU.
That’s how we end up with products like the Radeon HD 7870 XT.</p>

<h2 id="starting-point-for-investigating-the-problem">Starting point for investigating the problem</h2>

<h3 id="initial-testing">Initial testing</h3>

<p>To start with this work, open source enthusiast Leonardo Frassetto
helped me to buy a used 7870 XT in good condition from an Italian used hardware site.
After plugging in this GPU and booting my system, I noticed the following:</p>

<ul>
  <li>Firmware (BIOS) can recognize the GPU, show a logo and boot grub</li>
  <li>When amdgpu loads, the picture disappears and becomes a colorful mess</li>
  <li>Looking at the logs, it seems the GFX block immediately hangs and goes into a GPU reset loop,
as the kernel attempts to reset the GPU to fix the hang, which is expected</li>
</ul>

<h3 id="information-from-wikipedia">Information from Wikipedia</h3>

<p>From Wikipedia, we got a
<a href="https://en.wikipedia.org/wiki/List_of_AMD_graphics_processing_units#Radeon_HD_7000_series">list of AMD GPUs</a>
and
<a href="https://en.wikipedia.org/wiki/Graphics_Core_Next#Comparison_of_GCN_GPUs">an article about GCN</a>
to give us some basic info.</p>

<p>We can see that Tahiti LE is a harvested (cut down) version
of the full Tahiti chip as the 7870 XT has lower specs than the 7970 (or R9 280X).
There are plenty of GPUs with disabled CUs supported already, so I went with the assumption
that the disabled CUs aren’t the issue.</p>

<table>
  <thead>
    <tr>
      <th style="text-align: center">Tahiti (top spec)</th>
      <th style="text-align: center">Tahiti LE (cut down)</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td style="text-align: center">32 CU (compute units)</td>
      <td style="text-align: center">24 CU</td>
    </tr>
    <tr>
      <td style="text-align: center">32 RB (render output units)</td>
      <td style="text-align: center">32 RB</td>
    </tr>
    <tr>
      <td style="text-align: center">384-bit memory bus</td>
      <td style="text-align: center">256-bit memory bus</td>
    </tr>
  </tbody>
</table>

<h3 id="information-from-freedesktop-bugzilla">Information from Freedesktop Bugzilla</h3>

<p>Someone opened
<a href="https://bugs.freedesktop.org/show_bug.cgi?id=60879">a bug report on the old Freedesktop Bugzilla</a>
in 2013 complaining that the 7870 XT didn’t work.
Although the issue has never been solved, we can still glean some interesting information
from that bug report:</p>

<ul>
  <li>The display (ie. modesetting) should work, and the issue
is <em>“only”</em> with 3D acceleration.</li>
  <li>One commenter was able to get the 7870 XT to work with
basic compute shaders but not much else (definitely not a full desktop).</li>
  <li>The register dumps attached to the bug only contain the DCE (display engine)
registers, so are not really conclusive.</li>
  <li>There were suggestions to change the <code class="language-plaintext highlighter-rouge">CGTS_TCC_DISABLE</code> register in the kernel driver,
which didn’t help.</li>
  <li>The developers already corrected the register programming for
harvested (cut down) RBs, and the 7870 XT doesn’t have those anyway,
so that isn’t the issue.</li>
</ul>

<h2 id="booting-a-working-system">Booting a working system</h2>

<p>How do we even begin to diagnose what the problem is
if the GPU hangs immediately at boot?</p>

<h3 id="booting-in-runlevel-3">Booting in runlevel 3</h3>

<p>I started by booting to runlevel 3 (basically just a terminal and nothing else).
In this mode, the <code class="language-plaintext highlighter-rouge">amdgpu</code> kernel driver can initialize all blocks in the GPU
correctly and the display works. We are in a terminal only environment
so there is nothing submitting jobs to the GPU.</p>

<h3 id="booting-a-desktop-with-software-rendering">Booting a desktop with software rendering</h3>

<p>I configured the system to use
software rendering for both OpenGL and Vulkan by setting
the following environment variables temporarily:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code># Ask OpenGL loader for software rendering
LIBGL_ALWAYS_SOFTWARE=1
# Force using lavapipe as a Vulkan driver
VK_ICD_FILENAMES=/usr/share/vulkan/icd.d/lvp_icd.x86_64.json
# Force using swrast as a Gallium driver (for OpenGL)
MESA_LOADER_DRIVER_OVERRIDE=swrast
</code></pre></div></div>

<p>With that, the system can indeed boot with the 7870 XT,
although the graphical user interface is slow because
we are not using any hardware acceleration (obviously).
I would not recommend anyone to regularly use their system this way.</p>

<h3 id="testing-simple-shaders">Testing simple shaders</h3>

<p>Even though all the system uses software rendering,
we can still set different environment variables for specific apps and
have just one test application run with “real” drivers for the hardware.
I decided to use <a href="https://gitlab.freedesktop.org/mesa/vkrunner">the vkrunner suite</a>
and wrote a very simple test case with a very simple compute shader.
The test case allocates two buffers (SSBO).
The shader has only one invocation that reads a small piece of data
from the <code class="language-plaintext highlighter-rouge">values_in</code> buffer and writes it to the <code class="language-plaintext highlighter-rouge">values_out</code> buffer.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>[compute shader]
#version 450

layout(local_size_x = 1, local_size_y = 1, local_size_z = 1) in;
layout(binding = 1) buffer block_out { uint values_out[]; };
layout(binding = 2) buffer block_in { uint values_in[]; };

void main()
{
  values_out[gl_LocalInvocationIndex] = gl_WorkGroupID.x;
}

[test]
ssbo 1 1048576
ssbo 2 1048576

compute 1 1 1
</code></pre></div></div>

<p>That indeed works correctly, confirming what we found
in the Freedesktop bugzilla, that simple compute shaders
indeed work. What happens if we slightly complicate it though?
The first thing we can do is to increase the number of invocations
so that more than one invocation reads and writes memory.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>layout(local_size_x = 96, local_size_y = 1, local_size_z = 1) in;
</code></pre></div></div>

<p>Whoops! This test case now hangs the GPU.
I guess the way we changed the memory access
must have caused the GPU to hang.
With some trial and error, we can find that <code class="language-plaintext highlighter-rouge">local_size_x = 64</code> still works
but <code class="language-plaintext highlighter-rouge">local_size_x = 65</code> and higher hangs.
After some further trial and error I noticed that
I can still use a larger workgroup if I skip
memory accesses to certain address ranges.
This definitely confirms that the issue is with memory access somehow.</p>

<h2 id="lets-look-at-registers-with-umr">Let’s look at registers with umr</h2>

<p>One of the developers who commented on the old bugzilla thread
were mentioning the <code class="language-plaintext highlighter-rouge">CGTS_TCC_DISABLE</code> register.
Although the suggested patch didn’t help, I thought
okay, let’s see what is actually the value of this
register using <a href="https://gitlab.freedesktop.org/tomstdenis/umr">umr</a>:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ sudo umr -O bits -r tahiti.gfx600.mmCGTS_TCC_DISABLE
gfx600.mmCGTS_TCC_DISABLE =&gt; 0x09240001
        .TCC_DISABLE[16:31] == 2340 (0x00000924)
</code></pre></div></div>

<p>Each bit represents a disabled TCC.
We can see that some TCC units are disabled by default:
2, 5, 8, 11.
Why are they disabled and what does that mean exactly?
We saw from Wikipedia that the 7870 XT only has a 256-bit memory bus,
although other Tahiti based GPUs have a 384-bit bus.
This means that only two-thirds of the memory channels
on this GPU are enabled and the rest are disabled.</p>

<p>I started to think, is it possible the GPU is trying to read from those
disabled memory channels or use some disabled TCC units, or something like that?
Technically, the disabled parts should be fused off and
not accessible, but maybe it still tries to interact with them?</p>

<p>I went to take a look at the
<a href="https://github.com/torvalds/linux/blob/master/drivers/gpu/drm/amd/include/asic_reg/gca/gfx_6_0_d.h">registers</a>
and
<a href="https://github.com/torvalds/linux/blob/master/drivers/gpu/drm/amd/include/asic_reg/gca/gfx_6_0_sh_mask.h">register fields</a>
of GFX 6 to see if there is anything that stands out.
I basically searched for “TCC” and looked at the results hoping for a clue.
I found two interesting things:</p>

<ul>
  <li>The <code class="language-plaintext highlighter-rouge">TCP_ADDR_CONFIG</code> register has a field called <code class="language-plaintext highlighter-rouge">NUM_TCC_BANKS</code></li>
  <li>There are <code class="language-plaintext highlighter-rouge">TCP_CHAN_STEER_LO</code> and <code class="language-plaintext highlighter-rouge">TCP_CHAN_STEER_HI</code> registers which have fields for channels</li>
</ul>

<p>Let’s see the value of these registers:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ sudo umr -O bits -r tahiti.gfx600.mmTCP_ADDR_CONFIG
gfx600.mmTCP_ADDR_CONFIG =&gt; 0x000002fb
        .COLHI_WIDTH[6:8]    ==  3 (0x00000003)
        .NUM_BANKS[4:5]      ==  3 (0x00000003)
        .NUM_TCC_BANKS[0:3]  == 11 (0x0000000b)
        .RB_SPLIT_COLHI[9:9] ==  1 (0x00000001)

$ sudo umr -O bits -r tahiti.gfx600.mmTCP_CHAN_STEER_LO
gfx600.mmTCP_CHAN_STEER_LO =&gt; 0xa9210876
        .CHAN0[0:3]   ==  6 (0x00000006)
        .CHAN1[4:7]   ==  7 (0x00000007)
        .CHAN2[8:11]  ==  8 (0x00000008)
        .CHAN3[12:15] ==  0 (0x00000000)
        .CHAN4[16:19] ==  1 (0x00000001)
        .CHAN5[20:23] ==  2 (0x00000002)
        .CHAN6[24:27] ==  9 (0x00000009)
        .CHAN7[28:31] == 10 (0x0000000a)

$ sudo umr -O bits -r tahiti.gfx600.mmTCP_CHAN_STEER_HI
gfx600.mmTCP_CHAN_STEER_HI =&gt; 0x0000543b
        .CHAN8[0:3]   == 11 (0x0000000b)
        .CHAN9[4:7]   ==  3 (0x00000003)
        .CHANA[8:11]  ==  4 (0x00000004)
        .CHANB[12:15] ==  5 (0x00000005)
        .CHANC[16:19] ==  0 (0x00000000)
        .CHAND[20:23] ==  0 (0x00000000)
        .CHANE[24:27] ==  0 (0x00000000)
        .CHANF[28:31] ==  0 (0x00000000)
</code></pre></div></div>

<p><strong>Whoah!!!</strong>
It seems like the registers indeed refer to the disabled memory channels:</p>

<ul>
  <li><code class="language-plaintext highlighter-rouge">TCP_ADDR_CONFIG.NUM_TCC_BANKS</code> indicates 12 channels (value of 11)
even though the GPU only has 8 active memory channels.</li>
  <li><code class="language-plaintext highlighter-rouge">TCP_CHAN_STEER_LO</code>/<code class="language-plaintext highlighter-rouge">HI</code> refer to channels 2, 5, 8, 11
even though those memory channels are disabled.</li>
</ul>

<p>Let’s try our luck and see what happens if we remove those.
We simply need to edit the bit pattern for these registers,
I typically use Gnome Calculator in programming mode
to toggle the bits by hand.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code># Change NUM_TCC_BANKS to 7
$ sudo umr -w tahiti.gfx600.mmTCP_ADDR_CONFIG 0x000002f7
# Use channels 0, 1, 3, 4, 6, 7, 9, 10
$ sudo umr -w tahiti.gfx600.mmTCP_CHAN_STEER_LO 0x43a91076
# We don't have any more channels so clear this to zeroes
$ sudo umr -w tahiti.gfx600.mmTCP_CHAN_STEER_HI 0x00000000
</code></pre></div></div>

<p>And… <strong>Yesss!!!</strong> with that, the test doesn’t hang anymore,
and the GPU starts working well.</p>

<h2 id="whats-actually-happening-on-this-gpu">What’s actually happening on this GPU?</h2>

<p>I had a chat with the lead developer of amdgpu Alex Deucher
and shared my findings. He helped me understand what’s what:</p>

<ul>
  <li>TCC (texture cache per channel) is the L2 cache
that is attached to each memory channel.
For disabled memory channels, the corresponding TCC
should be also disabled and should not be used (obviously).</li>
  <li>TCP (texture cache per pipe) is the L1 cache
that is part of each CU.</li>
  <li>The <code class="language-plaintext highlighter-rouge">TCP_ADDR_CONFIG</code> and <code class="language-plaintext highlighter-rouge">TCP_CHAN_STEER</code> registers
can tell the TCPs which TCCs they are allowed to use.
These registers were programmed from the <em>“golden”</em>
registers without regard to the fact that some channels
may be disabled.</li>
</ul>

<p>We can now see that the GPU was trying to use the L2 cache
that is attached to the disabled memory channels, which (obviously)
didn’t work and caused the GPU to hang.
With that understanding, I wrote
<a href="https://lists.freedesktop.org/archives/amd-gfx/2026-April/143047.html">a patch</a>.
With that patch, the system can boot normally (without a need to
force software rendering) and the 7870 XT works fine now.</p>

<p>The patch has been backported to stable kernels too.
If you are using a 7870 XT, you can now enjoy it fully working on Linux!</p>

<h2 id="perf-testing">Perf testing</h2>

<p>I also did some perf testing to see if it makes any difference
how it is configured. I used Rise of the Tomb Raider
at 1080p with lowest settings for these tests.
This shows that the values mentioned above are indeed
optimal for this GPU, so we only need to skip the
disabled TCCs but otherwise can keep the order they are in.</p>

<table>
  <thead>
    <tr>
      <th style="text-align: center"><code class="language-plaintext highlighter-rouge">TCP_CHAN_STEER_HI</code></th>
      <th style="text-align: center"><code class="language-plaintext highlighter-rouge">TCP_CHAN_STEER_LO</code></th>
      <th style="text-align: center"><code class="language-plaintext highlighter-rouge">NUM_TCC_BANKS</code></th>
      <th style="text-align: center">frame rate</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td style="text-align: center">0</td>
      <td style="text-align: center">0x43a91076</td>
      <td style="text-align: center">8</td>
      <td style="text-align: center">78 fps</td>
    </tr>
    <tr>
      <td style="text-align: center">0</td>
      <td style="text-align: center">0</td>
      <td style="text-align: center">12</td>
      <td style="text-align: center">27 fps</td>
    </tr>
    <tr>
      <td style="text-align: center">0xa147</td>
      <td style="text-align: center">0x43a91076</td>
      <td style="text-align: center">12</td>
      <td style="text-align: center">69.96 fps</td>
    </tr>
    <tr>
      <td style="text-align: center">0x4310</td>
      <td style="text-align: center">0x43a91076</td>
      <td style="text-align: center">12</td>
      <td style="text-align: center">61 fps</td>
    </tr>
    <tr>
      <td style="text-align: center">0</td>
      <td style="text-align: center">0xa9764310</td>
      <td style="text-align: center">8</td>
      <td style="text-align: center">66 fps</td>
    </tr>
  </tbody>
</table>

<h2 id="what-have-we-learned-from-this">What have we learned from this?</h2>

<p>It turns out this is one of those rare bugs which only affect a specific
variant of a chip and nothing else.
The issue with harvested TCCs is a problem unique to Tahiti LE,
which was only ever used in the 7870 XT (and the FirePro D500 according to Wikipedia),
so the fix doesn’t affect other GPUs.
There have been no more GCN GPUs with this kind of harvesting
(although RDNA1 has variants with harvested TCC as well).</p>

<p>On the bright side, it wasn’t a useless exercise for me.</p>

<ul>
  <li>I learned a lot about how the cache hierarchy works</li>
  <li>It was interesting to see how the cache configuration affects performance</li>
  <li>I feel proud that I was able to solve the mystery</li>
</ul>]]></content><author><name>Timur Kristóf</name></author><category term="graphics" /><category term="freedesktop" /><category term="work" /><summary type="html"><![CDATA[AMD is known to be Linux friendly and has had an open source driver stack for their GPUs for more than a decade. However, there was one GPU that has always been an outcast on Linux because it has never worked: the Radeon HD 7870 XT. This post is about how I fixed that so that Linux gamers can enjoy this GPU being fully functional now.]]></summary></entry><entry><title type="html">How does GPU recovery work with AMD GPUs on Linux?</title><link href="https://timur.hu/blog/2026/how-does-gpu-recovery-work-on-amd-gpus-on-linux" rel="alternate" type="text/html" title="How does GPU recovery work with AMD GPUs on Linux?" /><published>2026-08-26T19:19:00+02:00</published><updated>2026-08-26T19:19:00+02:00</updated><id>https://timur.hu/blog/2026/how-does-gpu-recovery-work-on-amd-gpus-on-linux</id><content type="html" xml:base="https://timur.hu/blog/2026/how-does-gpu-recovery-work-on-amd-gpus-on-linux"><![CDATA[<p>An inconvenient part of GPU driver development is
the fact that GPUs can crash and hang for various
reasons, just like CPUs.
Really, this can happen
on any operating system to GPUs from any manufacturer.
We’ve seen many such issues
on the open source Linux driver stack for AMD GPUs.
We’ve been tackling many bugs that lead to GPU hangs.
We need to deal with the fact that hangs can happen
and when they happen, we need to make sure that
the system can recover and the user can keep using
their Linux desktop.
The purpose of this blog post is to give an overview
of what the problem is and what steps we are taking
to improve it.</p>

<h2 id="why-does-a-gpu-hang-or-freeze-in-the-first-place">Why does a GPU hang or freeze in the first place?</h2>

<p>Many users are referring to this topic as “<strong>the</strong> bug”,
as if it was just one problem. If only we lazy driver
devs fixed just that one problem, life would be better, wouldn’t it?</p>

<p>In reality however, there are many different reasons
why a GPU can hang, in fact there are so many possible
reasons for hangs that it would be impossible to list
all of them. We have fixed so many of these kinds of
bugs over the years that it’s really impossible to even
give a list of those bug fixes.</p>

<p>I’ll try to come up with some examples:</p>

<ul>
  <li>Issues with shader instructions, eg. incorrect opcodes,
unmitigated hazards, infinite loops, etc.</li>
  <li>On some GPUs, accessing unmapped memory (ie. a page fault)
will also lead to a GPU hang</li>
  <li>Invalid commands submitted to the GPU</li>
  <li>Deadlock, ie. waiting for something that never happens
(sometimes also caused by coherency issues)</li>
  <li>Missed interrupt which leads to a deadlock</li>
  <li>And many others…</li>
</ul>

<h3 id="setting-expectations">Setting expectations</h3>

<p>When talking about this problem space, it’s often difficult
to judge what we are talking about, what is possible and what isn’t, so first let’s
start with setting some expectations about what we can do.</p>

<p>Firstly, we need to acknowledge that every GPU has different
IP blocks (parts such as graphics, compute, DMA engines, display, video decoder, etc.)
and each IP block may offer a very different uAPI and programming model.
Therefore, each of them can fail in different ways and need to be
recovered in different ways, too.
It is impossible to handle every conceiveable
issue with every IP block the same way.
For example:</p>

<ul>
  <li>In order to use graphics and compute,
we have a command submission uAPI which userspace
applications can use to submit jobs.
Under the hood, user-mode drivers (UMD) use this uAPI
to execute Vulkan, OpenGL commands.</li>
  <li>The display engine offers the modesetting uAPI,
which is largely shared between all GPU vendors
and works on very different principles.</li>
  <li>Some IP blocks like MC (memory controller) and others
are not directly exposed to userspace, but are essential for
correct functionality. When something goes wrong with one
of these, that requires separate consideration.</li>
</ul>

<p><strong>This blog post focuses on GPU hangs caused by jobs submitted
by userspace applications.</strong><br />
The other topic are out of scope for this post.<br />
So, what can we reasonably expect about job submissions?</p>

<ul>
  <li>When an app (or game) submits commands that crash or hang the GPU,
the graphics context of that app is considered “guilty”.
We need to accept that it won’t be able to continue and will crash
(unless it was specifically designed to handle GPU failure).
In some cases (such as VM faults, known hazards etc.)
we can make an effort to try to stop it from crashing,
but not always.</li>
  <li>We should do our best to make sure we don’t freeze
or crash other “non-guilty” applications or the whole desktop.
However, sadly, trade-offs need to be made for the sake of performance.</li>
</ul>

<h2 id="why-is-it-difficult-to-deal-with-gpu-hangs">Why is it difficult to deal with GPU hangs?</h2>

<p>Let’s start with a quick recap of <a href="/blog/2025/how-do-graphics-drivers-work">how graphics drivers work</a>.
The way the graphics stack handles GPU jobs is the following:</p>

<ul>
  <li>A userspace driver generates commands for the GPU (and compiles shaders, etc.)</li>
  <li>A job with those commands is submitted to the kernel driver through a uAPI (userspace API)</li>
  <li>The kernel resolves job dependencies, BO (buffer object) state etc. and writes the
job to a hardware ring buffer (which is shared accross many processes)</li>
  <li>The GPU executes the commands from the job and when they are completed, signals a fence</li>
</ul>

<p>The above model has barely any room for detecting and handling errors.
The only thing we can detect is that a GPU job didn’t complete within
a timeout (eg. 2 seconds). We don’t even know if that’s because the commands
are taking too long (and would complete in a longer timeout) or the
GPU is stuck somewhere and isn’t making any progress.
Furthermore, job execution may overlap, so when it hangs, we can’t always know for
sure which job was responsible.</p>

<p>Actually, it’s even worse than that. Modern GPUs have multiple job queues
that can execute in parallel and all share the same resources
(eg. compute units for running shaders).
That means it is not even possible to be sure which queue is
really responsible for a timeout:
If two different jobs are executing on two queues in parallel,
it can happen that the “guilty” job hogs all compute units,
causing the other queue to “starve” and time out.</p>

<p>So, where does that leave us?</p>

<ul>
  <li>We can detect when a job times out</li>
  <li>We don’t know which job is really responsible</li>
  <li>We don’t know which queue is really responsible</li>
  <li>We do know which jobs were in flight when a timeout happened</li>
  <li>We can’t know why the timeout happened</li>
</ul>

<h2 id="how-do-we-deal-with-gpu-hangs-anyway">How do we deal with GPU hangs, anyway?</h2>

<p>Thanks to the excellent work of Alex Deucher and his team at AMD
on the <code class="language-plaintext highlighter-rouge">amdgpu</code> kernel driver,
various strategies were developed over the years to recover
GPUs from a hung state and to make the problems less severe.</p>

<h4 id="enforcing-isolation">Enforcing isolation</h4>

<p>Enforcing isolation means that we try to reduce how much
an application using the GPU can affect another, effectively
disabling parallel execution from different contexts.
This greatly limits the scope of what jobs are potentially
affected when there is a crash or hang, so makes it
less likely that a “guilty” context can crash others.</p>

<ul>
  <li>Currently, <code class="language-plaintext highlighter-rouge">amdgpu</code> does not allow jobs from different contexts
to overlap on the same queue. This means when only one queue
is active, we can 100% identify the “guilty” context correctly.</li>
  <li>There is a <a href="https://docs.kernel.org/gpu/amdgpu/module-parameters.html">kernel parameter</a>
<code class="language-plaintext highlighter-rouge">amdgpu.enforce_isolation</code>
which will additionally isolate different contexts
that are running on different queues.
This is currently disabled by default for performance reasons,
you can enable it for better stability.</li>
</ul>

<h4 id="asic-reset">ASIC reset</h4>

<p>ASIC reset is the simplest, and most destructive type of reset:</p>

<ul>
  <li>All pending or in-flight jobs are killed</li>
  <li>The GPU is completely reinitialized</li>
  <li>On dedicated GPUs, VRAM is erased</li>
</ul>

<p>That means that <em>all processes
that used the GPU will lose all resources they may have had in VRAM</em> (except on APUs).
The user sees that the screen turns black briefly, then every
application and the desktop just crash (unless the compositor and apps were robust).
This reset strategy means that just one misbehaving application
can cause all other applications and the entire desktop to crash.
It is better than watching a completely frozen screen, but not by much.</p>

<h4 id="soft-recovery">Soft recovery</h4>

<p>Soft recovery was the first attempt at making resets less destructive.
What it does is it kills all currently running shaders on a specific
queue and hopes that the GPU can then move on and complete the job.</p>

<p>This can solve quite a few issues such as infinite loops in shaders,
but it is somewhat dangerous because the kernel doesn’t really
have any knowledge if it worked, and can only judge by seeing
whether the job now completes within a certain time or not.
There is no way to know if the current job or subsequent jobs
will actually work.
So, soft recovery should be avoided when better recovery methods
are available.</p>

<h4 id="queue-reset">Queue reset</h4>

<p>Queue reset (as its name suggests) attempts to reset just
one specific queue without affecting others.
There are mainly two ways this can be implemented for different hardware blocks:</p>

<ul>
  <li>Graphics and compute queues on newer GPUs have a firmware-assisted
queue reset, which means it’s a feature of the CP (command processor) firmware.
It basically terminates all operations (including shaders) that
are executing or pending on the specific queue, and then moves on.</li>
  <li>SDMA, VCN and other queues can be reset by simply resetting
the whole hardware IP block. These blocks usually only have one
single queue, so the reset doesn’t perturb anything else.</li>
</ul>

<p>In my opinion, queue reset is the best way to handle GPU recovery.
The only issue with queue reset was that in itself,
it would still kill all currently executing or pending jobs from
the given queue, even those jobs that haven’t started yet.
From a user perspective, that means it could still crash
other apps and the desktop (unless you enabled enforcing isolation too).</p>

<p>Starting from Linux 6.18, an important improvement was
made to queue resets:
the kernel can now re-emit pending jobs from other contexts
after the queue reset is complete, so in practice it is very
likely that only the “guilty” misbehaved app is killed
and everything else can continue. This is not 100% guaranteed though,
because it is still possible that a job from a different queue
can starve other jobs.
For the safest user experience, you should turn on enforcing isolation too.</p>

<h4 id="ip-block-soft-reset">IP block soft reset</h4>

<p>I introduced IP block soft reset as a GPU recovery method very recently.
This method is more blunt than the queue reset, because IP block soft reset
will reset an entire IP block including every queue it has.
For the graphics/compute block this means it will practically reset all
graphics and compute queues at the same time.
The reason why I added this is because it works on GPUs that don’t have firmware support
for queue reset, or in situations where the firmware failed to do the reset.
This method uses the same re-emit code that was added for queue reset
so it is very likely to be able to keep your system running after a hang.</p>

<p>The main benefit of this reset method is that it’s markedly better
than a full ASIC reset because it doesn’t erase the contents of VRAM,
and it can be used on old APUs where ASIC reset is not available at all.</p>

<p>Starting from Linux 7.3 you can benefit from this new recovery method
on GCN 1-4.</p>

<h2 id="but-what-about-the-page-flip-timeout-and-other-issues">But… what about the page flip timeout and other issues?</h2>

<p>Page flip timeouts are a different beast entirely, because they are
caused by issues with the display engine which has a different programming
model and userspace interacts with it using a different uAPI.
So this is out of scope for the current post.</p>

<p>However, I need to mention that
<a href="https://lists.freedesktop.org/archives/amd-gfx/2026-June/146851.html">Leo Li has done some excellent work</a>
tracking down the root cause for many page flip timeout related issues.</p>

<h2 id="recommendations">Recommendations</h2>

<p>As you can see, a lot of improvements have been made to GPU recovery recently,
so if you experience a lot of GPU hangs, my recommendation is to upgrade your kernel if possible.
If that’s not possible, consider enabling enforcing isolation.</p>

<p>Here is some simple advice in a nutshell:</p>

<ul>
  <li>For good GPU recovery
    <ul>
      <li>Queue resets with re-emit on RDNA ― use Linux 6.18 or newer</li>
      <li>Queue resets with re-emit on Vega ― use Linux 7.0 or newer</li>
      <li>IP block soft reset with re-emit on GCN 1-4 ― use Linux 7.3 or newer</li>
      <li>For the safest experience, use <code class="language-plaintext highlighter-rouge">amdgpu.enforce_isolation=1</code></li>
    </ul>
  </li>
  <li>If you need to use older kernels
    <ul>
      <li>On RDNA, use <code class="language-plaintext highlighter-rouge">amdgpu.enforce_isolation=1</code> which will make queue resets work much better</li>
      <li>You need to accept that Vega and older don’t have any decent recovery options on those kernels</li>
    </ul>
  </li>
  <li>If you use newer kernels but still experience problems
    <ul>
      <li>Try <code class="language-plaintext highlighter-rouge">amdgpu.enforce_isolation=1</code></li>
      <li>If that didn’t help,
<a href="https://gitlab.freedesktop.org/drm/amd/-/work_items">open an issue here</a>
and please don’t forget to mention your system specs, upload a <code class="language-plaintext highlighter-rouge">dmesg</code> log and write down the steps to reproduce</li>
    </ul>
  </li>
</ul>

<p>Hope this helps!</p>]]></content><author><name>Timur Kristóf</name></author><category term="graphics" /><category term="freedesktop" /><category term="work" /><summary type="html"><![CDATA[An inconvenient part of GPU driver development is the fact that GPUs can crash and hang for various reasons, just like CPUs. Really, this can happen on any operating system to GPUs from any manufacturer. We’ve seen many such issues on the open source Linux driver stack for AMD GPUs. We’ve been tackling many bugs that lead to GPU hangs. We need to deal with the fact that hangs can happen and when they happen, we need to make sure that the system can recover and the user can keep using their Linux desktop. The purpose of this blog post is to give an overview of what the problem is and what steps we are taking to improve it.]]></summary></entry><entry><title type="html">A love song for Linux gamers with old GPUs (EOY 2025)</title><link href="https://timur.hu/blog/2026/love-song-for-linux-gamers-with-old-gpus-eoy2025" rel="alternate" type="text/html" title="A love song for Linux gamers with old GPUs (EOY 2025)" /><published>2026-01-01T01:00:00+01:00</published><updated>2026-01-01T01:00:00+01:00</updated><id>https://timur.hu/blog/2026/love-song-for-linux-gamers-with-old-gpus-eoy2025</id><content type="html" xml:base="https://timur.hu/blog/2026/love-song-for-linux-gamers-with-old-gpus-eoy2025"><![CDATA[<p>AMD GPUs are famous for working very well on Linux.
However, what about the very first GCN GPUs?
Are they working as well as the new ones?
In this post, I’m going to summarize how well these
old GPUs are supported and what I’ve been doing
to improve them.</p>

<p>This story is about the first two generations of GCN: Southern Islands (aka. SI, GCN1, GFX6)
and Sea Islands (aka. CIK, GCN2, GFX7).</p>

<h2 id="working-on-old-gpus">Working on old GPUs</h2>

<p>While AMD GPUs generally have a good reputation on Linux,
these old GCN graphics cards have been a sore spot
for as long as I’ve been working on the driver stack.</p>

<p>It occurred to me that resolving some of the long-standing
issues on these old GPUs might be a great way to get me started
on working on the <em>amdgpu</em> kernel driver and would help improve the
default user experience of Linux users on these GPUs.
I figured that it would give me a good base understanding,
and later I could also start contributing
code and bug fixes to newer GPUs.</p>

<h3 id="where-i-started">Where I started</h3>

<p>The RADV team has supported RADV on SI and CIK GPUs
for a long time. RADV support was already there even before I
joined the team in mid-2019. Daniel added <a href="https://gitlab.freedesktop.org/mesa/mesa/-/merge_requests/2751">ACO support for GFX7</a>
in November 2019,
and Samuel added <a href="https://gitlab.freedesktop.org/mesa/mesa/-/merge_requests/3533">ACO support for GFX6</a> in January 2020. More recently, Martin added a
<a href="https://gitlab.freedesktop.org/mesa/mesa/-/merge_requests/27812">Tahiti</a> (GFX6) and <a href="https://gitlab.freedesktop.org/mesa/mesa/-/merge_requests/33563">Hawaii</a> (GFX7) GPU to the Mesa CI which
are running post-merge “nightly” jobs. So we can catch
regressions and test our work on these GPUs quite quickly.</p>

<p>The kernel driver situation was less fortunate.</p>

<p>On the kernel side, <em>amdgpu</em> (the newer kernel driver) has supported <a href="https://gitlab.freedesktop.org/agd5f/linux/-/commit/a2e73f56fa6282481927ec43aa9362c03c2e2104">CIK since June 2015</a>
and <a href="https://gitlab.freedesktop.org/agd5f/linux/-/commit/2cd46ad22383ab8372b86cdb5257589496099412">SI since August 2016</a>. DC (the new display driver) has
supported CIK since September 2017 (the beginning), and
<a href="https://lists.freedesktop.org/archives/amd-gfx/2020-July/051604.html">SI support was added in July 2020 by Mauro</a>.
However, the old <em>radeon</em> driver was the default driver.
Unfortunately, <em>radeon</em> doesn’t support Vulkan,
so in the default user experience, users couldn’t play most games
or benefit from any of the Linux gaming related work we’ve been doing for the last 10 years.</p>

<p>In order to get working Vulkan support on SI and CIK, we needed to use the following kernel params:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>radeon.si_support=0 radeon.cik_support=0 amdgpu.si_support=1 amdgpu.cik_support=1
</code></pre></div></div>

<p>Then, you could boot with <em>amdgpu</em> and enjoy a semblance of a good
user experience until the GPU crashed / hung, or until you tried to use
some functionality which was missing from <em>amdgpu</em>, or until you plugged
in a display which the display driver couldn’t handle.</p>

<p>It was… not the best user experience.</p>

<h3 id="where-to-go-from-there">Where to go from there?</h3>

<p>The first question that came to mind is,
why wasn’t <em>amdgpu</em> the default kernel driver for these GPUs?
Since the “experimental” support had been there for 10 years,
we had thought the kernel devs would eventually just enable
<em>amdgpu</em> by default, but that never happened.
At XDC 2024 I met Alex Deucher, the lead developer of <em>amdgpu</em>
and asked him what was missing. Alex explained to me that the
main reason the default wasn’t switched is to avoid regressions
for users who rely on some functionality not supported by <em>amdgpu</em>:</p>

<ul>
  <li>Display features: analog connectors in DC (or DP/HDMI audio support in non-DC)</li>
  <li>VCE1 for video coding on SI</li>
</ul>

<p>It doesn’t seem like much, does it?
How hard can it be?</p>

<h2 id="display-features">Display features</h2>

<h3 id="on-a-2025-summer-afternoon">On a 2025 summer afternoon…</h3>

<p>I messaged Alex Deucher to get some advice on where to start.
Alex was very considerate and helped me to get a good understanding of
how the code is organized, how the parts fit together and where I should start reading.
Harry Wentland also helped a lot with making a plan how to fit
analog connectors in DC.
Then, I plugged my monitors into my Raphael iGPU to be used as
a primary GPU, then plugged in an old Oland card as a secondary GPU, and started hacking.</p>

<h3 id="focus">Focus</h3>

<p>For the display, I decided that the best way forward is to add what is missing
from DC for these GPUs and use DC by default. That way, we can eventually get rid
of the legacy display code (which was always meant as a temporary solution until DC landed).</p>

<p>Additionally, I decided to focus on dedicated GPUs because these are the most useful for gaming
and are easy to test using a desktop computer.
There is still work left to do for CIK APUs.</p>

<h3 id="analog-connector-support-in-dc">Analog connector support in DC</h3>

<p>Analog connectors have been actually quite easy to deal with,
once I understood the structure
of the DC (display core) codebase.
I could use the legacy
display code as a reference.
The DAC (digital to analog converter) is actually programmed by the VBIOS,
and the driver just needs to call the VBIOS to tell it what to do.
Easier said than done, but not too hard.</p>

<p>It also turned out that some chips that already defaulted to DC (eg. Tonga, Hawaii)
also have analog connectors, which apparently just didn’t work on Linux by default.
<a href="https://lists.freedesktop.org/archives/amd-gfx/2025-July/127752.html">I managed to submit the first version of this in July</a>. Then I was sidetracked with a lot of other issues, so I submitted <a href="https://lists.freedesktop.org/archives/amd-gfx/2025-September/131174.html">the second version of the series</a> in September, which then got merged.</p>

<h3 id="going-shopping">Going shopping</h3>

<p>It is incredibly difficult to debug issues when you don’t have
the hardware to reproduce them yourself. Some developers have
a good talent for writing patches to fix issues without actually
seeing the issue, but I feel I still have a long way to go to be that good.
It was pretty clear from the beginning that the only way to
make sure my work actually works on all SI/CIK GPUs is to
test all of them myself.</p>

<p>So, I went ahead an acquired at least one of each SI and CIK chip.
I got most of them from used hardware ad sites, and Leonardo Frassetto sent me a few as well.</p>

<h3 id="fixing-dc-support-on-si-dce6">Fixing DC support on SI (DCE6)</h3>

<p>After I got the analog connector working using the old GPUs as a
secondary GPU, I thought it’s time to test how well it works
as a primary GPU. You know, the way most actual users would use them.
So I disabled the iGPU and booted my computer with each dGPU with <code class="language-plaintext highlighter-rouge">amdgpu.dc=1</code> to see what happens.
This is where things started going crazy…</p>

<ul>
  <li>Tahiti (R9 280X) booted into “no signal”, absolutely dead</li>
  <li>Oland (R7 250) had heavy flickering and hung very quickly</li>
  <li>Oland (Radeon 520) booted into “unsupported signal” with DC and massive flickering with non-DC</li>
  <li>Pitcairn (R9 270X) had some artifacts</li>
  <li>Cape Verde (HD 7770) I didn’t even plug it in at this point…</li>
  <li>Hainan fortunately doesn’t have DCE (display controller engine) so that wasn’t a problem</li>
</ul>

<p>The way to debug these problems is the following:</p>

<ul>
  <li>Boot with <code class="language-plaintext highlighter-rouge">amdgpu.dc=0</code>, dump all DCE registers using umr:
<code class="language-plaintext highlighter-rouge">umr -r oland.dce600..* &gt; oland_nodc_good.txt</code></li>
  <li>Boot with <code class="language-plaintext highlighter-rouge">amdgpu.dc=1</code>, dump all DCE registers using umr:
<code class="language-plaintext highlighter-rouge">umr -r oland.dce600..* &gt; oland_dc_bad.txt</code></li>
  <li>Compare the two DCE register dumps using a diff viewer, eg. Meld.
Try to find what are the register differences that are
responsible for the bad behaviour.</li>
  <li>Use umr (either the GUI or CLI) to try to change the registers in real time,
poke at it until the issue is gone.</li>
  <li>Wait until headache is gone.</li>
  <li>Read the code that sets the problematic registers and develop an actual fix.</li>
</ul>

<p>I decided to fix the bugs before adding new features.
I sent a few patch series to address a bunch of display issues mainly with SI (DCE6):</p>

<ul>
  <li><a href="https://lists.freedesktop.org/archives/amd-gfx/2025-July/127707.html">Fixed broken PLL programming and some mistakes</a></li>
  <li><a href="https://lists.freedesktop.org/archives/amd-gfx/2025-July/128002.html">Fixed DC “overclocking” the display clock and a few other issues</a> ― many years ago someone fixed an issue on Polaris by unconditionally raising the display clock by 15%,
but unfortunately they also applied this to older GPUs; additionally the display clock was already set higher than the max</li>
  <li><a href="https://lists.freedesktop.org/archives/amd-gfx/2025-August/129334.html">Fixed DVI-D/HDMI adapters</a> ― these
would just give a black screen when I plugged in a 4K monitor</li>
  <li>While at it, I also <a href="https://lists.freedesktop.org/archives/amd-gfx/2025-August/129353.html">fixed them in the legacy code</a></li>
  <li><a href="https://lists.freedesktop.org/archives/amd-gfx/2025-August/128102.html">Fixed a freeze caused by relying on a non-existent interrupt</a> ― it seems that DCE6 is not capable of VRR, so we just shouldn’t try to enable it
or rely on interrupts that don’t exist on this HW</li>
  <li><a href="https://lists.freedesktop.org/archives/amd-gfx/2025-September/130999.html">Fixed another black screen by rejecting too high pixel clocks</a> ― technically, DP supports the bandwidth required by
4K 120Hz using 6-bit color with YUV420 on SI/CIK/VI, so DC would happily advertise this mode, but the GPUs didn’t actually support a high enough display clock for 4K 120Hz</li>
  <li><a href="https://lists.freedesktop.org/archives/amd-gfx/2025-September/131126.html">Fixed an issue with the DCE6 scaler not being properly disabled</a> ― apparently the VBIOS sets up the scaler automatically on some GPUs,
which needs to be disabled by the kernel, otherwise you get weird artifacts</li>
</ul>

<h3 id="displayporthdmi-audio-support-on-si-dce6">DisplayPort/HDMI audio support on SI (DCE6)</h3>

<p>I noticed that HDMI audio worked alright on all GPUs with DC (as expected),
however DP audio didn’t (which was unexpected). However it worked when both DP and HDMI were plugged in…
After consulting with Alex and doing some trial
and error, it turned out that this was just due to setting some clock
frequency in the wrong way: <a href="https://lists.freedesktop.org/archives/amd-gfx/2025-August/128101.html">Fix DP audio DTO1 clock source on DCE6</a>.</p>

<p>In order to figure out the correct frequencies, I wrote a script that set the frequency using umr
then played a sound. I just laid back and let the script run until I heard the sound. Then
it was just a matter of figuring out why that frequency was correct.</p>

<p>A small fun fact: it turns out that DP audio on Tahiti didn’t work on any Linux driver before.
Now it works with DC.</p>

<h3 id="poweeeeer">Poweeeeer</h3>

<p>The DCE (Display Controller Engine), just like other parts of the GPU,
has its own power requirements and needs certain clocks, voltages, etc. It is the responsibility
of the power management code to make sure DCE gets the power it needs.
Unfortunately, DC didn’t talk to the legacy power management code.
Even more unfortunately, the power management code was buggy so that’s
what I started with.</p>

<ul>
  <li><a href="https://lists.freedesktop.org/archives/amd-gfx/2025-August/129608.html">SI power management fixes</a>
― contains some fixes to get Tahiti to boot with DC,
also it turns out that the SMC (system management controller)
needs a longer timeout to complete some tasks</li>
  <li><a href="https://lists.freedesktop.org/archives/amd-gfx/2025-September/131198.html">More SI power management and PLL fixes</a>
― most importantly this disables ASPM on SI, which caused “random hangs”</li>
  <li><a href="https://lists.freedesktop.org/archives/amd-gfx/2025-September/130166.html">Finally, this series hooks up SI to the legacy DPM code</a>
― this is required because the power management code needs to know how many and what kind of
displays are connected</li>
</ul>

<p>After I was mostly done with SI, I also fixed an issue with CIK,
where <a href="https://lists.freedesktop.org/archives/amd-gfx/2025-October/131879.html">the shutdown temperature was incorrectly reported</a>.</p>

<h2 id="vce1-video-encoding-on-si">VCE1 video encoding on SI</h2>

<p>Video encoding is usually an afterthought, not something that most users think about
unless they are interested in streaming or video transcoding.
It was definitely an afterthought for the hardware designers of SI,
which has the first generation VCE (video coding engine) that
only supports H264 and only up to 2048 x 1152.
However, the old <em>radeon</em> kernel driver supports this engine and
for anyone relying on this functionality, it would be a regression
when switching to <em>amdgpu</em>. So <a href="https://gitlab.freedesktop.org/drm/amd/-/issues/1776#note_2831578">we need to support it</a>. There was <a href="https://gitlab.freedesktop.org/drm/amd/-/issues/1776#note_1613496">already some work by Alexandre Demers</a> to support VCE1, but that work was stalled due to issues caused by the firmware validation mechanism.</p>

<p>In order to switch SI to <em>amdgpu</em> by default, I needed to deal with VCE1.
So I started a conversation with Christian König (<em>amdgpu</em> expert) to identify what the
problem actually was, and with Alexandre to see how far along his work was.</p>

<ul>
  <li>It turns out that due to some HW/FW limitations, the firmware (VCPU BO)
needs to be mapped at a low 32-bit address.</li>
  <li>It also needs to be in VRAM for optimal performance (otherwise it would incur too many roundtrips to system RAM).</li>
  <li>However, there was no way for <em>amdgpu</em> to place something in VRAM and map it in the low 32-bit address space.
(Note, it can actually do this for the address space of userspace apps, just not inside the kernel itself.)</li>
</ul>

<p>Christian helped me a lot with understanding how the memory controller and the page table work.</p>

<p>After I got over the headache, I came up with this idea:</p>

<ul>
  <li>Let <em>amdgpu</em> place the VCPU BO in VRAM</li>
  <li>Map the GART (graphics address remapping table)
in the low 32-bit address space (instead of using best fit)</li>
  <li>Insert a few page table entries in the GART which would practically
map the VCPU BO into the low 32-bit address space</li>
</ul>

<p>With that out of the way, the rest of the work on VCE1 was pretty straightforward.
I could use Alexandre’s research, as well as the VCE2 code from <em>amdgpu</em> and the VCE1 code from <em>radeon</em> as a reference.
Finally, a few reviews and three revisions later, <a href="https://lists.freedesktop.org/archives/amd-gfx/2025-November/133595.html">the VCE1 series was accepted</a>.</p>

<h2 id="final-thoughts">Final thoughts</h2>

<h3 id="who-is-this-for">Who is this for?</h3>

<p>In the current economic situation of our world,
I expect that people are going to use GPUs for much longer,
and replace them less often.
And when an old GPU is replaced, it doesn’t die, it goes
to somebody who upgrades an even older GPU.
Eventually it will reach somebody that can’t afford a better one.
There are some efforts to use Linux to keep old
computers alive, <a href="https://www.youtube.com/watch?v=NHLTOdsqDRg">for example this one</a>.
My goal with this work is to make Linux gaming a good experience
also for those who use old GPUs.</p>

<p>Other than that, I also did it for myself. Not because I want to run old GPUs myself,
but because it has been a great learning experience to get into the <em>amdgpu</em> kernel driver.</p>

<h3 id="why-amdgpu-why-dc">Why <em>amdgpu</em>? Why DC?</h3>

<p>The open source community including AMD themselves as well as other
entities like Valve, Igalia, Red Hat etc. have invested a lot of
time and effort into <em>amdgpu</em> and DC, which now support many generations
of AMD GPUs: GCN1-5, RDNA1-4, as well as CDNA.
In fact <em>amdgpu</em> supports more generations of GPUs now than what came before,
and it looks like it will support many generations of future GPUs.</p>

<p>By making <em>amdgpu</em> work well with SI and CIK, we ensure that these GPUs
remain competently supported for the foreseeable future.</p>

<p>By switching SI and CIK to use DC by default, we enable display features like atomic modesetting, VRR, HDR, etc.
and this also allows the <em>amdgpu</em> maintainers
to eventually move on from the legacy display code without losing functionality.</p>

<h3 id="what-is-left-to-do">What is left to do?</h3>

<p>Now that <em>amdgpu</em> is at feature parity with <em>radeon</em> on old GPUs,
we switched the default to <em>amdgpu</em> on SI and CIK dedicated GPUs.
It’s time to start thinking about what else is left to do.</p>

<ul>
  <li>Add support for DRM format modifiers for all SI/CIK/VI/Polaris GPUs.
This would be a huge step forward for the Vulkan ecosystem,
it would enable using purely Vulkan based compositors, Zink, and other features.</li>
  <li>Add support for TRAVIS and NUTMEG display bridges, so that we can also
switch to <em>amdgpu</em> by default for CIK APUs.
I couldn’t find the hardware for this work (mainly looking for Kaveri APUs), if you have it and want to help, please reach out. Your <code class="language-plaintext highlighter-rouge">dmesg</code> log will mention if the APU uses TRAVIS or NUTMEG.</li>
  <li>Refactor SI and KV power management so that we can retire the legacy
power management code, which would further ease the maintenance burden of these GPUs.</li>
  <li>Eventually retire the non-DC legacy display code from <em>amdgpu</em> to ease the maintenance burden.</li>
  <li>Deal with a few lingering bugs, such as <a href="https://gitlab.freedesktop.org/drm/amd/-/issues/2390">power limit on Radeon 430</a>,
black screen with the analog connector on Radeon HD 7790,
as well as <a href="https://gitlab.freedesktop.org/mesa/mesa/-/merge_requests/37885/diffs?commit_id=765a748840e6a67d64c2b29b149f6aadee3a39fd">reenable compute queues on SI</a>, <a href="https://gitlab.freedesktop.org/mesa/mesa/-/merge_requests/38769">mitigate VM faults on SI/CIK</a>, etc.</li>
  <li>Verify sparse mapping (PRT) support. I already wrote <a href="https://lists.freedesktop.org/archives/amd-gfx/2025-November/134153.html">a kernel fix</a> and <a href="https://gitlab.freedesktop.org/mesa/mesa/-/merge_requests/38553">a Mesa MR</a>
for enabling it.</li>
  <li>Implement transfer queue support for old GPUs in RADV.</li>
</ul>

<h3 id="what-have-i-learned-from-all-this">What have I learned from all this?</h3>

<h4 id="it-isnt-that-scary">It isn’t that scary</h4>

<p>Kernel development is not as scary as it looks.
It is a different technical challenge than what I was used to,
but not in a bad way. Just needed to figure out a good workflow
for how to configure a code editor, as well as what is a good way
to test my work without rebuilding everything all the time.</p>

<h4 id="maintainers-are-friendly">Maintainers are friendly</h4>

<p><strong>AMD engineers have been very friendly and helpful to me all the way.</strong>
Although there are a lot of memes and articles on the internet
about attitude and rude/toxic messages by some kernel developers,
I didn’t see that in <em>amdgpu</em> at least.</p>

<p>My approach was that even before I wrote a single line of code,
I started talking to the maintainers (who would eventually review my patches)
to find out what would be the good solution to them and how to get my work accepted.
Communicating with the maintainers saved a lot of time and made the work faster, more pleasant and more collaborative.</p>

<h4 id="development-latency">Development latency</h4>

<p>Sadly, there is a huge latency between a Linux kernel developer working on something
and the work reaching end users. Even if the patches are accepted quickly, it can take
3~6 months until users can actually use it.</p>

<ul>
  <li>In Mesa, we can merge any features to the next Mesa release up to the branch point,
and afterwards we backport bug fixes to that release. Simple and efficient.</li>
  <li>In the Linux kernel, there is a deadline for merging new features to the next release,
(it’s not clearly communicated when that is). Bug fixes may be backported to
previous releases any time, but upstream maintainers aren’t involved in that.</li>
</ul>

<p>In hindsight, if I had focused on finishing the analog support and VCE1 first (instead of fixing all the bugs I found),
my work would have ended up in Linux 6.18 (including the bug fixes, as there is no deadline for those).
Due to how I prioritized bug fixing, the features I’ve developed are only included in Linux 6.19,
so this will be the version where SI and CIK will default to amdgpu by default.</p>

<h4 id="xdc-2025">XDC 2025</h4>

<p>I presented a lightning talk on this topic at XDC 2025,
where I talked about the state of SI and CIK support as of September 2025.
You can find <a href="https://indico.freedesktop.org/event/10/contributions/429/attachments/246/332/xdc2025_old_gpus.pdf">the slide deck here</a> and the <a href="https://www.youtube.com/watch?v=3L5OE9gmWGE&amp;t=492s">video here</a>.</p>

<h3 id="acknowledgements">Acknowledgements</h3>

<p>I’d like to say a big thank you to all of these people.
All of the work I mentioned in this post would not have been
possible without them.</p>

<ul>
  <li>Alex Deucher, Christian König (amdgpu devs)</li>
  <li>Harry Wentland, Rodrigo Siquiera (DC devs)</li>
  <li>Marek Olsák, Pierre-Eric Pelloux-Prayer (radeonsi devs)</li>
  <li>Bas Nieuwenhuizen, Samuel Pitoiset (radv devs)</li>
  <li>Martin Roukala, né Peres (CI expert)</li>
  <li>Tom St Dennis (umr dev)</li>
  <li>Mauro Rossi (DCE6 in DC)</li>
  <li>Alexandre Demers (VCE1 research)</li>
  <li>Leonardo Frassetto (HW donation)</li>
  <li>Roman Elshin and others (testing)</li>
  <li>Pierre-Loup Griffais (Valve)</li>
</ul>

<h3 id="which-graphics-cards-are-affected-exactly">Which graphics cards are affected exactly?</h3>

<p>When in doubt, <a href="https://en.wikipedia.org/wiki/List_of_AMD_graphics_processing_units">consult Wikipedia</a>.</p>

<p>GFX6 aka. GCN1 - Southern Islands (SI) dedicated GPUs:
<em>amdgpu</em> is now the default kernel driver as of Linux 6.19.
The DC display driver is now the default and is now usable for these GPUs.
DC now supports analog connectors, power management is less buggy, and video encoding is now supported by <em>amdgpu</em>.</p>

<ul>
  <li>Tahiti
    <ul>
      <li>Radeon HD 7870 XT, 7950, 7970, 7990, 8950, 8970, 8990</li>
      <li>Radeon R9 280, 280X</li>
      <li>FirePro W8000, W9000, D500, D700, S9000, S9050, S10000</li>
      <li>Radeon Sky 700, 900</li>
    </ul>
  </li>
  <li>Pitcairn
    <ul>
      <li>Radeon HD 7850, 7870, 7970M, 8870, 8970M</li>
      <li>Radeon R9 265, 270, 270X, 370, 370X, M290X, M390</li>
      <li>FirePro W5000, W7000, D300, R5000, S7000</li>
    </ul>
  </li>
  <li>Cape Verde
    <ul>
      <li>Radeon HD 7730, 7750, 7770, 8730, 8760</li>
      <li>Radeon R7 250E, 250X, 350, 450</li>
      <li>FirePro W600, W4100, M4000, M6000</li>
    </ul>
  </li>
  <li>Oland
    <ul>
      <li>Radeon HD 8570, 8670</li>
      <li>Radeon R5 240, 250, 330, 340, 350, 430, 520, 610</li>
      <li>FirePro W2100</li>
      <li>various mobile GPUs</li>
    </ul>
  </li>
  <li>Hainan
    <ul>
      <li>various mobile GPUs</li>
    </ul>
  </li>
</ul>

<p>GFX7 aka. GCN2 - Sea Islands (CIK) dedicated GPUs:
<em>amdgpu</em> is now the default kernel driver as of Linux 6.19.
The DC display driver is now the default for Bonaire (was already the case for Hawaii).
DC now supports analog connectors. Minor bug fixes.</p>

<ul>
  <li>Hawaii
    <ul>
      <li>Radeon R9 290, 290X, 295X2, 390, 390X</li>
      <li>FirePro W8100, W9100, S9100, S9150, S9170</li>
    </ul>
  </li>
  <li>Bonaire
    <ul>
      <li>Radeon HD 7790/8870</li>
      <li>Radeon R7 260/360/450</li>
      <li>Radeon RX 455, FirePro W5100, etc.</li>
      <li>various mobile GPUs</li>
    </ul>
  </li>
</ul>

<p>GFX8 aka. GCN3 - Volcanic Islands (VI) dedicated GPUs:
DC now supports analog connectors.<br />
(Note that <em>amdgpu</em> and DC were already supported on these GPUs since release.)</p>

<ul>
  <li>Tonga
    <ul>
      <li>Radeon R9 285, 380, 380X</li>
    </ul>
  </li>
  <li>(other chips of this family are not affected by the work in this post)</li>
</ul>]]></content><author><name>Timur Kristóf</name></author><category term="graphics" /><category term="freedesktop" /><category term="work" /><summary type="html"><![CDATA[AMD GPUs are famous for working very well on Linux. However, what about the very first GCN GPUs? Are they working as well as the new ones? In this post, I’m going to summarize how well these old GPUs are supported and what I’ve been doing to improve them.]]></summary></entry><entry><title type="html">Understanding your Linux open source drivers</title><link href="https://timur.hu/blog/2025/understanding-your-linux-open-source-drivers" rel="alternate" type="text/html" title="Understanding your Linux open source drivers" /><published>2025-12-22T00:52:00+01:00</published><updated>2025-12-22T00:52:00+01:00</updated><id>https://timur.hu/blog/2025/understanding-your-linux-open-source-drivers</id><content type="html" xml:base="https://timur.hu/blog/2025/understanding-your-linux-open-source-drivers"><![CDATA[<p>After introducing how graphics drivers work in general,
I’d like to give a brief overview about what is what
in the Linux graphics stack, what are the important parts
and what the key projects are where the development happens,
as well as what you need to do to get the best user experience out of it.</p>

<h2 id="the-open-source-linux-graphics-driver-stack">The open source Linux graphics driver stack</h2>

<p>Please refer to <a href="/blog/2025/how-do-graphics-drivers-work">my previous post</a> for a more detailed general explanation
on graphics drivers in general. This post focuses on how things work
in the open source graphics stack on Linux.</p>

<h3 id="which-gpus-are-supported">Which GPUs are supported?</h3>

<p>We have open source drivers for the GPUs from all major manufacturers
with varying degrees of success.</p>

<ul>
  <li>Some companies (eg. AMD, Intel and others) choose to participate
in the open source community and develop open source drivers themselves,
with contributions also coming from other parties (eg. Valve, Red Hat, Google, etc).
If you have an AMD or Intel GPU, their open source drivers typically
work better than their alternatives (if any), and have been for a long time.</li>
  <li>Others (eg. NVidia and Apple) don’t recognize the benefits of this style
of development and
leave it to the community to create drivers based on reverse-engineering
or sometimes minimal help from the manufacturer.
If you have an NVidia GPU, as of late 2025 the open source drivers
may not be quite ready just yet.
In this post I am not going to discuss the proprietary drivers.</li>
</ul>

<h3 id="what-parts-do-you-need">What parts do you need?</h3>

<p>The components you need in order to get your GPU working on
open source drivers on a Linux distro are the following:</p>

<ul>
  <li><strong>Linux kernel</strong> (obviously) ― contains the open source kernel drivers (KMD).</li>
  <li><strong>linux-firmware</strong> ― contains the necessary firmware.
Note that even when the actual drivers are open source,
most (all?) GPUs require closed source firmware to function.</li>
  <li><strong>Mesa</strong> ― contains the most userspace drivers (relevant to gaming)
as well as a shader compiler stack.</li>
  <li><strong>LLVM</strong> ― needed by some Mesa drivers for shader compilation.</li>
  <li>Some vendors have other projects (eg. AMD <strong>ROCm</strong>)
for supporting other features that aren’t part of Mesa.
These parts are out of scope for this blog post.</li>
</ul>

<p>To make your GPU work, you need new enough versions of
the Linux kernel, linux-firmware and Mesa (and LLVM) that include support for your GPU.</p>

<p>To make your GPU work <strong>well</strong>, I highly recommend to use
the <strong>latest stable versions</strong> of all of the above.
If you use old versions, you are missing out.
By using old versions you are choosing not to benefit from the latest
developments (features and bug fixes) that open source developers have worked on,
and you will have a sub-par experience (especially on relatively new hardware).</p>

<h3 id="wait-arent-the-drivers-in-the-kernel">Wait, aren’t the drivers in the kernel?</h3>

<p>If you read Reddit posts, you will stumble upon some people
who believe that “the drivers are in the kernel” on Linux.
This is a half-truth.
Only the KMDs are part of the kernel, everything else (linux-firmware, Mesa, LLVM) is distributed in separate packges.
How exactly those packages are organized, depends on your distribution.</p>

<h3 id="what-is-the-mesa-project">What is the Mesa project?</h3>

<p>Mesa is a collection of userspace drivers which implement various
different APIs. It is the cornerstone of the open source graphics stack.
I’m going to attempt to give a brief overview of what are the most
relevant parts of Mesa.</p>

<h4 id="gallium">Gallium</h4>

<p>An important part of Mesa is the Gallium driver infrastructure, which
contains a lot of common code for implementing different APIs, such as:</p>

<ul>
  <li>Graphics: OpenGL, OpenGL ES, EGL</li>
  <li>Compute: OpenCL</li>
  <li>Video decoding and encoding: VAAPI (previously also VDPAU)</li>
</ul>

<h4 id="vulkan">Vulkan</h4>

<p>Mesa also contains a collection of Vulkan drivers.
Originally, Vulkan was deemed “lower level than Gallium”,
so Vulkan drivers are not part of the Gallium driver infrastructure.
However, Vulkan has a lot of overlapping functionality with the
aforementioned APIs, so Vulkan drivers still share a lot of code with
their Gallium counterparts when appropriate.</p>

<h4 id="nir">NIR</h4>

<p>Another important part of Mesa is the NIR shader compiler stack,
which is at the heart of every Mesa driver that is still being maintained.
This enables sharing a lot of compiler code across different drivers.
I highly recommend Faith Ekstrand’s post <a href="https://www.jlekstrand.net/jason/blog/2022/01/in-defense-of-nir/">In defense of NIR</a> to learn more about it.</p>

<h3 id="compatibility-layers-and-api-translation">Compatibility layers and API translation</h3>

<p>Technically they are not drivers, but
in practice, if you want to run Windows games,
you will need a compatibility layer like Wine or Proton,
including graphics translation layers.
The recommended ones are:</p>

<ul>
  <li><a href="https://github.com/doitsujin/dxvk">DXVK</a>: translates DirectX 8-11 to Vulkan.</li>
  <li><a href="https://github.com/HansKristian-Work/vkd3d-proton/">VKD3D-Proton</a>: translates DirectX 12 to Vulkan.</li>
</ul>

<p>Those are default in Proton and offer the best performance.
However, for “political” reasons, these are sadly not the defaults in Wine,
so either you’ll have to use Proton or make sure to install the above in Wine manually.</p>

<p>Just for the sake of completeness, I’ll also mention the Wine defaults:</p>

<ul>
  <li>WineD3D: translates DirectX 1-11 to OpenGL.
It is what we all used before Vulkan and DXVK existed,
sadly its performance and compatibility has always been lacking.</li>
  <li>VKD3D: translates DirectX 12 to Vulkan.
Not practically usable.
Can only actually run a select few games,
and those with lackluster performance.
(Not to be confused with VKD3D-Proton, which is actually fully-featured.)</li>
</ul>

<h3 id="side-note-about-window-systems">Side note about window systems</h3>

<p>Despite the X server being abandoned for a long time, there is still
a debate between Linux users whether to use a Wayland compositor
or the X server.
I’m not going to discuss the advantages and disadvantages of these,
because I don’t participate in their development and I feel it has
already been well-explained by the community.</p>

<p>I’m just going to say that it helps to choose a competent
compositor that implements direct scanout.
This means that the frames as rendered by your game can be sent directly
to the display without the need for the compositor to do any additional
processing on it.</p>

<p>In this blog post I focus on just the driver stack,
because that is largely shared between both solutions.</p>

<h3 id="making-your-games-run-well">Making your games run (well)</h3>

<p>Sadly, many Linux distributions choose to ship old versions of the kernel and/or
other parts of the driver stack, giving their users a sub-par experience.
Debian, Ubuntu LTS and their derivatives like Mint, Pop OS, etc. are
all guilty of this.
They justify this by claiming that older versions are more reliable,
but this is actually not true.</p>

<p>In reality, us driver developers as well as the developers of the API translation layers
work hard to implement new features that are needed to get new games working,
as well as fixing bugs that are exposed by new games (or updates of old games).</p>

<p>Regressions are real, but they are usually quickly fixed thanks to the
extensive testing that we do: every time we merge new code, our automated
testing system runs the full Vulkan conformance test suite to make sure that
all functionality is still intact, thanks to <a href="https://mupuf.org/blog/">Martin’s genious</a>.</p>]]></content><author><name>Timur Kristóf</name></author><category term="graphics" /><category term="freedesktop" /><category term="work" /><summary type="html"><![CDATA[After introducing how graphics drivers work in general, I’d like to give a brief overview about what is what in the Linux graphics stack, what are the important parts and what the key projects are where the development happens, as well as what you need to do to get the best user experience out of it.]]></summary></entry><entry><title type="html">How do graphics drivers work?</title><link href="https://timur.hu/blog/2025/how-do-graphics-drivers-work" rel="alternate" type="text/html" title="How do graphics drivers work?" /><published>2025-12-16T01:09:44+01:00</published><updated>2025-12-16T01:09:44+01:00</updated><id>https://timur.hu/blog/2025/how-do-graphics-drivers-work</id><content type="html" xml:base="https://timur.hu/blog/2025/how-do-graphics-drivers-work"><![CDATA[<p>I’d like to give an overview on how graphics drivers work in general,
and then write a little bit about the Linux graphics stack for AMD GPUs.
The intention of this post is to clear up a bunch of misunderstandings
that people have on the internet about open source graphics drivers.</p>

<h2 id="what-is-a-graphics-driver">What is a graphics driver?</h2>

<p>A graphics driver is a piece of software code that is written for the
purpose of allowing programs on your computer to access the features
of your GPU. Every GPU is different and may have different capabilities
or different ways of achieving things, so they need different
drivers, or at least different code paths in a driver that may
handle multiple GPUs from the same vendor and/or the same hardware generation.</p>

<p>The main motivation for graphics drivers is to allow applications
to utilize your hardware efficiently.
This enables games to render pretty pixels,
scientific apps to calculate stuff,
as well as video apps to encode / decode efficiently.</p>

<h2 id="organization-of-graphics-drivers">Organization of graphics drivers</h2>

<p>Compared to drivers for other hardware, graphics is very complicated
because the functionality is very broad and the differences between
each piece of hardware can be also vast.</p>

<p>Here is a simplified explanation on how a graphics driver stack usually works.
Note that most of the time, these components (or some variation)
are bundled together to make them easier to use.</p>

<ul>
  <li><strong>GPU firmware (FW)</strong> ―
low-level code for power management, context switching, command processing, display engine, video encoding/decoding, etc.</li>
  <li><strong>Kernel driver, aka. kernel-mode driver (KMD)</strong> ―
makes it possible for multiple userspace applications to submit commands to the GPU,
and is responsible for memory management and display functionality.</li>
  <li><strong>Userspace driver, aka. user-mode driver (UMD)</strong> ―
responsible for implementing an API, such as Vulkan, OpenGL, etc.
For each piece of hardware, there may be multiple different UMDs implementing different APIs.</li>
  <li><strong>Shader compiler</strong> ―
a userspace library that compiles shader programs
for your GPU from the HW-independent code that applications have.
Can be possibly shared between UMDs, sometimes developed as a separate project.</li>
</ul>

<p>I’ll give a brief overview of each component below.</p>

<h3 id="gpu-firmware">GPU firmware</h3>

<p>Most GPUs have additional processors (other than the shader cores)
which run a firmware that is responsible for operating
the low-level details of the hardware,
usually stuff that is too low-level even for the kernel.</p>

<p>The firmware on those processors are responsible for:
power management, context switching, command processing, display,
video encoding/decoding etc.
Among other things it parses the commands we submitted to it,
launches shaders, distributes work between the shader cores etc.</p>

<p>Some GPU manufacturers are moving more and more functionality
to firmware, which means that the GPU can operate more
autonomously and less intervention is needed by the CPU.
This tendency is generally positive for reducing CPU time
spent on programming the GPU (as well as “CPU bubbles”),
but at the same time it also means that the way the GPU
actually works becomes less transparent.</p>

<h3 id="kernel-driver">Kernel driver</h3>

<p>You might ask, why not implement all driver functionality in the kernel?
Wouldn’t it be simpler to “just” have everything in the kernel?
The answer is <strong>no</strong>, mainly because there is a LOT going on which nobody wants in the kernel.</p>

<ul>
  <li>You don’t want to have your kernel crash when a game misbehaves.
Sadly it can still happen, but it would happen a lot more if the
kernel and userspace components weren’t separated.</li>
  <li>You definitiely don’t want to run a fully-fledged compiler inside your kernel
which takes arbitrary input from the user.</li>
  <li>You want to avoid having to upgrade your kernel to deploy most fixes and improvements
to the graphics stack.
(This is not always avoidable but can be minimized.)</li>
</ul>

<p>So, usually, the KMD is only left with some low-level tasks that every user needs:</p>

<ul>
  <li>Command submission userspace API:
an interface that allows userspace processes to submit commands to the GPU,
query information about the GPU, etc.</li>
  <li>Memory management:
deciding which process gets to use how much VRAM,
defining GTT,
handling low-memory situations,
etc.</li>
  <li>Display functionality:
making display connectors work, by programming the registers of the display controller.
There is also a separate uAPI for just this purpose.</li>
  <li>Power management:
making sure the GPU doesn’t draw too much power when not needed,
and also making sure applications can get the best clock speeds etc. when that is needed,
in cooperation with the power management firmware.</li>
  <li>GPU recovery:
when the GPU hangs or crashes for some reason,
it’s the kernel’s responsibility to ensure that the GPU can be recovered
and that the crash doesn’t affect other processes.</li>
</ul>

<h3 id="userspace-driver">Userspace driver</h3>

<p>Applications interact with userspace drivers instead of the kernel
(or the hardware directly).
Userspace drivers are compiled as shared libraries and are responsible for
implementing one or more specific APIs for graphics, compute or video
for a specific family of GPUs.
(For example, Vulkan, OpenGL or OpenCL, etc.)
Each graphics API has entry points which load the
available driver(s) for the GPU(s) in the user’s system.
The Vulkan loader is an example of this;
other APIs have similar components for this purpose.</p>

<p>The main functionality of a userspace driver is to take the commands from the API
(for example, draw calls or compute dispatches)
and turn them into low level commands in a binary format that the GPU can understand.
In Vulkan, this is analogous to recording a command buffer.
Additionally, they utilize a <strong>shader compiler</strong> to turn a higher level shader language (eg. GLSL)
or bytecode (eg. SPIR-V) into hardware instructions which the GPU’s shader cores can execute.</p>

<p>Furthermore, userspace drivers also take part in memory management,
they basically act as an interface between the memory model of the graphics API
and kernel’s memory manager.</p>

<p>The userspace driver calls the aforementioned kernel uAPI to submit the
recorded commands to the kernel which then schedules it and hands it to the
firmware to be executed.</p>

<h3 id="shader-compiler">Shader compiler</h3>

<p>If you’ve seen a loading screen in your favourite game which told you it was
“compiling shaders…” you probably wondered what that’s about and why it’s necessary.</p>

<p>Unlike CPUs which have converged to a few common instruction set architectures (ISA),
GPUs are a mess and don’t share the same ISA, not even between different GPU models
from the same manufacturer.
Although most modern GPUs have converged to SIMD based architectures,
the ISA is still very different between manufacturers and it still changes
from generation to generation
(sometimes different chips of the same generation have slightly different ISA).
GPU makers keep adding new instructions when they identify new ways
to implement some features more effectively.</p>

<p>To deal with all that mess, graphics drivers have to do online compilation of shaders
(as opposed to offline compilation which usually happens for apps running on your CPU).</p>

<p>This means that shaders have to be recompiled when the userspace graphics driver is updated
either because new functionality is available or
because bug fixes were added to the driver and/or compiler.</p>

<h3 id="but-i-only-downloaded-one-driver">But I only downloaded <strong>one</strong> driver!</h3>

<p>On some systems (especially proprietary operating systems like Windows), GPU manufacturers
intend to make users’ lives easier by offering all of the above in a single installer package,
which is just called “the driver”.</p>

<p>Typically such a package includes:</p>

<ul>
  <li>Firmware files for all hardware that the package supports</li>
  <li>A kernel driver</li>
  <li>Several userspace drivers for various APIs</li>
  <li>A shader compiler (sometimes more) that is used by those userspace drivers</li>
  <li>A “user-friendly” application (ie. a control panel) to present all the functionality to the user</li>
  <li>Various other utilities and libraries (that you may or may not need).</li>
</ul>

<h3 id="but-i-didnt-download-any-drivers">But I didn’t download <strong>any</strong> drivers!</h3>

<p>On some systems (typically on open source systems like Linux distributions),
usually you can already find a set of packages to handle most common hardware,
so you can use most functionality out of the box without needing to install anything manually.</p>

<p>Neat, isn’t it?</p>

<p>However, on open source systems, the graphics stack is more transparent,
which means that there are many parts that are scattered across different
projects, and in some cases there is more than one driver available for the same HW.
To end users, it can be very confusing.</p>

<p>However, this doesn’t mean that open source drivers are designed worse.
It is just that due to their community oriented nature,
they are organized differently.</p>

<p>One of the main sources of confusion is that various Linux distributions
mix and match different versions of the kernel with different versions of different UMDs
which means that users of different distros can get a wildly different
user experience based on the choices made for them by the developers of the distro.</p>

<p>Another source of confusion is that we driver developers are really, <strong>really</strong> bad
at naming things, so sometimes different projects end up having the same name,
or some projects have nonsensical or outdated names.</p>

<h3 id="the-linux-graphics-stack">The Linux graphics stack</h3>

<p><a href="/blog/2025/understanding-your-linux-open-source-drivers">In the next post</a>, I’ll continue this story and discuss how the above
applies to the open source Linux graphics stack.</p>]]></content><author><name>Timur Kristóf</name></author><category term="graphics" /><category term="freedesktop" /><category term="work" /><summary type="html"><![CDATA[I’d like to give an overview on how graphics drivers work in general, and then write a little bit about the Linux graphics stack for AMD GPUs. The intention of this post is to clear up a bunch of misunderstandings that people have on the internet about open source graphics drivers.]]></summary></entry><entry><title type="html">Rabbit holes in shader linking</title><link href="https://timur.hu/blog/2024/shader-linking-rabbit-holes" rel="alternate" type="text/html" title="Rabbit holes in shader linking" /><published>2024-06-10T19:17:44+02:00</published><updated>2024-06-10T19:17:44+02:00</updated><id>https://timur.hu/blog/2024/shader-linking-rabbit-holes</id><content type="html" xml:base="https://timur.hu/blog/2024/shader-linking-rabbit-holes"><![CDATA[<p>In <a href="/blog/2024/shader-linking-intro">the previous post</a> I gave an introduction to shader linking.
<a href="https://www.supergoodcode.com/adventures-in-linking/">Mike has already blogged about this topic</a>
a while ago, focusing mostly on Zink, and now it’s time for me to share some of my adventures about it too,
but of course focusing on how we improved it in RADV and the various rabbit holes that
this work has lead me to.</p>

<h2 id="motivation-for-improving-shader-linking-in-radv">Motivation for improving shader linking in RADV</h2>

<p>In Mesa, we mainly represent shaders in NIR (the NIR intermediate representation) and
that is where link-time optimizations happen.</p>

<p>The big news is that Marek Olšák wrote a new pass called
<code class="language-plaintext highlighter-rouge">nir_opt_varyings</code> which is an all-in-one solution to all the optimizations above, and
now authors of various drivers are rushing to take advantage of this new code.
We can’t miss the opportunity to start using <code class="language-plaintext highlighter-rouge">nir_opt_varyings</code> in RADV too,
so that’s what I’ve been working on for the past several weeks.</p>

<p>It is intended to replace all of the previous linking passes and can do all of the following:</p>

<ul>
  <li>Remove unused outputs and undefined inputs (including “system values”)</li>
  <li>Code motion between stages</li>
  <li>Compaction of I/O space</li>
</ul>

<p>So, I started by adding a call to <code class="language-plaintext highlighter-rouge">nir_opt_varyings</code> and went from there.</p>

<h2 id="enabling-the-new-linking-optimization-in-radv">Enabling the new linking optimization in RADV</h2>

<p>The naive reader might think using the new pass is as simple as
going to <code class="language-plaintext highlighter-rouge">radv_link_shaders</code> and calling <code class="language-plaintext highlighter-rouge">nir_opt_varyings</code> there.
But it can never be that easy, can it?</p>

<p>The issue is that one can’t simply deal with shader linking.
We also need to get our hands dirty with all the details of how shader I/O works
on a very low level.</p>

<h3 id="io-variable-dereferece-vs-lowered-explicit-io">I/O variable dereferece vs. lowered explicit I/O</h3>

<p>The first problem is that RADV’s current linking solution <code class="language-plaintext highlighter-rouge">radv_link_shaders</code>
works with the shaders when their I/O variables are still intact,
meaning that they are still treated as dereferenced variables.
However <code class="language-plaintext highlighter-rouge">nir_opt_varyings</code> expects to work with explicit I/O.</p>

<p>In fact, all of RADV’s linking code all works based on I/O variables and dereferences,
so much so that it’d be too much to refactor all of that
(and such refactoring probably would have its own set of problems and rabbit holes).
So the solution here is to add a new linking step that runs after <code class="language-plaintext highlighter-rouge">nir_lower_io</code> and
call the new pass in there.</p>

<ul>
  <li><a href="https://gitlab.freedesktop.org/mesa/mesa/-/merge_requests/28676">Here is the MR that enables <code class="language-plaintext highlighter-rouge">nir_opt_varyings</code> in RADV</a></li>
</ul>

<p>After writing the above, I quickly discovered that
some tests crash, others fail, and most applications render incorrectly.
So I’ve set out on a journey to solve all that.</p>

<h2 id="the-rabbit-holes">The rabbit holes</h2>

<h3 id="shader-io-information-collection">Shader I/O information collection</h3>

<p>Like every driver, RADV needs to collect certain information about every shader in
order to program the GPU’s registers correctly before a draw.
This information includes the number of inputs / outputs (and which slots are used),
in order to determine how much LDS needs to be allocated (in case of tessellation shaders)
or how much FS inputs are needed, etc.</p>

<p>This is done by <code class="language-plaintext highlighter-rouge">radv_nir_shader_info_pass</code> which also operated on I/O variables,
rather than information from I/O instructions.
However, after <code class="language-plaintext highlighter-rouge">nir_lower_io</code> the explicit I/O instructions may no longer be in
sync with the original I/O variables. This wasn’t a problem before because we
haven’t done any optimizations on explicit I/O so we could rely on I/O variable
information being accurate.</p>

<p>However, in order to use an optimization based on explicit I/O,
the RADV shader info pass had to be refactored
to collect its information from explicit I/O intrinsics, otherwise we wouldn’t be
able to have up-to-date information after running <code class="language-plaintext highlighter-rouge">nir_opt_varyings</code>, resulting
in wrong register programming.</p>

<ul>
  <li><a href="https://gitlab.freedesktop.org/mesa/mesa/-/merge_requests/28172">Part 1 of refactoring RADV to use IO semantics, covering everything but FS</a></li>
  <li><a href="https://gitlab.freedesktop.org/mesa/mesa/-/merge_requests/28506">Part 2 of refactoring RADV to use IO semantics, covering FS and deleting IO variables afterwards</a></li>
</ul>

<h3 id="dealing-with-driver-locations">Dealing with driver locations</h3>

<p>Driver location assignment is how the driver decides which input and output
goes to which “slot” or “address”. RADV did this after linking,
but still based on I/O variables, so the mechanism needed to be re-thought.</p>

<p>It also came to my attention that
<a href="https://gitlab.freedesktop.org/mesa/mesa/-/issues/10948">there are some plans to deprecate the concept of driver locations in NIR
in favour of so-called I/O semantics</a>.
So I had to do my refactor with this in mind; I spent some effort on removing
our uses of driver locations in order to make the new code somewhat future-proof.</p>

<p>For most stage combinations, <code class="language-plaintext highlighter-rouge">nir_recompute_io_bases</code> can be used as a stopgap to
simply reassign the driver locations based on the assumption that a shader will
only write the outputs that the next stage reads.
However, this is somewhat difficult to achieve for tessellation shaders because of their
unique “brain puzze” (TCS can read its own outputs, so the compiler can’t simply
remove TCS outputs when TES doesn’t read them).</p>

<ul>
  <li><a href="https://gitlab.freedesktop.org/mesa/mesa/-/merge_requests/28553">Removed driver locations for trivial cases</a></li>
  <li><a href="https://gitlab.freedesktop.org/mesa/mesa/-/merge_requests/28488">Refactored tessellation I/O to be independent of driver locations</a> (based on all the other work listed below on tessellation shader I/O)</li>
</ul>

<h3 id="tessellation-control-shader-epilogs">Tessellation control shader epilogs</h3>

<p>Due to the unique brain puzzle that is I/O in tessellation shaders,
they require extra brain power…
shader linking between TCS and TES was implemented
all over the place; even our backend compiler ACO had some dependence on TCS linking information,
which made any kind of refactor difficult.
At the time, <code class="language-plaintext highlighter-rouge">VK_EXT_shader_object</code> was new, and our implementation
used so-called <em>shader epilogs</em> to deal with the dynamic states of the TCS
(including in OpenGL for RadeonSI),
which is what ACO needed the linking information for.</p>

<p>After a discussion with the team, we decided that TCS epilogs had to go;
not only because of my shader linking effort, but also to make the
code base saner and more maintainable.</p>

<ul>
  <li><a href="https://gitlab.freedesktop.org/mesa/mesa/-/merge_requests/28371">I changed the code to pass tess factors in registers</a></li>
  <li><a href="https://gitlab.freedesktop.org/mesa/mesa/-/merge_requests/28408">Then I entirely deleted TCS epilogs from RADV</a></li>
  <li><a href="https://gitlab.freedesktop.org/mesa/mesa/-/merge_requests/28425">Finally I also deleted them from RadeonSI, allowing it to be ultimately removed from ACO as well</a></li>
</ul>

<p>This effort made our code lighter by about 1200 LOC.</p>

<h3 id="tessellation-shader-io">Tessellation shader I/O</h3>

<p>On AMD hardware, TCS outputs are implemented using LDS (when the TCS reads them)
and VRAM (when the TES reads them), which means that the driver has two different
ways to store these variables depending on their use. However, since the code
was based on <code class="language-plaintext highlighter-rouge">driver_location</code> and there can only be one driver location,
we used effectively the same location for both LDS and VRAM, which was suboptimal.</p>

<p>With the TCS epilog out of the way, now <code class="language-plaintext highlighter-rouge">ac_nir_lower_tess_io_to_mem</code> is free to
choose the LDS layout because the drivers no longer need to generate a TCS epilog
that would need to make assumptions about their memory layout.</p>

<ul>
  <li><a href="https://gitlab.freedesktop.org/mesa/mesa/-/merge_requests/28487">Changed the LDS location to be independent of the VRAM location, making it more efficient</a></li>
  <li><a href="https://gitlab.freedesktop.org/mesa/mesa/-/merge_requests/28544">Also removed an extra dword of unused LDS when VS outputs don’t need it</a></li>
  <li><a href="https://gitlab.freedesktop.org/mesa/mesa/-/merge_requests/28490">Refactored the SGPR arg that contains the dynamic state</a></li>
  <li>With all of that, I found an inefficiency in an ACO optimization, so
<a href="https://gitlab.freedesktop.org/mesa/mesa/-/merge_requests/28545">that had to be fixed too</a></li>
  <li><a href="https://gitlab.freedesktop.org/mesa/mesa/-/merge_requests/28739">Fix of an unintended regression</a></li>
  <li><a href="https://gitlab.freedesktop.org/mesa/mesa/-/merge_requests/28015">In the meantime, Samuel has found an opportunity to share some code between RADV and RadeonSI</a></li>
  <li>After all the above was merged and tessellation I/O was independent from driver locations,
<a href="https://gitlab.freedesktop.org/mesa/mesa/-/merge_requests/29436">I also made another MR to undo a small stats regression</a> by using a more optimal VRAM layout as well.</li>
  <li><a href="https://gitlab.freedesktop.org/mesa/mesa/-/merge_requests/29696">Fixing another regression</a></li>
</ul>

<h3 id="packed-16-bit-io">Packed 16-bit I/O</h3>

<p>One of the innovations of <code class="language-plaintext highlighter-rouge">nir_opt_varyings</code> is that it can pack two 16-bit inputs and
outputs together into a single 32-bit slot in order to save I/O space.
However, unfortunately RADV didn’t really work at all with packed 16-bit I/O.
Practically, this meant that every test case using 16-bit I/O failed.</p>

<p>I considered to disable 16-bit packing in <code class="language-plaintext highlighter-rouge">nir_opt_varyings</code> but eventually
I decided to just implement it in RADV properly instead.</p>

<ul>
  <li><a href="https://gitlab.freedesktop.org/mesa/mesa/-/merge_requests/28704">Packed 16-bit mesh shader outputs</a></li>
  <li><a href="https://gitlab.freedesktop.org/mesa/mesa/-/merge_requests/28764">Packed 16-bit FS inputs</a></li>
  <li><a href="https://gitlab.freedesktop.org/mesa/mesa/-/merge_requests/28765">Packed 16-bit pre-rasterization outputs</a></li>
  <li><a href="https://gitlab.freedesktop.org/mesa/mesa/-/merge_requests/28768">Packed 16-bit tessellation and GS I/O</a></li>
</ul>

<h3 id="repetitiveness-in-amd-common-code">Repetitiveness in AMD common code</h3>

<p>While writing patches to handle packed 16-bit I/O, we’ve taken note of
how repetitive the code was; basically the same thing was implemented several
times with subtle differences. Of course, this had to be dealt with.</p>

<ul>
  <li><a href="https://gitlab.freedesktop.org/mesa/mesa/-/merge_requests/28936">Refactored pre-rasterization output info to avoid repetition</a></li>
</ul>

<h3 id="mesh-shading-per-primitive-io">Mesh shading per-primitive I/O</h3>

<p>Mesh shading pipelines have so-called per-primitive I/O, which need special handling.
For example, it is wrong to pack per-primitive and per-vertex inputs or outputs
into the same slot. Because OpenGL doesn’t have per-primitive I/O, this was
left unsolved and needed to be fixed in <code class="language-plaintext highlighter-rouge">nir_opt_varyings</code> before RADV could use it.</p>

<ul>
  <li><a href="https://gitlab.freedesktop.org/mesa/mesa/-/merge_requests/28489"><code class="language-plaintext highlighter-rouge">nir_recompute_io_bases</code> needed to learn about per-primitive I/O</a></li>
  <li><a href="https://gitlab.freedesktop.org/mesa/mesa/-/merge_requests/28685"><code class="language-plaintext highlighter-rouge">nir_opt_varyings</code> itself needed to learn per-primitive I/O too</a></li>
</ul>

<h3 id="updating-loadstore-alignments">Updating load/store alignments</h3>

<p>Using <code class="language-plaintext highlighter-rouge">nir_opt_varyings</code> had a slight regression in shader instruction counts
due to inter-stage code motion.
Essentially, it moved some instructions into the previous stage, which prevented
<code class="language-plaintext highlighter-rouge">nir_opt_load_store_vectorize</code> to deduce the alignment of some memory instructions,
resulting in worse vectorization.</p>

<p>The solution was to add a new pass based on the code already written for
<code class="language-plaintext highlighter-rouge">nir_opt_load_store_vectorize</code> that would just update the alignments of each
memory access called <code class="language-plaintext highlighter-rouge">nir_opt_load_store_update_alignments</code>, and run that pass before
<code class="language-plaintext highlighter-rouge">nir_opt_varyings</code>, thereby preserving the aligment info before it is lost.</p>

<ul>
  <li><a href="https://gitlab.freedesktop.org/mesa/mesa/-/merge_requests/29210">Added <code class="language-plaintext highlighter-rouge">nir_opt_load_store_update_alignments</code></a></li>
</ul>

<h3 id="promoting-fs-inputs-to-flat">Promoting FS inputs to <code class="language-plaintext highlighter-rouge">FLAT</code></h3>

<p><code class="language-plaintext highlighter-rouge">FLAT</code> fragment shader inputs are generally better because they require no interpolation
and allow packing 32-bit and 16-bit inputs together, so
<code class="language-plaintext highlighter-rouge">nir_opt_varyings</code> takes special care trying to promote interpolated inputs to
<code class="language-plaintext highlighter-rouge">FLAT</code> when possible.</p>

<p>However, there was a regression caused by this mechanism unintentionally
creating more inputs than there were before.</p>

<ul>
  <li><a href="https://gitlab.freedesktop.org/mesa/mesa/-/merge_requests/29208">Here is the fix so that it only promotes to <code class="language-plaintext highlighter-rouge">FLAT</code> when appropriate</a></li>
</ul>

<h3 id="dealing-with-mediump-io">Dealing with <code class="language-plaintext highlighter-rouge">mediump</code> I/O</h3>

<p>The <code class="language-plaintext highlighter-rouge">mediump</code> qualifier effectively means that the application allows the driver to
use either 16-bit or 32-bit precision for a variable, whichever it
deems more optimal for a specific shader.</p>

<p>It turned out that RADV didn’t deal with <code class="language-plaintext highlighter-rouge">mediump</code> I/O at all.
This was fine, because it just meant they got treated as normal 32-bit I/O,
but it became a problem when it turned out <code class="language-plaintext highlighter-rouge">nir_opt_varyings</code> is unaware of
<code class="language-plaintext highlighter-rouge">mediump</code> and mixed it up with other inputs, which confused the vectorizer.</p>

<ul>
  <li><a href="https://gitlab.freedesktop.org/mesa/mesa/-/merge_requests/29435">This MR deals with <code class="language-plaintext highlighter-rouge">mediump</code> by lowering it to normal 32-bit I/O</a></li>
</ul>

<p>Side note: I am not quite done yet with <code class="language-plaintext highlighter-rouge">mediump</code>.
In the future I plan to lower it to 16-bit precision,
but only when I can make sure it doesn’t result in more inputs.</p>

<h3 id="explicitly-interpolated-per-vertex-fs-inputs">Explicitly interpolated (per-vertex) FS inputs</h3>

<p>Vulkan has some functionality that allow applications to do custom FS input interpolation
in shader code, which from the driver perspective means that each FS invocation needs to
access the output of each vertex. (This requires special register programming from RADV
on the FS inputs.) This is something that also needed to be added to <code class="language-plaintext highlighter-rouge">nir_opt_varyings</code>
before RADV could use it.</p>

<ul>
  <li><a href="https://gitlab.freedesktop.org/mesa/mesa/-/merge_requests/28247">Marek wrote some patches to deal with explicit FS inputs</a></li>
</ul>

<h3 id="scalarization-and-re-vectorization-of-io-components">Scalarization and re-vectorization of I/O components</h3>

<p>The <code class="language-plaintext highlighter-rouge">nir_opt_varyings</code> pass only works on so-called scalarized I/O, meaning that it can
only deal with instructions that write a single output component or read a single
input component. Fortunately, there is already a handy <code class="language-plaintext highlighter-rouge">nir_lower_io_to_scalar</code>
pass which we can use.</p>

<p>The downside is that scalarized shader I/O becomes sub-optimal (on all stages on AMD HW except VS -&gt; PS)
because the I/O instructions are really memory accesses, which are simply
more optimal when more components are accessed by the same instruction.</p>

<p>This is solved in two ways:</p>

<ul>
  <li><a href="https://gitlab.freedesktop.org/mesa/mesa/-/merge_requests/29242">Rhys has enhanced the excellent <code class="language-plaintext highlighter-rouge">nir_opt_load_store_vectorize</code> pass</a> to better deal with
lowered shader I/O, meaning that it can now better vectorize the memory access instructions
that are generated by scalarized I/O.</li>
  <li><a href="https://gitlab.freedesktop.org/mesa/mesa/-/merge_requests/29406">Marek has developed a new <code class="language-plaintext highlighter-rouge">nir_opt_vectorize_io</code> pass</a> which can re-vectorize the
I/O intrinsics (before they are lowered to memory access).</li>
</ul>

<h3 id="shader-io-stats">Shader I/O stats</h3>

<p>One of the main questions with any kind of optimization is how to measure the
effects of that optimization in an objective way. This is a solved problem,
we have shader stats for this which contain instructions about various aspects
of a shader, such as number of instructions, register use etc. Except, there was
no stats about I/O, so this needed to be added.</p>

<p>These stats are useful to prove that all of this work actually improved things.
Furthermore, they turned out useful for finding bugs in existing code as well.</p>

<ul>
  <li><a href="https://gitlab.freedesktop.org/mesa/mesa/-/merge_requests/29209">Added shader stats for inputs and outputs</a></li>
  <li><a href="https://gitlab.freedesktop.org/mesa/mesa/-/merge_requests/29327">Fix for a tessellation I/O bug discovered using I/O stats</a></li>
</ul>

<h3 id="removing-the-old-linking-passes">Removing the old linking passes</h3>

<p>Considering that <code class="language-plaintext highlighter-rouge">nir_opt_varyings</code> is supposed to be an all-in-one linking solution,
a naive person like me would assume that once the driver had been refactored to use
<code class="language-plaintext highlighter-rouge">nir_opt_varyings</code> we can simply stop using all of the old linking passes. But…
It turns out that getting rid of any of the other passes seem to cause regressions in shaders stats such as instruction count (which we don’t want).</p>

<p>Why is this?</p>

<p>Due to the order in which we call various NIR optimizations, it seems that we can’t effectively
take advantake of new optimization opportunities after <code class="language-plaintext highlighter-rouge">nir_opt_varyings</code>. This means that
we either have to re-run all expensive optimizations once more after the new linking step,
or we will have to reorder our optimizations in order to be able to remove the old linking
passes.</p>

<h2 id="conclusion-future-work">Conclusion; future work</h2>

<p>While we haven’t yet found the exit from all the rabbit holes we fell into, we made
really good progress and I feel that all of our I/O code ended up better after this effort.
Some work on RADV shader I/O (as of June 2024) remains:</p>

<ul>
  <li>Completely remove the old linking passes</li>
  <li>Stop using driver locations (in the few places where they are still used)</li>
  <li>Lower <code class="language-plaintext highlighter-rouge">mediump</code> to 16-bit when beneficial</li>
</ul>

<h3 id="thanks">Thanks</h3>

<p>I owe a big thank you to Marek for developing <code class="language-plaintext highlighter-rouge">nir_opt_varyings</code> in the first place
and helping me adopt it every step of the way.
Also thanks to Samuel, Rhys and Georg for the good conversations we had and for reviewing my patches.</p>]]></content><author><name>Timur Kristóf</name></author><category term="graphics" /><category term="freedesktop" /><category term="work" /><summary type="html"><![CDATA[In the previous post I gave an introduction to shader linking. Mike has already blogged about this topic a while ago, focusing mostly on Zink, and now it’s time for me to share some of my adventures about it too, but of course focusing on how we improved it in RADV and the various rabbit holes that this work has lead me to.]]></summary></entry><entry><title type="html">What is shader linking?</title><link href="https://timur.hu/blog/2024/shader-linking-intro" rel="alternate" type="text/html" title="What is shader linking?" /><published>2024-06-09T12:07:00+02:00</published><updated>2024-06-09T12:07:00+02:00</updated><id>https://timur.hu/blog/2024/shader-linking-intro</id><content type="html" xml:base="https://timur.hu/blog/2024/shader-linking-intro"><![CDATA[<p>Shader linking is one of the more complicated topics in graphics driver development.
It is both a never ending effort in the pursuit of performance and a black hole in which driver developers disappear.
In this post, I intend to give an introduction to what shader linking is
and why it’s worth spending our time working on it in general.</p>

<h2 id="lets-start-with-the-basics">Let’s start with the basics.</h2>

<p>Shaders are smallish programs that run on your GPU and are necessary
for any graphical application in order to draw things on your screen using your GPU.
A typical game can have thousands, or even hundreds of thousands of shaders.
Because every GPU has its own instruction set with major differences, it is generally the
reponsibility of the graphics driver to compile shaders in a way that is most optimal
on your GPU in order to make games run fast.</p>

<p>One of the ways of making them faster is linking.
Many times, the driver knows exactly which shaders are going to be used together and
that gives it the opportunity to perform optimizations based on the assumption that
two shaders are only ever used together (and never with other shaders).</p>

<p>In Vulkan, there are now three ways for
an application to create graphics shaders
and all of these have a possibility for utilizing linking:</p>

<ol>
  <li><strong>Graphics pipelines</strong>, which contain a set of shaders and a bunch of graphics state baked together.
We can always link shaders of a graphics pipeline, because it is impossible to change the shaders
in a pipeline after it was created.</li>
  <li><strong>Graphics pipeline libraries</strong>, which essentially split a pipeline into some parts.
The API allows to create full pipelines by linking pipeline libraries together.</li>
  <li><strong>Shader objects</strong>, which is a newer extension that deals with shaders individually,
however still allows the application to ask the driver link them together.</li>
</ol>

<p>In Mesa, we mainly represent shaders in NIR (the NIR intermediate representation) and
that is where link-time optimizations happen.</p>

<h2 id="why-is-shader-linking-beneficial-to-performance">Why is shader linking beneficial to performance?</h2>

<p>Shader linking allows the compiler stack to make assumptions about a shader by looking at another
shader that it is used together with.
Let’s take a look at what optimizations are possible.</p>

<h3 id="deletion-of-io-operations">Deletion of I/O operations</h3>

<p>The compiler may look at the outputs of a shader and the inputs of the next stage,
and delete unnecessary I/O.
For example, when you have a pipeline with VS (vertex shader) and FS (fragment shader):</p>

<ul>
  <li>The compiler can safely remove outputs from the VS that are not read by the FS.
As a result, any shader code which was used to calculate the value
of those outputs will now become dead code and may be removed as well.</li>
  <li>The compiler can replace FS inputs that aren’t written by the VS
with an “undefined” value (or zero) which algebraic optimizations can take advantage of.</li>
  <li>The compiler may detect that some VS outputs are duplicates and may remove the superfluous outputs
from the VS, and also merge their corresponding inputs in the FS.</li>
  <li>When a VS output is a constant value, the compiler can delete the VS output and replace
the corresponding FS input load instructions with the constant value. This enables
further algebraic optimizations in the FS.</li>
</ul>

<p>As a result, both the VS and FS will have fewer IO instructions and more optimal algebraic instructions.
The same ideas are basically applicable to any two shader stages.</p>

<p>This first group of optimizations are the easiest to implement and has been supported
by NIR for a long time: <code class="language-plaintext highlighter-rouge">nir_remove_dead_variables</code>, <code class="language-plaintext highlighter-rouge">nir_remove_unused_varyings</code> and <code class="language-plaintext highlighter-rouge">nir_link_opt_varyings</code>
have existed for a long time.</p>

<h3 id="compaction-of-io-space">Compaction of I/O space</h3>

<p>Shader linking also lets the compiler to “compact” the
output space, by reordering I/O variables in both shaders
so that they use the least amount of space possible.</p>

<p>For example, it may be possible that they have “gaps” between the I/O slots that they use,
and the compiler can then be smart and rearrange the I/O variables so that there are as
few gaps as possible.</p>

<p>As a result, less I/O space will be used. The exact benefit of this optimization depends highly
on the hardware architecture and which stages are involved. But generally speaking, using less
space can mean less memory use (which can translate into better occupancy or higher throughput),
or simply that the next stage is launched faster, or will use fewer registers, or
less fixed-function HW resources needed, etc.</p>

<p>NIR has also supported I/O compaction in <code class="language-plaintext highlighter-rouge">nir_compact_varyings</code>, however its implementation
was far from perfect, the main challenges were handling indirect indexing and
it lacked packing 16-bit varyings into 32-bits.</p>

<h3 id="code-motion-between-shader-stages">Code motion between shader stages</h3>

<p>Also known as inter-stage code motion, this is a complex optimization that has two main goals:</p>

<ul>
  <li>Create more optimization opportunities for doing more of the aforementioned optimizations.
For example, when you have two outputs such that the value of one output can be trivially
calculated from the other, it may be beneficial to just calculate that value in the next stage,
which then enables us to remove the extra output.</li>
  <li>Move code to earlier stages, with the assumption that earlier stages have fewer invocations
than later ones, which means the same instructions will need to be executed fewer times,
making the pipeline overall faster. Most of the time, we can safely assume that there
are fewer VS invocations than FS, so it’s overall a good thing to move instructions
from FS to VS. The same is unquestionably beneficial for geometry amplification, such as
moving code from TES to TCS.</li>
</ul>

<p>This concept is all-new in Mesa and hasn’t existed until Marek wrote <code class="language-plaintext highlighter-rouge">nir_opt_varyings</code> recently.</p>

<h2 id="why-is-all-of-that-necessary">Why is all of that necessary?</h2>

<p>At this point you might ask yourself the question, why is all of this necessary?
In other words, why do shaders actually need these optimizations?
Why don’t app developers write shaders that are already optimal?</p>

<p>The answer might surprise you.</p>

<p>Many times, the same shader is reused between different pipelines,
in which case the application developer needs to write them in a way in which they
are interchangeable. This is simply a good practice from the perspective of
the application developer, reducing the number of shaders they need to maintain.</p>

<p>Sometimes, applications effectively generate different shaders from the same
source using ifdefs, specialization constants etc.</p>

<p>Even though the same source shader was written to usable with multiple other shaders;
in each pipeline the driver can deal with it as if it were a different shader
and in each pipeline the shader will be linked to the other shaders in that specific pipeline.</p>

<h2 id="whats-new-in-mesa-shader-linking">What’s new in Mesa shader linking?</h2>

<p>The big news is that Marek Olšák wrote a new pass called
<code class="language-plaintext highlighter-rouge">nir_opt_varyings</code> which is an all-in-one solution to all the optimizations above, and
now authors of various drivers are rushing to take advantage of this new code.
I’ll share my experience of using that in RADV in the next blog post.</p>]]></content><author><name>Timur Kristóf</name></author><category term="graphics" /><category term="freedesktop" /><category term="work" /><summary type="html"><![CDATA[Shader linking is one of the more complicated topics in graphics driver development. It is both a never ending effort in the pursuit of performance and a black hole in which driver developers disappear. In this post, I intend to give an introduction to what shader linking is and why it’s worth spending our time working on it in general.]]></summary></entry><entry><title type="html">AMD RDNA3 mesh shading with RADV</title><link href="https://timur.hu/blog/2024/rdna3-mesh-shading" rel="alternate" type="text/html" title="AMD RDNA3 mesh shading with RADV" /><published>2024-06-09T09:30:00+02:00</published><updated>2024-06-09T09:30:00+02:00</updated><id>https://timur.hu/blog/2024/rdna3-mesh-shading</id><content type="html" xml:base="https://timur.hu/blog/2024/rdna3-mesh-shading"><![CDATA[<p>This is a long-awaited update to the previous mesh shading related posts.
RDNA3 brings many interesting improvements to the hardware which simplify how
mesh shaders work.</p>

<h2 id="reminder-main-limitation-of-mesh-shading-on-rdna2">Reminder: main limitation of mesh shading on RDNA2</h2>

<p>RDNA2 already supported mesh and task shaders, but mesh shaders had a big caveat
regarding how outputs work: each shader invocation could only really write
up to 1 vertex and 1 primitive, which meant that the shader compiler had
to work around that to implement the programming model of the mesh shading API.</p>

<p>On RDNA2 the shader compiler had to:</p>

<ul>
  <li>Make sure to launch (potentially) more invocations than the API shader needed,
to accomodate a larger number of output vertices / primitives.</li>
  <li>Save all outputs to memory (shared memory or VRAM) and reload them at the end,
unless they were only indexed by the local invocation index.</li>
</ul>

<h2 id="shader-output-changes-on-rdna3">Shader output changes on RDNA3</h2>

<p>RDNA3 changes how shader outputs work on pre-rasterization stages (including VS, TES, GS, MS).</p>

<h3 id="attribute-ring">Attribute ring</h3>

<p>Previous architectures had a special buffer called <em>parameter cache</em> where
the pre-rasterization stage stored positions and
generic output attributes for fragment shaders (pixel shaders) to read.</p>

<p>The <em>parameter cache</em> was removed from RDNA3 in favour of the <em>attribute ring</em>
which is basically a buffer in VRAM. Shaders must now store their outputs to this
buffer and after rasterization, the HW reads the attributes from the <em>attribute ring</em>
and stores them to the LDS space of fragment shaders.</p>

<p>When I first heard about the <em>attribute ring</em> I didn’t understand how this is an improvement
over the previous design (VRAM bandwidth is considered a bottleneck in many cases),
but then I realized that this is meant to work together
with the Infinity Cache that these new chips have. In the ideal access pattern,
each attribute store would overwrite a full cache line so the shader won’t actually touch VRAM.</p>

<p>For mesh shaders, this has two consequences:</p>

<ul>
  <li>Any invocation can now truly write generic attributes of any other invocation
without restrictions, because these are just a memory write.</li>
  <li>The shader compiler now has to worry about memory access patterns.</li>
</ul>

<p>RADV already supports the attribute ring for VS, TES and GS so we have some experience with
how it works and only needed to apply that to mesh shaders.</p>

<h3 id="row-exports">Row exports</h3>

<p>For non-generic output attributes (such as position, clip/cull distances, etc.) we
still need to use <code class="language-plaintext highlighter-rouge">exp</code> instructions just like the old hardware. However, these now
have a new mode called <em>row export</em> which allows each lane to write not only its own
outputs but also others in the same row.</p>

<h2 id="basic-rdna3-mesh-shading-legacy-fast-launch-mode">Basic RDNA3 mesh shading: legacy fast launch mode</h2>

<p>The legacy fast launch mode is essentially the same thing as RDNA2 had, so in this mode
mesh shaders can be compiled with the same structure and the compiler only needs to be
adjusted to use the <em>attribute ring</em>.</p>

<p>The drawback of this mode is that it still has the same issue with workgroup size
as RDNA2 had. So this is just useful for helping driver developers port their code
to the new architecture but it doesn’t allow us to fully utilize the new capabilities
of the hardware.</p>

<p><a href="https://gitlab.freedesktop.org/mesa/mesa/-/merge_requests/21409">The initial MS implementation in RADV</a> used this mode.</p>

<h2 id="new-fast-launch-mode">New fast launch mode</h2>

<p>In this mode, the number of HW shader invocations is determined similarly to how
a compute shader would work, and there is no need to match the number of vertices
and primitives in this mode.</p>

<p><a href="https://gitlab.freedesktop.org/mesa/mesa/-/merge_requests/25040">Thanks to Rhys for working on this and enabling the new mode on RDNA3.</a></p>

<p>Based on the information we can glean from the open source progress
(in particular, the published register files) happening thus far,
we think RDNA4 will only support this new mode.</p>

<h2 id="what-took-you-so-long">What took you so long?</h2>

<p>I’ve wanted to write about this for some time, but somehow forgot that I have a blog… Sorry!</p>

<h2 id="references">References</h2>

<p>As always, what I discuss here is based on open source driver code including
mesa (RadeonSI and RADV) and AMD’s reference driver code.</p>

<ul>
  <li>RadeonSI and RADV already had code and comments that explain the <em>attribute ring</em>.</li>
  <li><a href="https://developer.amd.com/wp-content/resources/RDNA3_Shader_ISA_December2022.pdf">RDNA3 shader ISA</a> and <a href="https://github.com/GPUOpen-Drivers/llpc/blob/dev/lgc/patch/MeshTaskShader.cpp">LLPC mesh/task code</a>
do a good job at explaining row exports and hint at the new fast launch mode.</li>
  <li><a href="https://github.com/GPUOpen-Drivers/pal/blob/dev/src/core/hw/gfxip/gfx9/gfx9CmdUtil.cpp">PAL’s reference implementation</a> explains how the draw packets work.</li>
</ul>]]></content><author><name>Timur Kristóf</name></author><category term="graphics" /><category term="mesh" /><category term="freedesktop" /><category term="work" /><summary type="html"><![CDATA[This is a long-awaited update to the previous mesh shading related posts. RDNA3 brings many interesting improvements to the hardware which simplify how mesh shaders work.]]></summary></entry><entry><title type="html">Mesh shaders arrive on your Linux computers</title><link href="https://timur.hu/blog/2022/mesh-shaders-arrive-on-linux" rel="alternate" type="text/html" title="Mesh shaders arrive on your Linux computers" /><published>2022-09-03T07:17:44+02:00</published><updated>2022-09-03T07:17:44+02:00</updated><id>https://timur.hu/blog/2022/mesh-shaders-arrive-on-linux</id><content type="html" xml:base="https://timur.hu/blog/2022/mesh-shaders-arrive-on-linux"><![CDATA[<p>September 1 was a big day!
The <a href="https://github.com/KhronosGroup/Vulkan-Docs/commit/135da3a538263ef0d194cab25e2bb091119bdc42">official cross-vendor Vulkan mesh shading extension</a> that I teased a while ago, has
<a href="https://www.khronos.org/blog/mesh-shading-for-vulkan">now been officially released</a>.
This is a significant moment for me because I’ve spent considerable time making
<a href="https://gitlab.freedesktop.org/mesa/mesa/-/merge_requests/18367">the RADV implementation</a> and
collaborated with some excellent people to help shape this extension in Khronos.</p>

<h2 id="how-it-started">How it started</h2>

<p>We first started talking about mesh shaders in Mesa about two years (maybe more?) ago.
At the time the only publicly available Vulkan mesh shading API was the vendor-specific
<code class="language-plaintext highlighter-rouge">NV_mesh_shader</code> made by NVidia.</p>

<ul>
  <li>At the time nobody quite fully understood what mesh shaders are supposed to be
and how they could work on the HW. I initially anticipated that they could be
made to work even on RDNA1, but this turned out false due to some HW limitations.</li>
  <li>It was unclear what was needed to get good performance.</li>
  <li>The NVidia extension was a good start, but it was full of things that don’t make
any real sense on any other HW.</li>
  <li>Nobody had a clue how we would implement task shaders.</li>
</ul>

<p>I was working together with <a href="https://twitter.com/pixeljetstream">Christoph Kubisch</a> (from NVidia) who helped understand what
this topic is all about.
<a href="https://gitlab.freedesktop.org/cmarcelo">Caio Oliveira</a> and <a href="https://gitlab.freedesktop.org/mslusarz">Marcin Slusarz</a> (from Intel, working on ANV)
joined the adventure too.</p>

<h2 id="how-we-made-it-work">How we made it work</h2>

<p>We made the decision to start working on some preliminary support for
the NV extension to get some experience with the topic and learn how it’s supposed to work.
Once we were satisfied with that, we made the jump to the EXT.</p>

<h3 id="nir-and-spir-v">NIR and SPIR-V</h3>

<p>These are <a href="https://www.jlekstrand.net/jason/blog/2022/01/in-defense-of-nir/">the common Mesa pieces that all drivers can use</a>.
The front-end and middleware code for mesh/task shader support are here.
Caio created the initial pieces and I expanded on that as I found more and more
things that needed adjustment in NIR, added a new storage class for task payloads etc.
Marcin also chimed in with fixes and improvements.</p>

<p>AMD and Intel hardware work differently, so most of the hard
work couldn’t be shared and needed to be implemented in the backends.
However, some of the commonalities are implemented in eg. <a href="https://gitlab.freedesktop.org/mesa/mesa/-/merge_requests/16720"><code class="language-plaintext highlighter-rouge">nir_lower_task_shader</code></a>
for the work that needs to happen in both RADV and ANV.
There were dozens of merge requests that added support for various features,
cleaned up old features to make them not crash on mesh shaders, etc.
The latest is <a href="https://gitlab.freedesktop.org/mesa/mesa/-/merge_requests/18366">this MR</a>
which adds all the remaining puzzle pieces for the EXT.</p>

<h3 id="lowering-the-shaders-in-the-backend">Lowering the shaders in the backend</h3>

<p>Because mesh shaders use NGG, the heavy lifting is done in <code class="language-plaintext highlighter-rouge">ac_nir_lower_ngg</code>
which is already responsible for other NGG shaders (VS, TES, GS).
The lowering basically “translates” the API shader to work like the HW expects.
Without going into much detail, it essentially wraps the application shader and replaces
some pieces of it to make them understandable by the HW.</p>

<p>There is now also an <a href="https://gitlab.freedesktop.org/mesa/mesa/-/merge_requests/14929"><code class="language-plaintext highlighter-rouge">ac_nir_lower_taskmesh_io_to_mem</code></a>
for translating task payload I/O and <code class="language-plaintext highlighter-rouge">EmitMeshTasksEXT</code> to something the HW can understand.</p>

<h3 id="mesh-shading-draw-calls-in-radv">Mesh shading draw calls in RADV</h3>

<p>Previously I was mostly working on the compiler stack (NIR and ACO) and had
little experience with the hardcore driver code,
such as how draws/dispatches work and how the driver submits cmd buffers
to the GPU. As I had near-zero knowledge of these areas, I had to learn about them,
mostly by just reading the code.</p>

<p>So, I split the RADV work in two parts:</p>

<ol>
  <li><a href="https://gitlab.freedesktop.org/mesa/mesa/-/merge_requests/13580">Mesh shader only pipelines.</a>
These required only moderate changes to
<code class="language-plaintext highlighter-rouge">radv_cmd_buffer</code> to add some new draw calls, and minor work in <code class="language-plaintext highlighter-rouge">radv_pipeline</code>
to figure out per-primitive output attributes and get the register programming right.</li>
  <li><a href="https://gitlab.freedesktop.org/mesa/mesa/-/merge_requests/16531">Task shader support.</a>
Due to how task shaders work on AMD HW, these required
very severe refactoring in <code class="language-plaintext highlighter-rouge">radv_device</code> because we now have to submit to multiple
queues at once. This is actually not finished yet because “gang submit” is still missing.
Additionally, <code class="language-plaintext highlighter-rouge">radv_cmd_buffer</code> needed heavy changes to support an internal compute cmdbuf.</li>
</ol>

<p>Naturally, during this work I also hit several RADV bugs in pre-existing use cases which
just nobody noticed yet. Some of these were issues with secondary command buffers and
conditional rendering on compute-only queues. There was also a nasty firmware bug, and other
exciting stuff.</p>

<p>Let’s just say that my GPU loved to <strong>hang</strong> out with me.</p>

<h3 id="mesh-shading-on-intel">Mesh shading on Intel</h3>

<p>The Intel ANV compiler backend and driver implementation were done by
Caio and Marcin and I just want to take this opportunity to say that
I really enjoyed working together with them.</p>

<h3 id="the-guy-who-wrote-the-most-mesh-shaders-on-earth">The guy who wrote the most mesh shaders on Earth</h3>

<p>All of the above would have been impossible if I didn’t have some solid test cases
which I could throw at my implementation. Ricardo Garcia developed the
CTS (Vulkan Conformance Test Suite) testcases for both NV_mesh_shader and EXT_mesh_shader.
During that work, Ricardo wrote <strong>several thousand</strong> mesh and task shaders for us to test with.
Ricardo if you’re reading this, <strong>THANK YOU</strong>!!!</p>

<h2 id="conclusion">Conclusion</h2>

<p>Implementing <code class="language-plaintext highlighter-rouge">VK_EXT_mesh_shader</code> gave me a very good learning experience and helped me
get an understanding of parts of the driver that I had never looked at before.</p>

<h3 id="what-happens-to-nv_mesh_shader-now">What happens to NV_mesh_shader now?</h3>

<p>We never wanted to officially support it, it was just a stepping stone for us to help
start working on the EXT. The NV extension support will be removed soon.</p>

<h3 id="when-is-it-coming-to-my-steam-deck--linux-computer">When is it coming to my Steam Deck / Linux computer?</h3>

<p>The RADV and ANV support will be included once the system is updated to Mesa 22.3,
though we may be convinced to bring it to the Deck sooner
if somebody finds a game that uses mesh shaders.</p>

<p>For NVidia proprietary driver users, EXT_mesh_shader is already included in the latest beta drivers.</p>

<h3 id="waiting-for-the-gang">Waiting for the gang…</h3>

<p>We marked mesh/task shader support “experimental” in RADV because it has one main caveat
that we are unable to solve without kernel support.
Thanks to how we need to submit to two different queues at the same time, this can deadlock
your GPU if you are running two (or more) processes which use task shaders at the same time.
To properly solve it we need the <strong>“gang submit”</strong> feature in the kernel which prevents such deadlocks.</p>

<p>Unfortunately “gang submit” is not upstream yet. Cross your fingers and let’s hope it’ll be included in Linux 6.1.</p>

<p>Until then, you can use the <code class="language-plaintext highlighter-rouge">RADV_PERFTEST=ext_ms</code> environment variable
to play your favourite mesh shader games!</p>]]></content><author><name>Timur Kristóf</name></author><category term="graphics" /><category term="mesh" /><category term="freedesktop" /><category term="work" /><summary type="html"><![CDATA[September 1 was a big day! The official cross-vendor Vulkan mesh shading extension that I teased a while ago, has now been officially released. This is a significant moment for me because I’ve spent considerable time making the RADV implementation and collaborated with some excellent people to help shape this extension in Khronos.]]></summary></entry><entry><title type="html">What is NGG and shader culling on AMD RDNA GPUs?</title><link href="https://timur.hu/blog/2022/what-is-ngg" rel="alternate" type="text/html" title="What is NGG and shader culling on AMD RDNA GPUs?" /><published>2022-06-27T07:17:44+02:00</published><updated>2022-06-27T07:17:44+02:00</updated><id>https://timur.hu/blog/2022/what-is-ngg</id><content type="html" xml:base="https://timur.hu/blog/2022/what-is-ngg"><![CDATA[<p>NGG (Next Generation Geometry) is the technology that is responsible for
any vertex and geometry processing in AMD RDNA GPUs.
I decided to do a write-up about my experience implementing it
in RADV, which is the Vulkan driver used by many Linux systems, including the Steam Deck.
I will also talk about shader culling on RDNA GPUs.</p>

<h2 id="old-stuff-the-legacy-geometry-pipeline-on-gcn">Old stuff: the legacy geometry pipeline on GCN</h2>

<p>Let’s start by briefly going over how the old GCN geometry pipeline works,
so that we can compare old and new.</p>

<p>GCN GPUs have 5 programmable hardware shader stages for vertex/geometry processing: LS, HS, ES, GS, VS.
These HW stages don’t exactly map to the software stages that are advertised in the API.
Instead, it is the responsibility of the driver to select which HW stages need to be
used for a given pipeline. <a href="https://gitlab.freedesktop.org/mesa/mesa/-/blob/main/src/amd/compiler/README.md#which-software-stage-runs-on-which-hardware-stage">We have a table</a> if you want details.</p>

<p>The rasterizer can only consume the output from HW VS, so the last SW stage in your pipeline
must be compiled to HW VS. This is trivial for VS and TES (yes, tess eval shaders are “VS” to
the hardware), but GS is complicated.
GS outputs are written to memory. The driver has no choice but to compile a separate shader that runs as HW VS,
and copies this memory to the rasterizer.
We call this the “GS copy shader” in Mesa. (It is not part of the API pipeline but required to make GS work.)</p>

<p>Notes:</p>

<ul>
  <li>All of these HW stages (except GS, of course) use a model in which
1 shader invocation (SIMD lane, or simply thread in D3D jargon) corresponds to 1 output vertex.
These stages (except GS) are also not aware of output primitives.</li>
  <li>Vega introduced “merged shaders” (LS+HS, and ES+GS) but did not fundamentally change the above model.</li>
</ul>

<h2 id="new-stuff-ngg-pipeline-on-rdna">New stuff: NGG pipeline on RDNA</h2>

<p>The next-generation geometry pipeline vastly simplifies how the hardware works.
(At the expense of some increased driver complexity.)</p>

<p>There are now only 2 HW shader stages for vertex/geometry processing:</p>

<ul>
  <li><em>Surface shader</em> which is a pre-tessellation stage and is equivalent to what LS + HS was in the old HW.</li>
  <li><em>Primitive shader</em> which can feed the rasterizer and replaces all of the old ES + GS + VS stages.</li>
</ul>

<p>The surface shader is not too interesting, it runs the merged SW VS + TCS when tessellation is enabled.
I’m not aware of any changes to how this works compared to old HW.</p>

<p>The interesting part, and subject of much discussion on the internet is the primitive shader.
In some hardware documentation and register header files the new stage is referred to as simply “GS”,
because AMD essentially took what the GS stage could already do and added the ability for it to
directly feed the rasterizer using <code class="language-plaintext highlighter-rouge">exp</code> (export) instructions.
Don’t confuse this with SW GS.
It supports a superset of the functionality that you can do in software VS, TES, GS and MS.
In very loose terms you can think about it as a “mesh-like” stage which all these software stages can be compiled to.</p>

<p>Compared to the old HW VS, a primitive shader has these new features:</p>

<ul>
  <li>Compute-like: they are running in workgroups, and have full support for features
such as workgroup ID, subgroup count, local invocation index, etc.</li>
  <li>Aware of both input primitives and vertices:
there are registers which contain information about the input
primitive topology and the overall number of vertices/primitives (similar to GS).</li>
  <li>They have to export not only vertex output attributes (positions and parameters),
but also the <em>primitive topology</em>, ie. which primitive (eg. triangle) contains which vertices
and in what order.
Instead of processing vertices in a fixed topology, it is up to the shader to create
as many vertices and primitives as the application wants.</li>
  <li>Each shader invocation can create up to 1 vertex and up to 1 primitive.</li>
  <li>Before outputting any vertex or primitive, a workgroup has to tell how many it will output,
using <code class="language-plaintext highlighter-rouge">s_sendmsg(gs_alloc_req)</code> which ensures that the necessary amount of space
in the parameter cache is allocated for them.</li>
  <li>On RDNA2, per-primitive output params are also supported.</li>
</ul>

<h3 id="how-is-shader-compilation-different">How is shader compilation different?</h3>

<p>Software VS and TES:<br />
Compared to the legacy pipeline, the compiled shaders must now not only export vertex output attributes
for a fixed number of vertices, but instead they
create vertices/primitives (after declaring how many they will create).
This is trivial to implement because all they have to do is read the registers that contain the input primitive
topology and then export the exact same topology.</p>

<p>Software GS:<br />
As noted above, each NGG shader invocation can only create up to 1 vertex + up to 1 primitive.
This mismatches the programming model of SW GS and makes it difficult to implement.
In a nutshell, for SW GS the hardware launches a large enough workgroup to fit every possible
output vertex. This results in poor HW utilization (most of those threads just sit there doing nothing
while the GS threads do the work), but there is not much we can do about that.</p>

<p>Mesh shaders:<br />
The new pipeline enables us to support mesh shaders, which was simply impossible on the legacy pipeline,
due to how the programming model entirely mismatches anything the old hardware could do.</p>

<h3 id="how-does-any-of-this-make-my-games-go-faster">How does any of this make my games go faster?</h3>

<p>We did some benchmarks when we switched RADV and ACO to use the new pipeline.
We found no significant perf changes. At all.
Considering all the hype we heard about NGG at the hardware launch, I was quite surprised.</p>

<p>However, after I set the hype aside, it was quite self-explanatory.
When we switched to NGG, we still compiled our shaders mostly the same way as before, so even though
we used the new geometry pipeline, we didn’t do anything to take advantage of its new capabilities.</p>

<p>The actual perf improvement came after I also implemented shader-based culling.</p>

<h3 id="what-is-ngg-shader-culling">What is NGG shader culling?</h3>

<p>The NGG pipeline makes it possible for shaders to know about input primitives and
create an arbitrary topology of output primitives.
Even though the API does not make this information available to application shaders, it is possible
for driver developers to make their compiler aware of it and add some crazy code that
can get rid of primitives when it knows that those will never be actually
visible. The technique is known as “shader culling”, or “NGG culling”.</p>

<p>This can improve performance in games that have a lot of triangles, because
we only calculate the output positions of every vertex before we decide
which triangle to remove. We then also remove unused vertices.</p>

<p>The benefits are:</p>

<ul>
  <li>Reduced bottleneck from the fixed-function HW that traditionally does culling.</li>
  <li>Improved bandwidth use, because we can avoid loading some inputs for vertices we delete.</li>
  <li>Improved shader HW utilization because we can avoid computing additional vertex attributes for deleted vertices.</li>
  <li>More efficient PC (parameter cache) use as we don’t need to reserve output space for deleted vertices and primitives.</li>
</ul>

<p>If there is interest, I may write a blog post about the implementation details later.</p>

<h4 id="caveats-of-shader-culling">Caveats of shader culling</h4>

<p>Due to how all of this reduces certain bottlenecks, its effectiveness very highly depends on
whether you actually had a bottleneck in the first place.
How many primitives it can remove of course depends on the application. Therefore
the exact percentage of performance gain (or loss) also depends on the application.</p>

<p>If an application didn’t have any of the aforementioned bottlenecks or already mitigates them in its
own way, then all of this new code may just add unnecessary overhead and actually slightly
reduce performance rather than improve it.</p>

<p>Other than that, there is some concern that a shader-based implementation may be less accurate
than the fixed-function HW.</p>

<ul>
  <li>It may leave some triangles which should have been removed.
This is not really an issue as these will be removed by fixed-func HW anyway.</li>
  <li>The bigger problem is that it may delete triangles which should have been kept.
This can manifest itself by missing objects from a scene or flickering, etc.</li>
</ul>

<h4 id="our-results-with-shader-culling-on-rdna2">Our results with shader culling on RDNA2</h4>

<p>Shader culling seems to be most efficient in benchmarks and apps that output a lot of
triangles without having any in-app solution for dealing with the bottlenecks.
It is also very effective on games that suffer from overtessellation (ie.
create a lot of very small triangles which are not visible).</p>

<ul>
  <li>An extreme example is the instancing demo by Sascha Willems which gets a massive boost</li>
  <li>Basemark sees 10%+ performance improvement</li>
  <li>Doom Eternal gets a 3%-5% boost (depending on the GPU and scene)</li>
  <li>The Witcher 3 also benefits (likely thanks to its overuse of tessellation)</li>
  <li>In less demanding games, the difference is negligible, around 1%</li>
</ul>

<p>While shader culling can also work on RDNA1, we don’t enable it by default
because we haven’t yet found a game that noticably benefits from it.
On RDNA1, it seems that the old and new pipelines have similar performance.</p>

<h4 id="notes-about-hardware-support">Notes about hardware support</h4>

<ul>
  <li>Vega had something similar, but I haven’t heard of any drivers that ever used this.
Based on public info I cound find, it’s not even worth looking into.</li>
  <li>Navi 10 and 12 lack some features such as per-primitive outputs which makes it
impossible to implement mesh shaders on these GPUs.
We don’t use NGG on Navi 14 (RX 5500 series) because it doesn’t work.</li>
  <li>Navi 21 and newer have the best support.
They have all necessary features for mesh shaders.
We enabled shader culling by default on these GPUs because they show a measurable benefit.</li>
  <li>Van Gogh (the GPU in the Steam Deck) has the same feature set as Navi 2x.
It also shows benefits from shader culling, but to a smaller extent.</li>
</ul>

<h2 id="closing-thoughts">Closing thoughts</h2>

<p>The main takeaway from this post is that NGG is not a performance silver bullet that
magically makes all your games faster. Instead, it is an enabler of new features.
It lets the driver implement new techniques such as shader culling and new programming models like mesh shaders.</p>]]></content><author><name>Timur Kristóf</name></author><category term="graphics" /><category term="mesh" /><category term="freedesktop" /><category term="work" /><summary type="html"><![CDATA[NGG (Next Generation Geometry) is the technology that is responsible for any vertex and geometry processing in AMD RDNA GPUs. I decided to do a write-up about my experience implementing it in RADV, which is the Vulkan driver used by many Linux systems, including the Steam Deck. I will also talk about shader culling on RDNA GPUs.]]></summary></entry></feed>