bouncebuf.c 2.2 KB

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