OpenCores
URL https://opencores.org/ocsvn/neorv32/neorv32/trunk

Subversion Repositories neorv32

[/] [neorv32/] [trunk/] [sw/] [bootloader/] [bootloader.c] - Blame information for rev 58

Go to most recent revision | Details | Compare with Previous | View Log

Line No. Rev Author Line
1 2 zero_gravi
// #################################################################################################
2
// # << NEORV32 - Bootloader >>                                                                    #
3
// # ********************************************************************************************* #
4 55 zero_gravi
// # In order to run the bootloader on *any* CPU configuration, the bootloader should be compiled  #
5 33 zero_gravi
// # unsing the base ISA (rv32i/rv32e) only.                                                       #
6 2 zero_gravi
// # ********************************************************************************************* #
7
// # Boot from (internal) instruction memory, UART or SPI Flash.                                   #
8
// #                                                                                               #
9 50 zero_gravi
// # The bootloader uses the primary UART (UART0) for user console interface.                      #
10
// #                                                                                               #
11 42 zero_gravi
// # UART configuration: 8 data bits, NO parity bit, 1 stop bit, 19200 baud (19200-8N1)            #
12 2 zero_gravi
// # Boot Flash: 8-bit SPI, 24-bit addresses (like Micron N25Q032A) @ neorv32.spi_csn_o(0)         #
13 33 zero_gravi
// # neorv32.gpio_o(0) is used as high-active status LED (can be disabled via #STATUS_LED_EN).     #
14 2 zero_gravi
// #                                                                                               #
15 33 zero_gravi
// # Auto boot sequence (can be disabled via #AUTOBOOT_EN) after timeout (via #AUTOBOOT_TIMEOUT):  #
16 2 zero_gravi
// #  -> Try booting from SPI flash at spi_csn_o(0).                                               #
17 33 zero_gravi
// #  -> Permanently light up status led and stall CPU if SPI flash booting attempt fails.         #
18 2 zero_gravi
// # ********************************************************************************************* #
19
// # BSD 3-Clause License                                                                          #
20
// #                                                                                               #
21 55 zero_gravi
// # Copyright (c) 2021, Stephan Nolting. All rights reserved.                                     #
22 2 zero_gravi
// #                                                                                               #
23
// # Redistribution and use in source and binary forms, with or without modification, are          #
24
// # permitted provided that the following conditions are met:                                     #
25
// #                                                                                               #
26
// # 1. Redistributions of source code must retain the above copyright notice, this list of        #
27
// #    conditions and the following disclaimer.                                                   #
28
// #                                                                                               #
29
// # 2. Redistributions in binary form must reproduce the above copyright notice, this list of     #
30
// #    conditions and the following disclaimer in the documentation and/or other materials        #
31
// #    provided with the distribution.                                                            #
32
// #                                                                                               #
33
// # 3. Neither the name of the copyright holder nor the names of its contributors may be used to  #
34
// #    endorse or promote products derived from this software without specific prior written      #
35
// #    permission.                                                                                #
36
// #                                                                                               #
37
// # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS   #
38
// # OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF               #
39
// # MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE    #
40
// # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,     #
41
// # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE #
42
// # GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED    #
43
// # AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING     #
44
// # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED  #
45
// # OF THE POSSIBILITY OF SUCH DAMAGE.                                                            #
46
// # ********************************************************************************************* #
47
// # The NEORV32 Processor - https://github.com/stnolting/neorv32              (c) Stephan Nolting #
48
// #################################################################################################
49
 
50
 
51
/**********************************************************************//**
52
 * @file bootloader.c
53
 * @author Stephan Nolting
54 33 zero_gravi
 * @brief Default NEORV32 bootloader.
55 2 zero_gravi
 **************************************************************************/
56
 
57
// Libraries
58
#include <stdint.h>
59
#include <neorv32.h>
60
 
61
 
62
/**********************************************************************//**
63
 * @name User configuration
64
 **************************************************************************/
