user1468106
user1468106

Reputation: 33

How to get a device file name using major and minor number

I am trying add some debug messages in block io to track the io operation in linux kernel.

IO could happen to multiple block device, I have dev_t value with me.

I can get major and minor number from dev_t.

I want to know is there any way to get the device file name from /dev/ dir using these major and minor number?

Of course, I need kernel APIs.

Upvotes: 2

Views: 4592

Answers (3)

Raydel Miranda
Raydel Miranda

Reputation: 14360

You can also use libudev. Since you already have the dev_t id this way is aesier.

#include <libudev.h>

// Create the udev context.
struct udev *udev = udev_new();

// Create de udev_device from the dev_t.
struct udev_device *dev = udev_device_new_from_devnum(udev, 'b', sb.st_dev);

// Finally obtain the node.
const char* node  = udev_device_get_devnode(dev);

udev_unref(udev);

Upvotes: 1

Ilya Matveychikov
Ilya Matveychikov

Reputation: 4024

It's simple:

  1. Use bdget function to find the block_device by dev_t.
  2. Use bdevname to get the device name.
  3. Use bdput to put the device reference.

Have fun.

Upvotes: 4

mvp
mvp

Reputation: 116317

In general, you cannot do such simple reverse mapping. This is because knowing some major and major numbers, one can always use mknod to create valid device file anywhere, not necessarily under /dev.

At the end of the day, kernel does not care much how did any particular device node with certain major/minor came about - such a node is simply entry point into the kernel device driver that can handle this hardware or software device.

Granted, in practice on most modern Linux systems most device nodes are located in /dev and maintained by udev - but it is user-space daemon, which your kernel driver cannot talk to. Also note that udev can be configured to create new device nodes with any name.

Upvotes: 0

Related Questions