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

Subversion Repositories neorv32

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

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

powered by: WebSVN 2.1.0

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