1 /* Copyright (c) 2000, 2014, Oracle and/or its affiliates.
2    Copyright (c) 2009, 2020, MariaDB Corporation.
3 
4    This program is free software; you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation; version 2 of the License.
7 
8    This program is distributed in the hope that it will be useful,
9    but WITHOUT ANY WARRANTY; without even the implied warranty of
10    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11    GNU General Public License for more details.
12 
13    You should have received a copy of the GNU General Public License
14    along with this program; if not, write to the Free Software
15    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1335  USA */
16 
17 /* Defines to make different thread packages compatible */
18 
19 #ifndef _my_pthread_h
20 #define _my_pthread_h
21 
22 #ifndef ETIME
23 #define ETIME ETIMEDOUT				/* For FreeBSD */
24 #endif
25 
26 #ifdef  __cplusplus
27 #define EXTERNC extern "C"
28 extern "C" {
29 #else
30 #define EXTERNC
31 #endif /* __cplusplus */
32 
33 #if defined(__WIN__)
34 typedef CRITICAL_SECTION pthread_mutex_t;
35 typedef DWORD		 pthread_t;
36 typedef struct thread_attr {
37     DWORD dwStackSize ;
38     DWORD dwCreatingFlag ;
39 } pthread_attr_t ;
40 
41 typedef struct { int dummy; } pthread_condattr_t;
42 
43 /* Implementation of posix conditions */
44 
45 typedef struct st_pthread_link {
46   DWORD thread_id;
47   struct st_pthread_link *next;
48 } pthread_link;
49 
50 /**
51   Implementation of Windows condition variables.
52   We use native conditions on Vista and later, and fallback to own
53   implementation on earlier OS version.
54 */
55 typedef  CONDITION_VARIABLE pthread_cond_t;
56 
57 
58 typedef int pthread_mutexattr_t;
59 #define pthread_self() GetCurrentThreadId()
60 #define pthread_handler_t EXTERNC void * __cdecl
61 typedef void * (__cdecl *pthread_handler)(void *);
62 
63 typedef INIT_ONCE my_pthread_once_t;
64 #define MY_PTHREAD_ONCE_INIT INIT_ONCE_STATIC_INIT;
65 
66 #if !STRUCT_TIMESPEC_HAS_TV_SEC  || !STRUCT_TIMESPEC_HAS_TV_NSEC
67 struct timespec {
68   time_t tv_sec;
69   long tv_nsec;
70 };
71 #endif
72 
73 int win_pthread_mutex_trylock(pthread_mutex_t *mutex);
74 int pthread_create(pthread_t *, const pthread_attr_t *, pthread_handler, void *);
75 int pthread_cond_init(pthread_cond_t *cond, const pthread_condattr_t *attr);
76 int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex);
77 int pthread_cond_timedwait(pthread_cond_t *cond, pthread_mutex_t *mutex,
78 			   const struct timespec *abstime);
79 int pthread_cond_signal(pthread_cond_t *cond);
80 int pthread_cond_broadcast(pthread_cond_t *cond);
81 int pthread_cond_destroy(pthread_cond_t *cond);
82 int pthread_attr_init(pthread_attr_t *connect_att);
83 int pthread_attr_setstacksize(pthread_attr_t *connect_att,size_t stack);
84 int pthread_attr_destroy(pthread_attr_t *connect_att);
85 int my_pthread_once(my_pthread_once_t *once_control,void (*init_routine)(void));
86 
localtime_r(const time_t * timep,struct tm * tmp)87 static inline struct tm *localtime_r(const time_t *timep, struct tm *tmp)
88 {
89   localtime_s(tmp, timep);
90   return tmp;
91 }
92 
gmtime_r(const time_t * clock,struct tm * res)93 static inline struct tm *gmtime_r(const time_t *clock, struct tm *res)
94 {
95   gmtime_s(res, clock);
96   return res;
97 }
98 
99 void pthread_exit(void *a);
100 int pthread_join(pthread_t thread, void **value_ptr);
101 int pthread_cancel(pthread_t thread);
102 
103 #ifndef ETIMEDOUT
104 #define ETIMEDOUT 145		    /* Win32 doesn't have this */
105 #endif
106 
107 #define getpid() GetCurrentThreadId()
108 #define HAVE_LOCALTIME_R		1
109 #define _REENTRANT			1
110 #define HAVE_PTHREAD_ATTR_SETSTACKSIZE	1
111 
112 #undef SAFE_MUTEX				/* This will cause conflicts */
113 #define pthread_key(T,V)  DWORD V
114 #define pthread_key_create(A,B) ((*A=TlsAlloc())==0xFFFFFFFF)
115 #define pthread_key_delete(A) TlsFree(A)
116 #define my_pthread_setspecific_ptr(T,V) (!TlsSetValue((T),(V)))
117 #define pthread_setspecific(A,B) (!TlsSetValue((A),(LPVOID)(B)))
118 #define pthread_getspecific(A) (TlsGetValue(A))
119 #define my_pthread_getspecific(T,A) ((T) TlsGetValue(A))
120 #define my_pthread_getspecific_ptr(T,V) ((T) TlsGetValue(V))
121 
122 #define pthread_equal(A,B) ((A) == (B))
123 #define pthread_mutex_init(A,B)  (InitializeCriticalSection(A),0)
124 #define pthread_mutex_lock(A)	 (EnterCriticalSection(A),0)
125 #define pthread_mutex_trylock(A) win_pthread_mutex_trylock((A))
126 #define pthread_mutex_unlock(A)  (LeaveCriticalSection(A), 0)
127 #define pthread_mutex_destroy(A) (DeleteCriticalSection(A), 0)
128 #define pthread_kill(A,B) pthread_dummy((A) ? 0 : ESRCH)
129 
130 
131 /* Dummy defines for easier code */
132 #define pthread_attr_setdetachstate(A,B) pthread_dummy(0)
133 #define pthread_attr_setscope(A,B)
134 #define pthread_detach_this_thread()
135 #define pthread_condattr_init(A)
136 #define pthread_condattr_destroy(A)
137 #define pthread_yield() SwitchToThread()
138 #define my_sigset(A,B) signal(A,B)
139 
140 #else /* Normal threads */
141 
142 #ifdef HAVE_rts_threads
143 #define sigwait org_sigwait
144 #include <signal.h>
145 #undef sigwait
146 #endif
147 #include <pthread.h>
148 #ifndef _REENTRANT
149 #define _REENTRANT
150 #endif
151 #ifdef HAVE_THR_SETCONCURRENCY
152 #include <thread.h>			/* Probably solaris */
153 #endif
154 #ifdef HAVE_SCHED_H
155 #include <sched.h>
156 #endif
157 #ifdef HAVE_SYNCH_H
158 #include <synch.h>
159 #endif
160 
161 #define pthread_key(T,V) pthread_key_t V
162 #define my_pthread_getspecific_ptr(T,V) my_pthread_getspecific(T,(V))
163 #define my_pthread_setspecific_ptr(T,V) pthread_setspecific(T,(void*) (V))
164 #define pthread_detach_this_thread()
165 #define pthread_handler_t EXTERNC void *
166 typedef void *(* pthread_handler)(void *);
167 
168 #define my_pthread_once_t pthread_once_t
169 #if defined(PTHREAD_ONCE_INITIALIZER)
170 #define MY_PTHREAD_ONCE_INIT PTHREAD_ONCE_INITIALIZER
171 #else
172 #define MY_PTHREAD_ONCE_INIT PTHREAD_ONCE_INIT
173 #endif
174 #define my_pthread_once(C,F) pthread_once(C,F)
175 
176 /* Test first for RTS or FSU threads */
177 
178 #if defined(PTHREAD_SCOPE_GLOBAL) && !defined(PTHREAD_SCOPE_SYSTEM)
179 #define HAVE_rts_threads
180 extern int my_pthread_create_detached;
181 #define pthread_sigmask(A,B,C) sigprocmask((A),(B),(C))
182 #define PTHREAD_CREATE_DETACHED &my_pthread_create_detached
183 #define PTHREAD_SCOPE_SYSTEM  PTHREAD_SCOPE_GLOBAL
184 #define PTHREAD_SCOPE_PROCESS PTHREAD_SCOPE_LOCAL
185 #define USE_ALARM_THREAD
186 #endif /* defined(PTHREAD_SCOPE_GLOBAL) && !defined(PTHREAD_SCOPE_SYSTEM) */
187 
188 #if defined(_BSDI_VERSION) && _BSDI_VERSION < 199910
189 int sigwait(sigset_t *set, int *sig);
190 #endif
191 
192 static inline int my_sigwait(sigset_t *set, int *sig, int *code)
193 {
194 #ifdef HAVE_SIGWAITINFO
195   siginfo_t siginfo;
196   *sig= sigwaitinfo(set, &siginfo);
197   *code= siginfo.si_code;
198   return *sig < 0 ?  errno : 0;
199 /* XXX */
200 #ifndef SI_KERNEL
201 #define SI_KERNEL 128
202 #endif
203 #else
204   *code= 0;
205   return sigwait(set, sig);
206 #endif
207 }
208 
209 #if defined(HAVE_SIGTHREADMASK) && !defined(HAVE_PTHREAD_SIGMASK)
210 #define pthread_sigmask(A,B,C) sigthreadmask((A),(B),(C))
211 #endif
212 
213 #if !defined(HAVE_SIGWAIT) && !defined(HAVE_rts_threads) && !defined(sigwait) && !defined(alpha_linux_port) && !defined(_AIX)
214 int sigwait(sigset_t *setp, int *sigp);		/* Use our implementation */
215 #endif
216 
217 
218 /*
219   We define my_sigset() and use that instead of the system sigset() so that
220   we can favor an implementation based on sigaction(). On some systems, such
221   as Mac OS X, sigset() results in flags such as SA_RESTART being set, and
222   we want to make sure that no such flags are set.
223 */
224 #if defined(HAVE_SIGACTION) && !defined(my_sigset)
225 #define my_sigset(A,B) do { struct sigaction l_s; sigset_t l_set;           \
226                             DBUG_ASSERT((A) != 0);                          \
227                             sigemptyset(&l_set);                            \
228                             l_s.sa_handler = (B);                           \
229                             l_s.sa_mask   = l_set;                          \
230                             l_s.sa_flags   = 0;                             \
231                             sigaction((A), &l_s, NULL);                     \
232                           } while (0)
233 #elif defined(HAVE_SIGSET) && !defined(my_sigset)
234 #define my_sigset(A,B) sigset((A),(B))
235 #elif !defined(my_sigset)
236 #define my_sigset(A,B) signal((A),(B))
237 #endif
238 
239 #if !defined(HAVE_PTHREAD_ATTR_SETSCOPE)
240 #define pthread_attr_setscope(A,B)
241 #undef	HAVE_GETHOSTBYADDR_R			/* No definition */
242 #endif
243 
244 #define my_pthread_getspecific(A,B) ((A) pthread_getspecific(B))
245 
246 #ifndef HAVE_LOCALTIME_R
247 struct tm *localtime_r(const time_t *clock, struct tm *res);
248 #endif
249 
250 #ifndef HAVE_GMTIME_R
251 struct tm *gmtime_r(const time_t *clock, struct tm *res);
252 #endif
253 
254 #ifdef HAVE_PTHREAD_CONDATTR_CREATE
255 /* DCE threads on HPUX 10.20 */
256 #define pthread_condattr_init pthread_condattr_create
257 #define pthread_condattr_destroy pthread_condattr_delete
258 #endif
259 
260 /* FSU THREADS */
261 #if !defined(HAVE_PTHREAD_KEY_DELETE) && !defined(pthread_key_delete)
262 #define pthread_key_delete(A) pthread_dummy(0)
263 #endif
264 
265 #if defined(HAVE_PTHREAD_ATTR_CREATE) && !defined(HAVE_SIGWAIT)
266 /* This is set on AIX_3_2 and Siemens unix (and DEC OSF/1 3.2 too) */
267 #define pthread_key_create(A,B) \
268 		pthread_keycreate(A,(B) ?\
269 				  (pthread_destructor_t) (B) :\
270 				  (pthread_destructor_t) pthread_dummy)
271 #define pthread_attr_init(A) pthread_attr_create(A)
272 #define pthread_attr_destroy(A) pthread_attr_delete(A)
273 #define pthread_attr_setdetachstate(A,B) pthread_dummy(0)
274 #define pthread_create(A,B,C,D) pthread_create((A),*(B),(C),(D))
275 #ifndef pthread_sigmask
276 #define pthread_sigmask(A,B,C) sigprocmask((A),(B),(C))
277 #endif
278 #define pthread_kill(A,B) pthread_dummy((A) ? 0 : ESRCH)
279 #undef	pthread_detach_this_thread
280 #define pthread_detach_this_thread() { pthread_t tmp=pthread_self() ; pthread_detach(&tmp); }
281 #else /* HAVE_PTHREAD_ATTR_CREATE && !HAVE_SIGWAIT */
282 #define HAVE_PTHREAD_KILL 1
283 #endif
284 
285 #endif /* defined(__WIN__) */
286 
287 #if defined(HPUX10) && !defined(DONT_REMAP_PTHREAD_FUNCTIONS)
288 #undef pthread_cond_timedwait
289 #define pthread_cond_timedwait(a,b,c) my_pthread_cond_timedwait((a),(b),(c))
290 int my_pthread_cond_timedwait(pthread_cond_t *cond, pthread_mutex_t *mutex,
291 			      struct timespec *abstime);
292 #endif
293 
294 #if defined(HPUX10)
295 #define pthread_attr_getstacksize(A,B) my_pthread_attr_getstacksize(A,B)
296 void my_pthread_attr_getstacksize(pthread_attr_t *attrib, size_t *size);
297 #endif
298 
299 #if defined(HAVE_POSIX1003_4a_MUTEX) && !defined(DONT_REMAP_PTHREAD_FUNCTIONS)
300 #undef pthread_mutex_trylock
301 #define pthread_mutex_trylock(a) my_pthread_mutex_trylock((a))
302 int my_pthread_mutex_trylock(pthread_mutex_t *mutex);
303 #endif
304 
305 #ifdef HAVE_SCHED_YIELD
306 #define pthread_yield() sched_yield()
307 #else
308 #if !defined(HAVE_PTHREAD_YIELD_ZERO_ARG)
309 /* no pthread_yield() available */
310 #if defined(HAVE_PTHREAD_YIELD_NP) /* can be Mac OS X */
311 #define pthread_yield() pthread_yield_np()
312 #elif defined(HAVE_THR_YIELD)
313 #define pthread_yield() thr_yield()
314 #endif //defined(HAVE_PTHREAD_YIELD_NP)
315 #endif //!defined(HAVE_PTHREAD_YIELD_ZERO_ARG)
316 #endif //HAVE_SCHED_YIELD
317 
318 size_t my_setstacksize(pthread_attr_t *attr, size_t stacksize);
319 
320 /*
321   The defines set_timespec and set_timespec_nsec should be used
322   for calculating an absolute time at which
323   pthread_cond_timedwait should timeout
324 */
325 #define set_timespec(ABSTIME,SEC) set_timespec_nsec((ABSTIME),(SEC)*1000000000ULL)
326 
327 #ifndef set_timespec_nsec
328 #define set_timespec_nsec(ABSTIME,NSEC)                                 \
329   set_timespec_time_nsec((ABSTIME), my_hrtime_coarse().val*1000 + (NSEC))
330 #endif /* !set_timespec_nsec */
331 
332 /* adapt for two different flavors of struct timespec */
333 #ifdef HAVE_TIMESPEC_TS_SEC
334 #define MY_tv_sec  ts_sec
335 #define MY_tv_nsec ts_nsec
336 #else
337 #define MY_tv_sec  tv_sec
338 #define MY_tv_nsec tv_nsec
339 #endif /* HAVE_TIMESPEC_TS_SEC */
340 
341 /**
342    Compare two timespec structs.
343 
344    @retval  1 If TS1 ends after TS2.
345 
346    @retval  0 If TS1 is equal to TS2.
347 
348    @retval -1 If TS1 ends before TS2.
349 */
350 #ifndef cmp_timespec
351 #define cmp_timespec(TS1, TS2) \
352   ((TS1.MY_tv_sec > TS2.MY_tv_sec || \
353     (TS1.MY_tv_sec == TS2.MY_tv_sec && TS1.MY_tv_nsec > TS2.MY_tv_nsec)) ? 1 : \
354    ((TS1.MY_tv_sec < TS2.MY_tv_sec || \
355      (TS1.MY_tv_sec == TS2.MY_tv_sec && TS1.MY_tv_nsec < TS2.MY_tv_nsec)) ? -1 : 0))
356 #endif /* !cmp_timespec */
357 
358 #ifndef set_timespec_time_nsec
359 #define set_timespec_time_nsec(ABSTIME,NSEC) do {		\
360   ulonglong _now_= (NSEC);					\
361   (ABSTIME).MY_tv_sec=  (time_t) (_now_ / 1000000000ULL);	\
362   (ABSTIME).MY_tv_nsec= (ulong) (_now_ % 1000000000UL);		\
363 } while(0)
364 #endif /* !set_timespec_time_nsec */
365 
366 #ifdef MYSQL_CLIENT
367 #define _current_thd() NULL
368 #else
369 MYSQL_THD _current_thd();
370 #endif
371 
372 /* safe_mutex adds checking to mutex for easier debugging */
373 struct st_hash;
374 typedef struct st_safe_mutex_t
375 {
376   pthread_mutex_t global,mutex;
377   const char *file, *name;
378   uint line,count;
379   myf create_flags, active_flags;
380   ulong id;
381   pthread_t thread;
382   struct st_hash *locked_mutex, *used_mutex;
383   struct st_safe_mutex_t *prev, *next;
384 #ifdef SAFE_MUTEX_DETECT_DESTROY
385   struct st_safe_mutex_info_t *info;	/* to track destroying of mutexes */
386 #endif
387 } safe_mutex_t;
388 
389 typedef struct st_safe_mutex_deadlock_t
390 {
391   const char *file, *name;
392   safe_mutex_t *mutex;
393   uint line;
394   ulong count;
395   ulong id;
396   my_bool warning_only;
397 } safe_mutex_deadlock_t;
398 
399 #ifdef SAFE_MUTEX_DETECT_DESTROY
400 /*
401   Used to track the destroying of mutexes. This needs to be a separate
402   structure because the safe_mutex_t structure could be freed before
403   the mutexes are destroyed.
404 */
405 
406 typedef struct st_safe_mutex_info_t
407 {
408   struct st_safe_mutex_info_t *next;
409   struct st_safe_mutex_info_t *prev;
410   const char *init_file;
411   uint32 init_line;
412 } safe_mutex_info_t;
413 #endif /* SAFE_MUTEX_DETECT_DESTROY */
414 
415 int safe_mutex_init(safe_mutex_t *mp, const pthread_mutexattr_t *attr,
416                     const char *name, const char *file, uint line);
417 int safe_mutex_lock(safe_mutex_t *mp, myf my_flags, const char *file,
418                     uint line);
419 int safe_mutex_unlock(safe_mutex_t *mp,const char *file, uint line);
420 int safe_mutex_destroy(safe_mutex_t *mp,const char *file, uint line);
421 int safe_cond_wait(pthread_cond_t *cond, safe_mutex_t *mp,const char *file,
422 		   uint line);
423 int safe_cond_timedwait(pthread_cond_t *cond, safe_mutex_t *mp,
424                         const struct timespec *abstime,
425                         const char *file, uint line);
426 void safe_mutex_global_init(void);
427 void safe_mutex_end(FILE *file);
428 void safe_mutex_free_deadlock_data(safe_mutex_t *mp);
429 
430 	/* Wrappers if safe mutex is actually used */
431 #define MYF_TRY_LOCK              1
432 #define MYF_NO_DEADLOCK_DETECTION 2
433 
434 #ifdef SAFE_MUTEX
435 #define safe_mutex_is_owner(mp) ((mp)->count > 0 && \
436                                  pthread_equal(pthread_self(), (mp)->thread))
437 #define safe_mutex_assert_owner(mp) DBUG_ASSERT(safe_mutex_is_owner(mp))
438 #define safe_mutex_assert_not_owner(mp) DBUG_ASSERT(!safe_mutex_is_owner(mp))
439 #define safe_mutex_setflags(mp, F)      do { (mp)->create_flags|= (F); } while (0)
440 #define my_cond_timedwait(A,B,C) safe_cond_timedwait((A),(B),(C),__FILE__,__LINE__)
441 #define my_cond_wait(A,B) safe_cond_wait((A), (B), __FILE__, __LINE__)
442 #else
443 
444 #define safe_mutex_assert_owner(mp) do {} while (0)
445 #define safe_mutex_assert_not_owner(mp) do {} while (0)
446 #define safe_mutex_setflags(mp, F) do {} while (0)
447 
448 #define my_cond_timedwait(A,B,C) pthread_cond_timedwait((A),(B),(C))
449 #define my_cond_wait(A,B) pthread_cond_wait((A), (B))
450 #endif /* !SAFE_MUTEX */
451 
452 	/* READ-WRITE thread locking */
453 
454 #if defined(USE_MUTEX_INSTEAD_OF_RW_LOCKS)
455 /* use these defs for simple mutex locking */
456 #define rw_lock_t pthread_mutex_t
457 #define my_rwlock_init(A,B) pthread_mutex_init((A),(B))
458 #define rw_rdlock(A) pthread_mutex_lock((A))
459 #define rw_wrlock(A) pthread_mutex_lock((A))
460 #define rw_tryrdlock(A) pthread_mutex_trylock((A))
461 #define rw_trywrlock(A) pthread_mutex_trylock((A))
462 #define rw_unlock(A) pthread_mutex_unlock((A))
463 #define rwlock_destroy(A) pthread_mutex_destroy((A))
464 #elif defined(HAVE_PTHREAD_RWLOCK_RDLOCK)
465 #define rw_lock_t pthread_rwlock_t
466 #define my_rwlock_init(A,B) pthread_rwlock_init((A),(B))
467 #define rw_rdlock(A) pthread_rwlock_rdlock(A)
468 #define rw_wrlock(A) pthread_rwlock_wrlock(A)
469 #define rw_tryrdlock(A) pthread_rwlock_tryrdlock((A))
470 #define rw_trywrlock(A) pthread_rwlock_trywrlock((A))
471 #define rw_unlock(A) pthread_rwlock_unlock(A)
472 #define rwlock_destroy(A) pthread_rwlock_destroy(A)
473 #elif defined(HAVE_RWLOCK_INIT)
474 #ifdef HAVE_RWLOCK_T				/* For example Solaris 2.6-> */
475 #define rw_lock_t rwlock_t
476 #endif
477 #define my_rwlock_init(A,B) rwlock_init((A),USYNC_THREAD,0)
478 #else
479 /* Use our own version of read/write locks */
480 #define NEED_MY_RW_LOCK 1
481 #define rw_lock_t my_rw_lock_t
482 #define my_rwlock_init(A,B) my_rw_init((A))
483 #define rw_rdlock(A) my_rw_rdlock((A))
484 #define rw_wrlock(A) my_rw_wrlock((A))
485 #define rw_tryrdlock(A) my_rw_tryrdlock((A))
486 #define rw_trywrlock(A) my_rw_trywrlock((A))
487 #define rw_unlock(A) my_rw_unlock((A))
488 #define rwlock_destroy(A) my_rw_destroy((A))
489 #define rw_lock_assert_write_owner(A) my_rw_lock_assert_write_owner((A))
490 #define rw_lock_assert_not_write_owner(A) my_rw_lock_assert_not_write_owner((A))
491 #endif /* USE_MUTEX_INSTEAD_OF_RW_LOCKS */
492 
493 
494 /**
495   Portable implementation of special type of read-write locks.
496 
497   These locks have two properties which are unusual for rwlocks:
498   1) They "prefer readers" in the sense that they do not allow
499      situations in which rwlock is rd-locked and there is a
500      pending rd-lock which is blocked (e.g. due to pending
501      request for wr-lock).
502      This is a stronger guarantee than one which is provided for
503      PTHREAD_RWLOCK_PREFER_READER_NP rwlocks in Linux.
504      MDL subsystem deadlock detector relies on this property for
505      its correctness.
506   2) They are optimized for uncontended wr-lock/unlock case.
507      This is a scenario in which they are most often used
508      within MDL subsystem. Optimizing for it gives significant
509      performance improvements in some of the tests involving many
510      connections.
511 
512   Another important requirement imposed on this type of rwlock
513   by the MDL subsystem is that it should be OK to destroy rwlock
514   object which is in unlocked state even though some threads might
515   have not yet fully left unlock operation for it (of course there
516   is an external guarantee that no thread will try to lock rwlock
517   which is destroyed).
518   Putting it another way the unlock operation should not access
519   rwlock data after changing its state to unlocked.
520 
521   TODO/FIXME: We should consider alleviating this requirement as
522   it blocks us from doing certain performance optimizations.
523 */
524 
525 typedef struct st_rw_pr_lock_t {
526   /**
527     Lock which protects the structure.
528     Also held for the duration of wr-lock.
529   */
530   pthread_mutex_t lock;
531   /**
532     Condition variable which is used to wake-up
533     writers waiting for readers to go away.
534   */
535   pthread_cond_t no_active_readers;
536   /** Number of active readers. */
537   uint active_readers;
538   /** Number of writers waiting for readers to go away. */
539   uint writers_waiting_readers;
540   /** Indicates whether there is an active writer. */
541   my_bool active_writer;
542 #ifdef SAFE_MUTEX
543   /** Thread holding wr-lock (for debug purposes only). */
544   pthread_t writer_thread;
545 #endif
546 } rw_pr_lock_t;
547 
548 extern int rw_pr_init(rw_pr_lock_t *);
549 extern int rw_pr_rdlock(rw_pr_lock_t *);
550 extern int rw_pr_wrlock(rw_pr_lock_t *);
551 extern int rw_pr_unlock(rw_pr_lock_t *);
552 extern int rw_pr_destroy(rw_pr_lock_t *);
553 #ifdef SAFE_MUTEX
554 #define rw_pr_lock_assert_write_owner(A) \
555   DBUG_ASSERT((A)->active_writer && pthread_equal(pthread_self(), \
556                                                   (A)->writer_thread))
557 #define rw_pr_lock_assert_not_write_owner(A) \
558   DBUG_ASSERT(! (A)->active_writer || ! pthread_equal(pthread_self(), \
559                                                       (A)->writer_thread))
560 #else
561 #define rw_pr_lock_assert_write_owner(A)
562 #define rw_pr_lock_assert_not_write_owner(A)
563 #endif /* SAFE_MUTEX */
564 
565 
566 #ifdef NEED_MY_RW_LOCK
567 
568 #ifdef _WIN32
569 
570 /**
571   Implementation of Windows rwlock.
572 
573   We use native (slim) rwlocks on Windows, which requires Win7
574   or later.
575 */
576 typedef struct _my_rwlock_t
577 {
578   SRWLOCK srwlock;             /* native reader writer lock */
579   BOOL have_exclusive_srwlock; /* used for unlock */
580 } my_rw_lock_t;
581 
582 
583 #else /* _WIN32 */
584 
585 /*
586   On systems which don't support native read/write locks we have
587   to use own implementation.
588 */
589 typedef struct st_my_rw_lock_t {
590 	pthread_mutex_t lock;		/* lock for structure		*/
591 	pthread_cond_t	readers;	/* waiting readers		*/
592 	pthread_cond_t	writers;	/* waiting writers		*/
593 	int		state;		/* -1:writer,0:free,>0:readers	*/
594 	int             waiters;        /* number of waiting writers	*/
595 #ifdef SAFE_MUTEX
596         pthread_t       write_thread;
597 #endif
598 } my_rw_lock_t;
599 
600 #endif /*! _WIN32 */
601 
602 extern int my_rw_init(my_rw_lock_t *);
603 extern int my_rw_destroy(my_rw_lock_t *);
604 extern int my_rw_rdlock(my_rw_lock_t *);
605 extern int my_rw_wrlock(my_rw_lock_t *);
606 extern int my_rw_unlock(my_rw_lock_t *);
607 extern int my_rw_tryrdlock(my_rw_lock_t *);
608 extern int my_rw_trywrlock(my_rw_lock_t *);
609 #ifdef SAFE_MUTEX
610 #define my_rw_lock_assert_write_owner(A) \
611   DBUG_ASSERT((A)->state == -1 && pthread_equal(pthread_self(), \
612                                                 (A)->write_thread))
613 #define my_rw_lock_assert_not_write_owner(A) \
614   DBUG_ASSERT((A)->state >= 0 || ! pthread_equal(pthread_self(), \
615                                                  (A)->write_thread))
616 #else
617 #define my_rw_lock_assert_write_owner(A)
618 #define my_rw_lock_assert_not_write_owner(A)
619 #endif
620 #endif /* NEED_MY_RW_LOCK */
621 
622 
623 #define GETHOSTBYADDR_BUFF_SIZE 2048
624 
625 #ifndef HAVE_THR_SETCONCURRENCY
626 #define thr_setconcurrency(A) pthread_dummy(0)
627 #endif
628 #if !defined(HAVE_PTHREAD_ATTR_SETSTACKSIZE) && ! defined(pthread_attr_setstacksize)
629 #define pthread_attr_setstacksize(A,B) pthread_dummy(0)
630 #endif
631 
632 /* Define mutex types, see my_thr_init.c */
633 #define MY_MUTEX_INIT_SLOW   NULL
634 #ifdef PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP
635 extern pthread_mutexattr_t my_fast_mutexattr;
636 #define MY_MUTEX_INIT_FAST &my_fast_mutexattr
637 #else
638 #define MY_MUTEX_INIT_FAST   NULL
639 #endif
640 #ifdef PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP
641 extern pthread_mutexattr_t my_errorcheck_mutexattr;
642 #define MY_MUTEX_INIT_ERRCHK &my_errorcheck_mutexattr
643 #else
644 #define MY_MUTEX_INIT_ERRCHK   NULL
645 #endif
646 
647 #ifndef ESRCH
648 /* Define it to something */
649 #define ESRCH 1
650 #endif
651 
652 typedef uint64 my_thread_id;
653 
654 extern void my_threadattr_global_init(void);
655 extern my_bool my_thread_global_init(void);
656 extern void my_thread_global_reinit(void);
657 extern void my_thread_global_end(void);
658 extern my_bool my_thread_init(void);
659 extern void my_thread_end(void);
660 extern const char *my_thread_name(void);
661 extern my_thread_id my_thread_dbug_id(void);
662 extern int pthread_dummy(int);
663 extern void my_mutex_init(void);
664 extern void my_mutex_end(void);
665 
666 /* All thread specific variables are in the following struct */
667 
668 #define THREAD_NAME_SIZE 10
669 #ifndef DEFAULT_THREAD_STACK
670 /*
671   We need to have at least 256K stack to handle calls to myisamchk_init()
672   with the current number of keys and key parts.
673 */
674 #if defined(__SANITIZE_ADDRESS__) || defined(WITH_UBSAN)
675 #ifndef DBUG_OFF
676 #define DEFAULT_THREAD_STACK	(1024*1024L)
677 #else
678 #define DEFAULT_THREAD_STACK	(383*1024L) /* 392192 */
679 #endif
680 #else
681 #define DEFAULT_THREAD_STACK	(292*1024L) /* 299008 */
682 #endif
683 #endif
684 
685 #define MY_PTHREAD_LOCK_READ 0
686 #define MY_PTHREAD_LOCK_WRITE 1
687 
688 #include <mysql/psi/mysql_thread.h>
689 
690 #define INSTRUMENT_ME 0
691 
692 /*
693   Thread specific variables
694 
695   Aria key cache is using the following variables for keeping track of
696   state:
697   suspend, next, prev, keycache_link, keycache_file, suspend, lock_type
698 
699   MariaDB uses the following to
700   mutex, current_mutex, current_cond, abort
701 */
702 
703 struct st_my_thread_var
704 {
705   int thr_errno;
706   mysql_cond_t suspend;
707   mysql_mutex_t mutex;
708   struct st_my_thread_var *next,**prev;
709   mysql_mutex_t * volatile current_mutex;
710   mysql_cond_t * volatile current_cond;
711   void *keycache_link;
712   void *keycache_file;
713   void *stack_ends_here;
714   safe_mutex_t *mutex_in_use;
715   pthread_t pthread_self;
716   my_thread_id id, dbug_id;
717   int volatile abort;
718   uint lock_type; /* used by conditional release the queue */
719   my_bool init;
720 #ifndef DBUG_OFF
721   void *dbug;
722   char name[THREAD_NAME_SIZE+1];
723 #endif
724 };
725 
726 struct st_my_thread_var *_my_thread_var(void);
727 extern void **my_thread_var_dbug(void);
728 extern safe_mutex_t **my_thread_var_mutex_in_use(void);
729 extern uint my_thread_end_wait_time;
730 extern my_bool safe_mutex_deadlock_detector;
731 #define my_thread_var (_my_thread_var())
732 #define my_errno my_thread_var->thr_errno
733 int set_mysys_var(struct st_my_thread_var *mysys_var);
734 
735 
736 /*
737   thread_safe_xxx functions are for critical statistic or counters.
738   The implementation is guaranteed to be thread safe, on all platforms.
739   Note that the calling code should *not* assume the counter is protected
740   by the mutex given, as the implementation of these helpers may change
741   to use my_atomic operations instead.
742 */
743 
744 #ifndef thread_safe_increment
745 #ifdef _WIN32
746 #define thread_safe_increment(V,L) InterlockedIncrement((long*) &(V))
747 #define thread_safe_decrement(V,L) InterlockedDecrement((long*) &(V))
748 #else
749 #define thread_safe_increment(V,L) \
750         (mysql_mutex_lock((L)), (V)++, mysql_mutex_unlock((L)))
751 #define thread_safe_decrement(V,L) \
752         (mysql_mutex_lock((L)), (V)--, mysql_mutex_unlock((L)))
753 #endif
754 #endif
755 
756 #ifndef thread_safe_add
757 #ifdef _WIN32
758 #define thread_safe_add(V,C,L) InterlockedExchangeAdd((long*) &(V),(C))
759 #define thread_safe_sub(V,C,L) InterlockedExchangeAdd((long*) &(V),-(long) (C))
760 #else
761 #define thread_safe_add(V,C,L) \
762         (mysql_mutex_lock((L)), (V)+=(C), mysql_mutex_unlock((L)))
763 #define thread_safe_sub(V,C,L) \
764         (mysql_mutex_lock((L)), (V)-=(C), mysql_mutex_unlock((L)))
765 #endif
766 #endif
767 
768 
769 /*
770   statistics_xxx functions are for non critical statistic,
771   maintained in global variables.
772   When compiling with SAFE_STATISTICS:
773   - race conditions can not occur.
774   - some locking occurs, which may cause performance degradation.
775 
776   When compiling without SAFE_STATISTICS:
777   - race conditions can occur, making the result slightly inaccurate.
778   - the lock given is not honored.
779 */
780 #ifdef SAFE_STATISTICS
781 #define statistic_increment(V,L) thread_safe_increment((V),(L))
782 #define statistic_decrement(V,L) thread_safe_decrement((V),(L))
783 #define statistic_add(V,C,L)     thread_safe_add((V),(C),(L))
784 #define statistic_sub(V,C,L)     thread_safe_sub((V),(C),(L))
785 #else
786 #define statistic_decrement(V,L) (V)--
787 #define statistic_increment(V,L) (V)++
788 #define statistic_add(V,C,L)     (V)+=(C)
789 #define statistic_sub(V,C,L)     (V)-=(C)
790 #endif /* SAFE_STATISTICS */
791 
792 /*
793   No locking needed, the counter is owned by the thread
794 */
795 #define status_var_increment(V) (V)++
796 #define status_var_decrement(V) (V)--
797 #define status_var_add(V,C)     (V)+=(C)
798 #define status_var_sub(V,C)     (V)-=(C)
799 
800 #ifdef SAFE_MUTEX
801 #define mysql_mutex_record_order(A,B)                   \
802   do {                                                  \
803     mysql_mutex_lock(A); mysql_mutex_lock(B);           \
804     mysql_mutex_unlock(B); mysql_mutex_unlock(A);       \
805   }  while(0)
806 #else
807 #define mysql_mutex_record_order(A,B) do { } while(0)
808 #endif
809 
810 /* At least Windows and NetBSD do not have this definition */
811 #ifndef PTHREAD_STACK_MIN
812 #define PTHREAD_STACK_MIN 65536
813 #endif
814 
815 #ifdef  __cplusplus
816 }
817 #endif
818 #endif /* _my_ptread_h */
819