wait_bit.h 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /* SPDX-License-Identifier: GPL-2.0+ */
  2. /*
  3. * Wait for bit with timeout and ctrlc
  4. *
  5. * (C) Copyright 2015 Mateusz Kulikowski <mateusz.kulikowski@gmail.com>
  6. */
  7. #ifndef __WAIT_BIT_H
  8. #define __WAIT_BIT_H
  9. #include <console.h>
  10. #include <log.h>
  11. #include <time.h>
  12. #include <watchdog.h>
  13. #include <linux/delay.h>
  14. #include <linux/errno.h>
  15. #include <asm/io.h>
  16. /**
  17. * wait_for_bit_x() waits for bit set/cleared in register
  18. *
  19. * Function polls register waiting for specific bit(s) change
  20. * (either 0->1 or 1->0). It can fail under two conditions:
  21. * - Timeout
  22. * - User interaction (CTRL-C)
  23. * Function succeeds only if all bits of masked register are set/cleared
  24. * (depending on set option).
  25. *
  26. * @param reg Register that will be read (using read_x())
  27. * @param mask Bit(s) of register that must be active
  28. * @param set Selects wait condition (bit set or clear)
  29. * @param timeout_ms Timeout (in milliseconds)
  30. * @param breakable Enables CTRL-C interruption
  31. * @return 0 on success, -ETIMEDOUT or -EINTR on failure
  32. */
  33. #define BUILD_WAIT_FOR_BIT(sfx, type, read) \
  34. \
  35. static inline int wait_for_bit_##sfx(const void *reg, \
  36. const type mask, \
  37. const bool set, \
  38. const unsigned int timeout_ms, \
  39. const bool breakable) \
  40. { \
  41. type val; \
  42. unsigned long start = get_timer(0); \
  43. \
  44. while (1) { \
  45. val = read(reg); \
  46. \
  47. if (!set) \
  48. val = ~val; \
  49. \
  50. if ((val & mask) == mask) \
  51. return 0; \
  52. \
  53. if (get_timer(start) > timeout_ms) \
  54. break; \
  55. \
  56. if (breakable && ctrlc()) { \
  57. puts("Abort\n"); \
  58. return -EINTR; \
  59. } \
  60. \
  61. udelay(1); \
  62. WATCHDOG_RESET(); \
  63. } \
  64. \
  65. debug("%s: Timeout (reg=%p mask=%x wait_set=%i)\n", __func__, \
  66. reg, mask, set); \
  67. \
  68. return -ETIMEDOUT; \
  69. }
  70. BUILD_WAIT_FOR_BIT(8, u8, readb)
  71. BUILD_WAIT_FOR_BIT(le16, u16, readw)
  72. BUILD_WAIT_FOR_BIT(16, u16, readw)
  73. #ifdef readw_be
  74. BUILD_WAIT_FOR_BIT(be16, u16, readw_be)
  75. #endif
  76. BUILD_WAIT_FOR_BIT(le32, u32, readl)
  77. BUILD_WAIT_FOR_BIT(32, u32, readl)
  78. #ifdef readl_be
  79. BUILD_WAIT_FOR_BIT(be32, u32, readl_be)
  80. #endif
  81. #endif