2 * Copyright 2013 Facebook, Inc.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 #ifndef FOLLY_DETAIL_CACHELOCALITY_H_
18 #define FOLLY_DETAIL_CACHELOCALITY_H_
26 #include <type_traits>
28 #include "folly/Likely.h"
30 namespace folly { namespace detail {
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.
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.
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.
50 struct CacheLocality {
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
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;
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;
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.
79 /// If you are into yo dawgs, this is a shared cache of the local
80 /// locality of the shared caches.
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();
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);
103 /// Reads CacheLocality information from the real sysfs filesystem.
104 /// Throws an exception if no cache information can be loaded.
105 static CacheLocality readFromSysfs();
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);
113 /// Holds a function pointer to the VDSO implementation of getcpu(2),
116 /// Function pointer to a function with the same signature as getcpu(2).
117 typedef int (*Func)(unsigned* cpu, unsigned* node, void* unused);
119 /// Returns a pointer to the VDSO implementation of getcpu(2), if
120 /// available, or nullptr otherwise
121 static Func vdsoFunc();
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 {
131 /// Returns the thread id assigned to the current thread
132 static size_t get() {
134 if (UNLIKELY(rv == 0)) {
135 rv = currentId = ++prevId;
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) {
155 static Atom<size_t> prevId;
157 // TODO: switch to thread_local
158 static __thread size_t currentId;
161 template <template<typename> class Atom, size_t kMaxCpus>
162 struct AccessSpreaderArray;
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).
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).
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
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.
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.
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
203 template <template<typename> class Atom = std::atomic>
204 struct AccessSpreader {
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);
212 // the last shared element handles all large sizes
213 return AccessSpreaderArray<Atom,kMaxCpus>::sharedInstance[
214 std::min(size_t(kMaxCpus), numStripes)];
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();
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;
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;
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
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)
248 auto n = cacheLocality.numCpus;
249 for (size_t cpu = 0; cpu < kMaxCpus && cpu < n; ++cpu) {
250 auto index = cacheLocality.localityIndexByCpu[cpu];
252 // as index goes from 0..n, post-transform value goes from
254 stripeByCpu[cpu] = (index * numStripes_) / n;
255 assert(stripeByCpu[cpu] < numStripes_);
257 for (size_t cpu = n; cpu < kMaxCpus; ++cpu) {
258 stripeByCpu[cpu] = stripeByCpu[cpu - n];
262 /// Returns 1 more than the maximum value that can be returned from
264 size_t numStripes() const {
268 /// Returns the stripe associated with the current CPU
269 size_t current() const {
271 getcpuFunc_(&cpu, nullptr, nullptr);
272 return stripeByCpu[cpu % kMaxCpus];
277 /// If there are more cpus than this nothing will crash, but there
278 /// might be unnecessary sharing
279 enum { kMaxCpus = 128 };
281 typedef uint8_t CompactStripe;
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");
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_;
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];
302 /// Returns the best getcpu implementation for this type and width
303 /// of AccessSpreader
304 static Getcpu::Func pickGetcpuFunc(size_t numStripes);
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 {
312 AccessSpreaderArray() {
313 for (size_t i = 0; i <= kMaxStripe; ++i) {
314 new (raw + i) AccessSpreader<Atom>(std::max(size_t(1), i));
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();
325 AccessSpreader<Atom> const& operator[] (size_t index) const {
326 return *static_cast<AccessSpreader<Atom> const*>(
327 static_cast<void const*>(raw + index));
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 };
338 // AccessSpreader uses sharedInstance
339 friend AccessSpreader<Atom>;
341 static AccessSpreaderArray<Atom,kMaxStripe> sharedInstance;
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
352 #endif /* FOLLY_DETAIL_CacheLocality_H_ */