Kumar Gaurav
Kumar Gaurav

Reputation: 1317

what is difference between cdev_alloc and cdev_init

I'm creating a character device. I found two way to initialize char device

cdev_alloc

and

cdev_init

According to book, if i'm embedding struct cdev in my device struct then i should use cdev_init

Can any one tell me that what are difference between them?

Upvotes: 5

Views: 7319

Answers (3)

Mahmoud Morsy
Mahmoud Morsy

Reputation: 41

you can use either:

struct cdev my_cdev;

in this case you don't need to call cdev_alloc because memory is already allocated. Instead you must call cdev_init(&my_cdev, &fops). and then my_cdev.owner = THIS_MODULE;

OR

you can use:

struct cdev *my_cdev_p;

in this case you must call cdev_alloc() to allocate memory. Then, you have to initialize my_cdev_p->ops=&fops; and my_cdev_p->owner = THIS_MODULE;. Never use cdev_init() in this case!

Note that the 2 above methods don't belong to the old mechanism.

Upvotes: 4

Kumar Gaurav
Kumar Gaurav

Reputation: 1317

According to LDD3 for using cdev_init cdev should be initialized and shouldn't be NULL, so either use struct cdev dev as suggested by kripanand or if using struct cdev *dev then allocate dev memory using kzalloc, if using kmalloc memset would be required. This is wat cdev_alloc does.

I've now replaced cdev_alloc in my code as

//vcar->dev=cdev_alloc;
vcar->dev=kzalloc(sizeof(struct cdev),GFP_KERNEL);

Upvotes: 0

user2760375
user2760375

Reputation: 2568

According to linux device drivers 3rd edition .

cdev_alloc() is a older mechanism .this is used for getting cdev structure at runtime of your character driver module .then you have to manually assign operation to ops variable to cdev structure .However cdev_init is the new mechanism in this we have to pass cdev structure variable (or already initialized cdev structure pointer) and file operation variable,for information go here

http://lwn.net/Kernel/LDD3/

chapter 3

Upvotes: 1

Related Questions