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