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

Subversion Repositories neorv32

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

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 33 zero_gravi
// # In order to run the bootloader on any CPU configuration, the bootloader should be compiled    #
5
// # 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
// # Copyright (c) 2020, Stephan Nolting. All rights reserved.                                     #
22
// #                                                                                               #
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 9 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 39 zero_gravi
/** SPI_DIRECT_BOOT_EN: Define/uncomment to enable SPI direct boot (disables the entire user console!) */
75
//#define SPI_DIRECT_BOOT_EN
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
#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 39 zero_gravi
#ifdef __riscv_compressed
195
  #warning In order to allow the bootloader to run on any CPU configuration it should be compiled using the base ISA (rv32i/e) only.
196
#endif
197
 
198 47 zero_gravi
  exe_available = 0; // global variable for executable size; 0 means there is no exe available
199
  getting_exe   = 0; // we are not trying to get an executable yet
200 39 zero_gravi
 
201 2 zero_gravi
  // ------------------------------------------------
202 39 zero_gravi
  // Minimal processor hardware initialization
203
  // - all IO devices are reset and disabled by the crt0 code
204
  // ------------------------------------------------
205
 
206 2 zero_gravi
  // get clock speed (in Hz)
207 12 zero_gravi
  uint32_t clock_speed = SYSINFO_CLK;
208 2 zero_gravi
 
209 48 zero_gravi
  // init SPI for 8-bit, clock-mode 0
210 2 zero_gravi
  if (clock_speed < 40000000) {
211 48 zero_gravi
    neorv32_spi_setup(SPI_FLASH_CLK_PRSC, 0, 0);
212 2 zero_gravi
  }
213
  else {
214 48 zero_gravi
    neorv32_spi_setup(CLK_PRSC_128, 0, 0);
215 2 zero_gravi
  }
216
 
217 39 zero_gravi
  if (STATUS_LED_EN == 1) {
218
    // activate status LED, clear all others
219
    neorv32_gpio_port_set(1 << STATUS_LED);
220
  }
221
 
222 51 zero_gravi
  // init UART (no parity bit, no hardware flow control)
223
  neorv32_uart_setup(BAUD_RATE, PARITY_NONE, FLOW_CONTROL_NONE);
224 2 zero_gravi
 
225
  // Configure machine system timer interrupt for ~2Hz
226
  neorv32_mtime_set_timecmp(neorv32_mtime_get_time() + (clock_speed/4));
227
 
228 47 zero_gravi
  // confiure trap handler (bare-metal, no neorv32 rte available)
229
  neorv32_cpu_csr_write(CSR_MTVEC, (uint32_t)(&bootloader_trap_handler));
230
 
231
  // active timer IRQ
232 42 zero_gravi
  neorv32_cpu_csr_write(CSR_MIE, 1 << CSR_MIE_MTIE); // activate MTIME IRQ source
233 2 zero_gravi
  neorv32_cpu_eint(); // enable global interrupts
234
 
235
 
236 39 zero_gravi
  // ------------------------------------------------
237
  // Fast boot mode: Direct SPI boot
238
  // Bootloader will directly boot and execute image from SPI memory.
239
  // No user UART console is available in this mode!
240
  // ------------------------------------------------
241
#ifdef SPI_DIRECT_BOOT_EN
242
  #warning Compiling bootloader in 'SPI direct boot mode'. Bootloader will directly boot from SPI memory. No user UART console will be available.
243 2 zero_gravi
 
244 39 zero_gravi
  neorv32_uart_print("\nNEORV32 bootloader\nAccessing SPI flash at ");
245
  print_hex_word((uint32_t)SPI_FLASH_BOOT_ADR);
246
  neorv32_uart_print("\n");
247 2 zero_gravi
 
248 39 zero_gravi
  get_exe(EXE_STREAM_FLASH);
249
  neorv32_uart_print("\n");
250
  start_app();
251
 
252
  return 0;
253
#endif
254
 
255
 