65
/**@{*/
66
/** UART BAUD rate */
67
#define BAUD_RATE              (19200)
68 33 zero_gravi
/** Enable auto-boot sequence if != 0 */
69
#define AUTOBOOT_EN            (1)
70 2 zero_gravi
/** Time until the auto-boot sequence starts (in seconds) */
71 56 zero_gravi
#define AUTOBOOT_TIMEOUT       (8)
72 22 zero_gravi
/** Set to 0 to disable bootloader status LED */
73
#define STATUS_LED_EN          (1)
74 56 zero_gravi
/** Set to 1 to enable SPI direct boot (disables the entire user console!) */
75
#define SPI_DIRECT_BOOT_EN     (0)
76 22 zero_gravi
/** Bootloader status LED at GPIO output port */
77 2 zero_gravi
#define STATUS_LED             (0)
78 33 zero_gravi
/** SPI flash boot image base address (warning! address might wrap-around!) */
79 11 zero_gravi
#define SPI_FLASH_BOOT_ADR     (0x00800000)
80 33 zero_gravi
/** SPI flash chip select line at spi_csn_o */
81 2 zero_gravi
#define SPI_FLASH_CS           (0)
82 33 zero_gravi
/** Default SPI flash clock prescaler */
83 2 zero_gravi
#define SPI_FLASH_CLK_PRSC     (CLK_PRSC_8)
84 33 zero_gravi
/** SPI flash sector size in bytes (default = 64kb) */
85 2 zero_gravi
#define SPI_FLASH_SECTOR_SIZE  (64*1024)
86 34 zero_gravi
/** ASCII char to start fast executable upload process (for use with automatic upload scripts) */
87 56 zero_gravi
#define FAST_UPLOAD_CMD        ('#')
88 2 zero_gravi
/**@}*/
89
 
90
 
91
/**********************************************************************//**
92
  Executable stream source select
93
 **************************************************************************/
94
enum EXE_STREAM_SOURCE {
95
  EXE_STREAM_UART  = 0, /**< Get executable via UART */
96
  EXE_STREAM_FLASH = 1  /**< Get executable via SPI flash */
97
};
98
 
99
 
100
/**********************************************************************//**
101
 * Error codes
102
 **************************************************************************/
103
enum ERROR_CODES {
104
  ERROR_SIGNATURE = 0, /**< 0: Wrong signature in executable */
105
  ERROR_SIZE      = 1, /**< 1: Insufficient instruction memory capacity */
106
  ERROR_CHECKSUM  = 2, /**< 2: Checksum error in executable */
107
  ERROR_FLASH     = 3, /**< 3: SPI flash access error */
108
  ERROR_ROM       = 4, /**< 4: Instruction memory is marked as read-only */
109
  ERROR_SYSTEM    = 5  /**< 5: System exception */
110
};
111
 
112
 
113
/**********************************************************************//**
114
 * SPI flash commands
115
 **************************************************************************/
116
enum SPI_FLASH_CMD {
117
  SPI_FLASH_CMD_PAGE_PROGRAM = 0x02, /**< Program page */
118
  SPI_FLASH_CMD_READ         = 0x03, /**< Read data */
119
  SPI_FLASH_CMD_READ_STATUS  = 0x05, /**< Get status register */
120
  SPI_FLASH_CMD_WRITE_ENABLE = 0x06, /**< Allow write access */
121
  SPI_FLASH_CMD_READ_ID      = 0x9E, /**< Read manufacturer ID */
122
  SPI_FLASH_CMD_SECTOR_ERASE = 0xD8  /**< Erase complete sector */
123
};
124
 
125
 
126
/**********************************************************************//**
127
 * NEORV32 executable
128
 **************************************************************************/
129
enum NEORV32_EXECUTABLE {
130
  EXE_OFFSET_SIGNATURE =  0, /**< Offset in bytes from start to signature (32-bit) */
131
  EXE_OFFSET_SIZE      =  4, /**< Offset in bytes from start to size (32-bit) */
132
  EXE_OFFSET_CHECKSUM  =  8, /**< Offset in bytes from start to checksum (32-bit) */
133
  EXE_OFFSET_DATA      = 12, /**< Offset in bytes from start to data (32-bit) */
134
};
135
 
136
 
137
/**********************************************************************//**
138
 * Valid executable identification signature.
139
 **************************************************************************/
140
#define EXE_SIGNATURE 0x4788CAFE
141
 
142
 
143
/**********************************************************************//**
144
 * String output helper macros.
145
 **************************************************************************/
146
/**@{*/
147
/* Actual define-to-string helper */
148
#define xstr(a) str(a)
149
/* Internal helper macro */
150
#define str(a) #a
151
/**@}*/
152
 
153
 
154 22 zero_gravi
/**********************************************************************//**
155
 * This global variable keeps the size of the available executable in bytes.
156
 * If =0 no executable is available (yet).
157
 **************************************************************************/
158 47 zero_gravi
volatile uint32_t exe_available = 0;
159 22 zero_gravi
 
160
 
161 47 zero_gravi
/**********************************************************************//**
162
 * Only set during executable fetch (required for cpaturing STORE-BUS-TIMOUT exception).
163
 **************************************************************************/
164
volatile uint32_t getting_exe = 0;
165
 
166
 
167 2 zero_gravi
// Function prototypes
168 22 zero_gravi
void __attribute__((__interrupt__)) bootloader_trap_handler(void);
169 34 zero_gravi
void fast_upload(int src);
170 2 zero_gravi
void print_help(void);
171
void start_app(void);
172
void get_exe(int src);
173
void save_exe(void);
174
uint32_t get_exe_word(int src, uint32_t addr);
175
void system_error(uint8_t err_code);
176
void print_hex_word(uint32_t num);
177
 
