i2c-mxv7.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /*
  2. * Copyright (C) 2012 Boundary Devices Inc.
  3. *
  4. * SPDX-License-Identifier: GPL-2.0+
  5. */
  6. #include <common.h>
  7. #include <asm/arch/clock.h>
  8. #include <asm/arch/imx-regs.h>
  9. #include <asm/errno.h>
  10. #include <asm/gpio.h>
  11. #include <asm/imx-common/mxc_i2c.h>
  12. #include <watchdog.h>
  13. static int force_idle_bus(void *priv)
  14. {
  15. int i;
  16. int sda, scl;
  17. ulong elapsed, start_time;
  18. struct i2c_pads_info *p = (struct i2c_pads_info *)priv;
  19. int ret = 0;
  20. gpio_direction_input(p->sda.gp);
  21. gpio_direction_input(p->scl.gp);
  22. imx_iomux_v3_setup_pad(p->sda.gpio_mode);
  23. imx_iomux_v3_setup_pad(p->scl.gpio_mode);
  24. sda = gpio_get_value(p->sda.gp);
  25. scl = gpio_get_value(p->scl.gp);
  26. if ((sda & scl) == 1)
  27. goto exit; /* Bus is idle already */
  28. printf("%s: sda=%d scl=%d sda.gp=0x%x scl.gp=0x%x\n", __func__,
  29. sda, scl, p->sda.gp, p->scl.gp);
  30. /* Send high and low on the SCL line */
  31. for (i = 0; i < 9; i++) {
  32. gpio_direction_output(p->scl.gp, 0);
  33. udelay(50);
  34. gpio_direction_input(p->scl.gp);
  35. udelay(50);
  36. }
  37. start_time = get_timer(0);
  38. for (;;) {
  39. sda = gpio_get_value(p->sda.gp);
  40. scl = gpio_get_value(p->scl.gp);
  41. if ((sda & scl) == 1)
  42. break;
  43. WATCHDOG_RESET();
  44. elapsed = get_timer(start_time);
  45. if (elapsed > (CONFIG_SYS_HZ / 5)) { /* .2 seconds */
  46. ret = -EBUSY;
  47. printf("%s: failed to clear bus, sda=%d scl=%d\n",
  48. __func__, sda, scl);
  49. break;
  50. }
  51. }
  52. exit:
  53. imx_iomux_v3_setup_pad(p->sda.i2c_mode);
  54. imx_iomux_v3_setup_pad(p->scl.i2c_mode);
  55. return ret;
  56. }
  57. static void * const i2c_bases[] = {
  58. (void *)I2C1_BASE_ADDR,
  59. (void *)I2C2_BASE_ADDR,
  60. #ifdef I2C3_BASE_ADDR
  61. (void *)I2C3_BASE_ADDR,
  62. #endif
  63. };
  64. /* i2c_index can be from 0 - 2 */
  65. void setup_i2c(unsigned i2c_index, int speed, int slave_addr,
  66. struct i2c_pads_info *p)
  67. {
  68. if (i2c_index >= ARRAY_SIZE(i2c_bases))
  69. return;
  70. /* Enable i2c clock */
  71. enable_i2c_clk(1, i2c_index);
  72. /* Make sure bus is idle */
  73. force_idle_bus(p);
  74. bus_i2c_init(i2c_bases[i2c_index], speed, slave_addr,
  75. force_idle_bus, p);
  76. }