256 2 zero_gravi
  // ------------------------------------------------
257
  // Show bootloader intro and system info
258
  // ------------------------------------------------
259
  neorv32_uart_print("\n\n\n\n<< NEORV32 Bootloader >>\n\n"
260
                     "BLDV: "__DATE__"\nHWV:  ");
261 37 zero_gravi
  print_hex_word(neorv32_cpu_csr_read(CSR_MIMPID));
262 2 zero_gravi
  neorv32_uart_print("\nCLK:  ");
263 12 zero_gravi
  print_hex_word(SYSINFO_CLK);
264
  neorv32_uart_print(" Hz\nUSER: ");
265
  print_hex_word(SYSINFO_USER_CODE);
266 6 zero_gravi
  neorv32_uart_print("\nMISA: ");
267 2 zero_gravi
  print_hex_word(neorv32_cpu_csr_read(CSR_MISA));
268 27 zero_gravi
  neorv32_uart_print("\nPROC: ");
269 12 zero_gravi
  print_hex_word(SYSINFO_FEATURES);
270 2 zero_gravi
  neorv32_uart_print("\nIMEM: ");
271 23 zero_gravi
  print_hex_word(SYSINFO_IMEM_SIZE);
272 2 zero_gravi
  neorv32_uart_print(" bytes @ ");
273 12 zero_gravi
  print_hex_word(SYSINFO_ISPACE_BASE);
274 2 zero_gravi
  neorv32_uart_print("\nDMEM: ");
275 23 zero_gravi
  print_hex_word(SYSINFO_DMEM_SIZE);
276 2 zero_gravi
  neorv32_uart_print(" bytes @ ");
277 12 zero_gravi
  print_hex_word(SYSINFO_DSPACE_BASE);
278 2 zero_gravi
 
279
 
280
  // ------------------------------------------------
281
  // Auto boot sequence
282
  // ------------------------------------------------
283 24 zero_gravi
#if (AUTOBOOT_EN != 0)
284 2 zero_gravi
  neorv32_uart_print("\n\nAutoboot in "xstr(AUTOBOOT_TIMEOUT)"s. Press key to abort.\n");
285
 
286 13 zero_gravi
  uint64_t timeout_time = neorv32_mtime_get_time() + (uint64_t)(AUTOBOOT_TIMEOUT * clock_speed);
287
 
288 50 zero_gravi
  while (neorv32_uart_char_received() == 0) { // wait for any key to be pressed
289 2 zero_gravi
 
290
    if (neorv32_mtime_get_time() >= timeout_time) { // timeout? start auto boot sequence
291 34 zero_gravi
      fast_upload(EXE_STREAM_FLASH); // try booting from flash
292 2 zero_gravi
    }
293
  }
294
  neorv32_uart_print("Aborted.\n\n");
295 34 zero_gravi
 
296
  // fast executable upload?
297
  if (neorv32_uart_char_received_get() == FAST_UPLOAD_CMD) {
298
    fast_upload(EXE_STREAM_UART);
299
  }
300 24 zero_gravi
#else
301
  neorv32_uart_print("\n\n");
302
#endif
303
 
304 2 zero_gravi
  print_help();
305
 
306
 
307
  // ------------------------------------------------
308
  // Bootloader console
309
  // ------------------------------------------------