178 37 zero_gravi
// SPI flash driver functions
179 2 zero_gravi
uint8_t spi_flash_read_byte(uint32_t addr);
180
void spi_flash_write_byte(uint32_t addr, uint8_t wdata);
181
void spi_flash_write_word(uint32_t addr, uint32_t wdata);
182
void spi_flash_erase_sector(uint32_t addr);
183
uint8_t spi_flash_read_1st_id(void);
184 37 zero_gravi
void spi_flash_write_wait(void);
185 4 zero_gravi
void spi_flash_write_enable(void);
186
void spi_flash_write_addr(uint32_t addr);
187 2 zero_gravi
 
188
 
189
/**********************************************************************//**
190
 * Bootloader main.
191
 **************************************************************************/
192
int main(void) {
193
 
194 56 zero_gravi
// check ISA
195
#if defined __riscv_atomic || defined __riscv_a || __riscv_b || __riscv_compressed || defined __riscv_c || defined __riscv_mul || defined __riscv_m
196
  #warning In order to allow the bootloader to run on *ANY* CPU configuration it should be compiled using the base ISA (rv32i/e) only.
197 39 zero_gravi
#endif
198
 
199 47 zero_gravi
  exe_available = 0; // global variable for executable size; 0 means there is no exe available
200
  getting_exe   = 0; // we are not trying to get an executable yet
201 39 zero_gravi
 
202 2 zero_gravi
  // ------------------------------------------------
203 39 zero_gravi
  // Minimal processor hardware initialization
204
  // - all IO devices are reset and disabled by the crt0 code
205
  // ------------------------------------------------
206
 
207 2 zero_gravi
  // get clock speed (in Hz)
208 12 zero_gravi
  uint32_t clock_speed = SYSINFO_CLK;
209 2 zero_gravi
 
210 48 zero_gravi
  // init SPI for 8-bit, clock-mode 0
211 2 zero_gravi
  if (clock_speed < 40000000) {
212 48 zero_gravi
    neorv32_spi_setup(SPI_FLASH_CLK_PRSC, 0, 0);
213 2 zero_gravi
  }
214
  else {
215 48 zero_gravi
    neorv32_spi_setup(CLK_PRSC_128, 0, 0);
216 2 zero_gravi
  }
217
 
218 56 zero_gravi
#if (STATUS_LED_EN != 0)
219 39 zero_gravi
    // activate status LED, clear all others
220
    neorv32_gpio_port_set(1 << STATUS_LED);
221 56 zero_gravi
#endif
222 39 zero_gravi
 
223 51 zero_gravi
  // init UART (no parity bit, no hardware flow control)
224
  neorv32_uart_setup(BAUD_RATE, PARITY_NONE, FLOW_CONTROL_NONE);
225 2 zero_gravi
 
226
  // Configure machine system timer interrupt for ~2Hz
227
  neorv32_mtime_set_timecmp(neorv32_mtime_get_time() + (clock_speed/4));
228
 
229 47 zero_gravi
  // confiure trap handler (bare-metal, no neorv32 rte available)
230
  neorv32_cpu_csr_write(CSR_MTVEC, (uint32_t)(&bootloader_trap_handler));
231
 
232
  // active timer IRQ
233 42 zero_gravi
  neorv32_cpu_csr_write(CSR_MIE, 1 << CSR_MIE_MTIE); // activate MTIME IRQ source
234 2 zero_gravi
  neorv32_cpu_eint(); // enable global interrupts
235
 
236
 
237 39 zero_gravi
  // ------------------------------------------------
238
  // Fast boot mode: Direct SPI boot
239
  // Bootloader will directly boot and execute image from SPI memory.
240
  // No user UART console is available in this mode!
241
  // ------------------------------------------------
242 56 zero_gravi
#if (SPI_DIRECT_BOOT_EN != 0)
243 39 zero_gravi
  #warning Compiling bootloader in 'SPI direct boot mode'. Bootloader will directly boot from SPI memory. No user UART console will be available.
244 2 zero_gravi
 
245 39 zero_gravi
  neorv32_uart_print("\nNEORV32 bootloader\nAccessing SPI flash at ");
246
  print_hex_word((uint32_t)SPI_FLASH_BOOT_ADR);
247
  neorv32_uart_print("\n");
248 2 zero_gravi
 
249 39 zero_gravi
  get_exe(EXE_STREAM_FLASH);
250
  neorv32_uart_print("\n");
251
  start_app();
252
 
253
  return 0;
254
#endif
255
 
256
 
257 2 zero_gravi
  // ------------------------------------------------
258
  // Show bootloader intro and system info
259
  // ------------------------------------------------
260
  neorv32_uart_print("\n\n\n\n<< NEORV32 Bootloader >>\n\n"
261
                     "BLDV: "__DATE__"\nHWV:  ");
262 37 zero_gravi
  print_hex_word(neorv32_cpu_csr_read(CSR_MIMPID));
263 2 zero_gravi
  neorv32_uart_print("\nCLK:  ");
264 12 zero_gravi
  print_hex_word(SYSINFO_CLK);
265 55 zero_gravi
  neorv32_uart_print("\nUSER: ");
266 12 zero_gravi
  print_hex_word(SYSINFO_USER_CODE);
267 6 zero_gravi
  neorv32_uart_print("\nMISA: ");
268 2 zero_gravi
  print_hex_word(neorv32_cpu_csr_read(CSR_MISA));
269 55 zero_gravi
  neorv32_uart_print("\nZEXT: ");
270
  print_hex_word(neorv32_cpu_csr_read(CSR_MZEXT));
271 27 zero_gravi
  neorv32_uart_print("\nPROC: ");
272 12 zero_gravi
  print_hex_word(SYSINFO_FEATURES);
273 2 zero_gravi
  neorv32_uart_print("\nIMEM: ");
274 23 zero_gravi
  print_hex_word(SYSINFO_IMEM_SIZE);
275 2 zero_gravi
  neorv32_uart_print(" bytes @ ");
276 12 zero_gravi
  print_hex_word(SYSINFO_ISPACE_BASE);
277 2 zero_gravi
  neorv32_uart_print("\nDMEM: ");
278 23 zero_gravi
  print_hex_word(SYSINFO_DMEM_SIZE);
279 2 zero_gravi
  neorv32_uart_print(" bytes @ ");
280 12 zero_gravi
  print_hex_word(SYSINFO_DSPACE_BASE);
281 2 zero_gravi
 
282
 
283
  // ------------------------------------------------
284
  // Auto boot sequence
285
  // ------------------------------------------------
286 24 zero_gravi
#if (AUTOBOOT_EN != 0)
287 2 zero_gravi
  neorv32_uart_print("\n\nAutoboot in "xstr(AUTOBOOT_TIMEOUT)"s. Press key to abort.\n");
288
 
289 13 zero_gravi
  uint64_t timeout_time = neorv32_mtime_get_time() + (uint64_t)(AUTOBOOT_TIMEOUT * clock_speed);
290
 
291 50 zero_gravi
  while (neorv32_uart_char_received() == 0) { // wait for any key to be pressed
292 2 zero_gravi
 
293
    if (neorv32_mtime_get_time() >= timeout_time) { // timeout? start auto boot sequence
294 34 zero_gravi
      fast_upload(EXE_STREAM_FLASH); // try booting from flash
295 2 zero_gravi
    }
296
  }
297
  neorv32_uart_print("Aborted.\n\n");
298 34 zero_gravi
 
299
  // fast executable upload?
300
  if (neorv32_uart_char_received_get() == FAST_UPLOAD_CMD) {
301
    fast_upload(EXE_STREAM_UART);
302
  }
303 24 zero_gravi
#else
304
  neorv32_uart_print("\n\n");
305
#endif
306
 
307 2 zero_gravi
  print_help();
308
 
309
 
310
  // ------------------------------------------------
311
  // Bootloader console
312
  // ------------------------------------------------
313
  while (1) {
314
 
315
    neorv32_uart_print("\nCMD:> ");
316
    char c = neorv32_uart_getc();
317
    neorv32_uart_putc(c); // echo
318
    neorv32_uart_print("\n");
319
 
320 34 zero_gravi
    if (c == FAST_UPLOAD_CMD) { // fast executable upload
321
      fast_upload(EXE_STREAM_UART);
322
    }
323
    else if (c == 'r') { // restart bootloader
324 22 zero_gravi
      asm volatile ("li t0, %[input_i]; jr t0" :  : [input_i] "i" (BOOTLOADER_BASE_ADDRESS)); // jump to beginning of boot ROM
325 2 zero_gravi
    }
326
    else if (c == 'h') { // help menu
327
      print_help();
328
    }
329
    else if (c == 'u') { // get executable via UART
330
      get_exe(EXE_STREAM_UART);
331
    }
332 24 zero_gravi
    else if (c == 's') { // program flash from memory (IMEM)
333 2 zero_gravi
      save_exe();
334
    }
335
    else if (c == 'l') { // get executable from flash
336
      get_exe(EXE_STREAM_FLASH);
337
    }
338
    else if (c == 'e') { // start application program
339
      start_app();
340
    }
341 22 zero_gravi
    else if (c == '?') {
342 2 zero_gravi
      neorv32_uart_print("by Stephan Nolting");
343
    }
344
    else { // unknown command
345
      neorv32_uart_print("Invalid CMD");
346
    }
347
  }
348
 
349 12 zero_gravi
  return 0; // bootloader should never return
350 2 zero_gravi
}
351
 
