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

Subversion Repositories neorv32

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

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

powered by: WebSVN 2.1.0

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