310
  while (1) {
311
 
312
    neorv32_uart_print("\nCMD:> ");
313
    char c = neorv32_uart_getc();
314
    neorv32_uart_putc(c); // echo
315
    neorv32_uart_print("\n");
316
 
317 34 zero_gravi
    if (c == FAST_UPLOAD_CMD) { // fast executable upload
318
      fast_upload(EXE_STREAM_UART);
319
    }
320
    else if (c == 'r') { // restart bootloader
321 22 zero_gravi
      asm volatile ("li t0, %[input_i]; jr t0" :  : [input_i] "i" (BOOTLOADER_BASE_ADDRESS)); // jump to beginning of boot ROM
322 2 zero_gravi
    }
323
    else if (c == 'h') { // help menu
324
      print_help();
325
    }
326
    else if (c == 'u') { // get executable via UART
327
      get_exe(EXE_STREAM_UART);
328
    }
329 24 zero_gravi
    else if (c == 's') { // program flash from memory (IMEM)
330 2 zero_gravi
      save_exe();
331
    }
332
    else if (c == 'l') { // get executable from flash
333
      get_exe(EXE_STREAM_FLASH);
334
    }
335
    else if (c == 'e') { // start application program
336
      start_app();
337
    }
338 22 zero_gravi
    else if (c == '?') {
339 2 zero_gravi
      neorv32_uart_print("by Stephan Nolting");
340
    }
341
    else { // unknown command
342
      neorv32_uart_print("Invalid CMD");
343
    }
344
  }
345
 
346 12 zero_gravi
  return 0; // bootloader should never return
347 2 zero_gravi
}
348
 
349
 
350
/**********************************************************************//**
351 34 zero_gravi
 * Get executable stream and execute it.
352
 *
353
 * @param src Source of executable stream data. See #EXE_STREAM_SOURCE.
354
 **************************************************************************/
355
void fast_upload(int src) {
356
 
357
  get_exe(src);
358
  neorv32_uart_print("\n");
359
  start_app();
360
  while(1);
361
}
362
 
363
 
364
/**********************************************************************//**
365 2 zero_gravi
 * Print help menu.
366
 **************************************************************************/
367
void print_help(void) {
368
 
369
  neorv32_uart_print("Available CMDs:\n"
370
                     " h: Help\n"
371
                     " r: Restart\n"
372
                     " u: Upload\n"
373
                     " s: Store to flash\n"
374
                     " l: Load from flash\n"
375
                     " e: Execute");
376
}
377
 
378
 
379
/**********************************************************************//**
380
 * Start application program at the beginning of instruction space.
381
 **************************************************************************/
382
void start_app(void) {
383
 
384 4 zero_gravi
  // executable available?
385 22 zero_gravi
  if (exe_available == 0) {
386 4 zero_gravi
    neorv32_uart_print("No executable available.");
387
    return;
388
  }
389
 
390 39 zero_gravi
  // no need to shut down/reset the used peripherals
391 23 zero_gravi
  // no need to disable interrupt sources
392 39 zero_gravi
  // -> crt0 will do a clean CPU/processor reset/setup
393 2 zero_gravi
 
394 23 zero_gravi
  // deactivate global IRQs
395 2 zero_gravi
  neorv32_cpu_dint();
396
 
397
  neorv32_uart_print("Booting...\n\n");
398
 
399
  // wait for UART to finish transmitting
400 50 zero_gravi
  while (neorv32_uart_tx_busy());
401 2 zero_gravi
 
402
  // start app at instruction space base address
403 14 zero_gravi
  register uint32_t app_base = SYSINFO_ISPACE_BASE;
404
  asm volatile ("jalr zero, %0" : : "r" (app_base));
405
  while (1);
406 2 zero_gravi
}
407
 
408
 
409
/**********************************************************************//**
410 23 zero_gravi
 * Bootloader trap handler. Used for the MTIME tick and to capture any other traps.
411 47 zero_gravi
 * @warning Since we have no runtime environment, we have to use the interrupt attribute here. Here and only here!
412 2 zero_gravi
 **************************************************************************/
