Hosting a blog on an FPGA

I wanted to learn digital logic design. Here are my criteria:

After some deliberation it hit me. You are reading this right now on my blog. Why not serve you the content directly from an FPGA. There are many reasons why people don’t usually do this, which conveniently satisfies criteria 1.

In a traditional web server, there are a lot of operations that need to happen, and those of high complexity are usually related to negotiating a secure connection. To not die by scope creep, I landed on bare HTTP. This way, we can ignore TLS and encryption. This also means that we would have to make use of a reverse proxy to perform this task. This is quite a common network architecture, and is also the one used in my home network. This also allows us to make simplifying assumptions on the way to the final goal. More on this later.

Hardware choice

Whilst scouring for a suitable development board, I found the Colorlight 5A-75B to be an easy and natural choice. There aren’t many FPGA boards that are cheap and also come with an on board Ethernet PHY. On top of that, it even has 2 PHYs, 2MB of SDRAM and flash storage. Although not a conventional choice, others have provided a more concrete run-down and even done reverse engineering of the pins. As the main purpose of the Colorlight was to drive LED panels with whatever pattern you desire, we have not a bad selection to work with:

You can find out more about this board here. Link to where you can buy one here.

The setup used for development is a simple point to point Ethernet connection with my laptop. We can even repurpose one of the IO pins as a UART TX line. This would serve as our mode of printf debugging for the entire project.

the hardware setup

ARP: The first stepping stone

The first key milestone is responding to Address Resolution Protocol (ARP) packets. These are the baseline, and require the device to have an IP and MAC address to respond with. Easily enough, we can hardcode this.

localparam [47:0] LOC_MAC_ADDR = 48'hDEADBEEFCAFE;
localparam [31:0] LOC_IP_ADDR = 32'h69696969; // 105.105.105.105

One available tool in Linux is arping, which lets you specify the target MAC address and craft a ARP request rather than IPV4 ICMP packet. Getting this to work would mean successfully driving the RGMII interface of the PHY.

The design I decided to go with is to process the frame data in-place rather than saving the entire frame in a buffer and processing it separately. This means the decoding logic runs off the PHY RXC clock. There are a few advantages of this approach. The first is slightly reduced latency as the decoding is done during the receive itself. At 1 gigabit, we would save at most max frame size / 1 gigabit; 1518/125000000 = 12 micro seconds. Another one is that a separate buffer for the frame is not necessary. However, this means the decoding logic must also keep up with RXC. This is fine as we are mostly selecting parts of the packet based on a counter value or state machine. The checksum calculation can also be done per-cycle every 2 bytes. For in-line processing, it would also be great if there is a way to determine the transition between payload and checksum. This can be done by adding 4 cycles of latency and delaying the RXD and RXDV lines. When RXDV is low, RXD delayed will have the last payload value.

decode done in a streaming fashion

With that, the next thing to do is generate ARP replies. From the receive path, info such as the source hardware address and IP has to be extracted. The main challenge here is to do a Clock Domain Crossing from the PHY RXC, into the system clock. This is a solved problem using a gray-coded counter FIFO, and one of the main references for doing this is Clifford Cumming’s paper. Rather than crossing all the decoded values, only the done and error signals are crossed and then used to trigger the transmit logic.

To keep the transmit path simple from the start, I chose to stream the data from the encoder directly to the RGMII lanes, rather than to first build a packet in a separate buffer. The main issue with this approach is that header information must be ready before the encoding starts. Checksums for example, are the trickiest. This would come back to bite me later, but works OK for ARP.

The main challenge here is timing. Driving a gigabit RGMII lane first requires a 125 mhz clock. The Colorlight offers a 25mhz clock generated by an external crystal and passed through by the PHY. We can quite easily create the frequency we need using the EHXPLL primitive. Thankfully, a good reference can be found in project trellis. They have even documented examples of which parameters to change for generating more complex clock signals. Specifically, the RGMII spec requires a minimum setup and hold time of 1.2ns of on the data and control signals. The solution I came up with, which is also what is described in this excellent post by Jonathan McGee, is to generate the data on one clock, while the TXC is offset by 90 degrees with respect to that clock.

