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

Subversion Repositories neorv32

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

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 2 zero_gravi
/** Bootloader status LED at GPIO output port (0..15) */
68
#define STATUS_LED             (0)
69
/** SPI flash boot image base address */
70 11 zero_gravi
#define SPI_FLASH_BOOT_ADR     (0x00800000)
71 2 zero_gravi
/** SPI flash chip select at spi_csn_o */
72
#define SPI_FLASH_CS           (0)
73
/** Default SPI flash clock prescaler for serial peripheral interface */
74
#define SPI_FLASH_CLK_PRSC     (CLK_PRSC_8)
75
/** SPI flash sector size in bytes */
76
#define SPI_FLASH_SECTOR_SIZE  (64*1024)
77
/**@}*/
78
 
79
 
80
/**********************************************************************//**
81
  Executable stream source select
82
 **************************************************************************/
83
enum EXE_STREAM_SOURCE {
84
  EXE_STREAM_UART  = 0, /**< Get executable via UART */
85
  EXE_STREAM_FLASH = 1  /**< Get executable via SPI flash */
86
};
87
 
88
 
89
/**********************************************************************//**
90
 * Error codes
91
 **************************************************************************/
92
enum ERROR_CODES {
93
  ERROR_SIGNATURE = 0, /**< 0: Wrong signature in executable */
94
  ERROR_SIZE      = 1, /**< 1: Insufficient instruction memory capacity */
95
  ERROR_CHECKSUM  = 2, /**< 2: Checksum error in executable */
96
  ERROR_FLASH     = 3, /**< 3: SPI flash access error */
97
  ERROR_ROM       = 4, /**< 4: Instruction memory is marked as read-only */
98
  ERROR_SYSTEM    = 5  /**< 5: System exception */
99
};
100
 
101
 
102
/**********************************************************************//**
103
 * SPI flash commands
104
 **************************************************************************/
105
enum SPI_FLASH_CMD {
106
  SPI_FLASH_CMD_PAGE_PROGRAM = 0x02, /**< Program page */
107
  SPI_FLASH_CMD_READ         = 0x03, /**< Read data */
108
  SPI_FLASH_CMD_READ_STATUS  = 0x05, /**< Get status register */
109
  SPI_FLASH_CMD_WRITE_ENABLE = 0x06, /**< Allow write access */
110
  SPI_FLASH_CMD_READ_ID      = 0x9E, /**< Read manufacturer ID */
111
  SPI_FLASH_CMD_SECTOR_ERASE = 0xD8  /**< Erase complete sector */
112
};
113
 
114
 
115
/**********************************************************************//**
116
 * NEORV32 executable
117
 **************************************************************************/
118
enum NEORV32_EXECUTABLE {
119
  EXE_OFFSET_SIGNATURE =  0, /**< Offset in bytes from start to signature (32-bit) */
120
  EXE_OFFSET_SIZE      =  4, /**< Offset in bytes from start to size (32-bit) */
121
  EXE_OFFSET_CHECKSUM  =  8, /**< Offset in bytes from start to checksum (32-bit) */
122
  EXE_OFFSET_DATA      = 12, /**< Offset in bytes from start to data (32-bit) */
123
};
124
 
125
 
126
/**********************************************************************//**
127
 * Valid executable identification signature.
128
 **************************************************************************/
129
#define EXE_SIGNATURE 0x4788CAFE
130
 
131
 
132
/**********************************************************************//**
133
 * String output helper macros.
134
 **************************************************************************/
135
/**@{*/
136
/* Actual define-to-string helper */
137
#define xstr(a) str(a)
138
/* Internal helper macro */
139
#define str(a) #a
140
/**@}*/
141
 
142
 
143
// Function prototypes
144
void __attribute__((__interrupt__)) mtime_irq_handler(void);
145
void print_help(void);
146
void start_app(void);
147
void get_exe(int src);
148
void save_exe(void);
149
uint32_t get_exe_word(int src, uint32_t addr);
150
void system_error(uint8_t err_code);
151
void print_hex_word(uint32_t num);
152
 
153
// SPI flash access
154
uint8_t spi_flash_read_byte(uint32_t addr);
155
void spi_flash_write_byte(uint32_t addr, uint8_t wdata);
156
void spi_flash_write_word(uint32_t addr, uint32_t wdata);
157
void spi_flash_erase_sector(uint32_t addr);
158
uint8_t spi_flash_read_status(void);
159
uint8_t spi_flash_read_1st_id(void);
160 4 zero_gravi
void spi_flash_write_enable(void);
161
void spi_flash_write_addr(uint32_t addr);
162 2 zero_gravi
 