413 22 zero_gravi
void __attribute__((__interrupt__)) bootloader_trap_handler(void) {
414 2 zero_gravi
 
415 47 zero_gravi
  uint32_t cause = neorv32_cpu_csr_read(CSR_MCAUSE);
416
 
417 2 zero_gravi
  // make sure this was caused by MTIME IRQ
418 23 zero_gravi
  if (cause == TRAP_CODE_MTI) { // raw exception code for MTI
419 22 zero_gravi
    if (STATUS_LED_EN == 1) {
420
      // toggle status LED
421
      neorv32_gpio_pin_toggle(STATUS_LED);
422
    }
423 2 zero_gravi
    // set time for next IRQ
424 12 zero_gravi
    neorv32_mtime_set_timecmp(neorv32_mtime_get_time() + (SYSINFO_CLK/4));
425 2 zero_gravi
  }
426 23 zero_gravi
  else {
427 47 zero_gravi
    // store bus access error during get_exe
428
    // -> seems like executable is too large
429
    if ((cause == TRAP_CODE_S_ACCESS) && (getting_exe)) {
430
      system_error(ERROR_SIZE);
431
    }
432
    // unknown error
433
    else {
434
      neorv32_uart_print("\n\nEXC (");
435
      print_hex_word(cause);
436
      neorv32_uart_print(") @ 0x");
437
      print_hex_word(neorv32_cpu_csr_read(CSR_MEPC));
438
      system_error(ERROR_SYSTEM);
439
    }
440 23 zero_gravi
  }
441 2 zero_gravi
}
442
 
443
 
444
/**********************************************************************//**
445
 * Get executable stream.
446
 *
447
 * @param src Source of executable stream data. See #EXE_STREAM_SOURCE.
448
 **************************************************************************/
449
void get_exe(int src) {
450
 
451 47 zero_gravi
  getting_exe = 1; // to inform trap handler we were trying to get an executable
452
 
453 35 zero_gravi
  // is MEM implemented and read-only?
454
  if ((SYSINFO_FEATURES & (1 << SYSINFO_FEATURES_MEM_INT_IMEM_ROM)) &&
455
      (SYSINFO_FEATURES & (1 << SYSINFO_FEATURES_MEM_INT_IMEM)))  {
456 2 zero_gravi
    system_error(ERROR_ROM);
457
  }
458
 
459
  // flash image base address
460
  uint32_t addr = SPI_FLASH_BOOT_ADR;
461
 
462
  // get image from flash?
463
  if (src == EXE_STREAM_UART) {
464
    neorv32_uart_print("Awaiting neorv32_exe.bin... ");
465
  }
466
  else {
467
    neorv32_uart_print("Loading... ");
468
 
469
    // check if flash ready (or available at all)
470
    if (spi_flash_read_1st_id() == 0x00) { // manufacturer ID
471
      system_error(ERROR_FLASH);
472
    }
473
  }
474
 
475
  // check if valid image
476
  uint32_t signature = get_exe_word(src, addr + EXE_OFFSET_SIGNATURE);
477
  if (signature != EXE_SIGNATURE) { // signature
478
    system_error(ERROR_SIGNATURE);
479
  }
480
 
481
  // image size and checksum
482
  uint32_t size  = get_exe_word(src, addr + EXE_OFFSET_SIZE); // size in bytes
483
  uint32_t check = get_exe_word(src, addr + EXE_OFFSET_CHECKSUM); // complement sum checksum
484
 
485
  // transfer program data
486 12 zero_gravi
  uint32_t *pnt = (uint32_t*)SYSINFO_ISPACE_BASE;
487 2 zero_gravi
  uint32_t checksum = 0;
488
  uint32_t d = 0, i = 0;
489
  addr = addr + EXE_OFFSET_DATA;
490
  while (i < (size/4)) { // in words
491
    d = get_exe_word(src, addr);
492
    checksum += d;
493
    pnt[i++] = d;
494
    addr += 4;
495
  }
496
 
497
  // error during transfer?
498
  if ((checksum + check) != 0) {
499
    system_error(ERROR_CHECKSUM);
500
  }
501
  else {
502
    neorv32_uart_print("OK");
503 22 zero_gravi
    exe_available = size; // store exe size
504 2 zero_gravi
  }
505 47 zero_gravi
 
506
  getting_exe = 0; // to inform trap handler we are done getting an executable
507 2 zero_gravi
}
508
 
509
 
510
/**********************************************************************//**
511
 * Store content of instruction memory to SPI flash.
512
 **************************************************************************/
