dee
dee

Reputation: 95

explain devm_kzalloc parameters and usage

I am new to kernel driver programming and would like to understand few aspects.

In the below code from http://lxr.free-electrons.com/source/drivers/i2c/busses/i2c-ocores.c?v=3.19

static int ocores_i2c_probe(struct platform_device *pdev)
{
   struct ocores_i2c *i2c;
    i2c = devm_kzalloc(&pdev->dev, sizeof(*i2c), GFP_KERNEL);
}
  1. pdev is pointer to a platform device. The content of the structure to which pdev is pointing to is already created when platform device is initialized and driver core will pass that information to this probe function. ?? This is the same with pci dev structure where driver core is passing pci_dev it identified during probe for driver to use? Is my understanding right?
  2. I am not clear on the parameters of devm_kzalloc. what does "Device to allocate memory for" mean at line 763 http://lxr.free-electrons.com/source/drivers/base/devres.c?v=3.19#L774 ? At the end of the day we just need to allocate memory in kernel of size struct ocores_i2c. Is the first parameter used as a tracking mechanism to free it later automatically (based on reading devres kernel documentation)?
  3. return value of devm_kzalloc is pointer to newly allocated memory of size ocores_i2c in kernel. If this is the case shouldnt the second parameter of devm_kzalloc be sizeof(struct ocores_i2c) instead of sizeof(*i2c )?

Upvotes: 2

Views: 2623

Answers (1)

slugonamission
slugonamission

Reputation: 9642

1) Yes, the kernel will fill out this structure for you and then pass it to your probe function to perform initialisation.

2) In short, all of the devm_ suite of functions will tie the lifecycle of the returned resource to the lifecycle of the actual device. Any returned resources will therefore be automatically cleaned up when the specified device is un-probed.

3) Probably, yes, although the sizeof operator will follow the definition of i2c, so this is actually basically the same as sizeof(struct ocores_i2c).

Upvotes: 2

Related Questions