usercopy.c 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. // SPDX-License-Identifier: GPL-2.0
  2. #include <linux/uaccess.h>
  3. #include <linux/bitops.h>
  4. /* out-of-line parts */
  5. #ifndef INLINE_COPY_FROM_USER
  6. unsigned long _copy_from_user(void *to, const void __user *from, unsigned long n)
  7. {
  8. unsigned long res = n;
  9. might_fault();
  10. if (likely(access_ok(from, n))) {
  11. kasan_check_write(to, n);
  12. res = raw_copy_from_user(to, from, n);
  13. }
  14. if (unlikely(res))
  15. memset(to + (n - res), 0, res);
  16. return res;
  17. }
  18. EXPORT_SYMBOL(_copy_from_user);
  19. #endif
  20. #ifndef INLINE_COPY_TO_USER
  21. unsigned long _copy_to_user(void __user *to, const void *from, unsigned long n)
  22. {
  23. might_fault();
  24. if (likely(access_ok(to, n))) {
  25. kasan_check_read(from, n);
  26. n = raw_copy_to_user(to, from, n);
  27. }
  28. return n;
  29. }
  30. EXPORT_SYMBOL(_copy_to_user);
  31. #endif
  32. /**
  33. * check_zeroed_user: check if a userspace buffer only contains zero bytes
  34. * @from: Source address, in userspace.
  35. * @size: Size of buffer.
  36. *
  37. * This is effectively shorthand for "memchr_inv(from, 0, size) == NULL" for
  38. * userspace addresses (and is more efficient because we don't care where the
  39. * first non-zero byte is).
  40. *
  41. * Returns:
  42. * * 0: There were non-zero bytes present in the buffer.
  43. * * 1: The buffer was full of zero bytes.
  44. * * -EFAULT: access to userspace failed.
  45. */
  46. int check_zeroed_user(const void __user *from, size_t size)
  47. {
  48. unsigned long val;
  49. uintptr_t align = (uintptr_t) from % sizeof(unsigned long);
  50. if (unlikely(size == 0))
  51. return 1;
  52. from -= align;
  53. size += align;
  54. if (!user_access_begin(from, size))
  55. return -EFAULT;
  56. unsafe_get_user(val, (unsigned long __user *) from, err_fault);
  57. if (align)
  58. val &= ~aligned_byte_mask(align);
  59. while (size > sizeof(unsigned long)) {
  60. if (unlikely(val))
  61. goto done;
  62. from += sizeof(unsigned long);
  63. size -= sizeof(unsigned long);
  64. unsafe_get_user(val, (unsigned long __user *) from, err_fault);
  65. }
  66. if (size < sizeof(unsigned long))
  67. val &= aligned_byte_mask(size);
  68. done:
  69. user_access_end();
  70. return (val == 0);
  71. err_fault:
  72. user_access_end();
  73. return -EFAULT;
  74. }
  75. EXPORT_SYMBOL(check_zeroed_user);