513
void save_exe(void) {
514
 
515
  // size of last uploaded executable
516 22 zero_gravi
  uint32_t size = exe_available;
517 2 zero_gravi
 
518
  if (size == 0) {
519
    neorv32_uart_print("No executable available.");
520
    return;
521
  }
522
 
523
  uint32_t addr = SPI_FLASH_BOOT_ADR;
524
 
525
  // info and prompt
526
  neorv32_uart_print("Write 0x");
527
  print_hex_word(size);
528
  neorv32_uart_print(" bytes to SPI flash @ 0x");
529
  print_hex_word(addr);
530
  neorv32_uart_print("? (y/n) ");
531
 
532
  char c = neorv32_uart_getc();
533
  neorv32_uart_putc(c);
534
  if (c != 'y') {
535
    return;
536
  }
537
 
538
  // check if flash ready (or available at all)
539
  if (spi_flash_read_1st_id() == 0x00) { // manufacturer ID
540
    system_error(ERROR_FLASH);
541
  }
542
 
543
  neorv32_uart_print("\nFlashing... ");
544
 
545
  // clear memory before writing
546
  uint32_t num_sectors = (size / SPI_FLASH_SECTOR_SIZE) + 1; // clear at least 1 sector
547
  uint32_t sector = SPI_FLASH_BOOT_ADR;
548
  while (num_sectors--) {
549
    spi_flash_erase_sector(sector);
550
    sector += SPI_FLASH_SECTOR_SIZE;
551
  }
552
 
553
  // write EXE signature
554
  spi_flash_write_word(addr + EXE_OFFSET_SIGNATURE, EXE_SIGNATURE);
555
 
556
  // write size
557
  spi_flash_write_word(addr + EXE_OFFSET_SIZE, size);
558
 
559
  // store data from instruction memory and update checksum
560
  uint32_t checksum = 0;
561 12 zero_gravi
  uint32_t *pnt = (uint32_t*)SYSINFO_ISPACE_BASE;
562 2 zero_gravi
  addr = addr + EXE_OFFSET_DATA;
563
  uint32_t i = 0;
564
  while (i < (size/4)) { // in words
565
    uint32_t d = (uint32_t)*pnt++;
566
    checksum += d;
567
    spi_flash_write_word(addr, d);
568
    addr += 4;
569
    i++;
570
  }
571
 
572
  // write checksum (sum complement)
573
  checksum = (~checksum) + 1;
574
  spi_flash_write_word(SPI_FLASH_BOOT_ADR + EXE_OFFSET_CHECKSUM, checksum);
575
 
576
  neorv32_uart_print("OK");
577
}
578
 
579
 
580
/**********************************************************************//**
581
 * Get word from executable stream
582
 *
583
 * @param src Source of executable stream data. See #EXE_STREAM_SOURCE.
584
 * @param addr Address when accessing SPI flash.
585
 * @return 32-bit data word from stream.
586
 **************************************************************************/
587
uint32_t get_exe_word(int src, uint32_t addr) {
588
 
589
  union {
590
    uint32_t uint32;
591
    uint8_t  uint8[sizeof(uint32_t)];
592
  } data;
593
 
594
  uint32_t i;
595
  for (i=0; i<4; i++) {
596
    if (src == EXE_STREAM_UART) {
597
      data.uint8[3-i] = (uint8_t)neorv32_uart_getc();
598
    }
599
    else {
600
      data.uint8[3-i] = spi_flash_read_byte(addr + i);
601
    }
602
  }
603
 
604
  return data.uint32;
605
}
606
 
607
 
608
/**********************************************************************//**
609
 * Output system error ID and stall.
610
 *
611
 * @param[in] err_code Error code. See #ERROR_CODES.
612
 **************************************************************************/
