aboutsummaryrefslogtreecommitdiff
path: root/verilog_constants.h
blob: 1b00b96dcabe1efb0ba2ba0bd31987f0422a14fb (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
/*
 * verilog_constants.h
 * -------------------
 * Magic constants which must match Verilog code, mostly bus addresses.
 *
 * In the long run, this should be generated by a script which pulls
 * these numbers out of the Verilog source code.  For the moment, it's
 * hand-edited.
 *
 * Authors: Joachim Strombergson, Paul Selkirk, Rob Austein
 * Copyright (c) 2015-2017, NORDUnet A/S All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 * - Redistributions of source code must retain the above copyright notice,
 *   this list of conditions and the following disclaimer.
 *
 * - Redistributions in binary form must reproduce the above copyright
 *   notice, this list of conditions and the following disclaimer in the
 *   documentation and/or other materials provided with the distribution.
 *
 * - Neither the name of the NORDUnet nor the names of its contributors may
 *   be used to endorse or promote products derived from this software
 *   without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
 * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#ifndef _VERILOG_CONSTANTS_H_
#define _VERILOG_CONSTANTS_H_

/*
 * Common to all cores.
 */
#define ADDR_NAME0              (0x00)
#define ADDR_NAME1              (0x01)
#define ADDR_VERSION            (0x02)
#define ADDR_CTRL               (0x08)
#define CTRL_INIT               (1)
#define CTRL_NEXT               (2)
#define ADDR_STATUS             (0x09)
#define STATUS_READY            (1)
#define STATUS_VALID            (2)

/*
 * Hash cores.
 */

#define SHA1_ADDR_BLOCK         (0x10)
#define SHA1_ADDR_DIGEST        (0x20)
#define SHA1_BLOCK_LEN          bitsToBytes(512)
#define SHA1_LENGTH_LEN         bitsToBytes(64)
#define SHA1_DIGEST_LEN         bitsToBytes(160)

#define SHA256_ADDR_BLOCK       (0x10)
#define SHA256_ADDR_DIGEST      (0x20)
#define SHA256_BLOCK_LEN        bitsToBytes(512)
#define SHA256_LENGTH_LEN       bitsToBytes(64)
#define SHA224_DIGEST_LEN       bitsToBytes(224)
#define SHA256_DIGEST_LEN       bitsToBytes(256)
#define SHA256_MODE_SHA_224     (0 << 2)
#define SHA256_MODE_SHA_256     (1 << 2)
#define SHA256_MODE_MASK        (1 << 2)

#define SHA512_ADDR_BLOCK       (0x10)
#define SHA512_ADDR_DIGEST      (0x40)
#define SHA512_BLOCK_LEN        bitsToBytes(1024)
#define SHA512_LENGTH_LEN       bitsToBytes(128)
#define SHA512_224_DIGEST_LEN   bitsToBytes(224)
#define SHA512_256_DIGEST_LEN   bitsToBytes(256)
#define SHA384_DIGEST_LEN       bitsToBytes(384)
#define SHA512_DIGEST_LEN       bitsToBytes(512)
#define SHA512_MODE_SHA_512_224 (0 << 2)
#define SHA512_MODE_SHA_512_256 (1 << 2)
#define SHA512_MODE_SHA_384     (2 << 2)
#define SHA512_MODE_SHA_512     (3 << 2)
#define SHA512_MODE_MASK        (3 << 2)

/*
 * RNG cores.
 */

#define TRNG_CTRL_DISCARD       (1)
#define TRNG_CTRL_TEST_MODE     (2)
/* No status bits defined (yet) */
#define TRNG_ADDR_DELAY         (0x13)

#define ENTROPY1_CTRL_ENABLE    (1)
#define ENTROPY1_STATUS_VALID   (2)
#define ENTROPY1_ADDR_ENTROPY   (0x20)
#define ENTROPY1_ADDR_DELTA     (0x30)

#define ENTROPY2_CTRL_ENABLE    (1)
#define ENTROPY2_STATUS_VALID   (2)
#define ENTROPY2_ADDR_OPA       (0x18)
#define ENTROPY2_ADDR_OPB       (0x19)
#define ENTROPY2_ADDR_ENTROPY   (0x20)
#define ENTROPY2_ADDR_RAW       (0x21)
#define ENTROPY2_ADDR_ROSC      (0x22)

#define MIXER_CTRL_ENABLE       (1)
#define MIXER_CTRL_RESTART      (2)
/* No status bits defined (yet) */
#define MIXER_ADDR_TIMEOUT      (0x20)

#define CSPRNG_CTRL_ENABLE      (1)
#define CSPRNG_CTRL_SEED        (2)
#define CSPRNG_STATUS_VALID     (2)
#define CSPRNG_ADDR_RANDOM      (0x20)
#define CSPRNG_ADDR_NROUNDS     (0x40)
#define CSPRNG_ADDR_NBLOCKS_LO  (0x41)
#define CSPRNG_ADDR_NBLOCKS_HI  (0x42)

/*
 * Cipher cores.
 */

#define AES_ADDR_CONFIG         (0x0a)
#define AES_CONFIG_ENCDEC       (1)
#define AES_CONFIG_KEYLEN       (2)

#define AES_ADDR_KEY0           (0x10)
#define AES_ADDR_KEY1           (0x11)
#define AES_ADDR_KEY2           (0x12)
#define AES_ADDR_KEY3           (0x13)
#define AES_ADDR_KEY4           (0x14)
#define AES_ADDR_KEY5           (0x15)
#define AES_ADDR_KEY6           (0x16)
#define AES_ADDR_KEY7           (0x17)

#define AES_ADDR_BLOCK0         (0x20)
#define AES_ADDR_BLOCK1         (0x21)
#define AES_ADDR_BLOCK2         (0x22)
#define AES_ADDR_BLOCK3         (0x23)

#define AES_ADDR_RESULT0        (0x30)
#define AES_ADDR_RESULT1        (0x31)
#define AES_ADDR_RESULT2        (0x32)
#define AES_ADDR_RESULT3        (0x33)

/* Chacha core */

#define CHACHA_ADDR_KEYLEN      (0x0a)
#define CHACHA_KEYLEN           (1)

#define CHACHA_ADDR_ROUNDS      (0x0b)

#define CHACHA_ADDR_KEY0        (0x10)
#define CHACHA_ADDR_KEY1        (0x11)
#define CHACHA_ADDR_KEY2        (0x12)
#define CHACHA_ADDR_KEY3        (0x13)
#define CHACHA_ADDR_KEY4        (0x14)
#define CHACHA_ADDR_KEY5        (0x15)
#define CHACHA_ADDR_KEY6        (0x16)
#define CHACHA_ADDR_KEY7        (0x17)

#define CHACHA_ADDR_IV0         (0x20)
#define CHACHA_ADDR_IV1         (0x21)

#define CHACHA_ADDR_DATA_IN0    (0x40)
#define CHACHA_ADDR_DATA_IN1    (0x41)
#define CHACHA_ADDR_DATA_IN2    (0x42)
#define CHACHA_ADDR_DATA_IN3    (0x43)
#define CHACHA_ADDR_DATA_IN4    (0x44)
#define CHACHA_ADDR_DATA_IN5    (0x45)
#define CHACHA_ADDR_DATA_IN6    (0x46)
#define CHACHA_ADDR_DATA_IN7    (0x47)
#define CHACHA_ADDR_DATA_IN8    (0x48)
#define CHACHA_ADDR_DATA_IN9    (0x49)
#define CHACHA_ADDR_DATA_IN10   (0x4a)
#define CHACHA_ADDR_DATA_IN11   (0x4b)
#define CHACHA_ADDR_DATA_IN12   (0x4c)
#define CHACHA_ADDR_DATA_IN13   (0x4d)
#define CHACHA_ADDR_DATA_IN14   (0x4e)
#define CHACHA_ADDR_DATA_IN15   (0x4f)

#define CHACHA_ADDR_DATA_OUT0   (0x80)
#define CHACHA_ADDR_DATA_OUT1   (0x81)
#define CHACHA_ADDR_DATA_OUT2   (0x82)
#define CHACHA_ADDR_DATA_OUT3   (0x83)
#define CHACHA_ADDR_DATA_OUT4   (0x84)
#define CHACHA_ADDR_DATA_OUT5   (0x85)
#define CHACHA_ADDR_DATA_OUT6   (0x86)
#define CHACHA_ADDR_DATA_OUT7   (0x87)
#define CHACHA_ADDR_DATA_OUT8   (0x88)
#define CHACHA_ADDR_DATA_OUT9   (0x89)
#define CHACHA_ADDR_DATA_OUT10  (0x8a)
#define CHACHA_ADDR_DATA_OUT11  (0x8b)
#define CHACHA_ADDR_DATA_OUT12  (0x8c)
#define CHACHA_ADDR_DATA_OUT13  (0x8d)
#define CHACHA_ADDR_DATA_OUT14  (0x8e)
#define CHACHA_ADDR_DATA_OUT15  (0x8f)

/*
 * Math cores.
 */

/*
 * ModExpS6 core.  MODEXPS6_OPERAND_BITS is size in bits of largest
 * supported modulus.
 */

#define MODEXPS6_OPERAND_BITS           (4096)
#define MODEXPS6_OPERAND_WORDS          (MODEXPS6_OPERAND_BITS / 32)
#define MODEXPS6_ADDR_REGISTERS         (0 * MODEXPS6_OPERAND_WORDS)
#define MODEXPS6_ADDR_OPERANDS          (4 * MODEXPS6_OPERAND_WORDS)
#define MODEXPS6_ADDR_MODE              (MODEXPS6_ADDR_REGISTERS + 0x10)
#define MODEXPS6_ADDR_MODULUS_WIDTH     (MODEXPS6_ADDR_REGISTERS + 0x11)
#define MODEXPS6_ADDR_EXPONENT_WIDTH    (MODEXPS6_ADDR_REGISTERS + 0x12)
#define MODEXPS6_ADDR_MODULUS           (MODEXPS6_ADDR_OPERANDS + 0 * MODEXPS6_OPERAND_WORDS)
#define MODEXPS6_ADDR_MESSAGE           (MODEXPS6_ADDR_OPERANDS + 1 * MODEXPS6_OPERAND_WORDS)
#define MODEXPS6_ADDR_EXPONENT          (MODEXPS6_ADDR_OPERANDS + 2 * MODEXPS6_OPERAND_WORDS)
#define MODEXPS6_ADDR_RESULT            (MODEXPS6_ADDR_OPERANDS + 3 * MODEXPS6_OPERAND_WORDS)
#define MODEXPS6_MODE_CONSTANT_TIME	(0)
#define MODEXPS6_MODE_FAST_PUBLIC	(1)

/*
 * ModExpA7 core.  MODEXPA7_OPERAND_BITS is size in bits of largest
 * supported modulus.
 *
 * I prefer the way Pavel wrote the constants for this in his sample
 * code to what I've done here, but let's get the thing working before
 * worrying about the yaks' pedicures.
 */

#define MODEXPA7_OPERAND_BITS                   (4096)
#define MODEXPA7_OPERAND_BYTES                  (MODEXPA7_OPERAND_BITS /  8)
#define MODEXPA7_OPERAND_WORDS                  (MODEXPA7_OPERAND_BITS / 32)
#define MODEXPA7_ADDR_REGISTERS                 (0 * MODEXPA7_OPERAND_WORDS)
#define MODEXPA7_ADDR_OPERANDS                  (8 * MODEXPA7_OPERAND_WORDS)
#define MODEXPA7_ADDR_MODE                      (MODEXPA7_ADDR_REGISTERS + 0x10)
#define MODEXPA7_ADDR_MODULUS_BITS              (MODEXPA7_ADDR_REGISTERS + 0x11)
#define MODEXPA7_ADDR_EXPONENT_BITS             (MODEXPA7_ADDR_REGISTERS + 0x12)
#define MODEXPA7_ADDR_BUFFER_BITS               (MODEXPA7_ADDR_REGISTERS + 0x13)
#define MODEXPA7_ADDR_ARRAY_BITS                (MODEXPA7_ADDR_REGISTERS + 0x14)
#define MODEXPA7_ADDR_MODULUS                   (MODEXPA7_ADDR_OPERANDS + 0 * MODEXPA7_OPERAND_WORDS)
#define MODEXPA7_ADDR_MESSAGE                   (MODEXPA7_ADDR_OPERANDS + 1 * MODEXPA7_OPERAND_WORDS)
#define MODEXPA7_ADDR_EXPONENT                  (MODEXPA7_ADDR_OPERANDS + 2 * MODEXPA7_OPERAND_WORDS)
#define MODEXPA7_ADDR_RESULT                    (MODEXPA7_ADDR_OPERANDS + 3 * MODEXPA7_OPERAND_WORDS)
#define MODEXPA7_ADDR_MODULUS_COEFF_OUT         (MODEXPA7_ADDR_OPERANDS + 4 * MODEXPA7_OPERAND_WORDS)
#define MODEXPA7_ADDR_MODULUS_COEFF_IN          (MODEXPA7_ADDR_OPERANDS + 5 * MODEXPA7_OPERAND_WORDS)
#define MODEXPA7_ADDR_MONTGOMERY_FACTOR_OUT     (MODEXPA7_ADDR_OPERANDS + 6 * MODEXPA7_OPERAND_WORDS)
#define MODEXPA7_ADDR_MONTGOMERY_FACTOR_IN      (MODEXPA7_ADDR_OPERANDS + 7 * MODEXPA7_OPERAND_WORDS)
#define MODEXPA7_MODE_CRT                       (1 << 1)
#define MODEXPA7_MODE_PLAIN                     (0 << 1)

/*
 * ECDSA P-256 point multiplier core.  ECDSA256_OPERAND_BITS is size
 * in bits of the (only) supported operand size (256 bits, imagine that).
 *
 * (Not sure which category EC Point Mulitiplier will end up in, but
 * let's pretend it's "math".)
 */

#define ECDSA256_OPERAND_BITS           (256)
#define ECDSA256_ADDR_REGISTERS         (0x00)
#define ECDSA256_ADDR_K                 (0x20)
#define ECDSA256_ADDR_X                 (0x28)
#define ECDSA256_ADDR_Y                 (0x30)

/*
 * ECDSA P-384 point multiplier core.  ECDSA384_OPERAND_BITS is size
 * in bits of the (only) supported operand size (384 bits, imagine that).
 *
 * (Not sure which category EC Point Mulitiplier will end up in, but
 * let's pretend it's "math".)
 */

#define ECDSA384_OPERAND_BITS           (384)
#define ECDSA384_ADDR_REGISTERS         (0x00)
#define ECDSA384_ADDR_K                 (0x40)
#define ECDSA384_ADDR_X                 (0x50)
#define ECDSA384_ADDR_Y                 (0x60)

/*
 * Utility cores.
 */

/*
 * Master Key Memory Interface core.
 */
#define MKMIF_ADDR_CTRL         ADDR_CTRL
#define MKMIF_CTRL_CMD_READ     (0x01)
#define MKMIF_CTRL_CMD_WRITE    (0x02)
#define MKMIF_CTRL_CMD_INIT     (0x04)
#define MKMIF_ADDR_SCLK_DIV     (0x0a)
#define MKMIF_ADDR_EMEM_ADDR    (0x10)
#define MKMIF_ADDR_EMEM_DATA    (0x20)

#endif /* _VERILOG_CONSTANTS_H_ */

/*
 * Local variables:
 * indent-tabs-mode: nil
 * End:
 */

                                                            
                                                         

                            



                               


                                        



















                                                                            
 
/*
 * rpc_server.c
 * ------------
 * Remote procedure call server-side private API implementation.
 *
 * Copyright (c) 2016, NORDUnet A/S All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 * - Redistributions of source code must retain the above copyright notice,
 *   this list of conditions and the following disclaimer.
 *
 * - Redistributions in binary form must reproduce the above copyright
 *   notice, this list of conditions and the following disclaimer in the
 *   documentation and/or other materials provided with the distribution.
 *
 * - Neither the name of the NORDUnet nor the names of its contributors may
 *   be used to endorse or promote products derived from this software
 *   without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
 * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/*
 * This is the main RPC server moddule. It creates a new thread to deal
 * with each request, to prevent a long-running request (e.g. RSA keygen)
 * from blocking independent requests from other clients. This has a
 * number of consequences. We can't do a blocking receive in the main
 * thread, because that prevents the dispatch thread from transmitting the
 * response (because they both want to lock the UART - see
 * stm32f4xx_hal_uart.c). So we have to do a non-blocking receive with a
 * callback routine. But we can't create a thread from the callback
 * routine, because it's in the context of an ISR, so we raise a semaphore
 * for the main thread to create the dispatch thread.
 */

#include "cmsis_os.h"

#include "stm-init.h"
#include "stm-led.h"
#include "stm-fmc.h"
#include "stm-uart.h"

/* stm32f4xx_hal_def.h and hal.h both define HAL_OK as an enum value */
#define HAL_OK HAL_OKAY

#include "hal.h"
#include "hal_internal.h"	/* hal_rpc_sendto, hal_rpc_recvfrom */
#include "xdr_internal.h"	/* hal_xdr_encode_int */

/* RPC buffers. For each active RPC, there will be two - input and output.
 */

#ifndef NUM_RPC_BUFFER
/* An arbitrary number, but we don't expect to have more than 8 concurrent
 * RPC requests.
 */
#define NUM_RPC_BUFFER 16
#endif

#ifndef MAX_PKT_SIZE
/* Another arbitrary number, more or less driven by the 4096-bit RSA
 * keygen test.
 */
#define MAX_PKT_SIZE 4096
#endif

/* The thread entry point takes a single void* argument, so we bundle the
 * packet buffer and length arguments together.
 */
typedef struct {
    size_t len;
    uint8_t buf[MAX_PKT_SIZE];
} rpc_buffer_t;

osPoolDef(rpc_buffer_pool, NUM_RPC_BUFFER, rpc_buffer_t);
osPoolId  rpc_buffer_pool;

static rpc_buffer_t *rpc_buffer_alloc(void)
{
    return (rpc_buffer_t *)osPoolCAlloc(rpc_buffer_pool);
}

/* A mutex to arbitrate concurrent UART transmits, from RPC responses.
 */
osMutexId  uart_mutex;
osMutexDef(uart_mutex);

/* Borrowed from xdr.c. We know the target architecture is little-endian,
 * but we pretend for the sake of appearances.
 */
#ifdef __ARMEL__                /* little endian */
static inline uint32_t htonl(uint32_t w)
{
  return
    ((w & 0x000000ff) << 24) +
    ((w & 0x0000ff00) << 8) +
    ((w & 0x00ff0000) >> 8) +
    ((w & 0xff000000) >> 24);
}
#else
#define htonl(x) (x)
#endif

/* Thread entry point for the RPC request handler.
 */
static void dispatch_thread(void const *args)
{
    rpc_buffer_t *ibuf = (rpc_buffer_t *)args;
    rpc_buffer_t *obuf = rpc_buffer_alloc();
    if (obuf == NULL) {
        uint32_t err = htonl(HAL_ERROR_ALLOCATION_FAILURE);
        osMutexWait(uart_mutex, osWaitForever);
        hal_rpc_sendto((uint8_t *)&err, 4, NULL);
        osMutexRelease(uart_mutex);
        osPoolFree(rpc_buffer_pool, ibuf);
        Error_Handler();
    }
    obuf->len = sizeof(obuf->buf);
    hal_rpc_server_dispatch(ibuf->buf, ibuf->len, obuf->buf, &obuf->len);
    osPoolFree(rpc_buffer_pool, ibuf);
    osMutexWait(uart_mutex, osWaitForever);
    hal_error_t ret = hal_rpc_sendto(obuf->buf, obuf->len, NULL);
    osMutexRelease(uart_mutex);
    osPoolFree(rpc_buffer_pool, obuf);
    if (ret != HAL_OK)
        Error_Handler();
}
osThreadDef(dispatch_thread, osPriorityNormal, DEFAULT_STACK_SIZE);

/* Semaphore to inform the main thread that there's a new RPC request.
 */
osSemaphoreId rpc_sem;
osSemaphoreDef(rpc_sem);

static uint8_t c;		/* current character received from UART */
static rpc_buffer_t *ibuf;	/* current RPC input buffer */

/* Add a byte to the input buffer.
 */
static inline void ibuf_push(uint8_t c) {
    if (ibuf->len < MAX_PKT_SIZE)
        ibuf->buf[ibuf->len++] = c;
}

/* Callback for HAL_UART_Receive_IT().
 */
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
/* SLIP special characters */
#define END             0300    /* indicates end of packet */
#define ESC             0333    /* indicates byte stuffing */
#define ESC_END         0334    /* ESC ESC_END means END data byte */
#define ESC_ESC         0335    /* ESC ESC_ESC means ESC data byte */

    static int esc_flag = 0;	/* previous char was ESC */

    /* got 1 char - un-SLIP it */
    switch (c) {
    case END:
        if (ibuf->len)
            osSemaphoreRelease(rpc_sem);
        break;
    case ESC:
        esc_flag = 1;
        break;
    default:
        if (esc_flag) {
            esc_flag = 0;
            switch (c) {
            case ESC_END:
                ibuf_push(END);
                break;
            case ESC_ESC:
                ibuf_push(ESC);
                break;
            default:
                ibuf_push(c);
            }
        }
        else {
            ibuf_push(c);
        }
        break;
    }

    HAL_UART_Receive_IT(huart, &c, 1);
}

