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

Subversion Repositories neorv32

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

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

powered by: WebSVN 2.1.0

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