613
void system_error(uint8_t err_code) {
614
 
615 23 zero_gravi
  neorv32_uart_print("\a\nERROR_"); // output error code with annoying bell sound
616 22 zero_gravi
  neorv32_uart_putc('0' + ((char)err_code)); // FIXME err_code should/must be below 10
617 2 zero_gravi
 
618
  neorv32_cpu_dint(); // deactivate IRQs
619 22 zero_gravi
  if (STATUS_LED_EN == 1) {
620
    neorv32_gpio_port_set(1 << STATUS_LED); // permanently light up status LED
621
  }
622 2 zero_gravi
 
623
  while(1); // freeze
624
}
625
 
626
 
627
/**********************************************************************//**
628
 * Print 32-bit number as 8-digit hexadecimal value (with "0x" suffix).
629
 *
630
 * @param[in] num Number to print as hexadecimal.
631
 **************************************************************************/
632
void print_hex_word(uint32_t num) {
633
 
634
  static const char hex_symbols[16] = "0123456789ABCDEF";
635
 
636
  neorv32_uart_print("0x");
637
 
638
  int i;
639
  for (i=0; i<8; i++) {
640
    uint32_t index = (num >> (28 - 4*i)) & 0xF;
641
    neorv32_uart_putc(hex_symbols[index]);
642
  }
643
}
644
 
645
 
646
 
647
// -------------------------------------------------------------------------------------
648 37 zero_gravi
// SPI flash driver functions
649 2 zero_gravi
// -------------------------------------------------------------------------------------
650
 
651
/**********************************************************************//**
652
 * Read byte from SPI flash.
653
 *
654
 * @param[in] addr Flash read address.
655
 * @return Read byte from SPI flash.
656
 **************************************************************************/
657
uint8_t spi_flash_read_byte(uint32_t addr) {
658
 
659
  neorv32_spi_cs_en(SPI_FLASH_CS);
660
 
661
  neorv32_spi_trans(SPI_FLASH_CMD_READ);
662 4 zero_gravi
  spi_flash_write_addr(addr);
663 2 zero_gravi
  uint8_t rdata = (uint8_t)neorv32_spi_trans(0);
664
 
665
  neorv32_spi_cs_dis(SPI_FLASH_CS);
666
 
667
  return rdata;
668
}
669
 
670
 
671
/**********************************************************************//**
672
 * Write byte to SPI flash.
673
 *
674
 * @param[in] addr SPI flash read address.
675
 * @param[in] wdata SPI flash read data.
676
 **************************************************************************/
677
void spi_flash_write_byte(uint32_t addr, uint8_t wdata) {
678
 
679 4 zero_gravi
  spi_flash_write_enable(); // allow write-access
680 2 zero_gravi
 
681
  neorv32_spi_cs_en(SPI_FLASH_CS);
682
 
683
  neorv32_spi_trans(SPI_FLASH_CMD_PAGE_PROGRAM);
684 4 zero_gravi
  spi_flash_write_addr(addr);
685 2 zero_gravi
  neorv32_spi_trans(wdata);
686
 
687
  neorv32_spi_cs_dis(SPI_FLASH_CS);
688
 
689 37 zero_gravi
  spi_flash_write_wait(); // wait for write operation to finish
690 2 zero_gravi
}
691
 
692
 
693
/**********************************************************************//**
694
 * Write word to SPI flash.
695
 *
696
 * @param addr SPI flash write address.
697
 * @param wdata SPI flash write data.
698
 **************************************************************************/
699
void spi_flash_write_word(uint32_t addr, uint32_t wdata) {
700
 
701
  union {
702
    uint32_t uint32;
703
    uint8_t  uint8[sizeof(uint32_t)];
704
  } data;
705
 
706
  data.uint32 = wdata;
707
 
708 39 zero_gravi
  int i;
709 2 zero_gravi
  for (i=0; i<4; i++) {
710
    spi_flash_write_byte(addr + i, data.uint8[3-i]);
711
  }
712
}
713
 
714
 
715
/**********************************************************************//**
716
 * Erase sector (64kB) at base adress.
717
 *
718
 * @param[in] addr Base address of sector to erase.
719
 **************************************************************************/
