-
Notifications
You must be signed in to change notification settings - Fork 4k
/
mutex.cpp
1334 lines (1189 loc) · 50.8 KB
/
mutex.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
// bthread - An M:N threading library to make applications more concurrent.
// Date: Sun Aug 3 12:46:15 CST 2014
#include <sys/cdefs.h>
#include <pthread.h>
#include <dlfcn.h> // dlsym
#include <fcntl.h> // O_RDONLY
#include "butil/atomicops.h"
#include "bvar/bvar.h"
#include "bvar/collector.h"
#include "butil/macros.h" // BAIDU_CASSERT
#include "butil/containers/flat_map.h"
#include "butil/iobuf.h"
#include "butil/fd_guard.h"
#include "butil/files/file.h"
#include "butil/files/file_path.h"
#include "butil/file_util.h"
#include "butil/unique_ptr.h"
#include "butil/memory/scope_guard.h"
#include "butil/third_party/murmurhash3/murmurhash3.h"
#include "butil/third_party/symbolize/symbolize.h"
#include "butil/logging.h"
#include "butil/object_pool.h"
#include "butil/debug/stack_trace.h"
#include "butil/thread_local.h"
#include "bthread/butex.h" // butex_*
#include "bthread/mutex.h" // bthread_mutex_t
#include "bthread/sys_futex.h"
#include "bthread/log.h"
#include "bthread/processor.h"
#include "bthread/task_group.h"
__BEGIN_DECLS
extern void* BAIDU_WEAK _dl_sym(void* handle, const char* symbol, void* caller);
__END_DECLS
namespace bthread {
EXTERN_BAIDU_VOLATILE_THREAD_LOCAL(TaskGroup*, tls_task_group);
// Warm up backtrace before main().
const butil::debug::StackTrace ALLOW_UNUSED dummy_bt;
// For controlling contentions collected per second.
bvar::CollectorSpeedLimit g_cp_sl = BVAR_COLLECTOR_SPEED_LIMIT_INITIALIZER;
const size_t MAX_CACHED_CONTENTIONS = 512;
// Skip frames which are always same: the unlock function and submit_contention()
const int SKIPPED_STACK_FRAMES = 2;
struct SampledContention : public bvar::Collected {
// time taken by lock and unlock, normalized according to sampling_range
int64_t duration_ns;
// number of samples, normalized according to to sampling_range
double count;
void* stack[26]; // backtrace.
int nframes; // #elements in stack
// Implement bvar::Collected
void dump_and_destroy(size_t round) override;
void destroy() override;
bvar::CollectorSpeedLimit* speed_limit() override { return &g_cp_sl; }
size_t hash_code() const {
if (nframes == 0) {
return 0;
}
if (_hash_code == 0) {
_hash_code = 1;
uint32_t seed = nframes;
butil::MurmurHash3_x86_32(stack, sizeof(void*) * nframes, seed, &_hash_code);
}
return _hash_code;
}
private:
friend butil::ObjectPool<SampledContention>;
SampledContention()
: duration_ns(0), count(0), stack{NULL}, nframes(0), _hash_code(0) {}
~SampledContention() override = default;
mutable uint32_t _hash_code; // For combining samples with hashmap.
};
BAIDU_CASSERT(sizeof(SampledContention) == 256, be_friendly_to_allocator);
// Functor to compare contentions.
struct ContentionEqual {
bool operator()(const SampledContention* c1,
const SampledContention* c2) const {
return c1->hash_code() == c2->hash_code() &&
c1->nframes == c2->nframes &&
memcmp(c1->stack, c2->stack, sizeof(void*) * c1->nframes) == 0;
}
};
// Functor to hash contentions.
struct ContentionHash {
size_t operator()(const SampledContention* c) const {
return c->hash_code();
}
};
// The global context for contention profiler.
class ContentionProfiler {
public:
typedef butil::FlatMap<SampledContention*, SampledContention*,
ContentionHash, ContentionEqual> ContentionMap;
explicit ContentionProfiler(const char* name);
~ContentionProfiler();
void dump_and_destroy(SampledContention* c);
// Write buffered data into resulting file. If `ending' is true, append
// content of /proc/self/maps and retry writing until buffer is empty.
void flush_to_disk(bool ending);
void init_if_needed();
private:
bool _init; // false before first dump_and_destroy is called
bool _first_write; // true if buffer was not written to file yet.
std::string _filename; // the file storing profiling result.
butil::IOBuf _disk_buf; // temp buf before saving the file.
ContentionMap _dedup_map; // combining same samples to make result smaller.
};
ContentionProfiler::ContentionProfiler(const char* name)
: _init(false)
, _first_write(true)
, _filename(name) {
}
ContentionProfiler::~ContentionProfiler() {
if (!_init) {
// Don't write file if dump_and_destroy was never called. We may create
// such instances in ContentionProfilerStart.
return;
}
flush_to_disk(true);
}
void ContentionProfiler::init_if_needed() {
if (!_init) {
// Already output nanoseconds, always set cycles/second to 1000000000.
_disk_buf.append("--- contention\ncycles/second=1000000000\n");
CHECK_EQ(0, _dedup_map.init(1024, 60));
_init = true;
}
}
void ContentionProfiler::dump_and_destroy(SampledContention* c) {
init_if_needed();
// Categorize the contention.
SampledContention** p_c2 = _dedup_map.seek(c);
if (p_c2) {
// Most contentions are caused by several hotspots, this should be
// the common branch.
SampledContention* c2 = *p_c2;
c2->duration_ns += c->duration_ns;
c2->count += c->count;
c->destroy();
} else {
_dedup_map.insert(c, c);
}
if (_dedup_map.size() > MAX_CACHED_CONTENTIONS) {
flush_to_disk(false);
}
}
void ContentionProfiler::flush_to_disk(bool ending) {
BT_VLOG << "flush_to_disk(ending=" << ending << ")";
// Serialize contentions in _dedup_map into _disk_buf.
if (!_dedup_map.empty()) {
BT_VLOG << "dedup_map=" << _dedup_map.size();
butil::IOBufBuilder os;
for (ContentionMap::const_iterator
it = _dedup_map.begin(); it != _dedup_map.end(); ++it) {
SampledContention* c = it->second;
os << c->duration_ns << ' ' << (size_t)ceil(c->count) << " @";
for (int i = SKIPPED_STACK_FRAMES; i < c->nframes; ++i) {
os << ' ' << (void*)c->stack[i];
}
os << '\n';
c->destroy();
}
_dedup_map.clear();
_disk_buf.append(os.buf());
}
// Append /proc/self/maps to the end of the contention file, required by
// pprof.pl, otherwise the functions in sys libs are not interpreted.
if (ending) {
BT_VLOG << "Append /proc/self/maps";
// Failures are not critical, don't return directly.
butil::IOPortal mem_maps;
const butil::fd_guard fd(open("/proc/self/maps", O_RDONLY));
if (fd >= 0) {
while (true) {
ssize_t nr = mem_maps.append_from_file_descriptor(fd, 8192);
if (nr < 0) {
if (errno == EINTR) {
continue;
}
PLOG(ERROR) << "Fail to read /proc/self/maps";
break;
}
if (nr == 0) {
_disk_buf.append(mem_maps);
break;
}
}
} else {
PLOG(ERROR) << "Fail to open /proc/self/maps";
}
}
// Write _disk_buf into _filename
butil::File::Error error;
butil::FilePath path(_filename);
butil::FilePath dir = path.DirName();
if (!butil::CreateDirectoryAndGetError(dir, &error)) {
LOG(ERROR) << "Fail to create directory=`" << dir.value()
<< "', " << error;
return;
}
// Truncate on first write, append on later writes.
int flag = O_APPEND;
if (_first_write) {
_first_write = false;
flag = O_TRUNC;
}
butil::fd_guard fd(open(_filename.c_str(), O_WRONLY|O_CREAT|flag, 0666));
if (fd < 0) {
PLOG(ERROR) << "Fail to open " << _filename;
return;
}
// Write once normally, write until empty in the end.
do {
ssize_t nw = _disk_buf.cut_into_file_descriptor(fd);
if (nw < 0) {
if (errno == EINTR) {
continue;
}
PLOG(ERROR) << "Fail to write into " << _filename;
return;
}
BT_VLOG << "Write " << nw << " bytes into " << _filename;
} while (!_disk_buf.empty() && ending);
}
// If contention profiler is on, this variable will be set with a valid
// instance. NULL otherwise.
BAIDU_CACHELINE_ALIGNMENT ContentionProfiler* g_cp = NULL;
// Need this version to solve an issue that non-empty entries left by
// previous contention profilers should be detected and overwritten.
static uint64_t g_cp_version = 0;
// Protecting accesses to g_cp.
static pthread_mutex_t g_cp_mutex = PTHREAD_MUTEX_INITIALIZER;
// The map storing information for profiling pthread_mutex. Different from
// bthread_mutex, we can't save stuff into pthread_mutex, we neither can
// save the info in TLS reliably, since a mutex can be unlocked in a different
// thread from the one locked (although rare, undefined behavior)
// This map must be very fast, since it's accessed inside the lock.
// Layout of the map:
// * Align each entry by cacheline so that different threads do not collide.
// * Hash the mutex into the map by its address. If the entry is occupied,
// cancel sampling.
// The canceling rate should be small provided that programs are unlikely to
// lock a lot of mutexes simultaneously.
const size_t MUTEX_MAP_SIZE = 1024;
BAIDU_CASSERT((MUTEX_MAP_SIZE & (MUTEX_MAP_SIZE - 1)) == 0, must_be_power_of_2);
struct BAIDU_CACHELINE_ALIGNMENT MutexMapEntry {
butil::static_atomic<uint64_t> versioned_mutex;
bthread_contention_site_t csite;
};
static MutexMapEntry g_mutex_map[MUTEX_MAP_SIZE] = {}; // zero-initialize
void SampledContention::dump_and_destroy(size_t /*round*/) {
if (g_cp) {
// Must be protected with mutex to avoid race with deletion of ctx.
// dump_and_destroy is called from dumping thread only so this mutex
// is not contended at most of time.
BAIDU_SCOPED_LOCK(g_cp_mutex);
if (g_cp) {
g_cp->dump_and_destroy(this);
return;
}
}
destroy();
}
void SampledContention::destroy() {
_hash_code = 0;
butil::return_object(this);
}
// Remember the conflict hashes for troubleshooting, should be 0 at most of time.
static butil::static_atomic<int64_t> g_nconflicthash = BUTIL_STATIC_ATOMIC_INIT(0);
static int64_t get_nconflicthash(void*) {
return g_nconflicthash.load(butil::memory_order_relaxed);
}
// Start profiling contention.
bool ContentionProfilerStart(const char* filename) {
if (filename == NULL) {
LOG(ERROR) << "Parameter [filename] is NULL";
return false;
}
// g_cp is also the flag marking start/stop.
if (g_cp) {
return false;
}
// Create related global bvar lazily.
static bvar::PassiveStatus<int64_t> g_nconflicthash_var
("contention_profiler_conflict_hash", get_nconflicthash, NULL);
static bvar::DisplaySamplingRatio g_sampling_ratio_var(
"contention_profiler_sampling_ratio", &g_cp_sl);
// Optimistic locking. A not-used ContentionProfiler does not write file.
std::unique_ptr<ContentionProfiler> ctx(new ContentionProfiler(filename));
{
BAIDU_SCOPED_LOCK(g_cp_mutex);
if (g_cp) {
return false;
}
g_cp = ctx.release();
++g_cp_version; // invalidate non-empty entries that may exist.
}
return true;
}
// Stop contention profiler.
void ContentionProfilerStop() {
ContentionProfiler* ctx = NULL;
if (g_cp) {
std::unique_lock<pthread_mutex_t> mu(g_cp_mutex);
if (g_cp) {
ctx = g_cp;
g_cp = NULL;
mu.unlock();
// make sure it's initialiazed in case no sample was gathered,
// otherwise nothing will be written and succeeding pprof will fail.
ctx->init_if_needed();
// Deletion is safe because usages of g_cp are inside g_cp_mutex.
delete ctx;
return;
}
}
LOG(ERROR) << "Contention profiler is not started!";
}
bool is_contention_site_valid(const bthread_contention_site_t& cs) {
return bvar::is_sampling_range_valid(cs.sampling_range);
}
void make_contention_site_invalid(bthread_contention_site_t* cs) {
cs->sampling_range = 0;
}
#ifndef NO_PTHREAD_MUTEX_HOOK
// Replace pthread_mutex_lock and pthread_mutex_unlock:
// First call to sys_pthread_mutex_lock sets sys_pthread_mutex_lock to the
// real function so that next calls go to the real function directly. This
// technique avoids calling pthread_once each time.
typedef int (*MutexInitOp)(pthread_mutex_t*, const pthread_mutexattr_t*);
typedef int (*MutexOp)(pthread_mutex_t*);
int first_sys_pthread_mutex_init(pthread_mutex_t* mutex, const pthread_mutexattr_t* mutexattr);
int first_sys_pthread_mutex_destroy(pthread_mutex_t* mutex);
int first_sys_pthread_mutex_lock(pthread_mutex_t* mutex);
int first_sys_pthread_mutex_trylock(pthread_mutex_t* mutex);
int first_sys_pthread_mutex_unlock(pthread_mutex_t* mutex);
static MutexInitOp sys_pthread_mutex_init = first_sys_pthread_mutex_init;
static MutexOp sys_pthread_mutex_destroy = first_sys_pthread_mutex_destroy;
static MutexOp sys_pthread_mutex_lock = first_sys_pthread_mutex_lock;
static MutexOp sys_pthread_mutex_trylock = first_sys_pthread_mutex_trylock;
static MutexOp sys_pthread_mutex_unlock = first_sys_pthread_mutex_unlock;
#if HAS_PTHREAD_MUTEX_TIMEDLOCK
typedef int (*TimedMutexOp)(pthread_mutex_t*, const struct timespec*);
int first_sys_pthread_mutex_timedlock(pthread_mutex_t* mutex,
const struct timespec* __abstime);
static TimedMutexOp sys_pthread_mutex_timedlock = first_sys_pthread_mutex_timedlock;
#endif // HAS_PTHREAD_MUTEX_TIMEDLOCK
static pthread_once_t init_sys_mutex_lock_once = PTHREAD_ONCE_INIT;
// dlsym may call malloc to allocate space for dlerror and causes contention
// profiler to deadlock at boostraping when the program is linked with
// libunwind. The deadlock bt:
// #0 0x00007effddc99b80 in __nanosleep_nocancel () at ../sysdeps/unix/syscall-template.S:81
// #1 0x00000000004b4df7 in butil::internal::SpinLockDelay(int volatile*, int, int) ()
// #2 0x00000000004b4d57 in SpinLock::SlowLock() ()
// #3 0x00000000004b4a63 in tcmalloc::ThreadCache::InitModule() ()
// #4 0x00000000004aa2b5 in tcmalloc::ThreadCache::GetCache() ()
// #5 0x000000000040c6c5 in (anonymous namespace)::do_malloc_no_errno(unsigned long) [clone.part.16] ()
// #6 0x00000000006fc125 in tc_calloc ()
// #7 0x00007effdd245690 in _dlerror_run (operate=operate@entry=0x7effdd245130 <dlsym_doit>, args=args@entry=0x7fff483dedf0) at dlerror.c:141
// #8 0x00007effdd245198 in __dlsym (handle=<optimized out>, name=<optimized out>) at dlsym.c:70
// #9 0x0000000000666517 in bthread::init_sys_mutex_lock () at bthread/mutex.cpp:358
// #10 0x00007effddc97a90 in pthread_once () at ../nptl/sysdeps/unix/sysv/linux/x86_64/pthread_once.S:103
// #11 0x000000000066649f in bthread::first_sys_pthread_mutex_lock (mutex=0xbaf880 <_ULx86_64_lock>) at bthread/mutex.cpp:366
// #12 0x00000000006678bc in pthread_mutex_lock_impl (mutex=0xbaf880 <_ULx86_64_lock>) at bthread/mutex.cpp:489
// #13 pthread_mutex_lock (__mutex=__mutex@entry=0xbaf880 <_ULx86_64_lock>) at bthread/mutex.cpp:751
// #14 0x00000000004c6ea1 in _ULx86_64_init () at x86_64/Gglobal.c:83
// #15 0x00000000004c44fb in _ULx86_64_init_local (cursor=0x7fff483df340, uc=0x7fff483def90) at x86_64/Ginit_local.c:47
// #16 0x00000000004b5012 in GetStackTrace(void**, int, int) ()
// #17 0x00000000004b2095 in tcmalloc::PageHeap::GrowHeap(unsigned long) ()
// #18 0x00000000004b23a3 in tcmalloc::PageHeap::New(unsigned long) ()
// #19 0x00000000004ad457 in tcmalloc::CentralFreeList::Populate() ()
// #20 0x00000000004ad628 in tcmalloc::CentralFreeList::FetchFromSpansSafe() ()
// #21 0x00000000004ad6a3 in tcmalloc::CentralFreeList::RemoveRange(void**, void**, int) ()
// #22 0x00000000004b3ed3 in tcmalloc::ThreadCache::FetchFromCentralCache(unsigned long, unsigned long) ()
// #23 0x00000000006fbb9a in tc_malloc ()
// Call _dl_sym which is a private function in glibc to workaround the malloc
// causing deadlock temporarily. This fix is hardly portable.
static void init_sys_mutex_lock() {
// When bRPC library is linked as a shared library, need to make sure bRPC
// shared library is loaded before the pthread shared library. Otherwise,
// it may cause runtime error: undefined symbol: pthread_mutex_xxx.
// Alternatively, static linking can also avoid this problem.
#if defined(OS_LINUX)
// TODO: may need dlvsym when GLIBC has multiple versions of a same symbol.
// http://blog.fesnel.com/blog/2009/08/25/preloading-with-multiple-symbol-versions
if (_dl_sym) {
sys_pthread_mutex_init = (MutexInitOp)_dl_sym(
RTLD_NEXT, "pthread_mutex_init", (void*)init_sys_mutex_lock);
sys_pthread_mutex_destroy = (MutexOp)_dl_sym(
RTLD_NEXT, "pthread_mutex_destroy", (void*)init_sys_mutex_lock);
sys_pthread_mutex_lock = (MutexOp)_dl_sym(
RTLD_NEXT, "pthread_mutex_lock", (void*)init_sys_mutex_lock);
sys_pthread_mutex_unlock = (MutexOp)_dl_sym(
RTLD_NEXT, "pthread_mutex_unlock", (void*)init_sys_mutex_lock);
sys_pthread_mutex_trylock = (MutexOp)_dl_sym(
RTLD_NEXT, "pthread_mutex_trylock", (void*)init_sys_mutex_lock);
#if HAS_PTHREAD_MUTEX_TIMEDLOCK
sys_pthread_mutex_timedlock = (TimedMutexOp)_dl_sym(
RTLD_NEXT, "pthread_mutex_timedlock", (void*)init_sys_mutex_lock);
#endif // HAS_PTHREAD_MUTEX_TIMEDLOCK
} else {
// _dl_sym may be undefined reference in some system, fallback to dlsym
sys_pthread_mutex_init = (MutexInitOp)dlsym(RTLD_NEXT, "pthread_mutex_init");
sys_pthread_mutex_destroy = (MutexOp)dlsym(RTLD_NEXT, "pthread_mutex_destroy");
sys_pthread_mutex_lock = (MutexOp)dlsym(RTLD_NEXT, "pthread_mutex_lock");
sys_pthread_mutex_unlock = (MutexOp)dlsym(RTLD_NEXT, "pthread_mutex_unlock");
sys_pthread_mutex_trylock = (MutexOp)dlsym(RTLD_NEXT, "pthread_mutex_trylock");
#if HAS_PTHREAD_MUTEX_TIMEDLOCK
sys_pthread_mutex_timedlock = (TimedMutexOp)dlsym(RTLD_NEXT, "pthread_mutex_timedlock");
#endif // HAS_PTHREAD_MUTEX_TIMEDLOCK
}
#elif defined(OS_MACOSX)
// TODO: look workaround for dlsym on mac
sys_pthread_mutex_init = (MutexInitOp)dlsym(RTLD_NEXT, "pthread_mutex_init");
sys_pthread_mutex_destroy = (MutexOp)dlsym(RTLD_NEXT, "pthread_mutex_destroy");
sys_pthread_mutex_lock = (MutexOp)dlsym(RTLD_NEXT, "pthread_mutex_lock");
sys_pthread_mutex_trylock = (MutexOp)dlsym(RTLD_NEXT, "pthread_mutex_trylock");
sys_pthread_mutex_unlock = (MutexOp)dlsym(RTLD_NEXT, "pthread_mutex_unlock");
#endif
}
// Make sure pthread functions are ready before main().
const int ALLOW_UNUSED dummy = pthread_once(&init_sys_mutex_lock_once, init_sys_mutex_lock);
int first_sys_pthread_mutex_init(pthread_mutex_t* mutex, const pthread_mutexattr_t* mutexattr) {
pthread_once(&init_sys_mutex_lock_once, init_sys_mutex_lock);
return sys_pthread_mutex_init(mutex, mutexattr);
}
int first_sys_pthread_mutex_destroy(pthread_mutex_t* mutex) {
pthread_once(&init_sys_mutex_lock_once, init_sys_mutex_lock);
return sys_pthread_mutex_destroy(mutex);
}
int first_sys_pthread_mutex_lock(pthread_mutex_t* mutex) {
pthread_once(&init_sys_mutex_lock_once, init_sys_mutex_lock);
return sys_pthread_mutex_lock(mutex);
}
int first_sys_pthread_mutex_trylock(pthread_mutex_t* mutex) {
pthread_once(&init_sys_mutex_lock_once, init_sys_mutex_lock);
return sys_pthread_mutex_trylock(mutex);
}
#if HAS_PTHREAD_MUTEX_TIMEDLOCK
int first_sys_pthread_mutex_timedlock(pthread_mutex_t* mutex,
const struct timespec* abstime) {
pthread_once(&init_sys_mutex_lock_once, init_sys_mutex_lock);
return sys_pthread_mutex_timedlock(mutex, abstime);
}
#endif // HAS_PTHREAD_MUTEX_TIMEDLOCK
int first_sys_pthread_mutex_unlock(pthread_mutex_t* mutex) {
pthread_once(&init_sys_mutex_lock_once, init_sys_mutex_lock);
return sys_pthread_mutex_unlock(mutex);
}
#endif
template <typename Mutex>
inline uint64_t hash_mutex_ptr(const Mutex* m) {
return butil::fmix64((uint64_t)m);
}
// Mark being inside locking so that pthread_mutex calls inside collecting
// code are never sampled, otherwise deadlock may occur.
static __thread bool tls_inside_lock = false;
// Warn up some singleton objects used in contention profiler
// to avoid deadlock in malloc call stack.
static __thread bool tls_warn_up = false;
#if BRPC_DEBUG_BTHREAD_SCHE_SAFETY
// ++tls_pthread_lock_count when pthread locking,
// --tls_pthread_lock_count when pthread unlocking.
// Only when it is equal to 0, it is safe for the bthread to be scheduled.
// Note: If a mutex is locked/unlocked in different thread,
// `tls_pthread_lock_count' is inaccurate, so this feature cannot be used.
static __thread int tls_pthread_lock_count = 0;
#define ADD_TLS_PTHREAD_LOCK_COUNT ++tls_pthread_lock_count
#define SUB_TLS_PTHREAD_LOCK_COUNT --tls_pthread_lock_count
void CheckBthreadScheSafety() {
if (BAIDU_LIKELY(0 == tls_pthread_lock_count)) {
return;
}
static butil::atomic<bool> b_sched_in_p_lock_logged{false};
if (BAIDU_UNLIKELY(!b_sched_in_p_lock_logged.exchange(
true, butil::memory_order_relaxed))) {
butil::debug::StackTrace trace(true);
// It can only be checked once because the counter is messed up.
LOG(ERROR) << "bthread is suspended while holding "
<< tls_pthread_lock_count << " pthread locks."
<< std::endl << trace.ToString();
}
}
#else
#define ADD_TLS_PTHREAD_LOCK_COUNT ((void)0)
#define SUB_TLS_PTHREAD_LOCK_COUNT ((void)0)
void CheckBthreadScheSafety() {}
#endif // BRPC_DEBUG_BTHREAD_SCHE_SAFETY
// Speed up with TLS:
// Most pthread_mutex are locked and unlocked in the same thread. Putting
// contention information in TLS avoids collisions that may occur in
// g_mutex_map. However when user unlocks in another thread, the info cached
// in the locking thread is not removed, making the space bloated. We use a
// simple strategy to solve the issue: If a thread has enough thread-local
// space to store the info, save it, otherwise save it in g_mutex_map. For
// a program that locks and unlocks in the same thread and does not lock a
// lot of mutexes simulateneously, this strategy always uses the TLS.
#ifndef DONT_SPEEDUP_PTHREAD_CONTENTION_PROFILER_WITH_TLS
const int TLS_MAX_COUNT = 3;
struct MutexAndContentionSite {
void* mutex;
bthread_contention_site_t csite;
};
struct TLSPthreadContentionSites {
int count;
uint64_t cp_version;
MutexAndContentionSite list[TLS_MAX_COUNT];
};
static __thread TLSPthreadContentionSites tls_csites = {0,0,{}};
#endif // DONT_SPEEDUP_PTHREAD_CONTENTION_PROFILER_WITH_TLS
// Guaranteed in linux/win.
const int PTR_BITS = 48;
template <typename Mutex>
inline bthread_contention_site_t*
add_pthread_contention_site(const Mutex* mutex) {
MutexMapEntry& entry = g_mutex_map[hash_mutex_ptr(mutex) & (MUTEX_MAP_SIZE - 1)];
butil::static_atomic<uint64_t>& m = entry.versioned_mutex;
uint64_t expected = m.load(butil::memory_order_relaxed);
// If the entry is not used or used by previous profiler, try to CAS it.
if (expected == 0 ||
(expected >> PTR_BITS) != (g_cp_version & ((1 << (64 - PTR_BITS)) - 1))) {
uint64_t desired = (g_cp_version << PTR_BITS) | (uint64_t)mutex;
if (m.compare_exchange_strong(
expected, desired, butil::memory_order_acquire)) {
return &entry.csite;
}
}
g_nconflicthash.fetch_add(1, butil::memory_order_relaxed);
return NULL;
}
template <typename Mutex>
inline bool remove_pthread_contention_site(const Mutex* mutex,
bthread_contention_site_t* saved_csite) {
MutexMapEntry& entry = g_mutex_map[hash_mutex_ptr(mutex) & (MUTEX_MAP_SIZE - 1)];
butil::static_atomic<uint64_t>& m = entry.versioned_mutex;
if ((m.load(butil::memory_order_relaxed) & ((((uint64_t)1) << PTR_BITS) - 1))
!= (uint64_t)mutex) {
// This branch should be the most common case since most locks are
// neither contended nor sampled. We have one memory indirection and
// several bitwise operations here, the cost should be ~ 5-50ns
return false;
}
// Although this branch is inside a contended lock, we should also make it
// as simple as possible because altering the critical section too much
// may make unpredictable impact to thread interleaving status, which
// makes profiling result less accurate.
*saved_csite = entry.csite;
make_contention_site_invalid(&entry.csite);
m.store(0, butil::memory_order_release);
return true;
}
// Submit the contention along with the callsite('s stacktrace)
void submit_contention(const bthread_contention_site_t& csite, int64_t now_ns) {
tls_inside_lock = true;
BRPC_SCOPE_EXIT {
tls_inside_lock = false;
};
butil::debug::StackTrace stack(true); // May lock.
if (0 == stack.FrameCount()) {
return;
}
// There are two situations where we need to check whether in the
// malloc call stack:
// 1. Warn up some singleton objects used in `submit_contention'
// to avoid deadlock in malloc call stack.
// 2. LocalPool is empty, GlobalPool may allocate memory by malloc.
if (!tls_warn_up || butil::local_pool_free_empty<SampledContention>()) {
// In malloc call stack, can not submit contention.
if (stack.FindSymbol((void*)malloc)) {
return;
}
}
auto sc = butil::get_object<SampledContention>();
// Normalize duration_us and count so that they're addable in later
// processings. Notice that sampling_range is adjusted periodically by
// collecting thread.
sc->duration_ns = csite.duration_ns * bvar::COLLECTOR_SAMPLING_BASE
/ csite.sampling_range;
sc->count = bvar::COLLECTOR_SAMPLING_BASE / (double)csite.sampling_range;
sc->nframes = stack.CopyAddressTo(sc->stack, arraysize(sc->stack));
sc->submit(now_ns / 1000); // may lock
// Once submit a contention, complete warn up.
tls_warn_up = true;
}
#if BRPC_DEBUG_LOCK
#define MUTEX_RESET_OWNER_COMMON(owner) \
((butil::atomic<bool>*)&(owner).hold) \
->store(false, butil::memory_order_relaxed)
#define PTHREAD_MUTEX_SET_OWNER(owner) \
owner.id = pthread_numeric_id(); \
((butil::atomic<bool>*)&(owner).hold) \
->store(true, butil::memory_order_release)
// Check if the mutex has been locked by the current thread.
// Double lock on the same thread will cause deadlock.
#define PTHREAD_MUTEX_CHECK_OWNER(owner) \
bool hold = ((butil::atomic<bool>*)&(owner).hold) \
->load(butil::memory_order_acquire); \
if (hold && (owner).id == pthread_numeric_id()) { \
butil::debug::StackTrace trace(true); \
LOG(ERROR) << "Detected deadlock caused by double lock of FastPthreadMutex:" \
<< std::endl << trace.ToString(); \
}
#else
#define MUTEX_RESET_OWNER_COMMON(owner) ((void)0)
#define PTHREAD_MUTEX_SET_OWNER(owner) ((void)0)
#define PTHREAD_MUTEX_CHECK_OWNER(owner) ((void)0)
#endif // BRPC_DEBUG_LOCK
namespace internal {
#ifndef NO_PTHREAD_MUTEX_HOOK
#if BRPC_DEBUG_LOCK
struct BAIDU_CACHELINE_ALIGNMENT MutexOwnerMapEntry {
butil::static_atomic<bool> valid;
pthread_mutex_t* mutex;
mutex_owner_t owner;
};
// The map storing owner information for pthread_mutex. Different from
// bthread_mutex, we can't save stuff into pthread_mutex, we neither can
// save the info in TLS reliably, since a mutex can be unlocked in a different
// thread from the one locked (although rare).
static MutexOwnerMapEntry g_mutex_owner_map[MUTEX_MAP_SIZE] = {}; // zero-initialize
static void InitMutexOwnerMapEntry(pthread_mutex_t* mutex,
const pthread_mutexattr_t* mutexattr) {
int type = PTHREAD_MUTEX_DEFAULT;
if (NULL != mutexattr) {
pthread_mutexattr_gettype(mutexattr, &type);
}
// Only normal mutexes are tracked.
if (type != PTHREAD_MUTEX_NORMAL) {
return;
}
// Fast path: If the hash entry is not used, use it.
MutexOwnerMapEntry& hash_entry =
g_mutex_owner_map[hash_mutex_ptr(mutex) & (MUTEX_MAP_SIZE - 1)];
if (!hash_entry.valid.exchange(true, butil::memory_order_relaxed)) {
MUTEX_RESET_OWNER_COMMON(hash_entry.owner);
return;
}
// Slow path: Find an unused entry.
for (auto& entry : g_mutex_owner_map) {
if (!entry.valid.exchange(true, butil::memory_order_relaxed)) {
MUTEX_RESET_OWNER_COMMON(entry.owner);
return;
}
}
}
static BUTIL_FORCE_INLINE
MutexOwnerMapEntry* FindMutexOwnerMapEntry(pthread_mutex_t* mutex) {
if (NULL == mutex) {
return NULL;
}
// Fast path.
MutexOwnerMapEntry* hash_entry =
&g_mutex_owner_map[hash_mutex_ptr(mutex) & (MUTEX_MAP_SIZE - 1)];
if (hash_entry->valid.load(butil::memory_order_relaxed) && hash_entry->mutex == mutex) {
return hash_entry;
}
// Slow path.
for (auto& entry : g_mutex_owner_map) {
if (entry.valid.load(butil::memory_order_relaxed) && entry.mutex == mutex) {
return &entry;
}
}
return NULL;
}
static void DestroyMutexOwnerMapEntry(pthread_mutex_t* mutex) {
MutexOwnerMapEntry* entry = FindMutexOwnerMapEntry(mutex);
if (NULL != entry) {
entry->valid.store(false, butil::memory_order_relaxed);
}
}
#define INIT_MUTEX_OWNER_MAP_ENTRY(mutex, mutexattr) \
::bthread::internal::InitMutexOwnerMapEntry(mutex, mutexattr)
#define DESTROY_MUTEX_OWNER_MAP_ENTRY(mutex) \
::bthread::internal::DestroyMutexOwnerMapEntry(mutex)
#define FIND_SYS_PTHREAD_MUTEX_OWNER_MAP_ENTRY(mutex) \
MutexOwnerMapEntry* entry = ::bthread::internal::FindMutexOwnerMapEntry(mutex)
#define SYS_PTHREAD_MUTEX_CHECK_OWNER \
if (NULL != entry) { \
PTHREAD_MUTEX_CHECK_OWNER(entry->owner); \
}
#define SYS_PTHREAD_MUTEX_SET_OWNER \
if (NULL != entry) { \
PTHREAD_MUTEX_SET_OWNER(entry->owner); \
}
#define SYS_PTHREAD_MUTEX_RESET_OWNER(mutex) \
FIND_SYS_PTHREAD_MUTEX_OWNER_MAP_ENTRY(mutex); \
if (NULL != entry) { \
MUTEX_RESET_OWNER_COMMON(entry->owner); \
}
#else
#define INIT_MUTEX_OWNER_MAP_ENTRY(mutex, mutexattr) ((void)0)
#define DESTROY_MUTEX_OWNER_MAP_ENTRY(mutex) ((void)0)
#define FIND_SYS_PTHREAD_MUTEX_OWNER_MAP_ENTRY(mutex) ((void)0)
#define SYS_PTHREAD_MUTEX_CHECK_OWNER ((void)0)
#define SYS_PTHREAD_MUTEX_SET_OWNER ((void)0)
#define SYS_PTHREAD_MUTEX_RESET_OWNER(mutex) ((void)0)
#endif // BRPC_DEBUG_LOCK
#if HAS_PTHREAD_MUTEX_TIMEDLOCK
BUTIL_FORCE_INLINE int pthread_mutex_lock_internal(pthread_mutex_t* mutex,
const struct timespec* abstime) {
int rc = 0;
if (NULL == abstime) {
FIND_SYS_PTHREAD_MUTEX_OWNER_MAP_ENTRY(mutex);
SYS_PTHREAD_MUTEX_CHECK_OWNER;
rc = sys_pthread_mutex_lock(mutex);
if (0 == rc) {
SYS_PTHREAD_MUTEX_SET_OWNER;
}
} else {
rc = sys_pthread_mutex_timedlock(mutex, abstime);
if (0 == rc) {
FIND_SYS_PTHREAD_MUTEX_OWNER_MAP_ENTRY(mutex);
SYS_PTHREAD_MUTEX_SET_OWNER;
}
}
if (0 == rc) {
ADD_TLS_PTHREAD_LOCK_COUNT;
}
return rc;
}
#else
BUTIL_FORCE_INLINE int pthread_mutex_lock_internal(pthread_mutex_t* mutex,
const struct timespec*/* Not supported */) {
FIND_SYS_PTHREAD_MUTEX_OWNER_MAP_ENTRY(mutex);
SYS_PTHREAD_MUTEX_CHECK_OWNER;
int rc = sys_pthread_mutex_lock(mutex);
if (0 == rc) {
SYS_PTHREAD_MUTEX_SET_OWNER;
ADD_TLS_PTHREAD_LOCK_COUNT;
}
return rc;
}
#endif // HAS_PTHREAD_MUTEX_TIMEDLOCK
BUTIL_FORCE_INLINE int pthread_mutex_trylock_internal(pthread_mutex_t* mutex) {
int rc = sys_pthread_mutex_trylock(mutex);
if (0 == rc) {
FIND_SYS_PTHREAD_MUTEX_OWNER_MAP_ENTRY(mutex);
SYS_PTHREAD_MUTEX_SET_OWNER;
ADD_TLS_PTHREAD_LOCK_COUNT;
}
return rc;
}
BUTIL_FORCE_INLINE int pthread_mutex_unlock_internal(pthread_mutex_t* mutex) {
SYS_PTHREAD_MUTEX_RESET_OWNER(mutex);
SUB_TLS_PTHREAD_LOCK_COUNT;
return sys_pthread_mutex_unlock(mutex);
}
#endif // NO_PTHREAD_MUTEX_HOOK
BUTIL_FORCE_INLINE int pthread_mutex_lock_internal(FastPthreadMutex* mutex,
const struct timespec* abstime) {
if (NULL == abstime) {
mutex->lock();
return 0;
} else {
return mutex->timed_lock(abstime) ? 0 : errno;
}
}
BUTIL_FORCE_INLINE int pthread_mutex_trylock_internal(FastPthreadMutex* mutex) {
return mutex->try_lock() ? 0 : EBUSY;
}
BUTIL_FORCE_INLINE int pthread_mutex_unlock_internal(FastPthreadMutex* mutex) {
mutex->unlock();
return 0;
}
template <typename Mutex>
BUTIL_FORCE_INLINE int pthread_mutex_lock_impl(Mutex* mutex, const struct timespec* abstime) {
// Don't change behavior of lock when profiler is off.
if (!g_cp ||
// collecting code including backtrace() and submit() may call
// pthread_mutex_lock and cause deadlock. Don't sample.
tls_inside_lock) {
return pthread_mutex_lock_internal(mutex, abstime);
}
// Don't slow down non-contended locks.
int rc = pthread_mutex_trylock_internal(mutex);
if (rc != EBUSY) {
return rc;
}
// Ask bvar::Collector if this (contended) locking should be sampled
const size_t sampling_range = bvar::is_collectable(&g_cp_sl);
bthread_contention_site_t* csite = NULL;
#ifndef DONT_SPEEDUP_PTHREAD_CONTENTION_PROFILER_WITH_TLS
TLSPthreadContentionSites& fast_alt = tls_csites;
if (fast_alt.cp_version != g_cp_version) {
fast_alt.cp_version = g_cp_version;
fast_alt.count = 0;
}
if (fast_alt.count < TLS_MAX_COUNT) {
MutexAndContentionSite& entry = fast_alt.list[fast_alt.count++];
entry.mutex = mutex;
csite = &entry.csite;
if (!bvar::is_sampling_range_valid(sampling_range)) {
make_contention_site_invalid(&entry.csite);
return pthread_mutex_lock_internal(mutex, abstime);
}
}
#endif
if (!bvar::is_sampling_range_valid(sampling_range)) { // don't sample
return pthread_mutex_lock_internal(mutex, abstime);
}
// Lock and monitor the waiting time.
const int64_t start_ns = butil::cpuwide_time_ns();
rc = pthread_mutex_lock_internal(mutex, abstime);
if (!rc) { // Inside lock
if (!csite) {
csite = add_pthread_contention_site(mutex);
if (csite == NULL) {
return rc;
}
}
csite->duration_ns = butil::cpuwide_time_ns() - start_ns;
csite->sampling_range = sampling_range;
} // else rare
return rc;
}
template <typename Mutex>
BUTIL_FORCE_INLINE int pthread_mutex_trylock_impl(Mutex* mutex) {
return pthread_mutex_trylock_internal(mutex);
}
template <typename Mutex>
BUTIL_FORCE_INLINE int pthread_mutex_unlock_impl(Mutex* mutex) {
// Don't change behavior of unlock when profiler is off.
if (!g_cp || tls_inside_lock) {
// This branch brings an issue that an entry created by
// add_pthread_contention_site may not be cleared. Thus we add a
// 16-bit rolling version in the entry to find out such entry.
return pthread_mutex_unlock_internal(mutex);
}
int64_t unlock_start_ns = 0;
bool miss_in_tls = true;
bthread_contention_site_t saved_csite = {0,0};
#ifndef DONT_SPEEDUP_PTHREAD_CONTENTION_PROFILER_WITH_TLS
TLSPthreadContentionSites& fast_alt = tls_csites;
for (int i = fast_alt.count - 1; i >= 0; --i) {
if (fast_alt.list[i].mutex == mutex) {
if (is_contention_site_valid(fast_alt.list[i].csite)) {
saved_csite = fast_alt.list[i].csite;
unlock_start_ns = butil::cpuwide_time_ns();
}
fast_alt.list[i] = fast_alt.list[--fast_alt.count];
miss_in_tls = false;
break;
}
}
#endif
// Check the map to see if the lock is sampled. Notice that we're still
// inside critical section.
if (miss_in_tls) {
if (remove_pthread_contention_site(mutex, &saved_csite)) {
unlock_start_ns = butil::cpuwide_time_ns();
}
}
const int rc = pthread_mutex_unlock_internal(mutex);
// [Outside lock]
if (unlock_start_ns) {
const int64_t unlock_end_ns = butil::cpuwide_time_ns();
saved_csite.duration_ns += unlock_end_ns - unlock_start_ns;
submit_contention(saved_csite, unlock_end_ns);
}
return rc;
}
}
#ifndef NO_PTHREAD_MUTEX_HOOK
BUTIL_FORCE_INLINE int pthread_mutex_lock_impl(pthread_mutex_t* mutex) {
return internal::pthread_mutex_lock_impl(mutex, NULL);
}
BUTIL_FORCE_INLINE int pthread_mutex_trylock_impl(pthread_mutex_t* mutex) {
return internal::pthread_mutex_trylock_impl(mutex);
}
#if HAS_PTHREAD_MUTEX_TIMEDLOCK
BUTIL_FORCE_INLINE int pthread_mutex_timedlock_impl(pthread_mutex_t* mutex,
const struct timespec* abstime) {
return internal::pthread_mutex_lock_impl(mutex, abstime);
}
#endif // HAS_PTHREAD_MUTEX_TIMEDLOCK
BUTIL_FORCE_INLINE int pthread_mutex_unlock_impl(pthread_mutex_t* mutex) {
return internal::pthread_mutex_unlock_impl(mutex);
}
#endif
// Implement bthread_mutex_t related functions
struct MutexInternal {
butil::static_atomic<unsigned char> locked;
butil::static_atomic<unsigned char> contended;