title: copy_from_user()/__get_user() works fine within ioctl, but failed outside ioctl
body: <p>I am currently doing experiments with a kernel module.</p>
  <p>I wrote a function that takes in a pointer to a structure (in user space) as a parameter, with the aim to copy that structure from user space to kernel space; hence, I need <code>copy_from_user</code> or <code>__get_user</code>.</p>
  <p>The definition of the structure is quite simple:</p>
  <pre><code>struct A {
      int a;
  };
  </code></pre>
  <p>The function in my kernel module aims to get the value of a, and return its value, which is as follows (with two approaches):</p>
  <pre><code>static int foo(struct A __user *arg)
  {
      int num, ret; 
  
      if (!access_ok(VERIFY_WRITE, arg, sizeof(struct A)))
          return -EFAULT;
      
      /* approach1: directly copy the value from user space */
      ret = __get_user(num, (int __user *)&amp;arg-&gt;a);
      if (ret) return -ENOMEM;
  
      /* approach2: allocate space for struct A, then copy the whole struct */
      struct A *tmp = kmalloc(sizeof(struct A), GFP_KERNEL);
      if (!tmp) return -ENOMEM;
  
      ret = copy_from_user(tmp, (const void __user *)arg, sizeof(struct A));
      if (ret) return -EFAULT;
  
      num = tmp-&gt;a;
      kfree(tmp);
      
      return num;
  }
  </code></pre>
  <p>No matter which approach I use, this function works fine in <code>ioctl</code>. Below is a snippet of the code in <code>ioctl</code>:</p>
  <pre><code>long foo_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
  {
      struct A __user *tmp_struct;
      int ret;
      ...
  
      switch (cmd) {
      case IOC_FOO:
          ret = foo((struct A __user *)arg);
          break;
      ...
      }
      
      ...
      return ret;
  }
  </code></pre>
  <p>However, when I move <code>foo()</code> into another function <code>foo2()</code>, it will fail on either <code>__get_user()</code> or <code>copy_from_user()</code>. The pseudo-code is as follows:</p>
  <pre><code>int foo2() 
  {
      int val;
      ...
      struct A __user *addr = the address of struct A in user space
      val = foo(addr); /* this is where error occurrs */
      ...
  }
  </code></pre>
  <p>Note that the code is a simpler version of my experiment. <code>foo2()</code> is called through another cmd in <code>ioctl()</code>, issued by the same process. I got the address of struct A - <code>addr</code> from user space using another ioctl() cmd, which is irrelevant to this question. I have already checked that the address of struct A in user space is correct (by printing the addresses both in user space and kernel space), which makes me quite confused - why a valid user space address would lead to error in <code>copy_from_user()</code> or <code>__get_user()</code>?</p>
  <p>Why <code>foo()</code> works in <code>ioctl()</code> but does not work in <code>foo2()</code>?</p>
  <p>Any idea would be appreciated.</p>