Here is a simple example of how to allocate and register a DMA device and start a DMA transfer in Linux Kernel 4.19 using the platform_device_alloc() function:
#include <linux/platform_device.h>
#include <linux/dmaengine.h>
// Define the DMA device configuration
static struct {
int id;
int channel;
int irq;
void *data;
} my_dma_device = {
.id = 1,
.channel = 0,
.irq = 10,
.data = NULL,
};
// Define the platform device structure
static struct platform_device my_platform_device = {
.dev = {
.name = "my_dma_device",
},
.id = -1,
.num_resources = 0,
.resource = NULL,
};
static int __init my_init(void)
{
struct dma_chan *chan;
struct scatterlist sg;
dma_cookie_t cookie;
int ret;
// Allocate and register the platform device
ret = platform_device_register(&my_platform_device);
if (ret) {
printk(KERN_ERR "Failed to register the platform device\n");
return ret;
}
// Get the DMA channel for the device
chan = dma_request_slave_channel(&my_platform_device.dev, "mem2dev");
if (!chan) {
printk(KERN_ERR "Failed to get the DMA channel\n");
return -ENODEV;
}
// Prepare the scatterlist to transfer data
sg_init_one(&sg, my_dma_device.data, sizeof(my_dma_device.data));
// Start the DMA transfer
cookie = dmaengine_prep_slave_sg(chan, &sg, 1, DMA_TO_DEVICE, DMA_PREP_INTERRUPT);
if (dma_submit_error(cookie)) {
printk(KERN_ERR "Failed to prepare the DMA transfer\n");
ret = -EINVAL;
goto out;
}
// Wait for the DMA transfer to complete
ret = dma_sync_wait(chan, cookie);
if (ret) {
printk(KERN_ERR "DMA transfer failed with error %d\n", ret);
}
out:
dma_release_channel(chan);
return ret;
}
static void __exit my_exit(void)
{
// Unregister the platform device
platform_device_unregister(&my_platform_device);
}
module_init(my_init);
module_exit(my_exit);
MODULE_AUTHOR("Your Name");
MODULE_DESCRIPTION("Example DMA device driver");
MODULE_LICENSE("GPL");
In this example, we define a DMA device configuration struct called my_dma_device. We also define a platform device struct called my_platform_device that wraps around the DMA device. We then use the platform_device_register() function to allocate and register the platform device.
We retrieve the DMA channel for the device using the dma_request_slave_channel() function. We then prepare a scatterlist sg that describes the data to be transferred. We use the dmaengine_prep_slave_sg() function to prepare the DMA transfer, passing in the scatterlist, the transfer direction (DMA_TO_DEVICE in this case), and the DMA_PREP_INTERRUPT flag to request an interrupt when the transfer is complete.
We submit the DMA transfer using the dma_submit_error() function and wait for it to complete using the dma_sync_wait() function. Finally, we release the DMA channel using the dma_release_channel() function and unregister the platform device using the platform_device_unregister() function.
Note that this is just an example and the configuration values and transfer details would need to be customized for the specific DMA device being used.