352
 
353
/**********************************************************************//**
354 34 zero_gravi
 * Get executable stream and execute it.
355
 *
356
 * @param src Source of executable stream data. See #EXE_STREAM_SOURCE.
357
 **************************************************************************/
358
void fast_upload(int src) {
359
 
360
  get_exe(src);
361
  neorv32_uart_print("\n");
362
  start_app();
363
  while(1);
364
}
365
 
366
 
367
/**********************************************************************//**
368 2 zero_gravi
 * Print help menu.
369
 **************************************************************************/
370
void print_help(void) {
371
 
372
  neorv32_uart_print("Available CMDs:\n"
373
                     " h: Help\n"
374
                     " r: Restart\n"
375
                     " u: Upload\n"
376
                     " s: Store to flash\n"
377
                     " l: Load from flash\n"
378
                     " e: Execute");
379
}
380
 
381
 
382
/**********************************************************************//**
383
 * Start application program at the beginning of instruction space.
384
 **************************************************************************/
385
void start_app(void) {
386
 
387 4 zero_gravi
  // executable available?
388 22 zero_gravi
  if (exe_available == 0) {
389 4 zero_gravi
    neorv32_uart_print("No executable available.");
390
    return;
391
  }
392
 
393 39 zero_gravi
  // no need to shut down/reset the used peripherals
394 23 zero_gravi
  // no need to disable interrupt sources
395 39 zero_gravi
  // -> crt0 will do a clean CPU/processor reset/setup
396 2 zero_gravi
 
397 23 zero_gravi
  // deactivate global IRQs
398 2 zero_gravi
  neorv32_cpu_dint();
399
 
400
  neorv32_uart_print("Booting...\n\n");
401
 
402
  // wait for UART to finish transmitting
403 50 zero_gravi
  while (neorv32_uart_tx_busy());
404 2 zero_gravi
 
405
  // start app at instruction space base address
406 14 zero_gravi
  register uint32_t app_base = SYSINFO_ISPACE_BASE;
407
  asm volatile ("jalr zero, %0" : : "r" (app_base));
408
  while (1);
409 2 zero_gravi
}
410
 
