bouncebuf.c 1.9 KB

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