163
 
164
/**********************************************************************//**
165
 * Bootloader main.
166
 **************************************************************************/
167
int main(void) {
168
 
169
  // ------------------------------------------------
170
  // Processor hardware initialization
171
  // ------------------------------------------------
172
 
173 11 zero_gravi
  // reset system time
174 12 zero_gravi
  MTIME_LO = 0;
175
  MTIME_HI = 0;
176 11 zero_gravi
 
177 2 zero_gravi
  // deactivate unused IO devices
178 12 zero_gravi
  neorv32_wdt_disable();
179 2 zero_gravi
  neorv32_clic_disable();
180
  neorv32_pwm_disable();
181
  neorv32_spi_disable();
182
  neorv32_trng_disable();
183
  neorv32_twi_disable();
184
 
185
  // get clock speed (in Hz)
186 12 zero_gravi
  uint32_t clock_speed = SYSINFO_CLK;
187 2 zero_gravi
 
188
  // init SPI for 8-bit, clock-mode 0, MSB-first, no interrupt
189
  if (clock_speed < 40000000) {
190
    neorv32_spi_setup(SPI_FLASH_CLK_PRSC, 0, 0, 0, 0);
191
  }
192
  else {
193
    neorv32_spi_setup(CLK_PRSC_128, 0, 0, 0, 0);
194
  }
195
 
196
  // init UART (no interrupts)
197
  neorv32_uart_setup(BAUD_RATE, 0, 0);
198
 
199
  // Configure machine system timer interrupt for ~2Hz
200
  neorv32_mtime_set_timecmp(neorv32_mtime_get_time() + (clock_speed/4));
201
 
202
  // confiure interrupt vector (bare-metal, no neorv32 rte)
203
  neorv32_cpu_csr_write(CSR_MTVEC, (uint32_t)(&mtime_irq_handler));
204
  neorv32_cpu_csr_write(CSR_MIE, 1 << CPU_MIE_MTIE); // activate MTIME IRQ source
205
 
206
  neorv32_cpu_eint(); // enable global interrupts
207
 
208
  // init GPIO
209
  neorv32_gpio_port_set(1 << STATUS_LED); // activate status LED, clear all others
210
 
211
  // abuse mscratch CSR as global variable to store the size of the last uploaded executable
212
  // this CSR must not be used by the bootloader's crt0.S!
213
  neorv32_cpu_csr_write(CSR_MSCRATCH, 0);
214
 
215
 
216
  // ------------------------------------------------
217
  // Show bootloader intro and system info
218
  // ------------------------------------------------
219
  neorv32_uart_print("\n\n\n\n<< NEORV32 Bootloader >>\n\n"
220
                     "BLDV: "__DATE__"\nHWV:  ");
221 12 zero_gravi
  neorv32_rte_print_hw_version();
222 2 zero_gravi
  neorv32_uart_print("\nCLK:  ");
223 12 zero_gravi
  print_hex_word(SYSINFO_CLK);
224
  neorv32_uart_print(" Hz\nUSER: ");
225
  print_hex_word(SYSINFO_USER_CODE);
226 6 zero_gravi
  neorv32_uart_print("\nMISA: ");
227 2 zero_gravi
  print_hex_word(neorv32_cpu_csr_read(CSR_MISA));
228
  neorv32_uart_print("\nCONF: ");
229 12 zero_gravi
  print_hex_word(SYSINFO_FEATURES);
230 2 zero_gravi
  neorv32_uart_print("\nIMEM: ");
231 12 zero_gravi
  print_hex_word(SYSINFO_ISPACE_SIZE);
232 2 zero_gravi
  neorv32_uart_print(" bytes @ ");
233 12 zero_gravi
  print_hex_word(SYSINFO_ISPACE_BASE);
234 2 zero_gravi
  neorv32_uart_print("\nDMEM: ");
235 12 zero_gravi
  print_hex_word(SYSINFO_DSPACE_SIZE);
236 2 zero_gravi
  neorv32_uart_print(" bytes @ ");
237 12 zero_gravi
  print_hex_word(SYSINFO_DSPACE_BASE);
238 2 zero_gravi
 
239
 
240
  // ------------------------------------------------
241
  // Auto boot sequence
242
  // ------------------------------------------------
243
  neorv32_uart_print("\n\nAutoboot in "xstr(AUTOBOOT_TIMEOUT)"s. Press key to abort.\n");
244
 
245 13 zero_gravi
  uint64_t timeout_time = neorv32_mtime_get_time() + (uint64_t)(AUTOBOOT_TIMEOUT * clock_speed);
246
 
247 2 zero_gravi
  while ((UART_DATA & (1 << UART_DATA_AVAIL)) == 0) { // wait for any key to be pressed or timeout
248
 
249
    if (neorv32_mtime_get_time() >= timeout_time) { // timeout? start auto boot sequence
250
      get_exe(EXE_STREAM_FLASH); // try loading from spi flash
251
      neorv32_uart_print("\n");
252
      start_app();
253
    }
254
  }
255
  neorv32_uart_print("Aborted.\n\n");
256
  print_help();
257
 
258
 
259
  // ------------------------------------------------
260
  // Bootloader console
261
  // ------------------------------------------------
262
  while (1) {
263
 
264
    neorv32_uart_print("\nCMD:> ");
265
    char c = neorv32_uart_getc();
266
    neorv32_uart_putc(c); // echo
267
    neorv32_uart_print("\n");
268
 
269
    if (c == 'r') { // restart bootloader
270 12 zero_gravi
      neorv32_cpu_dint(); // disable global interrupts
271
      // jump to beginning of boot ROM
272
      asm volatile ("li t0, %[input_i]; jr t0" :  : [input_i] "i" (BOOTLOADER_BASE_ADDRESS));
273
      while(1); // just for the compiler
274 2 zero_gravi
    }
275
    else if (c == 'h') { // help menu
276
      print_help();
277
    }
278
    else if (c == 'u') { // get executable via UART
279
      get_exe(EXE_STREAM_UART);
280
    }
281
    else if (c == 's') { // program EEPROM from RAM
282
      save_exe();
283
    }
284
    else if (c == 'l') { // get executable from flash
285
      get_exe(EXE_STREAM_FLASH);
286
    }
287
    else if (c == 'e') { // start application program
288
      start_app();
289
    }
290
    else if (c == '?') { // credits
291
      neorv32_uart_print("by Stephan Nolting");
292
    }
293
    else { // unknown command
294
      neorv32_uart_print("Invalid CMD");
295
    }
296
  }
297
 
298 12 zero_gravi
  return 0; // bootloader should never return
299 2 zero_gravi
}
300
 
