3

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

James
  • 799
  • 1
  • 14
  • 33

2 Answers2

2

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.

Community
  • 1
  • 1
oakad
  • 6,945
  • 1
  • 22
  • 31
  • I've looked at the link above. The solution doesn't work any more for linux 2.6 and later, vfs_read() requires a buffer pointer from user space. And that user space pointer has been passed deeper into do_generic_file_aio_read() in mm/filemap.c. I got lost from this place. I'm thinking about how I can get data into kernel space instead of into user space. Any hints? THX – James Mar 13 '14 at 01:47
  • http://lxr.free-electrons.com/source/fs/exec.c#L799 - it seems, set_fs does exactly what you want (as mentioned in the linked question). – oakad Mar 13 '14 at 02:07
  • Already tried it out. Works like a charm!!! Thank you, oakad. For more information if any one else is looking at this issue, another useful link is : http://www.linuxjournal.com/article/8110?page=0,1 Though the link talks about this is not something you want to do, it shows how to do it anyway later in the article. – James Mar 13 '14 at 02:13
1

In case anyone is interested in doing this with Node.js, we released a native add on yesterday with helpers for opening and working with block devices: https://github.com/ronomon/direct-io

Joran Greef
  • 577
  • 6
  • 9