loader.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. // SPDX-License-Identifier: BSD-2-Clause
  2. /*
  3. * Copyright (c) 2022 Matthias Schiffer <[email protected]>
  4. */
  5. #include <image.h>
  6. #include <init.h>
  7. #include <spi.h>
  8. #include <spi-nor.h>
  9. #include <stdio.h>
  10. #include <string.h>
  11. static bool check_image_header(const image_header_t *header)
  12. {
  13. if (header->ih_magic != cpu_to_be32(IH_MAGIC_OKLI)) {
  14. puts("Invalid image magic\n");
  15. return false;
  16. }
  17. if (header->ih_comp != cpu_to_be32(IH_COMP_NONE)) {
  18. puts("Unsupported compressed image\n");
  19. return false;
  20. }
  21. return true;
  22. }
  23. static uint32_t do_load(void)
  24. {
  25. image_header_t header;
  26. uint32_t ih_size, ih_load, ih_ep;
  27. if (spi_nor_read_id())
  28. return UINT32_MAX;
  29. puts("Reading image header...\n");
  30. if (spi_nor_read_data(&header, CONFIG_IMAGE_OFFSET, sizeof(header)))
  31. return UINT32_MAX;
  32. if (!check_image_header(&header))
  33. return UINT32_MAX;
  34. header.ih_name[sizeof(header.ih_name) - 1] = 0;
  35. ih_size = be32_to_cpu(header.ih_size);
  36. ih_load = be32_to_cpu(header.ih_load);
  37. ih_ep = be32_to_cpu(header.ih_ep);
  38. put_with_label("Image Name: ", puts, (const char *)header.ih_name);
  39. put_with_label("Data Size: ", put_u32, ih_size);
  40. put_with_label("Load Address: ", put_u32, ih_load);
  41. put_with_label("Entry Point: ", put_u32, ih_ep);
  42. puts("Reading image data...\n");
  43. void *loadaddr = (void *)ih_load;
  44. if (spi_nor_read_data(loadaddr, CONFIG_IMAGE_OFFSET + sizeof(header),
  45. ih_size))
  46. return false;
  47. flush_cache(loadaddr, ih_size);
  48. return ih_ep;
  49. }
  50. static void enter_image(uint32_t addr)
  51. {
  52. typedef void (*entry_t)(void);
  53. entry_t entry = (entry_t)addr;
  54. puts("Starting image...\n");
  55. entry();
  56. }
  57. static void load(void)
  58. {
  59. uint32_t addr;
  60. int ret;
  61. ret = spi_init(0, CONFIG_SPI_MAX_HZ, SPI_MODE_0);
  62. if (ret) {
  63. puts("Failed to initialize SPI controller\n");
  64. return;
  65. }
  66. ret = spi_claim_bus();
  67. if (ret) {
  68. puts("Failed to enable SPI controller\n");
  69. return;
  70. }
  71. addr = do_load();
  72. spi_release_bus();
  73. if (addr != UINT32_MAX)
  74. enter_image(addr);
  75. }
  76. void start(void)
  77. {
  78. serial_console_init();
  79. puts("=== " CONFIG_PROGRAM_NAME " ===\n");
  80. load();
  81. puts("Halting execution.\n");
  82. while (true) {}
  83. }