Why is it that every function in most device drivers are static? As static functions are not visible outside of the file scope. Then, how do these driver function get called by user space applications?
相关问题
- Multiple sockets for clients to connect to
- What is the best way to do a search in a large fil
- glDrawElements only draws half a quad
- Index of single bit in long integer (in C) [duplic
- Equivalent of std::pair in C
Remember than in C everything is addresses. That means you can call a function if you have the address. The kernel has a macro named
EXPORT_SYMBOL
that does just that. It exports the address of a function so that driver functions can be called without having to place header declarations since those functions are sometimes not know at compile time. In cases like this the static qualifier is just made to ensure that they are only called through this method and not from other files that may include that driver code (in some cases it's not a good idea to include driver code headers and call them directly).EDIT: Since it was pointed out that I did not cover userspace.
Driver functions are usually not called through userspace directly (except for x86 implementation of SYSCALL instruction which does some little tricks to save the context switch sometimes). So the static keyword here makes no difference. It only makes a difference in kernel space. As pointed out by @Cong Wang, functions are usually place into a structure of function pointers so that they may be called by simply having structures point to this structure (such as file_ops, schedulers, filesystems, network code, etc...).
The kernel has thousands of modules and they are (or used to be) all object files, loaded dynamically via a process similar to linking --or are actually linked-- into the executable. Can you imagine how many name clashes there would be if they were all to export all their function names, as is the default C behavior unless
static
is specified?Userspace applications cannot call driver functions directly, but there are other ways to interact.
Because these static function are not supposed to be used directly outside of the module. They are called by other functions in the module, among which can be the interface to an ioctl or whatever callbacks. This is why they can be called from user-space, they are just in the call path.
Take a look at the network dummy module:
dummy_dev_init() is obviously static:
but it is a callback of ->ndo_init() which is called when registering this network device.
And obvious no one should call dummy_dev_init() directly.