5.2 probe方法
我们来看看spidev_probe这个函数,该函数位于drivers/spi/spidev.c。
- #define SPIDEV_MAJOR 153 /* assigned */
- #define N_SPI_MINORS 32 /* ... up to 256 */
- static unsigned long minors[N_SPI_MINORS / BITS_PER_LONG]; /**/
- static LIST_HEAD(device_list);
- static DEFINE_MUTEX(device_list_lock);
- static int spidev_probe(struct spi_device *spi)
- {
- struct spidev_data *spidev;
- int status;
- unsigned long minor;
- /* Allocate driver data */
- spidev = kzalloc(sizeof(*spidev), GFP_KERNEL); /*以kmalloc分配内存,并清0*/
- if (!spidev)
- return -ENOMEM;
- /* Initialize the driver data */
- spidev->spi = spi; /*保存spi_device*/
- spin_lock_init(&spidev->spi_lock); /*初始化自旋锁*/
- mutex_init(&spidev->buf_lock); /*初始化互斥体*/
- INIT_LIST_HEAD(&spidev->device_entry); /*初始化链表头,链表为双向循环链表*/
- /* If we can allocate a minor number, hook up this device.
- * Reusing minors is fine so long as udev or mdev is working.
- */
- mutex_lock(&device_list_lock); /*上锁*/
- minor = find_first_zero_bit(minors, N_SPI_MINORS); /*分配次设备号*/
- if (minor < N_SPI_MINORS) {
- struct device *dev;
- spidev->devt = MKDEV(SPIDEV_MAJOR, minor); /*根据主次设备号来获取设备号*/
- dev = device_create(spidev_class, &spi->dev, spidev->devt, /*创建设备节点*/
- spidev, "spidev%d.%d",
- spi->master->bus_num, spi->chip_select);
- status = IS_ERR(dev) ? PTR_ERR(dev) : 0;
- } else {
- dev_dbg(&spi->dev, "no minor number available!\n");
- status = -ENODEV;
- }
- if (status == 0) {
- set_bit(minor, minors); /*保存已使用的次设备号*/
- list_add(&spidev->device_entry, &device_list);/*在链表头list后面添加entry*/
- }
- mutex_unlock(&device_list_lock);/*解锁互斥体*/
- if (status == 0)
- spi_set_drvdata(spi, spidev);/*spi->dev.driver_data=spidev*/
- else
- kfree(spidev);
- return status;
- }
其中用到的的struct spidev_data结构如下:
- struct spidev_data {
- dev_t devt;
- spinlock_t spi_lock;
- struct spi_device *spi;
- struct list_head device_entry;
- /* buffer is NULL unless this device is open (users > 0) */
- struct mutex buf_lock;
- unsigned users;
- u8 *buffer;
- };
这个函数中,分配了spidev_data和次设备号,随后根据主次设备号创建了设备节点。设备节点的名字是spidev“bus_num””.chip_select",意思就是该设备是在第几个SPI接口上的第几个设备。
此外,将spidev添加到device_list中,这样做就方便查找该spidev。
