proto_memory.h 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /* SPDX-License-Identifier: GPL-2.0-or-later */
  2. #ifndef _PROTO_MEMORY_H
  3. #define _PROTO_MEMORY_H
  4. #include <net/sock.h>
  5. #include <net/hotdata.h>
  6. /* 1 MB per cpu, in page units */
  7. #define SK_MEMORY_PCPU_RESERVE (1 << (20 - PAGE_SHIFT))
  8. static inline bool sk_has_memory_pressure(const struct sock *sk)
  9. {
  10. return sk->sk_prot->memory_pressure != NULL;
  11. }
  12. static inline bool
  13. proto_memory_pressure(const struct proto *prot)
  14. {
  15. if (!prot->memory_pressure)
  16. return false;
  17. return !!READ_ONCE(*prot->memory_pressure);
  18. }
  19. static inline bool sk_under_global_memory_pressure(const struct sock *sk)
  20. {
  21. return proto_memory_pressure(sk->sk_prot);
  22. }
  23. static inline bool sk_under_memory_pressure(const struct sock *sk)
  24. {
  25. if (!sk->sk_prot->memory_pressure)
  26. return false;
  27. if (mem_cgroup_sk_enabled(sk) &&
  28. mem_cgroup_sk_under_memory_pressure(sk))
  29. return true;
  30. if (sk->sk_bypass_prot_mem)
  31. return false;
  32. return !!READ_ONCE(*sk->sk_prot->memory_pressure);
  33. }
  34. static inline long
  35. proto_memory_allocated(const struct proto *prot)
  36. {
  37. return max(0L, atomic_long_read(prot->memory_allocated));
  38. }
  39. static inline long
  40. sk_memory_allocated(const struct sock *sk)
  41. {
  42. return proto_memory_allocated(sk->sk_prot);
  43. }
  44. static inline void proto_memory_pcpu_drain(struct proto *proto)
  45. {
  46. int val = this_cpu_xchg(*proto->per_cpu_fw_alloc, 0);
  47. if (val)
  48. atomic_long_add(val, proto->memory_allocated);
  49. }
  50. static inline void
  51. sk_memory_allocated_add(const struct sock *sk, int val)
  52. {
  53. struct proto *proto = sk->sk_prot;
  54. val = this_cpu_add_return(*proto->per_cpu_fw_alloc, val);
  55. if (unlikely(val >= READ_ONCE(net_hotdata.sysctl_mem_pcpu_rsv)))
  56. proto_memory_pcpu_drain(proto);
  57. }
  58. static inline void
  59. sk_memory_allocated_sub(const struct sock *sk, int val)
  60. {
  61. struct proto *proto = sk->sk_prot;
  62. val = this_cpu_sub_return(*proto->per_cpu_fw_alloc, val);
  63. if (unlikely(val <= -READ_ONCE(net_hotdata.sysctl_mem_pcpu_rsv)))
  64. proto_memory_pcpu_drain(proto);
  65. }
  66. #endif /* _PROTO_MEMORY_H */