ram.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <sys/param.h> /* MIN */
  4. #include <sys/sysinfo.h>
  5. #include "../lib/util.h"
  6. #include "../aslstatus.h"
  7. #include "../lib/meminfo.h"
  8. #define DEF_RAM(STRUCT, STATIC, OUT) \
  9. int* fd = (STATIC)->data; \
  10. struct meminfo_ram STRUCT = MEMINFO_INIT_RAM; \
  11. if (!(STATIC)->cleanup) (STATIC)->cleanup = fd_cleanup; \
  12. if (!MEMINFO_FD(fd)) ERRRET(OUT); \
  13. if (!get_meminfo_ram(*fd, &STRUCT)) ERRRET(OUT)
  14. static inline memory_t get_used(const struct meminfo_ram* info);
  15. void
  16. ram_free(char* out,
  17. const char __unused* _a,
  18. uint32_t __unused _i,
  19. static_data_t* static_data)
  20. {
  21. DEF_RAM(info, static_data, out);
  22. fmt_human(
  23. out,
  24. (info.available ? MIN(info.available, info.total) : info.free)
  25. * 1024);
  26. }
  27. void
  28. ram_perc(char* out,
  29. const char __unused* _a,
  30. uint32_t __unused _i,
  31. static_data_t* static_data)
  32. {
  33. DEF_RAM(info, static_data, out);
  34. if (!info.total) ERRRET(out);
  35. bprintf(out,
  36. "%" PRIperc,
  37. (percent_t)(100 * get_used(&info) / info.total));
  38. }
  39. void
  40. ram_total(char* out,
  41. const char __unused* _a,
  42. uint32_t __unused _i,
  43. void __unused* _p)
  44. {
  45. struct sysinfo info;
  46. if (!!sysinfo(&info)) ERRRET(out);
  47. fmt_human(out, info.totalram * info.mem_unit);
  48. }
  49. void
  50. ram_used(char* out,
  51. const char __unused* _a,
  52. uint32_t __unused _i,
  53. static_data_t* static_data)
  54. {
  55. DEF_RAM(info, static_data, out);
  56. fmt_human(out, get_used(&info) * 1024);
  57. }
  58. static inline memory_t
  59. get_used(const struct meminfo_ram* info)
  60. {
  61. /*
  62. * see procps(free):
  63. * https://gitlab.com/procps-ng/procps/-/blob/master/proc/sysinfo.c
  64. *
  65. * and htop:
  66. * https://github.com/htop-dev/htop/blob/master/linux/LinuxProcessList.c
  67. */
  68. const memory_t diff =
  69. info->free
  70. + (info->cached + info->reclaimable - info->shared
  71. /*
  72. * Adjustments:
  73. * - Shmem in part of Cached
  74. * https://lore.kernel.org/patchwork/patch/648763/
  75. */
  76. )
  77. + info->buffers;
  78. return (info->total >= diff) ? info->total - diff
  79. : info->total - info->free;
  80. }