301
 
302
/**********************************************************************//**
303
 * Print help menu.
304
 **************************************************************************/
305
void print_help(void) {
306
 
307
  neorv32_uart_print("Available CMDs:\n"
308
                     " h: Help\n"
309
                     " r: Restart\n"
310
                     " u: Upload\n"
311
                     " s: Store to flash\n"
312
                     " l: Load from flash\n"
313
                     " e: Execute");
314
}
315
 
316
 
317
/**********************************************************************//**
318
 * Start application program at the beginning of instruction space.
319
 **************************************************************************/
320
void start_app(void) {
321
 
322 4 zero_gravi
  // executable available?
323
  if (neorv32_cpu_csr_read(CSR_MSCRATCH) == 0) {
324
    neorv32_uart_print("No executable available.");
325
    return;
326
  }
327
 
328 2 zero_gravi
  // no need to shutdown or reset the used peripherals
329
  // -> this will be done by application's crt0
330
 
331
  // deactivate IRQs and IRQ sources
332
  neorv32_cpu_dint();
333
  neorv32_cpu_csr_write(CSR_MIE, 0);
334
 
335
  neorv32_uart_print("Booting...\n\n");
336
 
337
  // wait for UART to finish transmitting
338
  while ((UART_CT & (1<<UART_CT_TX_BUSY)) != 0);
339
 
340 12 zero_gravi
  // reset performance counters (to benchmark actual application)
341
  asm volatile ("csrrw zero, mcycle,    zero"); // will also clear 'cycle'
342
  asm volatile ("csrrw zero, mcycleh,   zero"); // will also clear 'cycleh'
343
  asm volatile ("csrrw zero, minstret,  zero"); // will also clear 'instret'
344
  asm volatile ("csrrw zero, minstreth, zero"); // will also clear 'instreth'
345
 
346 2 zero_gravi
  // start app at instruction space base address
347
  while (1) {
348 12 zero_gravi
    register uint32_t app_base = SYSINFO_ISPACE_BASE;
349 2 zero_gravi
    asm volatile ("jalr zero, %0" : : "r" (app_base));
350
  }
351
}
352
 
