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