RGMII interface setup & hold time

I found that the phase offset was not strictly necessary in practice. Probing the TXDLY lines revealed that the PHY is configured to use the built-in 2ns delay on the TXC. However, one important note is to ensure that the delays for TXD and TXC lined up. Since ODDR is used to generate the data, TXC should also go through the same path:

  oddr #(
      .INPUT_WIDTH(4)
  ) _oddr (
      .rst(rst),
      .clk(clk),
      .d1 (txd_1),
      .d2 (txd_2),
      .q  (phy_txd)
  );

  oddr #(
      .INPUT_WIDTH(1)
  ) txc_oddr (
      .rst(rst),
      .clk(clk),
      .d1 (1'b1),
      .d2 (1'b0),
      .q  (phy_txc)
  );

The Colorlight was also especially chosen because the ECP5 primitives we need are supported by open source tooling like yosys and next-pnr. Avoiding vendor GUIs is always a plus in my book as I can now run the entire synthesis, place and route and programming flow using a simple Makefile. next-pnr even supports a few basic constraints such as SLEWRATE and DRIVE which can be quite important for meeting the strict rise/fall times for RGMII.

IOBUF PORT "phy0_txd[0]" IO_TYPE=LVCMOS33 PULLMODE=NONE DRIVE=8 SLEWRATE=FAST ;
IOBUF PORT "phy0_txd[1]" IO_TYPE=LVCMOS33 PULLMODE=NONE DRIVE=8 SLEWRATE=FAST ;
IOBUF PORT "phy0_txd[2]" IO_TYPE=LVCMOS33 PULLMODE=NONE DRIVE=8 SLEWRATE=FAST ;
IOBUF PORT "phy0_txd[3]" IO_TYPE=LVCMOS33 PULLMODE=NONE DRIVE=8 SLEWRATE=FAST ;
IOBUF PORT "phy0_txctl"  IO_TYPE=LVCMOS33 PULLMODE=NONE DRIVE=8 SLEWRATE=FAST ;
IOBUF PORT "phy0_txc"    IO_TYPE=LVCMOS33 PULLMODE=NONE DRIVE=8 SLEWRATE=FAST ;

And voila. With ARP support, any device can now discover the IP address of our FPGA. In fact, if we probe the interface in wireshark we can see that this is done by the host before the TCP handshake is initiated. In the next section, I describe how to achieve the “hello, world” of networking tutorials, a TCP echo server on the FPGA.

sudo arping -c 1 -i enp61s0 -t DE:AD:BE:EF:CA:FE -S 192.168.69.100 105.105.105.105
ARPING 105.105.105.105
60 bytes from de:ad:be:ef:ca:fe (105.105.105.105): index=0 time=66.489 usec

--- 105.105.105.105 statistics ---
1 packets transmitted, 1 packets received,   0% unanswered (0 extra)
rtt min/avg/max/std-dev = 0.066/0.066/0.066/0.000 ms

Getting to a TCP Echo Server

Conventional TCP is an absolute behemoth and there is still ongoing research for making it higher performance and reliable. In summary, it offers (1) reliable transmission through retransmission of lost data packets; (2) error detection with checksums; (3) reordering of data received out of order (4) flow control using receiver advertised windows; (5) congestion control using sender tracked congestion window. For a bare minimum TCP echo server, we can strip down most of the components that make TCP challenging. We will first ignore points (4) and (5), although adding them in the future is less complicated.

The big win in terms of complexity is to ignore out of order packets, TCP’s main objective to provide reliable delivery of packets. We forgo this property by assuming the network is controlled with no chance of re-ordering and leave this for future me. For the final set-up, since the request is mediated by our reverse proxy anyway, the re-ordering is limited to the network path from the reverse proxy to the FPGA. Hence, for our use case, packets received out of order (OOP) are silently dropped. Basically, if the sequence number received is not expected, the TCP engine will reject the payload and no ACK is sent. This would rely on the sender to detect this packet as lost and re-transmit the entire payload once more, hopefully allowing the packet to be received in-order at the FPGA.

tcp::ESTABLISHED: begin
  if (i_flags_has_ack) begin
    // find a match
    // Ack came for one of to_be_ack, due to cumulative ack, we can
    // safely deallocate all smaller acks
    clear_ack_en <= i_ack_num >= tcb_expected_ack_num;
  end

  if (has_payload) begin
    if (seq_match) begin
      // received sequence number is what we expect the next byte to be
      accept_payload <= 1'b1;
      ack_op <= 2'b10;
      send_ack <= 1'b1;
    end else begin
      // simply do not accept out of order packets right now
      $display("ERROR: incoming seq > current ack");
      reject_payload <= 1'b1;
    end
  end else begin
    $display("LOG: no payload data in incoming packet");
    reject_payload <= 1'b1;
  end

  if (i_flags_has_rst) begin
    next_state <= tcp::LISTEN;
  end else if (i_flags_has_fin) begin
    ack_op <= 2'b01;
    next_state <= tcp::LASTACK;
    send_ack <= 1'b1;
  end else next_state <= tcp::ESTABLISHED;
end

However, this is definitely not the right solution, and only solves issues where the OOP is a result of some intermittent issue on the network path like a spike in traffic. It could be that OOP are perpetually received, because out of order is not a pathological thing (i.e. network placement, routing placement). Since we are self-hosting this, and testing is done peer-to-peer, we can “safely” ignore this for now.

Core

At its core, the TCP engine consumes packet_t, forwards it to a corresponding tcb_t and does the reverse for transmission.

Packet: Contains the Information decoded or required for encoding onto the RGMII. This is metadata, such as the IP addresses, port, payload size, address to the payload in memory.

Transmission Control Block (TCB): represents one tcp connection and holds all the state for it. The basic metadata is stored in on-chip registers and is used often by the engine to check for valid packets and create new ones.

typedef struct packed {
  // to identify this TCB uniquely
  logic [31:0] peer_addr;
  logic [15:0] peer_port;
  // Sequence number for transmitting our own data. It is the sequence_num
  // for the next transmit packet
  logic [31:0] sequence_num;
  // Ack number used for transmitting. i.e. the number expected by the
  // receiver (received sequence_num + 1)
  logic [31:0] ack_num;
  logic [15:0] window;

  CONN_STATE state;
} tcb_t;
// in registers
tcp::tcb_t tcb_mem;

In addition, each TCB module holds 3 other FIFOs. First, to_send is a FIFO holding pending transmit packets. These are written by the arbiter in the next section when the upper layer logic wants to make a transmission. The next, to_ack is an internal fifo holding packets that have been submitted to the transmission engine but waiting for an ack response. An ACK received will clear this FIFO. Cumulative ACKs (ack number is larger than the smallest ACK number we have in the FIFO) are easily supported; by popping off from the FIFO until it is either empty, or we reach the packet the ACK is meant for).

A sequence diagram of the interactions between the to_send, to_ack and to_serialize FIFO

Although I previously mentioned how OOP are ignored, this is only “safe” on the RX path. On the TX side, it is definitely likely the packet gets lost in the network towards the client. To support this, a retransmit timer would sit here and copy the packet metadata from to_ack back into the third FIFO serialized. This is needed to ensure proper sequencing of all these different ways packets can be introduced into the transmit path. Some additional ways include a FIN timeout which would send a FIN if the TCB has been in FINWAIT for an extended period of time. To prevent hogging, the TCB also transitions into FINWAIT if it has been idle long enough. As some of these transitions like ESTABLISHED to FINWAIT would want to trigger a packet with flags but no payload, these are supported through the introduction of pseudo_packets.

// TCB is allowed to independently transition, for e.g.to FINWAIT if it has been idle
always @(posedge clk) begin
  if (rst) begin
    tcb_mem.state <= tcp::LISTEN;
  end else if (rx_update_en) begin
    tcb_mem.state <= i_state;
  end else if (tcb_mem.state == tcp::FINWAIT && fin_timeout) begin
    tcb_mem.state <= tcp::LISTEN;
  end else if (tcb_mem.state == tcp::ESTABLISHED && !echo_en) begin
    if (idle_timeout || (serial_empty && actual_payload_serialized && to_ack_empty))
      tcb_mem.state <= tcp::FINWAIT;
  end
end

// Transitions can cause fin_pending
always @(posedge clk) begin
  if (rst || state_rst) begin
    fin_pending   <= 0;
    fin_pending_q <= 0;
  end else begin
    fin_pending_q <= fin_pending;
    if (tcb_mem.state == tcp::FINWAIT) begin
      fin_pending <= 1'b1;
    end else if (tcb_mem.state == tcp::ESTABLISHED && !echo_en &&
    serial_empty && actual_payload_serialized && to_ack_empty && to_send_empty)
    begin
      fin_pending <= 1'b1;
    end else if (tcb_mem.state != tcp::ESTABLISHED) begin
      fin_pending <= 0;
    end
  end
end

// fin_pending will assert pseudo_pkt_pending, which will be serialized
always @(posedge clk) begin
  if (rst || state_rst || pseudo_pkt_granted) pseudo_pkt_pending <= 1'b0;
  // allow transition to FINWAIT to trigger pseudo packet
  else if (wait_pkt_done || (fin_pending && !fin_pending_q))
      pseudo_pkt_pending <= 1'b1;
end

State Machine

The original state machine is rather large. For an echo server, we need only implement the responder sections. We can also remove close-wait by sending fin and ack together.

Annotated TCP state machine, removing unnecessary sections

The entire thing is implemented as a module separate from the arbiter. Its inputs are the packet data such as the flags, sequence number etc. whether the packet data is intended for the RX or TX path, the current TCB data such as the current sequence number to determine the validity of the packet data. It has a few key outputs. seq_op and ack_op, which are used to update the TCB internal state, such as to increment the sequence number. send_ack is asserted to force TCB to place a pending packet into its queue with no payload but with the ACK flag. accept_payload and reject_payload are used to signal the application layer whether its safe to process the TCP payload.

Arbiter

The number of simultaneous active connections is limited by the number of TCBs. To handle multiple TCBs, an arbiter is used. It activates the correct TCB based on the IP address and port within the packet data. It also checks which TCBs have a pending packet to send and is in charge of muxing these requests with the transmission module. It also arbitrates access to the TCP state machine handler.

There are 3 kinds of requests that the arbiter needs to handle, which become serialized using their own set of pending and granted signals.

  1. Echo request. This is our MVP. It bypasses signalling to the upper layers. The received TCP payload is buffered in memory, and routed back out onto the TX path.
  2. State machine requests. For example, the send_ack from above gets placed into the TCB’s pending queue.
  3. Upper layer requests. An application layer module can place a packet into TCB’s pending queue through the arbiter. If the payload is larger than MSS, the arbiter breaks it up by incrementing the payload address and setting the correct size for each until each is able to fit.
  4. All the requests eventually end up inside the serialized FIFO introduced earlier. The arbiter checks each of these in each TCB and grants them round robin access.

Before going further, here is a block diagram for all of what’s discussed:

Architecture block diagram

Testing

I think this is a good place to introduce the infrastructure used for testing. Simulation is done using cocotb, a python framework. This ties in nicely with libraries like scapy and its Automaton class to specify state machines transitions, which I found useful for modelling network protocol behavior. Here is an example of the included TCP client model, omitted for brevity of showing how the 3 way handshake is represented.

class TCP_client(Automaton):
    def master_filter(self, pkt):
        return (IP in pkt and
                pkt[IP].src == self.dst and
                pkt[IP].dst == self.src and
                TCP in pkt and
                pkt[TCP].sport == self.dport and
                pkt[TCP].dport == self.sport and
                self.l4[TCP].seq >= pkt[TCP].ack and
                ((self.l4[TCP].ack == 0) or 
                (self.sack <= pkt[TCP].seq <= self.l4[TCP].ack + pkt[TCP].window)))

    @ATMT.state()
    def SYN_SENT(self):
        pass

    @ATMT.state()
    def ESTABLISHED(self):
        pass

    @ATMT.condition(START)
    def connect(self):
        raise self.SYN_SENT()

    @ATMT.action(connect)
    def send_syn(self):
        self.l4[TCP].flags = "S"
        self.send(self.l4)
        self.l4[TCP].seq += 1

    @ATMT.receive_condition(SYN_SENT)
    def synack_received(self, pkt):
        if pkt[TCP].flags.SA:
            raise self.ESTABLISHED().action_parameters(pkt)

The only thing that is needed is a little code to convert the RGMII signals from the test bench into scapy packets that it can understand and vice versa. Thankfully, Alex Foreinch developed cocotb-eth, capable of doing the heavy lifting from RGMII to raw bytes. Scapy can easily do the conversion from there with a little coercion. With all this in place, I can sprinkle assertions on sequence number, expected payloads, checksum validity, number of received packets, to ensure the design works. I also added test cases using different sized payloads and even dropped packets to simulate the retransmit behavior.

What I have described is more akin to integration testing of all the combined modules. As each piece was being built, simulation helped to check that each part of the pipeline produced the right values for the next. For basic modules like the FIFO, I employed small amounts of formal checks.

A completely static HTTP

In the process of achieving the TCP echo server, we have almost all the required components for serving a webpage; instead of echoing the payload, we just need to parse for a semi-valid HTTP request and respond accordingly.

The HTTP decoder is simple enough, read the first line for the method and target, ignore all headers. We just need a way to translate the endpoint to the data for the page. Minimally, this means the starting address of the content in memory as well as the size.

There is actually slightly more to keep things completely static. For this approach that builds the packet in-situ during the transmission, not only must the content be static, but the payload checksum needs to be precomputed. Moreover, the entire HTTP header is statically stored together with the content. Below is a snippet of what is actually written to the on board flash:

HTTP/1.0 200 OK
Content-Length: 21308

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>This Page is on an FPGA</title>
    ...

For each page, a little tool I wrote would attach the HTTP header and combine them all into a single file for writing to the flash. Each page is also sequentially assigned its address in flash aligned to 32bits. To know how much data to read, each of the content sizes are written to a separate file. The address and size files are hardcoded as ROM blocks on the FPGA as HTTP_ADDR_FILE and HTTP_SIZE_FILE respectively.

At first, I stored the precomputed checksum next to the payload size, hardcoded into ROM blocks. You can start to see how this breaks down if we have to support packets larger than max segment size, as the checksum is only for the entire payload. Although this could somewhat be mitigated if the reverse proxy is configured for jumbo segments, the maximum jumbo segment is only 9000 bytes anyway. I transitioned to computing the required checksum during the transfer from SDRAM into block RAM.

// For now we only support ascii [0-7] and [a-z|A-Z]
// working contains {X,X,0,\}: X = dont-care
// -48: convert to ascii
// +1: 0 index is 404
if (state == TARGET) key <= {1'b0, working[15:8]} - 'd47;

always_comb begin
next_state = state;
case (state)
  IDLE: if (tcp_payload_valid) next_state = GET_PAYLOAD;
  GET_PAYLOAD: if (i_payload_valid) next_state = METHOD;
  METHOD: begin
    // LSB order
    if (" TEG" == working) next_state = TARGET;
    else next_state = ABORT;
  end
  TARGET: begin
    // take only the first byte as target endpoint
    next_state = MATCH;
  end
  MATCH: begin
    next_state = WAIT_MEM1;
  end
  WAIT_MEM1: next_state = WAIT_MEM2;
  WAIT_MEM2: begin
    next_state = IDLE;
  end
  ABORT: if (!i_payload_valid) next_state = IDLE;
  default: next_state = IDLE;
endcase
end

http_entry #(
  .HTTP_ADDR_FILE(HTTP_ADDR_FILE),
  .HTTP_SIZE_FILE(HTTP_SIZE_FILE)
) meta (
  .clk(clk),
  .key(key),
  .content_addr(res_payload_addr),
  .content_size(res_payload_size)
);

The 4MB of non-volatile flash memory will hold all the static pages, written once during programming. This way, I could also add additional pages in the future by writing to flash. However, reading from flash during runtime would also be prohibitively slow, which means a SDRAM controller is in-order.

Putting everything together, the memory flow for the system would be:

  1. Navigate to page URL endpoint, for example “/1”
  2. Use endpoint as a key (in this case “1”) to lookup the actual page content starting address in SDRAM
  3. Use endpoint as key to lookup the size of the page content in ROM
  4. Transfer page content from SDRAM into block RAM and transmit

Dealing with memories

The SDRAM controller is a dual port interface to a single port memory, and provides grant signals to indicate that the request has been latched into the state machine. The addressing width is according to what the hardware expects, 11 bit row and 8 bit column. One other detail is the tristate nature of sdram_dq. Luckily yosys seems to support this alright, otherwise, one might need to manually instantiate the tristate buffer primitives BB.

module sdram_ctrl #(
    parameter int FREQ = 125_000_000
) (
    input clk,
    input rst,

    input wr_req,
    // 18:8 is the row address, 7:0 is column address
    input [18:0] wr_ad,
    input [31:0] wr_data,
    output reg wr_granted,

    input rd_req,
    input [18:0] rd_ad,
    output reg rd_valid,
    output reg [31:0] rd_data,
    output reg rd_granted,
    // Boot complete signal. 1: boot done
    output reg boot_done,

    output reg [1:0] sdram_ba,
    output reg sdram_we_n,
    output reg sdram_cas_n,
    output reg sdram_ras_n,
    output wire sdram_clk,
    inout [31:0] sdram_dq,
    output reg [10:0] sdram_addr
);

