folly: replace old-style header guards with "pragma once"
[folly.git] / folly / detail / MemoryIdler.h
1 /*
2  * Copyright 2016 Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #pragma once
18
19 #include <atomic>
20 #include <chrono>
21 #include <folly/AtomicStruct.h>
22 #include <folly/Hash.h>
23 #include <folly/Traits.h>
24 #include <folly/detail/Futex.h>
25
26 namespace folly {
27
28 // gcc 4.7 doesn't do std::is_trivial correctly, override so we can use
29 // AtomicStruct<duration>
30 template<>
31 struct IsTriviallyCopyable<std::chrono::steady_clock::duration>
32   : std::true_type {};
33
34 }
35
36 namespace folly { namespace detail {
37
38 /// MemoryIdler provides helper routines that allow routines to return
39 /// some assigned memory resources back to the system.  The intended
40 /// use is that when a thread is waiting for a long time (perhaps it
41 /// is in a LIFO thread pool and hasn't been needed for a long time)
42 /// it should release its thread-local malloc caches (both jemalloc and
43 /// tcmalloc use these for better performance) and unmap the stack pages
44 /// that contain no useful data.
45 struct MemoryIdler {
46
47   /// Returns memory from thread-local allocation pools to the global
48   /// pool, if we know how to for the current malloc implementation.
49   /// jemalloc is supported.
50   static void flushLocalMallocCaches();
51
52
53   enum {
54     /// This value is a tradeoff between reclaiming memory and triggering
55     /// a page fault immediately on wakeup.  Note that the actual unit
56     /// of idling for the stack is pages, so the actual stack that
57     /// will be available on wakeup without a page fault is between
58     /// kDefaultStackToRetain and kDefaultStackToRetain + PageSize -
59     /// 1 bytes.
60     kDefaultStackToRetain = 1024,
61   };
62
63   /// Uses madvise to discard the portion of the thread's stack that
64   /// currently doesn't hold any data, trying to ensure that no page
65   /// faults will occur during the next retain bytes of stack allocation
66   static void unmapUnusedStack(size_t retain = kDefaultStackToRetain);
67
68
69   /// The system-wide default for the amount of time a blocking
70   /// thread should wait before reclaiming idle memory.  Set this to
71   /// Duration::max() to never wait.  The default value is 5 seconds.
72   /// Endpoints using this idle timeout might randomly wait longer to
73   /// avoid synchronizing their flushes.
74   static AtomicStruct<std::chrono::steady_clock::duration> defaultIdleTimeout;
75
76   /// Selects a timeout pseudo-randomly chosen to be between
77   /// idleTimeout and idleTimeout * (1 + timeoutVariationFraction), to
78   /// smooth out the behavior in a bursty system
79   template <typename Clock = std::chrono::steady_clock>
80   static typename Clock::duration getVariationTimeout(
81       typename Clock::duration idleTimeout
82           = defaultIdleTimeout.load(std::memory_order_acquire),
83       float timeoutVariationFrac = 0.5) {
84     if (idleTimeout.count() > 0 && timeoutVariationFrac > 0) {
85       // hash the pthread_t and the time to get the adjustment.
86       // Standard hash func isn't very good, so bit mix the result
87       auto pr = std::make_pair(pthread_self(),
88                                Clock::now().time_since_epoch().count());
89       std::hash<decltype(pr)> hash_fn;
90       uint64_t h = folly::hash::twang_mix64(hash_fn(pr));
91
92       // multiplying the duration by a floating point doesn't work, grr..
93       auto extraFrac =
94         timeoutVariationFrac / std::numeric_limits<uint64_t>::max() * h;
95       uint64_t tics = idleTimeout.count() * (1 + extraFrac);
96       idleTimeout = typename Clock::duration(tics);
97     }
98
99     return idleTimeout;
100   }
101
102   /// Equivalent to fut.futexWait(expected, waitMask), but calls
103   /// flushLocalMallocCaches() and unmapUnusedStack(stackToRetain)
104   /// after idleTimeout has passed (if it has passed).  Internally uses
105   /// fut.futexWait and fut.futexWaitUntil.  Like futexWait, returns
106   /// false if interrupted with a signal.  The actual timeout will be
107   /// pseudo-randomly chosen to be between idleTimeout and idleTimeout *
108   /// (1 + timeoutVariationFraction), to smooth out the behavior in a
109   /// system with bursty requests.  The default is to wait up to 50%
110   /// extra, so on average 25% extra
111   template <template <typename> class Atom,
112             typename Clock = std::chrono::steady_clock>
113   static bool futexWait(
114       Futex<Atom>& fut,
115       uint32_t expected,
116       uint32_t waitMask = -1,
117       typename Clock::duration idleTimeout
118           = defaultIdleTimeout.load(std::memory_order_acquire),
119       size_t stackToRetain = kDefaultStackToRetain,
120       float timeoutVariationFrac = 0.5) {
121
122     if (idleTimeout == Clock::duration::max()) {
123       // no need to use futexWaitUntil if no timeout is possible
124       return fut.futexWait(expected, waitMask);
125     }
126
127     idleTimeout = getVariationTimeout(idleTimeout, timeoutVariationFrac);
128     if (idleTimeout.count() > 0) {
129       while (true) {
130         auto rv = fut.futexWaitUntil(
131           expected, Clock::now() + idleTimeout, waitMask);
132         if (rv == FutexResult::TIMEDOUT) {
133           // timeout is over
134           break;
135         }
136         // finished before timeout hit, no flush
137         assert(rv == FutexResult::VALUE_CHANGED || rv == FutexResult::AWOKEN ||
138                rv == FutexResult::INTERRUPTED);
139         return rv == FutexResult::AWOKEN;
140       }
141     }
142
143     // flush, then wait with no timeout
144     flushLocalMallocCaches();
145     unmapUnusedStack(stackToRetain);
146     return fut.futexWait(expected, waitMask);
147   }
148 };
149
150 }} // namespace folly::detail