411
 
412
/**********************************************************************//**
413 23 zero_gravi
 * Bootloader trap handler. Used for the MTIME tick and to capture any other traps.
414 47 zero_gravi
 * @warning Since we have no runtime environment, we have to use the interrupt attribute here. Here and only here!
415 2 zero_gravi
 **************************************************************************/
416 22 zero_gravi
void __attribute__((__interrupt__)) bootloader_trap_handler(void) {
417 2 zero_gravi
 
418 47 zero_gravi
  uint32_t cause = neorv32_cpu_csr_read(CSR_MCAUSE);
419
 
420 2 zero_gravi
  // make sure this was caused by MTIME IRQ
421 23 zero_gravi
  if (cause == TRAP_CODE_MTI) { // raw exception code for MTI
422 56 zero_gravi
#if (STATUS_LED_EN != 0)
423 22 zero_gravi
      // toggle status LED
424
      neorv32_gpio_pin_toggle(STATUS_LED);
425 56 zero_gravi
#endif
426 2 zero_gravi
    // set time for next IRQ
427 12 zero_gravi
    neorv32_mtime_set_timecmp(neorv32_mtime_get_time() + (SYSINFO_CLK/4));
428 2 zero_gravi
  }
429 23 zero_gravi
  else {
430 47 zero_gravi
    // store bus access error during get_exe
431
    // -> seems like executable is too large
432
    if ((cause == TRAP_CODE_S_ACCESS) && (getting_exe)) {
433
      system_error(ERROR_SIZE);
434
    }
435
    // unknown error
436
    else {
437 56 zero_gravi
      neorv32_uart_print("\n\nEXCEPTION mcause=");
438 47 zero_gravi
      print_hex_word(cause);
439 56 zero_gravi
      neorv32_uart_print(" @ pc=");
440 47 zero_gravi
      print_hex_word(neorv32_cpu_csr_read(CSR_MEPC));
441
      system_error(ERROR_SYSTEM);
442
    }
443 23 zero_gravi
  }
444 2 zero_gravi
}
445
 
446
 
447
/**********************************************************************//**
448
 * Get executable stream.
449
 *
450
 * @param src Source of executable stream data. See #EXE_STREAM_SOURCE.
451
 **************************************************************************/
