#include #include #include #include #include #include #include struct mem_ioctl_data { unsigned long requested_size; unsigned long start_of_vma; unsigned long return_offset; }; void * dma_malloc(unsigned int size) { int fd = -1; unsigned int retval; int mmap_size; struct mem_ioctl_data mid; void * mmaprv; printf("\ndma_malloc called with size %u\n", size); if ((fd = open("/dev/my_module", O_RDWR)) < 0) { perror("open failed for /dev/my_module"); return NULL; } else { //printf("\nopen succeeded\n"); } mmap_size = (size/4096) + 1; printf("\nmmap_size = 0x%x\n", mmap_size); mmaprv = mmap(0, mmap_size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0); if(mmaprv == MAP_FAILED) { printf("\nmmap failed\n"); perror("mmap failure"); return NULL; } else { printf("\nmmap succeeded mmaprv = 0x%p\n", mmaprv); } mid.requested_size = size; mid.start_of_vma = (unsigned long)mmaprv; mid.return_offset = 0xffffffff; retval = ioctl(fd, 1, &mid); if(retval) { perror("ioctl failed"); return NULL; } else { printf("\nioctl succeeded\n"); } if(mid.return_offset == 0xffffffff) { printf("\nmid.return_offset = 0x%lx\n", mid.return_offset); return NULL; } printf("\nmid.return_offset = 0x%lx\n", mid.return_offset); return (void *)(mmaprv + mid.return_offset); } int main(int argc, char * argv[]) { unsigned int size; char *cptr; void * ptr; printf("\nEnter the size of allocation ...\n"); while (scanf("%u", &size)) { printf("\nSize asked is %u\n", size); ptr = dma_malloc(size); if (ptr == NULL) { printf("\ndma_malloc failed for size %d ptr = 0x%p\n\n", size, ptr); return 0; } else { printf("\ndma_malloc succeeded for size %d ptr = 0x%p\n\n", size, ptr); } cptr = (char *)ptr; /* * This should print the signature that we wrote to the kmalloc'ed * area in the driver */ printf("\nptr = 0x%lx\n", *(unsigned long *)ptr); } return 0; }