maccess.c 1.6 KB

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