452
void get_exe(int src) {
453
 
454 47 zero_gravi
  getting_exe = 1; // to inform trap handler we were trying to get an executable
455
 
456 35 zero_gravi
  // is MEM implemented and read-only?
457
  if ((SYSINFO_FEATURES & (1 << SYSINFO_FEATURES_MEM_INT_IMEM_ROM)) &&
458
      (SYSINFO_FEATURES & (1 << SYSINFO_FEATURES_MEM_INT_IMEM)))  {
459 2 zero_gravi
    system_error(ERROR_ROM);
460
  }
461
 
462
  // flash image base address
463
  uint32_t addr = SPI_FLASH_BOOT_ADR;
464
 
465
  // get image from flash?
466
  if (src == EXE_STREAM_UART) {
467
    neorv32_uart_print("Awaiting neorv32_exe.bin... ");
468
  }
469
  else {
470
    neorv32_uart_print("Loading... ");
471
 
472 57 zero_gravi
    // check if SPI is available at all
473
    if (neorv32_spi_available() == 0) {
474
      system_error(ERROR_FLASH);
475
    }
476
 
477 2 zero_gravi
    // check if flash ready (or available at all)
478
    if (spi_flash_read_1st_id() == 0x00) { // manufacturer ID
479
      system_error(ERROR_FLASH);
480
    }
481
  }
482
 
483
  // check if valid image
484
  uint32_t signature = get_exe_word(src, addr + EXE_OFFSET_SIGNATURE);
485
  if (signature != EXE_SIGNATURE) { // signature
486
    system_error(ERROR_SIGNATURE);
487
  }
488
 
489
  // image size and checksum
490
  uint32_t size  = get_exe_word(src, addr + EXE_OFFSET_SIZE); // size in bytes
491
  uint32_t check = get_exe_word(src, addr + EXE_OFFSET_CHECKSUM); // complement sum checksum
492
 
493
  // transfer program data
494 12 zero_gravi
  uint32_t *pnt = (uint32_t*)SYSINFO_ISPACE_BASE;
495 2 zero_gravi
  uint32_t checksum = 0;
496
  uint32_t d = 0, i = 0;
497
  addr = addr + EXE_OFFSET_DATA;
498
  while (i < (size/4)) { // in words
499
    d = get_exe_word(src, addr);
500
    checksum += d;
501
    pnt[i++] = d;
502
    addr += 4;
503
  }
504
 
505
  // error during transfer?
506
  if ((checksum + check) != 0) {
507
    system_error(ERROR_CHECKSUM);
508
  }
509
  else {
510
    neorv32_uart_print("OK");
511 22 zero_gravi
    exe_available = size; // store exe size
512 2 zero_gravi
  }
513 47 zero_gravi
 
514
  getting_exe = 0; // to inform trap handler we are done getting an executable
515 2 zero_gravi
}
516
 
517
 
518
/**********************************************************************//**
519
 * Store content of instruction memory to SPI flash.
520
 **************************************************************************/
521
void save_exe(void) {
522
 
523
  // size of last uploaded executable
524 22 zero_gravi
  uint32_t size = exe_available;
525 2 zero_gravi
 
526
  if (size == 0) {
527
    neorv32_uart_print("No executable available.");
528
    return;
529
  }
530
 
531
  uint32_t addr = SPI_FLASH_BOOT_ADR;
532
 
533
  // info and prompt
534
  neorv32_uart_print("Write 0x");
535
  print_hex_word(size);
536
  neorv32_uart_print(" bytes to SPI flash @ 0x");
537
  print_hex_word(addr);
538
  neorv32_uart_print("? (y/n) ");
539
 
540
  char c = neorv32_uart_getc();
541
  neorv32_uart_putc(c);
542
  if (c != 'y') {
543
    return;
544
  }
545
 
546
  // check if flash ready (or available at all)
547
  if (spi_flash_read_1st_id() == 0x00) { // manufacturer ID
548
    system_error(ERROR_FLASH);
549
  }
550
 
551
  neorv32_uart_print("\nFlashing... ");
552
 
553
  // clear memory before writing
554
  uint32_t num_sectors = (size / SPI_FLASH_SECTOR_SIZE) + 1; // clear at least 1 sector
555
  uint32_t sector = SPI_FLASH_BOOT_ADR;
556
  while (num_sectors--) {
557
    spi_flash_erase_sector(sector);
558
    sector += SPI_FLASH_SECTOR_SIZE;
559
  }
560
 
561
  // write EXE signature
562
  spi_flash_write_word(addr + EXE_OFFSET_SIGNATURE, EXE_SIGNATURE);
563
 
564
  // write size
565
  spi_flash_write_word(addr + EXE_OFFSET_SIZE, size);
566
 
567
  // store data from instruction memory and update checksum
568
  uint32_t checksum = 0;
569 12 zero_gravi
  uint32_t *pnt = (uint32_t*)SYSINFO_ISPACE_BASE;
570 2 zero_gravi
  addr = addr + EXE_OFFSET_DATA;
571
  uint32_t i = 0;
572
  while (i < (size/4)) { // in words
573
    uint32_t d = (uint32_t)*pnt++;
574
    checksum += d;
575
    spi_flash_write_word(addr, d);
576
    addr += 4;
577
    i++;
578
  }
579
 
580
  // write checksum (sum complement)
581
  checksum = (~checksum) + 1;
582
  spi_flash_write_word(SPI_FLASH_BOOT_ADR + EXE_OFFSET_CHECKSUM, checksum);
583
 
584
  neorv32_uart_print("OK");
585
}
586
 
