How to use sysfs inside kernel module?

2019-04-16 03:46发布

问题:

In userspace I can just echo noop > /sys/block/sda/queue/scheduler.

How to do the same inside a kernel module?

I expect something like this (pseudocode):

struct dentry* e = sysfs_get_root();
vfs_path_lookup(e, ????, "block/sda/queue/scheduler", ???);
????;
struct something* q = ????;
????->store(q, "noop", 1);
/* some cleanup */

How to implement it properly?

My kernel module just registers SysRQ handler and should configure the io scheduler when that SysRQ is triggered (userspace programs can be hung at that time because of the bad io-scheduler)

回答1:

There is just no way to implement it properly. If you want to do it anyway, and also understand the reason why it is a Bad Idea (tm), see this article



回答2:

If you want to configure something for your kernel module, you can do that in a wrapper script which inserts your kernel module using insmod command.

And have a look at this article where it tell "Why it is bad to write files from Kernel"



回答3:

Wrong wrong wrong. sysfs is an interface to userspace, you should not be using it inside the kernel.

If your module wants to change the block scheduler then you should work out how to do that inside the kernel, ie. when a user writes to /sys/block/sda/queue/scheduler some kernel code is run, you should be calling that code directly.

Having said that this seems like a Bad Idea, how will you handle multiple block devices for example?