bouncebuf.c 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. /*
  2. * Generic bounce buffer implementation
  3. *
  4. * Copyright (C) 2012 Marek Vasut <marex@denx.de>
  5. *
  6. * See file CREDITS for list of people who contributed to this
  7. * project.
  8. *
  9. * This program is free software; you can redistribute it and/or
  10. * modify it under the terms of the GNU General Public License as
  11. * published by the Free Software Foundation; either version 2 of
  12. * the License, or (at your option) any later version.
  13. *
  14. * This program is distributed in the hope that it will be useful,
  15. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. * GNU General Public License for more details.
  18. *
  19. * You should have received a copy of the GNU General Public License
  20. * along with this program; if not, write to the Free Software
  21. * Foundation, Inc., 59 Temple Place, Suite 330, Boston,
  22. * MA 02111-1307 USA
  23. */
  24. #include <common.h>
  25. #include <malloc.h>
  26. #include <errno.h>
  27. #include <bouncebuf.h>
  28. static int addr_aligned(void *data, size_t len)
  29. {
  30. const ulong align_mask = ARCH_DMA_MINALIGN - 1;
  31. /* Check if start is aligned */
  32. if ((ulong)data & align_mask) {
  33. debug("Unaligned start address %p\n", data);
  34. return 0;
  35. }
  36. data += len;
  37. /* Check if end is aligned */
  38. if ((ulong)data & align_mask) {
  39. debug("Unaligned end address %p\n", data);
  40. return 0;
  41. }
  42. /* Aligned */
  43. return 1;
  44. }
  45. int bounce_buffer_start(void **data, size_t len, void **backup, uint8_t flags)
  46. {
  47. void *tmp;
  48. size_t alen;
  49. if (addr_aligned(*data, len)) {
  50. *backup = NULL;
  51. return 0;
  52. }
  53. alen = roundup(len, ARCH_DMA_MINALIGN);
  54. tmp = memalign(ARCH_DMA_MINALIGN, alen);
  55. if (!tmp)
  56. return -ENOMEM;
  57. if (flags & GEN_BB_READ)
  58. memcpy(tmp, *data, len);
  59. *backup = *data;
  60. *data = tmp;
  61. return 0;
  62. }
  63. int bounce_buffer_stop(void **data, size_t len, void **backup, uint8_t flags)
  64. {
  65. void *tmp = *data;
  66. /* The buffer was already aligned, since "backup" is NULL. */
  67. if (!*backup)
  68. return 0;
  69. if (flags & GEN_BB_WRITE)
  70. memcpy(*backup, *data, len);
  71. *data = *backup;
  72. free(tmp);
  73. return 0;
  74. }