io.h 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. #ifndef IO_H
  2. #define IO_H
  3. #include <stdint.h>
  4. #include <stdarg.h>
  5. #include <stdbool.h>
  6. #include "ioregs.h"
  7. #include "picorv32.h"
  8. #include "irq.h"
  9. #define barrier() do { asm volatile("" : : : "memory"); } while (0)
  10. static __always_inline void pause(void)
  11. {
  12. /* Placeholder for anything that might want to be done while waiting */
  13. }
  14. static __always_inline void set_leds(unsigned int leds)
  15. {
  16. SYS_LED = leds;
  17. }
  18. static __always_inline void set_led(unsigned int led, bool on)
  19. {
  20. unsigned int leds = SYS_LED;
  21. unsigned int mask = 1 << led;
  22. leds &= ~mask;
  23. leds |= on ? mask : 0;
  24. SYS_LED = leds;
  25. }
  26. enum leds {
  27. LED_SDCARD,
  28. LED_DISKIO,
  29. LED_ABCBUS
  30. };
  31. static __always_inline no_return reset(unsigned int type)
  32. {
  33. p_maskirq(~0, 0); /* Block all interrupts */
  34. for (;;)
  35. SYS_RESET = type;
  36. }
  37. extern const uint32_t time_zero;
  38. static __always_inline uint32_t rdtime(void)
  39. {
  40. uint32_t t;
  41. asm volatile("rdtime %0" : "=r" (t));
  42. return t;
  43. }
  44. static __always_inline uint64_t rdtimeq(void)
  45. {
  46. uint32_t l, h1, h0;
  47. asm volatile("rdtimeh %0; rdtime %1; %rdtimeh %2"
  48. : "=r" (h1), "=r" (l), "=r" (h0));
  49. return ((uint64_t)(((int32_t)l < 0) ? h1 : h0) << 32) + l;
  50. }
  51. static __always_inline void udelay(uint32_t us)
  52. {
  53. uint32_t cycles = us * (CPU_HZ / 1000000);
  54. uint32_t start = rdtime();
  55. while (rdtime() - start < cycles)
  56. pause();
  57. }
  58. static inline void i2c_set_speed(unsigned int khz)
  59. {
  60. I2C_DIVISOR = ((CPU_HZ/4000)-1)/khz;
  61. }
  62. static __always_inline void wait_romcopy_done(void)
  63. {
  64. while (~irqmask() & (1 << ROMCOPY_IRQ))
  65. pause();
  66. barrier();
  67. }
  68. /* Read a random 32-bit number */
  69. static inline uint32_t rdrand(void)
  70. {
  71. waitfor(RANDOM_IRQ);
  72. return RANDOM_DATA;
  73. }
  74. #endif /* IO_H */