title: What is the point of using the linux macro access_ok()
body: <p>I've been doing some research and I'm a little confused about this macro. Hopefully someone can give me some guidance. I have some ioctl code (which I've inherited, not written) and the first thing it does if check if <code>access_ok()</code> before moving on to copying data over from user space:</p>
  
  <pre><code>#define __lddk_copy_from_user(a,b,c) copy_from_user(a,b,c)
  #define __lddk_copy_to_user(a,b,c) copy_to_user(a,b,c)
  
  long can_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
  {
    switch(cmd) {
      case COMMAND:
        if(! access_ok(VERIFY_READ, (void *)arg, sizeof(Message_par_t)))
          return(retval); 
  
        if(! access_ok(VERIFY_WRITE, (void *)arg, sizeof(Message_par_t)))
          return(retval); 
  
        argp = &amp;Command;
        __lddk_copy_from_user( (void *) argp,(Command_par_t *) arg, sizeof(Command_par_t));
  </code></pre>
  
  <p>So the code works just fine, but I'm not sure it's needed. The first question comes from this description of access_ok's return: </p>
  
  <ul>
  <li>The function returns non-zero if the region is likely accessible (though access may still result in -EFAULT). This function simply checks that the address is likely in user space, not in the kernel.</li>
  </ul>
  
  <p>So this means that it really does nothing more then make sure the pointer we're checking against is <strong>probably</strong> initialized in user space? Since we know that we couldn't come into this function other than a user space call, and it couldn't happen unless we opened a valid file descriptor to this device, is this really needed? Is it really any safer then just making sure we didn't get a NULL pointer?</p>
  
  <p>Second question comes from this description:</p>
  
  <ul>
  <li>The type argument can be specified as VERIFY_READ or VERIFY_WRITE. The VERIFY_WRITE symbolic also identifies whether the memory region is readable as well as writable.</li>
  </ul>
  
  <p>Does this mean the first check in my code is redundant? If we're going to check for a writable area we get readable as a freebie?</p>
  
  <p>I'm using a x86 architecture so the definations of access_ok() and __range_no_ok() are those from /usr/src/linux-3.1.10-1.16/arch/x86/include/asm/uaccess.h as follows:</p>
  
  <pre><code>#define access_ok(type, addr, size) (likely(__range_not_ok(addr, size) == 0))
  
  #define __range_not_ok(addr, size)                  \
  ({                                  \
      unsigned long flag, roksum;                 \
      __chk_user_ptr(addr);                       \
      asm("add %3,%1 ; sbb %0,%0 ; cmp %1,%4 ; sbb $0,%0"     \
          : "=&amp;r" (flag), "=r" (roksum)               \
          : "1" (addr), "g" ((long)(size)),               \
            "rm" (current_thread_info()-&gt;addr_limit.seg));        \
      flag;                               \
  })
  </code></pre>