/* UART interrupt handler. This eventually calls HAL_UART_RxCpltCallback.
 */
void USART2_IRQHandler(void)
{
    HAL_UART_IRQHandler(&huart2);
}

/* The main thread. After the system setup, it waits for the RPC-request
 * semaphore from HAL_UART_RxCpltCallback, and spawns a dispatch thread.
 */
int main()
{
    stm_init();

#ifdef TARGET_CRYPTECH_DEV_BRIDGE
    /* Wait six seconds to not upset the Novena at boot. */
    led_on(LED_BLUE);
    for (int i = 0; i < 12; i++) {
	osDelay(500);
	led_toggle(LED_BLUE);
    }
    led_off(LED_BLUE);
    led_on(LED_GREEN);
#endif
    /* Prepare FMC interface. */
    fmc_init();

    /* Haaaack. probe_cores() calls malloc(), which works from the main
     * thread, but not from a spawned thread. It would be better to
     * rewrite it to use static memory, but for now, just force it to
     * probe early.
     */
    hal_core_iterate(NULL);

    rpc_buffer_pool = osPoolCreate(osPool(rpc_buffer_pool));
    uart_mutex = osMutexCreate(osMutex(uart_mutex));
    rpc_sem = osSemaphoreCreate(osSemaphore(rpc_sem), 0);

#ifdef TARGET_CRYPTECH_ALPHA
    /* Launch other threads:
     * - admin thread on USART1
     * - csprng warm-up thread?
     */
#endif

    if (hal_rpc_server_init() != HAL_OK)
	Error_Handler();

    ibuf = rpc_buffer_alloc();
    if (ibuf == NULL)
        /* Something is badly wrong. */
        Error_Handler();

    /* Start the non-blocking receive */
    HAL_UART_Receive_IT(&huart2, &c, 1);

    while (1) {
        osSemaphoreWait(rpc_sem, osWaitForever);
        if (osThreadCreate(osThread(dispatch_thread), (void *)ibuf) == NULL)
            Error_Handler();
        while ((ibuf = rpc_buffer_alloc()) == NULL);
        /* XXX There's a potential race condition, where another request
         * could write into the old ibuf, or into the null pointer if
         * we're out of ibufs.
         */
    }
}