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

Subversion Repositories neorv32

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

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

powered by: WebSVN 2.1.0

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