2

I always thought copy_to_user was necessary when the kernel writes to users via procfs.

I forgot to do it once though (and I used snprintf) and everything was working fine. Now that I noticed it, I have been searching. I found this link that doesn't say copy_to_user is needed even though for the other section (kernel reading from user) it does say copy_from_user is necessary.

So, is the buffer provided to kernel module to write data (so user reads from it), in kernel space already? Is it true that you don't need copy_to_user when writing through procfs? Or have I been lucky not to get a crash?

Shahbaz
  • 46,337
  • 19
  • 116
  • 182
  • Wihtout seeing your actual code it's hard to tell. I suspect the copy_to_user part is done by the procfs machinery when the buffer is read. – stsquad Apr 03 '12 at 11:27
  • @stsquad, that was my suspicion too, but I was surprised at that. I mean, if the kernel does the `copy_to_user`, why does it even exist? – Shahbaz Apr 03 '12 at 12:20

1 Answers1

2

Always use copy_from_user and copy_to_user when dealing with user space pointers. Even if simple memcpy sometimes works for you there are situations where it can fail. See this thread for the information.

Speaking about procfs it's necessary to take into account that it use a little trick with kernel memory preallocation. See this link for details.

Ilya Matveychikov
  • 3,936
  • 2
  • 27
  • 42
  • Thanks! The link to the /proc reader was really helpful and the discussion is quite interesting – Shahbaz Apr 03 '12 at 12:26
  • FYI, `copy_to_user` always failed for me. In a case as simple as `char str[7] = "ABCDEF"; ret = copy_to_user(page + offset, str, 7);` it always returned `7`. The thing is, according to the same code you pointed me to, I indeed don't get a user pointer, but I always thought `copy_to_user` would understand and ignore kernel pointers. Nevertheless, the kernel explicitly calls `copy_to_user` itself, so I was forced to remove it. – Shahbaz Apr 03 '12 at 23:03