xref: /openbsd-src/gnu/llvm/compiler-rt/lib/scudo/standalone/rss_limit_checker.cpp (revision 810390e339a5425391477d5d41c78d7cab2424ac)
1*810390e3Srobert //===-- common.cpp ----------------------------------------------*- C++ -*-===//
2*810390e3Srobert //
3*810390e3Srobert // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4*810390e3Srobert // See https://llvm.org/LICENSE.txt for license information.
5*810390e3Srobert // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6*810390e3Srobert //
7*810390e3Srobert //===----------------------------------------------------------------------===//
8*810390e3Srobert 
9*810390e3Srobert #include "rss_limit_checker.h"
10*810390e3Srobert #include "atomic_helpers.h"
11*810390e3Srobert #include "string_utils.h"
12*810390e3Srobert 
13*810390e3Srobert namespace scudo {
14*810390e3Srobert 
check(u64 NextCheck)15*810390e3Srobert void RssLimitChecker::check(u64 NextCheck) {
16*810390e3Srobert   // The interval for the checks is 250ms.
17*810390e3Srobert   static constexpr u64 CheckInterval = 250 * 1000000;
18*810390e3Srobert 
19*810390e3Srobert   // Early return in case another thread already did the calculation.
20*810390e3Srobert   if (!atomic_compare_exchange_strong(&RssNextCheckAtNS, &NextCheck,
21*810390e3Srobert                                       getMonotonicTime() + CheckInterval,
22*810390e3Srobert                                       memory_order_relaxed)) {
23*810390e3Srobert     return;
24*810390e3Srobert   }
25*810390e3Srobert 
26*810390e3Srobert   const uptr CurrentRssMb = GetRSS() >> 20;
27*810390e3Srobert 
28*810390e3Srobert   RssLimitExceeded Result = RssLimitExceeded::Neither;
29*810390e3Srobert   if (UNLIKELY(HardRssLimitMb && HardRssLimitMb < CurrentRssMb))
30*810390e3Srobert     Result = RssLimitExceeded::Hard;
31*810390e3Srobert   else if (UNLIKELY(SoftRssLimitMb && SoftRssLimitMb < CurrentRssMb))
32*810390e3Srobert     Result = RssLimitExceeded::Soft;
33*810390e3Srobert 
34*810390e3Srobert   atomic_store_relaxed(&RssLimitStatus, static_cast<u8>(Result));
35*810390e3Srobert }
36*810390e3Srobert 
37*810390e3Srobert } // namespace scudo
38