720
void spi_flash_erase_sector(uint32_t addr) {
721
 
722 4 zero_gravi
  spi_flash_write_enable(); // allow write-access
723 2 zero_gravi
 
724
  neorv32_spi_cs_en(SPI_FLASH_CS);
725
 
726
  neorv32_spi_trans(SPI_FLASH_CMD_SECTOR_ERASE);
727 4 zero_gravi
  spi_flash_write_addr(addr);
728 2 zero_gravi
 
729
  neorv32_spi_cs_dis(SPI_FLASH_CS);
730
 
731 37 zero_gravi
  spi_flash_write_wait(); // wait for write operation to finish
732 2 zero_gravi
}
733
 
734
 
735
/**********************************************************************//**
736 37 zero_gravi
 * Read first byte of ID (manufacturer ID), should be != 0x00.
737 2 zero_gravi
 *
738 37 zero_gravi
 * @note The first bit of the manufacturer ID is used to detect if a Flash is connected at all.
739
 *
740
 * @return First byte of ID.
741 2 zero_gravi
 **************************************************************************/
742 37 zero_gravi
uint8_t spi_flash_read_1st_id(void) {
743 2 zero_gravi
 
744
  neorv32_spi_cs_en(SPI_FLASH_CS);
745
 
746 37 zero_gravi
  neorv32_spi_trans(SPI_FLASH_CMD_READ_ID);
747
  uint8_t id = (uint8_t)neorv32_spi_trans(0);
748 2 zero_gravi
 
749
  neorv32_spi_cs_dis(SPI_FLASH_CS);
750
 
751 37 zero_gravi
  return id;
752 2 zero_gravi
}
753
 
754
 
755
/**********************************************************************//**
756 37 zero_gravi
 * Wait for flash write operation to finisch.
757 2 zero_gravi
 **************************************************************************/
758 37 zero_gravi
void spi_flash_write_wait(void) {
759 2 zero_gravi
 
760 37 zero_gravi
  while(1) {
761 2 zero_gravi
 
762 37 zero_gravi
    neorv32_spi_cs_en(SPI_FLASH_CS);
763 2 zero_gravi
 
764 37 zero_gravi
    neorv32_spi_trans(SPI_FLASH_CMD_READ_STATUS);
765
    uint8_t status = (uint8_t)neorv32_spi_trans(0);
766 2 zero_gravi
 
767 37 zero_gravi
    neorv32_spi_cs_dis(SPI_FLASH_CS);
768
 
769
    if ((status & 0x01) == 0) { // write in progress flag cleared?
770
      break;
771
    }
772
  }
773 2 zero_gravi
}
774
 
775
 
776
/**********************************************************************//**
777 4 zero_gravi
 * Enable flash write access.
778 2 zero_gravi
 **************************************************************************/
779 4 zero_gravi
void spi_flash_write_enable(void) {
780 2 zero_gravi
 
781
  neorv32_spi_cs_en(SPI_FLASH_CS);
782 4 zero_gravi
  neorv32_spi_trans(SPI_FLASH_CMD_WRITE_ENABLE);
783
  neorv32_spi_cs_dis(SPI_FLASH_CS);
784
}
785 2 zero_gravi
 
786
 
787 4 zero_gravi
/**********************************************************************//**
788
 * Send address word to flash.
789
 *
790
 * @param[in] addr Address word.
791
 **************************************************************************/
792
void spi_flash_write_addr(uint32_t addr) {
793
 
794
  union {
795
    uint32_t uint32;
796
    uint8_t  uint8[sizeof(uint32_t)];
797
  } address;
798
 
799
  address.uint32 = addr;
800
 
801 39 zero_gravi
  int i;
802
  for (i=2; i>=0; i--) {
803
    neorv32_spi_trans(address.uint8[i]);
804
  }
805 2 zero_gravi
}

powered by: WebSVN 2.1.0

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