bouncebuf.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. // SPDX-License-Identifier: GPL-2.0+
  2. /*
  3. * Generic bounce buffer implementation
  4. *
  5. * Copyright (C) 2012 Marek Vasut <marex@denx.de>
  6. */
  7. #include <common.h>
  8. #include <cpu_func.h>
  9. #include <malloc.h>
  10. #include <errno.h>
  11. #include <bouncebuf.h>
  12. static int addr_aligned(struct bounce_buffer *state)
  13. {
  14. const ulong align_mask = ARCH_DMA_MINALIGN - 1;
  15. /* Check if start is aligned */
  16. if ((ulong)state->user_buffer & align_mask) {
  17. debug("Unaligned buffer address %p\n", state->user_buffer);
  18. return 0;
  19. }
  20. /* Check if length is aligned */
  21. if (state->len != state->len_aligned) {
  22. debug("Unaligned buffer length %zu\n", state->len);
  23. return 0;
  24. }
  25. /* Aligned */
  26. return 1;
  27. }
  28. int bounce_buffer_start_extalign(struct bounce_buffer *state, void *data,
  29. size_t len, unsigned int flags,
  30. size_t alignment,
  31. int (*addr_is_aligned)(struct bounce_buffer *state))
  32. {
  33. state->user_buffer = data;
  34. state->bounce_buffer = data;
  35. state->len = len;
  36. state->len_aligned = roundup(len, alignment);
  37. state->flags = flags;
  38. if (!addr_is_aligned(state)) {
  39. state->bounce_buffer = memalign(alignment,
  40. state->len_aligned);
  41. if (!state->bounce_buffer)
  42. return -ENOMEM;
  43. if (state->flags & GEN_BB_READ)
  44. memcpy(state->bounce_buffer, state->user_buffer,
  45. state->len);
  46. }
  47. /*
  48. * Flush data to RAM so DMA reads can pick it up,
  49. * and any CPU writebacks don't race with DMA writes
  50. */
  51. flush_dcache_range((unsigned long)state->bounce_buffer,
  52. (unsigned long)(state->bounce_buffer) +
  53. state->len_aligned);
  54. return 0;
  55. }
  56. int bounce_buffer_start(struct bounce_buffer *state, void *data,
  57. size_t len, unsigned int flags)
  58. {
  59. return bounce_buffer_start_extalign(state, data, len, flags,
  60. ARCH_DMA_MINALIGN,
  61. addr_aligned);
  62. }
  63. int bounce_buffer_stop(struct bounce_buffer *state)
  64. {
  65. if (state->flags & GEN_BB_WRITE) {
  66. /* Invalidate cache so that CPU can see any newly DMA'd data */
  67. invalidate_dcache_range((unsigned long)state->bounce_buffer,
  68. (unsigned long)(state->bounce_buffer) +
  69. state->len_aligned);
  70. }
  71. if (state->bounce_buffer == state->user_buffer)
  72. return 0;
  73. if (state->flags & GEN_BB_WRITE)
  74. memcpy(state->user_buffer, state->bounce_buffer, state->len);
  75. free(state->bounce_buffer);
  76. return 0;
  77. }