In the code of Linux driver, we often see the functions in the title. So how does this function work, and what does it do? Let's take a look at the implementation of this function in detail.
DRIVER/BASE/DD.C 1. void *dev_get_drvdata (const struct device *dev) 2. {3. if (dev && dev->p) {4. Return dev->p->driver_data;5. Return null;6. }
From the 4th line of code, we can see that this function mainly returns the Device->p->driver_data pointer. So, let's take a look at the more important device structure in kernel, which is actually an abstract representation of all the devices in the kernel. All devices have a device instance that corresponds to it, and the main use of the machine structure is to embed it in other device structures, such as platform_device. At the same time, the device structure is responsible for the interaction between subsystems as a unified parameter. So, let's take a look at the composition of the device structure.
Include/linux/device.h
struct Device {struct device *parent; struct Device_private *p; The data struct Kobject kobj is responsible for preserving driver core; const char *init_name; .... struct device_driver *driver; #ifdef config_pinctrl struct dev_pin_info *pins; #endfi .... struct Device_node *of_node; Responsible for saving the corresponding node address in device_tree .... const struct Attribute_group **groups; ......}
struct Device_private {struct klist klist_children; struct Klist_node knode_parent; struct Klist_node knode_driver; struct Klist_node Knode_bus; struct List_head deferred_probe; void *driver_data; Responsible for preserving the corresponding driver_data struct device *device in driver;} So, when did the Driver_data initialize? By tracing the code, we can find that the initialization of general driver_data occurs in the probe function in the driver file.
In the probe function, malloc finishes the corresponding driver data struct, populates the corresponding domain, and assigns the address of driver data to driver data. In this way, when implementing interfaces that interact with other subsystems, the corresponding driver data can be found through the device pointers passed by other subsystems.
Dev_get_drvdata () function