0d839bec14e4b889977a93f5aeeb117c3e3a6742
[folly.git] / folly / detail / CacheLocality.h
1 /*
2  * Copyright 2013 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 #ifndef FOLLY_DETAIL_CACHELOCALITY_H_
18 #define FOLLY_DETAIL_CACHELOCALITY_H_
19
20 #include <sched.h>
21 #include <atomic>
22 #include <cassert>
23 #include <functional>
24 #include <limits>
25 #include <string>
26 #include <type_traits>
27 #include <vector>
28 #include "folly/Likely.h"
29
30 namespace folly { namespace detail {
31
32 // This file contains several classes that might be useful if you are
33 // trying to dynamically optimize cache locality: CacheLocality reads
34 // cache sharing information from sysfs to determine how CPUs should be
35 // grouped to minimize contention, Getcpu provides fast access to the
36 // current CPU via __vdso_getcpu, and AccessSpreader uses these two to
37 // optimally spread accesses among a predetermined number of stripes.
38 //
39 // AccessSpreader<>::current(n) microbenchmarks at 22 nanos, which is
40 // substantially less than the cost of a cache miss.  This means that we
41 // can effectively use it to reduce cache line ping-pong on striped data
42 // structures such as IndexedMemPool or statistics counters.
43 //
44 // Because CacheLocality looks at all of the cache levels, it can be
45 // used for different levels of optimization.  AccessSpreader(2) does
46 // per-chip spreading on a dual socket system.  AccessSpreader(numCpus)
47 // does perfect per-cpu spreading.  AccessSpreader(numCpus / 2) does
48 // perfect L1 spreading in a system with hyperthreading enabled.
49
50 struct CacheLocality {
51
52   /// 1 more than the maximum value that can be returned from sched_getcpu
53   /// or getcpu.  This is the number of hardware thread contexts provided
54   /// by the processors
55   size_t numCpus;
56
57   /// Holds the number of caches present at each cache level (0 is
58   /// the closest to the cpu).  This is the number of AccessSpreader
59   /// stripes needed to avoid cross-cache communication at the specified
60   /// layer.  numCachesByLevel.front() is the number of L1 caches and
61   /// numCachesByLevel.back() is the number of last-level caches.
62   std::vector<size_t> numCachesByLevel;
63
64   /// A map from cpu (from sched_getcpu or getcpu) to an index in the
65   /// range 0..numCpus-1, where neighboring locality indices are more
66   /// likely to share caches then indices far away.  All of the members
67   /// of a particular cache level be contiguous in their locality index.
68   /// For example, if numCpus is 32 and numCachesByLevel.back() is 2,
69   /// then cpus with a locality index < 16 will share one last-level
70   /// cache and cpus with a locality index >= 16 will share the other.
71   std::vector<size_t> localityIndexByCpu;
72
73
74   /// Returns the best CacheLocality information available for the current
75   /// system, cached for fast access.  This will be loaded from sysfs if
76   /// possible, otherwise it will be correct in the number of CPUs but
77   /// not in their sharing structure.
78   ///
79   /// If you are into yo dawgs, this is a shared cache of the local
80   /// locality of the shared caches.
81   ///
82   /// The template parameter here is used to allow injection of a
83   /// repeatable CacheLocality structure during testing.  Rather than
84   /// inject the type of the CacheLocality provider into every data type
85   /// that transitively uses it, all components select between the default
86   /// sysfs implementation and a deterministic implementation by keying
87   /// off the type of the underlying atomic.  See DeterministicScheduler.
88   template <template<typename> class Atom = std::atomic>
89   static const CacheLocality& system();
90
91
92   /// Reads CacheLocality information from a tree structured like
93   /// the sysfs filesystem.  The provided function will be evaluated
94   /// for each sysfs file that needs to be queried.  The function
95   /// should return a string containing the first line of the file
96   /// (not including the newline), or an empty string if the file does
97   /// not exist.  The function will be called with paths of the form
98   /// /sys/devices/system/cpu/cpu*/cache/index*/{type,shared_cpu_list} .
99   /// Throws an exception if no caches can be parsed at all.
100   static CacheLocality readFromSysfsTree(
101       const std::function<std::string(std::string)>& mapping);
102
103   /// Reads CacheLocality information from the real sysfs filesystem.
104   /// Throws an exception if no cache information can be loaded.
105   static CacheLocality readFromSysfs();
106
107   /// Returns a usable (but probably not reflective of reality)
108   /// CacheLocality structure with the specified number of cpus and a
109   /// single cache level that associates one cpu per cache.
110   static CacheLocality uniform(size_t numCpus);
111 };
112
113 /// Holds a function pointer to the VDSO implementation of getcpu(2),
114 /// if available
115 struct Getcpu {
116   /// Function pointer to a function with the same signature as getcpu(2).
117   typedef int (*Func)(unsigned* cpu, unsigned* node, void* unused);
118
119   /// Returns a pointer to the VDSO implementation of getcpu(2), if
120   /// available, or nullptr otherwise
121   static Func vdsoFunc();
122 };
123
124 /// A class that lazily binds a unique (for each implementation of Atom)
125 /// identifier to a thread.  This is a fallback mechanism for the access
126 /// spreader if we are in testing (using DeterministicAtomic) or if
127 /// __vdso_getcpu can't be dynamically loaded
128 template <template<typename> class Atom>
129 struct SequentialThreadId {
130
131   /// Returns the thread id assigned to the current thread
132   static size_t get() {
133     auto rv = currentId;
134     if (UNLIKELY(rv == 0)) {
135       rv = currentId = ++prevId;
136     }
137     return rv;
138   }
139
140   /// Fills the thread id into the cpu and node out params (if they
141   /// are non-null).  This method is intended to act like getcpu when a
142   /// fast-enough form of getcpu isn't available or isn't desired
143   static int getcpu(unsigned* cpu, unsigned* node, void* unused) {
144     auto id = get();
145     if (cpu) {
146       *cpu = id;
147     }
148     if (node) {
149       *node = id;
150     }
151     return 0;
152   }
153
154  private:
155   static Atom<size_t> prevId;
156
157   // TODO: switch to thread_local
158   static __thread size_t currentId;
159 };
160
161 template <template<typename> class Atom, size_t kMaxCpus>
162 struct AccessSpreaderArray;
163
164 /// AccessSpreader arranges access to a striped data structure in such a
165 /// way that concurrently executing threads are likely to be accessing
166 /// different stripes.  It does NOT guarantee uncontended access.
167 /// Your underlying algorithm must be thread-safe without spreading, this
168 /// is merely an optimization.  AccessSpreader::current(n) is typically
169 /// much faster than a cache miss (22 nanos on my dev box, tested fast
170 /// in both 2.6 and 3.2 kernels).
171 ///
172 /// You are free to create your own AccessSpreader-s or to cache the
173 /// results of AccessSpreader<>::shared(n), but you will probably want
174 /// to use one of the system-wide shared ones.  Calling .current() on
175 /// a particular AccessSpreader instance only saves about 1 nanosecond
176 /// over calling AccessSpreader<>::shared(n).
177 ///
178 /// If available (and not using the deterministic testing implementation)
179 /// AccessSpreader uses the getcpu system call via VDSO and the
180 /// precise locality information retrieved from sysfs by CacheLocality.
181 /// This provides optimal anti-sharing at a fraction of the cost of a
182 /// cache miss.
183 ///
184 /// When there are not as many stripes as processors, we try to optimally
185 /// place the cache sharing boundaries.  This means that if you have 2
186 /// stripes and run on a dual-socket system, your 2 stripes will each get
187 /// all of the cores from a single socket.  If you have 16 stripes on a
188 /// 16 core system plus hyperthreading (32 cpus), each core will get its
189 /// own stripe and there will be no cache sharing at all.
190 ///
191 /// AccessSpreader has a fallback mechanism for when __vdso_getcpu can't be
192 /// loaded, or for use during deterministic testing.  Using sched_getcpu or
193 /// the getcpu syscall would negate the performance advantages of access
194 /// spreading, so we use a thread-local value and a shared atomic counter
195 /// to spread access out.
196 ///
197 /// AccessSpreader is templated on the template type that is used
198 /// to implement atomics, as a way to instantiate the underlying
199 /// heuristics differently for production use and deterministic unit
200 /// testing.  See DeterministicScheduler for more.  If you aren't using
201 /// DeterministicScheduler, you can just use the default template parameter
202 /// all of the time.
203 template <template<typename> class Atom = std::atomic>
204 struct AccessSpreader {
205
206   /// Returns a never-destructed shared AccessSpreader instance.
207   /// numStripes should be > 0.
208   static const AccessSpreader& shared(size_t numStripes) {
209     // sharedInstances[0] actually has numStripes == 1
210     assert(numStripes > 0);
211
212     // the last shared element handles all large sizes
213     return AccessSpreaderArray<Atom,kMaxCpus>::sharedInstance[
214         std::min(size_t(kMaxCpus), numStripes)];
215   }
216
217   /// Returns the stripe associated with the current CPU, assuming
218   /// that there are numStripes (non-zero) stripes.  Equivalent to
219   /// AccessSpreader::shared(numStripes)->current.
220   static size_t current(size_t numStripes) {
221     return shared(numStripes).current();
222   }
223
224   /// stripeByCore uses 1 stripe per L1 cache, according to
225   /// CacheLocality::system<>().  Use stripeByCore.numStripes() to see
226   /// its width, or stripeByCore.current() to get the current stripe
227   static const AccessSpreader stripeByCore;
228
229   /// stripeByChip uses 1 stripe per last-level cache, which is the fewest
230   /// number of stripes for which off-chip communication can be avoided
231   /// (assuming all caches are on-chip).  Use stripeByChip.numStripes()
232   /// to see its width, or stripeByChip.current() to get the current stripe
233   static const AccessSpreader stripeByChip;
234
235
236   /// Constructs an AccessSpreader that will return values from
237   /// 0 to numStripes-1 (inclusive), precomputing the mapping
238   /// from CPU to stripe.  There is no use in having more than
239   /// CacheLocality::system<Atom>().localityIndexByCpu.size() stripes or
240   /// kMaxCpus stripes
241   explicit AccessSpreader(size_t spreaderNumStripes,
242                           const CacheLocality& cacheLocality =
243                               CacheLocality::system<Atom>(),
244                           Getcpu::Func getcpuFunc = nullptr)
245     : getcpuFunc_(getcpuFunc ? getcpuFunc : pickGetcpuFunc(spreaderNumStripes))
246     , numStripes_(spreaderNumStripes)
247   {
248     auto n = cacheLocality.numCpus;
249     for (size_t cpu = 0; cpu < kMaxCpus && cpu < n; ++cpu) {
250       auto index = cacheLocality.localityIndexByCpu[cpu];
251       assert(index < n);
252       // as index goes from 0..n, post-transform value goes from
253       // 0..numStripes
254       stripeByCpu[cpu] = (index * numStripes_) / n;
255       assert(stripeByCpu[cpu] < numStripes_);
256     }
257     for (size_t cpu = n; cpu < kMaxCpus; ++cpu) {
258       stripeByCpu[cpu] = stripeByCpu[cpu - n];
259     }
260   }
261
262   /// Returns 1 more than the maximum value that can be returned from
263   /// current()
264   size_t numStripes() const {
265     return numStripes_;
266   }
267
268   /// Returns the stripe associated with the current CPU
269   size_t current() const {
270     unsigned cpu;
271     getcpuFunc_(&cpu, nullptr, nullptr);
272     return stripeByCpu[cpu % kMaxCpus];
273   }
274
275  private:
276
277   /// If there are more cpus than this nothing will crash, but there
278   /// might be unnecessary sharing
279   enum { kMaxCpus = 128 };
280
281   typedef uint8_t CompactStripe;
282
283   static_assert((kMaxCpus & (kMaxCpus - 1)) == 0,
284       "kMaxCpus should be a power of two so modulo is fast");
285   static_assert(kMaxCpus - 1 <= std::numeric_limits<CompactStripe>::max(),
286       "stripeByCpu element type isn't wide enough");
287
288
289   /// Points to the getcpu-like function we are using to obtain the
290   /// current cpu.  It should not be assumed that the returned cpu value
291   /// is in range.  We use a member for this instead of a static so that
292   /// this fetch preloads a prefix the stripeByCpu array
293   Getcpu::Func getcpuFunc_;
294
295   /// A precomputed map from cpu to stripe.  Rather than add a layer of
296   /// indirection requiring a dynamic bounds check and another cache miss,
297   /// we always precompute the whole array
298   CompactStripe stripeByCpu[kMaxCpus];
299
300   size_t numStripes_;
301
302   /// Returns the best getcpu implementation for this type and width
303   /// of AccessSpreader
304   static Getcpu::Func pickGetcpuFunc(size_t numStripes);
305 };
306
307 /// An array of kMaxCpus+1 AccessSpreader<Atom> instances constructed
308 /// with default params, with the zero-th element having 1 stripe
309 template <template<typename> class Atom, size_t kMaxStripe>
310 struct AccessSpreaderArray {
311
312   AccessSpreaderArray() {
313     for (size_t i = 0; i <= kMaxStripe; ++i) {
314       new (raw + i) AccessSpreader<Atom>(std::max(size_t(1), i));
315     }
316   }
317
318   ~AccessSpreaderArray() {
319     for (size_t i = 0; i <= kMaxStripe; ++i) {
320       auto p = static_cast<AccessSpreader<Atom>*>(static_cast<void*>(raw + i));
321       p->~AccessSpreader();
322     }
323   }
324
325   AccessSpreader<Atom> const& operator[] (size_t index) const {
326     return *static_cast<AccessSpreader<Atom> const*>(
327         static_cast<void const*>(raw + index));
328   }
329
330  private:
331
332   /// If we align the access spreaders at the beginning of a cache line
333   /// then getcpuFunc_ and the first 56 bytes of stripeByCpu will be on
334   /// the same cache line
335   enum { kAlignment = 64 };
336
337
338   // AccessSpreader uses sharedInstance
339   friend AccessSpreader<Atom>;
340
341   static AccessSpreaderArray<Atom,kMaxStripe> sharedInstance;
342
343
344   /// aligned_storage is uninitialized, we use placement new since there
345   /// is no AccessSpreader default constructor
346   typename std::aligned_storage<sizeof(AccessSpreader<Atom>),kAlignment>::type
347       raw[kMaxStripe + 1];
348 };
349
350 } }
351
352 #endif /* FOLLY_DETAIL_CacheLocality_H_ */
353