proto_memory.h 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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_sockets_enabled && sk->sk_memcg &&
  28. mem_cgroup_under_socket_pressure(sk->sk_memcg))
  29. return true;
  30. return !!READ_ONCE(*sk->sk_prot->memory_pressure);
  31. }
  32. static inline long
  33. proto_memory_allocated(const struct proto *prot)
  34. {
  35. return max(0L, atomic_long_read(prot->memory_allocated));
  36. }
  37. static inline long
  38. sk_memory_allocated(const struct sock *sk)
  39. {
  40. return proto_memory_allocated(sk->sk_prot);
  41. }
  42. static inline void proto_memory_pcpu_drain(struct proto *proto)
  43. {
  44. int val = this_cpu_xchg(*proto->per_cpu_fw_alloc, 0);
  45. if (val)
  46. atomic_long_add(val, proto->memory_allocated);
  47. }
  48. static inline void
  49. sk_memory_allocated_add(const struct sock *sk, int val)
  50. {
  51. struct proto *proto = sk->sk_prot;
  52. val = this_cpu_add_return(*proto->per_cpu_fw_alloc, val);
  53. if (unlikely(val >= READ_ONCE(net_hotdata.sysctl_mem_pcpu_rsv)))
  54. proto_memory_pcpu_drain(proto);
  55. }
  56. static inline void
  57. sk_memory_allocated_sub(const struct sock *sk, int val)
  58. {
  59. struct proto *proto = sk->sk_prot;
  60. val = this_cpu_sub_return(*proto->per_cpu_fw_alloc, val);
  61. if (unlikely(val <= -READ_ONCE(net_hotdata.sysctl_mem_pcpu_rsv)))
  62. proto_memory_pcpu_drain(proto);
  63. }
  64. #endif /* _PROTO_MEMORY_H */