The actual controller is mostly an exercise in scouring the datasheet. For the uninitiated, DRAM holds data bits in lines of capacitors which need to be periodically refreshed to maintain their charge. The basic commands available to the external controllers are PRECHARGE, AUTOREFRESH, ACTIVATE, READ and WRITE. The DRAM module we are working on also supports additional features like BURST READ and BURST WRITE but we can ignore that for now. For a read or write operation starting from a blank slate, one should issue PRECHARGE to clear the row buffer, ACTIVATE to select the bank and row that we want, then read or write with the column address. A refresh must also be issued for each row at least every 64ms. One additional complication is the start up sequence, which on our module requires us to send PRECHARGE, MRS, 2x AUTOREFRESH. The MRS (mode register set) is the way to configure parameters like the CAS latency, which is the number of cycles after a read command where the data output is ready. Working at this signalling level provided a new kind of joy once the data from a write operation successfully appeared on the UART terminal after a read command.

I designed an initialization module that would pull all the pages into SDRAM once reset is released and the SDRAM initialization is complete. (Since SDRAM is only 2MB, and I only use 1 bank for now, the total memory limitation must be under 512KB).

You can check out the entire controller here.

One challenge when designing all this is meeting timing @ 125 mhz. The clk-to-q delay for reads is already around 5.8ns. Hence, any logic using these read values should be registered. Unfortunately, my first attempt did not synthesize to a registered output.