587
 
588
/**********************************************************************//**
589
 * Get word from executable stream
590
 *
591
 * @param src Source of executable stream data. See #EXE_STREAM_SOURCE.
592
 * @param addr Address when accessing SPI flash.
593
 * @return 32-bit data word from stream.
594
 **************************************************************************/
595
uint32_t get_exe_word(int src, uint32_t addr) {
596
 
597
  union {
598
    uint32_t uint32;
599
    uint8_t  uint8[sizeof(uint32_t)];
600
  } data;
601
 
602
  uint32_t i;
603
  for (i=0; i<4; i++) {
604
    if (src == EXE_STREAM_UART) {
605
      data.uint8[3-i] = (uint8_t)neorv32_uart_getc();
606
    }
607
    else {
608
      data.uint8[3-i] = spi_flash_read_byte(addr + i);
609
    }
610
  }
611
 
612
  return data.uint32;
613
}
614
 
615
 
616
/**********************************************************************//**
617
 * Output system error ID and stall.
618
 *
619
 * @param[in] err_code Error code. See #ERROR_CODES.
620
 **************************************************************************/
621
void system_error(uint8_t err_code) {
622
 
623 23 zero_gravi
  neorv32_uart_print("\a\nERROR_"); // output error code with annoying bell sound
624 22 zero_gravi
  neorv32_uart_putc('0' + ((char)err_code)); // FIXME err_code should/must be below 10
625 2 zero_gravi
 
626
  neorv32_cpu_dint(); // deactivate IRQs
627 22 zero_gravi
  if (STATUS_LED_EN == 1) {
628
    neorv32_gpio_port_set(1 << STATUS_LED); // permanently light up status LED
629
  }
630 2 zero_gravi
 
631
  while(1); // freeze
632
}
633
 
634
 
635
/**********************************************************************//**
636
 * Print 32-bit number as 8-digit hexadecimal value (with "0x" suffix).
637
 *
638
 * @param[in] num Number to print as hexadecimal.
639
 **************************************************************************/
640
void print_hex_word(uint32_t num) {
641
 
642 56 zero_gravi
  static const char hex_symbols[16] = "0123456789abcdef";
643 2 zero_gravi
 
644
  neorv32_uart_print("0x");
645
 
646
  int i;
647
  for (i=0; i<8; i++) {
648
    uint32_t index = (num >> (28 - 4*i)) & 0xF;
649
    neorv32_uart_putc(hex_symbols[index]);
650
  }
651
}
652
 
653
 
654
 
655
// -------------------------------------------------------------------------------------
656 37 zero_gravi
// SPI flash driver functions
657 2 zero_gravi
// -------------------------------------------------------------------------------------
658
 
659
/**********************************************************************//**
660
 * Read byte from SPI flash.
661
 *
662
 * @param[in] addr Flash read address.
663
 * @return Read byte from SPI flash.
664
 **************************************************************************/
665
uint8_t spi_flash_read_byte(uint32_t addr) {
666
 
667
  neorv32_spi_cs_en(SPI_FLASH_CS);
668
 
669
  neorv32_spi_trans(SPI_FLASH_CMD_READ);
670 4 zero_gravi
  spi_flash_write_addr(addr);
671 2 zero_gravi
  uint8_t rdata = (uint8_t)neorv32_spi_trans(0);
672
 
673
  neorv32_spi_cs_dis(SPI_FLASH_CS);
674
 
675
  return rdata;
676
}
677
 
678
 
679
/**********************************************************************//**
680
 * Write byte to SPI flash.
681
 *
682
 * @param[in] addr SPI flash read address.
683
 * @param[in] wdata SPI flash read data.
684
 **************************************************************************/
685
void spi_flash_write_byte(uint32_t addr, uint8_t wdata) {
686
 
687 4 zero_gravi
  spi_flash_write_enable(); // allow write-access
688 2 zero_gravi
 
689
  neorv32_spi_cs_en(SPI_FLASH_CS);
690
 
691
  neorv32_spi_trans(SPI_FLASH_CMD_PAGE_PROGRAM);
692 4 zero_gravi
  spi_flash_write_addr(addr);
693 2 zero_gravi
  neorv32_spi_trans(wdata);
694
 
695
  neorv32_spi_cs_dis(SPI_FLASH_CS);
696
 
697 37 zero_gravi
  spi_flash_write_wait(); // wait for write operation to finish
698 2 zero_gravi
}
699
 
700
 
