Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux device driver, Is it possible to get the minor number using a file descriptor?

I am writing a device driver for Linux. It creates a device with 4 minor numbers. Whenever we attempt to write to the device at minor number 3, we are suppose to kill the device and currently it isn't suppose to do anything else except print it is writing to the booga device. Here is some of my current code and I can post more code if necessary:

Write method:

static ssize_t booga_write (struct file *filp, const char *buf, size_t count, loff_t *f_pose) {
    printk("Attempting to write to booga device\n");
    /* need to protect this with a semaphore if multiple processes
       will invoke this driver to prevent a race condition */

    if (down_interruptible (&booga_device_stats->sem))
        return (-ERESTARTSYS);
    booga_device_stats->num_bytes_written += count; 
    up(&booga_device_stats->sem);
    return count; // pretend that count bytes were written

}

How it is tested:

static void run_write_test(char *device, int bufsize)
{
    char *buf;
    int src;
    int out;

    src = open(device, O_WRONLY);
    if (src < 0) {
        perror("Open for write failed:");
        exit(1);
    }
    buf = (char *) malloc(sizeof(char)*(bufsize+1));
    fprintf(stderr, "Attempting to write to booga device\n");
    out = write(src, buf, bufsize);
    fprintf(stderr, "Wrote %d bytes.\n", out);
    free(buf);
    close(src);

}

I am wondering if there is a way to get the minor number. I looked in linux/fs.h and saw that the file struct has a member called private_data but whenever I attempt to call this, it will crash my system as it is currently set to null.

Or should I not be trying to get the minor number from the struct file at all and should attempt to keep track of it when I first open the device?

like image 689
Kat Avatar asked Oct 19 '12 20:10

Kat


People also ask

How do you find major and minor numbers in Linux?

If you issue the ls -l command, you'll see two numbers (separated by a comma) in the device file entries before the date of last modification, where the file length normally appears. These numbers are the major device number and minor device number for the particular device.

How do I find my device number Linux?

All devices, classified by type (char or block), and identified by their MAJOR/MINOR number can be found in the dev subdirectory of the sysfs file system entry (/sys). A platform device is then linked to each MAJOR/MINOR number.

What is minor device number?

The minor number is assigned in the driver. The minor number must map each driver to a specific device instance. Minor numbers usually refer to sub-devices. For example, a disk driver might communicate with a hardware controller device that has several disk drives attached.


1 Answers

You can get the minor number like so:

iminor(filp->f_path.dentry->d_inode)
like image 182
Jester Avatar answered Nov 07 '22 09:11

Jester