353
 
354
/**********************************************************************//**
355
 * Machine system timer (MTIME) interrupt handler.
356
 * @warning Since we have no runtime environment, we have to use the interrupt attribute here. Here, and only here!
357
 **************************************************************************/
358
void __attribute__((__interrupt__)) mtime_irq_handler(void) {
359
 
360
  // make sure this was caused by MTIME IRQ
361
  uint32_t cause = neorv32_cpu_csr_read(CSR_MCAUSE);
362 12 zero_gravi
  if (cause != EXCCODE_MTI) { // raw exception code for MTI
363 2 zero_gravi
    neorv32_uart_print("\n\nEXCEPTION: ");
364
    print_hex_word(cause);
365
    neorv32_uart_print(" @ 0x");
366
    print_hex_word(neorv32_cpu_csr_read(CSR_MEPC));
367
    system_error(ERROR_SYSTEM);
368
    while(1); // freeze
369
  }
370
  else {
371
    // toggle status LED
372
    neorv32_gpio_pin_toggle(STATUS_LED);
373
    // 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
  // is instruction memory (actually, the 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
/*
436
  // Debugging stuff
437
  neorv32_uart_putc('.');
438
  print_hex_word(signature);
439
  neorv32_uart_putc('.');
440
  print_hex_word(imem_size);
441
  neorv32_uart_putc('.');
442
  print_hex_word(check);
443
  neorv32_uart_putc('.');
444
  print_hex_word(checksum);
445
  neorv32_uart_putc('.');
446
*/
447
 
448
  // error during transfer?
449
  if ((checksum + check) != 0) {
450
    system_error(ERROR_CHECKSUM);
451
  }
452
  else {
453
    neorv32_uart_print("OK");
454
    neorv32_cpu_csr_write(CSR_MSCRATCH, size); // store exe size in "global variable"
455
  }
456
}
457
 
458
 
459
/**********************************************************************//**
460
 * Store content of instruction memory to SPI flash.
461
 **************************************************************************/
462
void save_exe(void) {
463
 
464
  // size of last uploaded executable
465
  uint32_t size = neorv32_cpu_csr_read(CSR_MSCRATCH);
466
 
467
  if (size == 0) {
468
    neorv32_uart_print("No executable available.");
469
    return;
470
  }
471
 
472
  uint32_t addr = SPI_FLASH_BOOT_ADR;
473
 
474
  // info and prompt
475
  neorv32_uart_print("Write 0x");
476
  print_hex_word(size);
477
  neorv32_uart_print(" bytes to SPI flash @ 0x");
478
  print_hex_word(addr);
479
  neorv32_uart_print("? (y/n) ");
480
 
481
  char c = neorv32_uart_getc();
482
  neorv32_uart_putc(c);
483
  if (c != 'y') {
484
    return;
485
  }
486
 
487
  // check if flash ready (or available at all)
488
  if (spi_flash_read_1st_id() == 0x00) { // manufacturer ID
489
    system_error(ERROR_FLASH);
490
  }
491
 
492
  neorv32_uart_print("\nFlashing... ");
493
 
494
  // clear memory before writing
495
  uint32_t num_sectors = (size / SPI_FLASH_SECTOR_SIZE) + 1; // clear at least 1 sector
496
  uint32_t sector = SPI_FLASH_BOOT_ADR;
497
  while (num_sectors--) {
498
    spi_flash_erase_sector(sector);
499
    sector += SPI_FLASH_SECTOR_SIZE;
500
  }
501
 
502
  // write EXE signature
503
  spi_flash_write_word(addr + EXE_OFFSET_SIGNATURE, EXE_SIGNATURE);
504
 
505
  // write size
506
  spi_flash_write_word(addr + EXE_OFFSET_SIZE, size);
507
 
508
  // store data from instruction memory and update checksum
509
  uint32_t checksum = 0;
510 12 zero_gravi
  uint32_t *pnt = (uint32_t*)SYSINFO_ISPACE_BASE;
511 2 zero_gravi
  addr = addr + EXE_OFFSET_DATA;
512
  uint32_t i = 0;
513
  while (i < (size/4)) { // in words
514
    uint32_t d = (uint32_t)*pnt++;
515
    checksum += d;
516
    spi_flash_write_word(addr, d);
517
    addr += 4;
518
    i++;
519
//  if ((i & 0x000000FF) == 0) {
520
//    neorv32_uart_putc('.');
521
//  }
522
  }
523
 
524
  // write checksum (sum complement)
525
  checksum = (~checksum) + 1;
526
  spi_flash_write_word(SPI_FLASH_BOOT_ADR + EXE_OFFSET_CHECKSUM, checksum);
527
 
528
  neorv32_uart_print("OK");
529
}
530
 
531
 
532
/**********************************************************************//**
533
 * Get word from executable stream
534
 *
535
 * @param src Source of executable stream data. See #EXE_STREAM_SOURCE.
536
 * @param addr Address when accessing SPI flash.
537
 * @return 32-bit data word from stream.
538
 **************************************************************************/
539
uint32_t get_exe_word(int src, uint32_t addr) {
540
 
541
  union {
542
    uint32_t uint32;
543
    uint8_t  uint8[sizeof(uint32_t)];
544
  } data;
545
 
546
  uint32_t i;
547
  for (i=0; i<4; i++) {
548
    if (src == EXE_STREAM_UART) {
549
      data.uint8[3-i] = (uint8_t)neorv32_uart_getc();
550
    }
551
    else {
552
      data.uint8[3-i] = spi_flash_read_byte(addr + i);
553
    }
554
  }
555
 
556
  return data.uint32;
557
}
558
 
559
 
560
/**********************************************************************//**
561
 * Output system error ID and stall.
562
 *
563
 * @param[in] err_code Error code. See #ERROR_CODES.
564
 **************************************************************************/
565
void system_error(uint8_t err_code) {
566
 
567
  neorv32_uart_print("\a\nERR_"); // output error code with annoying bell sound
568
  if (err_code <= ERROR_SYSTEM) {
569
    neorv32_uart_putc('0' + ((char)err_code));
570
  }
571
  else {
572
    neorv32_uart_print("unknown");
573
  }
574
 
575
  neorv32_cpu_dint(); // deactivate IRQs
576
  neorv32_gpio_port_set(1 << STATUS_LED); // permanently light up status LED
577
 
578 13 zero_gravi
  asm volatile ("wfi"); // power-down
579 2 zero_gravi
  while(1); // freeze
580
}
581
 
582
 
583
/**********************************************************************//**
584
 * Print 32-bit number as 8-digit hexadecimal value (with "0x" suffix).
585
 *
586
 * @param[in] num Number to print as hexadecimal.
587
 **************************************************************************/
588
void print_hex_word(uint32_t num) {
589
 
590
  static const char hex_symbols[16] = "0123456789ABCDEF";
591
 
592
  neorv32_uart_print("0x");
593
 
594
  int i;
595
  for (i=0; i<8; i++) {
596
    uint32_t index = (num >> (28 - 4*i)) & 0xF;
597
    neorv32_uart_putc(hex_symbols[index]);
598
  }
599
}
600
 
601
 
602
 
603
// -------------------------------------------------------------------------------------
604
// SPI flash functions
605
// -------------------------------------------------------------------------------------
606
 
607
/**********************************************************************//**
608
 * Read byte from SPI flash.
609
 *
610
 * @param[in] addr Flash read address.
611
 * @return Read byte from SPI flash.
612
 **************************************************************************/
613
uint8_t spi_flash_read_byte(uint32_t addr) {
614
 
615
  neorv32_spi_cs_en(SPI_FLASH_CS);
616
 
617
  neorv32_spi_trans(SPI_FLASH_CMD_READ);
618 4 zero_gravi
  spi_flash_write_addr(addr);
619 2 zero_gravi
  uint8_t rdata = (uint8_t)neorv32_spi_trans(0);
620
 
621
  neorv32_spi_cs_dis(SPI_FLASH_CS);
622
 
623
  return rdata;
624
}
625
 
626
 
627
/**********************************************************************//**
628
 * Write byte to SPI flash.
629
 *
630
 * @param[in] addr SPI flash read address.
631
 * @param[in] wdata SPI flash read data.
632
 **************************************************************************/
633
void spi_flash_write_byte(uint32_t addr, uint8_t wdata) {
634
 
635 4 zero_gravi
  spi_flash_write_enable(); // allow write-access
636 2 zero_gravi
 
637
  neorv32_spi_cs_en(SPI_FLASH_CS);
638
 
639
  neorv32_spi_trans(SPI_FLASH_CMD_PAGE_PROGRAM);
640 4 zero_gravi
  spi_flash_write_addr(addr);
641 2 zero_gravi
  neorv32_spi_trans(wdata);
642
 
643
  neorv32_spi_cs_dis(SPI_FLASH_CS);
644
 
645
  while (1) {
646
    uint8_t tmp = spi_flash_read_status();
647
    if ((tmp & 0x01) == 0) { // write in progress flag cleared?
648
      break;
649
    }
650
  }
651
}
652
 
653
 
654
/**********************************************************************//**
655
 * Write word to SPI flash.
656
 *
657
 * @param addr SPI flash write address.
658
 * @param wdata SPI flash write data.
659
 **************************************************************************/
660
void spi_flash_write_word(uint32_t addr, uint32_t wdata) {
661
 
662
  union {
663
    uint32_t uint32;
664
    uint8_t  uint8[sizeof(uint32_t)];
665
  } data;
666
 
667
  data.uint32 = wdata;
668
 
669
  uint32_t i;
670
  for (i=0; i<4; i++) {
671
    spi_flash_write_byte(addr + i, data.uint8[3-i]);
672
  }
673
}
674
 
675
 
676
/**********************************************************************//**
677
 * Erase sector (64kB) at base adress.
678
 *
679
 * @param[in] addr Base address of sector to erase.
680
 **************************************************************************/
681
void spi_flash_erase_sector(uint32_t addr) {
682
 
683 4 zero_gravi
  spi_flash_write_enable(); // allow write-access
684 2 zero_gravi
 
685
  neorv32_spi_cs_en(SPI_FLASH_CS);
686
 
687
  neorv32_spi_trans(SPI_FLASH_CMD_SECTOR_ERASE);
688 4 zero_gravi
  spi_flash_write_addr(addr);
689 2 zero_gravi
 
690
  neorv32_spi_cs_dis(SPI_FLASH_CS);
691
 
692
  while (1) {
693
    uint8_t tmp = spi_flash_read_status();
694
    if ((tmp & 0x01) == 0) { // write in progress flag cleared?
695
      break;
696
    }
697
  }
698
}
699
 
700
 
701
/**********************************************************************//**
702
 * Read status register.
703
 *
704
 * @return Status register.
705
 **************************************************************************/
706
uint8_t spi_flash_read_status(void) {
707
 
708
  neorv32_spi_cs_en(SPI_FLASH_CS);
709
 
710
  neorv32_spi_trans(SPI_FLASH_CMD_READ_STATUS);
711
  uint8_t status = (uint8_t)neorv32_spi_trans(0);
712
 
713
  neorv32_spi_cs_dis(SPI_FLASH_CS);
714
 
715
  return status;
716
}
717
 
718
 
719
/**********************************************************************//**
720
 * Read first byte of ID (manufacturer ID), should be != 0x00.
721
 *
722
 * @note The first bit of the manufacturer ID is used to detect if a Flash is connected at all.
723
 *
724
 * @return First byte of ID.
725
 **************************************************************************/
726
uint8_t spi_flash_read_1st_id(void) {
727
 
728
  neorv32_spi_cs_en(SPI_FLASH_CS);
729
 
730
  neorv32_spi_trans(SPI_FLASH_CMD_READ_ID);
731
  uint8_t id = (uint8_t)neorv32_spi_trans(0);
732
 
733
  neorv32_spi_cs_dis(SPI_FLASH_CS);
734
 
735
  return id;
736
}
737
 
738
 
739
/**********************************************************************//**
740 4 zero_gravi
 * Enable flash write access.
741 2 zero_gravi
 **************************************************************************/
742 4 zero_gravi
void spi_flash_write_enable(void) {
743 2 zero_gravi
 
744
  neorv32_spi_cs_en(SPI_FLASH_CS);
745 4 zero_gravi
  neorv32_spi_trans(SPI_FLASH_CMD_WRITE_ENABLE);
746
  neorv32_spi_cs_dis(SPI_FLASH_CS);
747
}
748 2 zero_gravi
 
749
 
750 4 zero_gravi
/**********************************************************************//**
751
 * Send address word to flash.
752
 *
753
 * @param[in] addr Address word.
754
 **************************************************************************/
755
void spi_flash_write_addr(uint32_t addr) {
756
 
757
  union {
758
    uint32_t uint32;
759
    uint8_t  uint8[sizeof(uint32_t)];
760
  } address;
761
 
762
  address.uint32 = addr;
763
 
764
  neorv32_spi_trans(address.uint8[2]);
765
  neorv32_spi_trans(address.uint8[1]);
766
  neorv32_spi_trans(address.uint8[0]);
767 2 zero_gravi
}
768
 

powered by: WebSVN 2.1.0

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