blob: 98c408997f9a789f8d8bb3b45512f6c883a2300e [file] [log] [blame]
John Zulauf79f06582021-02-27 18:38:39 -07001/* Copyright (c) 2015-2017, 2019-2021 The Khronos Group Inc.
2 * Copyright (c) 2015-2017, 2019-2021 Valve Corporation
3 * Copyright (c) 2015-2017, 2019-2021 LunarG, Inc.
Mark Lobodzinski6f2274e2015-09-22 09:33:21 -06004 *
Jon Ashburn3ebf1252016-04-19 11:30:31 -06005 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
Mark Lobodzinski6f2274e2015-09-22 09:33:21 -06008 *
Jon Ashburn3ebf1252016-04-19 11:30:31 -06009 * http://www.apache.org/licenses/LICENSE-2.0
Mark Lobodzinski6f2274e2015-09-22 09:33:21 -060010 *
Jon Ashburn3ebf1252016-04-19 11:30:31 -060011 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
Mark Lobodzinski6f2274e2015-09-22 09:33:21 -060016 *
Jon Ashburne922f712015-11-03 13:41:23 -070017 * Author: Mark Lobodzinski <mark@lunarg.com>
18 * Author: Courtney Goeltzenleuchter <courtney@LunarG.com>
Dave Houlton59a20702017-02-02 17:26:23 -070019 * Author: Dave Houlton <daveh@lunarg.com>
Mark Lobodzinski6eda00a2016-02-02 15:55:36 -070020 */
21
Mark Lobodzinski6f2274e2015-09-22 09:33:21 -060022#pragma once
John Zulauff05b3772019-04-03 18:04:23 -060023
24#include <cassert>
25#include <cstddef>
26#include <functional>
Mark Lobodzinski6f2274e2015-09-22 09:33:21 -060027#include <stdbool.h>
John Zulauf965d88d2018-04-12 15:47:26 -060028#include <string>
Mark Lobodzinski1079e1b2016-03-15 14:21:59 -060029#include <vector>
Mark Lobodzinski44145db2020-08-11 08:01:47 -060030#include <iomanip>
John Zulauf2c2ccd42019-04-05 13:13:13 -060031#include "cast_utils.h"
Dave Houlton3c9fca72017-03-27 17:25:54 -060032#include "vk_format_utils.h"
Mark Lobodzinski1079e1b2016-03-15 14:21:59 -060033#include "vk_layer_logging.h"
34
Courtney Goeltzenleuchterd2635502015-10-21 17:08:06 -060035#ifndef WIN32
Mark Lobodzinski64318ba2017-01-26 13:34:13 -070036#include <strings.h> // For ffs()
Courtney Goeltzenleuchter3698c622015-10-27 11:23:21 -060037#else
Mark Lobodzinski64318ba2017-01-26 13:34:13 -070038#include <intrin.h> // For __lzcnt()
Courtney Goeltzenleuchterd2635502015-10-21 17:08:06 -060039#endif
Mark Lobodzinski6f2274e2015-09-22 09:33:21 -060040
Petr Krausc3382e92019-12-14 00:41:30 +010041#define STRINGIFY(s) STRINGIFY_HELPER(s)
42#define STRINGIFY_HELPER(s) #s
43
Mark Lobodzinski6f2274e2015-09-22 09:33:21 -060044#ifdef __cplusplus
John Zulauf1507ee42020-05-18 11:33:09 -060045static inline VkExtent3D CastTo3D(const VkExtent2D &d2) {
46 VkExtent3D d3 = {d2.width, d2.height, 1};
47 return d3;
48}
49
50static inline VkOffset3D CastTo3D(const VkOffset2D &d2) {
51 VkOffset3D d3 = {d2.x, d2.y, 0};
52 return d3;
53}
54
Mark Lobodzinski44145db2020-08-11 08:01:47 -060055// Convert integer API version to a string
56static inline std::string StringAPIVersion(uint32_t version) {
57 std::stringstream version_name;
58 uint32_t major = VK_VERSION_MAJOR(version);
59 uint32_t minor = VK_VERSION_MINOR(version);
60 uint32_t patch = VK_VERSION_PATCH(version);
61 version_name << major << "." << minor << "." << patch << " (0x" << std::setfill('0') << std::setw(8) << std::hex << version
62 << ")";
63 return version_name.str();
64}
65
John Zulauf965d88d2018-04-12 15:47:26 -060066// Traits objects to allow string_join to operate on collections of const char *
67template <typename String>
68struct StringJoinSizeTrait {
69 static size_t size(const String &str) { return str.size(); }
70};
71
72template <>
73struct StringJoinSizeTrait<const char *> {
74 static size_t size(const char *str) {
75 if (!str) return 0;
76 return strlen(str);
77 }
78};
79// Similar to perl/python join
80// * String must support size, reserve, append, and be default constructable
81// * StringCollection must support size, const forward iteration, and store
82// strings compatible with String::append
83// * Accessor trait can be set if default accessors (compatible with string
84// and const char *) don't support size(StringCollection::value_type &)
85//
86// Return type based on sep type
87template <typename String = std::string, typename StringCollection = std::vector<String>,
88 typename Accessor = StringJoinSizeTrait<typename StringCollection::value_type>>
89static inline String string_join(const String &sep, const StringCollection &strings) {
90 String joined;
91 const size_t count = strings.size();
92 if (!count) return joined;
93
94 // Prereserved storage, s.t. we will execute in linear time (avoids reallocation copies)
95 size_t reserve = (count - 1) * sep.size();
96 for (const auto &str : strings) {
97 reserve += Accessor::size(str); // abstracted to allow const char * type in StringCollection
98 }
99 joined.reserve(reserve + 1);
100
101 // Seps only occur *between* strings entries, so first is special
102 auto current = strings.cbegin();
103 joined.append(*current);
104 ++current;
105 for (; current != strings.cend(); ++current) {
106 joined.append(sep);
107 joined.append(*current);
108 }
109 return joined;
110}
111
112// Requires StringCollection::value_type has a const char * constructor and is compatible the string_join::String above
113template <typename StringCollection = std::vector<std::string>, typename SepString = std::string>
114static inline SepString string_join(const char *sep, const StringCollection &strings) {
115 return string_join<SepString, StringCollection>(SepString(sep), strings);
116}
117
Petr Kraus168417e2019-09-07 16:45:40 +0200118static inline std::string string_trim(const std::string &s) {
119 const char *whitespace = " \t\f\v\n\r";
120
121 const auto trimmed_beg = s.find_first_not_of(whitespace);
122 if (trimmed_beg == std::string::npos) return "";
123
124 const auto trimmed_end = s.find_last_not_of(whitespace);
125 assert(trimmed_end != std::string::npos && trimmed_beg <= trimmed_end);
126
127 return s.substr(trimmed_beg, trimmed_end - trimmed_beg + 1);
128}
129
John Zulaufdf851b12018-06-12 14:49:04 -0600130// Perl/Python style join operation for general types using stream semantics
131// Note: won't be as fast as string_join above, but simpler to use (and code)
132// Note: Modifiable reference doesn't match the google style but does match std style for stream handling and algorithms
133template <typename Stream, typename String, typename ForwardIt>
134Stream &stream_join(Stream &stream, const String &sep, ForwardIt first, ForwardIt last) {
135 if (first != last) {
136 stream << *first;
137 ++first;
138 while (first != last) {
139 stream << sep << *first;
140 ++first;
141 }
142 }
143 return stream;
144}
145
146// stream_join For whole collections with forward iterators
147template <typename Stream, typename String, typename Collection>
148Stream &stream_join(Stream &stream, const String &sep, const Collection &values) {
149 return stream_join(stream, sep, values.cbegin(), values.cend());
150}
151
Mark Lobodzinskic1b5b882018-06-25 14:54:04 -0600152typedef void *dispatch_key;
153static inline dispatch_key get_dispatch_key(const void *object) { return (dispatch_key) * (VkLayerDispatchTable **)object; }
154
155VK_LAYER_EXPORT VkLayerInstanceCreateInfo *get_chain_info(const VkInstanceCreateInfo *pCreateInfo, VkLayerFunction func);
156VK_LAYER_EXPORT VkLayerDeviceCreateInfo *get_chain_info(const VkDeviceCreateInfo *pCreateInfo, VkLayerFunction func);
157
Chris Mayer334e72f2018-11-29 14:25:41 +0100158static inline bool IsPowerOfTwo(unsigned x) { return x && !(x & (x - 1)); }
Chris Mayer9bc9d092018-11-12 12:29:10 +0100159
sfricke-samsung8f658d42020-05-03 20:12:24 -0700160static inline uint32_t SampleCountSize(VkSampleCountFlagBits sample_count) {
161 uint32_t size = 0;
162 switch (sample_count) {
163 case VK_SAMPLE_COUNT_1_BIT:
164 size = 1;
165 break;
166 case VK_SAMPLE_COUNT_2_BIT:
167 size = 2;
168 break;
169 case VK_SAMPLE_COUNT_4_BIT:
170 size = 4;
171 break;
172 case VK_SAMPLE_COUNT_8_BIT:
173 size = 8;
174 break;
175 case VK_SAMPLE_COUNT_16_BIT:
176 size = 16;
177 break;
178 case VK_SAMPLE_COUNT_32_BIT:
179 size = 32;
180 break;
181 case VK_SAMPLE_COUNT_64_BIT:
182 size = 64;
183 break;
184 default:
185 size = 0;
186 }
187 return size;
188}
189
sfricke-samsungbd0e8052020-06-06 01:36:39 -0700190static inline bool IsIdentitySwizzle(VkComponentMapping components) {
191 // clang-format off
192 return (
193 ((components.r == VK_COMPONENT_SWIZZLE_IDENTITY) || (components.r == VK_COMPONENT_SWIZZLE_R)) &&
194 ((components.g == VK_COMPONENT_SWIZZLE_IDENTITY) || (components.g == VK_COMPONENT_SWIZZLE_G)) &&
195 ((components.b == VK_COMPONENT_SWIZZLE_IDENTITY) || (components.b == VK_COMPONENT_SWIZZLE_B)) &&
196 ((components.a == VK_COMPONENT_SWIZZLE_IDENTITY) || (components.a == VK_COMPONENT_SWIZZLE_A))
197 );
198 // clang-format on
199}
200
sfricke-samsungdcb31412021-08-29 22:16:34 -0700201static inline VkDeviceSize GetIndexAlignment(VkIndexType indexType) {
202 switch (indexType) {
203 case VK_INDEX_TYPE_UINT16:
204 return 2;
205 case VK_INDEX_TYPE_UINT32:
206 return 4;
207 case VK_INDEX_TYPE_UINT8_EXT:
208 return 1;
209 default:
210 // Not a real index type. Express no alignment requirement here; we expect upper layer
211 // to have already picked up on the enum being nonsense.
212 return 1;
213 }
214}
215
sfricke-samsunged028b02021-09-06 23:14:51 -0700216// Perform a zero-tolerant modulo operation
217static inline VkDeviceSize SafeModulo(VkDeviceSize dividend, VkDeviceSize divisor) {
218 VkDeviceSize result = 0;
219 if (divisor != 0) {
220 result = dividend % divisor;
221 }
222 return result;
223}
224
225static inline VkDeviceSize SafeDivision(VkDeviceSize dividend, VkDeviceSize divisor) {
226 VkDeviceSize result = 0;
227 if (divisor != 0) {
228 result = dividend / divisor;
229 }
230 return result;
231}
232
Mark Lobodzinski6f2274e2015-09-22 09:33:21 -0600233extern "C" {
234#endif
235
Jon Ashburnd883d812016-03-24 08:32:09 -0600236#define VK_LAYER_API_VERSION VK_MAKE_VERSION(1, 0, VK_HEADER_VERSION)
Mark Lobodzinskiadaac9d2016-01-08 11:07:56 -0700237
Mark Lobodzinskia9f33492016-01-11 14:17:05 -0700238typedef enum VkStringErrorFlagBits {
Jon Ashburn5484e0c2016-03-08 17:48:44 -0700239 VK_STRING_ERROR_NONE = 0x00000000,
240 VK_STRING_ERROR_LENGTH = 0x00000001,
241 VK_STRING_ERROR_BAD_DATA = 0x00000002,
Mark Lobodzinskia9f33492016-01-11 14:17:05 -0700242} VkStringErrorFlagBits;
243typedef VkFlags VkStringErrorFlags;
Mark Lobodzinski1ed594e2016-02-03 09:57:14 -0700244
Petr Kraus4ed81e32019-09-02 23:41:19 +0200245VK_LAYER_EXPORT void layer_debug_report_actions(debug_report_data *report_data, const VkAllocationCallbacks *pAllocator,
246 const char *layer_identifier);
Mark Young6ba8abe2017-11-09 10:37:04 -0700247
Petr Kraus4ed81e32019-09-02 23:41:19 +0200248VK_LAYER_EXPORT void layer_debug_messenger_actions(debug_report_data *report_data, const VkAllocationCallbacks *pAllocator,
249 const char *layer_identifier);
Mark Lobodzinski1079e1b2016-03-15 14:21:59 -0600250
Mike Stroyana551bc02016-09-28 09:42:28 -0600251VK_LAYER_EXPORT VkStringErrorFlags vk_string_validate(const int max_length, const char *char_array);
Mark Lobodzinskia0555012018-08-15 16:43:49 -0600252VK_LAYER_EXPORT bool white_list(const char *item, const std::set<std::string> &whitelist);
Mark Lobodzinski6f2274e2015-09-22 09:33:21 -0600253
Jon Ashburn5484e0c2016-03-08 17:48:44 -0700254static inline int u_ffs(int val) {
Courtney Goeltzenleuchterd2635502015-10-21 17:08:06 -0600255#ifdef WIN32
Mark Lobodzinski5ddf6c32015-12-16 17:47:28 -0700256 unsigned long bit_pos = 0;
Mike Stroyandebb9842016-01-07 10:05:21 -0700257 if (_BitScanForward(&bit_pos, val) != 0) {
Mark Lobodzinski5ddf6c32015-12-16 17:47:28 -0700258 bit_pos += 1;
259 }
260 return bit_pos;
Courtney Goeltzenleuchterd2635502015-10-21 17:08:06 -0600261#else
Mark Lobodzinski5ddf6c32015-12-16 17:47:28 -0700262 return ffs(val);
Courtney Goeltzenleuchterd2635502015-10-21 17:08:06 -0600263#endif
264}
Mark Lobodzinski6f2274e2015-09-22 09:33:21 -0600265
266#ifdef __cplusplus
267}
268#endif
Jeff Bolz89b9a502019-08-20 08:58:51 -0500269
Jeremy Gebben32811462021-09-20 12:54:20 -0600270#ifdef __cplusplus
Jeremy Gebbena7c3a352021-09-20 12:54:20 -0600271// clang sets _MSC_VER to 1800 and _MSC_FULL_VER to 180000000, but we only want to clean up after MSVC.
272#if defined(_MSC_FULL_VER) && !defined(__clang__)
Bruce Dawson5fab7f82020-06-09 16:23:07 -0700273// Minimum Visual Studio 2015 Update 2, or libc++ with C++17
Jeremy Gebbena7c3a352021-09-20 12:54:20 -0600274// But, before Visual Studio 2017 version 15.7, __cplusplus is not set
275// correctly. See:
276// https://docs.microsoft.com/en-us/cpp/build/reference/zc-cplusplus?view=msvc-160
277// Also, according to commit e2a6c442cb1e4, SDKs older than NTDDI_WIN10_RS2 do not
278// support shared_mutex.
279#if _MSC_FULL_VER >= 190023918 && NTDDI_VERSION > NTDDI_WIN10_RS2 && (!defined(_LIBCPP_VERSION) || __cplusplus >= 201703)
Jeremy Gebben32811462021-09-20 12:54:20 -0600280#define VVL_USE_SHARED_MUTEX 1
281#endif
282#elif __cplusplus >= 201703
283#define VVL_USE_SHARED_MUTEX 1
Jeremy Gebben7891d762021-10-11 17:17:58 -0600284#elif __cplusplus >= 201402
285#define VVL_USE_SHARED_TIMED_MUTEX 1
Jeremy Gebben32811462021-09-20 12:54:20 -0600286#endif
287
Jeremy Gebben7891d762021-10-11 17:17:58 -0600288#if defined(VVL_USE_SHARED_MUTEX) || defined(VVL_USE_SHARED_TIMED_MUTEX)
Jeff Bolz89b9a502019-08-20 08:58:51 -0500289#include <shared_mutex>
290#endif
291
Jeff Bolzcaeccc72019-10-15 15:35:26 -0500292class ReadWriteLock {
293 private:
Jeremy Gebben32811462021-09-20 12:54:20 -0600294#if defined(VVL_USE_SHARED_MUTEX)
Jeff Bolzcaeccc72019-10-15 15:35:26 -0500295 typedef std::shared_mutex lock_t;
Jeremy Gebben7891d762021-10-11 17:17:58 -0600296#elif defined(VVL_USE_SHARED_TIMED_MUTEX)
297 typedef std::shared_timed_mutex lock_t;
Jeff Bolzcaeccc72019-10-15 15:35:26 -0500298#else
299 typedef std::mutex lock_t;
300#endif
301
302 public:
303 void lock() { m_lock.lock(); }
304 bool try_lock() { return m_lock.try_lock(); }
305 void unlock() { m_lock.unlock(); }
Jeremy Gebben7891d762021-10-11 17:17:58 -0600306#if defined(VVL_USE_SHARED_MUTEX) || defined(VVL_USE_SHARED_TIMED_MUTEX)
Jeff Bolzcaeccc72019-10-15 15:35:26 -0500307 void lock_shared() { m_lock.lock_shared(); }
308 bool try_lock_shared() { return m_lock.try_lock_shared(); }
309 void unlock_shared() { m_lock.unlock_shared(); }
310#else
311 void lock_shared() { lock(); }
312 bool try_lock_shared() { return try_lock(); }
313 void unlock_shared() { unlock(); }
314#endif
315 private:
316 lock_t m_lock;
317};
318
Jeremy Gebben7891d762021-10-11 17:17:58 -0600319#if defined(VVL_USE_SHARED_MUTEX) || defined(VVL_USE_SHARED_TIMED_MUTEX)
Jeff Bolzcaeccc72019-10-15 15:35:26 -0500320typedef std::shared_lock<ReadWriteLock> read_lock_guard_t;
Jeff Bolzcaeccc72019-10-15 15:35:26 -0500321#else
322typedef std::unique_lock<ReadWriteLock> read_lock_guard_t;
Jeff Bolzcaeccc72019-10-15 15:35:26 -0500323#endif
Jeremy Gebben7891d762021-10-11 17:17:58 -0600324typedef std::unique_lock<ReadWriteLock> write_lock_guard_t;
Jeff Bolzcaeccc72019-10-15 15:35:26 -0500325
Jeff Bolz89b9a502019-08-20 08:58:51 -0500326// Limited concurrent_unordered_map that supports internally-synchronized
327// insert/erase/access. Splits locking across N buckets and uses shared_mutex
328// for read/write locking. Iterators are not supported. The following
329// operations are supported:
330//
331// insert_or_assign: Insert a new element or update an existing element.
Jeff Bolzfd3bb242019-08-22 06:10:49 -0500332// insert: Insert a new element and return whether it was inserted.
Jeff Bolz89b9a502019-08-20 08:58:51 -0500333// erase: Remove an element.
Jeff Bolzfd3bb242019-08-22 06:10:49 -0500334// contains: Returns true if the key is in the map.
Jeff Bolz89b9a502019-08-20 08:58:51 -0500335// find: Returns != end() if found, value is in ret->second.
336// pop: Erases and returns the erased value if found.
337//
338// find/end: find returns a vaguely iterator-like type that can be compared to
339// end and can use iter->second to retrieve the reference. This is to ease porting
340// for existing code that combines the existence check and lookup in a single
341// operation (and thus a single lock). i.e.:
342//
343// auto iter = map.find(key);
344// if (iter != map.end()) {
345// T t = iter->second;
346// ...
Jeff Bolzfd3bb242019-08-22 06:10:49 -0500347//
348// snapshot: Return an array of elements (key, value pairs) that satisfy an optional
349// predicate. This can be used as a substitute for iterators in exceptional cases.
Jeremy Gebbencbf22862021-03-03 12:01:22 -0700350template <typename Key, typename T, int BUCKETSLOG2 = 2, typename Hash = layer_data::hash<Key>>
Jeff Bolz89b9a502019-08-20 08:58:51 -0500351class vl_concurrent_unordered_map {
Petr Kraus4ed81e32019-09-02 23:41:19 +0200352 public:
Jeff Bolz89b9a502019-08-20 08:58:51 -0500353 void insert_or_assign(const Key &key, const T &value) {
354 uint32_t h = ConcurrentMapHashObject(key);
355 write_lock_guard_t lock(locks[h].lock);
356 maps[h][key] = value;
357 }
358
Jeff Bolzfd3bb242019-08-22 06:10:49 -0500359 bool insert(const Key &key, const T &value) {
360 uint32_t h = ConcurrentMapHashObject(key);
361 write_lock_guard_t lock(locks[h].lock);
Jeremy Gebbencbf22862021-03-03 12:01:22 -0700362 auto ret = maps[h].emplace(key, value);
Jeff Bolzfd3bb242019-08-22 06:10:49 -0500363 return ret.second;
364 }
365
Jeff Bolz89b9a502019-08-20 08:58:51 -0500366 // returns size_type
367 size_t erase(const Key &key) {
368 uint32_t h = ConcurrentMapHashObject(key);
369 write_lock_guard_t lock(locks[h].lock);
370 return maps[h].erase(key);
371 }
372
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500373 bool contains(const Key &key) const {
Jeff Bolzfd3bb242019-08-22 06:10:49 -0500374 uint32_t h = ConcurrentMapHashObject(key);
375 read_lock_guard_t lock(locks[h].lock);
376 return maps[h].count(key) != 0;
377 }
378
Jeff Bolz89b9a502019-08-20 08:58:51 -0500379 // type returned by find() and end().
380 class FindResult {
Petr Kraus4ed81e32019-09-02 23:41:19 +0200381 public:
Jeff Bolzfd3bb242019-08-22 06:10:49 -0500382 FindResult(bool a, T b) : result(a, std::move(b)) {}
Jeff Bolz89b9a502019-08-20 08:58:51 -0500383
384 // == and != only support comparing against end()
385 bool operator==(const FindResult &other) const {
386 if (result.first == false && other.result.first == false) {
387 return true;
388 }
389 return false;
390 }
391 bool operator!=(const FindResult &other) const { return !(*this == other); }
392
393 // Make -> act kind of like an iterator.
394 std::pair<bool, T> *operator->() { return &result; }
395 const std::pair<bool, T> *operator->() const { return &result; }
396
Petr Kraus4ed81e32019-09-02 23:41:19 +0200397 private:
Jeff Bolz89b9a502019-08-20 08:58:51 -0500398 // (found, reference to element)
399 std::pair<bool, T> result;
400 };
401
Jeff Bolzfd3bb242019-08-22 06:10:49 -0500402 // find()/end() return a FindResult containing a copy of the value. For end(),
403 // return a default value.
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500404 FindResult end() const { return FindResult(false, T()); }
Jeff Bolz89b9a502019-08-20 08:58:51 -0500405
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500406 FindResult find(const Key &key) const {
Jeff Bolz89b9a502019-08-20 08:58:51 -0500407 uint32_t h = ConcurrentMapHashObject(key);
408 read_lock_guard_t lock(locks[h].lock);
409
410 auto itr = maps[h].find(key);
411 bool found = itr != maps[h].end();
412
Jeff Bolzfd3bb242019-08-22 06:10:49 -0500413 if (found) {
414 return FindResult(true, itr->second);
415 } else {
416 return end();
417 }
Jeff Bolz89b9a502019-08-20 08:58:51 -0500418 }
419
420 FindResult pop(const Key &key) {
421 uint32_t h = ConcurrentMapHashObject(key);
422 write_lock_guard_t lock(locks[h].lock);
423
424 auto itr = maps[h].find(key);
425 bool found = itr != maps[h].end();
426
427 if (found) {
Jeff Bolzfd3bb242019-08-22 06:10:49 -0500428 auto ret = std::move(FindResult(true, itr->second));
Jeff Bolz89b9a502019-08-20 08:58:51 -0500429 maps[h].erase(itr);
430 return ret;
431 } else {
432 return end();
433 }
434 }
435
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500436 std::vector<std::pair<const Key, T>> snapshot(std::function<bool(T)> f = nullptr) const {
Jeff Bolzfd3bb242019-08-22 06:10:49 -0500437 std::vector<std::pair<const Key, T>> ret;
438 for (int h = 0; h < BUCKETS; ++h) {
439 read_lock_guard_t lock(locks[h].lock);
John Zulauf79f06582021-02-27 18:38:39 -0700440 for (const auto &j : maps[h]) {
Jeff Bolzfd3bb242019-08-22 06:10:49 -0500441 if (!f || f(j.second)) {
Jeremy Gebbencbf22862021-03-03 12:01:22 -0700442 ret.emplace_back(j.first, j.second);
Jeff Bolzfd3bb242019-08-22 06:10:49 -0500443 }
444 }
445 }
446 return ret;
447 }
448
Petr Kraus4ed81e32019-09-02 23:41:19 +0200449 private:
Jeff Bolz89b9a502019-08-20 08:58:51 -0500450 static const int BUCKETS = (1 << BUCKETSLOG2);
Jeff Bolz89b9a502019-08-20 08:58:51 -0500451
Jeremy Gebbencbf22862021-03-03 12:01:22 -0700452 layer_data::unordered_map<Key, T, Hash> maps[BUCKETS];
Jeff Bolz89b9a502019-08-20 08:58:51 -0500453 struct {
Jeff Bolzcaeccc72019-10-15 15:35:26 -0500454 mutable ReadWriteLock lock;
Jeff Bolz89b9a502019-08-20 08:58:51 -0500455 // Put each lock on its own cache line to avoid false cache line sharing.
Jeff Bolzcaeccc72019-10-15 15:35:26 -0500456 char padding[(-int(sizeof(ReadWriteLock))) & 63];
Jeff Bolz89b9a502019-08-20 08:58:51 -0500457 } locks[BUCKETS];
458
459 uint32_t ConcurrentMapHashObject(const Key &object) const {
460 uint64_t u64 = (uint64_t)(uintptr_t)object;
461 uint32_t hash = (uint32_t)(u64 >> 32) + (uint32_t)u64;
462 hash ^= (hash >> BUCKETSLOG2) ^ (hash >> (2 * BUCKETSLOG2));
463 hash &= (BUCKETS - 1);
464 return hash;
465 }
466};
Jeremy Gebben32811462021-09-20 12:54:20 -0600467#endif