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

Subversion Repositories neorv32

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

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

powered by: WebSVN 2.1.0

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