CS multi-threaded and locking.
[akaros.git] / tests / lock_test.c
1 /* Copyright (c) 2013 The Regents of the University of California
2  * Barret Rhoden <brho@cs.berkeley.edu>
3  * See LICENSE for details.
4  *
5  * lock_test: microbenchmark to measure different styles of spinlocks. */
6
7 #include <stdio.h>
8 #include <pthread.h>
9 #include <stdlib.h>
10 #include <unistd.h>
11 #include <sys/time.h>
12 #include <math.h>
13 #include <argp.h>
14
15 #include <tsc-compat.h>
16 #include <measure.h>
17
18 /* OS dependent #incs */
19 #include <parlib.h>
20 #include <vcore.h>
21 #include <timing.h>
22 #include <spinlock.h>
23 #include <mcs.h>
24 #include <arch/arch.h>
25 #include <event.h>
26
27 /* TODO: There's lot of work to do still, both on this program and on locking
28  * and vcore code.  For some of the issues, I'll leave in the discussion /
29  * answers, in case it comes up in the future (like when I read this in 8
30  * months).
31  *
32  * BUGS / COMMENTARY
33  *              Occasional deadlocks when preempting and not giving back!
34  *                      - with the new PDRs style, though that doesn't mean the older styles
35  *                      don't have this problem
36  *                      - shouldn't be any weaker than PDR.  they all check pred_vc to see
37  *                      if they are running, and if not, they make sure someone runs
38  *                      - could be weaker if we have an old value for the lockholder,
39  *                      someone outside the chain, and we made sure they ran, and they do
40  *                      nothing (spin in the 2LS or something?)
41  *                              no, they should have gotten a msg about us being preempted,
42  *                              since whoever we turn into gets the message about us swapping.
43  *                      - anyway, it's not clear if this is with MCSPDR, event delivery,
44  *                      preemption handling, or just an artifact of the test (less likely)
45  *              why aren't MCS locks in uth_ctx getting dealt with?
46  *                      - because the event is handled, but the lock holder isn't run.  the
47  *                      preemption was dealt with, but nothing saved the lock holder
48  *                      - any uthread_ctx lockholder that gets preempted will get
49  *                      interrupted, and other cores will handle the preemption.  but that
50  *                      uthread won't run again without 2LS support.  either all spinners
51  *                      need to be aware of the 'lockholder' (PDR-style), or the 2LS needs
52  *                      to know when a uthread becomes a 'lockholder' to make sure it runs
53  *                      via user-level preempts.  If the latter, this needs to happen
54  *                      atomically with grabbing the lock, or else be able to handle lots of
55  *                      fake 'lockholders' (like round-robin among all of them)
56  *              why is the delay more than the expected delay?
57  *                      because it takes ~2ms to spawn and run a process
58  *                      could do this in a separate process, instead of a script
59  *                              could also consider not using pth_test and changing prov, but
60  *                              driving it by yields and requests.  would also test the
61  *                              alarm/wakeup code (process sets alarm, goes to sleep, wakes up
62  *                              and requests X cores)
63  *              why do we get occasional preempt-storms? (lots of change_tos)
64  *                      due to the MCS-PDR chain, which i tried fixing by adjusting the
65  *                      number of workers down to the number of vcores
66  *                      why isn't the worker adaptation working?
67  *                              - it actually was working, and nr_workers == nr_vcores.  that
68  *                              just wasn't the root cause.
69  *                              - was expecting it to cut down on PDR kernel traffic
70  *                      - still get periods of low perf
71  *                              like O(100) preempt msgs per big preempt/prov
72  *                              does it really take that much to work out an MCS-PDR?
73  *                      - one thing is that if we fake vc ctx, we never receive preemption
74  *                      events.  might be a bad idea.
75  *                              - in general, yeah.  faking VC and turning off events can really
76  *                              muck with things
77  *                              - these events aren't necessarily delivered to a VC who will
78  *                              check events any time soon (might be the last one in the chain)
79  *                              - the core of the issue is that we have the right amount of
80  *                              workers and vcores, but that the system isn't given a chance to
81  *                              stabilize itself.  also, if we have some VCs that are just
82  *                              sitting around, spinning in the 2LS, if those get preempted, no
83  *                              one notices or cares (when faking vc_ctx / getting no events)
84  *                      - there is a slight race where we might make someone run who isn't a
85  *                      lockholder.  logically, its okay.  worst case, it would act like an
86  *                      extra preempt and different startcore, which shouldn't be too bad.
87  *
88  *              sanity check: does throughput match latency? (2.5GHz TSC, MCS lock)
89  *                      ex: 5000 locks/ms = 5 locks/us = 200ns/lock = 500 ticks / lock
90  *                      500 ticks * 31 workers (queue) = 15000 ticks
91  *                      avg acquire time was around 14K.  seems fine..
92  *                      when our MCSPDR throughput tanks (during preempts), it's around
93  *                      400-500 locks/ms, which is around 2us/lock.  
94  *                              when the locker on a preempted chain shows up, it needs to
95  *                              change to the next one in line. 
96  *                                      - though that should be in parallel with the other
97  *                                      lockholders letting go.  shouldn't be that bad
98  *                                      - no, it is probably at the head of the chain very soon,
99  *                                      such that it is the bottleneck for the actual lock.  2us
100  *                                      seems possible
101  *
102  *              what does it take to get out of a preemption with (old) MCS-PDR?
103  *                      - these are now called pdro locks (old)
104  *                      - for a single preempt, it will take 1..n-1 changes.  avg n/2
105  *                      - for multiple preempts, it's nr_pre * that (avg np/2, worst np)
106  *                      - for every unlock/reacquire cycle (someone unlocks, then rejoins
107  *                      the list), its nr_preempts (aka, nr_workers - nr_vcores)
108  *                      - if we need to have a specific worker get out of the chain, on
109  *                      average, it'd take n/2 cycles (p*n/2 changes)  worst: np
110  *                      - if we want to get multiple workers out, the worst case is still
111  *                      np, but as p increases, we're more likely to approach n cycles
112  *                      - so the current model is np for the initial hit (to move the
113  *                      offline VCs to the end of the chain) and another np to get our
114  *                      specific workers out of the chain and yielding (2np)
115  *
116  *                      - but even with 1 preempt, we're getting 80-200 changes per
117  *
118  *                      - it shouldn't matter that the sys_change_to is really slow, should
119  *                      be the same amount of changes.  however, the preempted ones are
120  *                      never really at the tail end of the chain - they should end up right
121  *                      before the lockholder often.  while the sys_change_tos are slowly
122  *                      moving towards the back of the chain, the locking code is quickly
123  *                      removing (online) nodes from the head and putting them on the back.
124  *
125  *                      - end result: based on lock hold time and lock delay time, a
126  *                      preempted VC stays in the MCS chain (swaps btw VC/nodes), and when
127  *                      it is inside the chain, someone is polling to make them run.  with
128  *                      someone polling, it is extremely unlikely that someone outside the
129  *                      chain will win the race and be able to change_to before the in-chain
130  *                      poller.  to clarify:
131  *                              - hold time and delay time matter, since the longer they are,
132  *                              the greater the amount of time the change_to percolation has to
133  *                              get the preempted VCs to the end of the chain (where no one
134  *                              polls them).
135  *                              - at least one vcore is getting the event to handle the
136  *                              preemption of the in-chain, offline VC.  we could change it so
137  *                              every VC polls the preempt_evq, or just wait til whoever is
138  *                              getting the messages eventually checks their messages (VC0)
139  *                              - if there is an in-chain poller, they will notice the instant
140  *                              the VC map changes, and then immediately change_to (and spin on
141  *                              the proclock in the kernel).  there's almost no chance of a
142  *                              normal preempt event handler doing that faster.  (would require
143  *                              some IRQ latency or something serious).
144  *                      - adding in any hold time trashes our microbenchmark's perf, but a
145  *                      little delay time actually helps: (all with no preempts going on)
146  *                              - mcspdr, no delay: 4200-4400 (-w31 -l10000, no faking, etc)
147  *                              - mcspdr, d = 1: 4400-4800
148  *                              - mcspdr, d = 2: 4200-5200
149  *                              - as you add delay, it cuts down on contention for the
150  *                              lock->lock cacheline.  but if you add in too much, you'll tank
151  *                              throughput (since there is no contention at all).
152  *                              - as we increase the delay, we cut down on the chance of the
153  *                              preempt storm / preempt-stuck-in-the-chain, though it can still
154  *                              happen, even with a delay of 10us
155  *                      - maybe add in the lockholder again? (removed in 73701d6bfb)
156  *                              - massively cuts performance, like 2x throughput, without
157  *                              preempts
158  *                              - it's ability to help depends on impl:
159  *                                      in one version (old style), it didn't help much at all
160  *                                      - in another (optimized lockholder setting), i can't even
161  *                                      see the throughput hit, it recovered right away, with O(5)
162  *                                      messages
163  *                                      - the diff was having the lockholder assign the vcoreid
164  *                                      before passing off to the next in the chain, so that there
165  *                                      is less time with having "no lockholder".  (there's a brief
166  *                                      period where the lockholder says it is the next person, who
167  *                                      still spins.  they'll have to make sure their pred runs)
168  *                      -adj workers doesn't matter either...
169  *                              - the 2LS and preemption handling might be doing this
170  *                              automatically, when handle_vc_preempt() does a
171  *                              thread_paused() on its current_uthread.
172  *                              - adj_workers isn't critical if we're using some locks
173  *                              that check notif_pending.  eventually someone hears
174  *                              about preempted VCs (assuming we can keep up)
175  *
176  *                      What about delays?  both hold and delay should make it easier to get
177  *                      the preempted vcore to the end of the chain.  but do they have to be
178  *                      too big to be reasonable?
179  *                              - yes.  hold doesn't really help much until everything is
180  *                              slower.  even with a hold of around 1.2us, we still have the
181  *                              change_to-storms and lowered throughput.
182  *                              - doing a combo helps too.  if you hold for 1ns (quite a bit
183  *                              more actually, due to the overhead of ndelay, but sufficient to
184  *                              be "doing work"), and delaying for around 7us before rejoining,
185  *                              there's only about a 1/5 chance of a single preempt messing us
186  *                              up
187  *                                      - though having multiple preempts outstanding make this less
188  *                                      likely to work.
189  *                                      - and it seems like if we get into the storm scenario, we
190  *                                      never really get out.  either we do quickly or never do.
191  *                                      depending on the workload, this could be a matter of luck
192  *
193  *                      So we could try tracking the lockholder, but only looking at it when
194  *                      we know someone was preempted in the chain - specifically, when our
195  *                      pred is offline.  when that happens, we don't change to them, we
196  *                      make sure the lockholder is running.
197  *                              - tracking takes us from 4200->2800 throughput or so for MCS
198  *                              - 5200 -> 3700 or so for MCS in vc_ctx (__MCSPDR)
199  *                              - main spike seems to be in the hold time.  bimodal distrib,
200  *                              with most below 91 (the usual is everything packed below 70) and
201  *                              a big spike around 320
202  *
203  *      Summary:
204  *              So we need to have someone outside the chain change_to the one in the
205  *              chain o/w, someone will always be in the chain.  Right now, it's always
206  *              the next in line who is doing the changing, so a preempted vcore is
207  *              always still in the chain. 
208  *
209  *              If the locking workload has some delaying, such as while holding the
210  *              lock or before reacquiring, the "change_to" storm might not be a
211  *              problem.  If it is, the only alternative I have so far is to check the
212  *              lockholder (which prevents a chain member from always ensuring their
213  *              pred runs).  This hurts the lock's scalability/performance when we
214  *              aren't being preempted.  On the otherhand, based on what you're doing
215  *              with the lock, one more cache miss might not be as big of a deal as in
216  *              lock_test.  Especially if when you get stormed, your throughput could be
217  *              terrible and never recover.
218  *
219  *              Similar point: you can use spinpdr locks.  They have the PDR-benefits,
220  *              and won't induce the storm of change_tos.  However, this isn't much
221  *              better for contended locks.  They perform 2-3x worse (on c89) without
222  *              preemption.  Arguably, if you were worried about the preempt storms and
223  *              want scalability, you might want to use mcspdr with lockholders.
224  *
225  *              The MCSPDRS (now just callced MCSPDR, these are default) locks can avoid
226  *              the storm, but at the cost of a little more in performance.  mcspdrs
227  *              style is about the same when not getting preempted from uth ctx compared
228  *              to mcspdr (slight drop).  When in vc ctx, it's about 10-20% perf hit
229  *              (PDRS gains little from --vc_ctx). 
230  *
231  *              Turns out there is a perf hit to PDRS (and any non-stack based qnode)
232  *              when running on c89.  The issue is that after shuffling the vcores
233  *              around, they are no longer mapped nicely to pcores (VC0->PC1, VC1->PC2).
234  *              This is due to some 'false sharing' of the cachelines, caused mostly by
235  *              aggressive prefetching (notably the intel adjacent cacheline prefetcher,
236  *              which grabs two CLs at a time!).  Basically, stack-based qnodes are
237  *              qnodes that are very far apart in memory.  Cranking up the padding in
238  *              qnodes in the "qnodes-in-locks" style replicates this.
239  *
240  *              For some info on the prefetching:
241  *                      http://software.intel.com/en-us/articles/optimizing-application-performance-on-intel-coret-microarchitecture-using-hardware-implemented-prefetchers/
242  *                      http://software.intel.com/en-us/forums/topic/341769
243  *
244  *              Here's some rough numbers of the different styles for qnodes on c89.
245  *              'in order' is VCn->PC(n+1) (0->1, 1->2).  Worst order is with even VCs
246  *              on one socket, odds on the other.  the number of CLs is the size of a
247  *              qnode.  mcspdr is the new style (called mcspdrs in some places in this
248  *              document), with lock-based qnodes.  mcspdr2 is the same, but with
249  *              stack-based qnodes.  mcspdro is the old style (bad a recovery), stack
250  *              based, sometimes just called mcs-pdr
251  *
252  *              with prefetchers disabled (MCS and DCU)
253  *                      mcspdr   1CL  4.8-5.4 in order, 3.8-4.2 worst order
254  *                      mcspdr   2CL          in order,         worst order
255  *                      mcspdr   4CL  5.2-6.0 in order, 4.7-5.3 worst order
256  *                      mcspdr   8CL  5.4-6.7 in order, 5.2-6.2 worst order
257  *                      mcspdr  16CL  5.1-5.8 in order, 5.2-6.8 worst order
258  *                      mcspdr2 stck          in order,         worst order
259  *                      mcspdro stck  4-3.4.3 in order, 4.2-4.5 worst order
260  *                      mcspdro-vcctx 4.8-7.0 in order, 5.3-6.7 worst order
261  *                      can we see the 2 humps? 
262  *                              mcspdr 1CL yes but less, varied, etc
263  *                              mcspdr2 no
264  *
265  *              test again with worst order with prefetchers enabled
266  *                      mcspdr   1CL  3.8-4.0 in order, 2.6-2.7 worst order
267  *                      mcspdr   2CL  4.2-4.4 in order, 3.8-3.9 worst order
268  *                      mcspdr   4CL  4.5-5.2 in order, 4.0-4.2 worst order
269  *                      mcspdr   8CL  4.4-5.1 in order, 4.3-4.7 worst order
270  *                      mcspdr  16CL  4.4-4.8 in order, 4.4-5.3 worst order
271  *                      mcspdr2 stck  3.0-3.0 in order, 2.9-3.0 worst order
272  *                      mcspdro stck  4.2-4.3 in order, 4.2-4.4 worst order
273  *                      mcspdro-vcctx 5.2-6.4 in order, 5.0-5.9 worst order
274  *                      can we see the 2 humps?
275  *                              mcspdrs 1CL yes, clearly
276  *                              mcspdr2 no
277  *
278  * PROGRAM FEATURES
279  *              - verbosity?  vcoremap, preempts, the throughput and latency histograms?
280  *              - have a max workers option (0?) == max vcores
281  *              - would like to randomize (within bounds) the hold/delay times
282  *                      - help avoid convoys with MCS locks
283  *
284  * PERFORMANCE:
285  *              pcore control?  (hyperthreading, core 0, cross socket?)
286  *                      want some options for controlling which threads run where, or which
287  *                      vcores are even used (like turning off hyperthreading)?
288  *              implement ticket spinlocks?  (more fair, more effects of preempts)
289  *                      no simple way to do PDR either, other than 'check everyone'
290  *              MCS vs MCSPDR vs __MCSPDR
291  *                      MCS seems slightly better than __MCSPDR (and it should)
292  *                      MCSPDR is a bit worse than __MCSPDR
293  *                              - the uth_disable/enable code seems to make a difference.
294  *                              - i see why the latencies are worse, since they have extra work
295  *                              to do, but the internal part that contends with other cores
296  *                              shouldn't be affected, unless there's some other thing going on.
297  *                              Or perhaps there isn't always someone waiting for the lock?
298  *                              - faking VC ctx mostly negates the cost of MCSPDR vs __MCSPDR
299  *                      things that made a big diff: CL aligning the qnodes, putting qnodes
300  *                      on stacks, reading in the vcoreid once before ensuring()
301  *              both MCS CAS unlocks could use some branch prediction work
302  *              spinpdr locks are 2-3x faster than spinlocks...
303  *                      test, test&set  vs the existing test&set, plus lots of asserts
304  *
305  *              some delay (like 10us) lowers latency while maintaining throughput
306  *                      - makes sense esp with MCS.  if you join the queue at the last
307  *                      second, you'll measure lower latency than attempting right away
308  *                      - also true for spinlocks
309  *                      - we can probably figure out the max throughput (TP = f(delay)) for
310  *                      each lock type
311  *
312  *              hard to get steady numbers with MCS - different runs of the same test
313  *              will vary in throughput by around 15-30% (e.g., MCS varying from 3k-4k
314  *              L/ms)
315  *                      - happens on c89 (NUMA) and hossin (UMA)
316  *                      - spinlocks seem a little steadier.
317  *                      - for MCS locks, the order in which they line up across the pcores
318  *                      will matter.  like if on one run, i regularly hand off between cores
319  *                      in the same socket and only do one cross-socket step
320  *                      - run a lot of shorter ones to get a trend, for now
321  *                      - might be correllated with spikes in held times (last bin)
322  *                      - can't turn off legacy USB on c89 (SMM) - interferes with PXE
323  *
324  * PREEMPTS:
325  *              better preempt record tracking?
326  *                      i just hacked some event-intercept and timestamp code together
327  *                      maybe put it in the event library?
328  *                      the timestamps definitely helped debugging
329  *
330  *              is it true that if uthread code never spins outside a PDR lock, then it
331  *              doesn't need preemption IPIs?  (just someone checks the event at some
332  *              point). 
333  *                      think so: so long as you make progress and when you aren't, you
334  *                      check events (like if a uthread blocks on something and enters VC
335  *                      ctx)
336  *              adjusting the number of workers, whether vcores or uthreads
337  *              - if you have more lockers than cores:
338  *                      - spinpdr a worker will get starved (akaros) (without 2LS support)
339  *                              - running this from uth context will cause a handle_events
340  *                      - mcspdr will require the kernel to switch (akaros)
341  *                      - spin (akaros) might DL (o/w nothing), (linux) poor perf
342  *                      - mcs (akaros) will DL, (linux) poor perf
343  *                      - poor perf (latency spikes) comes from running the wrong thread
344  *                      sometimes
345  *                      - deadlock comes from the lack of kernel-level context switching
346  *              - if we scale workers down to the number of active vcores:
347  *                      - two things: the initial hit, and the steady state.  during the
348  *                      initial hit, we can still deadlock, since we have more lockers than
349  *                      cores
350  *                              - non-pdr (akaros) could deadlock in the initial hit
351  *                              - (akaros) steady state, everything is normal (just fewer cores)
352  *                      - how can we adjust this in linux?
353  *                              - if know how many cores you have, then futex wait the others
354  *                              - need some way to wake them back up
355  *                              - if you do this in userspace, you might need something PDR-like
356  *                              to handle when the "2LS" code gets preempted
357  *                      - as mentioned above, the problem in akaros is that the lock/unlock
358  *                      might be happening too fast to get into the steady-state and recover
359  *                      from the initial preemption
360  *              - one of our benefits is that we can adapt in userspace, with userspace
361  *              knowledge, under any circumstance.
362  *                      - we have the deadlock windows (forcing PDR).
363  *                      - in return, we can do this adaptation in userspace
364  *                      - and (arguably) anyone who does this in userspace will need PDR
365  *
366  * MEASUREMENT (user/parlib/measure.c)
367  *              extract into its own library, for linux apps
368  *              print out raw TSC times?  might help sync up diff timelines
369  *              Need more latency bins, spinlocks vary too much
370  *              maybe we need better high/low too, since this hist looks bad too
371  *                      or not center on the average?
372  *                      for printing, its hard to know without already binning.
373  *                      maybe bin once (latency?), then use that to adjust the hist?
374  *
375  *              Had this on a spinlock:
376  *              [      32 -    35656] 1565231:
377  *              (less than 200 intermediate)
378  *          [  286557 - 20404788]   65298: *
379  *
380  *              Samples per dot: 34782
381  *              Total samples: 1640606
382  *              Avg time   : 96658
383  *              Stdev time : 604064.440882
384  *              Coef Var   : 6.249503
385  *                      High coeff of var with serious outliers, adjusted bins
386  *                      50/75/90/99: 33079 / 33079 / 33079 / 290219 (-<860)
387  *                      Min / Max  : 32 / 20404788
388  *              was 50/75/90 really within 860 of each other?
389  *
390  *              when we are preempted and don't even attempt anything, say for 10ms, it
391  *              actually doesn't hurt our 50/75/90/99 too much.  we have a ridiculous
392  *              stddev and max, and high average, but there aren't any additional
393  *              attempts at locking to mess with the attempt-latency.  Only nr_vcores
394  *              requests are in flight during the preemption, but we can spit out around
395  *              5000 per ms when we aren't preempted.
396  *
397  */
398
399 const char *argp_program_version = "lock_test v0.1475263";
400 const char *argp_program_bug_address = "<akaros@lists.eecs.berkeley.edu>";
401
402 static char doc[] = "lock_test -- spinlock benchmarking";
403 static char args_doc[] = "-w NUM -l NUM -t LOCK";
404
405 #define OPT_VC_CTX 1
406 #define OPT_ADJ_WORKERS 2
407
408 static struct argp_option options[] = {
409         {"workers",             'w', "NUM",     OPTION_NO_USAGE, "Number of threads/cores"},
410         {0, 0, 0, 0, ""},
411         {"loops",               'l', "NUM",     OPTION_NO_USAGE, "Number of loops per worker"},
412         {0, 0, 0, 0, ""},
413         {"type",                't', "LOCK",OPTION_NO_USAGE, "Type of lock to use.  "
414                                                      "Options:\n"
415                                                      "\tmcs\n"
416                                                      "\tmcscas\n"
417                                                      "\tmcspdr\n"
418                                                      "\tmcspdro\n"
419                                                      "\t__mcspdro\n"
420                                                      "\tspin\n"
421                                                      "\tspinpdr"},
422         {0, 0, 0, 0, "Other options (not mandatory):"},
423         {"adj_workers", OPT_ADJ_WORKERS, 0,     0, "Adjust workers such that the "
424                                                "number of workers equals the "
425                                                "number of vcores"},
426         {"vc_ctx",              OPT_VC_CTX, 0,  0, "Run threads in mock-vcore context"},
427         {0, 0, 0, 0, ""},
428         {"hold",                'h', "NSEC",    0, "nsec to hold the lock"},
429         {"delay",               'd', "NSEC",    0, "nsec to delay between grabs"},
430         {"print",               'p', "ROWS",    0, "Print ROWS of optional measurements"},
431         { 0 }
432 };
433
434 struct prog_args {
435         int                                                     nr_threads;
436         int                                                     nr_loops;
437         int                                                     hold_time;
438         int                                                     delay_time;
439         int                                                     nr_print_rows;
440         bool                                            fake_vc_ctx;
441         bool                                            adj_workers;
442         void *(*lock_type)(void *arg);
443 };
444 struct prog_args pargs = {0};
445
446 /* Globals */
447 struct time_stamp {
448         uint64_t pre;
449         uint64_t acq;
450         uint64_t un;
451         bool valid;
452 };
453 struct time_stamp **times;
454 bool run_locktest = TRUE;
455 pthread_barrier_t start_test;
456
457 /* Locking functions.  Define globals here, init them in main (if possible), and
458  * use the lock_func() macro to make your thread func. */
459
460 spinlock_t spin_lock = SPINLOCK_INITIALIZER;
461 struct spin_pdr_lock spdr_lock = SPINPDR_INITIALIZER;
462 struct mcs_lock mcs_lock = MCS_LOCK_INIT;
463 struct mcs_pdr_lock mcspdr_lock;
464 struct mcs_pdro_lock mcspdro_lock = MCSPDRO_LOCK_INIT;
465
466 #define lock_func(lock_name, lock_cmd, unlock_cmd)                             \
467 void *lock_name##_thread(void *arg)                                            \
468 {                                                                              \
469         long thread_id = (long)arg;                                                \
470         int hold_time = ACCESS_ONCE(pargs.hold_time);                              \
471         int delay_time = ACCESS_ONCE(pargs.delay_time);                            \
472         int nr_loops = ACCESS_ONCE(pargs.nr_loops);                                \
473         bool fake_vc_ctx = ACCESS_ONCE(pargs.fake_vc_ctx);                         \
474         bool adj_workers = ACCESS_ONCE(pargs.adj_workers);                         \
475         uint64_t pre_lock, acq_lock, un_lock;                                      \
476         struct time_stamp *this_time;                                              \
477         struct mcs_lock_qnode mcs_qnode = MCS_QNODE_INIT;                          \
478         struct mcs_pdro_qnode pdro_qnode = MCSPDRO_QNODE_INIT;                     \
479         /* guessing a unique vcoreid for vcoreid for the __mcspdr test.  if the
480          * program gets preempted for that test, things may go nuts */             \
481         pdro_qnode.vcoreid = thread_id - 1;                                        \
482         /* Wait til all threads are created.  Ideally, I'd like to busywait unless
483          * absolutely critical to yield */                                         \
484         pthread_barrier_wait(&start_test);                                         \
485         if (fake_vc_ctx) {                                                         \
486                 /* tells the kernel / other vcores we're in vc ctx */                  \
487                 uth_disable_notifs();                                                  \
488                 /* tricks ourselves into believing we're in vc ctx */                  \
489                 __vcore_context = TRUE;                                                \
490         }                                                                          \
491         for (int i = 0; i < nr_loops; i++) {                                       \
492                 if (!run_locktest)                                                     \
493                         break;                                                             \
494                 pre_lock = read_tsc_serialized();                                      \
495                                                                                \
496                 lock_cmd                                                               \
497                                                                                \
498                 acq_lock = read_tsc_serialized();                                      \
499                 if (hold_time)                                                         \
500                         ndelay(hold_time);                                                 \
501                                                                                \
502                 unlock_cmd                                                             \
503                                                                                \
504                 un_lock = read_tsc_serialized();                                       \
505                 this_time = &times[thread_id][i];                                      \
506                 this_time->pre = pre_lock;                                             \
507                 this_time->acq = acq_lock;                                             \
508                 this_time->un = un_lock;                                               \
509                 /* Can turn these on or off to control which samples we gather */      \
510                 this_time->valid = TRUE;                                               \
511                 /* this_time->valid = (num_vcores() == max_vcores());  */              \
512                                                                                \
513                 if (delay_time)                                                        \
514                         ndelay(delay_time);                                                \
515                 /* worker thread ids are 0..n-1.  if we're one of the threads that's
516                  * beyond the VC count, we yield. */                                   \
517                 if (adj_workers && num_vcores() < thread_id + 1) {                     \
518                         if (fake_vc_ctx) {                                                 \
519                                 __vcore_context = FALSE;                                       \
520                                 uth_enable_notifs();                                           \
521                         }                                                                  \
522                         /* we'll come back up once we have enough VCs running */           \
523                         pthread_yield();                                                   \
524                         if (fake_vc_ctx) {                                                 \
525                                 uth_disable_notifs();                                          \
526                                 __vcore_context = TRUE;                                        \
527                         }                                                                  \
528                 }                                                                      \
529                 cmb();                                                                 \
530         }                                                                          \
531         /* First thread to finish stops the test */                                \
532         run_locktest = FALSE;                                                      \
533         if (fake_vc_ctx) {                                                         \
534                 __vcore_context = FALSE;                                               \
535                 uth_enable_notifs();                                                   \
536         }                                                                          \
537         return arg;                                                                \
538 }
539
540 /* Defines locking funcs like "mcs_thread" */
541 lock_func(mcs,
542           mcs_lock_lock(&mcs_lock, &mcs_qnode);,
543           mcs_lock_unlock(&mcs_lock, &mcs_qnode);)
544 lock_func(mcscas,
545           mcs_lock_lock(&mcs_lock, &mcs_qnode);,
546           mcs_lock_unlock_cas(&mcs_lock, &mcs_qnode);)
547 lock_func(mcspdr,
548           mcs_pdr_lock(&mcspdr_lock);,
549           mcs_pdr_unlock(&mcspdr_lock);)
550 lock_func(mcspdro,
551           mcs_pdro_lock(&mcspdro_lock, &pdro_qnode);,
552           mcs_pdro_unlock(&mcspdro_lock, &pdro_qnode);)
553 lock_func(__mcspdro,
554           __mcs_pdro_lock(&mcspdro_lock, &pdro_qnode);,
555           __mcs_pdro_unlock(&mcspdro_lock, &pdro_qnode);)
556 lock_func(spin,
557           spinlock_lock(&spin_lock);,
558           spinlock_unlock(&spin_lock);)
559 lock_func(spinpdr,
560           spin_pdr_lock(&spdr_lock);,
561           spin_pdr_unlock(&spdr_lock);)
562
563 static int get_acq_latency(void **data, int i, int j, uint64_t *sample)
564 {
565         struct time_stamp **times = (struct time_stamp**)data;
566         /* 0 for initial time means we didn't measure */
567         if (times[i][j].pre == 0)
568                 return -1;
569         /* can optionally throw out invalid times (keep this in sync with the
570          * lock_test macro, based on what you want to meaasure. */
571         #if 0
572         if (!times[i][j].valid)
573                 return -1;
574         #endif
575         *sample = times[i][j].acq - times[i][j].pre - get_tsc_overhead();
576         return 0;
577 }
578
579 static int get_hld_latency(void **data, int i, int j, uint64_t *sample)
580 {
581         struct time_stamp **times = (struct time_stamp**)data;
582         /* 0 for initial time means we didn't measure */
583         if (times[i][j].pre == 0)
584                 return -1;
585         *sample = times[i][j].un - times[i][j].acq - get_tsc_overhead();
586         return 0;
587 }
588
589 static int get_acq_timestamp(void **data, int i, int j, uint64_t *sample)
590 {
591         struct time_stamp **times = (struct time_stamp**)data;
592         /* 0 for initial time means we didn't measure */
593         if (times[i][j].pre == 0)
594                 return -1;
595         *sample = times[i][j].acq;
596         return 0;
597 }
598
599 /* Lousy event intercept.  build something similar in the event library? */
600 #define MAX_NR_EVENT_TRACES 1000
601 uint64_t preempts[MAX_NR_EVENT_TRACES] = {0};
602 uint64_t indirs[MAX_NR_EVENT_TRACES] = {0};
603 atomic_t preempt_idx;
604 atomic_t indir_idx;
605 atomic_t preempt_cnt;
606 atomic_t indir_cnt;
607
608 static void trace_preempt(struct event_msg *ev_msg, unsigned int ev_type,
609                           void *data)
610 {
611         unsigned long my_slot = atomic_fetch_and_add(&preempt_idx, 1);
612         if (my_slot < MAX_NR_EVENT_TRACES)
613                 preempts[my_slot] = read_tsc();
614         atomic_inc(&preempt_cnt);
615 }
616
617 static void trace_indir(struct event_msg *ev_msg, unsigned int ev_type,
618                         void *data)
619 {
620         unsigned long my_slot = atomic_fetch_and_add(&indir_idx, 1);
621         if (my_slot < MAX_NR_EVENT_TRACES)
622                 indirs[my_slot] = read_tsc();
623         atomic_inc(&indir_cnt);
624 }
625
626 /* Helper, prints out the preempt trace */
627 static void print_preempt_trace(uint64_t starttsc, int nr_print_rows)
628 {
629         /* reusing nr_print_rows for the nr preempt/indirs rows as well */
630         int preempt_rows = MIN(MAX_NR_EVENT_TRACES, nr_print_rows);
631         if (pargs.fake_vc_ctx) {
632                 printf("No preempt trace available when faking vc ctx\n");
633                 return;
634         }
635         printf("\n");
636         printf("Nr Preempts: %d\n", atomic_read(&preempt_cnt));
637         printf("Nr Indirs  : %d\n", atomic_read(&indir_cnt));
638         if (preempt_rows)
639                 printf("Preempt/Indir events:\n-----------------\n");
640         for (int i = 0; i < preempt_rows; i++) {
641                 if (preempts[i])
642                         printf("Preempt %3d at %6llu\n", i, tsc2msec(preempts[i]
643                                                                      - starttsc));
644         }
645         for (int i = 0; i < preempt_rows; i++) {
646                 if (indirs[i])
647                         printf("Indir   %3d at %6llu\n", i, tsc2msec(indirs[i]
648                                                                      - starttsc));
649         }
650 }
651
652 /* Make sure we have enough VCs for nr_threads, pref 1:1 at the start */
653 static void os_prep_work(int nr_threads)
654 {
655         if (nr_threads > max_vcores()) {
656                 printf("Too many threads (%d) requested, can't get more than %d vc\n",
657                        nr_threads, max_vcores());
658                 exit(-1);
659         }
660         atomic_init(&preempt_idx, 0);
661         atomic_init(&indir_idx, 0);
662         atomic_init(&preempt_cnt, 0);
663         atomic_init(&indir_cnt, 0);
664         pthread_can_vcore_request(FALSE);       /* 2LS won't manage vcores */
665         pthread_need_tls(FALSE);
666         pthread_lib_init();                                     /* gives us one vcore */
667         register_ev_handler(EV_VCORE_PREEMPT, trace_preempt, 0);
668         register_ev_handler(EV_CHECK_MSGS, trace_indir, 0);
669         if (pargs.fake_vc_ctx) {
670                 /* need to disable events when faking vc ctx.  since we're looping and
671                  * not handling events, we could run OOM */
672                 clear_kevent_q(EV_VCORE_PREEMPT);
673                 clear_kevent_q(EV_CHECK_MSGS);
674         }
675         if (vcore_request(nr_threads - 1)) {
676                 printf("Failed to request %d more vcores, currently have %d\n",
677                        nr_threads - 1, num_vcores());
678                 exit(-1);
679         }
680         for (int i = 0; i < nr_threads; i++) {
681                 printd("Vcore %d mapped to pcore %d\n", i,
682                        __procinfo.vcoremap[i].pcoreid);
683         }
684 }
685
686 /* Argument parsing */
687 static error_t parse_opt (int key, char *arg, struct argp_state *state)
688 {
689         struct prog_args *pargs = state->input;
690         switch (key) {
691                 case 'w':
692                         pargs->nr_threads = atoi(arg);
693                         if (pargs->nr_threads < 0) {
694                                 printf("Negative nr_threads...\n\n");
695                                 argp_usage(state);
696                         }
697                         break;
698                 case 'l':
699                         pargs->nr_loops = atoi(arg);
700                         if (pargs->nr_loops < 0) {
701                                 printf("Negative nr_loops...\n\n");
702                                 argp_usage(state);
703                         }
704                         break;
705                 case OPT_ADJ_WORKERS:
706                         pargs->adj_workers = TRUE;
707                         break;
708                 case OPT_VC_CTX:
709                         pargs->fake_vc_ctx = TRUE;
710                         break;
711                 case 'h':
712                         pargs->hold_time = atoi(arg);
713                         if (pargs->hold_time < 0) {
714                                 printf("Negative hold_time...\n\n");
715                                 argp_usage(state);
716                         }
717                         break;
718                 case 'd':
719                         pargs->delay_time = atoi(arg);
720                         if (pargs->delay_time < 0) {
721                                 printf("Negative delay_time...\n\n");
722                                 argp_usage(state);
723                         }
724                         break;
725                 case 'p':
726                         pargs->nr_print_rows = atoi(arg);
727                         if (pargs->nr_print_rows < 0) {
728                                 printf("Negative print_rows...\n\n");
729                                 argp_usage(state);
730                         }
731                         break;
732                 case 't':
733                         if (!strcmp("mcs", arg)) {
734                                 pargs->lock_type = mcs_thread;
735                                 break;
736                         }
737                         if (!strcmp("mcscas", arg)) {
738                                 pargs->lock_type = mcscas_thread;
739                                 break;
740                         }
741                         if (!strcmp("mcspdr", arg)) {
742                                 pargs->lock_type = mcspdr_thread;
743                                 break;
744                         }
745                         if (!strcmp("mcspdro", arg)) {
746                                 pargs->lock_type = mcspdro_thread;
747                                 break;
748                         }
749                         if (!strcmp("__mcspdro", arg)) {
750                                 pargs->lock_type = __mcspdro_thread;
751                                 break;
752                         }
753                         if (!strcmp("spin", arg)) {
754                                 pargs->lock_type = spin_thread;
755                                 break;
756                         }
757                         if (!strcmp("spinpdr", arg)) {
758                                 pargs->lock_type = spinpdr_thread;
759                                 break;
760                         }
761                         printf("Unknown locktype %s\n\n", arg);
762                         argp_usage(state);
763                         break;
764                 case ARGP_KEY_ARG:
765                         printf("Warning, extra argument %s ignored\n\n", arg);
766                         break;
767                 case ARGP_KEY_END:
768                         if (!pargs->nr_threads) {
769                                 printf("Must select a number of threads.\n\n");
770                                 argp_usage(state);
771                                 break;
772                         }
773                         if (!pargs->nr_loops) {
774                                 printf("Must select a number of loops.\n\n");
775                                 argp_usage(state);
776                                 break;
777                         }
778                         if (!pargs->lock_type) {
779                                 printf("Must select a type of lock.\n\n");
780                                 argp_usage(state);
781                                 break;
782                         }
783                         break;
784                 default:
785                         return ARGP_ERR_UNKNOWN;
786         }
787         return 0;
788 }
789
790 static struct argp argp = {options, parse_opt, args_doc, doc};
791
792 int main(int argc, char** argv)
793 {
794         pthread_t *worker_threads;
795         void *dummy_retval;
796         struct timeval start_tv = {0};
797         struct timeval end_tv = {0};
798         long usec_diff;
799         uint64_t starttsc;
800         int nr_threads, nr_loops;
801         struct sample_stats acq_stats, hld_stats;
802
803         argp_parse(&argp, argc, argv, 0, 0, &pargs);
804         nr_threads = pargs.nr_threads;
805         nr_loops = pargs.nr_loops;
806         mcs_pdr_init(&mcspdr_lock);
807
808         worker_threads = malloc(sizeof(pthread_t) * nr_threads);
809         if (!worker_threads) {
810                 perror("pthread_t malloc failed:");
811                 exit(-1);
812         }
813         printf("Making %d workers of %d loops each, %sadapting workers to vcores, "
814                "and %sfaking vcore context\n", nr_threads, nr_loops,
815                pargs.adj_workers ? "" : "not ",
816                pargs.fake_vc_ctx ? "" : "not ");
817         pthread_barrier_init(&start_test, NULL, nr_threads);
818
819         times = malloc(sizeof(struct time_stamp *) * nr_threads);
820         assert(times);
821         for (int i = 0; i < nr_threads; i++) {
822                 times[i] = malloc(sizeof(struct time_stamp) * nr_loops);
823                 if (!times[i]) {
824                         perror("Record keeping malloc");
825                         exit(-1);
826                 }
827                 memset(times[i], 0, sizeof(struct time_stamp) * nr_loops);
828         }
829         printf("Record tracking takes %d bytes of memory\n",
830                nr_threads * nr_loops * sizeof(struct time_stamp));
831         os_prep_work(nr_threads);       /* ensure we have enough VCs */
832         /* Doing this in MCP ctx, so we might have been getting a few preempts
833          * already.  Want to read start before the threads pass their barrier */
834         starttsc = read_tsc();
835         /* create and join on yield */
836         for (long i = 0; i < nr_threads; i++) {
837                 if (pthread_create(&worker_threads[i], NULL, pargs.lock_type,
838                                    (void*)i))
839                         perror("pth_create failed");
840         }
841         if (gettimeofday(&start_tv, 0))
842                 perror("Start time error...");
843         for (int i = 0; i < nr_threads; i++) {
844                 pthread_join(worker_threads[i], &dummy_retval);
845         }
846         if (gettimeofday(&end_tv, 0))
847                 perror("End time error...");
848
849         printf("Acquire times (TSC Ticks)\n---------------------------\n");
850         acq_stats.get_sample = get_acq_latency;
851         compute_stats((void**)times, nr_threads, nr_loops, &acq_stats);
852
853         printf("Held times (from acq til rel done) (TSC Ticks)\n------\n");
854         hld_stats.get_sample = get_hld_latency;
855         compute_stats((void**)times, nr_threads, nr_loops, &hld_stats);
856
857         usec_diff = (end_tv.tv_sec - start_tv.tv_sec) * 1000000 +
858                     (end_tv.tv_usec - start_tv.tv_usec);
859         printf("Time to run: %d usec\n", usec_diff);
860
861         printf("\nLock throughput:\n-----------------\n");
862         /* throughput for the entire duration (in ms), 1ms steps.  print as many
863          * steps as they ask for (up to the end of the run). */
864         print_throughput((void**)times, usec_diff / 1000 + 1, msec2tsc(1),
865                          pargs.nr_print_rows,
866                          starttsc, nr_threads,
867                          nr_loops, get_acq_timestamp);
868         print_preempt_trace(starttsc, pargs.nr_print_rows);
869         printf("Done, exiting\n");
870 }