<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="3.10.0">Jekyll</generator><link href="/feed.xml" rel="self" type="application/atom+xml" /><link href="/" rel="alternate" type="text/html" /><updated>2026-08-18T19:42:08+00:00</updated><id>/feed.xml</id><title type="html">Sunaabh’s Knowledge Trove</title><subtitle>I&apos;m Sunaabh, an Engineer working at arm, and this is my blog.</subtitle><entry><title type="html">Jane Street ASIC Puzzle</title><link href="/systems/2026/08/18/jspuzzle.html" rel="alternate" type="text/html" title="Jane Street ASIC Puzzle" /><published>2026-08-18T00:00:00+00:00</published><updated>2026-08-18T00:00:00+00:00</updated><id>/systems/2026/08/18/jspuzzle</id><content type="html" xml:base="/systems/2026/08/18/jspuzzle.html"><![CDATA[<p>Jane Street recently announced a <a href="https://github.com/janestreet/asic-puzzle-2026/tree/master">hardware puzzle</a>. I came across it on hackernews, and was intrigued enough to take a look and spend a significant amount of time on it after work this week.</p>

<p>I work in hardware, so you can imagine how interesting I must have found this to continue staring at VS code after 8 hours of it in the office.</p>

<p>The puzzle involves reverse engineering an ASIC, starting from a GDS and figuring out:</p>

<ol>
  <li>What the design does</li>
  <li>What the success condition is</li>
</ol>

<p>The latter is the main part of the puzzle: finding what sequence of inputs causes a <code class="language-plaintext highlighter-rouge">success</code> output signal to go high. Immediately, it is clear that there is only one input bit, 8 output bits, a clock, reset and the success signal. We are almost certainly dealing with a serial input, which means we’ve definitely got some state machines in there along with all the combinational logic.</p>

<p>Now I was really intrigued. Time to dig in to this.</p>

<h1 id="gds-and-klayout">GDS and KLayout</h1>

<p>Now is the time to admit that I had only superficially seen a GDS file before, and certainly never stared too close at one. In their challenge GitHub, Jane Street suggests viewing the schematic, so this is what I did. After spending some time being confused about what all the layers mean, I found this <a href="https://skywater-pdk.readthedocs.io/en/main/rules/layers.html">incredibly useful resource</a> which lists the SKY130 standard layer used for each encoding, e.g., layer 69/20 is <code class="language-plaintext highlighter-rouge">met2</code> (metal layer 2).</p>

<p>I also discovered that KLayout has a Python API, which was great news. Step 1 then, was extracting a netlist from the GDS.</p>

<p>The API made this somewhat easy. Each routing layer (local interconnect, metal 1, metal 2, etc.) can be identified by its unique code, and these explicitly describe the connections between cells. We query the API to extract these connections: first the intra-layer connections (e.g., everything that’s connected via the local interconnect or on one metal layer). Then, we use the contacts/vias, which have their own identifier, to join connected components going up the stack.</p>

<p>What we get at the end of this is a graph of standard cells, and their connectivity — a netlist! The KLayout API has a nice internal representation of the netlist here, which gives us a good string representation of the entire circuit.</p>

<p>Cool! I have to admit, I found this part really interesting, having never looked at a GDS before — I hadn’t realised how much information you can extract from just the layers.</p>

<p>Also, pretty cool to see the Jane Street logo in the corner on metal layer 2 xD</p>

<p>!image.png</p>

<h1 id="emitting-rtl">Emitting RTL</h1>

<p>We now want to turn this netlist into RTL. Before we can do that, we need to actually pull some logic out of these standard cells. Each of them can be reduced to a simple set of gates: AND, OR, NOT, XOR (and their inverses), and a set of flops with associated clock.</p>

<p>We first convert to an internal logic IR representation:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">Expr</span><span class="p">:</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">output</span><span class="p">,</span> <span class="n">op</span><span class="p">,</span> <span class="n">inputs</span><span class="p">):</span>
        <span class="bp">self</span><span class="p">.</span><span class="n">output</span> <span class="o">=</span> <span class="n">output</span>
        <span class="bp">self</span><span class="p">.</span><span class="n">op</span> <span class="o">=</span> <span class="n">op</span>
        <span class="bp">self</span><span class="p">.</span><span class="n">inputs</span> <span class="o">=</span> <span class="n">inputs</span>

    <span class="k">def</span> <span class="nf">__repr__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span> <span class="sa">f</span><span class="s">"</span><span class="si">{</span><span class="bp">self</span><span class="p">.</span><span class="n">output</span><span class="si">}</span><span class="s"> = </span><span class="si">{</span><span class="bp">self</span><span class="p">.</span><span class="n">op</span><span class="si">}</span><span class="s">(</span><span class="si">{</span><span class="s">', '</span><span class="p">.</span><span class="n">join</span><span class="p">(</span><span class="nb">map</span><span class="p">(</span><span class="nb">str</span><span class="p">,</span> <span class="bp">self</span><span class="p">.</span><span class="n">inputs</span><span class="p">))</span><span class="si">}</span><span class="s">)"</span>
</code></pre></div></div>

<p>I did this originally with the idea of hand-rolling a compiler that would turn this IR into a set of z3 SMT solver predicates. However, I decided to just go with Yosys in the end, so this IR step ended up being somewhat unnecessary. It is fairly simple though, we just go through each net and turn it into an <code class="language-plaintext highlighter-rouge">Expr</code>, looking up a table that looks like this: (courtesy of Codex)</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code>   <span class="s">"sky130_fd_sc_hd__and2"</span><span class="p">:</span> <span class="k">lambda</span> <span class="n">p</span><span class="p">:</span> <span class="p">(</span><span class="s">"X"</span><span class="p">,</span> <span class="n">AND</span><span class="p">(</span><span class="n">p</span><span class="p">[</span><span class="s">"A"</span><span class="p">],</span> <span class="n">p</span><span class="p">[</span><span class="s">"B"</span><span class="p">])),</span>
    <span class="s">"sky130_fd_sc_hd__and3"</span><span class="p">:</span> <span class="k">lambda</span> <span class="n">p</span><span class="p">:</span> <span class="p">(</span><span class="s">"X"</span><span class="p">,</span> <span class="n">AND</span><span class="p">(</span><span class="n">p</span><span class="p">[</span><span class="s">"A"</span><span class="p">],</span> <span class="n">p</span><span class="p">[</span><span class="s">"B"</span><span class="p">],</span> <span class="n">p</span><span class="p">[</span><span class="s">"C"</span><span class="p">])),</span>
    <span class="s">"sky130_fd_sc_hd__and4"</span><span class="p">:</span> <span class="k">lambda</span> <span class="n">p</span><span class="p">:</span> <span class="p">(</span><span class="s">"X"</span><span class="p">,</span> <span class="n">AND</span><span class="p">(</span><span class="n">p</span><span class="p">[</span><span class="s">"A"</span><span class="p">],</span> <span class="n">p</span><span class="p">[</span><span class="s">"B"</span><span class="p">],</span> <span class="n">p</span><span class="p">[</span><span class="s">"C"</span><span class="p">],</span> <span class="n">p</span><span class="p">[</span><span class="s">"D"</span><span class="p">])),</span>
    <span class="s">"sky130_fd_sc_hd__and2b"</span><span class="p">:</span>  <span class="k">lambda</span> <span class="n">p</span><span class="p">:</span> <span class="p">(</span><span class="s">"X"</span><span class="p">,</span> <span class="n">AND</span><span class="p">(</span><span class="n">NOT</span><span class="p">(</span><span class="n">p</span><span class="p">[</span><span class="s">"A_N"</span><span class="p">]),</span> <span class="n">p</span><span class="p">[</span><span class="s">"B"</span><span class="p">])),</span>
    <span class="s">"sky130_fd_sc_hd__and3b"</span><span class="p">:</span>  <span class="k">lambda</span> <span class="n">p</span><span class="p">:</span> <span class="p">(</span><span class="s">"X"</span><span class="p">,</span> <span class="n">AND</span><span class="p">(</span><span class="n">NOT</span><span class="p">(</span><span class="n">p</span><span class="p">[</span><span class="s">"A_N"</span><span class="p">]),</span> <span class="n">p</span><span class="p">[</span><span class="s">"B"</span><span class="p">],</span> <span class="n">p</span><span class="p">[</span><span class="s">"C"</span><span class="p">])),</span>
    <span class="s">"sky130_fd_sc_hd__and4b"</span><span class="p">:</span>  <span class="k">lambda</span> <span class="n">p</span><span class="p">:</span> <span class="p">(</span><span class="s">"X"</span><span class="p">,</span> <span class="n">AND</span><span class="p">(</span><span class="n">NOT</span><span class="p">(</span><span class="n">p</span><span class="p">[</span><span class="s">"A_N"</span><span class="p">]),</span> <span class="n">p</span><span class="p">[</span><span class="s">"B"</span><span class="p">],</span> <span class="n">p</span><span class="p">[</span><span class="s">"C"</span><span class="p">],</span> <span class="n">p</span><span class="p">[</span><span class="s">"D"</span><span class="p">])),</span>
    <span class="s">"sky130_fd_sc_hd__and4bb"</span><span class="p">:</span> <span class="k">lambda</span> <span class="n">p</span><span class="p">:</span> <span class="p">(</span><span class="s">"X"</span><span class="p">,</span> <span class="n">AND</span><span class="p">(</span><span class="n">NOT</span><span class="p">(</span><span class="n">p</span><span class="p">[</span><span class="s">"A_N"</span><span class="p">]),</span> <span class="n">NOT</span><span class="p">(</span><span class="n">p</span><span class="p">[</span><span class="s">"B_N"</span><span class="p">]),</span> <span class="n">p</span><span class="p">[</span><span class="s">"C"</span><span class="p">],</span> <span class="n">p</span><span class="p">[</span><span class="s">"D"</span><span class="p">])),</span>
</code></pre></div></div>

<p>We can then emit actually verilog from this representation! Admittedly, I didn’t feel like doing this part, so I just let Codex do it for me. It does a lot of scaffolding work to set up the ports list, and declare all the wires (if combinational) and regs (if the net is used as the output of a flop), turns <code class="language-plaintext highlighter-rouge">DFF</code> expressions into actual verilog flops, and emits the correct syntax for all combinational logic.</p>

<p>It’s not awfully interesting, this part, but by the end of it, I can throw Yosys at <code class="language-plaintext highlighter-rouge">puzzle.v</code> and:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>sunaabh@JARVIS:~/jspuzzle<span class="nv">$ </span>yosys <span class="nt">-p</span> <span class="s2">"read_verilog puzzle.v; hierarchy -top puzzle; proc; flatten; opt -full; dffunmap; async2sync; stat"</span> yosys <span class="nt">-p</span> <span class="s2">"read_verilog puzzle.v; hierarchy -top puzzle; proc; flatten; opt -full; dffunmap; async2sync; stat"</span>

 /----------------------------------------------------------------------------<span class="se">\</span>
 |                                                                            |
 |  yosys <span class="nt">--</span> Yosys Open SYnthesis Suite                                       |
 |                                                                            |
 |  Copyright <span class="o">(</span>C<span class="o">)</span> 2012 - 2020  Claire Xenia Wolf &lt;claire@yosyshq.com&gt;         |
 |                                                                            |
 |  Permission to use, copy, modify, and/or distribute this software <span class="k">for </span>any  |
 |  purpose with or without fee is hereby granted, provided that the above    |
 |  copyright notice and this permission notice appear <span class="k">in </span>all copies.         |
 |                                                                            |
 |  THE SOFTWARE IS PROVIDED <span class="s2">"AS IS"</span> AND THE AUTHOR DISCLAIMS ALL WARRANTIES  |
 |  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF          |
 |  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR   |
 |  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES    |
 |  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN     |
 |  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF   |
 |  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.            |
 |                                                                            |
 <span class="se">\-</span><span class="nt">---------------------------------------------------------------------------</span>/

 Yosys 0.33 <span class="o">(</span>git sha1 2584903a060<span class="o">)</span>

<span class="nt">--</span> Running <span class="nb">command</span> <span class="sb">`</span>read_verilog puzzle.v<span class="p">;</span> hierarchy <span class="nt">-top</span> puzzle<span class="p">;</span> proc<span class="p">;</span> flatten<span class="p">;</span> opt <span class="nt">-full</span><span class="p">;</span> dffunmap<span class="p">;</span> async2sync<span class="p">;</span> <span class="nb">stat</span><span class="s1">' --

1. Executing Verilog-2005 frontend: puzzle.v

...

8. Printing statistics.

=== puzzle ===

   Number of wires:               1487
   Number of wire bits:           1494
   Number of public wires:         705
   Number of public wire bits:     712
   Number of memories:               0
   Number of memory bits:            0
   Number of processes:              0
   Number of cells:               1441
     $and                          502
     $dff                            4
     $mux                          109
     $not                          281
     $or                           411
     $sdff                          88
     $xor                           46

End of script. Logfile hash: a313f1cb75, CPU: user 0.15s system 0.02s, MEM: 18.38 MB peak
Yosys 0.33 (git sha1 2584903a060)
Time spent: 32% 4x opt_expr (0 sec), 19% 2x read_verilog (0 sec), ...

</span></code></pre></div></div>

<p>It compiles!</p>

<h1 id="solution">Solution</h1>

<p>In order to find the success condition, I first started digging around the emitted verilog to see what I could figure out. This was not exactly a fruitful endeavour, as the code is unsurprisingly obfuscated. One thing I did discover though is what looks like a modulo-11 4-bit counter:</p>

<div class="language-verilog highlighter-rouge"><div class="highlight"><pre class="highlight"><code>  <span class="k">always</span> <span class="o">@</span><span class="p">(</span><span class="kt">posedge</span> <span class="n">n_2213</span> <span class="kt">or</span> <span class="kt">negedge</span> <span class="n">rst_n</span><span class="p">)</span> <span class="k">begin</span>
    <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">rst_n</span><span class="p">)</span> <span class="k">begin</span>
      <span class="n">n_832</span> <span class="o">&lt;=</span> <span class="mb">1'b0</span><span class="p">;</span>
      <span class="n">n_20</span> <span class="o">&lt;=</span> <span class="mb">1'b0</span><span class="p">;</span>
      <span class="n">n_319</span> <span class="o">&lt;=</span> <span class="mb">1'b0</span><span class="p">;</span>
      <span class="n">n_380</span> <span class="o">&lt;=</span> <span class="mb">1'b0</span><span class="p">;</span>
      <span class="n">n_2254</span> <span class="o">&lt;=</span> <span class="mb">1'b0</span><span class="p">;</span>
      <span class="n">n_2419</span> <span class="o">&lt;=</span> <span class="mb">1'b0</span><span class="p">;</span>
    <span class="k">end</span> <span class="k">else</span> <span class="k">begin</span>
      <span class="n">n_832</span> <span class="o">&lt;=</span> <span class="n">n_2501</span><span class="p">;</span>
      <span class="n">n_20</span> <span class="o">&lt;=</span> <span class="n">n_2303</span><span class="p">;</span>
      <span class="n">n_319</span> <span class="o">&lt;=</span> <span class="n">n_2440</span><span class="p">;</span>
      <span class="n">n_380</span> <span class="o">&lt;=</span> <span class="n">n_2235</span><span class="p">;</span>
      <span class="c1">// These aren't relevant</span>
      <span class="n">n_2254</span> <span class="o">&lt;=</span> <span class="n">n_2396</span><span class="p">;</span>
      <span class="n">n_2419</span> <span class="o">&lt;=</span> <span class="n">n_2477</span><span class="p">;</span>
    <span class="k">end</span>
  <span class="k">end</span>
</code></pre></div></div>

<p>I know its a counter because the D inputs to this flop look like this:</p>

<div class="language-verilog highlighter-rouge"><div class="highlight"><pre class="highlight"><code>  <span class="k">assign</span> <span class="n">n_2303</span> <span class="o">=</span> <span class="o">~</span><span class="p">((</span><span class="n">n_934</span> <span class="o">&amp;</span> <span class="n">n_1526</span><span class="p">)</span> <span class="o">|</span> <span class="n">n_2374</span> <span class="o">|</span> <span class="n">n_2164</span><span class="p">)</span>
  <span class="k">assign</span> <span class="n">n_1526</span> <span class="o">=</span> <span class="p">(</span><span class="o">~</span><span class="n">n_319</span> <span class="o">&amp;</span> <span class="o">~</span><span class="n">n_380</span> <span class="o">&amp;</span> <span class="n">n_832</span> <span class="o">&amp;</span> <span class="n">n_20</span><span class="p">);</span>
  <span class="k">assign</span> <span class="n">n_2164</span> <span class="o">=</span> <span class="p">(</span><span class="n">n_20</span> <span class="o">&amp;</span> <span class="n">n_319</span> <span class="o">&amp;</span> <span class="n">n_934</span><span class="p">);</span>
  <span class="k">assign</span> <span class="n">n_2374</span> <span class="o">=</span> <span class="o">~</span><span class="p">((</span><span class="n">n_319</span> <span class="o">&amp;</span> <span class="n">n_934</span><span class="p">)</span> <span class="o">|</span> <span class="n">n_20</span><span class="p">);</span>
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">n_2164</code> is checking whether bits <code class="language-plaintext highlighter-rouge">n_20, n_319, n_934</code> are all set. I’ve noticed <code class="language-plaintext highlighter-rouge">n_934</code> is like a global enable signal that gates everything. Then, we can gather that <code class="language-plaintext highlighter-rouge">n_2303</code> checks if <code class="language-plaintext highlighter-rouge">n_20</code> and <code class="language-plaintext highlighter-rouge">n_319</code> are both high, and goes high if they are. Combined with <code class="language-plaintext highlighter-rouge">n_2374</code> , this gives us <code class="language-plaintext highlighter-rouge">n_20 ^ n_319,</code> a toggle on bit 1 of the counter.</p>

<p><code class="language-plaintext highlighter-rouge">n_1526</code>is clearly checking whether bits <code class="language-plaintext highlighter-rouge">n_832</code>and<code class="language-plaintext highlighter-rouge">n_20</code> are set, while <code class="language-plaintext highlighter-rouge">n_319</code> and <code class="language-plaintext highlighter-rouge">n_380</code> aren’t. This is the modulo-11 check: we are checking if bits 1 and 3 of the counter are set, and clear the counter if they are.</p>

<p>So we have something that counts to 10! This is what I found in roughly 1 hour of staring at numbers and letters…so this is certainly not a sustainable approach.</p>

<p>I then pivoted to something I had in mind since the start — a SAT solver approach. Yosys has built in support for this. However, we’re still missing something at this point. I know <em>what</em> the success condition is (<code class="language-plaintext highlighter-rouge">success = 1'b1</code> ) of course, but I don’t know <em>when</em> it should happen. It’s clear from the logic that we have some state machines in the design, and so the success condition is likely a function of time as well as the inputs:</p>

\[S = f(I, T)\]

<p>Luckily, we can infer quite a bit from the provided example simulation. From this sim, we can see that after enable goes high, we feed in our input bitstream for exactly 121 cycles of <code class="language-plaintext highlighter-rouge">clk</code>, before enable is de-asserted again and the output reads: <code class="language-plaintext highlighter-rouge">0x54 0x52 0x59 0x20 0x41 0x47 0x41 0x49 0x4e</code> — <strong>TRY AGAIN.</strong></p>

<p>Oh?</p>

<p>The sim then repeats this for a different input bitstream (again over 121 cycles), with the same output. We are dealing with a <strong>serial lock</strong>.</p>

<p>The great thing about this is it tells us exactly when <code class="language-plaintext highlighter-rouge">success</code> needs to go high: 121 cycles after enabled. So this is exactly what I told yosys:</p>

<p>(Glossing over some additional constraints required to make sure the SAT solver doesn’t turn <code class="language-plaintext highlighter-rouge">rst_n</code> and enable on and off as it pleases)</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c"># assuming enable goes high on cycle 4, set success to go high 121 cycles later</span>
sat <span class="nt">-seq</span> 140 <span class="nt">-set-at</span> 125 success 1 <span class="nt">-show</span> O <span class="nt">-show</span> success
</code></pre></div></div>

<p>We get the following solution:</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code>   <span class="mi">124</span> <span class="err">\</span><span class="n">O</span>                                                  <span class="mi">0</span>         <span class="mi">0</span>      <span class="mo">00000000</span>
   <span class="mi">124</span> <span class="err">\</span><span class="n">success</span>                                            <span class="mi">0</span>         <span class="mi">0</span>             <span class="mi">0</span>
  <span class="o">----</span> <span class="o">-----------------------------------------</span> <span class="o">-----------</span> <span class="o">---------</span> <span class="o">-------------</span>
   <span class="mi">125</span> <span class="err">\</span><span class="n">O</span>                                                 <span class="mi">40</span>        <span class="mi">28</span>      <span class="mo">00101000</span>
   <span class="mi">125</span> <span class="err">\</span><span class="n">success</span>                                            <span class="mi">1</span>         <span class="mi">1</span>             <span class="mi">1</span>
  <span class="o">----</span> <span class="o">-----------------------------------------</span> <span class="o">-----------</span> <span class="o">---------</span> <span class="o">-------------</span>
   <span class="mi">126</span> <span class="err">\</span><span class="n">O</span>                                                 <span class="mi">42</span>        <span class="mi">2</span><span class="n">a</span>      <span class="mo">00101010</span>
   <span class="mi">126</span> <span class="err">\</span><span class="n">success</span>                                            <span class="mi">1</span>         <span class="mi">1</span>             <span class="mi">1</span>
  <span class="o">----</span> <span class="o">-----------------------------------------</span> <span class="o">-----------</span> <span class="o">---------</span> <span class="o">-------------</span>
   <span class="mi">127</span> <span class="err">\</span><span class="n">O</span>                                                 <span class="mi">32</span>        <span class="mi">20</span>      <span class="mo">00100000</span>
   <span class="mi">127</span> <span class="err">\</span><span class="n">success</span>                                            <span class="mi">1</span>         <span class="mi">1</span>             <span class="mi">1</span>
  <span class="o">----</span> <span class="o">-----------------------------------------</span> <span class="o">-----------</span> <span class="o">---------</span> <span class="o">-------------</span>
   <span class="mi">128</span> <span class="err">\</span><span class="n">O</span>                                                 <span class="mi">84</span>        <span class="mi">54</span>      <span class="mo">01010100</span>
   <span class="mi">128</span> <span class="err">\</span><span class="n">success</span>                                            <span class="mi">1</span>         <span class="mi">1</span>             <span class="mi">1</span>
  <span class="o">----</span> <span class="o">-----------------------------------------</span> <span class="o">-----------</span> <span class="o">---------</span> <span class="o">-------------</span>
   <span class="mi">129</span> <span class="err">\</span><span class="n">O</span>                                                 <span class="mi">87</span>        <span class="mi">57</span>      <span class="mo">01010111</span>
   <span class="mi">129</span> <span class="err">\</span><span class="n">success</span>                                            <span class="mi">1</span>         <span class="mi">1</span>             <span class="mi">1</span>
  <span class="o">----</span> <span class="o">-----------------------------------------</span> <span class="o">-----------</span> <span class="o">---------</span> <span class="o">-------------</span>
   <span class="mi">130</span> <span class="err">\</span><span class="n">O</span>                                                 <span class="mi">79</span>        <span class="mi">4</span><span class="n">f</span>      <span class="mo">01001111</span>
   <span class="mi">130</span> <span class="err">\</span><span class="n">success</span>                                            <span class="mi">1</span>         <span class="mi">1</span>             <span class="mi">1</span>
  <span class="o">----</span> <span class="o">-----------------------------------------</span> <span class="o">-----------</span> <span class="o">---------</span> <span class="o">-------------</span>
   <span class="mi">131</span> <span class="err">\</span><span class="n">O</span>                                                 <span class="mi">32</span>        <span class="mi">20</span>      <span class="mo">00100000</span>
   <span class="mi">131</span> <span class="err">\</span><span class="n">success</span>                                            <span class="mi">1</span>         <span class="mi">1</span>             <span class="mi">1</span>
  <span class="o">----</span> <span class="o">-----------------------------------------</span> <span class="o">-----------</span> <span class="o">---------</span> <span class="o">-------------</span>
   <span class="mi">132</span> <span class="err">\</span><span class="n">O</span>                                                 <span class="mi">83</span>        <span class="mi">53</span>      <span class="mo">01010011</span>
   <span class="mi">132</span> <span class="err">\</span><span class="n">success</span>                                            <span class="mi">1</span>         <span class="mi">1</span>             <span class="mi">1</span>
  <span class="o">----</span> <span class="o">-----------------------------------------</span> <span class="o">-----------</span> <span class="o">---------</span> <span class="o">-------------</span>
   <span class="mi">133</span> <span class="err">\</span><span class="n">O</span>                                                 <span class="mi">84</span>        <span class="mi">54</span>      <span class="mo">01010100</span>
   <span class="mi">133</span> <span class="err">\</span><span class="n">success</span>                                            <span class="mi">1</span>         <span class="mi">1</span>             <span class="mi">1</span>
  <span class="o">----</span> <span class="o">-----------------------------------------</span> <span class="o">-----------</span> <span class="o">---------</span> <span class="o">-------------</span>
   <span class="mi">134</span> <span class="err">\</span><span class="n">O</span>                                                 <span class="mi">65</span>        <span class="mi">41</span>      <span class="mo">01000001</span>
   <span class="mi">134</span> <span class="err">\</span><span class="n">success</span>                                            <span class="mi">1</span>         <span class="mi">1</span>             <span class="mi">1</span>
  <span class="o">----</span> <span class="o">-----------------------------------------</span> <span class="o">-----------</span> <span class="o">---------</span> <span class="o">-------------</span>
   <span class="mi">135</span> <span class="err">\</span><span class="n">O</span>                                                 <span class="mi">82</span>        <span class="mi">52</span>      <span class="mo">01010010</span>
   <span class="mi">135</span> <span class="err">\</span><span class="n">success</span>                                            <span class="mi">1</span>         <span class="mi">1</span>             <span class="mi">1</span>
  <span class="o">----</span> <span class="o">-----------------------------------------</span> <span class="o">-----------</span> <span class="o">---------</span> <span class="o">-------------</span>
   <span class="mi">136</span> <span class="err">\</span><span class="n">O</span>                                                 <span class="mi">83</span>        <span class="mi">53</span>      <span class="mo">01010011</span>
   <span class="mi">136</span> <span class="err">\</span><span class="n">success</span>                                            <span class="mi">1</span>         <span class="mi">1</span>             <span class="mi">1</span>
  <span class="o">----</span> <span class="o">-----------------------------------------</span> <span class="o">-----------</span> <span class="o">---------</span> <span class="o">-------------</span>
   <span class="mi">137</span> <span class="err">\</span><span class="n">O</span>                                                 <span class="mi">32</span>        <span class="mi">20</span>      <span class="mo">00100000</span>
   <span class="mi">137</span> <span class="err">\</span><span class="n">success</span>                                            <span class="mi">1</span>         <span class="mi">1</span>             <span class="mi">1</span>
  <span class="o">----</span> <span class="o">-----------------------------------------</span> <span class="o">-----------</span> <span class="o">---------</span> <span class="o">-------------</span>
   <span class="mi">138</span> <span class="err">\</span><span class="n">O</span>                                                 <span class="mi">42</span>        <span class="mi">2</span><span class="n">a</span>      <span class="mo">00101010</span>
   <span class="mi">138</span> <span class="err">\</span><span class="n">success</span>                                            <span class="mi">1</span>         <span class="mi">1</span>             <span class="mi">1</span>
  <span class="o">----</span> <span class="o">-----------------------------------------</span> <span class="o">-----------</span> <span class="o">---------</span> <span class="o">-------------</span>
   <span class="mi">139</span> <span class="err">\</span><span class="n">O</span>                                                 <span class="mi">41</span>        <span class="mi">29</span>      <span class="mo">00101001</span>
   <span class="mi">139</span> <span class="err">\</span><span class="n">success</span>                                            <span class="mi">1</span>         <span class="mi">1</span>             <span class="mi">1</span>
  <span class="o">----</span> <span class="o">-----------------------------------------</span> <span class="o">-----------</span> <span class="o">---------</span> <span class="o">-------------</span>
   <span class="mi">140</span> <span class="err">\</span><span class="n">O</span>                                                  <span class="mi">0</span>         <span class="mi">0</span>      <span class="mo">00000000</span>
   <span class="mi">140</span> <span class="err">\</span><span class="n">success</span>                                            <span class="mi">0</span>         <span class="mi">0</span>             <span class="mi">0</span>
</code></pre></div></div>

<p>This gives:</p>

<p><code class="language-plaintext highlighter-rouge">0x28</code> → ‘(’</p>

<p><code class="language-plaintext highlighter-rouge">0x2a</code> → ‘*’</p>

<p><code class="language-plaintext highlighter-rouge">0x20</code> → ‘ ‘</p>

<p><code class="language-plaintext highlighter-rouge">0x54</code> → ‘T’</p>

<p>…</p>

<p><code class="language-plaintext highlighter-rouge">0x53</code> → ‘S’</p>

<p><code class="language-plaintext highlighter-rouge">0x20</code> → ‘ ‘</p>

<p><code class="language-plaintext highlighter-rouge">0x2a</code> → ‘*’</p>

<p><code class="language-plaintext highlighter-rouge">0x29</code> → ‘)’</p>

<p><strong>Solution: (* TWO STARS *)</strong></p>

<p>This, as I discovered, is how comments are written in Ocaml:</p>

<div class="language-ocaml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c">(* This is a comment *)</span>
<span class="o">//</span> <span class="nc">This</span> <span class="n">is</span> <span class="n">not</span> <span class="n">a</span> <span class="n">comment</span>
</code></pre></div></div>

<p>with two stars!</p>

<h1 id="the-input-sequence">The Input Sequence</h1>

<p>I was curious what the input sequence that produced this looks like. We can do this with <code class="language-plaintext highlighter-rouge">-show I</code> on the same yosys command.</p>

<p>(Admittedly, I had some help from Codex here in helping me connect the dots)</p>

<p>Taking the first 11 cycles of enable being high:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>  <span class="nt">----</span> <span class="nt">-----------------------------------------</span> <span class="nt">-----------</span> <span class="nt">---------</span> <span class="nt">-------------</span>
     3 <span class="se">\I</span>                                                  0         0             0
     3 <span class="se">\e</span>nable                                             1         1             1
  <span class="nt">----</span> <span class="nt">-----------------------------------------</span> <span class="nt">-----------</span> <span class="nt">---------</span> <span class="nt">-------------</span>
     4 <span class="se">\I</span>                                                  0         0             0
     4 <span class="se">\e</span>nable                                             1         1             1
  <span class="nt">----</span> <span class="nt">-----------------------------------------</span> <span class="nt">-----------</span> <span class="nt">---------</span> <span class="nt">-------------</span>
     5 <span class="se">\I</span>                                                  0         0             0
     5 <span class="se">\e</span>nable                                             1         1             1
  <span class="nt">----</span> <span class="nt">-----------------------------------------</span> <span class="nt">-----------</span> <span class="nt">---------</span> <span class="nt">-------------</span>
     6 <span class="se">\I</span>                                                  0         0             0
     6 <span class="se">\e</span>nable                                             1         1             1
  <span class="nt">----</span> <span class="nt">-----------------------------------------</span> <span class="nt">-----------</span> <span class="nt">---------</span> <span class="nt">-------------</span>
     7 <span class="se">\I</span>                                                  0         0             0
     7 <span class="se">\e</span>nable                                             1         1             1
  <span class="nt">----</span> <span class="nt">-----------------------------------------</span> <span class="nt">-----------</span> <span class="nt">---------</span> <span class="nt">-------------</span>
     8 <span class="se">\I</span>                                                  0         0             0
     8 <span class="se">\e</span>nable                                             1         1             1
  <span class="nt">----</span> <span class="nt">-----------------------------------------</span> <span class="nt">-----------</span> <span class="nt">---------</span> <span class="nt">-------------</span>
     9 <span class="se">\I</span>                                                  0         0             0
     9 <span class="se">\e</span>nable                                             1         1             1
  <span class="nt">----</span> <span class="nt">-----------------------------------------</span> <span class="nt">-----------</span> <span class="nt">---------</span> <span class="nt">-------------</span>
    10 <span class="se">\I</span>                                                  1         1             1
    10 <span class="se">\e</span>nable                                             1         1             1
  <span class="nt">----</span> <span class="nt">-----------------------------------------</span> <span class="nt">-----------</span> <span class="nt">---------</span> <span class="nt">-------------</span>
    11 <span class="se">\I</span>                                                  0         0             0
    11 <span class="se">\e</span>nable                                             1         1             1
  <span class="nt">----</span> <span class="nt">-----------------------------------------</span> <span class="nt">-----------</span> <span class="nt">---------</span> <span class="nt">-------------</span>
    12 <span class="se">\I</span>                                                  1         1             1
    12 <span class="se">\e</span>nable                                             1         1             1
      <span class="nt">----</span> <span class="nt">-----------------------------------------</span> <span class="nt">-----------</span> <span class="nt">---------</span> <span class="nt">-------------</span>
    13 <span class="se">\I</span>                                                  0         0             0
    13 <span class="se">\e</span>nable                                             1         1             1
</code></pre></div></div>

<p>So, taking the first enable as cycle 0, the input is high on <strong>cycle 7 and 9.</strong></p>

<p>The next set of 10:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nt">----</span> <span class="nt">-----------------------------------------</span> <span class="nt">-----------</span> <span class="nt">---------</span> <span class="nt">-------------</span>
    14 <span class="se">\I</span>                                                  1         1             1
    14 <span class="se">\e</span>nable                                             1         1             1
  <span class="nt">----</span> <span class="nt">-----------------------------------------</span> <span class="nt">-----------</span> <span class="nt">---------</span> <span class="nt">-------------</span>
    15 <span class="se">\I</span>                                                  0         0             0
    15 <span class="se">\e</span>nable                                             1         1             1
  <span class="nt">----</span> <span class="nt">-----------------------------------------</span> <span class="nt">-----------</span> <span class="nt">---------</span> <span class="nt">-------------</span>
    16 <span class="se">\I</span>                                                  0         0             0
    16 <span class="se">\e</span>nable                                             1         1             1
  <span class="nt">----</span> <span class="nt">-----------------------------------------</span> <span class="nt">-----------</span> <span class="nt">---------</span> <span class="nt">-------------</span>
    17 <span class="se">\I</span>                                                  0         0             0
    17 <span class="se">\e</span>nable                                             1         1             1
  <span class="nt">----</span> <span class="nt">-----------------------------------------</span> <span class="nt">-----------</span> <span class="nt">---------</span> <span class="nt">-------------</span>
    18 <span class="se">\I</span>                                                  0         0             0
    18 <span class="se">\e</span>nable                                             1         1             1
  <span class="nt">----</span> <span class="nt">-----------------------------------------</span> <span class="nt">-----------</span> <span class="nt">---------</span> <span class="nt">-------------</span>
    19 <span class="se">\I</span>                                                  1         1             1
    19 <span class="se">\e</span>nable                                             1         1             1
  <span class="nt">----</span> <span class="nt">-----------------------------------------</span> <span class="nt">-----------</span> <span class="nt">---------</span> <span class="nt">-------------</span>
    20 <span class="se">\I</span>                                                  0         0             0
    20 <span class="se">\e</span>nable                                             1         1             1
  <span class="nt">----</span> <span class="nt">-----------------------------------------</span> <span class="nt">-----------</span> <span class="nt">---------</span> <span class="nt">-------------</span>
    21 <span class="se">\I</span>                                                  0         0             0
    21 <span class="se">\e</span>nable                                             1         1             1
  <span class="nt">----</span> <span class="nt">-----------------------------------------</span> <span class="nt">-----------</span> <span class="nt">---------</span> <span class="nt">-------------</span>
    22 <span class="se">\I</span>                                                  0         0             0
    22 <span class="se">\e</span>nable                                             1         1             1
  <span class="nt">----</span> <span class="nt">-----------------------------------------</span> <span class="nt">-----------</span> <span class="nt">---------</span> <span class="nt">-------------</span>
    23 <span class="se">\I</span>                                                  0         0             0
    23 <span class="se">\e</span>nable                                             1         1             1
  <span class="nt">----</span> <span class="nt">-----------------------------------------</span> <span class="nt">-----------</span> <span class="nt">---------</span> <span class="nt">-------------</span>
    24 <span class="se">\I</span>                                                  0         0             0
    24 <span class="se">\e</span>nable                                             1         1             1
  <span class="nt">----</span> <span class="nt">-----------------------------------------</span> <span class="nt">-----------</span> <span class="nt">---------</span> <span class="nt">-------------</span>
</code></pre></div></div>

<p>I is high on <strong>cycles 0 and 5.</strong></p>

<p>This trend continues, with I only being high for 2 cycles out of each set of 11. This harkens back to the modulo-11 counter, it’s not a coincidence that we have 11 sets of 11 = 121 total cycles here — it is kind of begging us to put it on a grid:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">.</span> <span class="nb">.</span> <span class="nb">.</span> <span class="nb">.</span> <span class="nb">.</span> <span class="nb">.</span> <span class="nb">.</span> <span class="k">*</span> <span class="nb">.</span> <span class="k">*</span> <span class="nb">.</span>
<span class="k">*</span> <span class="nb">.</span> <span class="nb">.</span> <span class="nb">.</span> <span class="nb">.</span> <span class="k">*</span> <span class="nb">.</span> <span class="nb">.</span> <span class="nb">.</span> <span class="nb">.</span> <span class="nb">.</span>
<span class="nb">.</span> <span class="nb">.</span> <span class="nb">.</span> <span class="nb">.</span> <span class="nb">.</span> <span class="nb">.</span> <span class="nb">.</span> <span class="k">*</span> <span class="nb">.</span> <span class="k">*</span> <span class="nb">.</span>
<span class="k">*</span> <span class="nb">.</span> <span class="k">*</span> <span class="nb">.</span> <span class="nb">.</span> <span class="nb">.</span> <span class="nb">.</span> <span class="nb">.</span> <span class="nb">.</span> <span class="nb">.</span> <span class="nb">.</span>
<span class="nb">.</span> <span class="nb">.</span> <span class="nb">.</span> <span class="nb">.</span> <span class="k">*</span> <span class="nb">.</span> <span class="k">*</span> <span class="nb">.</span> <span class="nb">.</span> <span class="nb">.</span> <span class="nb">.</span>
<span class="nb">.</span> <span class="nb">.</span> <span class="k">*</span> <span class="nb">.</span> <span class="nb">.</span> <span class="nb">.</span> <span class="nb">.</span> <span class="nb">.</span> <span class="k">*</span> <span class="nb">.</span> <span class="nb">.</span>
<span class="nb">.</span> <span class="nb">.</span> <span class="nb">.</span> <span class="nb">.</span> <span class="k">*</span> <span class="nb">.</span> <span class="nb">.</span> <span class="nb">.</span> <span class="nb">.</span> <span class="nb">.</span> <span class="k">*</span>
<span class="nb">.</span> <span class="k">*</span> <span class="nb">.</span> <span class="nb">.</span> <span class="nb">.</span> <span class="nb">.</span> <span class="k">*</span> <span class="nb">.</span> <span class="nb">.</span> <span class="nb">.</span> <span class="nb">.</span>
<span class="nb">.</span> <span class="nb">.</span> <span class="nb">.</span> <span class="k">*</span> <span class="nb">.</span> <span class="nb">.</span> <span class="nb">.</span> <span class="nb">.</span> <span class="nb">.</span> <span class="nb">.</span> <span class="k">*</span>
<span class="nb">.</span> <span class="nb">.</span> <span class="nb">.</span> <span class="nb">.</span> <span class="nb">.</span> <span class="k">*</span> <span class="nb">.</span> <span class="nb">.</span> <span class="k">*</span> <span class="nb">.</span> <span class="nb">.</span>
<span class="nb">.</span> <span class="k">*</span> <span class="nb">.</span> <span class="k">*</span> <span class="nb">.</span> <span class="nb">.</span> <span class="nb">.</span> <span class="nb">.</span> <span class="nb">.</span> <span class="nb">.</span> <span class="nb">.</span>
</code></pre></div></div>

<p>It’s a <strong>star battle</strong>!</p>

<h1 id="some-ai-driven-exploration">Some AI-driven exploration</h1>

<p>At this point, I was happy enough to let Codex take a shot at parsing the obfuscated RTL to see what it could discover. There’s some pretty fun easter eggs in there. First, it seems like the <strong>TRY AGAIN</strong> message comes from a ROM. There are actually 3 more messages in ROMs: <strong>EMPTY SKY, BIG BANG, and TWO NOT TOUCH.</strong></p>

<p>This is <strong><em>awesome</em></strong>, these ROMs are basically debugging hints for anyone that tries to brute force the solution. It seems like the logic that picks the output mux select checks the number of “stars” in the input bitstream. If not enough, we get an “empty sky”. If there are too many, we have a “big bang”. If the number is correct (two per row), but they don’t follow the star battle rules, we get “two not touch”, which is a hint that we need to solve the two not touch game!</p>

<p>The actual solution is decidedly <strong>not</strong> in a ROM but instead ciphertext that needs to be deciphered with a keystream bit, which gets decoded correctly if <code class="language-plaintext highlighter-rouge">success</code> goes high and <code class="language-plaintext highlighter-rouge">enable</code> is de-asserted. Presumably, this path activates when the input bitstream satisfies the star battle rules.</p>

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

<p>This was really fun. I love the two-star theming, the solution was very satisfying, and it all just feels incredibly clever. It was also a great learning experience for me, familiarising myself with the (reverse of) the synthesis flow, and confronting the physics of the GDS. Thank you to whoever designed this puzzle!</p>

<p>I aimed NOT to use AI as far as possible to solve this challenge, and for the most part it wasn’t involved in the overall method I used, with the exception of some implementation. However, it’s surprisingly good at parsing obfuscated RTL and deducing the logic being implemented, which led to some super fun discoveries!</p>]]></content><author><name></name></author><category term="systems" /><summary type="html"><![CDATA[Jane Street recently announced a hardware puzzle. I came across it on hackernews, and was intrigued enough to take a look and spend a significant amount of time on it after work this week.]]></summary></entry><entry><title type="html">LDPC Decoders</title><link href="/systems/2026/07/29/ldpc.html" rel="alternate" type="text/html" title="LDPC Decoders" /><published>2026-07-29T00:00:00+00:00</published><updated>2026-07-29T00:00:00+00:00</updated><id>/systems/2026/07/29/ldpc</id><content type="html" xml:base="/systems/2026/07/29/ldpc.html"><![CDATA[<p><em>Iterative belief propagation over a sparse bipartite Tanner graph</em></p>

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

<p>I recently remembered my undergrad information theory course — it’s one of my favourite courses I studied whilst at university, and I think back quite fondly on it now. It was a difficult course, and although I scored fairly well on the exam, I still feel like I didn’t quite get as firm a grasp on the material as I maybe could have. The field of information theory is absolutely littered with proofs and derivations that can mask the real insight behind the theory, as Grant from 3Blue1Brown shows in <a href="https://www.youtube.com/watch?v=l6DKRf-fAAM">this fantastic video</a></p>

<p>This has motivated me to dive back into the field, and review my notes from a few years ago. I’d like to get some more insight, specifically, into low-density parity check (LDPC) codes and the algorithms used to decode such codes. To bring things alive, I’d also like to implement an LDPC decoder on some modern hardware. I’ve been meaning to mess around with the Qualcomm Hexagon DSP chip, so that’s what I’ll use.</p>

<h1 id="linear-block-codes">Linear Block Codes</h1>

<p>Lets start with what an LPDC code actually is, and what problem it tries to address.</p>

<p>An LDPC code is a type of <strong>error-correction channel code.</strong> These allow you to define codewords over a vocabulary to send over a noisy channel, over which errors are possible. A bitstream sent over such a channel is likely to accumulate errors, and so we need some way of adding redundancy to recover errors. The most famous ECC is the <strong>Hamming code,</strong> which is a type of <strong>linear block</strong> code. This means, they can be described by two matrices: the <strong>generator matrix</strong> $G$ and its associated <strong>parity check matrix</strong> $H$. For example, the Hamming (7, 4) code has:</p>

<p>!image.png</p>

<p>This code is defined over symbols of input length 4, and output codeword length 7, <em>i.e.,</em> it adds 3 bits of redundancy. To get a codeword $\mathbf{c} \in [0,1]^7$ from an input symbol $\mathbf{x} \in [0,1]^4$ we simply do</p>

\[\mathbf{c} = G^T\mathbf{x}\]

<p>The parity check matrix is more interesting. It satisfies the property,</p>

\[H\mathbf{c}^T = \mathbf{0}\]

<p>so that every valid codeword produces the all-zero vector when acted on by the parity-check matrix. We will come back to this, as it ends up being a useful property for LDPC codes.</p>

<p>Inspecting the generator matrix for the Hamming (7, 4) code in a bit more detail, we can see that 4 of the 7 rows are just picking out bits of the codeword (these are rows 2, 4, 5 and 6). Whereas rows 0, 1 and 3 give us extra <strong>parity</strong> bits:</p>

\[G^T\mathbf{x} = \begin{bmatrix}
x_0 + x_1 + x_3 \\
x_0 + x_2 + x_3 \\
x_0 \\
x_1 + x_2 + x_3 \\
x_1 \\
x_2 \\
x_3 
 \end{bmatrix}\]

<p>and this is the source of structured redundancy.</p>

<p>At this point, it is useful to know whether this is a good code. A good channel code can detect and correct more errors. However, taking this to its limit means we could just add more redundancy (<em>i.e.,</em>  a repetition code), and so there is another factor to trade-off — the rate $R$ of the code.</p>

<p>The number of errors a code can detect/correct is determined by something called its <strong>hamming distance</strong>, which is just the number of bits that are different between two codewords.</p>

<p>Specifically, we care about the <em>minimum</em> hamming distance $d_{min}$.</p>

\[d_{min} = \min_{\mathbf{c}_i\neq\mathbf{c}_j} d_H(\mathbf{c}_i, \mathbf{c}_j)\]

<p>The maximum number of errors a code can detect is exactly $d_{min} - 1$. This should be intuitive: once we have a codeword with $d_{min}$ errors in it, it is entirely possible for it to have turned into another codeword. Note that it is not <em>necessarily</em> the case, <em>i.e.,</em> it may well turn into something that is not a valid codeword in our vocabulary, but we cannot make strong guarantees about this.</p>

<p>Correction is harder. In order to correct a codeword, the number of errors must be small enough that it cannot be confused for any other codeword. This may seem like the same thing as detection, but consider a code with $d_{min} = 3$. Here, if there are 2 errors, we will know about it, since the received bits cannot be a valid codeword (say 1001). However, this could have been produced by two separate original codewords, <em>e.g.,</em>  (0101 → 1001 or 1010 → 1001). These are equally likely, and thus it becomes impossible to identify a unique decoding. In general, the maximum number of errors we can correct is roughly half the number we can detect:</p>

\[t = \left\lfloor\frac{d_{min}-1}{2}\right\rfloor\]

<p>Geometrically, this can be thought of as the maximum radius of spheres around valid codewords, such that these spheres never overlap.</p>

<p>It turns out that all Hamming codes have a $d_{min} =3$, and the rate $R = k/n$ depends on the specific type of Hamming code used. For a (7, 4) code, this is $R = 4/7 \approx 0.57$, which is kind of terrible. Larger Hamming codes achieve higher rates, but their error-correcting capability never improves. We are therefore motivated to ask whether we can construct linear block codes with both large minimum distance and high rate, allowing reliable communication with relatively little redundancy and operation close to the Shannon limit.</p>

<h1 id="ldpc-codes">LDPC Codes</h1>

<p>In designing LDPC codes, the first step is to take note of a paradigm shift. Previously, we were interested in designing a code such that there is no possibility of error, <em>i.e.,</em> codes with as high $d_{min}$ as possible. It turns out that this is not a sustainable way of generating codes with rates close to the channel capacity. Instead, we aim to minimise the <em>error probability,</em> accepting that a few errors are possible here and there.</p>

<h1 id="implementation">Implementation</h1>

<h2 id="1-naïve-c-implementation">1. Naïve C implementation</h2>

<p>My naive implementation of an LDPC decoder is entirely run on the CPU, in about 300 lines of C code. The main decode loop is a simple implementation of min-sum,</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">int</span> <span class="nf">decode</span><span class="p">(</span><span class="n">ldpc_code_t</span> <span class="o">*</span><span class="n">code</span><span class="p">,</span> <span class="n">ldpc_decoder_t</span> <span class="o">*</span><span class="n">decoder</span><span class="p">,</span> <span class="kt">int</span> <span class="o">*</span><span class="n">bits</span><span class="p">,</span> <span class="kt">int</span> <span class="n">max_iters</span><span class="p">)</span>
<span class="p">{</span>   

    <span class="k">for</span><span class="p">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="n">code</span><span class="o">-&gt;</span><span class="n">E</span><span class="p">;</span> <span class="n">i</span><span class="o">++</span><span class="p">)</span>  <span class="p">{</span>
        <span class="n">decoder</span><span class="o">-&gt;</span><span class="n">c2v</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="k">for</span> <span class="p">(</span><span class="kt">int</span> <span class="n">it</span> <span class="o">=</span> <span class="mi">1</span><span class="p">;</span> <span class="n">it</span> <span class="o">&lt;=</span> <span class="n">max_iters</span><span class="p">;</span> <span class="n">it</span><span class="o">++</span><span class="p">)</span> <span class="p">{</span>
        <span class="n">check_update</span><span class="p">(</span><span class="n">code</span><span class="p">,</span> <span class="n">decoder</span><span class="p">);</span>

        <span class="n">decode_hard</span><span class="p">(</span><span class="n">code</span><span class="p">,</span> <span class="n">decoder</span><span class="p">,</span> <span class="n">bits</span><span class="p">);</span>
        <span class="kt">int</span> <span class="n">bad</span> <span class="o">=</span> <span class="n">check_syndrome</span><span class="p">(</span><span class="n">code</span><span class="p">,</span> <span class="n">bits</span><span class="p">);</span>
        <span class="n">DPRINTF</span><span class="p">(</span><span class="s">"iter %i: %i unsatisfied checks</span><span class="se">\n</span><span class="s">"</span><span class="p">,</span> <span class="n">it</span><span class="p">,</span> <span class="n">bad</span><span class="p">);</span>
        <span class="k">if</span> <span class="p">(</span><span class="n">bad</span> <span class="o">==</span> <span class="mi">0</span><span class="p">)</span>   <span class="p">{</span>
            <span class="n">region_free</span><span class="p">(</span><span class="o">&amp;</span><span class="n">c2v_region</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">arena</span><span class="p">);</span>
            <span class="n">region_free</span><span class="p">(</span><span class="o">&amp;</span><span class="n">v2c_region</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">arena</span><span class="p">);</span>
            <span class="k">return</span> <span class="n">it</span><span class="p">;</span> <span class="c1">// converged to a valid codeword</span>
        <span class="p">}</span>

        <span class="n">var_update</span><span class="p">(</span><span class="n">code</span><span class="p">,</span> <span class="n">decoder</span><span class="p">);</span>
    <span class="p">}</span>

    <span class="n">region_free</span><span class="p">(</span><span class="o">&amp;</span><span class="n">c2v_region</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">arena</span><span class="p">);</span>
    <span class="n">region_free</span><span class="p">(</span><span class="o">&amp;</span><span class="n">v2c_region</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">arena</span><span class="p">);</span>

    <span class="k">return</span> <span class="o">-</span><span class="mi">1</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Besides using an arena allocator to avoid malloc overhead in allocating memory for the check/variable node messages, the algorithm is really not very optimised. Visual Studio’s profiler (yes I’m doing this on Windows, it will be clear later why) tells me that the hot path is very much in this decode loop, mostly in the <code class="language-plaintext highlighter-rouge">check_update()</code> function.</p>

<p>!image.png</p>

<p>This is not particularly surprising, as it involves the highest number of mathematical operations. It took us about 13 seconds to run a simulation harness. This specific test involves decoding 100k blocks for 8 different values of $E_b/N_0$. The $H$ matrix we chose here was 96.3.963 from <a href="https://inference.org.uk/mackay/codes/EN/C/">David Mackay’s library</a>.</p>

<p>This code has $n = 96, m=48$ and $288$  edges. As codes go, its big but not huge. The final goal is to decode <a href="https://inference.org.uk/mackay/codes/10000.10000.3.631/">this monster</a> with $n=20000$. Naturally, my current decoder is very unhappy with this</p>]]></content><author><name></name></author><category term="systems" /><summary type="html"><![CDATA[Iterative belief propagation over a sparse bipartite Tanner graph]]></summary></entry><entry><title type="html">usbdiff - A local directory diff tool</title><link href="/systems/2025/07/25/usbdiff.html" rel="alternate" type="text/html" title="usbdiff - A local directory diff tool" /><published>2025-07-25T00:00:00+00:00</published><updated>2025-07-25T00:00:00+00:00</updated><id>/systems/2025/07/25/usbdiff</id><content type="html" xml:base="/systems/2025/07/25/usbdiff.html"><![CDATA[<p>I typically back my files up from my laptop to a USB drive every month or so. The naive approach I tend to use is just to copy the entirety of my working directory to the USB, since I don’t know exactly which files I’ve updated since the last backup. There’s a pretty simple approach here: I could just keep track of a timestamp of the last backup, and only copy over the folders modified since then. But that’s too easy.</p>

<p>I want to make my life a little more difficult, and to make this task a bit more fun, so I’m opting for an overkill approach involving hashes, JSON and some nightmare-inducing use of the Windows API.</p>

<h2 id="outline-of-approach">Outline of Approach</h2>

<p>Taking inspiration from git, I wanted to build a changelog based approach, where I keep track of the state of all files in the directory and only copy over files when there has been a change in state. The way these states are tracked is via a <strong>SHA-256 hash</strong> of the file contents. The flow goes something like this:</p>

<ol>
  <li><strong>Load previous state</strong>
Read .usbdiff.json, which maps each file path to its SHA-256 hash.</li>
  <li><strong>Scan current directory</strong>
Recursively compute SHA-256 hashes of all current files.</li>
  <li><strong>Compare states</strong>
Detect files that are added, removed, or modified by comparing old and new hashes.</li>
  <li><strong>Update cache</strong>
Write the current file state back into .usbdiff.json.</li>
</ol>

<p>So the key components of the project are:</p>

<ul>
  <li><strong>File hash map</strong>: A hash map data structure to match file names to file hashes (a hash map for hashes!)</li>
  <li><strong>Hash cache:</strong> A file (.usbdiff.json) to store the previous state for change detection</li>
  <li><strong>JSON I/O:</strong> Utilities to create/parse JSON files for the hash cache</li>
  <li><strong>SHA-256 hashing:</strong> The core of the application, streaming file data from disk and computing the hash.</li>
</ul>

<h2 id="file-hash-map">File Hash Map</h2>

<p>The main property we need for our internal data structure is fast lookup, so we can check if a file in the current directory exists in the previous state (and if it has changed). A hash map is perfect for this! I built a simple chained hash table:</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">struct</span> <span class="n">fhash_entry</span>  <span class="p">{</span>
    <span class="kt">char</span> <span class="o">*</span><span class="n">filename</span><span class="p">;</span>
    <span class="kt">char</span> <span class="o">*</span><span class="n">filehash</span><span class="p">;</span>
    <span class="k">struct</span> <span class="n">fhash_entry</span> <span class="o">*</span><span class="n">next</span><span class="p">;</span> <span class="c1">// Chaining</span>
<span class="p">};</span>

<span class="k">typedef</span> <span class="k">struct</span>
<span class="p">{</span>
    <span class="n">fhashentry_t</span> <span class="o">*</span><span class="n">farray</span><span class="p">[</span><span class="n">HMAP_MAX_ELEMS</span><span class="p">];</span>

<span class="p">}</span> <span class="n">fhashmap_t</span><span class="p">;</span>
</code></pre></div></div>

<p>Here, <code class="language-plaintext highlighter-rouge">HMAP_MAX_ELEMS</code> is set to 4096, setting the maximum number of independent hashes. If there’s a collision, the item is placed into the bucket by chaining in the form of a linked list. In the worst case, the lookup complexity is \(\mathcal{O}(m)\) where \(m\) is the length of the linked list.</p>

<p>We go through all the files in the directory recursively and add them to the hash map, with the filename as the key and the file hash as the value:</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">char</span><span class="o">*</span> <span class="n">key</span> <span class="o">=</span> <span class="n">_strdup</span><span class="p">(</span><span class="n">full_path</span><span class="p">);</span>
<span class="kt">char</span><span class="o">*</span> <span class="n">value</span> <span class="o">=</span> <span class="n">_strdup</span><span class="p">(</span><span class="n">hash</span><span class="p">);</span>

<span class="k">if</span> <span class="p">(</span><span class="n">key</span> <span class="o">&amp;&amp;</span> <span class="n">value</span><span class="p">)</span> <span class="p">{</span>
    <span class="n">fhashmap_add</span><span class="p">(</span><span class="n">map</span><span class="p">,</span> <span class="n">key</span><span class="p">,</span> <span class="n">value</span><span class="p">);</span>
<span class="p">}</span>
</code></pre></div></div>

<p>here <code class="language-plaintext highlighter-rouge">map</code> is a pointer to the global variable <code class="language-plaintext highlighter-rouge">curr_fhashmap</code>, which is an <code class="language-plaintext highlighter-rouge">fhashmap_t</code>.</p>

<p>JSON I/O
All things JSON are handled via the cJSON library, for which I’ve just copied the header and source into my project directory. It’s quite a well-written, fun repository to use, and I’ve written a very simple wrapper around it for my purposes. The core responsibility of this wrapper code is to convert between my internal fhashmap_t and the cJSON object type. 
To that end, there are two key functions:</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// Create cJSON object from existing fhashmap_t map</span>
<span class="n">cJSON</span><span class="o">*</span> <span class="nf">create_json</span><span class="p">(</span><span class="n">fhashmap_t</span> <span class="o">*</span><span class="n">map</span><span class="p">);</span>

<span class="c1">// Parse JSON from infile into an internal fhashmap_t map</span>
<span class="kt">void</span> <span class="nf">parse_json</span><span class="p">(</span><span class="n">fhashmap_t</span> <span class="o">*</span><span class="n">map</span><span class="p">,</span> <span class="k">const</span> <span class="kt">char</span> <span class="o">*</span><span class="n">infile</span><span class="p">);</span>
</code></pre></div></div>

<p>which do exactly that.</p>

<p>Internally, the <code class="language-plaintext highlighter-rouge">cJSON</code> object is a tree data structure, so while it would be convenient to just compare them directly, lookup performance would be hampered compared to the hashmap.</p>

<p>The <code class="language-plaintext highlighter-rouge">create_json</code> function is quite simple, involving only traversal of the hashmap, building the <code class="language-plaintext highlighter-rouge">cJSON</code> object via the API and writing to a file. However, the parser is a bit more complex, as it involves reading the entire <code class="language-plaintext highlighter-rouge">.usbdiff.json</code> file and constructing a <code class="language-plaintext highlighter-rouge">cJSON</code> object from it. The cJSON API does not support streaming from a file into an object, so the entire file contents must be read into a buffer at once, giving rise to some pretty ugly code:</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// For now, reserve 1MB for JSON contents</span>
<span class="kt">size_t</span> <span class="n">rdbuf_size</span> <span class="o">=</span> <span class="mi">1</span> <span class="o">&lt;&lt;</span> <span class="mi">20</span><span class="p">;</span>
<span class="kt">char</span> <span class="o">*</span><span class="n">rdbuf</span> <span class="o">=</span> <span class="n">malloc</span><span class="p">(</span><span class="n">rdbuf_size</span><span class="p">);</span>
<span class="k">if</span><span class="p">(</span><span class="o">!</span><span class="n">rdbuf</span><span class="p">)</span>  <span class="p">{</span>
    <span class="n">fprintf</span><span class="p">(</span><span class="n">stderr</span><span class="p">,</span> <span class="s">"Failed to allocate space for JSON parsing buffer</span><span class="se">\n</span><span class="s">"</span><span class="p">);</span>
<span class="p">}</span>
</code></pre></div></div>

<p>is then converted to an <code class="language-plaintext highlighter-rouge">fhashmap_t</code>:</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">cJSON</span> <span class="o">*</span><span class="n">elem</span> <span class="o">=</span> <span class="nb">NULL</span><span class="p">;</span>
<span class="n">cJSON_ArrayForEach</span><span class="p">(</span><span class="n">elem</span><span class="p">,</span> <span class="n">object</span><span class="p">)</span>    <span class="p">{</span>
    <span class="k">if</span><span class="p">(</span><span class="o">!</span><span class="n">cJSON_IsString</span><span class="p">(</span><span class="n">elem</span><span class="p">))</span> <span class="k">continue</span><span class="p">;</span>
    <span class="n">fhashmap_add</span><span class="p">(</span><span class="n">map</span><span class="p">,</span> <span class="n">elem</span><span class="o">-&gt;</span><span class="n">string</span><span class="p">,</span> <span class="n">elem</span><span class="o">-&gt;</span><span class="n">valuestring</span><span class="p">);</span>
<span class="p">}</span>
</code></pre></div></div>

<p>We are also able to print the <code class="language-plaintext highlighter-rouge">cJSON</code>  object to the <code class="language-plaintext highlighter-rouge">.usbdiff.json</code> file by a trivial wrapper around the <code class="language-plaintext highlighter-rouge">cJSON_Print</code> function.</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">char</span> <span class="o">*</span><span class="n">string</span> <span class="o">=</span> <span class="n">cJSON_Print</span><span class="p">(</span><span class="n">object</span><span class="p">);</span>
<span class="n">fprintf</span><span class="p">(</span><span class="n">out</span><span class="p">,</span> <span class="s">"%s</span><span class="se">\n</span><span class="s">"</span><span class="p">,</span> <span class="n">string</span><span class="p">);</span>
</code></pre></div></div>

<h1 id="improving-the-parser">Improving the Parser</h1>

<p>Naturally, this is unideal and we want to be able to stream the JSON file contents so we don’t need to reserve a 1MB (or, potentially, larger) buffer.</p>

<p>The idea is to load the JSON data in chunks of, say, 4KB and try to form complete JSON objects from the loaded data. Naturally, there will be incompleteobjects at the end of the chunk, so we move any remaining characters to the start of the buffer and load the next chunk appended to it.</p>

<p>Any JSON objects found are iteratively merged to produce the final, whole, object. Merging involves simply duplicating the object and adding it to the merged object.</p>

<h2 id="hashing">#Hashing</h2>

<h2 id="detecting-changes">Detecting Changes</h2>

<p>To find changes between the two directory structures, we simply do pointwise comparisons of the two hashmaps. We need to do two passes:</p>

<ol>
  <li>One that looks for files in the cached directory state based on the current state (Looking for newly created files)</li>
  <li>One that does the opposite (Looking for modified and deleted files)</li>
</ol>

<p>We then simply add each diff to a <code class="language-plaintext highlighter-rouge">filediff_t</code> object that looks like this:</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">typedef</span> <span class="k">struct</span> <span class="p">{</span>
    <span class="kt">char</span> <span class="n">filename</span><span class="p">[</span><span class="n">MAX_PATH</span><span class="p">];</span>
    <span class="k">enum</span> <span class="p">{</span> <span class="n">MODIFIED</span><span class="p">,</span> <span class="n">DELETED</span> <span class="p">}</span> <span class="n">status</span><span class="p">;</span>
<span class="p">}</span> <span class="n">filediff_t</span><span class="p">;</span>
</code></pre></div></div>

<p>The <code class="language-plaintext highlighter-rouge">status</code> field allows us to keep track of the type of change to each file, so we can print the diff out in a nice, clear and coloured format:</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code>    <span class="n">HANDLE</span> <span class="n">hConsole</span> <span class="o">=</span> <span class="n">GetStdHandle</span><span class="p">(</span><span class="n">STD_OUTPUT_HANDLE</span><span class="p">);</span>
    <span class="n">printf</span><span class="p">(</span><span class="s">"Diffs: </span><span class="se">\n</span><span class="s">"</span><span class="p">);</span>
    <span class="k">for</span><span class="p">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="n">diff_count</span><span class="p">;</span> <span class="n">i</span><span class="o">++</span><span class="p">)</span> <span class="p">{</span>

        <span class="n">CONSOLE_SCREEN_BUFFER_INFO</span> <span class="n">info</span><span class="p">;</span>
        <span class="k">if</span><span class="p">(</span><span class="o">!</span><span class="n">GetConsoleScreenBufferInfo</span><span class="p">(</span><span class="n">hConsole</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">info</span><span class="p">))</span> <span class="k">return</span> <span class="nb">NULL</span><span class="p">;</span>

        <span class="k">if</span><span class="p">(</span><span class="n">diff</span><span class="p">[</span><span class="n">i</span><span class="p">].</span><span class="n">status</span> <span class="o">==</span> <span class="n">MODIFIED</span><span class="p">)</span> <span class="p">{</span> <span class="n">SetConsoleTextAttribute</span><span class="p">(</span><span class="n">hConsole</span><span class="p">,</span> <span class="n">FOREGROUND_GREEN</span><span class="p">);</span> <span class="n">printf</span><span class="p">(</span><span class="s">"+</span><span class="se">\t</span><span class="s">"</span><span class="p">);</span> <span class="p">}</span>
        <span class="k">if</span><span class="p">(</span><span class="n">diff</span><span class="p">[</span><span class="n">i</span><span class="p">].</span><span class="n">status</span> <span class="o">==</span> <span class="n">DELETED</span><span class="p">)</span>  <span class="p">{</span> <span class="n">SetConsoleTextAttribute</span><span class="p">(</span><span class="n">hConsole</span><span class="p">,</span> <span class="n">FOREGROUND_RED</span><span class="p">);</span> <span class="n">printf</span><span class="p">(</span><span class="s">"-</span><span class="se">\t</span><span class="s">"</span><span class="p">);</span> <span class="p">}</span>

        <span class="n">printf</span><span class="p">(</span><span class="s">"%s</span><span class="se">\n</span><span class="s">"</span><span class="p">,</span> <span class="n">diff</span><span class="p">[</span><span class="n">i</span><span class="p">].</span><span class="n">filename</span><span class="p">);</span>

        <span class="n">SetConsoleTextAttribute</span><span class="p">(</span><span class="n">hConsole</span><span class="p">,</span> <span class="n">info</span><span class="p">.</span><span class="n">wAttributes</span><span class="p">);</span>
    <span class="p">}</span>
</code></pre></div></div>

<p>The Windows API is a bit weird here. We essentially read the screen buffer info into the <code class="language-plaintext highlighter-rouge">info</code> variable in order to save the original console buffer state. We then set the text colour to red or green, based on whether the file was deleted or modified, using the <code class="language-plaintext highlighter-rouge">SetConsoleTextAttribute</code> API. This uses an opaque handle to the console object, so its unclear exactly how this function works, but we can assume Windows is casting it to some other struct and modifying a wAttributes field.</p>

<h2 id="refactoring--unix-support">Refactoring + UNIX support</h2>

<p>At this point, some refactoring of the code is in order. The main thing I wanted to change here was the <code class="language-plaintext highlighter-rouge">load_files</code> function, which is single-handedly traversing the directory structure, hashing file contents and adding to the hash map. I think it makes more sense to separate this into two functions: a <code class="language-plaintext highlighter-rouge">collect_files_list</code> function that recursively goes through the directory and adds files to an array, and a <code class="language-plaintext highlighter-rouge">load_files</code> function which then does the hard work of computing hashes and storing them into the <code class="language-plaintext highlighter-rouge">fhashmap_t</code>.</p>

<p>To that end, we define a <code class="language-plaintext highlighter-rouge">filelist_t</code> object, which is really just a wrapper around a static array, and add files to it.</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">void</span> <span class="nf">collect_files_list</span><span class="p">(</span><span class="k">const</span> <span class="kt">char</span> <span class="o">*</span><span class="n">dir</span><span class="p">,</span> <span class="n">filelist_t</span> <span class="o">*</span><span class="n">list</span><span class="p">)</span> <span class="p">{</span>
<span class="cp">#ifdef _WIN32
</span>    <span class="kt">char</span> <span class="n">search_path</span><span class="p">[</span><span class="n">MAX_PATH</span><span class="p">];</span>
    <span class="n">snprintf</span><span class="p">(</span><span class="n">search_path</span><span class="p">,</span> <span class="n">MAX_PATH</span><span class="p">,</span> <span class="s">"%s</span><span class="se">\\</span><span class="s">*"</span><span class="p">,</span> <span class="n">dir</span><span class="p">);</span>

    <span class="n">WIN32_FIND_DATAA</span> <span class="n">findData</span><span class="p">;</span>
    <span class="n">HANDLE</span> <span class="n">hFind</span> <span class="o">=</span> <span class="n">FindFirstFileA</span><span class="p">(</span><span class="n">search_path</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">findData</span><span class="p">);</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">hFind</span> <span class="o">==</span> <span class="n">INVALID_HANDLE_VALUE</span><span class="p">)</span> <span class="k">return</span><span class="p">;</span>

    <span class="k">do</span> <span class="p">{</span>
        <span class="k">if</span> <span class="p">(</span><span class="n">strcmp</span><span class="p">(</span><span class="n">findData</span><span class="p">.</span><span class="n">cFileName</span><span class="p">,</span> <span class="s">"."</span><span class="p">)</span> <span class="o">==</span> <span class="mi">0</span> <span class="o">||</span> <span class="n">strcmp</span><span class="p">(</span><span class="n">findData</span><span class="p">.</span><span class="n">cFileName</span><span class="p">,</span> <span class="s">".."</span><span class="p">)</span> <span class="o">==</span> <span class="mi">0</span><span class="p">)</span>
            <span class="k">continue</span><span class="p">;</span>

        <span class="kt">char</span> <span class="n">full_path</span><span class="p">[</span><span class="n">MAX_PATH</span><span class="p">];</span>
        <span class="n">snprintf</span><span class="p">(</span><span class="n">full_path</span><span class="p">,</span> <span class="k">sizeof</span><span class="p">(</span><span class="n">full_path</span><span class="p">),</span> <span class="s">"%s</span><span class="se">\\</span><span class="s">%s"</span><span class="p">,</span> <span class="n">dir</span><span class="p">,</span> <span class="n">findData</span><span class="p">.</span><span class="n">cFileName</span><span class="p">);</span>

        <span class="k">if</span> <span class="p">(</span><span class="n">findData</span><span class="p">.</span><span class="n">dwFileAttributes</span> <span class="o">&amp;</span> <span class="n">FILE_ATTRIBUTE_DIRECTORY</span><span class="p">)</span> <span class="p">{</span>
            <span class="n">collect_files_list</span><span class="p">(</span><span class="n">full_path</span><span class="p">,</span> <span class="n">list</span><span class="p">);</span>
        <span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
            <span class="k">if</span><span class="p">(</span><span class="n">list_add</span><span class="p">(</span><span class="n">list</span><span class="p">,</span> <span class="n">_strdup</span><span class="p">(</span><span class="n">full_path</span><span class="p">)))</span> <span class="k">return</span><span class="p">;</span>
        <span class="p">}</span>
    <span class="p">}</span> <span class="k">while</span> <span class="p">(</span><span class="n">FindNextFileA</span><span class="p">(</span><span class="n">hFind</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">findData</span><span class="p">));</span>

    <span class="n">FindClose</span><span class="p">(</span><span class="n">hFind</span><span class="p">);</span>

<span class="cp">#else // Linux/macOS
</span>    <span class="kt">DIR</span> <span class="o">*</span><span class="n">dp</span> <span class="o">=</span> <span class="n">opendir</span><span class="p">(</span><span class="n">dir</span><span class="p">);</span>
    <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">dp</span><span class="p">)</span> <span class="k">return</span><span class="p">;</span>

    <span class="k">struct</span> <span class="n">dirent</span> <span class="o">*</span><span class="n">entry</span><span class="p">;</span>
    <span class="k">while</span> <span class="p">((</span><span class="n">entry</span> <span class="o">=</span> <span class="n">readdir</span><span class="p">(</span><span class="n">dp</span><span class="p">))</span> <span class="o">!=</span> <span class="nb">NULL</span><span class="p">)</span> <span class="p">{</span>
        <span class="k">if</span> <span class="p">(</span><span class="n">strcmp</span><span class="p">(</span><span class="n">entry</span><span class="o">-&gt;</span><span class="n">d_name</span><span class="p">,</span> <span class="s">"."</span><span class="p">)</span> <span class="o">==</span> <span class="mi">0</span> <span class="o">||</span> <span class="n">strcmp</span><span class="p">(</span><span class="n">entry</span><span class="o">-&gt;</span><span class="n">d_name</span><span class="p">,</span> <span class="s">".."</span><span class="p">)</span> <span class="o">==</span> <span class="mi">0</span><span class="p">)</span>
            <span class="k">continue</span><span class="p">;</span>

        <span class="kt">char</span> <span class="n">full_path</span><span class="p">[</span><span class="n">PATH_MAX</span><span class="p">];</span>
        <span class="n">snprintf</span><span class="p">(</span><span class="n">full_path</span><span class="p">,</span> <span class="k">sizeof</span><span class="p">(</span><span class="n">full_path</span><span class="p">),</span> <span class="s">"%s/%s"</span><span class="p">,</span> <span class="n">dir</span><span class="p">,</span> <span class="n">entry</span><span class="o">-&gt;</span><span class="n">d_name</span><span class="p">);</span>

        <span class="k">struct</span> <span class="n">stat</span> <span class="n">path_stat</span><span class="p">;</span>
        <span class="k">if</span> <span class="p">(</span><span class="n">stat</span><span class="p">(</span><span class="n">full_path</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">path_stat</span><span class="p">)</span> <span class="o">==</span> <span class="o">-</span><span class="mi">1</span><span class="p">)</span> <span class="k">continue</span><span class="p">;</span>

        <span class="k">if</span> <span class="p">(</span><span class="n">S_ISDIR</span><span class="p">(</span><span class="n">path_stat</span><span class="p">.</span><span class="n">st_mode</span><span class="p">))</span> <span class="p">{</span>
            <span class="n">collect_files_list</span><span class="p">(</span><span class="n">full_path</span><span class="p">,</span> <span class="n">list</span><span class="p">);</span>
        <span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
            <span class="n">list_add</span><span class="p">(</span><span class="n">list</span><span class="p">,</span> <span class="n">_strdup</span><span class="p">(</span><span class="n">full_path</span><span class="p">));</span>
        <span class="p">}</span>
    <span class="p">}</span>

    <span class="n">closedir</span><span class="p">(</span><span class="n">dp</span><span class="p">);</span>
<span class="cp">#endif
</span><span class="p">}</span>
</code></pre></div></div>

<p>Another notable change is UNIX support, which is visible in the else branch of the ifdef. As a side effect, this was useful later on when doing performance profiling!</p>

<p>This all now works, and is organised better, but we can still aim to optimise the runtime. On a large directory, with a diverse set of files (PDFs, images, code, text, etc.), usbdiff takes minutes, which doesn’t seem good enough.</p>

<h2 id="profiling">Profiling</h2>

<p>Profiling the code with <code class="language-plaintext highlighter-rouge">perf record ./usbdiff &lt;directory&gt;</code> followed by <code class="language-plaintext highlighter-rouge">perf report</code>, we find that the runtime is dominated by two functions in the sha-256 hashing library: 
<code class="language-plaintext highlighter-rouge">consume_chunk</code> and <code class="language-plaintext highlighter-rouge">right_rot</code>. While these functions don’t have a large runtime on their own, they are called a significant number of times, which bottlenecks the total runtime of the program. Thus, the performance is <strong>compute-bound</strong>. This is good news, as there are many ways to improve on this, one of which being multi-threading. For a start, I am turning to my good friend <strong>OpenMP</strong>.</p>

<p>OpenMP defines the use of several <code class="language-plaintext highlighter-rouge">#pragma</code> macros that parallelise blocks of code, and it takes care of thread management behind the scenes. Very convenient.</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">int</span> <span class="nf">load_files</span><span class="p">(</span><span class="k">const</span> <span class="n">filelist_t</span> <span class="o">*</span><span class="k">const</span> <span class="n">list</span><span class="p">,</span> <span class="n">fhashmap_t</span> <span class="o">*</span><span class="n">map</span><span class="p">)</span>
<span class="p">{</span>   
    <span class="k">if</span><span class="p">(</span><span class="o">!</span><span class="n">list</span> <span class="o">||</span> <span class="o">!</span><span class="n">map</span><span class="p">)</span> <span class="k">return</span> <span class="mi">1</span><span class="p">;</span>
    
    <span class="cp">#pragma omp parallel for schedule(dynamic, 8)
</span>    <span class="k">for</span><span class="p">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="n">list</span><span class="o">-&gt;</span><span class="n">len</span><span class="p">;</span> <span class="n">i</span><span class="o">++</span><span class="p">)</span>  <span class="p">{</span>
        <span class="k">const</span> <span class="kt">char</span> <span class="o">*</span><span class="n">filename</span> <span class="o">=</span> <span class="n">list</span><span class="o">-&gt;</span><span class="n">filenames</span><span class="p">[</span><span class="n">i</span><span class="p">];</span>
        <span class="kt">char</span> <span class="o">*</span><span class="n">hash</span> <span class="o">=</span> <span class="n">compute_sha256</span><span class="p">(</span><span class="n">filename</span><span class="p">);</span>
        <span class="k">if</span><span class="p">(</span><span class="o">!</span><span class="n">hash</span><span class="p">)</span> <span class="p">{</span>
            <span class="n">fprintf</span><span class="p">(</span><span class="n">stderr</span><span class="p">,</span> <span class="s">"Couldn't hash %s, skipping</span><span class="se">\n</span><span class="s">"</span><span class="p">,</span> <span class="n">filename</span><span class="p">);</span>
            <span class="k">continue</span><span class="p">;</span>
        <span class="p">}</span>
        
        <span class="cp">#pragma omp critical
</span>        <span class="n">fhashmap_add</span><span class="p">(</span><span class="n">map</span><span class="p">,</span> <span class="n">filename</span><span class="p">,</span> <span class="n">_strdup</span><span class="p">(</span><span class="n">hash</span><span class="p">));</span>

        <span class="n">free</span><span class="p">(</span><span class="n">hash</span><span class="p">);</span>
    <span class="p">}</span>

    <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>

<h1 id="metadata-is-good">Metadata Is Good</h1>

<p>In all this, we’re doing something pretty stupid. Let’s say we have a working directory where we modify a few files, maybe add and delete some, but the majority of the directory remains unchanged. In that case, we will unnecessarily be computing hashes for every file in the directory every time we run the program. Most of the files haven’t even been touched! But this raises kind of a cyclical issue: we want to prevent computing the hash of a file if its is unchanged, but how can we know if a file has changed without computing its hash? The answer: metadata.</p>

<p>All internal data structures are updated to store two additional values:</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">typedef</span> <span class="k">struct</span>  <span class="p">{</span>
    <span class="kt">char</span> <span class="n">filename</span><span class="p">[</span><span class="n">MAX_PATH</span><span class="p">];</span>
    <span class="kt">long</span> <span class="kt">long</span> <span class="n">file_size</span><span class="p">;</span>
    <span class="kt">long</span> <span class="kt">long</span> <span class="n">mtime</span><span class="p">;</span>
<span class="p">}</span> <span class="n">file_t</span><span class="p">;</span>

<span class="k">typedef</span> <span class="k">struct</span> <span class="p">{</span>
    <span class="n">file_t</span> <span class="n">files</span><span class="p">[</span><span class="n">MAX_FILES</span><span class="p">];</span>
    <span class="kt">size_t</span> <span class="n">len</span><span class="p">;</span>
<span class="p">}</span> <span class="n">filelist_t</span><span class="p">;</span>
</code></pre></div></div>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">struct</span> <span class="n">fhash_entry</span>  <span class="p">{</span>
    <span class="kt">char</span> <span class="o">*</span><span class="n">filename</span><span class="p">;</span>
    <span class="kt">char</span> <span class="o">*</span><span class="n">filehash</span><span class="p">;</span>
    <span class="kt">long</span> <span class="kt">long</span> <span class="n">file_size</span><span class="p">;</span>
    <span class="kt">long</span> <span class="kt">long</span> <span class="n">mtime</span><span class="p">;</span>
    <span class="k">struct</span> <span class="n">fhash_entry</span> <span class="o">*</span><span class="n">next</span><span class="p">;</span> <span class="c1">// Chaining</span>
<span class="p">};</span>
</code></pre></div></div>

<p>Namely, the <code class="language-plaintext highlighter-rouge">file_size</code> and <code class="language-plaintext highlighter-rouge">mtime</code> fields. Thus, along with the filename, we keep track of the file’s size and last modified time. This data is read from the file when it is found, and kept stored in the JSON file. When it comes time to traverse the directory again, the JSON is parsed and the previous metadata fields compared to the current values. If they match, we can rest assured the file has definitely not been modified, and we don’t need to recompute its hash! This method covers the following scenarios:</p>

<ul>
  <li>A file has not been modified, so its metadata fields and hash are unchanged. In this case, we will simply see unchanged metadata fields, and reuse the previous hash.</li>
  <li>A file has been modified, but its file size has not changed. In this case, the <code class="language-plaintext highlighter-rouge">mtime</code> will have changed, and we will recompute the hash.</li>
  <li>A file has been modified, and its file size has changed. In this case, the file must have changed, and we will have to recompute the hash.</li>
</ul>

<p>This covers all possible scenarios, since it is impossible for a file to be modified and its <code class="language-plaintext highlighter-rouge">mtime</code> field to remain unchanged. The <code class="language-plaintext highlighter-rouge">file_size</code> field provides a quick check which, if failed, necessitates checking the <code class="language-plaintext highlighter-rouge">mtime</code>. This gives rise to the following section in <code class="language-plaintext highlighter-rouge">load_files</code>:</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">int</span> <span class="n">reuse_hash</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>

<span class="n">fhashentry_t</span> <span class="o">*</span><span class="n">entry</span> <span class="o">=</span> <span class="n">fhashmap_lookup</span><span class="p">(</span><span class="n">prev_map</span><span class="p">,</span> <span class="n">filename</span><span class="p">);</span>

<span class="c1">// If the file size does not match, this section is short-circuited since the file must have changed.</span>
<span class="k">if</span><span class="p">(</span><span class="n">entry</span> <span class="o">&amp;&amp;</span> <span class="n">file_size</span> <span class="o">==</span> <span class="n">entry</span><span class="o">-&gt;</span><span class="n">file_size</span><span class="p">)</span>  <span class="p">{</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">mtime</span> <span class="o">==</span> <span class="n">entry</span><span class="o">-&gt;</span><span class="n">mtime</span><span class="p">)</span> <span class="p">{</span>
        <span class="cp">#pragma omp critical
</span>        <span class="n">fhashmap_add</span><span class="p">(</span><span class="n">curr_map</span><span class="p">,</span> <span class="n">filename</span><span class="p">,</span> <span class="n">strdup</span><span class="p">(</span><span class="n">entry</span><span class="o">-&gt;</span><span class="n">filehash</span><span class="p">),</span> <span class="n">entry</span><span class="o">-&gt;</span><span class="n">file_size</span><span class="p">,</span> <span class="n">entry</span><span class="o">-&gt;</span><span class="n">mtime</span><span class="p">);</span>
        <span class="n">reuse_hash</span> <span class="o">=</span> <span class="mi">1</span><span class="p">;</span>
    <span class="p">}</span>
<span class="p">}</span>

<span class="k">if</span> <span class="p">(</span><span class="n">reuse_hash</span><span class="p">)</span> <span class="k">continue</span><span class="p">;</span>
</code></pre></div></div>

<p>The performance gains speak for themselves:</p>

<p><img src="Images/gprof_profile_original" alt="" title="Profile without metadata" />
<img src="Images/gprof_profile_metadata" alt="" title="Profile with metadata" /></p>

<h2 id="copy-to">–copy-to</h2>

<p>As a final addition, the <code class="language-plaintext highlighter-rouge">--copy-to</code> flag was added to let a user copy filesfrom the diff into another directory. The original purpose of this project was to allow exactly this - a quick USB backup of only the files that were updated.</p>

<p>The files marked with status <code class="language-plaintext highlighter-rouge">MODIFIED</code> in the diff are copied over to the chosen directory. This marks the completion of the project to the functional level I aimed for at the start. While there are some potential further avenues to explore such as:</p>

<ul>
  <li>Tracking directory status history</li>
  <li>Making a UI</li>
  <li>Manual threading with pthreads</li>
</ul>

<p>but I’m happy with the way it’s turned out, so let’s leave it at that. Maybe its fitting to reiterate the tagline:</p>

<p><em>Never copy your whole folder again - usbdiff tells you exactly what’s changed</em></p>]]></content><author><name></name></author><category term="systems" /><summary type="html"><![CDATA[I typically back my files up from my laptop to a USB drive every month or so. The naive approach I tend to use is just to copy the entirety of my working directory to the USB, since I don’t know exactly which files I’ve updated since the last backup. There’s a pretty simple approach here: I could just keep track of a timestamp of the last backup, and only copy over the folders modified since then. But that’s too easy.]]></summary></entry><entry><title type="html">On READ_ONCE and Memory Barriers in the Linux Kernel</title><link href="/systems/2025/06/22/mem-barriers.html" rel="alternate" type="text/html" title="On READ_ONCE and Memory Barriers in the Linux Kernel" /><published>2025-06-22T00:00:00+00:00</published><updated>2025-06-22T00:00:00+00:00</updated><id>/systems/2025/06/22/mem-barriers</id><content type="html" xml:base="/systems/2025/06/22/mem-barriers.html"><![CDATA[<p>I’ve been reading <em>Understanding the Linux Kernel</em> by Daniel P. Bovet and Marco Cesati, specifically looking at how memory management works in the kernel. I came across this macro in a deep dive into the <strong>buddy system allocator</strong>:</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="cp">#define list_first_entry_or_null(ptr, type, member) ({ \
	struct list_head *head__ = (ptr); \
	struct list_head *pos__ = READ_ONCE(head__-&gt;next); \
	pos__ != head__ ? list_entry(pos__, type, member) : NULL; \
})
</span></code></pre></div></div>

<p>At its surface, this is a simple macro that checks if a linked list is empty, and returns a pointer to its first entry if not. If we look a little closer, the read of the list entry is wrapped with the <code class="language-plaintext highlighter-rouge">READ_ONCE</code> macro, which expands to</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="cp">#define READ_ONCE(x) (*(volatile typeof(x) *)&amp;(x))
</span></code></pre></div></div>

<p>so we cast the variable to a <code class="language-plaintext highlighter-rouge">volatile</code> and then read that. This is an example of a <em>compiler barrier</em>, preventing the compiler from reordering instructions and doing optimisations that we don’t want. This got me interested to learn more, and so this post highlights my research into memory barriers in Linux, both compiler and CPU barriers.</p>

<h1 id="compiler-barriers">Compiler Barriers</h1>]]></content><author><name></name></author><category term="systems" /><summary type="html"><![CDATA[I’ve been reading Understanding the Linux Kernel by Daniel P. Bovet and Marco Cesati, specifically looking at how memory management works in the kernel. I came across this macro in a deep dive into the buddy system allocator:]]></summary></entry><entry><title type="html">sh_malloc - A sh** Memory Allocator in C</title><link href="/systems/2025/06/22/sh-malloc.html" rel="alternate" type="text/html" title="sh_malloc - A sh** Memory Allocator in C" /><published>2025-06-22T00:00:00+00:00</published><updated>2025-06-22T00:00:00+00:00</updated><id>/systems/2025/06/22/sh-malloc</id><content type="html" xml:base="/systems/2025/06/22/sh-malloc.html"><![CDATA[<p>Now that I’ve finished my final year exams, and submitted my Master’s thesis, I have a bit of time on my hands that I’m not quite sure what to do with. I’ve been meaning to write a memory allocator for a while now, so I figure I might as well do it now. What follows is a “garage door open” view of me building a memory allocator in C; the allocator is dubbed <strong>sh_malloc</strong> for <em>shit</em> malloc — I don’t expect it to be very good.</p>

<h1 id="building-blocks">Building Blocks</h1>

<p>The most bare-bones version of sh_malloc allocates memory in two steps: first, we check the <em>free-list</em> for any free blocks of memory that fit the required allocation size. If none exist, we turn to the OS, requesting additional memory. This flow necessitates the use of a data structure to manage the free-list, where we opt for a linked list.</p>

<p>This list chains together blocks of unused memory by linking <strong>headers</strong> at the start of those regions. The header is simply a block of metadata located just before the block of memory, containing information about its size, free-ness, and a pointer to the next header.</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">struct</span> <span class="n">header</span> <span class="p">{</span>
    <span class="kt">size_t</span> <span class="n">size</span><span class="p">;</span>
    <span class="kt">uint8_t</span> <span class="n">is_free</span><span class="p">;</span>
    <span class="k">struct</span> <span class="n">header</span> <span class="o">*</span><span class="n">next</span><span class="p">;</span>
    <span class="n">arena_t</span> <span class="o">*</span><span class="n">arena</span><span class="p">;</span>
<span class="p">}</span> <span class="n">__attribute__</span><span class="p">((</span><span class="n">aligned</span><span class="p">(</span><span class="mi">16</span><span class="p">)));</span> <span class="c1">// Ensure header is aligned to 16-byte boundary, maximum primitive type size in C</span>

<span class="k">typedef</span> <span class="k">struct</span> <span class="n">header</span> <span class="n">header_t</span><span class="p">;</span>
</code></pre></div></div>

<p>So, the allocation process involves moving through these headers to find a free block with a large enough size. This kind of structure means that we need only worry about managing these headers and, when it’s time to give memory to the user, we simply return a pointer to the memory block after the header:</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">return</span> <span class="p">(</span><span class="kt">void</span><span class="o">*</span><span class="p">)(</span><span class="n">hdr</span><span class="o">+</span><span class="mi">1</span><span class="p">);</span>
</code></pre></div></div>

<p>This is pretty cool, the memory itself <em>is</em> the free-list!</p>

<p>If we don’t find a suitable block, we need to request memory from the OS. In Linux, this involves an <code class="language-plaintext highlighter-rouge">mmap</code> syscall. However, I’m using Windows, which presents the <code class="language-plaintext highlighter-rouge">VirtualAlloc</code> function in its memory API.</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">void</span> <span class="o">*</span><span class="n">block</span> <span class="o">=</span> <span class="n">VirtualAlloc</span><span class="p">(</span><span class="nb">NULL</span><span class="p">,</span> <span class="n">total_size</span><span class="p">,</span> <span class="n">MEM_RESERVE</span> <span class="o">|</span> <span class="n">MEM_COMMIT</span><span class="p">,</span> <span class="n">PAGE_READWRITE</span><span class="p">);</span>
<span class="k">if</span><span class="p">(</span><span class="n">block</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span> <span class="p">{</span>
    <span class="k">return</span> <span class="nb">NULL</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Here, we use <code class="language-plaintext highlighter-rouge">MEM_RESERVE</code> and <code class="language-plaintext highlighter-rouge">MEM_COMMIT</code>, which means Windows will both reserve and allocate the actual pages, which is of course what we want.</p>

<p>There is one crucial element missing here. We’re good programmers, so we make the habit of freeing any unused memory to prevent a memory leak. To abide by this, we need an implementation for <strong>sh_free</strong>. In its current form, it’s actually extremely simple: we just return the memory block to the free-list by toggling the <code class="language-plaintext highlighter-rouge">is_free</code> flag.</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">header_t</span> <span class="o">*</span><span class="n">hdr</span> <span class="o">=</span> <span class="p">(</span><span class="n">header_t</span> <span class="o">*</span><span class="p">)</span><span class="n">ptr</span> <span class="o">-</span> <span class="mi">1</span><span class="p">;</span>
<span class="n">hdr</span><span class="o">-&gt;</span><span class="n">is_free</span> <span class="o">=</span> <span class="mi">1</span><span class="p">;</span>
</code></pre></div></div>

<h1 id="boundary-tagging">Boundary Tagging</h1>

<p>This works, but there are some clear performance issues. For one, it can be very wasteful to use an entire block of memory for a smaller allocation. Also, we can end up fragmenting our address space with many small blocks of memory, which can make it hard to find space for a large allocation later. We can improve on these by being more economical with the memory blocks we get from the OS.</p>

<p>First, <code class="language-plaintext highlighter-rouge">VirtualAlloc</code> gives us memory in multiples of the page size (as does <code class="language-plaintext highlighter-rouge">mmap</code>), so in not accounting for this, we’re wasting the entire rest of the page in perpetuity. It is, thus, much better to split the block so that the rest of the page gets added to the free-list. As a bonus, this also gives us natural <em>arenas</em> (the page itself) for each set of allocations to live in, which is useful for coalescing neighbouring blocks.</p>

<p>When it comes to freeing memory, we check if we can combine the newly freed block with either the next or the previous, if they are also free. Checking the next block is easy, we just jump forward by the size of the current block and check if that block is free. Looking at the previous block is a bit harder to do without going through the entire free-list, and checking every header. There’s a better way, and we’ve already been doing it.</p>

<p>The solution is to augment the current boundary tagging with an additional footer. That way, we can jump a few bytes backwards from the current block and figure out the size of the previous block, allowing us to jump back to its beginning. All of this allows for <strong>constant-time coalescing</strong> of free blocks.</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// Coalesce with next block</span>
<span class="n">header_t</span> <span class="o">*</span><span class="n">next_block</span> <span class="o">=</span> <span class="p">(</span><span class="n">header_t</span> <span class="o">*</span><span class="p">)((</span><span class="kt">char</span> <span class="o">*</span><span class="p">)</span><span class="n">hdr</span> <span class="o">+</span> <span class="k">sizeof</span><span class="p">(</span><span class="n">header_t</span><span class="p">)</span> <span class="o">+</span> <span class="n">hdr</span><span class="o">-&gt;</span><span class="n">size</span> <span class="o">+</span> <span class="k">sizeof</span><span class="p">(</span><span class="kt">size_t</span><span class="p">));</span>
<span class="k">if</span> <span class="p">((</span><span class="kt">void</span> <span class="o">*</span><span class="p">)</span><span class="n">next_block</span> <span class="o">&lt;</span> <span class="p">(</span><span class="kt">char</span> <span class="o">*</span><span class="p">)</span><span class="n">hdr</span><span class="o">-&gt;</span><span class="n">arena</span><span class="o">-&gt;</span><span class="n">base</span> <span class="o">+</span> <span class="n">hdr</span><span class="o">-&gt;</span><span class="n">arena</span><span class="o">-&gt;</span><span class="n">size</span><span class="p">)</span> <span class="p">{</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">next_block</span><span class="o">-&gt;</span><span class="n">is_free</span><span class="p">)</span> <span class="p">{</span>
        <span class="n">hdr</span><span class="o">-&gt;</span><span class="n">size</span> <span class="o">+=</span> <span class="k">sizeof</span><span class="p">(</span><span class="n">header_t</span><span class="p">)</span> <span class="o">+</span> <span class="n">next_block</span><span class="o">-&gt;</span><span class="n">size</span> <span class="o">+</span> <span class="k">sizeof</span><span class="p">(</span><span class="kt">size_t</span><span class="p">);</span>
        <span class="n">hdr</span><span class="o">-&gt;</span><span class="n">next</span> <span class="o">=</span> <span class="n">next_block</span><span class="o">-&gt;</span><span class="n">next</span><span class="p">;</span>
        <span class="n">hdr</span><span class="o">-&gt;</span><span class="n">arena</span><span class="o">-&gt;</span><span class="n">num_blocks</span><span class="o">--</span><span class="p">;</span>
        <span class="n">write_footer</span><span class="p">(</span><span class="n">hdr</span><span class="p">);</span>
    <span class="p">}</span>
<span class="p">}</span>

<span class="c1">// Coalesce with previous block</span>
<span class="kt">size_t</span> <span class="o">*</span><span class="n">prev_size_ptr</span> <span class="o">=</span> <span class="p">(</span><span class="kt">size_t</span> <span class="o">*</span><span class="p">)((</span><span class="kt">char</span> <span class="o">*</span><span class="p">)</span><span class="n">hdr</span> <span class="o">-</span> <span class="k">sizeof</span><span class="p">(</span><span class="kt">size_t</span><span class="p">));</span>
<span class="k">if</span> <span class="p">((</span><span class="kt">void</span> <span class="o">*</span><span class="p">)</span><span class="n">prev_size_ptr</span> <span class="o">&gt;</span> <span class="n">hdr</span><span class="o">-&gt;</span><span class="n">arena</span><span class="o">-&gt;</span><span class="n">base</span><span class="p">)</span> <span class="p">{</span>
    <span class="kt">size_t</span> <span class="n">prev_size</span> <span class="o">=</span> <span class="o">*</span><span class="n">prev_size_ptr</span><span class="p">;</span>
    <span class="n">header_t</span> <span class="o">*</span><span class="n">prev</span> <span class="o">=</span> <span class="p">(</span><span class="n">header_t</span> <span class="o">*</span><span class="p">)((</span><span class="kt">char</span> <span class="o">*</span><span class="p">)</span><span class="n">hdr</span> <span class="o">-</span> <span class="k">sizeof</span><span class="p">(</span><span class="kt">size_t</span><span class="p">)</span> <span class="o">-</span> <span class="n">prev_size</span> <span class="o">-</span> <span class="k">sizeof</span><span class="p">(</span><span class="n">header_t</span><span class="p">));</span>
    <span class="k">if</span> <span class="p">((</span><span class="kt">void</span> <span class="o">*</span><span class="p">)</span><span class="n">prev</span> <span class="o">&gt;</span> <span class="n">hdr</span><span class="o">-&gt;</span><span class="n">arena</span><span class="o">-&gt;</span><span class="n">base</span> <span class="o">&amp;&amp;</span> <span class="n">prev</span><span class="o">-&gt;</span><span class="n">is_free</span><span class="p">)</span> <span class="p">{</span>
        <span class="n">prev</span><span class="o">-&gt;</span><span class="n">size</span> <span class="o">+=</span> <span class="k">sizeof</span><span class="p">(</span><span class="n">header_t</span><span class="p">)</span> <span class="o">+</span> <span class="n">hdr</span><span class="o">-&gt;</span><span class="n">size</span> <span class="o">+</span> <span class="k">sizeof</span><span class="p">(</span><span class="kt">size_t</span><span class="p">);</span>
        <span class="n">prev</span><span class="o">-&gt;</span><span class="n">next</span> <span class="o">=</span> <span class="n">hdr</span><span class="o">-&gt;</span><span class="n">next</span><span class="p">;</span>
        <span class="n">prev</span><span class="o">-&gt;</span><span class="n">arena</span><span class="o">-&gt;</span><span class="n">num_blocks</span><span class="o">--</span><span class="p">;</span>
        <span class="n">write_footer</span><span class="p">(</span><span class="n">prev</span><span class="p">);</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Note that the arena region is used to bound the accesses of the next and previous block. This is needed since we can only guarantee that blocks generated in this arena are part of the free list, and memory beyond it may be unsafe to access. This does allow for some fragmentation across page boundaries.</p>

<h1 id="more-on-arenas">More on Arenas</h1>

<p>There’s a lot of talk here on arenas, but I haven’t really explained how they work in this implementation. The idea is simple: when we request memory from the OS, we do it in multiples of the page size, giving us a large memory region in which to do as many allocations as we can. This is an arena. If we need more space, we ask for it and get a new arena, but we hope most of our allocations will fit in an arena and fill it out, rather than fragmenting over multiple arenas.</p>

<p>Arenas are managed by a <code class="language-plaintext highlighter-rouge">struct arena_t</code> :</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">typedef</span> <span class="k">struct</span> <span class="p">{</span>
    <span class="kt">void</span> <span class="o">*</span><span class="n">base</span><span class="p">;</span>
    <span class="kt">size_t</span> <span class="n">size</span><span class="p">;</span>
    <span class="kt">int</span> <span class="n">num_free_blocks</span><span class="p">;</span>
    <span class="kt">int</span> <span class="n">num_blocks</span><span class="p">;</span>
<span class="p">}</span> <span class="n">arena_t</span><span class="p">;</span>
</code></pre></div></div>

<p>and you may have noticed that a pointer to this struct exists in the <code class="language-plaintext highlighter-rouge">header_t</code> for each block of memory.</p>

<p>We want to track the same arena object for all blocks of memory in an arena, so we need some kind of global definition for it. To get around dynamically allocating it (feels like cheating to use <code class="language-plaintext highlighter-rouge">malloc()</code> in a malloc implementation), we instead use a bit of space at the top of the arena to store the <code class="language-plaintext highlighter-rouge">arena_t</code> object. Thus, as long as the arena exists, we can refer to its <code class="language-plaintext highlighter-rouge">arena_t</code>, pretty cool!</p>

<p>This lets us do one more important thing: we can give memory back to the OS if the entire arena is free. This can be done at a more granular level, for each memory block, but we’ll likely spend too much time in syscalls, and also be giving up memory that we’ll likely need soon anyway. Giving up an entire arena when its free is a more balanced approach.</p>

<h1 id="thread-safety">Thread Safety</h1>]]></content><author><name></name></author><category term="systems" /><summary type="html"><![CDATA[Now that I’ve finished my final year exams, and submitted my Master’s thesis, I have a bit of time on my hands that I’m not quite sure what to do with. I’ve been meaning to write a memory allocator for a while now, so I figure I might as well do it now. What follows is a “garage door open” view of me building a memory allocator in C; the allocator is dubbed sh_malloc for shit malloc — I don’t expect it to be very good. Building Blocks The most bare-bones version of sh_malloc allocates memory in two steps: first, we check the free-list for any free blocks of memory that fit the required allocation size. If none exist, we turn to the OS, requesting additional memory. This flow necessitates the use of a data structure to manage the free-list, where we opt for a linked list. This list chains together blocks of unused memory by linking headers at the start of those regions. The header is simply a block of metadata located just before the block of memory, containing information about its size, free-ness, and a pointer to the next header. struct header { size_t size; uint8_t is_free; struct header *next; arena_t *arena; } __attribute__((aligned(16))); // Ensure header is aligned to 16-byte boundary, maximum primitive type size in C typedef struct header header_t; So, the allocation process involves moving through these headers to find a free block with a large enough size. This kind of structure means that we need only worry about managing these headers and, when it’s time to give memory to the user, we simply return a pointer to the memory block after the header: return (void*)(hdr+1); This is pretty cool, the memory itself is the free-list! If we don’t find a suitable block, we need to request memory from the OS. In Linux, this involves an mmap syscall. However, I’m using Windows, which presents the VirtualAlloc function in its memory API. void *block = VirtualAlloc(NULL, total_size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); if(block == NULL) { return NULL; } Here, we use MEM_RESERVE and MEM_COMMIT, which means Windows will both reserve and allocate the actual pages, which is of course what we want. There is one crucial element missing here. We’re good programmers, so we make the habit of freeing any unused memory to prevent a memory leak. To abide by this, we need an implementation for sh_free. In its current form, it’s actually extremely simple: we just return the memory block to the free-list by toggling the is_free flag. header_t *hdr = (header_t *)ptr - 1; hdr-&gt;is_free = 1; Boundary Tagging This works, but there are some clear performance issues. For one, it can be very wasteful to use an entire block of memory for a smaller allocation. Also, we can end up fragmenting our address space with many small blocks of memory, which can make it hard to find space for a large allocation later. We can improve on these by being more economical with the memory blocks we get from the OS. First, VirtualAlloc gives us memory in multiples of the page size (as does mmap), so in not accounting for this, we’re wasting the entire rest of the page in perpetuity. It is, thus, much better to split the block so that the rest of the page gets added to the free-list. As a bonus, this also gives us natural arenas (the page itself) for each set of allocations to live in, which is useful for coalescing neighbouring blocks. When it comes to freeing memory, we check if we can combine the newly freed block with either the next or the previous, if they are also free. Checking the next block is easy, we just jump forward by the size of the current block and check if that block is free. Looking at the previous block is a bit harder to do without going through the entire free-list, and checking every header. There’s a better way, and we’ve already been doing it. The solution is to augment the current boundary tagging with an additional footer. That way, we can jump a few bytes backwards from the current block and figure out the size of the previous block, allowing us to jump back to its beginning. All of this allows for constant-time coalescing of free blocks. // Coalesce with next block header_t *next_block = (header_t *)((char *)hdr + sizeof(header_t) + hdr-&gt;size + sizeof(size_t)); if ((void *)next_block &lt; (char *)hdr-&gt;arena-&gt;base + hdr-&gt;arena-&gt;size) { if (next_block-&gt;is_free) { hdr-&gt;size += sizeof(header_t) + next_block-&gt;size + sizeof(size_t); hdr-&gt;next = next_block-&gt;next; hdr-&gt;arena-&gt;num_blocks--; write_footer(hdr); } } // Coalesce with previous block size_t *prev_size_ptr = (size_t *)((char *)hdr - sizeof(size_t)); if ((void *)prev_size_ptr &gt; hdr-&gt;arena-&gt;base) { size_t prev_size = *prev_size_ptr; header_t *prev = (header_t *)((char *)hdr - sizeof(size_t) - prev_size - sizeof(header_t)); if ((void *)prev &gt; hdr-&gt;arena-&gt;base &amp;&amp; prev-&gt;is_free) { prev-&gt;size += sizeof(header_t) + hdr-&gt;size + sizeof(size_t); prev-&gt;next = hdr-&gt;next; prev-&gt;arena-&gt;num_blocks--; write_footer(prev); } } Note that the arena region is used to bound the accesses of the next and previous block. This is needed since we can only guarantee that blocks generated in this arena are part of the free list, and memory beyond it may be unsafe to access. This does allow for some fragmentation across page boundaries. More on Arenas There’s a lot of talk here on arenas, but I haven’t really explained how they work in this implementation. The idea is simple: when we request memory from the OS, we do it in multiples of the page size, giving us a large memory region in which to do as many allocations as we can. This is an arena. If we need more space, we ask for it and get a new arena, but we hope most of our allocations will fit in an arena and fill it out, rather than fragmenting over multiple arenas. Arenas are managed by a struct arena_t : typedef struct { void *base; size_t size; int num_free_blocks; int num_blocks; } arena_t; and you may have noticed that a pointer to this struct exists in the header_t for each block of memory. We want to track the same arena object for all blocks of memory in an arena, so we need some kind of global definition for it. To get around dynamically allocating it (feels like cheating to use malloc() in a malloc implementation), we instead use a bit of space at the top of the arena to store the arena_t object. Thus, as long as the arena exists, we can refer to its arena_t, pretty cool! This lets us do one more important thing: we can give memory back to the OS if the entire arena is free. This can be done at a more granular level, for each memory block, but we’ll likely spend too much time in syscalls, and also be giving up memory that we’ll likely need soon anyway. Giving up an entire arena when its free is a more balanced approach. Thread Safety]]></summary></entry></feed>