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),(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 /*
319   The defines set_timespec and set_timespec_nsec should be used
320   for calculating an absolute time at which
321   pthread_cond_timedwait should timeout
322 */
323 #define set_timespec(ABSTIME,SEC) set_timespec_nsec((ABSTIME),(SEC)*1000000000ULL)
324 
325 #ifndef set_timespec_nsec
326 #define set_timespec_nsec(ABSTIME,NSEC)                                 \
327   set_timespec_time_nsec((ABSTIME), my_hrtime_coarse().val*1000 + (NSEC))
328 #endif /* !set_timespec_nsec */
329 
330 /* adapt for two different flavors of struct timespec */
331 #ifdef HAVE_TIMESPEC_TS_SEC
332 #define MY_tv_sec  ts_sec
333 #define MY_tv_nsec ts_nsec
334 #else
335 #define MY_tv_sec  tv_sec
336 #define MY_tv_nsec tv_nsec
337 #endif /* HAVE_TIMESPEC_TS_SEC */
338 
339 /**
340    Compare two timespec structs.
341 
342    @retval  1 If TS1 ends after TS2.
343 
344    @retval  0 If TS1 is equal to TS2.
345 
346    @retval -1 If TS1 ends before TS2.
347 */
348 #ifndef cmp_timespec
349 #define cmp_timespec(TS1, TS2) \
350   ((TS1.MY_tv_sec > TS2.MY_tv_sec || \
351     (TS1.MY_tv_sec == TS2.MY_tv_sec && TS1.MY_tv_nsec > TS2.MY_tv_nsec)) ? 1 : \
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 : 0))
354 #endif /* !cmp_timespec */
355 
356 #ifndef set_timespec_time_nsec
357 #define set_timespec_time_nsec(ABSTIME,NSEC) do {    \
358   ulonglong _now_= (NSEC);                             \
359   (ABSTIME).MY_tv_sec=  (_now_ / 1000000000ULL);       \
360   (ABSTIME).MY_tv_nsec= (_now_ % 1000000000ULL);       \
361 } while(0)
362 #endif /* !set_timespec_time_nsec */
363 
364 #ifdef MYSQL_CLIENT
365 #define _current_thd() NULL
366 #elif defined(_WIN32)
367 #ifdef __cplusplus
368 extern "C"
369 #endif
370 MYSQL_THD _current_thd_noinline();
371 #define _current_thd() _current_thd_noinline()
372 #else
373 /*
374   THR_THD is a key which will be used to set/get THD* for a thread,
375   using my_pthread_setspecific_ptr()/my_thread_getspecific_ptr().
376 */
377 extern pthread_key(MYSQL_THD, THR_THD);
_current_thd(void)378 static inline MYSQL_THD _current_thd(void)
379 {
380   return my_pthread_getspecific_ptr(MYSQL_THD,THR_THD);
381 }
382 #endif
383 
384 /* safe_mutex adds checking to mutex for easier debugging */
385 struct st_hash;
386 typedef struct st_safe_mutex_t
387 {
388   pthread_mutex_t global,mutex;
389   const char *file, *name;
390   uint line,count;
391   myf create_flags, active_flags;
392   ulong id;
393   pthread_t thread;
394   struct st_hash *locked_mutex, *used_mutex;
395   struct st_safe_mutex_t *prev, *next;
396 #ifdef SAFE_MUTEX_DETECT_DESTROY
397   struct st_safe_mutex_info_t *info;	/* to track destroying of mutexes */
398 #endif
399 } safe_mutex_t;
400 
401 typedef struct st_safe_mutex_deadlock_t
402 {
403   const char *file, *name;
404   safe_mutex_t *mutex;
405   uint line;
406   ulong count;
407   ulong id;
408   my_bool warning_only;
409 } safe_mutex_deadlock_t;
410 
411 #ifdef SAFE_MUTEX_DETECT_DESTROY
412 /*
413   Used to track the destroying of mutexes. This needs to be a separate
414   structure because the safe_mutex_t structure could be freed before
415   the mutexes are destroyed.
416 */
417 
418 typedef struct st_safe_mutex_info_t
419 {
420   struct st_safe_mutex_info_t *next;
421   struct st_safe_mutex_info_t *prev;
422   const char *init_file;
423   uint32 init_line;
424 } safe_mutex_info_t;
425 #endif /* SAFE_MUTEX_DETECT_DESTROY */
426 
427 int safe_mutex_init(safe_mutex_t *mp, const pthread_mutexattr_t *attr,
428                     const char *name, const char *file, uint line);
429 int safe_mutex_lock(safe_mutex_t *mp, myf my_flags, const char *file,
430                     uint line);
431 int safe_mutex_unlock(safe_mutex_t *mp,const char *file, uint line);
432 int safe_mutex_destroy(safe_mutex_t *mp,const char *file, uint line);
433 int safe_cond_wait(pthread_cond_t *cond, safe_mutex_t *mp,const char *file,
434 		   uint line);
435 int safe_cond_timedwait(pthread_cond_t *cond, safe_mutex_t *mp,
436                         const struct timespec *abstime,
437                         const char *file, uint line);
438 void safe_mutex_global_init(void);
439 void safe_mutex_end(FILE *file);
440 void safe_mutex_free_deadlock_data(safe_mutex_t *mp);
441 
442 	/* Wrappers if safe mutex is actually used */
443 #define MYF_TRY_LOCK              1
444 #define MYF_NO_DEADLOCK_DETECTION 2
445 
446 #ifdef SAFE_MUTEX
447 #define safe_mutex_assert_owner(mp) \
448           DBUG_ASSERT((mp)->count > 0 && \
449                       pthread_equal(pthread_self(), (mp)->thread))
450 #define safe_mutex_assert_not_owner(mp) \
451           DBUG_ASSERT(! (mp)->count || \
452                       ! pthread_equal(pthread_self(), (mp)->thread))
453 #define safe_mutex_setflags(mp, F)      do { (mp)->create_flags|= (F); } while (0)
454 #define my_cond_timedwait(A,B,C) safe_cond_timedwait((A),(B),(C),__FILE__,__LINE__)
455 #define my_cond_wait(A,B) safe_cond_wait((A), (B), __FILE__, __LINE__)
456 #else
457 
458 #define safe_mutex_assert_owner(mp) do {} while (0)
459 #define safe_mutex_assert_not_owner(mp) do {} while (0)
460 #define safe_mutex_setflags(mp, F) do {} while (0)
461 
462 #define my_cond_timedwait(A,B,C) pthread_cond_timedwait((A),(B),(C))
463 #define my_cond_wait(A,B) pthread_cond_wait((A), (B))
464 #endif /* !SAFE_MUTEX */
465 
466 	/* READ-WRITE thread locking */
467 
468 #if defined(USE_MUTEX_INSTEAD_OF_RW_LOCKS)
469 /* use these defs for simple mutex locking */
470 #define rw_lock_t pthread_mutex_t
471 #define my_rwlock_init(A,B) pthread_mutex_init((A),(B))
472 #define rw_rdlock(A) pthread_mutex_lock((A))
473 #define rw_wrlock(A) pthread_mutex_lock((A))
474 #define rw_tryrdlock(A) pthread_mutex_trylock((A))
475 #define rw_trywrlock(A) pthread_mutex_trylock((A))
476 #define rw_unlock(A) pthread_mutex_unlock((A))
477 #define rwlock_destroy(A) pthread_mutex_destroy((A))
478 #elif defined(HAVE_PTHREAD_RWLOCK_RDLOCK)
479 #define rw_lock_t pthread_rwlock_t
480 #define my_rwlock_init(A,B) pthread_rwlock_init((A),(B))
481 #define rw_rdlock(A) pthread_rwlock_rdlock(A)
482 #define rw_wrlock(A) pthread_rwlock_wrlock(A)
483 #define rw_tryrdlock(A) pthread_rwlock_tryrdlock((A))
484 #define rw_trywrlock(A) pthread_rwlock_trywrlock((A))
485 #define rw_unlock(A) pthread_rwlock_unlock(A)
486 #define rwlock_destroy(A) pthread_rwlock_destroy(A)
487 #elif defined(HAVE_RWLOCK_INIT)
488 #ifdef HAVE_RWLOCK_T				/* For example Solaris 2.6-> */
489 #define rw_lock_t rwlock_t
490 #endif
491 #define my_rwlock_init(A,B) rwlock_init((A),USYNC_THREAD,0)
492 #else
493 /* Use our own version of read/write locks */
494 #define NEED_MY_RW_LOCK 1
495 #define rw_lock_t my_rw_lock_t
496 #define my_rwlock_init(A,B) my_rw_init((A))
497 #define rw_rdlock(A) my_rw_rdlock((A))
498 #define rw_wrlock(A) my_rw_wrlock((A))
499 #define rw_tryrdlock(A) my_rw_tryrdlock((A))
500 #define rw_trywrlock(A) my_rw_trywrlock((A))
501 #define rw_unlock(A) my_rw_unlock((A))
502 #define rwlock_destroy(A) my_rw_destroy((A))
503 #define rw_lock_assert_write_owner(A) my_rw_lock_assert_write_owner((A))
504 #define rw_lock_assert_not_write_owner(A) my_rw_lock_assert_not_write_owner((A))
505 #endif /* USE_MUTEX_INSTEAD_OF_RW_LOCKS */
506 
507 
508 /**
509   Portable implementation of special type of read-write locks.
510 
511   These locks have two properties which are unusual for rwlocks:
512   1) They "prefer readers" in the sense that they do not allow
513      situations in which rwlock is rd-locked and there is a
514      pending rd-lock which is blocked (e.g. due to pending
515      request for wr-lock).
516      This is a stronger guarantee than one which is provided for
517      PTHREAD_RWLOCK_PREFER_READER_NP rwlocks in Linux.
518      MDL subsystem deadlock detector relies on this property for
519      its correctness.
520   2) They are optimized for uncontended wr-lock/unlock case.
521      This is a scenario in which they are most often used
522      within MDL subsystem. Optimizing for it gives significant
523      performance improvements in some of the tests involving many
524      connections.
525 
526   Another important requirement imposed on this type of rwlock
527   by the MDL subsystem is that it should be OK to destroy rwlock
528   object which is in unlocked state even though some threads might
529   have not yet fully left unlock operation for it (of course there
530   is an external guarantee that no thread will try to lock rwlock
531   which is destroyed).
532   Putting it another way the unlock operation should not access
533   rwlock data after changing its state to unlocked.
534 
535   TODO/FIXME: We should consider alleviating this requirement as
536   it blocks us from doing certain performance optimizations.
537 */
538 
539 typedef struct st_rw_pr_lock_t {
540   /**
541     Lock which protects the structure.
542     Also held for the duration of wr-lock.
543   */
544   pthread_mutex_t lock;
545   /**
546     Condition variable which is used to wake-up
547     writers waiting for readers to go away.
548   */
549   pthread_cond_t no_active_readers;
550   /** Number of active readers. */
551   uint active_readers;
552   /** Number of writers waiting for readers to go away. */
553   uint writers_waiting_readers;
554   /** Indicates whether there is an active writer. */
555   my_bool active_writer;
556 #ifdef SAFE_MUTEX
557   /** Thread holding wr-lock (for debug purposes only). */
558   pthread_t writer_thread;
559 #endif
560 } rw_pr_lock_t;
561 
562 extern int rw_pr_init(rw_pr_lock_t *);
563 extern int rw_pr_rdlock(rw_pr_lock_t *);
564 extern int rw_pr_wrlock(rw_pr_lock_t *);
565 extern int rw_pr_unlock(rw_pr_lock_t *);
566 extern int rw_pr_destroy(rw_pr_lock_t *);
567 #ifdef SAFE_MUTEX
568 #define rw_pr_lock_assert_write_owner(A) \
569   DBUG_ASSERT((A)->active_writer && pthread_equal(pthread_self(), \
570                                                   (A)->writer_thread))
571 #define rw_pr_lock_assert_not_write_owner(A) \
572   DBUG_ASSERT(! (A)->active_writer || ! pthread_equal(pthread_self(), \
573                                                       (A)->writer_thread))
574 #else
575 #define rw_pr_lock_assert_write_owner(A)
576 #define rw_pr_lock_assert_not_write_owner(A)
577 #endif /* SAFE_MUTEX */
578 
579 
580 #ifdef NEED_MY_RW_LOCK
581 
582 #ifdef _WIN32
583 
584 /**
585   Implementation of Windows rwlock.
586 
587   We use native (slim) rwlocks on Win7 and later, and fallback to  portable
588   implementation on earlier Windows.
589 
590   slim rwlock are also available on Vista/WS2008, but we do not use it
591   ("trylock" APIs are missing on Vista)
592 */
593 typedef union
594 {
595   /* Native rwlock (is_srwlock == TRUE) */
596   struct
597   {
598     SRWLOCK srwlock;             /* native reader writer lock */
599     BOOL have_exclusive_srwlock; /* used for unlock */
600   };
601 
602   /*
603     Portable implementation (is_srwlock == FALSE)
604     Fields are identical with Unix my_rw_lock_t fields.
605   */
606   struct
607   {
608     pthread_mutex_t lock;       /* lock for structure		*/
609     pthread_cond_t  readers;    /* waiting readers		*/
610     pthread_cond_t  writers;    /* waiting writers		*/
611     int state;                  /* -1:writer,0:free,>0:readers	*/
612     int waiters;                /* number of waiting writers	*/
613 #ifdef SAFE_MUTEX
614     pthread_t  write_thread;
615 #endif
616   };
617 } my_rw_lock_t;
618 
619 
620 #else /* _WIN32 */
621 
622 /*
623   On systems which don't support native read/write locks we have
624   to use own implementation.
625 */
626 typedef struct st_my_rw_lock_t {
627 	pthread_mutex_t lock;		/* lock for structure		*/
628 	pthread_cond_t	readers;	/* waiting readers		*/
629 	pthread_cond_t	writers;	/* waiting writers		*/
630 	int		state;		/* -1:writer,0:free,>0:readers	*/
631 	int             waiters;        /* number of waiting writers	*/
632 #ifdef SAFE_MUTEX
633         pthread_t       write_thread;
634 #endif
635 } my_rw_lock_t;
636 
637 #endif /*! _WIN32 */
638 
639 extern int my_rw_init(my_rw_lock_t *);
640 extern int my_rw_destroy(my_rw_lock_t *);
641 extern int my_rw_rdlock(my_rw_lock_t *);
642 extern int my_rw_wrlock(my_rw_lock_t *);
643 extern int my_rw_unlock(my_rw_lock_t *);
644 extern int my_rw_tryrdlock(my_rw_lock_t *);
645 extern int my_rw_trywrlock(my_rw_lock_t *);
646 #ifdef SAFE_MUTEX
647 #define my_rw_lock_assert_write_owner(A) \
648   DBUG_ASSERT((A)->state == -1 && pthread_equal(pthread_self(), \
649                                                 (A)->write_thread))
650 #define my_rw_lock_assert_not_write_owner(A) \
651   DBUG_ASSERT((A)->state >= 0 || ! pthread_equal(pthread_self(), \
652                                                  (A)->write_thread))
653 #else
654 #define my_rw_lock_assert_write_owner(A)
655 #define my_rw_lock_assert_not_write_owner(A)
656 #endif
657 #endif /* NEED_MY_RW_LOCK */
658 
659 
660 #define GETHOSTBYADDR_BUFF_SIZE 2048
661 
662 #ifndef HAVE_THR_SETCONCURRENCY
663 #define thr_setconcurrency(A) pthread_dummy(0)
664 #endif
665 #if !defined(HAVE_PTHREAD_ATTR_SETSTACKSIZE) && ! defined(pthread_attr_setstacksize)
666 #define pthread_attr_setstacksize(A,B) pthread_dummy(0)
667 #endif
668 
669 /* Define mutex types, see my_thr_init.c */
670 #define MY_MUTEX_INIT_SLOW   NULL
671 #ifdef PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP
672 extern pthread_mutexattr_t my_fast_mutexattr;
673 #define MY_MUTEX_INIT_FAST &my_fast_mutexattr
674 #else
675 #define MY_MUTEX_INIT_FAST   NULL
676 #endif
677 #ifdef PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP
678 extern pthread_mutexattr_t my_errorcheck_mutexattr;
679 #define MY_MUTEX_INIT_ERRCHK &my_errorcheck_mutexattr
680 #else
681 #define MY_MUTEX_INIT_ERRCHK   NULL
682 #endif
683 
684 #ifndef ESRCH
685 /* Define it to something */
686 #define ESRCH 1
687 #endif
688 
689 typedef uint64 my_thread_id;
690 
691 extern void my_threadattr_global_init(void);
692 extern my_bool my_thread_global_init(void);
693 extern void my_thread_global_reinit(void);
694 extern void my_thread_global_end(void);
695 extern my_bool my_thread_init(void);
696 extern void my_thread_end(void);
697 extern const char *my_thread_name(void);
698 extern my_thread_id my_thread_dbug_id(void);
699 extern int pthread_dummy(int);
700 extern void my_mutex_init(void);
701 extern void my_mutex_end(void);
702 
703 /* All thread specific variables are in the following struct */
704 
705 #define THREAD_NAME_SIZE 10
706 #ifndef DEFAULT_THREAD_STACK
707 /*
708   We need to have at least 256K stack to handle calls to myisamchk_init()
709   with the current number of keys and key parts.
710 */
711 #if defined(__SANITIZE_ADDRESS__) || defined(WITH_UBSAN)
712 #define DEFAULT_THREAD_STACK	(383*1024L) /* 392192 */
713 #else
714 #define DEFAULT_THREAD_STACK	(292*1024L) /* 299008 */
715 #endif
716 #endif
717 
718 #define MY_PTHREAD_LOCK_READ 0
719 #define MY_PTHREAD_LOCK_WRITE 1
720 
721 #include <mysql/psi/mysql_thread.h>
722 
723 #define INSTRUMENT_ME 0
724 
725 struct st_my_thread_var
726 {
727   int thr_errno;
728   mysql_cond_t suspend;
729   mysql_mutex_t mutex;
730   mysql_mutex_t * volatile current_mutex;
731   mysql_cond_t * volatile current_cond;
732   pthread_t pthread_self;
733   my_thread_id id, dbug_id;
734   int volatile abort;
735   my_bool init;
736   struct st_my_thread_var *next,**prev;
737   void *keycache_link;
738   uint  lock_type; /* used by conditional release the queue */
739   void  *stack_ends_here;
740   safe_mutex_t *mutex_in_use;
741 #ifndef DBUG_OFF
742   void *dbug;
743   char name[THREAD_NAME_SIZE+1];
744 #endif
745 };
746 
747 struct st_my_thread_var *_my_thread_var(void);
748 extern void **my_thread_var_dbug(void);
749 extern safe_mutex_t **my_thread_var_mutex_in_use(void);
750 extern uint my_thread_end_wait_time;
751 extern my_bool safe_mutex_deadlock_detector;
752 #define my_thread_var (_my_thread_var())
753 #define my_errno my_thread_var->thr_errno
754 int set_mysys_var(struct st_my_thread_var *mysys_var);
755 /*
756   Keep track of shutdown,signal, and main threads so that my_end() will not
757   report errors with them
758 */
759 
760 /* Which kind of thread library is in use */
761 
762 #define THD_LIB_OTHER 1
763 #define THD_LIB_NPTL  2
764 #define THD_LIB_LT    4
765 
766 extern uint thd_lib_detected;
767 
768 /*
769   thread_safe_xxx functions are for critical statistic or counters.
770   The implementation is guaranteed to be thread safe, on all platforms.
771   Note that the calling code should *not* assume the counter is protected
772   by the mutex given, as the implementation of these helpers may change
773   to use my_atomic operations instead.
774 */
775 
776 #ifndef thread_safe_increment
777 #ifdef _WIN32
778 #define thread_safe_increment(V,L) InterlockedIncrement((long*) &(V))
779 #define thread_safe_decrement(V,L) InterlockedDecrement((long*) &(V))
780 #else
781 #define thread_safe_increment(V,L) \
782         (mysql_mutex_lock((L)), (V)++, mysql_mutex_unlock((L)))
783 #define thread_safe_decrement(V,L) \
784         (mysql_mutex_lock((L)), (V)--, mysql_mutex_unlock((L)))
785 #endif
786 #endif
787 
788 #ifndef thread_safe_add
789 #ifdef _WIN32
790 #define thread_safe_add(V,C,L) InterlockedExchangeAdd((long*) &(V),(C))
791 #define thread_safe_sub(V,C,L) InterlockedExchangeAdd((long*) &(V),-(long) (C))
792 #else
793 #define thread_safe_add(V,C,L) \
794         (mysql_mutex_lock((L)), (V)+=(C), mysql_mutex_unlock((L)))
795 #define thread_safe_sub(V,C,L) \
796         (mysql_mutex_lock((L)), (V)-=(C), mysql_mutex_unlock((L)))
797 #endif
798 #endif
799 
800 
801 /*
802   statistics_xxx functions are for non critical statistic,
803   maintained in global variables.
804   When compiling with SAFE_STATISTICS:
805   - race conditions can not occur.
806   - some locking occurs, which may cause performance degradation.
807 
808   When compiling without SAFE_STATISTICS:
809   - race conditions can occur, making the result slightly inaccurate.
810   - the lock given is not honored.
811 */
812 #ifdef SAFE_STATISTICS
813 #define statistic_increment(V,L) thread_safe_increment((V),(L))
814 #define statistic_decrement(V,L) thread_safe_decrement((V),(L))
815 #define statistic_add(V,C,L)     thread_safe_add((V),(C),(L))
816 #define statistic_sub(V,C,L)     thread_safe_sub((V),(C),(L))
817 #else
818 #define statistic_decrement(V,L) (V)--
819 #define statistic_increment(V,L) (V)++
820 #define statistic_add(V,C,L)     (V)+=(C)
821 #define statistic_sub(V,C,L)     (V)-=(C)
822 #endif /* SAFE_STATISTICS */
823 
824 /*
825   No locking needed, the counter is owned by the thread
826 */
827 #define status_var_increment(V) (V)++
828 #define status_var_decrement(V) (V)--
829 #define status_var_add(V,C)     (V)+=(C)
830 #define status_var_sub(V,C)     (V)-=(C)
831 
832 #ifdef SAFE_MUTEX
833 #define mysql_mutex_record_order(A,B)                   \
834   do {                                                  \
835     mysql_mutex_lock(A); mysql_mutex_lock(B);           \
836     mysql_mutex_unlock(B); mysql_mutex_unlock(A);       \
837   }  while(0)
838 #else
839 #define mysql_mutex_record_order(A,B) do { } while(0)
840 #endif
841 
842 /* At least Windows and NetBSD do not have this definition */
843 #ifndef PTHREAD_STACK_MIN
844 #define PTHREAD_STACK_MIN 65536
845 #endif
846 
847 #ifdef  __cplusplus
848 }
849 #endif
850 #endif /* _my_ptread_h */
851