| 110 | namespace detail { |
| 111 | |
| 112 | bool cgroup_available_bytes(uint64_t limit, const CgroupMemoryStat& stat, uint64_t& bytes) { |
| 113 | bytes = 0; |
| 114 | if (!stat.valid) return false; |
| 115 | |
| 116 | // memory.stat's counters can race memory.current, so bound them to charged usage first. The whole clean page |
| 117 | // cache is reclaimable (149: MemAvailable counts active file pages too); the kernel keeps a low-watermark share. |
| 118 | uint64_t reclaimable = std::min(std::max(stat.file, stat.inactive_file), stat.current); |
| 119 | reclaimable = stat.file_dirty >= reclaimable ? 0 : reclaimable - stat.file_dirty; |
| 120 | reclaimable = stat.file_writeback >= reclaimable ? 0 : reclaimable - stat.file_writeback; |
| 121 | reclaimable -= std::min(reclaimable / 2, limit / 64); |
| 122 | |
| 123 | // Reclaiming clean file pages reduces usage; saturating subtraction also handles a transient over-limit read. |
| 124 | const uint64_t usage_after_reclaim = stat.current - reclaimable; |
| 125 | bytes = usage_after_reclaim < limit ? limit - usage_after_reclaim : 0; |
| 126 | return true; |
| 127 | } |
| 128 | |
| 129 | uint64_t clamp_resident_budget(uint64_t requested, uint64_t physical, uint64_t commit, uint64_t headroom) { |
| 130 | const uint64_t available = std::min(physical, commit); |