always @(posedge clk) begin
data <= mem[addr];
match <= data == tag; // seemed to fold into mem[addr] == tag
end

Using (*keep*) or (*dont_touch*) attributes on the registers also did not seem to work. Adding a pipelined register manually also did not seem to break up the path. What worked in the end is to manually instantiate the DP16KD/PDPW16KD primitives, with the OUTREG REGMODE parameter. Luckily, this parameter is supported by the downstream tools, updating clk-to-q to 0.5ns. There were also other frustrations. OCER, are the clock enables for those output registers and should be tied accordingly for OUTREG to work. I also wanted to support asymmetric read and write widths such as for streaming quickly at 32 bits/cycle but then reading narrower at 8bits/cycle for transmitting. The primitives also support this natively, but care is needed to make sure the output and input port connections are correct. It took a while, but making use of the native Lattice IPExpress tool to generate the port connections allowed me to figure out what went wrong. An example below:

PDPW16KD #(
  .REGMODE(REGMODE),
  .DATA_WIDTH_R(EBR_WIDTH_B),
  .DATA_WIDTH_W(EBR_WIDTH_A)
) ebr (
  .DI0  (dia[0]),
  .DI1  (dia[1]),
  .DI2  (dia[2]),
  .DI3  (dia[3]),
  .DI4  (dia[4]),
  .DI5  (dia[5]),
  .DI6  (dia[6]),
  .DI7  (dia[7]),
  .DI8  ('0),    // this killed me
  .DI9  (dia[8]),
  //...
  .DI17 ('0),   // why didnt i check the tool earlier
  .DI18 (dia[16]),
  //...
  .DI26 ('0),
  //...
  .DI35 ('0),

HTTP 1.0 is a friend when lacking hardware

With that, opening the IP and port on a browser is able to display the endpoint properly. However, as it currently is, refreshing the page will cause the page to load for a long time. This is because in HTTP 1.1, browsers make use of a persistent keep-alive TCP connection to avoid needing to restart the 3-way handshake, and do not automatically terminate after each request (by sending FIN). Instead, a new TCP connection is created and often, parallel connections are started to avoid head of line blocking for multiple resources. For e.g. even though my site does not specify any favicon, a get request for it is made from Chrome browsers. In HTTP 2, browsers will make use of 1 TCP connection, and multiplex streams on the HTTP layer with a stream ID. However, since we are on very limited hardware, we would prefer if every request is terminated swiftly, so that someone else might reach the FPGA.

Introducing HTTP 1.0! Responding with that in the header would cause the browser to send a FIN immediately once it receives a response. Even if it does not, I designed each TCB to transition to the TCP FIN-WAIT state once it has transmitted the payload to aggressively close any connections. Hence, the main way that clients can hog the TCB is if no request is made, or a request that is not HTTP is made. An idle timer is introduced to transition the connection to FIN in these cases. This is all very bad for performance reasons, but is a trade off for working with multiple clients with only a few TCBs.

Speaking of Performance…

Let’s do a little performance characterization. In simulation, I used a dummy SDRAM which simply places data directly in registers and raises the valid data after 1 cycle of latency. This helps to reduce simulation time but is of course not really representing the delays that come with reading directly from memory. Here is the waveform, which shows the time delay from an incoming HTTP request to the complete outgoing HTTP response being roughly 20us.

Simulation waveform measurement with in GTKWave

We can also measure the delay from the first TCP SYN till the complete handshake, which only takes roughly 2.1us. This is our minimum latency since this is not dependent on any memory.

On wireshark with the real device, we can see the end-to-end latency going from user space to the FPGA and back into the application. For this connection, the handshake completes in 64us, while the first part of the HTTP response comes in 100us after the GET request.

Wireshark capture of end-to-end HTTP request

This is only 1 connection. A better method is to use a benchmark tool in order to stress test the device and collect statistics. One such tool is called Apache Benchmark (ab), which has been augmented by researchers at ETH Zurich to provide latency numbers in microseconds. This is a good place to point out some existing work on FPGA-based HTTP servers by the same researchers on their project called Strega. Strega makes use of their own TCP/IP kernel layered on with a HTTP engine written in a higher level synthesis language. Admittedly, I did not read much into their implementation as I am still a long way from understanding HLS. You can read more from their paper and even their source code here .

> ~/Downloads/apachebench/ab -n 100 -c 1 http://105.105.105.105:8080/1
This is ApacheBench, Version 2.3 <$Revision$>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://web.archive.org/web/20000304112933/http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking 105.105.105.105 (be patient).....done

Number of workers:      1
Concurrency Level:      1
Concurrency achieved:   1
Rampup delay:           0 [ms]
Time taken for tests:   2.318 seconds
Complete requests:      4000
Failed requests:        0
Non-2xx responses:      4000
Total transferred:      2640000 bytes
HTML transferred:       2452000 bytes
Requests per second:    1725.43 [#/sec] (mean)
Time per request:       0.580 [ms] (mean)
Time per request:       0.580 [ms] (mean, across all concurrent requests)
Transfer rate:          1112.09 [Kbytes/sec] received

Connection Times (us)
              min  mean[+/-sd] median   max
Connect:       47  319 16037.7     68 1014376
Processing:   107  235 4583.5    135  207175
Waiting:       26  188 4582.7     83  207093
Total:        155  555 16679.4    207 1014593

Percentage of the requests served within a certain time (us)
  50%    207
  66%    212
  75%    217
  80%    220
  90%    235
  95%    257
  98%    294
  99%    345
 100%  1014593 (longest request)

The results are for 4000 requests accessing the endpoint “/1”, which for this test is configured to point at the not found page. Also note the lack of concurrency (“-c 1”) as I have yet to fully test arbitration logic.

Immediately, what stands out are the max values. These are clear indicators of some bugs that will need further investigation. I shall leave that for a future write-up. This is also just the happy path, we can use Traffic Controller tc to create some artificial conditions like loss and reordering.

> sudo tc qdisc add dev enp61s0 root netem delay 20ms loss 10% reorder 10%

> ~/Downloads/apachebench/ab -n 4000 -c 1 http://105.105.105.105:8080/1
Number of workers:      1
Concurrency Level:      1
Concurrency achieved:   1
Rampup delay:           0 [ms]
Time taken for tests:   1031.066 seconds
Complete requests:      1606
Failed requests:        1
   (Connect: 0, Receive: 0, Length: 1, Exceptions: 0)
Non-2xx responses:      1605
Total transferred:      1059960 bytes
HTML transferred:       983865 bytes
Requests per second:    1.56 [#/sec] (mean)
Time per request:       642.009 [ms] (mean)
Time per request:       642.009 [ms] (mean, across all concurrent requests)
Transfer rate:          1.00 [Kbytes/sec] received

Connection Times (us)
              min  mean[+/-sd] median   max
Connect:       93 444779 971424.9  20185 15364006
Processing:   177 196554 744315.5  20277 9407976
Waiting:      101 196471 744315.2  20192 9407872
Total:        390 641334 1305493.8  40619 16383897

Percentage of the requests served within a certain time (us)
  50%  40619
  66%  267901
  75%  1047442
  80%  1055932
  90%  1259805
  95%  3071986
  98%  4227319
  99%  7160231
 100%  16383897 (longest request)

The main metric here is not latency, we just want to make sure that the device does not get stuck indefinitely. However, only 1605 requests completed and then timed out. The only upside here is that due to the idle timeout, a new request goes through OK.

For now at least, I feel semi confident to allow public traffic on this thing.

This post has been served to you by an FPGA!

There are a few layers of reverse proxying of course, but the text itself is all coming from the Colorlight in my home. In case it goes down and this page is hosted elsewhere, the link to the one from the FPGA is https://fpgablog.com. Here is the current setup, complete with a 5V PoE splitter from my switch to reduce clutter.

Setup using 5V PoE splitter

I would like to re-highlight the limitations of the implementation as it currently stands. A lot of the complexity has been moved elsewhere or ignored for the time being but I definitely have plans to add them.

In the process I learnt and implemented, UART controller (TX only), SPI master flash controller, SDRAM controller, RGMII MAC @ 125mhz, L2 & L3 Packet decoder / encoders, did basic timing closure and simulation.

All of this is possible only due to the important work on yosys, nextpnr, Project Trellis, verilator, cocotb, and gtkwave. This amazing ecosystem has allowed stupid projects like this one to come to an FPGA near you.

Source code: https://github.com/bbawj/fpga-web