bouncebuf.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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(struct bounce_buffer *state, void *data,
  29. size_t len, unsigned int flags)
  30. {
  31. state->user_buffer = data;
  32. state->bounce_buffer = data;
  33. state->len = len;
  34. state->len_aligned = roundup(len, ARCH_DMA_MINALIGN);
  35. state->flags = flags;
  36. if (!addr_aligned(state)) {
  37. state->bounce_buffer = memalign(ARCH_DMA_MINALIGN,
  38. state->len_aligned);
  39. if (!state->bounce_buffer)
  40. return -ENOMEM;
  41. if (state->flags & GEN_BB_READ)
  42. memcpy(state->bounce_buffer, state->user_buffer,
  43. state->len);
  44. }
  45. /*
  46. * Flush data to RAM so DMA reads can pick it up,
  47. * and any CPU writebacks don't race with DMA writes
  48. */
  49. flush_dcache_range((unsigned long)state->bounce_buffer,
  50. (unsigned long)(state->bounce_buffer) +
  51. state->len_aligned);
  52. return 0;
  53. }
  54. int bounce_buffer_stop(struct bounce_buffer *state)
  55. {
  56. if (state->flags & GEN_BB_WRITE) {
  57. /* Invalidate cache so that CPU can see any newly DMA'd data */
  58. invalidate_dcache_range((unsigned long)state->bounce_buffer,
  59. (unsigned long)(state->bounce_buffer) +
  60. state->len_aligned);
  61. }
  62. if (state->bounce_buffer == state->user_buffer)
  63. return 0;
  64. if (state->flags & GEN_BB_WRITE)
  65. memcpy(state->user_buffer, state->bounce_buffer, state->len);
  66. free(state->bounce_buffer);
  67. return 0;
  68. }