kernel - Misc adjustments used by the vkernel and VMM, misc optimizations
[dragonfly.git] / sys / kern / lwkt_ipiq.c
1 /*
2  * Copyright (c) 2003,2004 The DragonFly Project.  All rights reserved.
3  * 
4  * This code is derived from software contributed to The DragonFly Project
5  * by Matthew Dillon <dillon@backplane.com>
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  * 
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in
15  *    the documentation and/or other materials provided with the
16  *    distribution.
17  * 3. Neither the name of The DragonFly Project nor the names of its
18  *    contributors may be used to endorse or promote products derived
19  *    from this software without specific, prior written permission.
20  * 
21  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
24  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
25  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
26  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
27  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
28  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
29  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
30  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
31  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34
35 /*
36  * This module implements IPI message queueing and the MI portion of IPI
37  * message processing.
38  */
39
40 #include "opt_ddb.h"
41
42 #include <sys/param.h>
43 #include <sys/systm.h>
44 #include <sys/kernel.h>
45 #include <sys/proc.h>
46 #include <sys/rtprio.h>
47 #include <sys/queue.h>
48 #include <sys/thread2.h>
49 #include <sys/sysctl.h>
50 #include <sys/ktr.h>
51 #include <sys/kthread.h>
52 #include <machine/cpu.h>
53 #include <sys/lock.h>
54
55 #include <vm/vm.h>
56 #include <vm/vm_param.h>
57 #include <vm/vm_kern.h>
58 #include <vm/vm_object.h>
59 #include <vm/vm_page.h>
60 #include <vm/vm_map.h>
61 #include <vm/vm_pager.h>
62 #include <vm/vm_extern.h>
63 #include <vm/vm_zone.h>
64
65 #include <machine/stdarg.h>
66 #include <machine/smp.h>
67 #include <machine/atomic.h>
68
69 #ifdef _KERNEL_VIRTUAL
70 #include <pthread.h>
71 #endif
72
73 struct ipiq_stats {
74     __int64_t ipiq_count;       /* total calls to lwkt_send_ipiq*() */
75     __int64_t ipiq_fifofull;    /* number of fifo full conditions detected */
76     __int64_t ipiq_avoided;     /* interlock with target avoids cpu ipi */
77     __int64_t ipiq_passive;     /* passive IPI messages */
78     __int64_t ipiq_cscount;     /* number of cpu synchronizations */
79 } __cachealign;
80
81 static struct ipiq_stats ipiq_stats_percpu[MAXCPU];
82 #define ipiq_stat(gd)   ipiq_stats_percpu[(gd)->gd_cpuid]
83
84 static int ipiq_debug;          /* set to 1 for debug */
85 #ifdef PANIC_DEBUG
86 static int      panic_ipiq_cpu = -1;
87 static int      panic_ipiq_count = 100;
88 #endif
89
90 SYSCTL_INT(_lwkt, OID_AUTO, ipiq_debug, CTLFLAG_RW, &ipiq_debug, 0,
91     "");
92 #ifdef PANIC_DEBUG
93 SYSCTL_INT(_lwkt, OID_AUTO, panic_ipiq_cpu, CTLFLAG_RW, &panic_ipiq_cpu, 0, "");
94 SYSCTL_INT(_lwkt, OID_AUTO, panic_ipiq_count, CTLFLAG_RW, &panic_ipiq_count, 0, "");
95 #endif
96
97 #define IPIQ_STRING     "func=%p arg1=%p arg2=%d scpu=%d dcpu=%d"
98 #define IPIQ_ARGS       void *func, void *arg1, int arg2, int scpu, int dcpu
99
100 #if !defined(KTR_IPIQ)
101 #define KTR_IPIQ        KTR_ALL
102 #endif
103 KTR_INFO_MASTER(ipiq);
104 KTR_INFO(KTR_IPIQ, ipiq, send_norm, 0, IPIQ_STRING, IPIQ_ARGS);
105 KTR_INFO(KTR_IPIQ, ipiq, send_pasv, 1, IPIQ_STRING, IPIQ_ARGS);
106 KTR_INFO(KTR_IPIQ, ipiq, send_nbio, 2, IPIQ_STRING, IPIQ_ARGS);
107 KTR_INFO(KTR_IPIQ, ipiq, send_fail, 3, IPIQ_STRING, IPIQ_ARGS);
108 KTR_INFO(KTR_IPIQ, ipiq, receive, 4, IPIQ_STRING, IPIQ_ARGS);
109 KTR_INFO(KTR_IPIQ, ipiq, sync_start, 5, "cpumask=%08lx", unsigned long mask);
110 KTR_INFO(KTR_IPIQ, ipiq, sync_end, 6, "cpumask=%08lx", unsigned long mask);
111 KTR_INFO(KTR_IPIQ, ipiq, cpu_send, 7, IPIQ_STRING, IPIQ_ARGS);
112 KTR_INFO(KTR_IPIQ, ipiq, send_end, 8, IPIQ_STRING, IPIQ_ARGS);
113
114 #define logipiq(name, func, arg1, arg2, sgd, dgd)       \
115         KTR_LOG(ipiq_ ## name, func, arg1, arg2, sgd->gd_cpuid, dgd->gd_cpuid)
116 #define logipiq2(name, arg)     \
117         KTR_LOG(ipiq_ ## name, arg)
118
119 static int lwkt_process_ipiq_core(globaldata_t sgd, lwkt_ipiq_t ip, 
120                                   struct intrframe *frame);
121 static void lwkt_cpusync_remote1(lwkt_cpusync_t cs);
122 static void lwkt_cpusync_remote2(lwkt_cpusync_t cs);
123
124 #define IPIQ_SYSCTL(name) \
125 static int \
126 sysctl_##name(SYSCTL_HANDLER_ARGS) \
127 { \
128     __int64_t val = 0; \
129     int cpu, error; \
130  \
131     for (cpu = 0; cpu < ncpus; ++cpu) \
132         val += ipiq_stats_percpu[cpu].name; \
133  \
134     error = sysctl_handle_quad(oidp, &val, 0, req); \
135     if (error || req->newptr == NULL) \
136         return error; \
137  \
138     for (cpu = 0; cpu < ncpus; ++cpu) \
139         ipiq_stats_percpu[cpu].name = val; \
140  \
141     return 0; \
142 }
143
144 IPIQ_SYSCTL(ipiq_count);
145 IPIQ_SYSCTL(ipiq_fifofull);
146 IPIQ_SYSCTL(ipiq_avoided);
147 IPIQ_SYSCTL(ipiq_passive);
148 IPIQ_SYSCTL(ipiq_cscount);
149
150 SYSCTL_PROC(_lwkt, OID_AUTO, ipiq_count, (CTLTYPE_QUAD | CTLFLAG_RW),
151     0, 0, sysctl_ipiq_count, "Q", "Number of IPI's sent");
152 SYSCTL_PROC(_lwkt, OID_AUTO, ipiq_fifofull, (CTLTYPE_QUAD | CTLFLAG_RW),
153     0, 0, sysctl_ipiq_fifofull, "Q",
154     "Number of fifo full conditions detected");
155 SYSCTL_PROC(_lwkt, OID_AUTO, ipiq_avoided, (CTLTYPE_QUAD | CTLFLAG_RW),
156     0, 0, sysctl_ipiq_avoided, "Q",
157     "Number of IPI's avoided by interlock with target cpu");
158 SYSCTL_PROC(_lwkt, OID_AUTO, ipiq_passive, (CTLTYPE_QUAD | CTLFLAG_RW),
159     0, 0, sysctl_ipiq_passive, "Q",
160     "Number of passive IPI messages sent");
161 SYSCTL_PROC(_lwkt, OID_AUTO, ipiq_cscount, (CTLTYPE_QUAD | CTLFLAG_RW),
162     0, 0, sysctl_ipiq_cscount, "Q",
163     "Number of cpu synchronizations");
164
165 /*
166  * Send a function execution request to another cpu.  The request is queued
167  * on the cpu<->cpu ipiq matrix.  Each cpu owns a unique ipiq FIFO for every
168  * possible target cpu.  The FIFO can be written.
169  *
170  * If the FIFO fills up we have to enable interrupts to avoid an APIC
171  * deadlock and process pending IPIQs while waiting for it to empty.   
172  * Otherwise we may soft-deadlock with another cpu whos FIFO is also full.
173  *
174  * We can safely bump gd_intr_nesting_level because our crit_exit() at the
175  * end will take care of any pending interrupts.
176  *
177  * The actual hardware IPI is avoided if the target cpu is already processing
178  * the queue from a prior IPI.  It is possible to pipeline IPI messages
179  * very quickly between cpus due to the FIFO hysteresis.
180  *
181  * Need not be called from a critical section.
182  */
183 int
184 lwkt_send_ipiq3(globaldata_t target, ipifunc3_t func, void *arg1, int arg2)
185 {
186     lwkt_ipiq_t ip;
187     int windex;
188     struct globaldata *gd = mycpu;
189
190     logipiq(send_norm, func, arg1, arg2, gd, target);
191
192     if (target == gd) {
193         func(arg1, arg2, NULL);
194         logipiq(send_end, func, arg1, arg2, gd, target);
195         return(0);
196     } 
197     crit_enter();
198     ++gd->gd_intr_nesting_level;
199 #ifdef INVARIANTS
200     if (gd->gd_intr_nesting_level > 20)
201         panic("lwkt_send_ipiq: TOO HEAVILY NESTED!");
202 #endif
203     KKASSERT(curthread->td_critcount);
204     ++ipiq_stat(gd).ipiq_count;
205     ip = &gd->gd_ipiq[target->gd_cpuid];
206
207     /*
208      * Do not allow the FIFO to become full.  Interrupts must be physically
209      * enabled while we liveloop to avoid deadlocking the APIC.
210      *
211      * The target ipiq may have gotten filled up due to passive IPIs and thus
212      * not be aware that its queue is too full, so be sure to issue an
213      * ipiq interrupt to the target cpu.
214      */
215     if (ip->ip_windex - ip->ip_rindex > MAXCPUFIFO / 2) {
216 #if defined(__i386__)
217         unsigned int eflags = read_eflags();
218 #elif defined(__x86_64__)
219         unsigned long rflags = read_rflags();
220 #endif
221
222         cpu_enable_intr();
223         ++ipiq_stat(gd).ipiq_fifofull;
224         DEBUG_PUSH_INFO("send_ipiq3");
225         while (ip->ip_windex - ip->ip_rindex > MAXCPUFIFO / 4) {
226             if (atomic_poll_acquire_int(&target->gd_npoll)) {
227                 logipiq(cpu_send, func, arg1, arg2, gd, target);
228                 cpu_send_ipiq(target->gd_cpuid);
229             }
230             KKASSERT(ip->ip_windex - ip->ip_rindex != MAXCPUFIFO - 1);
231             lwkt_process_ipiq();
232             cpu_pause();
233         }
234         DEBUG_POP_INFO();
235 #if defined(__i386__)
236         write_eflags(eflags);
237 #elif defined(__x86_64__)
238         write_rflags(rflags);
239 #endif
240     }
241
242     /*
243      * Queue the new message
244      */
245     windex = ip->ip_windex & MAXCPUFIFO_MASK;
246     ip->ip_info[windex].func = func;
247     ip->ip_info[windex].arg1 = arg1;
248     ip->ip_info[windex].arg2 = arg2;
249     cpu_sfence();
250     ++ip->ip_windex;
251     atomic_set_cpumask(&target->gd_ipimask, gd->gd_cpumask);
252
253     /*
254      * signal the target cpu that there is work pending.
255      */
256     if (atomic_poll_acquire_int(&target->gd_npoll)) {
257         logipiq(cpu_send, func, arg1, arg2, gd, target);
258         cpu_send_ipiq(target->gd_cpuid);
259     } else {
260         ++ipiq_stat(gd).ipiq_avoided;
261     }
262     --gd->gd_intr_nesting_level;
263     crit_exit();
264     logipiq(send_end, func, arg1, arg2, gd, target);
265
266     return(ip->ip_windex);
267 }
268
269 /*
270  * Similar to lwkt_send_ipiq() but this function does not actually initiate
271  * the IPI to the target cpu unless the FIFO has become too full, so it is
272  * very fast.
273  *
274  * This function is used for non-critical IPI messages, such as memory
275  * deallocations.  The queue will typically be flushed by the target cpu at
276  * the next clock interrupt.
277  *
278  * Need not be called from a critical section.
279  */
280 int
281 lwkt_send_ipiq3_passive(globaldata_t target, ipifunc3_t func,
282                         void *arg1, int arg2)
283 {
284     lwkt_ipiq_t ip;
285     int windex;
286     struct globaldata *gd = mycpu;
287
288     KKASSERT(target != gd);
289     crit_enter();
290     ++gd->gd_intr_nesting_level;
291     logipiq(send_pasv, func, arg1, arg2, gd, target);
292 #ifdef INVARIANTS
293     if (gd->gd_intr_nesting_level > 20)
294         panic("lwkt_send_ipiq: TOO HEAVILY NESTED!");
295 #endif
296     KKASSERT(curthread->td_critcount);
297     ++ipiq_stat(gd).ipiq_count;
298     ++ipiq_stat(gd).ipiq_passive;
299     ip = &gd->gd_ipiq[target->gd_cpuid];
300
301     /*
302      * Do not allow the FIFO to become full.  Interrupts must be physically
303      * enabled while we liveloop to avoid deadlocking the APIC.
304      */
305     if (ip->ip_windex - ip->ip_rindex > MAXCPUFIFO / 2) {
306 #if defined(__i386__)
307         unsigned int eflags = read_eflags();
308 #elif defined(__x86_64__)
309         unsigned long rflags = read_rflags();
310 #endif
311
312         cpu_enable_intr();
313         ++ipiq_stat(gd).ipiq_fifofull;
314         DEBUG_PUSH_INFO("send_ipiq3_passive");
315         while (ip->ip_windex - ip->ip_rindex > MAXCPUFIFO / 4) {
316             if (atomic_poll_acquire_int(&target->gd_npoll)) {
317                 logipiq(cpu_send, func, arg1, arg2, gd, target);
318                 cpu_send_ipiq(target->gd_cpuid);
319             }
320             KKASSERT(ip->ip_windex - ip->ip_rindex != MAXCPUFIFO - 1);
321             lwkt_process_ipiq();
322             cpu_pause();
323         }
324         DEBUG_POP_INFO();
325 #if defined(__i386__)
326         write_eflags(eflags);
327 #elif defined(__x86_64__)
328         write_rflags(rflags);
329 #endif
330     }
331
332     /*
333      * Queue the new message
334      */
335     windex = ip->ip_windex & MAXCPUFIFO_MASK;
336     ip->ip_info[windex].func = func;
337     ip->ip_info[windex].arg1 = arg1;
338     ip->ip_info[windex].arg2 = arg2;
339     cpu_sfence();
340     ++ip->ip_windex;
341     atomic_set_cpumask(&target->gd_ipimask, gd->gd_cpumask);
342     --gd->gd_intr_nesting_level;
343
344     /*
345      * Do not signal the target cpu, it will pick up the IPI when it next
346      * polls (typically on the next tick).
347      */
348     crit_exit();
349     logipiq(send_end, func, arg1, arg2, gd, target);
350
351     return(ip->ip_windex);
352 }
353
354 /*
355  * Send an IPI request without blocking, return 0 on success, ENOENT on 
356  * failure.  The actual queueing of the hardware IPI may still force us
357  * to spin and process incoming IPIs but that will eventually go away
358  * when we've gotten rid of the other general IPIs.
359  */
360 int
361 lwkt_send_ipiq3_nowait(globaldata_t target, ipifunc3_t func, 
362                        void *arg1, int arg2)
363 {
364     lwkt_ipiq_t ip;
365     int windex;
366     struct globaldata *gd = mycpu;
367
368     logipiq(send_nbio, func, arg1, arg2, gd, target);
369     KKASSERT(curthread->td_critcount);
370     if (target == gd) {
371         func(arg1, arg2, NULL);
372         logipiq(send_end, func, arg1, arg2, gd, target);
373         return(0);
374     } 
375     crit_enter();
376     ++gd->gd_intr_nesting_level;
377     ++ipiq_stat(gd).ipiq_count;
378     ip = &gd->gd_ipiq[target->gd_cpuid];
379
380     if (ip->ip_windex - ip->ip_rindex >= MAXCPUFIFO * 2 / 3) {
381         logipiq(send_fail, func, arg1, arg2, gd, target);
382         --gd->gd_intr_nesting_level;
383         crit_exit();
384         return(ENOENT);
385     }
386     windex = ip->ip_windex & MAXCPUFIFO_MASK;
387     ip->ip_info[windex].func = func;
388     ip->ip_info[windex].arg1 = arg1;
389     ip->ip_info[windex].arg2 = arg2;
390     cpu_sfence();
391     ++ip->ip_windex;
392     atomic_set_cpumask(&target->gd_ipimask, gd->gd_cpumask);
393
394     /*
395      * This isn't a passive IPI, we still have to signal the target cpu.
396      */
397     if (atomic_poll_acquire_int(&target->gd_npoll)) {
398         logipiq(cpu_send, func, arg1, arg2, gd, target);
399         cpu_send_ipiq(target->gd_cpuid);
400     } else {
401         ++ipiq_stat(gd).ipiq_avoided;
402     }
403     --gd->gd_intr_nesting_level;
404     crit_exit();
405
406     logipiq(send_end, func, arg1, arg2, gd, target);
407     return(0);
408 }
409
410 /*
411  * deprecated, used only by fast int forwarding.
412  */
413 int
414 lwkt_send_ipiq3_bycpu(int dcpu, ipifunc3_t func, void *arg1, int arg2)
415 {
416     return(lwkt_send_ipiq3(globaldata_find(dcpu), func, arg1, arg2));
417 }
418
419 /*
420  * Send a message to several target cpus.  Typically used for scheduling.
421  * The message will not be sent to stopped cpus.
422  */
423 int
424 lwkt_send_ipiq3_mask(cpumask_t mask, ipifunc3_t func, void *arg1, int arg2)
425 {
426     int cpuid;
427     int count = 0;
428
429     mask &= ~stopped_cpus;
430     while (mask) {
431         cpuid = BSFCPUMASK(mask);
432         lwkt_send_ipiq3(globaldata_find(cpuid), func, arg1, arg2);
433         mask &= ~CPUMASK(cpuid);
434         ++count;
435     }
436     return(count);
437 }
438
439 /*
440  * Wait for the remote cpu to finish processing a function.
441  *
442  * YYY we have to enable interrupts and process the IPIQ while waiting
443  * for it to empty or we may deadlock with another cpu.  Create a CPU_*()
444  * function to do this!  YYY we really should 'block' here.
445  *
446  * MUST be called from a critical section.  This routine may be called
447  * from an interrupt (for example, if an interrupt wakes a foreign thread
448  * up).
449  */
450 void
451 lwkt_wait_ipiq(globaldata_t target, int seq)
452 {
453     lwkt_ipiq_t ip;
454
455     if (target != mycpu) {
456         ip = &mycpu->gd_ipiq[target->gd_cpuid];
457         if ((int)(ip->ip_xindex - seq) < 0) {
458 #if defined(__i386__)
459             unsigned int eflags = read_eflags();
460 #elif defined(__x86_64__)
461             unsigned long rflags = read_rflags();
462 #endif
463             int64_t time_tgt = tsc_get_target(1000000000LL);
464             int time_loops = 10;
465             int benice = 0;
466
467             cpu_enable_intr();
468             DEBUG_PUSH_INFO("wait_ipiq");
469             while ((int)(ip->ip_xindex - seq) < 0) {
470                 crit_enter();
471                 lwkt_process_ipiq();
472                 crit_exit();
473
474                 /*
475                  * IPIQs must be handled within 10 seconds and this code
476                  * will warn after one second.
477                  */
478                 if ((benice & 255) == 0 && tsc_test_target(time_tgt) > 0) {
479                         kprintf("LWKT_WAIT_IPIQ WARNING! %d wait %d (%d)\n",
480                                 mycpu->gd_cpuid, target->gd_cpuid,
481                                 ip->ip_xindex - seq);
482                         if (--time_loops == 0)
483                                 panic("LWKT_WAIT_IPIQ");
484                         time_tgt = tsc_get_target(1000000000LL);
485                 }
486                 ++benice;
487
488                 /*
489                  * xindex may be modified by another cpu, use a load fence
490                  * to ensure that the loop does not use a speculative value
491                  * (which may improve performance).
492                  */
493                 cpu_lfence();
494             }
495             DEBUG_POP_INFO();
496 #if defined(__i386__)
497             write_eflags(eflags);
498 #elif defined(__x86_64__)
499             write_rflags(rflags);
500 #endif
501         }
502     }
503 }
504
505 int
506 lwkt_seq_ipiq(globaldata_t target)
507 {
508     lwkt_ipiq_t ip;
509
510     ip = &mycpu->gd_ipiq[target->gd_cpuid];
511     return(ip->ip_windex);
512 }
513
514 /*
515  * Called from IPI interrupt (like a fast interrupt), which has placed
516  * us in a critical section.  The MP lock may or may not be held.
517  * May also be called from doreti or splz, or be reentrantly called
518  * indirectly through the ip_info[].func we run.
519  *
520  * There are two versions, one where no interrupt frame is available (when
521  * called from the send code and from splz, and one where an interrupt
522  * frame is available.
523  *
524  * When the current cpu is mastering a cpusync we do NOT internally loop
525  * on the cpusyncq poll.  We also do not re-flag a pending ipi due to
526  * the cpusyncq poll because this can cause doreti/splz to loop internally.
527  * The cpusync master's own loop must be allowed to run to avoid a deadlock.
528  */
529 void
530 lwkt_process_ipiq(void)
531 {
532     globaldata_t gd = mycpu;
533     globaldata_t sgd;
534     lwkt_ipiq_t ip;
535     cpumask_t mask;
536     int n;
537
538     ++gd->gd_processing_ipiq;
539 again:
540     cpu_lfence();
541     mask = gd->gd_ipimask;
542     atomic_clear_cpumask(&gd->gd_ipimask, mask);
543     while (mask) {
544         n = BSFCPUMASK(mask);
545         if (n != gd->gd_cpuid) {
546             sgd = globaldata_find(n);
547             ip = sgd->gd_ipiq;
548             if (ip != NULL) {
549                 while (lwkt_process_ipiq_core(sgd, &ip[gd->gd_cpuid], NULL))
550                     ;
551             }
552         }
553         mask &= ~CPUMASK(n);
554     }
555
556     /*
557      * Process pending cpusyncs.  If the current thread has a cpusync
558      * active cpusync we only run the list once and do not re-flag
559      * as the thread itself is processing its interlock.
560      */
561     if (lwkt_process_ipiq_core(gd, &gd->gd_cpusyncq, NULL)) {
562         if (gd->gd_curthread->td_cscount == 0)
563             goto again;
564         /* need_ipiq(); do not reflag */
565     }
566
567     /*
568      * Interlock to allow more IPI interrupts.  Recheck ipimask after
569      * releasing gd_npoll.
570      */
571     if (gd->gd_ipimask)
572         goto again;
573     atomic_poll_release_int(&gd->gd_npoll);
574     cpu_mfence();
575     if (gd->gd_ipimask)
576         goto again;
577     --gd->gd_processing_ipiq;
578 }
579
580 void
581 lwkt_process_ipiq_frame(struct intrframe *frame)
582 {
583     globaldata_t gd = mycpu;
584     globaldata_t sgd;
585     lwkt_ipiq_t ip;
586     cpumask_t mask;
587     int n;
588
589 again:
590     cpu_lfence();
591     mask = gd->gd_ipimask;
592     atomic_clear_cpumask(&gd->gd_ipimask, mask);
593     while (mask) {
594         n = BSFCPUMASK(mask);
595         if (n != gd->gd_cpuid) {
596             sgd = globaldata_find(n);
597             ip = sgd->gd_ipiq;
598             if (ip != NULL) {
599                 while (lwkt_process_ipiq_core(sgd, &ip[gd->gd_cpuid], frame))
600                     ;
601             }
602         }
603         mask &= ~CPUMASK(n);
604     }
605     if (gd->gd_cpusyncq.ip_rindex != gd->gd_cpusyncq.ip_windex) {
606         if (lwkt_process_ipiq_core(gd, &gd->gd_cpusyncq, frame)) {
607             if (gd->gd_curthread->td_cscount == 0)
608                 goto again;
609             /* need_ipiq(); do not reflag */
610         }
611     }
612
613     /*
614      * Interlock to allow more IPI interrupts.  Recheck ipimask after
615      * releasing gd_npoll.
616      */
617     if (gd->gd_ipimask)
618         goto again;
619     atomic_poll_release_int(&gd->gd_npoll);
620     cpu_mfence();
621     if (gd->gd_ipimask)
622         goto again;
623 }
624
625 #if 0
626 static int iqticks[SMP_MAXCPU];
627 static int iqcount[SMP_MAXCPU];
628 #endif
629 #if 0
630 static int iqterm[SMP_MAXCPU];
631 #endif
632
633 static int
634 lwkt_process_ipiq_core(globaldata_t sgd, lwkt_ipiq_t ip, 
635                        struct intrframe *frame)
636 {
637     globaldata_t mygd = mycpu;
638     int ri;
639     int wi;
640     ipifunc3_t copy_func;
641     void *copy_arg1;
642     int copy_arg2;
643
644 #if 0
645     if (iqticks[mygd->gd_cpuid] != ticks) {
646             iqticks[mygd->gd_cpuid] = ticks;
647             iqcount[mygd->gd_cpuid] = 0;
648     }
649     if (++iqcount[mygd->gd_cpuid] > 3000000) {
650         kprintf("cpu %d ipiq maxed cscount %d spin %d\n",
651                 mygd->gd_cpuid,
652                 mygd->gd_curthread->td_cscount,
653                 mygd->gd_spinlocks);
654         iqcount[mygd->gd_cpuid] = 0;
655 #if 0
656         if (++iqterm[mygd->gd_cpuid] > 10)
657                 panic("cpu %d ipiq maxed", mygd->gd_cpuid);
658 #endif
659         int i;
660         for (i = 0; i < ncpus; ++i) {
661                 if (globaldata_find(i)->gd_infomsg)
662                         kprintf(" %s", globaldata_find(i)->gd_infomsg);
663         }
664         kprintf("\n");
665     }
666 #endif
667
668     /*
669      * Clear the originating core from our ipimask, we will process all
670      * incoming messages.
671      *
672      * Obtain the current write index, which is modified by a remote cpu.
673      * Issue a load fence to prevent speculative reads of e.g. data written
674      * by the other cpu prior to it updating the index.
675      */
676     KKASSERT(curthread->td_critcount);
677     wi = ip->ip_windex;
678     cpu_lfence();
679     ++mygd->gd_intr_nesting_level;
680
681     /*
682      * NOTE: xindex is only updated after we are sure the function has
683      *       finished execution.  Beware lwkt_process_ipiq() reentrancy!
684      *       The function may send an IPI which may block/drain.
685      *
686      * NOTE: Due to additional IPI operations that the callback function
687      *       may make, it is possible for both rindex and windex to advance and
688      *       thus for rindex to advance passed our cached windex.
689      *
690      * NOTE: A load fence is required to prevent speculative loads prior
691      *       to the loading of ip_rindex.  Even though stores might be
692      *       ordered, loads are probably not.  A memory fence is required
693      *       to prevent reordering of the loads after the ip_rindex update.
694      *
695      * NOTE: Single pass only.  Returns non-zero if the queue is not empty
696      *       on return.
697      */
698     while (wi - (ri = ip->ip_rindex) > 0) {
699         ri &= MAXCPUFIFO_MASK;
700         cpu_lfence();
701         copy_func = ip->ip_info[ri].func;
702         copy_arg1 = ip->ip_info[ri].arg1;
703         copy_arg2 = ip->ip_info[ri].arg2;
704         cpu_mfence();
705         ++ip->ip_rindex;
706         KKASSERT((ip->ip_rindex & MAXCPUFIFO_MASK) ==
707                  ((ri + 1) & MAXCPUFIFO_MASK));
708         logipiq(receive, copy_func, copy_arg1, copy_arg2, sgd, mycpu);
709 #ifdef INVARIANTS
710         if (ipiq_debug && (ip->ip_rindex & 0xFFFFFF) == 0) {
711                 kprintf("cpu %d ipifunc %p %p %d (frame %p)\n",
712                         mycpu->gd_cpuid,
713                         copy_func, copy_arg1, copy_arg2,
714 #if defined(__i386__)
715                         (frame ? (void *)frame->if_eip : NULL));
716 #elif defined(__x86_64__)
717                         (frame ? (void *)frame->if_rip : NULL));
718 #else
719                         NULL);
720 #endif
721         }
722 #endif
723         copy_func(copy_arg1, copy_arg2, frame);
724         cpu_sfence();
725         ip->ip_xindex = ip->ip_rindex;
726
727 #ifdef PANIC_DEBUG
728         /*
729          * Simulate panics during the processing of an IPI
730          */
731         if (mycpu->gd_cpuid == panic_ipiq_cpu && panic_ipiq_count) {
732                 if (--panic_ipiq_count == 0) {
733 #ifdef DDB
734                         Debugger("PANIC_DEBUG");
735 #else
736                         panic("PANIC_DEBUG");
737 #endif
738                 }
739         }
740 #endif
741     }
742     --mygd->gd_intr_nesting_level;
743
744     /*
745      * Return non-zero if there is still more in the queue.
746      */
747     cpu_lfence();
748     return (ip->ip_rindex != ip->ip_windex);
749 }
750
751 static void
752 lwkt_sync_ipiq(void *arg)
753 {
754     volatile cpumask_t *cpumask = arg;
755
756     atomic_clear_cpumask(cpumask, mycpu->gd_cpumask);
757     if (*cpumask == 0)
758         wakeup(cpumask);
759 }
760
761 void
762 lwkt_synchronize_ipiqs(const char *wmesg)
763 {
764     volatile cpumask_t other_cpumask;
765
766     other_cpumask = mycpu->gd_other_cpus & smp_active_mask;
767     lwkt_send_ipiq_mask(other_cpumask, lwkt_sync_ipiq,
768         __DEVOLATILE(void *, &other_cpumask));
769
770     while (other_cpumask != 0) {
771         tsleep_interlock(&other_cpumask, 0);
772         if (other_cpumask != 0)
773             tsleep(&other_cpumask, PINTERLOCKED, wmesg, 0);
774     }
775 }
776
777 /*
778  * CPU Synchronization Support
779  *
780  * lwkt_cpusync_interlock()     - Place specified cpus in a quiescent state.
781  *                                The current cpu is placed in a hard critical
782  *                                section.
783  *
784  * lwkt_cpusync_deinterlock()   - Execute cs_func on specified cpus, including
785  *                                current cpu if specified, then return.
786  */
787 void
788 lwkt_cpusync_simple(cpumask_t mask, cpusync_func_t func, void *arg)
789 {
790     struct lwkt_cpusync cs;
791
792     lwkt_cpusync_init(&cs, mask, func, arg);
793     lwkt_cpusync_interlock(&cs);
794     lwkt_cpusync_deinterlock(&cs);
795 }
796
797
798 void
799 lwkt_cpusync_interlock(lwkt_cpusync_t cs)
800 {
801 #if 0
802     const char *smsg = "SMPSYNL";
803 #endif
804     globaldata_t gd = mycpu;
805     cpumask_t mask;
806
807     /*
808      * mask acknowledge (cs_mack):  0->mask for stage 1
809      *
810      * mack does not include the current cpu.
811      */
812     mask = cs->cs_mask & gd->gd_other_cpus & smp_active_mask;
813     cs->cs_mack = 0;
814     crit_enter_id("cpusync");
815     if (mask) {
816         DEBUG_PUSH_INFO("cpusync_interlock");
817         ++ipiq_stat(gd).ipiq_cscount;
818         ++gd->gd_curthread->td_cscount;
819         lwkt_send_ipiq_mask(mask, (ipifunc1_t)lwkt_cpusync_remote1, cs);
820         logipiq2(sync_start, (long)mask);
821 #if 0
822         if (gd->gd_curthread->td_wmesg == NULL)
823                 gd->gd_curthread->td_wmesg = smsg;
824 #endif
825         while (cs->cs_mack != mask) {
826             lwkt_process_ipiq();
827             cpu_pause();
828 #ifdef _KERNEL_VIRTUAL
829             pthread_yield();
830 #endif
831         }
832 #if 0
833         if (gd->gd_curthread->td_wmesg == smsg)
834                 gd->gd_curthread->td_wmesg = NULL;
835 #endif
836         DEBUG_POP_INFO();
837     }
838 }
839
840 /*
841  * Interlocked cpus have executed remote1 and are polling in remote2.
842  * To deinterlock we clear cs_mack and wait for the cpus to execute
843  * the func and set their bit in cs_mack again.
844  *
845  */
846 void
847 lwkt_cpusync_deinterlock(lwkt_cpusync_t cs)
848 {
849     globaldata_t gd = mycpu;
850 #if 0
851     const char *smsg = "SMPSYNU";
852 #endif
853     cpumask_t mask;
854
855     /*
856      * mask acknowledge (cs_mack):  mack->0->mack for stage 2
857      *
858      * Clearing cpu bits for polling cpus in cs_mack will cause them to
859      * execute stage 2, which executes the cs_func(cs_data) and then sets
860      * their bit in cs_mack again.
861      *
862      * mack does not include the current cpu.
863      */
864     mask = cs->cs_mack;
865     cpu_ccfence();
866     cs->cs_mack = 0;
867     cpu_ccfence();
868     if (cs->cs_func && (cs->cs_mask & gd->gd_cpumask))
869             cs->cs_func(cs->cs_data);
870     if (mask) {
871         DEBUG_PUSH_INFO("cpusync_deinterlock");
872 #if 0
873         if (gd->gd_curthread->td_wmesg == NULL)
874                 gd->gd_curthread->td_wmesg = smsg;
875 #endif
876         while (cs->cs_mack != mask) {
877             lwkt_process_ipiq();
878             cpu_pause();
879 #ifdef _KERNEL_VIRTUAL
880             pthread_yield();
881 #endif
882         }
883 #if 0
884         if (gd->gd_curthread->td_wmesg == smsg)
885                 gd->gd_curthread->td_wmesg = NULL;
886 #endif
887         DEBUG_POP_INFO();
888         /*
889          * cpusyncq ipis may be left queued without the RQF flag set due to
890          * a non-zero td_cscount, so be sure to process any laggards after
891          * decrementing td_cscount.
892          */
893         --gd->gd_curthread->td_cscount;
894         lwkt_process_ipiq();
895         logipiq2(sync_end, (long)mask);
896     }
897     crit_exit_id("cpusync");
898 }
899
900 /*
901  * helper IPI remote messaging function.
902  * 
903  * Called on remote cpu when a new cpu synchronization request has been
904  * sent to us.  Execute the run function and adjust cs_count, then requeue
905  * the request so we spin on it.
906  */
907 static void
908 lwkt_cpusync_remote1(lwkt_cpusync_t cs)
909 {
910     globaldata_t gd = mycpu;
911
912     atomic_set_cpumask(&cs->cs_mack, gd->gd_cpumask);
913     lwkt_cpusync_remote2(cs);
914 }
915
916 /*
917  * helper IPI remote messaging function.
918  *
919  * Poll for the originator telling us to finish.  If it hasn't, requeue
920  * our request so we spin on it.
921  */
922 static void
923 lwkt_cpusync_remote2(lwkt_cpusync_t cs)
924 {
925     globaldata_t gd = mycpu;
926
927     if ((cs->cs_mack & gd->gd_cpumask) == 0) {
928         if (cs->cs_func)
929                 cs->cs_func(cs->cs_data);
930         atomic_set_cpumask(&cs->cs_mack, gd->gd_cpumask);
931         /* cs can be ripped out at this point */
932     } else {
933         lwkt_ipiq_t ip;
934         int wi;
935
936 #ifdef _KERNEL_VIRTUAL
937         pthread_yield();
938 #endif
939         ip = &gd->gd_cpusyncq;
940         wi = ip->ip_windex & MAXCPUFIFO_MASK;
941         ip->ip_info[wi].func = (ipifunc3_t)(ipifunc1_t)lwkt_cpusync_remote2;
942         ip->ip_info[wi].arg1 = cs;
943         ip->ip_info[wi].arg2 = 0;
944         cpu_sfence();
945         KKASSERT(ip->ip_windex - ip->ip_rindex < MAXCPUFIFO);
946         ++ip->ip_windex;
947         if (ipiq_debug && (ip->ip_windex & 0xFFFFFF) == 0) {
948                 kprintf("cpu %d cm=%016jx %016jx f=%p\n",
949                         gd->gd_cpuid,
950                         (intmax_t)cs->cs_mask, (intmax_t)cs->cs_mack,
951                         cs->cs_func);
952         }
953     }
954 }