maccess.c 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. /*
  2. * Access kernel memory without faulting.
  3. */
  4. #include <linux/uaccess.h>
  5. #include <linux/module.h>
  6. #include <linux/mm.h>
  7. /**
  8. * probe_kernel_read(): safely attempt to read from a location
  9. * @dst: pointer to the buffer that shall take the data
  10. * @src: address to read from
  11. * @size: size of the data chunk
  12. *
  13. * Safely read from address @src to the buffer at @dst. If a kernel fault
  14. * happens, handle that and return -EFAULT.
  15. */
  16. long probe_kernel_read(void *dst, void *src, size_t size)
  17. {
  18. long ret;
  19. mm_segment_t old_fs = get_fs();
  20. set_fs(KERNEL_DS);
  21. pagefault_disable();
  22. ret = __copy_from_user_inatomic(dst,
  23. (__force const void __user *)src, size);
  24. pagefault_enable();
  25. set_fs(old_fs);
  26. return ret ? -EFAULT : 0;
  27. }
  28. EXPORT_SYMBOL_GPL(probe_kernel_read);
  29. /**
  30. * probe_kernel_write(): safely attempt to write to a location
  31. * @dst: address to write to
  32. * @src: pointer to the data that shall be written
  33. * @size: size of the data chunk
  34. *
  35. * Safely write to address @dst from the buffer at @src. If a kernel fault
  36. * happens, handle that and return -EFAULT.
  37. */
  38. long probe_kernel_write(void *dst, void *src, size_t size)
  39. {
  40. long ret;
  41. mm_segment_t old_fs = get_fs();
  42. set_fs(KERNEL_DS);
  43. pagefault_disable();
  44. ret = __copy_to_user_inatomic((__force void __user *)dst, src, size);
  45. pagefault_enable();
  46. set_fs(old_fs);
  47. return ret ? -EFAULT : 0;
  48. }
  49. EXPORT_SYMBOL_GPL(probe_kernel_write);