-
Notifications
You must be signed in to change notification settings - Fork 6
/
lwlocks.py
executable file
·348 lines (290 loc) · 8.7 KB
/
lwlocks.py
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
#!/usr/bin/env python
#
# lwlocks Track LWLocks in PostgreSQL and print wait/hold time
# as a histogram. For Linux, uses BCC, eBPF.
#
# usage: lwlocks $PG_BIN/postgres [-p PID] [-d]
from __future__ import print_function
from time import sleep
import argparse
import ctypes as ct
import signal
from bcc import BPF
text = """
#include <linux/ptrace.h>
typedef struct pg_atomic_uint32
{
volatile unsigned int value;
} pg_atomic_uint32;
typedef struct LWLock
{
unsigned short tranche; /* tranche ID */
pg_atomic_uint32 state; /* state of exclusive/nonexclusive lockers */
} LWLock;
struct lwlock {
u32 pid;
u32 mode;
u32 lock;
bool missing;
bool overwritten;
bool deleted;
bool wait;
bool hold;
u64 acquired;
u64 released;
};
typedef enum LWLockMode
{
LW_EXCLUSIVE,
LW_SHARED,
LW_WAIT_UNTIL_FREE /* A special mode used in PGPROC->lwlockMode,
* when waiting for lock to become free. Not
* to be used as LWLockAcquire argument */
} LWLockMode;
#define HASH_SIZE 2^14
BPF_PERF_OUTPUT(events);
BPF_HASH(lock_hold, u32, struct lwlock, HASH_SIZE);
BPF_HASH(lock_wait, u32, struct lwlock, HASH_SIZE);
// Histogram of lock hold times
BPF_HISTOGRAM(lock_hold_shared_hist, u64);
BPF_HISTOGRAM(lock_hold_exclusive_hist, u64);
// Histogram of lock wait times
BPF_HISTOGRAM(lock_wait_shared_hist, u64);
BPF_HISTOGRAM(lock_wait_exclusive_hist, u64);
void probe_lwlock_acquire_start(struct pt_regs *ctx,
struct LWLock *lock, int mode)
{
u64 now = bpf_ktime_get_ns();
u32 pid = bpf_get_current_pid_tgid();
struct lwlock data = {};
data.mode = mode;
data.acquired = now;
data.pid = pid;
data.released = 0;
data.lock = (u32) lock;
data.wait = true;
struct lwlock *test = lock_wait.lookup(&pid);
if (test != NULL)
{
test->overwritten = true;
events.perf_submit(ctx, test, sizeof(*test));
}
else
{
events.perf_submit(ctx, &data, sizeof(data));
lock_wait.update(&pid, &data);
}
}
void probe_lwlock_acquire_finish(struct pt_regs *ctx)
{
u64 now = bpf_ktime_get_ns();
u32 pid = bpf_get_current_pid_tgid();
struct lwlock data = {};
struct lwlock *wait_data = lock_wait.lookup(&pid);
if (wait_data != NULL)
{
u64 timestamp = now;
u64 wait_time = timestamp - wait_data->acquired;
u64 lwlock_slot = bpf_log2l(wait_time / 1000);
wait_data->released = timestamp;
data.mode = wait_data->mode;
data.lock = wait_data->lock;
switch (wait_data->mode)
{
case LW_EXCLUSIVE:
lock_wait_exclusive_hist.increment(lwlock_slot);
break;
case LW_SHARED:
lock_wait_shared_hist.increment(lwlock_slot);
break;
default:
break;
}
wait_data->deleted = true;
events.perf_submit(ctx, wait_data, sizeof(*wait_data));
lock_wait.delete(&pid);
}
else
{
// can't determine the mode, skip
return;
}
data.acquired = now;
data.pid = pid;
data.released = 0;
data.hold = true;
struct lwlock *test = lock_hold.lookup(&pid);
if (test != NULL)
{
test->overwritten = true;
events.perf_submit(ctx, test, sizeof(*test));
}
else
{
events.perf_submit(ctx, &data, sizeof(data));
lock_hold.update(&pid, &data);
}
}
void probe_lwlock_release(struct pt_regs *ctx, struct LWLock *lock)
{
u64 now = bpf_ktime_get_ns();
u32 pid = bpf_get_current_pid_tgid();
struct lwlock *data = lock_hold.lookup(&pid);
if (data == NULL)
{
struct lwlock hold_data = {};
hold_data.pid = pid;
hold_data.lock = (u32) lock;
hold_data.hold = true;
hold_data.missing = true;
events.perf_submit(ctx, &hold_data, sizeof(hold_data));
return;
}
u64 hold_time = now - data->acquired;
data->released = now;
u64 lwlock_slot = bpf_log2l(hold_time / 1000);
switch (data->mode)
{
case LW_EXCLUSIVE:
lock_hold_exclusive_hist.increment(lwlock_slot);
break;
case LW_SHARED:
lock_hold_shared_hist.increment(lwlock_slot);
break;
default:
break;
}
data->deleted = true;
events.perf_submit(ctx, data, sizeof(*data));
lock_hold.delete(&pid);
}
"""
def attach(bpf, args):
binary_path = args.path
pid = args.pid
bpf.attach_uprobe(
name=binary_path,
sym="LWLockAcquire",
fn_name="probe_lwlock_acquire_start",
pid=pid)
bpf.attach_uretprobe(
name=binary_path,
sym="LWLockAcquire",
fn_name="probe_lwlock_acquire_finish",
pid=pid)
bpf.attach_uprobe(
name=binary_path,
sym="LWLockAcquireOrWait",
fn_name="probe_lwlock_acquire_start",
pid=pid)
bpf.attach_uretprobe(
name=binary_path,
sym="LWLockAcquireOrWait",
fn_name="probe_lwlock_acquire_finish",
pid=pid)
bpf.attach_uprobe(
name=binary_path,
sym="LWLockRelease",
fn_name="probe_lwlock_release",
pid=pid)
# signal handler
def signal_ignore(sig, frame):
print()
class Data(ct.Structure):
_fields_ = [("pid", ct.c_uint32),
("mode", ct.c_uint32),
("lock", ct.c_uint32),
("missing", ct.c_bool),
("overwritten", ct.c_bool),
("deleted", ct.c_bool),
("wait", ct.c_bool),
("hold", ct.c_bool),
("acquired", ct.c_uint64),
("released", ct.c_uint64)]
def print_event(cpu, data, size):
event = ct.cast(data, ct.POINTER(Data)).contents
prefix = None
if event.missing:
prefix = "Missing"
if event.overwritten:
prefix = "Overwritten"
if event.deleted:
prefix = "About to delete"
if event.hold and prefix is not None:
prefix += " hold"
if event.wait and prefix is not None:
prefix += " wait"
if event.hold and prefix is None:
prefix = "Hold"
if event.wait and prefix is None:
prefix = "Wait"
print("{} event: acquired {} released {} pid {} mode {} lock {}".format(
prefix or "",
event.acquired,
event.released,
event.pid,
event.mode,
event.lock))
def run(args):
print("Attaching...")
debug = 4 if args.debug else 0
bpf = BPF(text=text, debug=debug)
attach(bpf, args)
lock_hold_exclusive_hist = bpf["lock_hold_exclusive_hist"]
lock_hold_shared_hist = bpf["lock_hold_shared_hist"]
lock_wait_exclusive_hist = bpf["lock_wait_exclusive_hist"]
lock_wait_shared_hist = bpf["lock_wait_shared_hist"]
exiting = False
if args.debug:
bpf["events"].open_perf_buffer(print_event)
print("Listening...")
while True:
try:
sleep(1)
if args.debug:
bpf.perf_buffer_poll()
except KeyboardInterrupt:
exiting = True
# as cleanup can take many seconds, trap Ctrl-C:
signal.signal(signal.SIGINT, signal_ignore)
if exiting:
print("Detaching...")
break
print("Exclusive lock holding time")
lock_hold_exclusive_hist.print_log2_hist("hold time (us)")
print()
print("Total count: {}".format(
sum([v.value for v in lock_hold_exclusive_hist.values()])))
print()
print("Shared lock holding time")
lock_hold_shared_hist.print_log2_hist("hold time (us)")
print()
print("Total count: {}".format(
sum([v.value for v in lock_hold_shared_hist.values()])))
print()
print("Exclusive lock waiting time")
lock_wait_exclusive_hist.print_log2_hist("wait time (us)")
print()
print("Total count: {}".format(
sum([v.value for v in lock_wait_exclusive_hist.values()])))
print()
print("Shared lock waiting time")
lock_wait_shared_hist.print_log2_hist("wait time (us)")
print()
print("Total count: {}".format(
sum([v.value for v in lock_wait_shared_hist.values()])))
print()
def parse_args():
parser = argparse.ArgumentParser(
description="Time LWLocks in PostgreSQL",
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("path", type=str, help="path to target binary")
parser.add_argument(
"-p", "--pid", type=int, default=-1,
help="trace this PID only")
parser.add_argument(
"-d", "--debug", action='store_true', default=False,
help="debug mode")
return parser.parse_args()
if __name__ == "__main__":
run(parse_args())