2017
[folly.git] / folly / detail / MemoryIdler.cpp
1 /*
2  * Copyright 2017 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 #include <folly/detail/MemoryIdler.h>
18
19 #include <folly/Logging.h>
20 #include <folly/MallctlHelper.h>
21 #include <folly/Malloc.h>
22 #include <folly/Portability.h>
23 #include <folly/ScopeGuard.h>
24 #include <folly/detail/CacheLocality.h>
25 #include <folly/portability/SysMman.h>
26 #include <folly/portability/Unistd.h>
27
28 #include <limits.h>
29 #include <pthread.h>
30 #include <stdio.h>
31 #include <string.h>
32 #include <utility>
33
34 namespace folly { namespace detail {
35
36 AtomicStruct<std::chrono::steady_clock::duration>
37 MemoryIdler::defaultIdleTimeout(std::chrono::seconds(5));
38
39 void MemoryIdler::flushLocalMallocCaches() {
40   if (!usingJEMalloc()) {
41     return;
42   }
43   if (!mallctl || !mallctlnametomib || !mallctlbymib) {
44     FB_LOG_EVERY_MS(ERROR, 10000) << "mallctl* weak link failed";
45     return;
46   }
47
48   try {
49     mallctlCall("thread.tcache.flush");
50
51     // By default jemalloc has 4 arenas per cpu, and then assigns each
52     // thread to one of those arenas.  This means that in any service
53     // that doesn't perform a lot of context switching, the chances that
54     // another thread will be using the current thread's arena (and hence
55     // doing the appropriate dirty-page purging) are low.  Some good
56     // tuned configurations (such as that used by hhvm) use fewer arenas
57     // and then pin threads to avoid contended access.  In that case,
58     // purging the arenas is counter-productive.  We use the heuristic
59     // that if narenas <= 2 * num_cpus then we shouldn't do anything here,
60     // which detects when the narenas has been reduced from the default
61     unsigned narenas;
62     unsigned arenaForCurrent;
63     size_t mib[3];
64     size_t miblen = 3;
65
66     mallctlRead("opt.narenas", &narenas);
67     mallctlRead("thread.arena", &arenaForCurrent);
68     if (narenas > 2 * CacheLocality::system().numCpus &&
69         mallctlnametomib("arena.0.purge", mib, &miblen) == 0) {
70       mib[1] = size_t(arenaForCurrent);
71       mallctlbymib(mib, miblen, nullptr, nullptr, nullptr, 0);
72     }
73   } catch (const std::runtime_error& ex) {
74     FB_LOG_EVERY_MS(WARNING, 10000) << ex.what();
75   }
76 }
77
78
79 // Stack madvise isn't Linux or glibc specific, but the system calls
80 // and arithmetic (and bug compatibility) are not portable.  The set of
81 // platforms could be increased if it was useful.
82 #if (FOLLY_X64 || FOLLY_PPC64) && defined(_GNU_SOURCE) && \
83     defined(__linux__) && !FOLLY_MOBILE
84
85 static FOLLY_TLS uintptr_t tls_stackLimit;
86 static FOLLY_TLS size_t tls_stackSize;
87
88 static size_t pageSize() {
89   static const size_t s_pageSize = sysconf(_SC_PAGESIZE);
90   return s_pageSize;
91 }
92
93 static void fetchStackLimits() {
94   pthread_attr_t attr;
95   pthread_getattr_np(pthread_self(), &attr);
96   SCOPE_EXIT { pthread_attr_destroy(&attr); };
97
98   void* addr;
99   size_t rawSize;
100   int err;
101   if ((err = pthread_attr_getstack(&attr, &addr, &rawSize))) {
102     // unexpected, but it is better to continue in prod than do nothing
103     FB_LOG_EVERY_MS(ERROR, 10000) << "pthread_attr_getstack error " << err;
104     assert(false);
105     tls_stackSize = 1;
106     return;
107   }
108   assert(addr != nullptr);
109   assert(rawSize >= PTHREAD_STACK_MIN);
110
111   // glibc subtracts guard page from stack size, even though pthread docs
112   // seem to imply the opposite
113   size_t guardSize;
114   if (pthread_attr_getguardsize(&attr, &guardSize) != 0) {
115     guardSize = 0;
116   }
117   assert(rawSize > guardSize);
118
119   // stack goes down, so guard page adds to the base addr
120   tls_stackLimit = uintptr_t(addr) + guardSize;
121   tls_stackSize = rawSize - guardSize;
122
123   assert((tls_stackLimit & (pageSize() - 1)) == 0);
124 }
125
126 FOLLY_NOINLINE static uintptr_t getStackPtr() {
127   char marker;
128   auto rv = uintptr_t(&marker);
129   return rv;
130 }
131
132 void MemoryIdler::unmapUnusedStack(size_t retain) {
133   if (tls_stackSize == 0) {
134     fetchStackLimits();
135   }
136   if (tls_stackSize <= std::max(size_t(1), retain)) {
137     // covers both missing stack info, and impossibly large retain
138     return;
139   }
140
141   auto sp = getStackPtr();
142   assert(sp >= tls_stackLimit);
143   assert(sp - tls_stackLimit < tls_stackSize);
144
145   auto end = (sp - retain) & ~(pageSize() - 1);
146   if (end <= tls_stackLimit) {
147     // no pages are eligible for unmapping
148     return;
149   }
150
151   size_t len = end - tls_stackLimit;
152   assert((len & (pageSize() - 1)) == 0);
153   if (madvise((void*)tls_stackLimit, len, MADV_DONTNEED) != 0) {
154     // It is likely that the stack vma hasn't been fully grown.  In this
155     // case madvise will apply dontneed to the present vmas, then return
156     // errno of ENOMEM.  We can also get an EAGAIN, theoretically.
157     // EINVAL means either an invalid alignment or length, or that some
158     // of the pages are locked or shared.  Neither should occur.
159     assert(errno == EAGAIN || errno == ENOMEM);
160   }
161 }
162
163 #else
164
165 void MemoryIdler::unmapUnusedStack(size_t retain) {
166 }
167
168 #endif
169
170 }}