我正在编写一个使用 I2C 与主机通信的设备驱动程序。
下面是我想学习和理解的代码。如果我对以下代码的理解有误,请帮帮我。“//”是我自己的评论和我对代码的理解。
// declare there will be a member struct inside the class example_state. This member is pointing to i2c_client.
struct example_state {
struct i2c_client *client;
};
static int example_probe(struct i2c_client *client, const struct i2c_device_id *id{
// declare this to be a local struct inside the example_probe
struct example_state *state;
// get "struct device" to be pointed client's member name dev
// Question: is "struct device *dev" part of "struct i2c_client"?
// if "struct device *dev" imported from somewhere that why there is no need to allocate memory?
struct device *dev = &client->dev;
// allocate a memory space for "struct example_state"
// at this point "struct example_state" is still empty/NULL
// **Question:** but what is the relationship of this local "struct example_state"
// with the one declared before entering struct example_state function?
state = kzalloc(sizeof(struct example_state), GFP_KERNEL);
if (state == NULL) {
dev_err(dev, "failed to create our state\n");
return -ENOMEM;
}
// after memory allocated set the "struct i2c_client" point to "struct example_state"'s member namely "client".
state->client = client;
// set the our device I2C driver information to the host.
// Question: Where to we set our device driver data?
i2c_set_clientdata(client, state);
/* rest of the initialisation goes here. */
dev_info(dev, "example client created\n");
return 0;
}
static int __devexit example_remove(struct i2c_client *client){
// get the loaded value from host, i guess is like unregister
// my device driver information from the host when i exited.
struct example_state *state = i2c_get_clientdata(client);
kfree(state);
return 0;
}
static struct i2c_device_id example_idtable[] = {
{ "example", 0 },
{ }
};