title: How Linux knows which ioctl function to call?
body: <p>Here is the <code>ioctl</code> call in user space:</p>
  
  <pre><code>int ioctl(int fd, int cmd, ...);
  </code></pre>
  
  <p>As far as I know, when we want to perfrom IO operations, we define our own <code>ioctl</code> function with a set of requests (commands), assign our <code>ioctl</code> to a <a href="http://lxr.free-electrons.com/source/include/linux/fs.h#L1525" rel="noreferrer">file_operations</a> structure like this:</p>
  
  <pre><code>struct file_operations fops = {
   .read = device_read,
   .write = device_write,
   .ioctl = device_ioctl, // device_ioctl is our function
   .open = device_open,
   .release = device_release,
  };
  </code></pre>
  
  <p>And the <code>device_ioctl</code> function is defined differently compared to the user space interface:</p>
  
  <pre><code>static long device_ioctl(struct file *f, unsigned int cmd, unsigned long arg)
  </code></pre>
  
  <p>I think based on the file descriptor, the kernel can get the appropriate file structure and calls the device's <code>ioctl</code>.</p>
  
  <p>This is just a guess because I cannot find it the generic function definition where the kernel selects appropriate <code>ioctl</code> function based on the file descriptor <code>fd</code> passed into the generic <code>ioctl</code> interface? There are only 3 <code>ioctl</code> definitions I can find, but apparently those are just the devices' definitions, not the kernel: <a href="http://lxr.free-electrons.com/ident?i=ioctl" rel="noreferrer">ioctl</a></p>