title: Why does mmap defined in a Linux kernel module return MAP_FAILED?
body: <p>I am trying to map a kernel buffer in user space using mmap method in linux 3.10.10. But it is returning <code>MAP_FAILED</code>. Why it is failed to map the buffer.</p>
  
  <p>Kernel module</p>
  
  <pre><code>#include &lt;linux/module.h&gt;  /* Needed by all modules */
  #include &lt;linux/kernel.h&gt;  /* Needed for KERN_ALERT */
  #include &lt;linux/init.h&gt;         /* Needed for the macros */
  #include &lt;linux/proc_fs.h&gt;
  #include &lt;asm/uaccess.h&gt;
  #include &lt;linux/interrupt.h&gt;
  #include &lt;linux/io.h&gt;
  #include &lt;linux/init.h&gt;
  #include &lt;linux/pci.h&gt;
  #include &lt;linux/slab.h&gt;
  #include &lt;sound/core.h&gt;
  #include &lt;sound/initval.h&gt;
  #include &lt;linux/module.h&gt;
  #include &lt;linux/kernel.h&gt;
  #include &lt;linux/proc_fs.h&gt;
  #include &lt;asm/uaccess.h&gt;
  #include &lt;linux/interrupt.h&gt;
  #include &lt;linux/io.h&gt;
  //#include &lt;linux/malloc.h&gt;
  
  #include &lt;linux/mm.h&gt;  /* mmap related stuff */
  
  long long  *buf1;
  long long* buf;
  
  
  static int driver_mmap(struct file *file, struct vm_area_struct *vma)
  {
    vma-&gt;vm_flags |= VM_LOCKED|VM_SHARED;
  
    int i = remap_pfn_range(vma, vma-&gt;vm_start,
               virt_to_phys(buf) &gt;&gt; PAGE_SHIFT,
               vma-&gt;vm_end-vma-&gt;vm_start, vma-&gt;vm_page_prot);
  
    SetPageReserved(virt_to_page(buf));
    printk("MMAP \n");
    return 0;
  }
  
  
  struct file_operations proc_fops =
  {
    mmap:driver_mmap,
  };
  int init_module_test(void)
  {
    int i;
    buf1 = kmalloc(4096, __GFP_COLD|GFP_DMA);
  
    buf = ((int)buf1 + PAGE_SIZE -1) &amp; PAGE_MASK;
    printk("&lt;1&gt;Hello world1\n");
    for (i = 0; i &lt; 512; i++)
    {
      buf[i] = (long long) i + 1;
    }
    proc_create ("mmap_example",0,NULL, &amp;proc_fops);
    printk("&lt;1&gt;Hello world3\n");
    printk("&lt;1&gt;BUF1 = 0x%08x\n BUF = 0x%08x\n", buf1,buf);
    return 0;
  }
  
  
  void cleanup_module_test(void)
  {
    remove_proc_entry ("mmap_example", NULL);
    kfree(buf1);
    printk("Goodbye world\n");
  }
  
  
  
  module_init(init_module_test);
  module_exit(cleanup_module_test);
  </code></pre>
  
  <p>Application code</p>
  
  <pre><code>#include&lt;stdio.h&gt;
  #include&lt;stdlib.h&gt;
  #include&lt;sys/mman.h&gt;
  
  int main(void)
  {
    int fd, i;
    long long *msg = NULL;
  
    if ((fd = fopen("/proc/mmap_example", "r")) &lt; 0)
    {
      printf("File not opened");
    }
    msg = mmap(NULL, 4096, PROT_READ, MAP_SHARED, fd, 0);
    if (msg == MAP_FAILED)
    {
      printf("MAP failed");
      return 0;
    }
    for (i = 0; i &lt; 512; i++)
      printf("0x%llx,", msg[i]);
  
    fclose(fd);
    return 0;
  }
  </code></pre>
  
  <p>I always end up seing <code>"MAP failed"</code>.
  Is there something wrong with my code?</p>