0

I have written a device driver that creates 3 devices with the same file system. So basically all the 3 devices when invoked, redirect to the same file operations. There is another user program that opens individual devices one by one to access data from it. Suppose i don't close a device before accessing another, what will be the consequences?

fd1 = open("/dev/dummy1", O_RDWR);
if(fd1 < 0){
    printf("Cannot open file");
    return -1;
}

if(ioctl(fd1, DV_DAT, data) == -1){
        printf("issue in getting data\n");
    }
else{
    printf("%d\n", data);
}

fd2 = open("/dev/dummy2", O_RDWR);
if(fd2 < 0){
    printf("Cannot open file");
    return -1;
}

if(ioctl(fd2, DV_DAT, data) == -1){
        printf("issue in getting data\n");
    }
else{
    printf("%d\n", data);
}

close(fd2);

fd3 = open("/dev/dummy3", O_RDWR);
if(fd3 < 0){
    printf("Cannot open file");
    return -1;
}

if(ioctl(fd3, DV_DAT, data) == -1){
        printf("issue in getting data\n");
    }
else{
    printf("%d\n", data);
}

close(fd3);
close(fd1);

This attempt is to test out a real scenario where all the three device nodes are considered independent and can be accessed by different programs simultaneously. This is when a program has already opened the file and is working on it when another program opens the file.

What is a solution to this issue? How can i make sure that i dont end up with kernel crashes?

  • Most problems with file operations that developers lazy to think about object lifetime. The consequences you are waiting for are kernel crashes. – 0andriy Apr 29 '20 at 10:29

1 Answers1

0

I found the issue. Actually it was not the devices that were responsible for kernel crashes. At every open function of the file, i was allocating memory using kmalloc. And at every release, i was calling kfree function for the same buffer memory. So when multiple devices are invoked, the same pointer is pointing to the memory allocated. and kfree() is performed on the same pointer twice. This is a double kfree issue. I solved it by making the pointer NULL after every kfree and putting the same as a condition before doing kfree.

if(kernel_buffer){
    kfree(kernel_buffer);
    kernel_buffer = NULL;
}