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