1 /*
2  * kmp_lock.h -- lock header file
3  */
4 
5 //===----------------------------------------------------------------------===//
6 //
7 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
8 // See https://llvm.org/LICENSE.txt for license information.
9 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #ifndef KMP_LOCK_H
14 #define KMP_LOCK_H
15 
16 #include <limits.h> // CHAR_BIT
17 #include <stddef.h> // offsetof
18 
19 #include "kmp_debug.h"
20 #include "kmp_os.h"
21 
22 #ifdef __cplusplus
23 #include <atomic>
24 
25 extern "C" {
26 #endif // __cplusplus
27 
28 // ----------------------------------------------------------------------------
29 // Have to copy these definitions from kmp.h because kmp.h cannot be included
30 // due to circular dependencies.  Will undef these at end of file.
31 
32 #define KMP_PAD(type, sz)                                                      \
33   (sizeof(type) + (sz - ((sizeof(type) - 1) % (sz)) - 1))
34 #define KMP_GTID_DNE (-2)
35 
36 // Forward declaration of ident and ident_t
37 
38 struct ident;
39 typedef struct ident ident_t;
40 
41 // End of copied code.
42 // ----------------------------------------------------------------------------
43 
44 // We need to know the size of the area we can assume that the compiler(s)
45 // allocated for objects of type omp_lock_t and omp_nest_lock_t.  The Intel
46 // compiler always allocates a pointer-sized area, as does visual studio.
47 //
48 // gcc however, only allocates 4 bytes for regular locks, even on 64-bit
49 // intel archs.  It allocates at least 8 bytes for nested lock (more on
50 // recent versions), but we are bounded by the pointer-sized chunks that
51 // the Intel compiler allocates.
52 
53 #if KMP_OS_LINUX && defined(KMP_GOMP_COMPAT)
54 #define OMP_LOCK_T_SIZE sizeof(int)
55 #define OMP_NEST_LOCK_T_SIZE sizeof(void *)
56 #else
57 #define OMP_LOCK_T_SIZE sizeof(void *)
58 #define OMP_NEST_LOCK_T_SIZE sizeof(void *)
59 #endif
60 
61 // The Intel compiler allocates a 32-byte chunk for a critical section.
62 // Both gcc and visual studio only allocate enough space for a pointer.
63 // Sometimes we know that the space was allocated by the Intel compiler.
64 #define OMP_CRITICAL_SIZE sizeof(void *)
65 #define INTEL_CRITICAL_SIZE 32
66 
67 // lock flags
68 typedef kmp_uint32 kmp_lock_flags_t;
69 
70 #define kmp_lf_critical_section 1
71 
72 // When a lock table is used, the indices are of kmp_lock_index_t
73 typedef kmp_uint32 kmp_lock_index_t;
74 
75 // When memory allocated for locks are on the lock pool (free list),
76 // it is treated as structs of this type.
77 struct kmp_lock_pool {
78   union kmp_user_lock *next;
79   kmp_lock_index_t index;
80 };
81 
82 typedef struct kmp_lock_pool kmp_lock_pool_t;
83 
84 extern void __kmp_validate_locks(void);
85 
86 // ----------------------------------------------------------------------------
87 //  There are 5 lock implementations:
88 //       1. Test and set locks.
89 //       2. futex locks (Linux* OS on x86 and
90 //          Intel(R) Many Integrated Core Architecture)
91 //       3. Ticket (Lamport bakery) locks.
92 //       4. Queuing locks (with separate spin fields).
93 //       5. DRPA (Dynamically Reconfigurable Distributed Polling Area) locks
94 //
95 //   and 3 lock purposes:
96 //       1. Bootstrap locks -- Used for a few locks available at library
97 //       startup-shutdown time.
98 //          These do not require non-negative global thread ID's.
99 //       2. Internal RTL locks -- Used everywhere else in the RTL
100 //       3. User locks (includes critical sections)
101 // ----------------------------------------------------------------------------
102 
103 // ============================================================================
104 // Lock implementations.
105 //
106 // Test and set locks.
107 //
108 // Non-nested test and set locks differ from the other lock kinds (except
109 // futex) in that we use the memory allocated by the compiler for the lock,
110 // rather than a pointer to it.
111 //
112 // On lin32, lin_32e, and win_32, the space allocated may be as small as 4
113 // bytes, so we have to use a lock table for nested locks, and avoid accessing
114 // the depth_locked field for non-nested locks.
115 //
116 // Information normally available to the tools, such as lock location, lock
117 // usage (normal lock vs. critical section), etc. is not available with test and
118 // set locks.
119 // ----------------------------------------------------------------------------
120 
121 struct kmp_base_tas_lock {
122   // KMP_LOCK_FREE(tas) => unlocked; locked: (gtid+1) of owning thread
123   std::atomic<kmp_int32> poll;
124   kmp_int32 depth_locked; // depth locked, for nested locks only
125 };
126 
127 typedef struct kmp_base_tas_lock kmp_base_tas_lock_t;
128 
129 union kmp_tas_lock {
130   kmp_base_tas_lock_t lk;
131   kmp_lock_pool_t pool; // make certain struct is large enough
132   double lk_align; // use worst case alignment; no cache line padding
133 };
134 
135 typedef union kmp_tas_lock kmp_tas_lock_t;
136 
137 // Static initializer for test and set lock variables. Usage:
138 //    kmp_tas_lock_t xlock = KMP_TAS_LOCK_INITIALIZER( xlock );
139 #define KMP_TAS_LOCK_INITIALIZER(lock)                                         \
140   {                                                                            \
141     { KMP_LOCK_FREE(tas), 0 }                                                  \
142   }
143 
144 extern int __kmp_acquire_tas_lock(kmp_tas_lock_t *lck, kmp_int32 gtid);
145 extern int __kmp_test_tas_lock(kmp_tas_lock_t *lck, kmp_int32 gtid);
146 extern int __kmp_release_tas_lock(kmp_tas_lock_t *lck, kmp_int32 gtid);
147 extern void __kmp_init_tas_lock(kmp_tas_lock_t *lck);
148 extern void __kmp_destroy_tas_lock(kmp_tas_lock_t *lck);
149 
150 extern int __kmp_acquire_nested_tas_lock(kmp_tas_lock_t *lck, kmp_int32 gtid);
151 extern int __kmp_test_nested_tas_lock(kmp_tas_lock_t *lck, kmp_int32 gtid);
152 extern int __kmp_release_nested_tas_lock(kmp_tas_lock_t *lck, kmp_int32 gtid);
153 extern void __kmp_init_nested_tas_lock(kmp_tas_lock_t *lck);
154 extern void __kmp_destroy_nested_tas_lock(kmp_tas_lock_t *lck);
155 
156 #define KMP_LOCK_RELEASED 1
157 #define KMP_LOCK_STILL_HELD 0
158 #define KMP_LOCK_ACQUIRED_FIRST 1
159 #define KMP_LOCK_ACQUIRED_NEXT 0
160 #ifndef KMP_USE_FUTEX
161 #define KMP_USE_FUTEX                                                          \
162   (KMP_OS_LINUX &&                                                             \
163    (KMP_ARCH_X86 || KMP_ARCH_X86_64 || KMP_ARCH_ARM || KMP_ARCH_AARCH64))
164 #endif
165 #if KMP_USE_FUTEX
166 
167 // ----------------------------------------------------------------------------
168 // futex locks.  futex locks are only available on Linux* OS.
169 //
170 // Like non-nested test and set lock, non-nested futex locks use the memory
171 // allocated by the compiler for the lock, rather than a pointer to it.
172 //
173 // Information normally available to the tools, such as lock location, lock
174 // usage (normal lock vs. critical section), etc. is not available with test and
175 // set locks. With non-nested futex locks, the lock owner is not even available.
176 // ----------------------------------------------------------------------------
177 
178 struct kmp_base_futex_lock {
179   volatile kmp_int32 poll; // KMP_LOCK_FREE(futex) => unlocked
180   // 2*(gtid+1) of owning thread, 0 if unlocked
181   // locked: (gtid+1) of owning thread
182   kmp_int32 depth_locked; // depth locked, for nested locks only
183 };
184 
185 typedef struct kmp_base_futex_lock kmp_base_futex_lock_t;
186 
187 union kmp_futex_lock {
188   kmp_base_futex_lock_t lk;
189   kmp_lock_pool_t pool; // make certain struct is large enough
190   double lk_align; // use worst case alignment
191   // no cache line padding
192 };
193 
194 typedef union kmp_futex_lock kmp_futex_lock_t;
195 
196 // Static initializer for futex lock variables. Usage:
197 //    kmp_futex_lock_t xlock = KMP_FUTEX_LOCK_INITIALIZER( xlock );
198 #define KMP_FUTEX_LOCK_INITIALIZER(lock)                                       \
199   {                                                                            \
200     { KMP_LOCK_FREE(futex), 0 }                                                \
201   }
202 
203 extern int __kmp_acquire_futex_lock(kmp_futex_lock_t *lck, kmp_int32 gtid);
204 extern int __kmp_test_futex_lock(kmp_futex_lock_t *lck, kmp_int32 gtid);
205 extern int __kmp_release_futex_lock(kmp_futex_lock_t *lck, kmp_int32 gtid);
206 extern void __kmp_init_futex_lock(kmp_futex_lock_t *lck);
207 extern void __kmp_destroy_futex_lock(kmp_futex_lock_t *lck);
208 
209 extern int __kmp_acquire_nested_futex_lock(kmp_futex_lock_t *lck,
210                                            kmp_int32 gtid);
211 extern int __kmp_test_nested_futex_lock(kmp_futex_lock_t *lck, kmp_int32 gtid);
212 extern int __kmp_release_nested_futex_lock(kmp_futex_lock_t *lck,
213                                            kmp_int32 gtid);
214 extern void __kmp_init_nested_futex_lock(kmp_futex_lock_t *lck);
215 extern void __kmp_destroy_nested_futex_lock(kmp_futex_lock_t *lck);
216 
217 #endif // KMP_USE_FUTEX
218 
219 // ----------------------------------------------------------------------------
220 // Ticket locks.
221 
222 #ifdef __cplusplus
223 
224 #ifdef _MSC_VER
225 // MSVC won't allow use of std::atomic<> in a union since it has non-trivial
226 // copy constructor.
227 
228 struct kmp_base_ticket_lock {
229   // `initialized' must be the first entry in the lock data structure!
230   std::atomic_bool initialized;
231   volatile union kmp_ticket_lock *self; // points to the lock union
232   ident_t const *location; // Source code location of omp_init_lock().
233   std::atomic_uint
234       next_ticket; // ticket number to give to next thread which acquires
235   std::atomic_uint now_serving; // ticket number for thread which holds the lock
236   std::atomic_int owner_id; // (gtid+1) of owning thread, 0 if unlocked
237   std::atomic_int depth_locked; // depth locked, for nested locks only
238   kmp_lock_flags_t flags; // lock specifics, e.g. critical section lock
239 };
240 #else
241 struct kmp_base_ticket_lock {
242   // `initialized' must be the first entry in the lock data structure!
243   std::atomic<bool> initialized;
244   volatile union kmp_ticket_lock *self; // points to the lock union
245   ident_t const *location; // Source code location of omp_init_lock().
246   std::atomic<unsigned>
247       next_ticket; // ticket number to give to next thread which acquires
248   std::atomic<unsigned>
249       now_serving; // ticket number for thread which holds the lock
250   std::atomic<int> owner_id; // (gtid+1) of owning thread, 0 if unlocked
251   std::atomic<int> depth_locked; // depth locked, for nested locks only
252   kmp_lock_flags_t flags; // lock specifics, e.g. critical section lock
253 };
254 #endif
255 
256 #else // __cplusplus
257 
258 struct kmp_base_ticket_lock;
259 
260 #endif // !__cplusplus
261 
262 typedef struct kmp_base_ticket_lock kmp_base_ticket_lock_t;
263 
264 union KMP_ALIGN_CACHE kmp_ticket_lock {
265   kmp_base_ticket_lock_t
266       lk; // This field must be first to allow static initializing.
267   kmp_lock_pool_t pool;
268   double lk_align; // use worst case alignment
269   char lk_pad[KMP_PAD(kmp_base_ticket_lock_t, CACHE_LINE)];
270 };
271 
272 typedef union kmp_ticket_lock kmp_ticket_lock_t;
273 
274 // Static initializer for simple ticket lock variables. Usage:
275 //    kmp_ticket_lock_t xlock = KMP_TICKET_LOCK_INITIALIZER( xlock );
276 // Note the macro argument. It is important to make var properly initialized.
277 #define KMP_TICKET_LOCK_INITIALIZER(lock)                                      \
278   {                                                                            \
279     { true, &(lock), NULL, 0U, 0U, 0, -1 }                                     \
280   }
281 
282 extern int __kmp_acquire_ticket_lock(kmp_ticket_lock_t *lck, kmp_int32 gtid);
283 extern int __kmp_test_ticket_lock(kmp_ticket_lock_t *lck, kmp_int32 gtid);
284 extern int __kmp_test_ticket_lock_with_cheks(kmp_ticket_lock_t *lck,
285                                              kmp_int32 gtid);
286 extern int __kmp_release_ticket_lock(kmp_ticket_lock_t *lck, kmp_int32 gtid);
287 extern void __kmp_init_ticket_lock(kmp_ticket_lock_t *lck);
288 extern void __kmp_destroy_ticket_lock(kmp_ticket_lock_t *lck);
289 
290 extern int __kmp_acquire_nested_ticket_lock(kmp_ticket_lock_t *lck,
291                                             kmp_int32 gtid);
292 extern int __kmp_test_nested_ticket_lock(kmp_ticket_lock_t *lck,
293                                          kmp_int32 gtid);
294 extern int __kmp_release_nested_ticket_lock(kmp_ticket_lock_t *lck,
295                                             kmp_int32 gtid);
296 extern void __kmp_init_nested_ticket_lock(kmp_ticket_lock_t *lck);
297 extern void __kmp_destroy_nested_ticket_lock(kmp_ticket_lock_t *lck);
298 
299 // ----------------------------------------------------------------------------
300 // Queuing locks.
301 
302 #if KMP_USE_ADAPTIVE_LOCKS
303 
304 struct kmp_adaptive_lock_info;
305 
306 typedef struct kmp_adaptive_lock_info kmp_adaptive_lock_info_t;
307 
308 #if KMP_DEBUG_ADAPTIVE_LOCKS
309 
310 struct kmp_adaptive_lock_statistics {
311   /* So we can get stats from locks that haven't been destroyed. */
312   kmp_adaptive_lock_info_t *next;
313   kmp_adaptive_lock_info_t *prev;
314 
315   /* Other statistics */
316   kmp_uint32 successfulSpeculations;
317   kmp_uint32 hardFailedSpeculations;
318   kmp_uint32 softFailedSpeculations;
319   kmp_uint32 nonSpeculativeAcquires;
320   kmp_uint32 nonSpeculativeAcquireAttempts;
321   kmp_uint32 lemmingYields;
322 };
323 
324 typedef struct kmp_adaptive_lock_statistics kmp_adaptive_lock_statistics_t;
325 
326 extern void __kmp_print_speculative_stats();
327 extern void __kmp_init_speculative_stats();
328 
329 #endif // KMP_DEBUG_ADAPTIVE_LOCKS
330 
331 struct kmp_adaptive_lock_info {
332   /* Values used for adaptivity.
333      Although these are accessed from multiple threads we don't access them
334      atomically, because if we miss updates it probably doesn't matter much. (It
335      just affects our decision about whether to try speculation on the lock). */
336   kmp_uint32 volatile badness;
337   kmp_uint32 volatile acquire_attempts;
338   /* Parameters of the lock. */
339   kmp_uint32 max_badness;
340   kmp_uint32 max_soft_retries;
341 
342 #if KMP_DEBUG_ADAPTIVE_LOCKS
343   kmp_adaptive_lock_statistics_t volatile stats;
344 #endif
345 };
346 
347 #endif // KMP_USE_ADAPTIVE_LOCKS
348 
349 struct kmp_base_queuing_lock {
350 
351   //  `initialized' must be the first entry in the lock data structure!
352   volatile union kmp_queuing_lock
353       *initialized; // Points to the lock union if in initialized state.
354 
355   ident_t const *location; // Source code location of omp_init_lock().
356 
357   KMP_ALIGN(8) // tail_id  must be 8-byte aligned!
358 
359   volatile kmp_int32
360       tail_id; // (gtid+1) of thread at tail of wait queue, 0 if empty
361   // Must be no padding here since head/tail used in 8-byte CAS
362   volatile kmp_int32
363       head_id; // (gtid+1) of thread at head of wait queue, 0 if empty
364   // Decl order assumes little endian
365   // bakery-style lock
366   volatile kmp_uint32
367       next_ticket; // ticket number to give to next thread which acquires
368   volatile kmp_uint32
369       now_serving; // ticket number for thread which holds the lock
370   volatile kmp_int32 owner_id; // (gtid+1) of owning thread, 0 if unlocked
371   kmp_int32 depth_locked; // depth locked, for nested locks only
372 
373   kmp_lock_flags_t flags; // lock specifics, e.g. critical section lock
374 };
375 
376 typedef struct kmp_base_queuing_lock kmp_base_queuing_lock_t;
377 
378 KMP_BUILD_ASSERT(offsetof(kmp_base_queuing_lock_t, tail_id) % 8 == 0);
379 
380 union KMP_ALIGN_CACHE kmp_queuing_lock {
381   kmp_base_queuing_lock_t
382       lk; // This field must be first to allow static initializing.
383   kmp_lock_pool_t pool;
384   double lk_align; // use worst case alignment
385   char lk_pad[KMP_PAD(kmp_base_queuing_lock_t, CACHE_LINE)];
386 };
387 
388 typedef union kmp_queuing_lock kmp_queuing_lock_t;
389 
390 extern int __kmp_acquire_queuing_lock(kmp_queuing_lock_t *lck, kmp_int32 gtid);
391 extern int __kmp_test_queuing_lock(kmp_queuing_lock_t *lck, kmp_int32 gtid);
392 extern int __kmp_release_queuing_lock(kmp_queuing_lock_t *lck, kmp_int32 gtid);
393 extern void __kmp_init_queuing_lock(kmp_queuing_lock_t *lck);
394 extern void __kmp_destroy_queuing_lock(kmp_queuing_lock_t *lck);
395 
396 extern int __kmp_acquire_nested_queuing_lock(kmp_queuing_lock_t *lck,
397                                              kmp_int32 gtid);
398 extern int __kmp_test_nested_queuing_lock(kmp_queuing_lock_t *lck,
399                                           kmp_int32 gtid);
400 extern int __kmp_release_nested_queuing_lock(kmp_queuing_lock_t *lck,
401                                              kmp_int32 gtid);
402 extern void __kmp_init_nested_queuing_lock(kmp_queuing_lock_t *lck);
403 extern void __kmp_destroy_nested_queuing_lock(kmp_queuing_lock_t *lck);
404 
405 #if KMP_USE_ADAPTIVE_LOCKS
406 
407 // ----------------------------------------------------------------------------
408 // Adaptive locks.
409 struct kmp_base_adaptive_lock {
410   kmp_base_queuing_lock qlk;
411   KMP_ALIGN(CACHE_LINE)
412   kmp_adaptive_lock_info_t
413       adaptive; // Information for the speculative adaptive lock
414 };
415 
416 typedef struct kmp_base_adaptive_lock kmp_base_adaptive_lock_t;
417 
418 union KMP_ALIGN_CACHE kmp_adaptive_lock {
419   kmp_base_adaptive_lock_t lk;
420   kmp_lock_pool_t pool;
421   double lk_align;
422   char lk_pad[KMP_PAD(kmp_base_adaptive_lock_t, CACHE_LINE)];
423 };
424 typedef union kmp_adaptive_lock kmp_adaptive_lock_t;
425 
426 #define GET_QLK_PTR(l) ((kmp_queuing_lock_t *)&(l)->lk.qlk)
427 
428 #endif // KMP_USE_ADAPTIVE_LOCKS
429 
430 // ----------------------------------------------------------------------------
431 // DRDPA ticket locks.
432 struct kmp_base_drdpa_lock {
433   // All of the fields on the first cache line are only written when
434   // initializing or reconfiguring the lock.  These are relatively rare
435   // operations, so data from the first cache line will usually stay resident in
436   // the cache of each thread trying to acquire the lock.
437   //
438   // initialized must be the first entry in the lock data structure!
439   KMP_ALIGN_CACHE
440 
441   volatile union kmp_drdpa_lock
442       *initialized; // points to the lock union if in initialized state
443   ident_t const *location; // Source code location of omp_init_lock().
444   std::atomic<std::atomic<kmp_uint64> *> polls;
445   std::atomic<kmp_uint64> mask; // is 2**num_polls-1 for mod op
446   kmp_uint64 cleanup_ticket; // thread with cleanup ticket
447   std::atomic<kmp_uint64> *old_polls; // will deallocate old_polls
448   kmp_uint32 num_polls; // must be power of 2
449 
450   // next_ticket it needs to exist in a separate cache line, as it is
451   // invalidated every time a thread takes a new ticket.
452   KMP_ALIGN_CACHE
453 
454   std::atomic<kmp_uint64> next_ticket;
455 
456   // now_serving is used to store our ticket value while we hold the lock. It
457   // has a slightly different meaning in the DRDPA ticket locks (where it is
458   // written by the acquiring thread) than it does in the simple ticket locks
459   // (where it is written by the releasing thread).
460   //
461   // Since now_serving is only read and written in the critical section,
462   // it is non-volatile, but it needs to exist on a separate cache line,
463   // as it is invalidated at every lock acquire.
464   //
465   // Likewise, the vars used for nested locks (owner_id and depth_locked) are
466   // only written by the thread owning the lock, so they are put in this cache
467   // line.  owner_id is read by other threads, so it must be declared volatile.
468   KMP_ALIGN_CACHE
469   kmp_uint64 now_serving; // doesn't have to be volatile
470   volatile kmp_uint32 owner_id; // (gtid+1) of owning thread, 0 if unlocked
471   kmp_int32 depth_locked; // depth locked
472   kmp_lock_flags_t flags; // lock specifics, e.g. critical section lock
473 };
474 
475 typedef struct kmp_base_drdpa_lock kmp_base_drdpa_lock_t;
476 
477 union KMP_ALIGN_CACHE kmp_drdpa_lock {
478   kmp_base_drdpa_lock_t
479       lk; // This field must be first to allow static initializing. */
480   kmp_lock_pool_t pool;
481   double lk_align; // use worst case alignment
482   char lk_pad[KMP_PAD(kmp_base_drdpa_lock_t, CACHE_LINE)];
483 };
484 
485 typedef union kmp_drdpa_lock kmp_drdpa_lock_t;
486 
487 extern int __kmp_acquire_drdpa_lock(kmp_drdpa_lock_t *lck, kmp_int32 gtid);
488 extern int __kmp_test_drdpa_lock(kmp_drdpa_lock_t *lck, kmp_int32 gtid);
489 extern int __kmp_release_drdpa_lock(kmp_drdpa_lock_t *lck, kmp_int32 gtid);
490 extern void __kmp_init_drdpa_lock(kmp_drdpa_lock_t *lck);
491 extern void __kmp_destroy_drdpa_lock(kmp_drdpa_lock_t *lck);
492 
493 extern int __kmp_acquire_nested_drdpa_lock(kmp_drdpa_lock_t *lck,
494                                            kmp_int32 gtid);
495 extern int __kmp_test_nested_drdpa_lock(kmp_drdpa_lock_t *lck, kmp_int32 gtid);
496 extern int __kmp_release_nested_drdpa_lock(kmp_drdpa_lock_t *lck,
497                                            kmp_int32 gtid);
498 extern void __kmp_init_nested_drdpa_lock(kmp_drdpa_lock_t *lck);
499 extern void __kmp_destroy_nested_drdpa_lock(kmp_drdpa_lock_t *lck);
500 
501 // ============================================================================
502 // Lock purposes.
503 // ============================================================================
504 
505 // Bootstrap locks.
506 //
507 // Bootstrap locks -- very few locks used at library initialization time.
508 // Bootstrap locks are currently implemented as ticket locks.
509 // They could also be implemented as test and set lock, but cannot be
510 // implemented with other lock kinds as they require gtids which are not
511 // available at initialization time.
512 
513 typedef kmp_ticket_lock_t kmp_bootstrap_lock_t;
514 
515 #define KMP_BOOTSTRAP_LOCK_INITIALIZER(lock) KMP_TICKET_LOCK_INITIALIZER((lock))
516 #define KMP_BOOTSTRAP_LOCK_INIT(lock)                                          \
517   kmp_bootstrap_lock_t lock = KMP_TICKET_LOCK_INITIALIZER(lock)
518 
519 static inline int __kmp_acquire_bootstrap_lock(kmp_bootstrap_lock_t *lck) {
520   return __kmp_acquire_ticket_lock(lck, KMP_GTID_DNE);
521 }
522 
523 static inline int __kmp_test_bootstrap_lock(kmp_bootstrap_lock_t *lck) {
524   return __kmp_test_ticket_lock(lck, KMP_GTID_DNE);
525 }
526 
527 static inline void __kmp_release_bootstrap_lock(kmp_bootstrap_lock_t *lck) {
528   __kmp_release_ticket_lock(lck, KMP_GTID_DNE);
529 }
530 
531 static inline void __kmp_init_bootstrap_lock(kmp_bootstrap_lock_t *lck) {
532   __kmp_init_ticket_lock(lck);
533 }
534 
535 static inline void __kmp_destroy_bootstrap_lock(kmp_bootstrap_lock_t *lck) {
536   __kmp_destroy_ticket_lock(lck);
537 }
538 
539 // Internal RTL locks.
540 //
541 // Internal RTL locks are also implemented as ticket locks, for now.
542 //
543 // FIXME - We should go through and figure out which lock kind works best for
544 // each internal lock, and use the type declaration and function calls for
545 // that explicit lock kind (and get rid of this section).
546 
547 typedef kmp_ticket_lock_t kmp_lock_t;
548 
549 #define KMP_LOCK_INIT(lock) kmp_lock_t lock = KMP_TICKET_LOCK_INITIALIZER(lock)
550 
551 static inline int __kmp_acquire_lock(kmp_lock_t *lck, kmp_int32 gtid) {
552   return __kmp_acquire_ticket_lock(lck, gtid);
553 }
554 
555 static inline int __kmp_test_lock(kmp_lock_t *lck, kmp_int32 gtid) {
556   return __kmp_test_ticket_lock(lck, gtid);
557 }
558 
559 static inline void __kmp_release_lock(kmp_lock_t *lck, kmp_int32 gtid) {
560   __kmp_release_ticket_lock(lck, gtid);
561 }
562 
563 static inline void __kmp_init_lock(kmp_lock_t *lck) {
564   __kmp_init_ticket_lock(lck);
565 }
566 
567 static inline void __kmp_destroy_lock(kmp_lock_t *lck) {
568   __kmp_destroy_ticket_lock(lck);
569 }
570 
571 // User locks.
572 //
573 // Do not allocate objects of type union kmp_user_lock!!! This will waste space
574 // unless __kmp_user_lock_kind == lk_drdpa. Instead, check the value of
575 // __kmp_user_lock_kind and allocate objects of the type of the appropriate
576 // union member, and cast their addresses to kmp_user_lock_p.
577 
578 enum kmp_lock_kind {
579   lk_default = 0,
580   lk_tas,
581 #if KMP_USE_FUTEX
582   lk_futex,
583 #endif
584 #if KMP_USE_DYNAMIC_LOCK && KMP_USE_TSX
585   lk_hle,
586   lk_rtm_queuing,
587   lk_rtm_spin,
588 #endif
589   lk_ticket,
590   lk_queuing,
591   lk_drdpa,
592 #if KMP_USE_ADAPTIVE_LOCKS
593   lk_adaptive
594 #endif // KMP_USE_ADAPTIVE_LOCKS
595 };
596 
597 typedef enum kmp_lock_kind kmp_lock_kind_t;
598 
599 extern kmp_lock_kind_t __kmp_user_lock_kind;
600 
601 union kmp_user_lock {
602   kmp_tas_lock_t tas;
603 #if KMP_USE_FUTEX
604   kmp_futex_lock_t futex;
605 #endif
606   kmp_ticket_lock_t ticket;
607   kmp_queuing_lock_t queuing;
608   kmp_drdpa_lock_t drdpa;
609 #if KMP_USE_ADAPTIVE_LOCKS
610   kmp_adaptive_lock_t adaptive;
611 #endif // KMP_USE_ADAPTIVE_LOCKS
612   kmp_lock_pool_t pool;
613 };
614 
615 typedef union kmp_user_lock *kmp_user_lock_p;
616 
617 #if !KMP_USE_DYNAMIC_LOCK
618 
619 extern size_t __kmp_base_user_lock_size;
620 extern size_t __kmp_user_lock_size;
621 
622 extern kmp_int32 (*__kmp_get_user_lock_owner_)(kmp_user_lock_p lck);
623 
624 static inline kmp_int32 __kmp_get_user_lock_owner(kmp_user_lock_p lck) {
625   KMP_DEBUG_ASSERT(__kmp_get_user_lock_owner_ != NULL);
626   return (*__kmp_get_user_lock_owner_)(lck);
627 }
628 
629 extern int (*__kmp_acquire_user_lock_with_checks_)(kmp_user_lock_p lck,
630                                                    kmp_int32 gtid);
631 
632 #if KMP_OS_LINUX &&                                                            \
633     (KMP_ARCH_X86 || KMP_ARCH_X86_64 || KMP_ARCH_ARM || KMP_ARCH_AARCH64)
634 
635 #define __kmp_acquire_user_lock_with_checks(lck, gtid)                         \
636   if (__kmp_user_lock_kind == lk_tas) {                                        \
637     if (__kmp_env_consistency_check) {                                         \
638       char const *const func = "omp_set_lock";                                 \
639       if ((sizeof(kmp_tas_lock_t) <= OMP_LOCK_T_SIZE) &&                       \
640           lck->tas.lk.depth_locked != -1) {                                    \
641         KMP_FATAL(LockNestableUsedAsSimple, func);                             \
642       }                                                                        \
643       if ((gtid >= 0) && (lck->tas.lk.poll - 1 == gtid)) {                     \
644         KMP_FATAL(LockIsAlreadyOwned, func);                                   \
645       }                                                                        \
646     }                                                                          \
647     if (lck->tas.lk.poll != 0 ||                                               \
648         !__kmp_atomic_compare_store_acq(&lck->tas.lk.poll, 0, gtid + 1)) {     \
649       kmp_uint32 spins;                                                        \
650       kmp_uint64 time;                                                         \
651       KMP_FSYNC_PREPARE(lck);                                                  \
652       KMP_INIT_YIELD(spins);                                                   \
653       KMP_INIT_BACKOFF(time);                                                  \
654       do {                                                                     \
655         KMP_YIELD_OVERSUB_ELSE_SPIN(spins, time);                              \
656       } while (                                                                \
657           lck->tas.lk.poll != 0 ||                                             \
658           !__kmp_atomic_compare_store_acq(&lck->tas.lk.poll, 0, gtid + 1));    \
659     }                                                                          \
660     KMP_FSYNC_ACQUIRED(lck);                                                   \
661   } else {                                                                     \
662     KMP_DEBUG_ASSERT(__kmp_acquire_user_lock_with_checks_ != NULL);            \
663     (*__kmp_acquire_user_lock_with_checks_)(lck, gtid);                        \
664   }
665 
666 #else
667 static inline int __kmp_acquire_user_lock_with_checks(kmp_user_lock_p lck,
668                                                       kmp_int32 gtid) {
669   KMP_DEBUG_ASSERT(__kmp_acquire_user_lock_with_checks_ != NULL);
670   return (*__kmp_acquire_user_lock_with_checks_)(lck, gtid);
671 }
672 #endif
673 
674 extern int (*__kmp_test_user_lock_with_checks_)(kmp_user_lock_p lck,
675                                                 kmp_int32 gtid);
676 
677 #if KMP_OS_LINUX &&                                                            \
678     (KMP_ARCH_X86 || KMP_ARCH_X86_64 || KMP_ARCH_ARM || KMP_ARCH_AARCH64)
679 
680 #include "kmp_i18n.h" /* AC: KMP_FATAL definition */
681 extern int __kmp_env_consistency_check; /* AC: copy from kmp.h here */
682 static inline int __kmp_test_user_lock_with_checks(kmp_user_lock_p lck,
683                                                    kmp_int32 gtid) {
684   if (__kmp_user_lock_kind == lk_tas) {
685     if (__kmp_env_consistency_check) {
686       char const *const func = "omp_test_lock";
687       if ((sizeof(kmp_tas_lock_t) <= OMP_LOCK_T_SIZE) &&
688           lck->tas.lk.depth_locked != -1) {
689         KMP_FATAL(LockNestableUsedAsSimple, func);
690       }
691     }
692     return ((lck->tas.lk.poll == 0) &&
693             __kmp_atomic_compare_store_acq(&lck->tas.lk.poll, 0, gtid + 1));
694   } else {
695     KMP_DEBUG_ASSERT(__kmp_test_user_lock_with_checks_ != NULL);
696     return (*__kmp_test_user_lock_with_checks_)(lck, gtid);
697   }
698 }
699 #else
700 static inline int __kmp_test_user_lock_with_checks(kmp_user_lock_p lck,
701                                                    kmp_int32 gtid) {
702   KMP_DEBUG_ASSERT(__kmp_test_user_lock_with_checks_ != NULL);
703   return (*__kmp_test_user_lock_with_checks_)(lck, gtid);
704 }
705 #endif
706 
707 extern int (*__kmp_release_user_lock_with_checks_)(kmp_user_lock_p lck,
708                                                    kmp_int32 gtid);
709 
710 static inline void __kmp_release_user_lock_with_checks(kmp_user_lock_p lck,
711                                                        kmp_int32 gtid) {
712   KMP_DEBUG_ASSERT(__kmp_release_user_lock_with_checks_ != NULL);
713   (*__kmp_release_user_lock_with_checks_)(lck, gtid);
714 }
715 
716 extern void (*__kmp_init_user_lock_with_checks_)(kmp_user_lock_p lck);
717 
718 static inline void __kmp_init_user_lock_with_checks(kmp_user_lock_p lck) {
719   KMP_DEBUG_ASSERT(__kmp_init_user_lock_with_checks_ != NULL);
720   (*__kmp_init_user_lock_with_checks_)(lck);
721 }
722 
723 // We need a non-checking version of destroy lock for when the RTL is
724 // doing the cleanup as it can't always tell if the lock is nested or not.
725 extern void (*__kmp_destroy_user_lock_)(kmp_user_lock_p lck);
726 
727 static inline void __kmp_destroy_user_lock(kmp_user_lock_p lck) {
728   KMP_DEBUG_ASSERT(__kmp_destroy_user_lock_ != NULL);
729   (*__kmp_destroy_user_lock_)(lck);
730 }
731 
732 extern void (*__kmp_destroy_user_lock_with_checks_)(kmp_user_lock_p lck);
733 
734 static inline void __kmp_destroy_user_lock_with_checks(kmp_user_lock_p lck) {
735   KMP_DEBUG_ASSERT(__kmp_destroy_user_lock_with_checks_ != NULL);
736   (*__kmp_destroy_user_lock_with_checks_)(lck);
737 }
738 
739 extern int (*__kmp_acquire_nested_user_lock_with_checks_)(kmp_user_lock_p lck,
740                                                           kmp_int32 gtid);
741 
742 #if KMP_OS_LINUX && (KMP_ARCH_X86 || KMP_ARCH_X86_64)
743 
744 #define __kmp_acquire_nested_user_lock_with_checks(lck, gtid, depth)           \
745   if (__kmp_user_lock_kind == lk_tas) {                                        \
746     if (__kmp_env_consistency_check) {                                         \
747       char const *const func = "omp_set_nest_lock";                            \
748       if ((sizeof(kmp_tas_lock_t) <= OMP_NEST_LOCK_T_SIZE) &&                  \
749           lck->tas.lk.depth_locked == -1) {                                    \
750         KMP_FATAL(LockSimpleUsedAsNestable, func);                             \
751       }                                                                        \
752     }                                                                          \
753     if (lck->tas.lk.poll - 1 == gtid) {                                        \
754       lck->tas.lk.depth_locked += 1;                                           \
755       *depth = KMP_LOCK_ACQUIRED_NEXT;                                         \
756     } else {                                                                   \
757       if ((lck->tas.lk.poll != 0) ||                                           \
758           !__kmp_atomic_compare_store_acq(&lck->tas.lk.poll, 0, gtid + 1)) {   \
759         kmp_uint32 spins;                                                      \
760         kmp_uint64 time;                                                       \
761         KMP_FSYNC_PREPARE(lck);                                                \
762         KMP_INIT_YIELD(spins);                                                 \
763         KMP_INIT_BACKOFF(time);                                                \
764         do {                                                                   \
765           KMP_YIELD_OVERSUB_ELSE_SPIN(spins, time);                            \
766         } while (                                                              \
767             (lck->tas.lk.poll != 0) ||                                         \
768             !__kmp_atomic_compare_store_acq(&lck->tas.lk.poll, 0, gtid + 1));  \
769       }                                                                        \
770       lck->tas.lk.depth_locked = 1;                                            \
771       *depth = KMP_LOCK_ACQUIRED_FIRST;                                        \
772     }                                                                          \
773     KMP_FSYNC_ACQUIRED(lck);                                                   \
774   } else {                                                                     \
775     KMP_DEBUG_ASSERT(__kmp_acquire_nested_user_lock_with_checks_ != NULL);     \
776     *depth = (*__kmp_acquire_nested_user_lock_with_checks_)(lck, gtid);        \
777   }
778 
779 #else
780 static inline void
781 __kmp_acquire_nested_user_lock_with_checks(kmp_user_lock_p lck, kmp_int32 gtid,
782                                            int *depth) {
783   KMP_DEBUG_ASSERT(__kmp_acquire_nested_user_lock_with_checks_ != NULL);
784   *depth = (*__kmp_acquire_nested_user_lock_with_checks_)(lck, gtid);
785 }
786 #endif
787 
788 extern int (*__kmp_test_nested_user_lock_with_checks_)(kmp_user_lock_p lck,
789                                                        kmp_int32 gtid);
790 
791 #if KMP_OS_LINUX && (KMP_ARCH_X86 || KMP_ARCH_X86_64)
792 static inline int __kmp_test_nested_user_lock_with_checks(kmp_user_lock_p lck,
793                                                           kmp_int32 gtid) {
794   if (__kmp_user_lock_kind == lk_tas) {
795     int retval;
796     if (__kmp_env_consistency_check) {
797       char const *const func = "omp_test_nest_lock";
798       if ((sizeof(kmp_tas_lock_t) <= OMP_NEST_LOCK_T_SIZE) &&
799           lck->tas.lk.depth_locked == -1) {
800         KMP_FATAL(LockSimpleUsedAsNestable, func);
801       }
802     }
803     KMP_DEBUG_ASSERT(gtid >= 0);
804     if (lck->tas.lk.poll - 1 ==
805         gtid) { /* __kmp_get_tas_lock_owner( lck ) == gtid */
806       return ++lck->tas.lk.depth_locked; /* same owner, depth increased */
807     }
808     retval = ((lck->tas.lk.poll == 0) &&
809               __kmp_atomic_compare_store_acq(&lck->tas.lk.poll, 0, gtid + 1));
810     if (retval) {
811       KMP_MB();
812       lck->tas.lk.depth_locked = 1;
813     }
814     return retval;
815   } else {
816     KMP_DEBUG_ASSERT(__kmp_test_nested_user_lock_with_checks_ != NULL);
817     return (*__kmp_test_nested_user_lock_with_checks_)(lck, gtid);
818   }
819 }
820 #else
821 static inline int __kmp_test_nested_user_lock_with_checks(kmp_user_lock_p lck,
822                                                           kmp_int32 gtid) {
823   KMP_DEBUG_ASSERT(__kmp_test_nested_user_lock_with_checks_ != NULL);
824   return (*__kmp_test_nested_user_lock_with_checks_)(lck, gtid);
825 }
826 #endif
827 
828 extern int (*__kmp_release_nested_user_lock_with_checks_)(kmp_user_lock_p lck,
829                                                           kmp_int32 gtid);
830 
831 static inline int
832 __kmp_release_nested_user_lock_with_checks(kmp_user_lock_p lck,
833                                            kmp_int32 gtid) {
834   KMP_DEBUG_ASSERT(__kmp_release_nested_user_lock_with_checks_ != NULL);
835   return (*__kmp_release_nested_user_lock_with_checks_)(lck, gtid);
836 }
837 
838 extern void (*__kmp_init_nested_user_lock_with_checks_)(kmp_user_lock_p lck);
839 
840 static inline void
841 __kmp_init_nested_user_lock_with_checks(kmp_user_lock_p lck) {
842   KMP_DEBUG_ASSERT(__kmp_init_nested_user_lock_with_checks_ != NULL);
843   (*__kmp_init_nested_user_lock_with_checks_)(lck);
844 }
845 
846 extern void (*__kmp_destroy_nested_user_lock_with_checks_)(kmp_user_lock_p lck);
847 
848 static inline void
849 __kmp_destroy_nested_user_lock_with_checks(kmp_user_lock_p lck) {
850   KMP_DEBUG_ASSERT(__kmp_destroy_nested_user_lock_with_checks_ != NULL);
851   (*__kmp_destroy_nested_user_lock_with_checks_)(lck);
852 }
853 
854 // user lock functions which do not necessarily exist for all lock kinds.
855 //
856 // The "set" functions usually have wrapper routines that check for a NULL set
857 // function pointer and call it if non-NULL.
858 //
859 // In some cases, it makes sense to have a "get" wrapper function check for a
860 // NULL get function pointer and return NULL / invalid value / error code if
861 // the function pointer is NULL.
862 //
863 // In other cases, the calling code really should differentiate between an
864 // unimplemented function and one that is implemented but returning NULL /
865 // invalid value.  If this is the case, no get function wrapper exists.
866 
867 extern int (*__kmp_is_user_lock_initialized_)(kmp_user_lock_p lck);
868 
869 // no set function; fields set during local allocation
870 
871 extern const ident_t *(*__kmp_get_user_lock_location_)(kmp_user_lock_p lck);
872 
873 static inline const ident_t *__kmp_get_user_lock_location(kmp_user_lock_p lck) {
874   if (__kmp_get_user_lock_location_ != NULL) {
875     return (*__kmp_get_user_lock_location_)(lck);
876   } else {
877     return NULL;
878   }
879 }
880 
881 extern void (*__kmp_set_user_lock_location_)(kmp_user_lock_p lck,
882                                              const ident_t *loc);
883 
884 static inline void __kmp_set_user_lock_location(kmp_user_lock_p lck,
885                                                 const ident_t *loc) {
886   if (__kmp_set_user_lock_location_ != NULL) {
887     (*__kmp_set_user_lock_location_)(lck, loc);
888   }
889 }
890 
891 extern kmp_lock_flags_t (*__kmp_get_user_lock_flags_)(kmp_user_lock_p lck);
892 
893 extern void (*__kmp_set_user_lock_flags_)(kmp_user_lock_p lck,
894                                           kmp_lock_flags_t flags);
895 
896 static inline void __kmp_set_user_lock_flags(kmp_user_lock_p lck,
897                                              kmp_lock_flags_t flags) {
898   if (__kmp_set_user_lock_flags_ != NULL) {
899     (*__kmp_set_user_lock_flags_)(lck, flags);
900   }
901 }
902 
903 // The function which sets up all of the vtbl pointers for kmp_user_lock_t.
904 extern void __kmp_set_user_lock_vptrs(kmp_lock_kind_t user_lock_kind);
905 
906 // Macros for binding user lock functions.
907 #define KMP_BIND_USER_LOCK_TEMPLATE(nest, kind, suffix)                        \
908   {                                                                            \
909     __kmp_acquire##nest##user_lock_with_checks_ = (int (*)(                    \
910         kmp_user_lock_p, kmp_int32))__kmp_acquire##nest##kind##_##suffix;      \
911     __kmp_release##nest##user_lock_with_checks_ = (int (*)(                    \
912         kmp_user_lock_p, kmp_int32))__kmp_release##nest##kind##_##suffix;      \
913     __kmp_test##nest##user_lock_with_checks_ = (int (*)(                       \
914         kmp_user_lock_p, kmp_int32))__kmp_test##nest##kind##_##suffix;         \
915     __kmp_init##nest##user_lock_with_checks_ =                                 \
916         (void (*)(kmp_user_lock_p))__kmp_init##nest##kind##_##suffix;          \
917     __kmp_destroy##nest##user_lock_with_checks_ =                              \
918         (void (*)(kmp_user_lock_p))__kmp_destroy##nest##kind##_##suffix;       \
919   }
920 
921 #define KMP_BIND_USER_LOCK(kind) KMP_BIND_USER_LOCK_TEMPLATE(_, kind, lock)
922 #define KMP_BIND_USER_LOCK_WITH_CHECKS(kind)                                   \
923   KMP_BIND_USER_LOCK_TEMPLATE(_, kind, lock_with_checks)
924 #define KMP_BIND_NESTED_USER_LOCK(kind)                                        \
925   KMP_BIND_USER_LOCK_TEMPLATE(_nested_, kind, lock)
926 #define KMP_BIND_NESTED_USER_LOCK_WITH_CHECKS(kind)                            \
927   KMP_BIND_USER_LOCK_TEMPLATE(_nested_, kind, lock_with_checks)
928 
929 // User lock table & lock allocation
930 /* On 64-bit Linux* OS (and OS X*) GNU compiler allocates only 4 bytems memory
931    for lock variable, which is not enough to store a pointer, so we have to use
932    lock indexes instead of pointers and maintain lock table to map indexes to
933    pointers.
934 
935 
936    Note: The first element of the table is not a pointer to lock! It is a
937    pointer to previously allocated table (or NULL if it is the first table).
938 
939    Usage:
940 
941    if ( OMP_LOCK_T_SIZE < sizeof( <lock> ) ) { // or OMP_NEST_LOCK_T_SIZE
942      Lock table is fully utilized. User locks are indexes, so table is used on
943      user lock operation.
944      Note: it may be the case (lin_32) that we don't need to use a lock
945      table for regular locks, but do need the table for nested locks.
946    }
947    else {
948      Lock table initialized but not actually used.
949    }
950 */
951 
952 struct kmp_lock_table {
953   kmp_lock_index_t used; // Number of used elements
954   kmp_lock_index_t allocated; // Number of allocated elements
955   kmp_user_lock_p *table; // Lock table.
956 };
957 
958 typedef struct kmp_lock_table kmp_lock_table_t;
959 
960 extern kmp_lock_table_t __kmp_user_lock_table;
961 extern kmp_user_lock_p __kmp_lock_pool;
962 
963 struct kmp_block_of_locks {
964   struct kmp_block_of_locks *next_block;
965   void *locks;
966 };
967 
968 typedef struct kmp_block_of_locks kmp_block_of_locks_t;
969 
970 extern kmp_block_of_locks_t *__kmp_lock_blocks;
971 extern int __kmp_num_locks_in_block;
972 
973 extern kmp_user_lock_p __kmp_user_lock_allocate(void **user_lock,
974                                                 kmp_int32 gtid,
975                                                 kmp_lock_flags_t flags);
976 extern void __kmp_user_lock_free(void **user_lock, kmp_int32 gtid,
977                                  kmp_user_lock_p lck);
978 extern kmp_user_lock_p __kmp_lookup_user_lock(void **user_lock,
979                                               char const *func);
980 extern void __kmp_cleanup_user_locks();
981 
982 #define KMP_CHECK_USER_LOCK_INIT()                                             \
983   {                                                                            \
984     if (!TCR_4(__kmp_init_user_locks)) {                                       \
985       __kmp_acquire_bootstrap_lock(&__kmp_initz_lock);                         \
986       if (!TCR_4(__kmp_init_user_locks)) {                                     \
987         TCW_4(__kmp_init_user_locks, TRUE);                                    \
988       }                                                                        \
989       __kmp_release_bootstrap_lock(&__kmp_initz_lock);                         \
990     }                                                                          \
991   }
992 
993 #endif // KMP_USE_DYNAMIC_LOCK
994 
995 #undef KMP_PAD
996 #undef KMP_GTID_DNE
997 
998 #if KMP_USE_DYNAMIC_LOCK
999 // KMP_USE_DYNAMIC_LOCK enables dynamic dispatch of lock functions without
1000 // breaking the current compatibility. Essential functionality of this new code
1001 // is dynamic dispatch, but it also implements (or enables implementation of)
1002 // hinted user lock and critical section which will be part of OMP 4.5 soon.
1003 //
1004 // Lock type can be decided at creation time (i.e., lock initialization), and
1005 // subsequent lock function call on the created lock object requires type
1006 // extraction and call through jump table using the extracted type. This type
1007 // information is stored in two different ways depending on the size of the lock
1008 // object, and we differentiate lock types by this size requirement - direct and
1009 // indirect locks.
1010 //
1011 // Direct locks:
1012 // A direct lock object fits into the space created by the compiler for an
1013 // omp_lock_t object, and TAS/Futex lock falls into this category. We use low
1014 // one byte of the lock object as the storage for the lock type, and appropriate
1015 // bit operation is required to access the data meaningful to the lock
1016 // algorithms. Also, to differentiate direct lock from indirect lock, 1 is
1017 // written to LSB of the lock object. The newly introduced "hle" lock is also a
1018 // direct lock.
1019 //
1020 // Indirect locks:
1021 // An indirect lock object requires more space than the compiler-generated
1022 // space, and it should be allocated from heap. Depending on the size of the
1023 // compiler-generated space for the lock (i.e., size of omp_lock_t), this
1024 // omp_lock_t object stores either the address of the heap-allocated indirect
1025 // lock (void * fits in the object) or an index to the indirect lock table entry
1026 // that holds the address. Ticket/Queuing/DRDPA/Adaptive lock falls into this
1027 // category, and the newly introduced "rtm" lock is also an indirect lock which
1028 // was implemented on top of the Queuing lock. When the omp_lock_t object holds
1029 // an index (not lock address), 0 is written to LSB to differentiate the lock
1030 // from a direct lock, and the remaining part is the actual index to the
1031 // indirect lock table.
1032 
1033 #include <stdint.h> // for uintptr_t
1034 
1035 // Shortcuts
1036 #define KMP_USE_INLINED_TAS                                                    \
1037   (KMP_OS_LINUX && (KMP_ARCH_X86 || KMP_ARCH_X86_64 || KMP_ARCH_ARM)) && 1
1038 #define KMP_USE_INLINED_FUTEX KMP_USE_FUTEX && 0
1039 
1040 // List of lock definitions; all nested locks are indirect locks.
1041 // hle lock is xchg lock prefixed with XACQUIRE/XRELEASE.
1042 // All nested locks are indirect lock types.
1043 #if KMP_USE_TSX
1044 #if KMP_USE_FUTEX
1045 #define KMP_FOREACH_D_LOCK(m, a) m(tas, a) m(futex, a) m(hle, a) m(rtm_spin, a)
1046 #define KMP_FOREACH_I_LOCK(m, a)                                               \
1047   m(ticket, a) m(queuing, a) m(adaptive, a) m(drdpa, a) m(rtm_queuing, a)      \
1048       m(nested_tas, a) m(nested_futex, a) m(nested_ticket, a)                  \
1049           m(nested_queuing, a) m(nested_drdpa, a)
1050 #else
1051 #define KMP_FOREACH_D_LOCK(m, a) m(tas, a) m(hle, a) m(rtm_spin, a)
1052 #define KMP_FOREACH_I_LOCK(m, a)                                               \
1053   m(ticket, a) m(queuing, a) m(adaptive, a) m(drdpa, a) m(rtm_queuing, a)      \
1054       m(nested_tas, a) m(nested_ticket, a) m(nested_queuing, a)                \
1055           m(nested_drdpa, a)
1056 #endif // KMP_USE_FUTEX
1057 #define KMP_LAST_D_LOCK lockseq_rtm_spin
1058 #else
1059 #if KMP_USE_FUTEX
1060 #define KMP_FOREACH_D_LOCK(m, a) m(tas, a) m(futex, a)
1061 #define KMP_FOREACH_I_LOCK(m, a)                                               \
1062   m(ticket, a) m(queuing, a) m(drdpa, a) m(nested_tas, a) m(nested_futex, a)   \
1063       m(nested_ticket, a) m(nested_queuing, a) m(nested_drdpa, a)
1064 #define KMP_LAST_D_LOCK lockseq_futex
1065 #else
1066 #define KMP_FOREACH_D_LOCK(m, a) m(tas, a)
1067 #define KMP_FOREACH_I_LOCK(m, a)                                               \
1068   m(ticket, a) m(queuing, a) m(drdpa, a) m(nested_tas, a) m(nested_ticket, a)  \
1069       m(nested_queuing, a) m(nested_drdpa, a)
1070 #define KMP_LAST_D_LOCK lockseq_tas
1071 #endif // KMP_USE_FUTEX
1072 #endif // KMP_USE_TSX
1073 
1074 // Information used in dynamic dispatch
1075 #define KMP_LOCK_SHIFT                                                         \
1076   8 // number of low bits to be used as tag for direct locks
1077 #define KMP_FIRST_D_LOCK lockseq_tas
1078 #define KMP_FIRST_I_LOCK lockseq_ticket
1079 #define KMP_LAST_I_LOCK lockseq_nested_drdpa
1080 #define KMP_NUM_I_LOCKS                                                        \
1081   (locktag_nested_drdpa + 1) // number of indirect lock types
1082 
1083 // Base type for dynamic locks.
1084 typedef kmp_uint32 kmp_dyna_lock_t;
1085 
1086 // Lock sequence that enumerates all lock kinds. Always make this enumeration
1087 // consistent with kmp_lockseq_t in the include directory.
1088 typedef enum {
1089   lockseq_indirect = 0,
1090 #define expand_seq(l, a) lockseq_##l,
1091   KMP_FOREACH_D_LOCK(expand_seq, 0) KMP_FOREACH_I_LOCK(expand_seq, 0)
1092 #undef expand_seq
1093 } kmp_dyna_lockseq_t;
1094 
1095 // Enumerates indirect lock tags.
1096 typedef enum {
1097 #define expand_tag(l, a) locktag_##l,
1098   KMP_FOREACH_I_LOCK(expand_tag, 0)
1099 #undef expand_tag
1100 } kmp_indirect_locktag_t;
1101 
1102 // Utility macros that extract information from lock sequences.
1103 #define KMP_IS_D_LOCK(seq)                                                     \
1104   ((seq) >= KMP_FIRST_D_LOCK && (seq) <= KMP_LAST_D_LOCK)
1105 #define KMP_IS_I_LOCK(seq)                                                     \
1106   ((seq) >= KMP_FIRST_I_LOCK && (seq) <= KMP_LAST_I_LOCK)
1107 #define KMP_GET_I_TAG(seq) (kmp_indirect_locktag_t)((seq)-KMP_FIRST_I_LOCK)
1108 #define KMP_GET_D_TAG(seq) ((seq) << 1 | 1)
1109 
1110 // Enumerates direct lock tags starting from indirect tag.
1111 typedef enum {
1112 #define expand_tag(l, a) locktag_##l = KMP_GET_D_TAG(lockseq_##l),
1113   KMP_FOREACH_D_LOCK(expand_tag, 0)
1114 #undef expand_tag
1115 } kmp_direct_locktag_t;
1116 
1117 // Indirect lock type
1118 typedef struct {
1119   kmp_user_lock_p lock;
1120   kmp_indirect_locktag_t type;
1121 } kmp_indirect_lock_t;
1122 
1123 // Function tables for direct locks. Set/unset/test differentiate functions
1124 // with/without consistency checking.
1125 extern void (*__kmp_direct_init[])(kmp_dyna_lock_t *, kmp_dyna_lockseq_t);
1126 extern void (**__kmp_direct_destroy)(kmp_dyna_lock_t *);
1127 extern int (**__kmp_direct_set)(kmp_dyna_lock_t *, kmp_int32);
1128 extern int (**__kmp_direct_unset)(kmp_dyna_lock_t *, kmp_int32);
1129 extern int (**__kmp_direct_test)(kmp_dyna_lock_t *, kmp_int32);
1130 
1131 // Function tables for indirect locks. Set/unset/test differentiate functions
1132 // with/without consistency checking.
1133 extern void (*__kmp_indirect_init[])(kmp_user_lock_p);
1134 extern void (**__kmp_indirect_destroy)(kmp_user_lock_p);
1135 extern int (**__kmp_indirect_set)(kmp_user_lock_p, kmp_int32);
1136 extern int (**__kmp_indirect_unset)(kmp_user_lock_p, kmp_int32);
1137 extern int (**__kmp_indirect_test)(kmp_user_lock_p, kmp_int32);
1138 
1139 // Extracts direct lock tag from a user lock pointer
1140 #define KMP_EXTRACT_D_TAG(l)                                                   \
1141   (*((kmp_dyna_lock_t *)(l)) & ((1 << KMP_LOCK_SHIFT) - 1) &                   \
1142    -(*((kmp_dyna_lock_t *)(l)) & 1))
1143 
1144 // Extracts indirect lock index from a user lock pointer
1145 #define KMP_EXTRACT_I_INDEX(l) (*(kmp_lock_index_t *)(l) >> 1)
1146 
1147 // Returns function pointer to the direct lock function with l (kmp_dyna_lock_t
1148 // *) and op (operation type).
1149 #define KMP_D_LOCK_FUNC(l, op) __kmp_direct_##op[KMP_EXTRACT_D_TAG(l)]
1150 
1151 // Returns function pointer to the indirect lock function with l
1152 // (kmp_indirect_lock_t *) and op (operation type).
1153 #define KMP_I_LOCK_FUNC(l, op)                                                 \
1154   __kmp_indirect_##op[((kmp_indirect_lock_t *)(l))->type]
1155 
1156 // Initializes a direct lock with the given lock pointer and lock sequence.
1157 #define KMP_INIT_D_LOCK(l, seq)                                                \
1158   __kmp_direct_init[KMP_GET_D_TAG(seq)]((kmp_dyna_lock_t *)l, seq)
1159 
1160 // Initializes an indirect lock with the given lock pointer and lock sequence.
1161 #define KMP_INIT_I_LOCK(l, seq)                                                \
1162   __kmp_direct_init[0]((kmp_dyna_lock_t *)(l), seq)
1163 
1164 // Returns "free" lock value for the given lock type.
1165 #define KMP_LOCK_FREE(type) (locktag_##type)
1166 
1167 // Returns "busy" lock value for the given lock teyp.
1168 #define KMP_LOCK_BUSY(v, type) ((v) << KMP_LOCK_SHIFT | locktag_##type)
1169 
1170 // Returns lock value after removing (shifting) lock tag.
1171 #define KMP_LOCK_STRIP(v) ((v) >> KMP_LOCK_SHIFT)
1172 
1173 // Initializes global states and data structures for managing dynamic user
1174 // locks.
1175 extern void __kmp_init_dynamic_user_locks();
1176 
1177 // Allocates and returns an indirect lock with the given indirect lock tag.
1178 extern kmp_indirect_lock_t *
1179 __kmp_allocate_indirect_lock(void **, kmp_int32, kmp_indirect_locktag_t);
1180 
1181 // Cleans up global states and data structures for managing dynamic user locks.
1182 extern void __kmp_cleanup_indirect_user_locks();
1183 
1184 // Default user lock sequence when not using hinted locks.
1185 extern kmp_dyna_lockseq_t __kmp_user_lock_seq;
1186 
1187 // Jump table for "set lock location", available only for indirect locks.
1188 extern void (*__kmp_indirect_set_location[KMP_NUM_I_LOCKS])(kmp_user_lock_p,
1189                                                             const ident_t *);
1190 #define KMP_SET_I_LOCK_LOCATION(lck, loc)                                      \
1191   {                                                                            \
1192     if (__kmp_indirect_set_location[(lck)->type] != NULL)                      \
1193       __kmp_indirect_set_location[(lck)->type]((lck)->lock, loc);              \
1194   }
1195 
1196 // Jump table for "set lock flags", available only for indirect locks.
1197 extern void (*__kmp_indirect_set_flags[KMP_NUM_I_LOCKS])(kmp_user_lock_p,
1198                                                          kmp_lock_flags_t);
1199 #define KMP_SET_I_LOCK_FLAGS(lck, flag)                                        \
1200   {                                                                            \
1201     if (__kmp_indirect_set_flags[(lck)->type] != NULL)                         \
1202       __kmp_indirect_set_flags[(lck)->type]((lck)->lock, flag);                \
1203   }
1204 
1205 // Jump table for "get lock location", available only for indirect locks.
1206 extern const ident_t *(*__kmp_indirect_get_location[KMP_NUM_I_LOCKS])(
1207     kmp_user_lock_p);
1208 #define KMP_GET_I_LOCK_LOCATION(lck)                                           \
1209   (__kmp_indirect_get_location[(lck)->type] != NULL                            \
1210        ? __kmp_indirect_get_location[(lck)->type]((lck)->lock)                 \
1211        : NULL)
1212 
1213 // Jump table for "get lock flags", available only for indirect locks.
1214 extern kmp_lock_flags_t (*__kmp_indirect_get_flags[KMP_NUM_I_LOCKS])(
1215     kmp_user_lock_p);
1216 #define KMP_GET_I_LOCK_FLAGS(lck)                                              \
1217   (__kmp_indirect_get_flags[(lck)->type] != NULL                               \
1218        ? __kmp_indirect_get_flags[(lck)->type]((lck)->lock)                    \
1219        : NULL)
1220 
1221 // number of kmp_indirect_lock_t objects to be allocated together
1222 #define KMP_I_LOCK_CHUNK 1024
1223 // Keep at a power of 2 since it is used in multiplication & division
1224 KMP_BUILD_ASSERT(KMP_I_LOCK_CHUNK % 2 == 0);
1225 // number of row entries in the initial lock table
1226 #define KMP_I_LOCK_TABLE_INIT_NROW_PTRS 8
1227 
1228 // Lock table for indirect locks.
1229 typedef struct kmp_indirect_lock_table {
1230   kmp_indirect_lock_t **table; // blocks of indirect locks allocated
1231   kmp_uint32 nrow_ptrs; // number *table pointer entries in table
1232   kmp_lock_index_t next; // index to the next lock to be allocated
1233   struct kmp_indirect_lock_table *next_table;
1234 } kmp_indirect_lock_table_t;
1235 
1236 extern kmp_indirect_lock_table_t __kmp_i_lock_table;
1237 
1238 // Returns the indirect lock associated with the given index.
1239 // Returns nullptr if no lock at given index
1240 static inline kmp_indirect_lock_t *__kmp_get_i_lock(kmp_lock_index_t idx) {
1241   kmp_indirect_lock_table_t *lock_table = &__kmp_i_lock_table;
1242   while (lock_table) {
1243     kmp_lock_index_t max_locks = lock_table->nrow_ptrs * KMP_I_LOCK_CHUNK;
1244     if (idx < max_locks) {
1245       kmp_lock_index_t row = idx / KMP_I_LOCK_CHUNK;
1246       kmp_lock_index_t col = idx % KMP_I_LOCK_CHUNK;
1247       if (!lock_table->table[row] || idx >= lock_table->next)
1248         break;
1249       return &lock_table->table[row][col];
1250     }
1251     idx -= max_locks;
1252     lock_table = lock_table->next_table;
1253   }
1254   return nullptr;
1255 }
1256 
1257 // Number of locks in a lock block, which is fixed to "1" now.
1258 // TODO: No lock block implementation now. If we do support, we need to manage
1259 // lock block data structure for each indirect lock type.
1260 extern int __kmp_num_locks_in_block;
1261 
1262 // Fast lock table lookup without consistency checking
1263 #define KMP_LOOKUP_I_LOCK(l)                                                   \
1264   ((OMP_LOCK_T_SIZE < sizeof(void *))                                          \
1265        ? __kmp_get_i_lock(KMP_EXTRACT_I_INDEX(l))                              \
1266        : *((kmp_indirect_lock_t **)(l)))
1267 
1268 // Used once in kmp_error.cpp
1269 extern kmp_int32 __kmp_get_user_lock_owner(kmp_user_lock_p, kmp_uint32);
1270 
1271 #else // KMP_USE_DYNAMIC_LOCK
1272 
1273 #define KMP_LOCK_BUSY(v, type) (v)
1274 #define KMP_LOCK_FREE(type) 0
1275 #define KMP_LOCK_STRIP(v) (v)
1276 
1277 #endif // KMP_USE_DYNAMIC_LOCK
1278 
1279 // data structure for using backoff within spin locks.
1280 typedef struct {
1281   kmp_uint32 step; // current step
1282   kmp_uint32 max_backoff; // upper bound of outer delay loop
1283   kmp_uint32 min_tick; // size of inner delay loop in ticks (machine-dependent)
1284 } kmp_backoff_t;
1285 
1286 // Runtime's default backoff parameters
1287 extern kmp_backoff_t __kmp_spin_backoff_params;
1288 
1289 // Backoff function
1290 extern void __kmp_spin_backoff(kmp_backoff_t *);
1291 
1292 #ifdef __cplusplus
1293 } // extern "C"
1294 #endif // __cplusplus
1295 
1296 #endif /* KMP_LOCK_H */
1297