folly: replace old-style header guards with "pragma once"
[folly.git] / folly / detail / CacheLocality.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 <sched.h>
20 #include <algorithm>
21 #include <atomic>
22 #include <cassert>
23 #include <functional>
24 #include <limits>
25 #include <string>
26 #include <type_traits>
27 #include <vector>
28 #include <pthread.h>
29 #include <folly/Hash.h>
30 #include <folly/Likely.h>
31 #include <folly/Portability.h>
32
33 namespace folly {
34 namespace detail {
35
36 // This file contains several classes that might be useful if you are
37 // trying to dynamically optimize cache locality: CacheLocality reads
38 // cache sharing information from sysfs to determine how CPUs should be
39 // grouped to minimize contention, Getcpu provides fast access to the
40 // current CPU via __vdso_getcpu, and AccessSpreader uses these two to
41 // optimally spread accesses among a predetermined number of stripes.
42 //
43 // AccessSpreader<>::current(n) microbenchmarks at 22 nanos, which is
44 // substantially less than the cost of a cache miss.  This means that we
45 // can effectively use it to reduce cache line ping-pong on striped data
46 // structures such as IndexedMemPool or statistics counters.
47 //
48 // Because CacheLocality looks at all of the cache levels, it can be
49 // used for different levels of optimization.  AccessSpreader(2) does
50 // per-chip spreading on a dual socket system.  AccessSpreader(numCpus)
51 // does perfect per-cpu spreading.  AccessSpreader(numCpus / 2) does
52 // perfect L1 spreading in a system with hyperthreading enabled.
53
54 struct CacheLocality {
55
56   /// 1 more than the maximum value that can be returned from sched_getcpu
57   /// or getcpu.  This is the number of hardware thread contexts provided
58   /// by the processors
59   size_t numCpus;
60
61   /// Holds the number of caches present at each cache level (0 is
62   /// the closest to the cpu).  This is the number of AccessSpreader
63   /// stripes needed to avoid cross-cache communication at the specified
64   /// layer.  numCachesByLevel.front() is the number of L1 caches and
65   /// numCachesByLevel.back() is the number of last-level caches.
66   std::vector<size_t> numCachesByLevel;
67
68   /// A map from cpu (from sched_getcpu or getcpu) to an index in the
69   /// range 0..numCpus-1, where neighboring locality indices are more
70   /// likely to share caches then indices far away.  All of the members
71   /// of a particular cache level be contiguous in their locality index.
72   /// For example, if numCpus is 32 and numCachesByLevel.back() is 2,
73   /// then cpus with a locality index < 16 will share one last-level
74   /// cache and cpus with a locality index >= 16 will share the other.
75   std::vector<size_t> localityIndexByCpu;
76
77   /// Returns the best CacheLocality information available for the current
78   /// system, cached for fast access.  This will be loaded from sysfs if
79   /// possible, otherwise it will be correct in the number of CPUs but
80   /// not in their sharing structure.
81   ///
82   /// If you are into yo dawgs, this is a shared cache of the local
83   /// locality of the shared caches.
84   ///
85   /// The template parameter here is used to allow injection of a
86   /// repeatable CacheLocality structure during testing.  Rather than
87   /// inject the type of the CacheLocality provider into every data type
88   /// that transitively uses it, all components select between the default
89   /// sysfs implementation and a deterministic implementation by keying
90   /// off the type of the underlying atomic.  See DeterministicScheduler.
91   template <template <typename> class Atom = std::atomic>
92   static const CacheLocality& system();
93
94   /// Reads CacheLocality information from a tree structured like
95   /// the sysfs filesystem.  The provided function will be evaluated
96   /// for each sysfs file that needs to be queried.  The function
97   /// should return a string containing the first line of the file
98   /// (not including the newline), or an empty string if the file does
99   /// not exist.  The function will be called with paths of the form
100   /// /sys/devices/system/cpu/cpu*/cache/index*/{type,shared_cpu_list} .
101   /// Throws an exception if no caches can be parsed at all.
102   static CacheLocality readFromSysfsTree(
103       const std::function<std::string(std::string)>& mapping);
104
105   /// Reads CacheLocality information from the real sysfs filesystem.
106   /// Throws an exception if no cache information can be loaded.
107   static CacheLocality readFromSysfs();
108
109   /// Returns a usable (but probably not reflective of reality)
110   /// CacheLocality structure with the specified number of cpus and a
111   /// single cache level that associates one cpu per cache.
112   static CacheLocality uniform(size_t numCpus);
113
114   enum {
115     /// Memory locations on the same cache line are subject to false
116     /// sharing, which is very bad for performance.  Microbenchmarks
117     /// indicate that pairs of cache lines also see interference under
118     /// heavy use of atomic operations (observed for atomic increment on
119     /// Sandy Bridge).  See FOLLY_ALIGN_TO_AVOID_FALSE_SHARING
120     kFalseSharingRange = 128
121   };
122
123   static_assert(
124       kFalseSharingRange == 128,
125       "FOLLY_ALIGN_TO_AVOID_FALSE_SHARING should track kFalseSharingRange");
126 };
127
128 // TODO replace __attribute__ with alignas and 128 with kFalseSharingRange
129
130 /// An attribute that will cause a variable or field to be aligned so that
131 /// it doesn't have false sharing with anything at a smaller memory address.
132 #define FOLLY_ALIGN_TO_AVOID_FALSE_SHARING FOLLY_ALIGNED(128)
133
134 /// Knows how to derive a function pointer to the VDSO implementation of
135 /// getcpu(2), if available
136 struct Getcpu {
137   /// Function pointer to a function with the same signature as getcpu(2).
138   typedef int (*Func)(unsigned* cpu, unsigned* node, void* unused);
139
140   /// Returns a pointer to the VDSO implementation of getcpu(2), if
141   /// available, or nullptr otherwise.  This function may be quite
142   /// expensive, be sure to cache the result.
143   static Func resolveVdsoFunc();
144 };
145
146 #ifdef FOLLY_TLS
147 template <template <typename> class Atom>
148 struct SequentialThreadId {
149
150   /// Returns the thread id assigned to the current thread
151   static size_t get() {
152     auto rv = currentId;
153     if (UNLIKELY(rv == 0)) {
154       rv = currentId = ++prevId;
155     }
156     return rv;
157   }
158
159  private:
160   static Atom<size_t> prevId;
161
162   static FOLLY_TLS size_t currentId;
163 };
164 #endif
165
166 struct HashingThreadId {
167   static size_t get() {
168     pthread_t pid = pthread_self();
169     uint64_t id = 0;
170     memcpy(&id, &pid, std::min(sizeof(pid), sizeof(id)));
171     return hash::twang_32from64(id);
172   }
173 };
174
175 /// A class that lazily binds a unique (for each implementation of Atom)
176 /// identifier to a thread.  This is a fallback mechanism for the access
177 /// spreader if __vdso_getcpu can't be loaded
178 template <typename ThreadId>
179 struct FallbackGetcpu {
180   /// Fills the thread id into the cpu and node out params (if they
181   /// are non-null).  This method is intended to act like getcpu when a
182   /// fast-enough form of getcpu isn't available or isn't desired
183   static int getcpu(unsigned* cpu, unsigned* node, void* /* unused */) {
184     auto id = ThreadId::get();
185     if (cpu) {
186       *cpu = id;
187     }
188     if (node) {
189       *node = id;
190     }
191     return 0;
192   }
193 };
194
195 #ifdef FOLLY_TLS
196 typedef FallbackGetcpu<SequentialThreadId<std::atomic>> FallbackGetcpuType;
197 #else
198 typedef FallbackGetcpu<HashingThreadId> FallbackGetcpuType;
199 #endif
200
201 /// AccessSpreader arranges access to a striped data structure in such a
202 /// way that concurrently executing threads are likely to be accessing
203 /// different stripes.  It does NOT guarantee uncontended access.
204 /// Your underlying algorithm must be thread-safe without spreading, this
205 /// is merely an optimization.  AccessSpreader::current(n) is typically
206 /// much faster than a cache miss (12 nanos on my dev box, tested fast
207 /// in both 2.6 and 3.2 kernels).
208 ///
209 /// If available (and not using the deterministic testing implementation)
210 /// AccessSpreader uses the getcpu system call via VDSO and the
211 /// precise locality information retrieved from sysfs by CacheLocality.
212 /// This provides optimal anti-sharing at a fraction of the cost of a
213 /// cache miss.
214 ///
215 /// When there are not as many stripes as processors, we try to optimally
216 /// place the cache sharing boundaries.  This means that if you have 2
217 /// stripes and run on a dual-socket system, your 2 stripes will each get
218 /// all of the cores from a single socket.  If you have 16 stripes on a
219 /// 16 core system plus hyperthreading (32 cpus), each core will get its
220 /// own stripe and there will be no cache sharing at all.
221 ///
222 /// AccessSpreader has a fallback mechanism for when __vdso_getcpu can't be
223 /// loaded, or for use during deterministic testing.  Using sched_getcpu
224 /// or the getcpu syscall would negate the performance advantages of
225 /// access spreading, so we use a thread-local value and a shared atomic
226 /// counter to spread access out.  On systems lacking both a fast getcpu()
227 /// and TLS, we hash the thread id to spread accesses.
228 ///
229 /// AccessSpreader is templated on the template type that is used
230 /// to implement atomics, as a way to instantiate the underlying
231 /// heuristics differently for production use and deterministic unit
232 /// testing.  See DeterministicScheduler for more.  If you aren't using
233 /// DeterministicScheduler, you can just use the default template parameter
234 /// all of the time.
235 template <template <typename> class Atom = std::atomic>
236 struct AccessSpreader {
237
238   /// Returns the stripe associated with the current CPU.  The returned
239   /// value will be < numStripes.
240   static size_t current(size_t numStripes) {
241     // widthAndCpuToStripe[0] will actually work okay (all zeros), but
242     // something's wrong with the caller
243     assert(numStripes > 0);
244
245     unsigned cpu;
246     getcpuFunc(&cpu, nullptr, nullptr);
247     return widthAndCpuToStripe[std::min(size_t(kMaxCpus),
248                                         numStripes)][cpu % kMaxCpus];
249   }
250
251  private:
252   /// If there are more cpus than this nothing will crash, but there
253   /// might be unnecessary sharing
254   enum { kMaxCpus = 128 };
255
256   typedef uint8_t CompactStripe;
257
258   static_assert((kMaxCpus & (kMaxCpus - 1)) == 0,
259                 "kMaxCpus should be a power of two so modulo is fast");
260   static_assert(kMaxCpus - 1 <= std::numeric_limits<CompactStripe>::max(),
261                 "stripeByCpu element type isn't wide enough");
262
263   /// Points to the getcpu-like function we are using to obtain the
264   /// current cpu.  It should not be assumed that the returned cpu value
265   /// is in range.  We use a static for this so that we can prearrange a
266   /// valid value in the pre-constructed state and avoid the need for a
267   /// conditional on every subsequent invocation (not normally a big win,
268   /// but 20% on some inner loops here).
269   static Getcpu::Func getcpuFunc;
270
271   /// For each level of splitting up to kMaxCpus, maps the cpu (mod
272   /// kMaxCpus) to the stripe.  Rather than performing any inequalities
273   /// or modulo on the actual number of cpus, we just fill in the entire
274   /// array.
275   static CompactStripe widthAndCpuToStripe[kMaxCpus + 1][kMaxCpus];
276
277   static bool initialized;
278
279   /// Returns the best getcpu implementation for Atom
280   static Getcpu::Func pickGetcpuFunc();
281
282   /// Always claims to be on CPU zero, node zero
283   static int degenerateGetcpu(unsigned* cpu, unsigned* node, void*) {
284     if (cpu != nullptr) {
285       *cpu = 0;
286     }
287     if (node != nullptr) {
288       *node = 0;
289     }
290     return 0;
291   }
292
293   // The function to call for fast lookup of getcpu is a singleton, as
294   // is the precomputed table of locality information.  AccessSpreader
295   // is used in very tight loops, however (we're trying to race an L1
296   // cache miss!), so the normal singleton mechanisms are noticeably
297   // expensive.  Even a not-taken branch guarding access to getcpuFunc
298   // slows AccessSpreader::current from 12 nanos to 14.  As a result, we
299   // populate the static members with simple (but valid) values that can
300   // be filled in by the linker, and then follow up with a normal static
301   // initializer call that puts in the proper version.  This means that
302   // when there are initialization order issues we will just observe a
303   // zero stripe.  Once a sanitizer gets smart enough to detect this as
304   // a race or undefined behavior, we can annotate it.
305
306   static bool initialize() {
307     getcpuFunc = pickGetcpuFunc();
308
309     auto& cacheLocality = CacheLocality::system<Atom>();
310     auto n = cacheLocality.numCpus;
311     for (size_t width = 0; width <= kMaxCpus; ++width) {
312       auto numStripes = std::max(size_t{1}, width);
313       for (size_t cpu = 0; cpu < kMaxCpus && cpu < n; ++cpu) {
314         auto index = cacheLocality.localityIndexByCpu[cpu];
315         assert(index < n);
316         // as index goes from 0..n, post-transform value goes from
317         // 0..numStripes
318         widthAndCpuToStripe[width][cpu] = (index * numStripes) / n;
319         assert(widthAndCpuToStripe[width][cpu] < numStripes);
320       }
321       for (size_t cpu = n; cpu < kMaxCpus; ++cpu) {
322         widthAndCpuToStripe[width][cpu] = widthAndCpuToStripe[width][cpu - n];
323       }
324     }
325     return true;
326   }
327 };
328
329 template <>
330 Getcpu::Func AccessSpreader<std::atomic>::pickGetcpuFunc();
331
332 #define DECLARE_ACCESS_SPREADER_TYPE(Atom)                                     \
333   namespace folly {                                                            \
334   namespace detail {                                                           \
335   template <>                                                                  \
336   Getcpu::Func AccessSpreader<Atom>::getcpuFunc =                              \
337       AccessSpreader<Atom>::degenerateGetcpu;                                  \
338   template <>                                                                  \
339   typename AccessSpreader<Atom>::CompactStripe                                 \
340       AccessSpreader<Atom>::widthAndCpuToStripe[129][128] = {};                \
341   template <>                                                                  \
342   bool AccessSpreader<Atom>::initialized = AccessSpreader<Atom>::initialize(); \
343   }                                                                            \
344   }
345
346 } // namespace detail
347 } // namespace folly