701
/**********************************************************************//**
702
 * Write word to SPI flash.
703
 *
704
 * @param addr SPI flash write address.
705
 * @param wdata SPI flash write data.
706
 **************************************************************************/
707
void spi_flash_write_word(uint32_t addr, uint32_t wdata) {
708
 
709
  union {
710
    uint32_t uint32;
711
    uint8_t  uint8[sizeof(uint32_t)];
712
  } data;
713
 
714
  data.uint32 = wdata;
715
 
716 39 zero_gravi
  int i;
717 2 zero_gravi
  for (i=0; i<4; i++) {
718
    spi_flash_write_byte(addr + i, data.uint8[3-i]);
719
  }
720
}
721
 
722
 
723
/**********************************************************************//**
724
 * Erase sector (64kB) at base adress.
725
 *
726
 * @param[in] addr Base address of sector to erase.
727
 **************************************************************************/
728
void spi_flash_erase_sector(uint32_t addr) {
729
 
730 4 zero_gravi
  spi_flash_write_enable(); // allow write-access
731 2 zero_gravi
 
732
  neorv32_spi_cs_en(SPI_FLASH_CS);
733
 
734
  neorv32_spi_trans(SPI_FLASH_CMD_SECTOR_ERASE);
735 4 zero_gravi
  spi_flash_write_addr(addr);
736 2 zero_gravi
 
737
  neorv32_spi_cs_dis(SPI_FLASH_CS);
738
 
739 37 zero_gravi
  spi_flash_write_wait(); // wait for write operation to finish
740 2 zero_gravi
}
741
 
742
 
743
/**********************************************************************//**
744 37 zero_gravi
 * Read first byte of ID (manufacturer ID), should be != 0x00.
745 2 zero_gravi
 *
746 37 zero_gravi
 * @note The first bit of the manufacturer ID is used to detect if a Flash is connected at all.
747
 *
748
 * @return First byte of ID.
749 2 zero_gravi
 **************************************************************************/
750 37 zero_gravi
uint8_t spi_flash_read_1st_id(void) {
751 2 zero_gravi
 
752
  neorv32_spi_cs_en(SPI_FLASH_CS);
753
 
754 37 zero_gravi
  neorv32_spi_trans(SPI_FLASH_CMD_READ_ID);
755
  uint8_t id = (uint8_t)neorv32_spi_trans(0);
756 2 zero_gravi
 
757
  neorv32_spi_cs_dis(SPI_FLASH_CS);
758
 
759 37 zero_gravi
  return id;
760 2 zero_gravi
}
761
 
762
 
763
/**********************************************************************//**
764 37 zero_gravi
 * Wait for flash write operation to finisch.
765 2 zero_gravi
 **************************************************************************/
766 37 zero_gravi
void spi_flash_write_wait(void) {
767 2 zero_gravi
 
768 37 zero_gravi
  while(1) {
769 2 zero_gravi
 
770 37 zero_gravi
    neorv32_spi_cs_en(SPI_FLASH_CS);
771 2 zero_gravi
 
772 37 zero_gravi
    neorv32_spi_trans(SPI_FLASH_CMD_READ_STATUS);
773
    uint8_t status = (uint8_t)neorv32_spi_trans(0);
774 2 zero_gravi
 
775 37 zero_gravi
    neorv32_spi_cs_dis(SPI_FLASH_CS);
776
 
777
    if ((status & 0x01) == 0) { // write in progress flag cleared?
778
      break;
779
    }
780
  }
781 2 zero_gravi
}
782
 
783
 
784
/**********************************************************************//**
785 4 zero_gravi
 * Enable flash write access.
786 2 zero_gravi
 **************************************************************************/
787 4 zero_gravi
void spi_flash_write_enable(void) {
788 2 zero_gravi
 
789
  neorv32_spi_cs_en(SPI_FLASH_CS);
790 4 zero_gravi
  neorv32_spi_trans(SPI_FLASH_CMD_WRITE_ENABLE);
791
  neorv32_spi_cs_dis(SPI_FLASH_CS);
792
}
793 2 zero_gravi
 
794
 
795 4 zero_gravi
/**********************************************************************//**
796
 * Send address word to flash.
797
 *
798
 * @param[in] addr Address word.
799
 **************************************************************************/
800
void spi_flash_write_addr(uint32_t addr) {
801
 
802
  union {
803
    uint32_t uint32;
804
    uint8_t  uint8[sizeof(uint32_t)];
805
  } address;
806
 
807
  address.uint32 = addr;
808
 
809 39 zero_gravi
  int i;
810
  for (i=2; i>=0; i--) {
811
    neorv32_spi_trans(address.uint8[i]);
812
  }
813 2 zero_gravi
}

powered by: WebSVN 2.1.0

© copyright 1999-2024 OpenCores.org, equivalent to Oliscience, all rights reserved. OpenCores®, registered trademark.