Merge branch 'vendor/LIBPCAP'
[dragonfly.git] / sys / kern / kern_spinlock.c
1 /*
2  * Copyright (c) 2005 Jeffrey M. Hsu.  All rights reserved.
3  *
4  * This code is derived from software contributed to The DragonFly Project
5  * by Jeffrey M. Hsu. and Matthew Dillon
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of The DragonFly Project nor the names of its
16  *    contributors may be used to endorse or promote products derived
17  *    from this software without specific, prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
22  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
23  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
24  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
25  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
26  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
27  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
28  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
29  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32 /*
33  * The spinlock code utilizes two counters to form a virtual FIFO, allowing
34  * a spinlock to allocate a slot and then only issue memory read operations
35  * until it is handed the lock (if it is not the next owner for the lock).
36  */
37
38 #include <sys/param.h>
39 #include <sys/systm.h>
40 #include <sys/types.h>
41 #include <sys/kernel.h>
42 #include <sys/sysctl.h>
43 #ifdef INVARIANTS
44 #include <sys/proc.h>
45 #endif
46 #include <sys/priv.h>
47 #include <machine/atomic.h>
48 #include <machine/cpu.h>
49 #include <machine/cpufunc.h>
50 #include <machine/specialreg.h>
51 #include <machine/clock.h>
52 #include <sys/spinlock.h>
53 #include <sys/spinlock2.h>
54 #include <sys/ktr.h>
55
56 struct spinlock pmap_spin = SPINLOCK_INITIALIZER(pmap_spin);
57
58 #ifdef SMP
59
60 struct indefinite_info {
61         sysclock_t      base;
62         int             secs;
63 };
64
65 /*
66  * Kernal Trace
67  */
68 #if !defined(KTR_SPIN_CONTENTION)
69 #define KTR_SPIN_CONTENTION     KTR_ALL
70 #endif
71 #define SPIN_STRING     "spin=%p type=%c"
72 #define SPIN_ARG_SIZE   (sizeof(void *) + sizeof(int))
73
74 KTR_INFO_MASTER(spin);
75 #if 0
76 KTR_INFO(KTR_SPIN_CONTENTION, spin, beg, 0, SPIN_STRING, SPIN_ARG_SIZE);
77 KTR_INFO(KTR_SPIN_CONTENTION, spin, end, 1, SPIN_STRING, SPIN_ARG_SIZE);
78 #endif
79
80 #define logspin(name, spin, type)                       \
81         KTR_LOG(spin_ ## name, spin, type)
82
83 #ifdef INVARIANTS
84 static int spin_lock_test_mode;
85 #endif
86
87 static int64_t spinlocks_contested1;
88 SYSCTL_QUAD(_debug, OID_AUTO, spinlocks_contested1, CTLFLAG_RD,
89     &spinlocks_contested1, 0,
90     "Spinlock contention count due to collisions with exclusive lock holders");
91
92 static int64_t spinlocks_contested2;
93 SYSCTL_QUAD(_debug, OID_AUTO, spinlocks_contested2, CTLFLAG_RD,
94     &spinlocks_contested2, 0,
95     "Serious spinlock contention count");
96
97 #ifdef DEBUG_LOCKS_LATENCY
98
99 static long spinlocks_add_latency;
100 SYSCTL_LONG(_debug, OID_AUTO, spinlocks_add_latency, CTLFLAG_RW,
101     &spinlocks_add_latency, 0,
102     "Add spinlock latency");
103
104 #endif
105
106
107 /*
108  * We need a fairly large pool to avoid contention on large SMP systems,
109  * particularly multi-chip systems.
110  */
111 /*#define SPINLOCK_NUM_POOL     8101*/
112 #define SPINLOCK_NUM_POOL       8192
113 #define SPINLOCK_NUM_POOL_MASK  (SPINLOCK_NUM_POOL - 1)
114
115 static __cachealign struct {
116         struct spinlock spin;
117         char filler[32 - sizeof(struct spinlock)];
118 } pool_spinlocks[SPINLOCK_NUM_POOL];
119
120 static int spin_indefinite_check(struct spinlock *spin,
121                                   struct indefinite_info *info);
122
123 /*
124  * We contested due to another exclusive lock holder.  We lose.
125  *
126  * We have to unwind the attempt and may acquire the spinlock
127  * anyway while doing so.  countb was incremented on our behalf.
128  */
129 int
130 spin_trylock_contested(struct spinlock *spin)
131 {
132         globaldata_t gd = mycpu;
133
134         /*++spinlocks_contested1;*/
135         --gd->gd_spinlocks_wr;
136         --gd->gd_curthread->td_critcount;
137         return (FALSE);
138 }
139
140 /*
141  * The spin_lock() inline was unable to acquire the lock.
142  *
143  * atomic_swap_int() is the absolute fastest spinlock instruction, at
144  * least on multi-socket systems.  All instructions seem to be about
145  * the same on single-socket multi-core systems.  However, atomic_swap_int()
146  * does not result in an even distribution of successful acquisitions.
147  *
148  * Another problem we have is that (at least on the 48-core opteron we test
149  * with) having all 48 cores contesting the same spin lock reduces
150  * performance to around 600,000 ops/sec, verses millions when fewer cores
151  * are going after the same lock.
152  *
153  * Backoff algorithms can create even worse starvation problems, and don't
154  * really improve performance when a lot of cores are contending.
155  *
156  * Our solution is to allow the data cache to lazy-update by reading it
157  * non-atomically and only attempting to acquire the lock if the lazy read
158  * looks good.  This effectively limits cache bus bandwidth.  A cpu_pause()
159  * (for intel/amd anyhow) is not strictly needed as cache bus resource use
160  * is governed by the lazy update.
161  *
162  * WARNING!!!!  Performance matters here, by a huge margin.
163  *
164  *      48-core test with pre-read / -j 48 no-modules kernel compile
165  *      with fanned-out inactive and active queues came in at 55 seconds.
166  *
167  *      48-core test with pre-read / -j 48 no-modules kernel compile
168  *      came in at 75 seconds.  Without pre-read it came in at 170 seconds.
169  *
170  *      4-core test with pre-read / -j 48 no-modules kernel compile
171  *      came in at 83 seconds.  Without pre-read it came in at 83 seconds
172  *      as well (no difference).
173  */
174 void
175 spin_lock_contested(struct spinlock *spin)
176 {
177         struct indefinite_info info = { 0, 0 };
178         int i;
179
180 #ifdef DEBUG_LOCKS_LATENCY
181         long j;
182         for (j = spinlocks_add_latency; j > 0; --j)
183                 cpu_ccfence();
184 #endif
185
186         i = 0;
187         ++spin->countb;
188
189         /*logspin(beg, spin, 'w');*/
190         for (;;) {
191                 /*
192                  * NOTE: Reading spin->counta prior to the swap is extremely
193                  *       important on multi-chip/many-core boxes.  On 48-core
194                  *       this one change improves fully concurrent all-cores
195                  *       compiles by 100% or better.
196                  *
197                  *       I can't emphasize enough how important the pre-read is in
198                  *       preventing hw cache bus armageddon on multi-chip systems.
199                  *       And on single-chip/multi-core systems it just doesn't hurt.
200                  */
201                 if (spin->counta == 0 && atomic_swap_int(&spin->counta, 1) == 0)
202                         break;
203                 if ((++i & 0x7F) == 0x7F) {
204                         ++spin->countb;
205                         if (spin_indefinite_check(spin, &info))
206                                 break;
207                 }
208         }
209         /*logspin(end, spin, 'w');*/
210 }
211
212 static __inline int
213 _spin_pool_hash(void *ptr)
214 {
215         int i;
216
217         i = ((int)(uintptr_t) ptr >> 5) ^ ((int)(uintptr_t)ptr >> 12);
218         i &= SPINLOCK_NUM_POOL_MASK;
219         return (i);
220 }
221
222 void
223 _spin_pool_lock(void *chan)
224 {
225         struct spinlock *sp;
226
227         sp = &pool_spinlocks[_spin_pool_hash(chan)].spin;
228         spin_lock(sp);
229 }
230
231 void
232 _spin_pool_unlock(void *chan)
233 {
234         struct spinlock *sp;
235
236         sp = &pool_spinlocks[_spin_pool_hash(chan)].spin;
237         spin_unlock(sp);
238 }
239
240
241 static
242 int
243 spin_indefinite_check(struct spinlock *spin, struct indefinite_info *info)
244 {
245         sysclock_t count;
246
247         cpu_spinlock_contested();
248
249         count = sys_cputimer->count();
250         if (info->secs == 0) {
251                 info->base = count;
252                 ++info->secs;
253         } else if (count - info->base > sys_cputimer->freq) {
254                 kprintf("spin_lock: %p, indefinite wait (%d secs)!\n",
255                         spin, info->secs);
256                 info->base = count;
257                 ++info->secs;
258                 if (panicstr)
259                         return (TRUE);
260 #if defined(INVARIANTS)
261                 if (spin_lock_test_mode) {
262                         print_backtrace(-1);
263                         return (TRUE);
264                 }
265 #endif
266 #if defined(INVARIANTS)
267                 if (info->secs == 11)
268                         print_backtrace(-1);
269 #endif
270                 if (info->secs == 60)
271                         panic("spin_lock: %p, indefinite wait!\n", spin);
272         }
273         return (FALSE);
274 }
275
276 /*
277  * If INVARIANTS is enabled various spinlock timing tests can be run
278  * by setting debug.spin_lock_test:
279  *
280  *      1       Test the indefinite wait code
281  *      2       Time the best-case exclusive lock overhead (spin_test_count)
282  *      3       Time the best-case shared lock overhead (spin_test_count)
283  */
284
285 #ifdef INVARIANTS
286
287 static int spin_test_count = 10000000;
288 SYSCTL_INT(_debug, OID_AUTO, spin_test_count, CTLFLAG_RW, &spin_test_count, 0,
289     "Number of iterations to use for spinlock wait code test");
290
291 static int
292 sysctl_spin_lock_test(SYSCTL_HANDLER_ARGS)
293 {
294         struct spinlock spin;
295         int error;
296         int value = 0;
297         int i;
298
299         if ((error = priv_check(curthread, PRIV_ROOT)) != 0)
300                 return (error);
301         if ((error = SYSCTL_IN(req, &value, sizeof(value))) != 0)
302                 return (error);
303
304         /*
305          * Indefinite wait test
306          */
307         if (value == 1) {
308                 spin_init(&spin);
309                 spin_lock(&spin);       /* force an indefinite wait */
310                 spin_lock_test_mode = 1;
311                 spin_lock(&spin);
312                 spin_unlock(&spin);     /* Clean up the spinlock count */
313                 spin_unlock(&spin);
314                 spin_lock_test_mode = 0;
315         }
316
317         /*
318          * Time best-case exclusive spinlocks
319          */
320         if (value == 2) {
321                 globaldata_t gd = mycpu;
322
323                 spin_init(&spin);
324                 for (i = spin_test_count; i > 0; --i) {
325                     spin_lock_quick(gd, &spin);
326                     spin_unlock_quick(gd, &spin);
327                 }
328         }
329
330         return (0);
331 }
332
333 SYSCTL_PROC(_debug, KERN_PROC_ALL, spin_lock_test, CTLFLAG_RW|CTLTYPE_INT,
334         0, 0, sysctl_spin_lock_test, "I", "Test spinlock wait code");
335
336 #endif  /* INVARIANTS */
337 #endif  /* SMP */