dma_alloc.c 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /* $OpenBSD: dma_alloc.c,v 1.12 2014/07/08 17:19:25 deraadt Exp $ */
  2. /*
  3. * Copyright (c) 2010 Theo de Raadt <deraadt@openbsd.org>
  4. *
  5. * Permission to use, copy, modify, and distribute this software for any
  6. * purpose with or without fee is hereby granted, provided that the above
  7. * copyright notice and this permission notice appear in all copies.
  8. *
  9. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  10. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  11. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  12. * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  13. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  14. * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  15. * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  16. */
  17. #include <sys/param.h>
  18. #include <sys/systm.h>
  19. #include <sys/pool.h>
  20. #include <uvm/uvm_extern.h>
  21. static __inline int dma_alloc_index(size_t size);
  22. /* Create dma pools from objects sized 2^4 to 2^16 */
  23. #define DMA_PAGE_SHIFT 16
  24. #define DMA_BUCKET_OFFSET 4
  25. static char dmanames[DMA_PAGE_SHIFT - DMA_BUCKET_OFFSET + 1][10];
  26. struct pool dmapools[DMA_PAGE_SHIFT - DMA_BUCKET_OFFSET + 1];
  27. void
  28. dma_alloc_init(void)
  29. {
  30. int i;
  31. for (i = 0; i < nitems(dmapools); i++) {
  32. snprintf(dmanames[i], sizeof(dmanames[0]), "dma%d",
  33. 1 << (i + DMA_BUCKET_OFFSET));
  34. pool_init(&dmapools[i], 1 << (i + DMA_BUCKET_OFFSET), 0, 0, 0,
  35. dmanames[i], NULL);
  36. pool_set_constraints(&dmapools[i], &kp_dma_contig);
  37. pool_setipl(&dmapools[i], IPL_VM);
  38. /* XXX need pool_setlowat(&dmapools[i], dmalowat); */
  39. }
  40. }
  41. static __inline int
  42. dma_alloc_index(size_t sz)
  43. {
  44. int b;
  45. for (b = 0; b < nitems(dmapools); b++)
  46. if (sz <= (1 << (b + DMA_BUCKET_OFFSET)))
  47. return (b);
  48. #ifdef DEBUG
  49. printf("dma_alloc/free: object %zd too large\n", sz);
  50. #endif
  51. return (-1);
  52. }
  53. void *
  54. dma_alloc(size_t size, int prflags)
  55. {
  56. int pi = dma_alloc_index(size);
  57. if (pi == -1)
  58. return (NULL);
  59. return pool_get(&dmapools[pi], prflags);
  60. }
  61. void
  62. dma_free(void *m, size_t size)
  63. {
  64. int pi = dma_alloc_index(size);
  65. if (pi == -1)
  66. return;
  67. pool_put(&dmapools[pi], m);
  68. }