Search code examples
linuxiooperating-systemkernelblock

Read/Write block directly to disk in linux kernel


As the title has said, I'm looking for how I can read/write blocks directly to disk in linux kernel space (bypassing the file system) and directly interact with block IO layer.

After reading through some kernel codes, I realize bio is the structure I should be using to achieve such goal in block IO layer. But I don't quite understand the structures of bio and haven't figure out how exactly I can do that.

Any helps? Thank you


Solution

  • If you're only doing something simple, you don't really need to mess with BIO. What you can do instead is to simply open the block device (/dev/whatever) as if it was a file. The kernel will do the right thing and will give you the "thin" wrapper for read/write operations.

    In regard to opening the file from the kernel space, there are few questions here, already answered, like this one:

    How to read/write files within a Linux kernel module?

    If you want to do anything more fancy, you will have to study the sources of the FS drivers (in the fs/ subdirectory) to hunt for examples.