[MIPS] Define MIPS_CPU_IRQ_BASE in generic header
[safe/jmp/linux-2.6] / arch / mips / kernel / smtc.c
1 /* Copyright (C) 2004 Mips Technologies, Inc */
2
3 #include <linux/kernel.h>
4 #include <linux/sched.h>
5 #include <linux/cpumask.h>
6 #include <linux/interrupt.h>
7 #include <linux/module.h>
8
9 #include <asm/cpu.h>
10 #include <asm/processor.h>
11 #include <asm/atomic.h>
12 #include <asm/system.h>
13 #include <asm/hardirq.h>
14 #include <asm/hazards.h>
15 #include <asm/mmu_context.h>
16 #include <asm/smp.h>
17 #include <asm/mipsregs.h>
18 #include <asm/cacheflush.h>
19 #include <asm/time.h>
20 #include <asm/addrspace.h>
21 #include <asm/smtc.h>
22 #include <asm/smtc_ipi.h>
23 #include <asm/smtc_proc.h>
24
25 /*
26  * This file should be built into the kernel only if CONFIG_MIPS_MT_SMTC is set.
27  */
28
29 #define MIPS_CPU_IPI_IRQ        1
30
31 #define LOCK_MT_PRA() \
32         local_irq_save(flags); \
33         mtflags = dmt()
34
35 #define UNLOCK_MT_PRA() \
36         emt(mtflags); \
37         local_irq_restore(flags)
38
39 #define LOCK_CORE_PRA() \
40         local_irq_save(flags); \
41         mtflags = dvpe()
42
43 #define UNLOCK_CORE_PRA() \
44         evpe(mtflags); \
45         local_irq_restore(flags)
46
47 /*
48  * Data structures purely associated with SMTC parallelism
49  */
50
51
52 /*
53  * Table for tracking ASIDs whose lifetime is prolonged.
54  */
55
56 asiduse smtc_live_asid[MAX_SMTC_TLBS][MAX_SMTC_ASIDS];
57
58 /*
59  * Clock interrupt "latch" buffers, per "CPU"
60  */
61
62 unsigned int ipi_timer_latch[NR_CPUS];
63
64 /*
65  * Number of InterProcessor Interupt (IPI) message buffers to allocate
66  */
67
68 #define IPIBUF_PER_CPU 4
69
70 struct smtc_ipi_q IPIQ[NR_CPUS];
71 struct smtc_ipi_q freeIPIq;
72
73
74 /* Forward declarations */
75
76 void ipi_decode(struct smtc_ipi *);
77 void post_direct_ipi(int cpu, struct smtc_ipi *pipi);
78 void setup_cross_vpe_interrupts(void);
79 void init_smtc_stats(void);
80
81 /* Global SMTC Status */
82
83 unsigned int smtc_status = 0;
84
85 /* Boot command line configuration overrides */
86
87 static int vpelimit = 0;
88 static int tclimit = 0;
89 static int ipibuffers = 0;
90 static int nostlb = 0;
91 static int asidmask = 0;
92 unsigned long smtc_asid_mask = 0xff;
93
94 static int __init maxvpes(char *str)
95 {
96         get_option(&str, &vpelimit);
97         return 1;
98 }
99
100 static int __init maxtcs(char *str)
101 {
102         get_option(&str, &tclimit);
103         return 1;
104 }
105
106 static int __init ipibufs(char *str)
107 {
108         get_option(&str, &ipibuffers);
109         return 1;
110 }
111
112 static int __init stlb_disable(char *s)
113 {
114         nostlb = 1;
115         return 1;
116 }
117
118 static int __init asidmask_set(char *str)
119 {
120         get_option(&str, &asidmask);
121         switch (asidmask) {
122         case 0x1:
123         case 0x3:
124         case 0x7:
125         case 0xf:
126         case 0x1f:
127         case 0x3f:
128         case 0x7f:
129         case 0xff:
130                 smtc_asid_mask = (unsigned long)asidmask;
131                 break;
132         default:
133                 printk("ILLEGAL ASID mask 0x%x from command line\n", asidmask);
134         }
135         return 1;
136 }
137
138 __setup("maxvpes=", maxvpes);
139 __setup("maxtcs=", maxtcs);
140 __setup("ipibufs=", ipibufs);
141 __setup("nostlb", stlb_disable);
142 __setup("asidmask=", asidmask_set);
143
144 /* Enable additional debug checks before going into CPU idle loop */
145 #define SMTC_IDLE_HOOK_DEBUG
146
147 #ifdef SMTC_IDLE_HOOK_DEBUG
148
149 static int hang_trig = 0;
150
151 static int __init hangtrig_enable(char *s)
152 {
153         hang_trig = 1;
154         return 1;
155 }
156
157
158 __setup("hangtrig", hangtrig_enable);
159
160 #define DEFAULT_BLOCKED_IPI_LIMIT 32
161
162 static int timerq_limit = DEFAULT_BLOCKED_IPI_LIMIT;
163
164 static int __init tintq(char *str)
165 {
166         get_option(&str, &timerq_limit);
167         return 1;
168 }
169
170 __setup("tintq=", tintq);
171
172 int imstuckcount[2][8];
173 /* vpemask represents IM/IE bits of per-VPE Status registers, low-to-high */
174 int vpemask[2][8] = {{0,1,1,0,0,0,0,1},{0,1,0,0,0,0,0,1}};
175 int tcnoprog[NR_CPUS];
176 static atomic_t idle_hook_initialized = {0};
177 static int clock_hang_reported[NR_CPUS];
178
179 #endif /* SMTC_IDLE_HOOK_DEBUG */
180
181 /* Initialize shared TLB - the should probably migrate to smtc_setup_cpus() */
182
183 void __init sanitize_tlb_entries(void)
184 {
185         printk("Deprecated sanitize_tlb_entries() invoked\n");
186 }
187
188
189 /*
190  * Configure shared TLB - VPC configuration bit must be set by caller
191  */
192
193 void smtc_configure_tlb(void)
194 {
195         int i,tlbsiz,vpes;
196         unsigned long mvpconf0;
197         unsigned long config1val;
198
199         /* Set up ASID preservation table */
200         for (vpes=0; vpes<MAX_SMTC_TLBS; vpes++) {
201             for(i = 0; i < MAX_SMTC_ASIDS; i++) {
202                 smtc_live_asid[vpes][i] = 0;
203             }
204         }
205         mvpconf0 = read_c0_mvpconf0();
206
207         if ((vpes = ((mvpconf0 & MVPCONF0_PVPE)
208                         >> MVPCONF0_PVPE_SHIFT) + 1) > 1) {
209             /* If we have multiple VPEs, try to share the TLB */
210             if ((mvpconf0 & MVPCONF0_TLBS) && !nostlb) {
211                 /*
212                  * If TLB sizing is programmable, shared TLB
213                  * size is the total available complement.
214                  * Otherwise, we have to take the sum of all
215                  * static VPE TLB entries.
216                  */
217                 if ((tlbsiz = ((mvpconf0 & MVPCONF0_PTLBE)
218                                 >> MVPCONF0_PTLBE_SHIFT)) == 0) {
219                     /*
220                      * If there's more than one VPE, there had better
221                      * be more than one TC, because we need one to bind
222                      * to each VPE in turn to be able to read
223                      * its configuration state!
224                      */
225                     settc(1);
226                     /* Stop the TC from doing anything foolish */
227                     write_tc_c0_tchalt(TCHALT_H);
228                     mips_ihb();
229                     /* No need to un-Halt - that happens later anyway */
230                     for (i=0; i < vpes; i++) {
231                         write_tc_c0_tcbind(i);
232                         /*
233                          * To be 100% sure we're really getting the right
234                          * information, we exit the configuration state
235                          * and do an IHB after each rebinding.
236                          */
237                         write_c0_mvpcontrol(
238                                 read_c0_mvpcontrol() & ~ MVPCONTROL_VPC );
239                         mips_ihb();
240                         /*
241                          * Only count if the MMU Type indicated is TLB
242                          */
243                         if (((read_vpe_c0_config() & MIPS_CONF_MT) >> 7) == 1) {
244                                 config1val = read_vpe_c0_config1();
245                                 tlbsiz += ((config1val >> 25) & 0x3f) + 1;
246                         }
247
248                         /* Put core back in configuration state */
249                         write_c0_mvpcontrol(
250                                 read_c0_mvpcontrol() | MVPCONTROL_VPC );
251                         mips_ihb();
252                     }
253                 }
254                 write_c0_mvpcontrol(read_c0_mvpcontrol() | MVPCONTROL_STLB);
255                 ehb();
256
257                 /*
258                  * Setup kernel data structures to use software total,
259                  * rather than read the per-VPE Config1 value. The values
260                  * for "CPU 0" gets copied to all the other CPUs as part
261                  * of their initialization in smtc_cpu_setup().
262                  */
263
264                 /* MIPS32 limits TLB indices to 64 */
265                 if (tlbsiz > 64)
266                         tlbsiz = 64;
267                 cpu_data[0].tlbsize = current_cpu_data.tlbsize = tlbsiz;
268                 smtc_status |= SMTC_TLB_SHARED;
269                 local_flush_tlb_all();
270
271                 printk("TLB of %d entry pairs shared by %d VPEs\n",
272                         tlbsiz, vpes);
273             } else {
274                 printk("WARNING: TLB Not Sharable on SMTC Boot!\n");
275             }
276         }
277 }
278
279
280 /*
281  * Incrementally build the CPU map out of constituent MIPS MT cores,
282  * using the specified available VPEs and TCs.  Plaform code needs
283  * to ensure that each MIPS MT core invokes this routine on reset,
284  * one at a time(!).
285  *
286  * This version of the build_cpu_map and prepare_cpus routines assumes
287  * that *all* TCs of a MIPS MT core will be used for Linux, and that
288  * they will be spread across *all* available VPEs (to minimise the
289  * loss of efficiency due to exception service serialization).
290  * An improved version would pick up configuration information and
291  * possibly leave some TCs/VPEs as "slave" processors.
292  *
293  * Use c0_MVPConf0 to find out how many TCs are available, setting up
294  * phys_cpu_present_map and the logical/physical mappings.
295  */
296
297 int __init mipsmt_build_cpu_map(int start_cpu_slot)
298 {
299         int i, ntcs;
300
301         /*
302          * The CPU map isn't actually used for anything at this point,
303          * so it's not clear what else we should do apart from set
304          * everything up so that "logical" = "physical".
305          */
306         ntcs = ((read_c0_mvpconf0() & MVPCONF0_PTC) >> MVPCONF0_PTC_SHIFT) + 1;
307         for (i=start_cpu_slot; i<NR_CPUS && i<ntcs; i++) {
308                 cpu_set(i, phys_cpu_present_map);
309                 __cpu_number_map[i] = i;
310                 __cpu_logical_map[i] = i;
311         }
312         /* Initialize map of CPUs with FPUs */
313         cpus_clear(mt_fpu_cpumask);
314
315         /* One of those TC's is the one booting, and not a secondary... */
316         printk("%i available secondary CPU TC(s)\n", i - 1);
317
318         return i;
319 }
320
321 /*
322  * Common setup before any secondaries are started
323  * Make sure all CPU's are in a sensible state before we boot any of the
324  * secondaries.
325  *
326  * For MIPS MT "SMTC" operation, we set up all TCs, spread as evenly
327  * as possible across the available VPEs.
328  */
329
330 static void smtc_tc_setup(int vpe, int tc, int cpu)
331 {
332         settc(tc);
333         write_tc_c0_tchalt(TCHALT_H);
334         mips_ihb();
335         write_tc_c0_tcstatus((read_tc_c0_tcstatus()
336                         & ~(TCSTATUS_TKSU | TCSTATUS_DA | TCSTATUS_IXMT))
337                         | TCSTATUS_A);
338         write_tc_c0_tccontext(0);
339         /* Bind tc to vpe */
340         write_tc_c0_tcbind(vpe);
341         /* In general, all TCs should have the same cpu_data indications */
342         memcpy(&cpu_data[cpu], &cpu_data[0], sizeof(struct cpuinfo_mips));
343         /* For 34Kf, start with TC/CPU 0 as sole owner of single FPU context */
344         if (cpu_data[0].cputype == CPU_34K)
345                 cpu_data[cpu].options &= ~MIPS_CPU_FPU;
346         cpu_data[cpu].vpe_id = vpe;
347         cpu_data[cpu].tc_id = tc;
348 }
349
350
351 void mipsmt_prepare_cpus(void)
352 {
353         int i, vpe, tc, ntc, nvpe, tcpervpe, slop, cpu;
354         unsigned long flags;
355         unsigned long val;
356         int nipi;
357         struct smtc_ipi *pipi;
358
359         /* disable interrupts so we can disable MT */
360         local_irq_save(flags);
361         /* disable MT so we can configure */
362         dvpe();
363         dmt();
364
365         spin_lock_init(&freeIPIq.lock);
366
367         /*
368          * We probably don't have as many VPEs as we do SMP "CPUs",
369          * but it's possible - and in any case we'll never use more!
370          */
371         for (i=0; i<NR_CPUS; i++) {
372                 IPIQ[i].head = IPIQ[i].tail = NULL;
373                 spin_lock_init(&IPIQ[i].lock);
374                 IPIQ[i].depth = 0;
375                 ipi_timer_latch[i] = 0;
376         }
377
378         /* cpu_data index starts at zero */
379         cpu = 0;
380         cpu_data[cpu].vpe_id = 0;
381         cpu_data[cpu].tc_id = 0;
382         cpu++;
383
384         /* Report on boot-time options */
385         mips_mt_set_cpuoptions ();
386         if (vpelimit > 0)
387                 printk("Limit of %d VPEs set\n", vpelimit);
388         if (tclimit > 0)
389                 printk("Limit of %d TCs set\n", tclimit);
390         if (nostlb) {
391                 printk("Shared TLB Use Inhibited - UNSAFE for Multi-VPE Operation\n");
392         }
393         if (asidmask)
394                 printk("ASID mask value override to 0x%x\n", asidmask);
395
396         /* Temporary */
397 #ifdef SMTC_IDLE_HOOK_DEBUG
398         if (hang_trig)
399                 printk("Logic Analyser Trigger on suspected TC hang\n");
400 #endif /* SMTC_IDLE_HOOK_DEBUG */
401
402         /* Put MVPE's into 'configuration state' */
403         write_c0_mvpcontrol( read_c0_mvpcontrol() | MVPCONTROL_VPC );
404
405         val = read_c0_mvpconf0();
406         nvpe = ((val & MVPCONF0_PVPE) >> MVPCONF0_PVPE_SHIFT) + 1;
407         if (vpelimit > 0 && nvpe > vpelimit)
408                 nvpe = vpelimit;
409         ntc = ((val & MVPCONF0_PTC) >> MVPCONF0_PTC_SHIFT) + 1;
410         if (ntc > NR_CPUS)
411                 ntc = NR_CPUS;
412         if (tclimit > 0 && ntc > tclimit)
413                 ntc = tclimit;
414         tcpervpe = ntc / nvpe;
415         slop = ntc % nvpe;      /* Residual TCs, < NVPE */
416
417         /* Set up shared TLB */
418         smtc_configure_tlb();
419
420         for (tc = 0, vpe = 0 ; (vpe < nvpe) && (tc < ntc) ; vpe++) {
421                 /*
422                  * Set the MVP bits.
423                  */
424                 settc(tc);
425                 write_vpe_c0_vpeconf0(read_vpe_c0_vpeconf0() | VPECONF0_MVP);
426                 if (vpe != 0)
427                         printk(", ");
428                 printk("VPE %d: TC", vpe);
429                 for (i = 0; i < tcpervpe; i++) {
430                         /*
431                          * TC 0 is bound to VPE 0 at reset,
432                          * and is presumably executing this
433                          * code.  Leave it alone!
434                          */
435                         if (tc != 0) {
436                                 smtc_tc_setup(vpe,tc, cpu);
437                                 cpu++;
438                         }
439                         printk(" %d", tc);
440                         tc++;
441                 }
442                 if (slop) {
443                         if (tc != 0) {
444                                 smtc_tc_setup(vpe,tc, cpu);
445                                 cpu++;
446                         }
447                         printk(" %d", tc);
448                         tc++;
449                         slop--;
450                 }
451                 if (vpe != 0) {
452                         /*
453                          * Clear any stale software interrupts from VPE's Cause
454                          */
455                         write_vpe_c0_cause(0);
456
457                         /*
458                          * Clear ERL/EXL of VPEs other than 0
459                          * and set restricted interrupt enable/mask.
460                          */
461                         write_vpe_c0_status((read_vpe_c0_status()
462                                 & ~(ST0_BEV | ST0_ERL | ST0_EXL | ST0_IM))
463                                 | (STATUSF_IP0 | STATUSF_IP1 | STATUSF_IP7
464                                 | ST0_IE));
465                         /*
466                          * set config to be the same as vpe0,
467                          *  particularly kseg0 coherency alg
468                          */
469                         write_vpe_c0_config(read_c0_config());
470                         /* Clear any pending timer interrupt */
471                         write_vpe_c0_compare(0);
472                         /* Propagate Config7 */
473                         write_vpe_c0_config7(read_c0_config7());
474                         write_vpe_c0_count(read_c0_count());
475                 }
476                 /* enable multi-threading within VPE */
477                 write_vpe_c0_vpecontrol(read_vpe_c0_vpecontrol() | VPECONTROL_TE);
478                 /* enable the VPE */
479                 write_vpe_c0_vpeconf0(read_vpe_c0_vpeconf0() | VPECONF0_VPA);
480         }
481
482         /*
483          * Pull any physically present but unused TCs out of circulation.
484          */
485         while (tc < (((val & MVPCONF0_PTC) >> MVPCONF0_PTC_SHIFT) + 1)) {
486                 cpu_clear(tc, phys_cpu_present_map);
487                 cpu_clear(tc, cpu_present_map);
488                 tc++;
489         }
490
491         /* release config state */
492         write_c0_mvpcontrol( read_c0_mvpcontrol() & ~ MVPCONTROL_VPC );
493
494         printk("\n");
495
496         /* Set up coprocessor affinity CPU mask(s) */
497
498         for (tc = 0; tc < ntc; tc++) {
499                 if (cpu_data[tc].options & MIPS_CPU_FPU)
500                         cpu_set(tc, mt_fpu_cpumask);
501         }
502
503         /* set up ipi interrupts... */
504
505         /* If we have multiple VPEs running, set up the cross-VPE interrupt */
506
507         if (nvpe > 1)
508                 setup_cross_vpe_interrupts();
509
510         /* Set up queue of free IPI "messages". */
511         nipi = NR_CPUS * IPIBUF_PER_CPU;
512         if (ipibuffers > 0)
513                 nipi = ipibuffers;
514
515         pipi = kmalloc(nipi *sizeof(struct smtc_ipi), GFP_KERNEL);
516         if (pipi == NULL)
517                 panic("kmalloc of IPI message buffers failed\n");
518         else
519                 printk("IPI buffer pool of %d buffers\n", nipi);
520         for (i = 0; i < nipi; i++) {
521                 smtc_ipi_nq(&freeIPIq, pipi);
522                 pipi++;
523         }
524
525         /* Arm multithreading and enable other VPEs - but all TCs are Halted */
526         emt(EMT_ENABLE);
527         evpe(EVPE_ENABLE);
528         local_irq_restore(flags);
529         /* Initialize SMTC /proc statistics/diagnostics */
530         init_smtc_stats();
531 }
532
533
534 /*
535  * Setup the PC, SP, and GP of a secondary processor and start it
536  * running!
537  * smp_bootstrap is the place to resume from
538  * __KSTK_TOS(idle) is apparently the stack pointer
539  * (unsigned long)idle->thread_info the gp
540  *
541  */
542 void smtc_boot_secondary(int cpu, struct task_struct *idle)
543 {
544         extern u32 kernelsp[NR_CPUS];
545         long flags;
546         int mtflags;
547
548         LOCK_MT_PRA();
549         if (cpu_data[cpu].vpe_id != cpu_data[smp_processor_id()].vpe_id) {
550                 dvpe();
551         }
552         settc(cpu_data[cpu].tc_id);
553
554         /* pc */
555         write_tc_c0_tcrestart((unsigned long)&smp_bootstrap);
556
557         /* stack pointer */
558         kernelsp[cpu] = __KSTK_TOS(idle);
559         write_tc_gpr_sp(__KSTK_TOS(idle));
560
561         /* global pointer */
562         write_tc_gpr_gp((unsigned long)idle->thread_info);
563
564         smtc_status |= SMTC_MTC_ACTIVE;
565         write_tc_c0_tchalt(0);
566         if (cpu_data[cpu].vpe_id != cpu_data[smp_processor_id()].vpe_id) {
567                 evpe(EVPE_ENABLE);
568         }
569         UNLOCK_MT_PRA();
570 }
571
572 void smtc_init_secondary(void)
573 {
574         /*
575          * Start timer on secondary VPEs if necessary.
576          * plat_timer_setup has already have been invoked by init/main
577          * on "boot" TC.  Like per_cpu_trap_init() hack, this assumes that
578          * SMTC init code assigns TCs consdecutively and in ascending order
579          * to across available VPEs.
580          */
581         if (((read_c0_tcbind() & TCBIND_CURTC) != 0) &&
582             ((read_c0_tcbind() & TCBIND_CURVPE)
583             != cpu_data[smp_processor_id() - 1].vpe_id)){
584                 write_c0_compare (read_c0_count() + mips_hpt_frequency/HZ);
585         }
586
587         local_irq_enable();
588 }
589
590 void smtc_smp_finish(void)
591 {
592         printk("TC %d going on-line as CPU %d\n",
593                 cpu_data[smp_processor_id()].tc_id, smp_processor_id());
594 }
595
596 void smtc_cpus_done(void)
597 {
598 }
599
600 /*
601  * Support for SMTC-optimized driver IRQ registration
602  */
603
604 /*
605  * SMTC Kernel needs to manipulate low-level CPU interrupt mask
606  * in do_IRQ. These are passed in setup_irq_smtc() and stored
607  * in this table.
608  */
609
610 int setup_irq_smtc(unsigned int irq, struct irqaction * new,
611                         unsigned long hwmask)
612 {
613         irq_hwmask[irq] = hwmask;
614
615         return setup_irq(irq, new);
616 }
617
618 /*
619  * IPI model for SMTC is tricky, because interrupts aren't TC-specific.
620  * Within a VPE one TC can interrupt another by different approaches.
621  * The easiest to get right would probably be to make all TCs except
622  * the target IXMT and set a software interrupt, but an IXMT-based
623  * scheme requires that a handler must run before a new IPI could
624  * be sent, which would break the "broadcast" loops in MIPS MT.
625  * A more gonzo approach within a VPE is to halt the TC, extract
626  * its Restart, Status, and a couple of GPRs, and program the Restart
627  * address to emulate an interrupt.
628  *
629  * Within a VPE, one can be confident that the target TC isn't in
630  * a critical EXL state when halted, since the write to the Halt
631  * register could not have issued on the writing thread if the
632  * halting thread had EXL set. So k0 and k1 of the target TC
633  * can be used by the injection code.  Across VPEs, one can't
634  * be certain that the target TC isn't in a critical exception
635  * state. So we try a two-step process of sending a software
636  * interrupt to the target VPE, which either handles the event
637  * itself (if it was the target) or injects the event within
638  * the VPE.
639  */
640
641 void smtc_ipi_qdump(void)
642 {
643         int i;
644
645         for (i = 0; i < NR_CPUS ;i++) {
646                 printk("IPIQ[%d]: head = 0x%x, tail = 0x%x, depth = %d\n",
647                         i, (unsigned)IPIQ[i].head, (unsigned)IPIQ[i].tail,
648                         IPIQ[i].depth);
649         }
650 }
651
652 /*
653  * The standard atomic.h primitives don't quite do what we want
654  * here: We need an atomic add-and-return-previous-value (which
655  * could be done with atomic_add_return and a decrement) and an
656  * atomic set/zero-and-return-previous-value (which can't really
657  * be done with the atomic.h primitives). And since this is
658  * MIPS MT, we can assume that we have LL/SC.
659  */
660 static __inline__ int atomic_postincrement(unsigned int *pv)
661 {
662         unsigned long result;
663
664         unsigned long temp;
665
666         __asm__ __volatile__(
667         "1:     ll      %0, %2                                  \n"
668         "       addu    %1, %0, 1                               \n"
669         "       sc      %1, %2                                  \n"
670         "       beqz    %1, 1b                                  \n"
671         "       sync                                            \n"
672         : "=&r" (result), "=&r" (temp), "=m" (*pv)
673         : "m" (*pv)
674         : "memory");
675
676         return result;
677 }
678
679 /* No longer used in IPI dispatch, but retained for future recycling */
680
681 static __inline__ int atomic_postclear(unsigned int *pv)
682 {
683         unsigned long result;
684
685         unsigned long temp;
686
687         __asm__ __volatile__(
688         "1:     ll      %0, %2                                  \n"
689         "       or      %1, $0, $0                              \n"
690         "       sc      %1, %2                                  \n"
691         "       beqz    %1, 1b                                  \n"
692         "       sync                                            \n"
693         : "=&r" (result), "=&r" (temp), "=m" (*pv)
694         : "m" (*pv)
695         : "memory");
696
697         return result;
698 }
699
700
701 void smtc_send_ipi(int cpu, int type, unsigned int action)
702 {
703         int tcstatus;
704         struct smtc_ipi *pipi;
705         long flags;
706         int mtflags;
707
708         if (cpu == smp_processor_id()) {
709                 printk("Cannot Send IPI to self!\n");
710                 return;
711         }
712         /* Set up a descriptor, to be delivered either promptly or queued */
713         pipi = smtc_ipi_dq(&freeIPIq);
714         if (pipi == NULL) {
715                 bust_spinlocks(1);
716                 mips_mt_regdump(dvpe());
717                 panic("IPI Msg. Buffers Depleted\n");
718         }
719         pipi->type = type;
720         pipi->arg = (void *)action;
721         pipi->dest = cpu;
722         if (cpu_data[cpu].vpe_id != cpu_data[smp_processor_id()].vpe_id) {
723                 /* If not on same VPE, enqueue and send cross-VPE interupt */
724                 smtc_ipi_nq(&IPIQ[cpu], pipi);
725                 LOCK_CORE_PRA();
726                 settc(cpu_data[cpu].tc_id);
727                 write_vpe_c0_cause(read_vpe_c0_cause() | C_SW1);
728                 UNLOCK_CORE_PRA();
729         } else {
730                 /*
731                  * Not sufficient to do a LOCK_MT_PRA (dmt) here,
732                  * since ASID shootdown on the other VPE may
733                  * collide with this operation.
734                  */
735                 LOCK_CORE_PRA();
736                 settc(cpu_data[cpu].tc_id);
737                 /* Halt the targeted TC */
738                 write_tc_c0_tchalt(TCHALT_H);
739                 mips_ihb();
740
741                 /*
742                  * Inspect TCStatus - if IXMT is set, we have to queue
743                  * a message. Otherwise, we set up the "interrupt"
744                  * of the other TC
745                  */
746                 tcstatus = read_tc_c0_tcstatus();
747
748                 if ((tcstatus & TCSTATUS_IXMT) != 0) {
749                         /*
750                          * Spin-waiting here can deadlock,
751                          * so we queue the message for the target TC.
752                          */
753                         write_tc_c0_tchalt(0);
754                         UNLOCK_CORE_PRA();
755                         /* Try to reduce redundant timer interrupt messages */
756                         if (type == SMTC_CLOCK_TICK) {
757                             if (atomic_postincrement(&ipi_timer_latch[cpu])!=0){
758                                 smtc_ipi_nq(&freeIPIq, pipi);
759                                 return;
760                             }
761                         }
762                         smtc_ipi_nq(&IPIQ[cpu], pipi);
763                 } else {
764                         post_direct_ipi(cpu, pipi);
765                         write_tc_c0_tchalt(0);
766                         UNLOCK_CORE_PRA();
767                 }
768         }
769 }
770
771 /*
772  * Send IPI message to Halted TC, TargTC/TargVPE already having been set
773  */
774 void post_direct_ipi(int cpu, struct smtc_ipi *pipi)
775 {
776         struct pt_regs *kstack;
777         unsigned long tcstatus;
778         unsigned long tcrestart;
779         extern u32 kernelsp[NR_CPUS];
780         extern void __smtc_ipi_vector(void);
781
782         /* Extract Status, EPC from halted TC */
783         tcstatus = read_tc_c0_tcstatus();
784         tcrestart = read_tc_c0_tcrestart();
785         /* If TCRestart indicates a WAIT instruction, advance the PC */
786         if ((tcrestart & 0x80000000)
787             && ((*(unsigned int *)tcrestart & 0xfe00003f) == 0x42000020)) {
788                 tcrestart += 4;
789         }
790         /*
791          * Save on TC's future kernel stack
792          *
793          * CU bit of Status is indicator that TC was
794          * already running on a kernel stack...
795          */
796         if (tcstatus & ST0_CU0)  {
797                 /* Note that this "- 1" is pointer arithmetic */
798                 kstack = ((struct pt_regs *)read_tc_gpr_sp()) - 1;
799         } else {
800                 kstack = ((struct pt_regs *)kernelsp[cpu]) - 1;
801         }
802
803         kstack->cp0_epc = (long)tcrestart;
804         /* Save TCStatus */
805         kstack->cp0_tcstatus = tcstatus;
806         /* Pass token of operation to be performed kernel stack pad area */
807         kstack->pad0[4] = (unsigned long)pipi;
808         /* Pass address of function to be called likewise */
809         kstack->pad0[5] = (unsigned long)&ipi_decode;
810         /* Set interrupt exempt and kernel mode */
811         tcstatus |= TCSTATUS_IXMT;
812         tcstatus &= ~TCSTATUS_TKSU;
813         write_tc_c0_tcstatus(tcstatus);
814         ehb();
815         /* Set TC Restart address to be SMTC IPI vector */
816         write_tc_c0_tcrestart(__smtc_ipi_vector);
817 }
818
819 static void ipi_resched_interrupt(void)
820 {
821         /* Return from interrupt should be enough to cause scheduler check */
822 }
823
824
825 static void ipi_call_interrupt(void)
826 {
827         /* Invoke generic function invocation code in smp.c */
828         smp_call_function_interrupt();
829 }
830
831 void ipi_decode(struct smtc_ipi *pipi)
832 {
833         void *arg_copy = pipi->arg;
834         int type_copy = pipi->type;
835         int dest_copy = pipi->dest;
836
837         smtc_ipi_nq(&freeIPIq, pipi);
838         switch (type_copy) {
839         case SMTC_CLOCK_TICK:
840                 /* Invoke Clock "Interrupt" */
841                 ipi_timer_latch[dest_copy] = 0;
842 #ifdef SMTC_IDLE_HOOK_DEBUG
843                 clock_hang_reported[dest_copy] = 0;
844 #endif /* SMTC_IDLE_HOOK_DEBUG */
845                 local_timer_interrupt(0, NULL);
846                 break;
847         case LINUX_SMP_IPI:
848                 switch ((int)arg_copy) {
849                 case SMP_RESCHEDULE_YOURSELF:
850                         ipi_resched_interrupt();
851                         break;
852                 case SMP_CALL_FUNCTION:
853                         ipi_call_interrupt();
854                         break;
855                 default:
856                         printk("Impossible SMTC IPI Argument 0x%x\n",
857                                 (int)arg_copy);
858                         break;
859                 }
860                 break;
861         default:
862                 printk("Impossible SMTC IPI Type 0x%x\n", type_copy);
863                 break;
864         }
865 }
866
867 void deferred_smtc_ipi(void)
868 {
869         struct smtc_ipi *pipi;
870         unsigned long flags;
871 /* DEBUG */
872         int q = smp_processor_id();
873
874         /*
875          * Test is not atomic, but much faster than a dequeue,
876          * and the vast majority of invocations will have a null queue.
877          */
878         if (IPIQ[q].head != NULL) {
879                 while((pipi = smtc_ipi_dq(&IPIQ[q])) != NULL) {
880                         /* ipi_decode() should be called with interrupts off */
881                         local_irq_save(flags);
882                         ipi_decode(pipi);
883                         local_irq_restore(flags);
884                 }
885         }
886 }
887
888 /*
889  * Send clock tick to all TCs except the one executing the funtion
890  */
891
892 void smtc_timer_broadcast(int vpe)
893 {
894         int cpu;
895         int myTC = cpu_data[smp_processor_id()].tc_id;
896         int myVPE = cpu_data[smp_processor_id()].vpe_id;
897
898         smtc_cpu_stats[smp_processor_id()].timerints++;
899
900         for_each_online_cpu(cpu) {
901                 if (cpu_data[cpu].vpe_id == myVPE &&
902                     cpu_data[cpu].tc_id != myTC)
903                         smtc_send_ipi(cpu, SMTC_CLOCK_TICK, 0);
904         }
905 }
906
907 /*
908  * Cross-VPE interrupts in the SMTC prototype use "software interrupts"
909  * set via cross-VPE MTTR manipulation of the Cause register. It would be
910  * in some regards preferable to have external logic for "doorbell" hardware
911  * interrupts.
912  */
913
914 static int cpu_ipi_irq = MIPS_CPU_IRQ_BASE + MIPS_CPU_IPI_IRQ;
915
916 static irqreturn_t ipi_interrupt(int irq, void *dev_idm)
917 {
918         int my_vpe = cpu_data[smp_processor_id()].vpe_id;
919         int my_tc = cpu_data[smp_processor_id()].tc_id;
920         int cpu;
921         struct smtc_ipi *pipi;
922         unsigned long tcstatus;
923         int sent;
924         long flags;
925         unsigned int mtflags;
926         unsigned int vpflags;
927
928         /*
929          * So long as cross-VPE interrupts are done via
930          * MFTR/MTTR read-modify-writes of Cause, we need
931          * to stop other VPEs whenever the local VPE does
932          * anything similar.
933          */
934         local_irq_save(flags);
935         vpflags = dvpe();
936         clear_c0_cause(0x100 << MIPS_CPU_IPI_IRQ);
937         set_c0_status(0x100 << MIPS_CPU_IPI_IRQ);
938         irq_enable_hazard();
939         evpe(vpflags);
940         local_irq_restore(flags);
941
942         /*
943          * Cross-VPE Interrupt handler: Try to directly deliver IPIs
944          * queued for TCs on this VPE other than the current one.
945          * Return-from-interrupt should cause us to drain the queue
946          * for the current TC, so we ought not to have to do it explicitly here.
947          */
948
949         for_each_online_cpu(cpu) {
950                 if (cpu_data[cpu].vpe_id != my_vpe)
951                         continue;
952
953                 pipi = smtc_ipi_dq(&IPIQ[cpu]);
954                 if (pipi != NULL) {
955                         if (cpu_data[cpu].tc_id != my_tc) {
956                                 sent = 0;
957                                 LOCK_MT_PRA();
958                                 settc(cpu_data[cpu].tc_id);
959                                 write_tc_c0_tchalt(TCHALT_H);
960                                 mips_ihb();
961                                 tcstatus = read_tc_c0_tcstatus();
962                                 if ((tcstatus & TCSTATUS_IXMT) == 0) {
963                                         post_direct_ipi(cpu, pipi);
964                                         sent = 1;
965                                 }
966                                 write_tc_c0_tchalt(0);
967                                 UNLOCK_MT_PRA();
968                                 if (!sent) {
969                                         smtc_ipi_req(&IPIQ[cpu], pipi);
970                                 }
971                         } else {
972                                 /*
973                                  * ipi_decode() should be called
974                                  * with interrupts off
975                                  */
976                                 local_irq_save(flags);
977                                 ipi_decode(pipi);
978                                 local_irq_restore(flags);
979                         }
980                 }
981         }
982
983         return IRQ_HANDLED;
984 }
985
986 static void ipi_irq_dispatch(void)
987 {
988         do_IRQ(cpu_ipi_irq);
989 }
990
991 static struct irqaction irq_ipi;
992
993 void setup_cross_vpe_interrupts(void)
994 {
995         if (!cpu_has_vint)
996                 panic("SMTC Kernel requires Vectored Interupt support");
997
998         set_vi_handler(MIPS_CPU_IPI_IRQ, ipi_irq_dispatch);
999
1000         irq_ipi.handler = ipi_interrupt;
1001         irq_ipi.flags = IRQF_DISABLED;
1002         irq_ipi.name = "SMTC_IPI";
1003
1004         setup_irq_smtc(cpu_ipi_irq, &irq_ipi, (0x100 << MIPS_CPU_IPI_IRQ));
1005
1006         irq_desc[cpu_ipi_irq].status |= IRQ_PER_CPU;
1007         set_irq_handler(cpu_ipi_irq, handle_percpu_irq);
1008 }
1009
1010 /*
1011  * SMTC-specific hacks invoked from elsewhere in the kernel.
1012  */
1013
1014 void smtc_ipi_replay(void)
1015 {
1016         /*
1017          * To the extent that we've ever turned interrupts off,
1018          * we may have accumulated deferred IPIs.  This is subtle.
1019          * If we use the smtc_ipi_qdepth() macro, we'll get an
1020          * exact number - but we'll also disable interrupts
1021          * and create a window of failure where a new IPI gets
1022          * queued after we test the depth but before we re-enable
1023          * interrupts. So long as IXMT never gets set, however,
1024          * we should be OK:  If we pick up something and dispatch
1025          * it here, that's great. If we see nothing, but concurrent
1026          * with this operation, another TC sends us an IPI, IXMT
1027          * is clear, and we'll handle it as a real pseudo-interrupt
1028          * and not a pseudo-pseudo interrupt.
1029          */
1030         if (IPIQ[smp_processor_id()].depth > 0) {
1031                 struct smtc_ipi *pipi;
1032                 extern void self_ipi(struct smtc_ipi *);
1033
1034                 while ((pipi = smtc_ipi_dq(&IPIQ[smp_processor_id()]))) {
1035                         self_ipi(pipi);
1036                         smtc_cpu_stats[smp_processor_id()].selfipis++;
1037                 }
1038         }
1039 }
1040
1041 EXPORT_SYMBOL(smtc_ipi_replay);
1042
1043 void smtc_idle_loop_hook(void)
1044 {
1045 #ifdef SMTC_IDLE_HOOK_DEBUG
1046         int im;
1047         int flags;
1048         int mtflags;
1049         int bit;
1050         int vpe;
1051         int tc;
1052         int hook_ntcs;
1053         /*
1054          * printk within DMT-protected regions can deadlock,
1055          * so buffer diagnostic messages for later output.
1056          */
1057         char *pdb_msg;
1058         char id_ho_db_msg[768]; /* worst-case use should be less than 700 */
1059
1060         if (atomic_read(&idle_hook_initialized) == 0) { /* fast test */
1061                 if (atomic_add_return(1, &idle_hook_initialized) == 1) {
1062                         int mvpconf0;
1063                         /* Tedious stuff to just do once */
1064                         mvpconf0 = read_c0_mvpconf0();
1065                         hook_ntcs = ((mvpconf0 & MVPCONF0_PTC) >> MVPCONF0_PTC_SHIFT) + 1;
1066                         if (hook_ntcs > NR_CPUS)
1067                                 hook_ntcs = NR_CPUS;
1068                         for (tc = 0; tc < hook_ntcs; tc++) {
1069                                 tcnoprog[tc] = 0;
1070                                 clock_hang_reported[tc] = 0;
1071                         }
1072                         for (vpe = 0; vpe < 2; vpe++)
1073                                 for (im = 0; im < 8; im++)
1074                                         imstuckcount[vpe][im] = 0;
1075                         printk("Idle loop test hook initialized for %d TCs\n", hook_ntcs);
1076                         atomic_set(&idle_hook_initialized, 1000);
1077                 } else {
1078                         /* Someone else is initializing in parallel - let 'em finish */
1079                         while (atomic_read(&idle_hook_initialized) < 1000)
1080                                 ;
1081                 }
1082         }
1083
1084         /* Have we stupidly left IXMT set somewhere? */
1085         if (read_c0_tcstatus() & 0x400) {
1086                 write_c0_tcstatus(read_c0_tcstatus() & ~0x400);
1087                 ehb();
1088                 printk("Dangling IXMT in cpu_idle()\n");
1089         }
1090
1091         /* Have we stupidly left an IM bit turned off? */
1092 #define IM_LIMIT 2000
1093         local_irq_save(flags);
1094         mtflags = dmt();
1095         pdb_msg = &id_ho_db_msg[0];
1096         im = read_c0_status();
1097         vpe = cpu_data[smp_processor_id()].vpe_id;
1098         for (bit = 0; bit < 8; bit++) {
1099                 /*
1100                  * In current prototype, I/O interrupts
1101                  * are masked for VPE > 0
1102                  */
1103                 if (vpemask[vpe][bit]) {
1104                         if (!(im & (0x100 << bit)))
1105                                 imstuckcount[vpe][bit]++;
1106                         else
1107                                 imstuckcount[vpe][bit] = 0;
1108                         if (imstuckcount[vpe][bit] > IM_LIMIT) {
1109                                 set_c0_status(0x100 << bit);
1110                                 ehb();
1111                                 imstuckcount[vpe][bit] = 0;
1112                                 pdb_msg += sprintf(pdb_msg,
1113                                         "Dangling IM %d fixed for VPE %d\n", bit,
1114                                         vpe);
1115                         }
1116                 }
1117         }
1118
1119         /*
1120          * Now that we limit outstanding timer IPIs, check for hung TC
1121          */
1122         for (tc = 0; tc < NR_CPUS; tc++) {
1123                 /* Don't check ourself - we'll dequeue IPIs just below */
1124                 if ((tc != smp_processor_id()) &&
1125                     ipi_timer_latch[tc] > timerq_limit) {
1126                     if (clock_hang_reported[tc] == 0) {
1127                         pdb_msg += sprintf(pdb_msg,
1128                                 "TC %d looks hung with timer latch at %d\n",
1129                                 tc, ipi_timer_latch[tc]);
1130                         clock_hang_reported[tc]++;
1131                         }
1132                 }
1133         }
1134         emt(mtflags);
1135         local_irq_restore(flags);
1136         if (pdb_msg != &id_ho_db_msg[0])
1137                 printk("CPU%d: %s", smp_processor_id(), id_ho_db_msg);
1138 #endif /* SMTC_IDLE_HOOK_DEBUG */
1139
1140         /*
1141          * Replay any accumulated deferred IPIs. If "Instant Replay"
1142          * is in use, there should never be any.
1143          */
1144 #ifndef CONFIG_MIPS_MT_SMTC_INSTANT_REPLAY
1145         smtc_ipi_replay();
1146 #endif /* CONFIG_MIPS_MT_SMTC_INSTANT_REPLAY */
1147 }
1148
1149 void smtc_soft_dump(void)
1150 {
1151         int i;
1152
1153         printk("Counter Interrupts taken per CPU (TC)\n");
1154         for (i=0; i < NR_CPUS; i++) {
1155                 printk("%d: %ld\n", i, smtc_cpu_stats[i].timerints);
1156         }
1157         printk("Self-IPI invocations:\n");
1158         for (i=0; i < NR_CPUS; i++) {
1159                 printk("%d: %ld\n", i, smtc_cpu_stats[i].selfipis);
1160         }
1161         smtc_ipi_qdump();
1162         printk("Timer IPI Backlogs:\n");
1163         for (i=0; i < NR_CPUS; i++) {
1164                 printk("%d: %d\n", i, ipi_timer_latch[i]);
1165         }
1166         printk("%d Recoveries of \"stolen\" FPU\n",
1167                atomic_read(&smtc_fpu_recoveries));
1168 }
1169
1170
1171 /*
1172  * TLB management routines special to SMTC
1173  */
1174
1175 void smtc_get_new_mmu_context(struct mm_struct *mm, unsigned long cpu)
1176 {
1177         unsigned long flags, mtflags, tcstat, prevhalt, asid;
1178         int tlb, i;
1179
1180         /*
1181          * It would be nice to be able to use a spinlock here,
1182          * but this is invoked from within TLB flush routines
1183          * that protect themselves with DVPE, so if a lock is
1184          * held by another TC, it'll never be freed.
1185          *
1186          * DVPE/DMT must not be done with interrupts enabled,
1187          * so even so most callers will already have disabled
1188          * them, let's be really careful...
1189          */
1190
1191         local_irq_save(flags);
1192         if (smtc_status & SMTC_TLB_SHARED) {
1193                 mtflags = dvpe();
1194                 tlb = 0;
1195         } else {
1196                 mtflags = dmt();
1197                 tlb = cpu_data[cpu].vpe_id;
1198         }
1199         asid = asid_cache(cpu);
1200
1201         do {
1202                 if (!((asid += ASID_INC) & ASID_MASK) ) {
1203                         if (cpu_has_vtag_icache)
1204                                 flush_icache_all();
1205                         /* Traverse all online CPUs (hack requires contigous range) */
1206                         for (i = 0; i < num_online_cpus(); i++) {
1207                                 /*
1208                                  * We don't need to worry about our own CPU, nor those of
1209                                  * CPUs who don't share our TLB.
1210                                  */
1211                                 if ((i != smp_processor_id()) &&
1212                                     ((smtc_status & SMTC_TLB_SHARED) ||
1213                                      (cpu_data[i].vpe_id == cpu_data[cpu].vpe_id))) {
1214                                         settc(cpu_data[i].tc_id);
1215                                         prevhalt = read_tc_c0_tchalt() & TCHALT_H;
1216                                         if (!prevhalt) {
1217                                                 write_tc_c0_tchalt(TCHALT_H);
1218                                                 mips_ihb();
1219                                         }
1220                                         tcstat = read_tc_c0_tcstatus();
1221                                         smtc_live_asid[tlb][(tcstat & ASID_MASK)] |= (asiduse)(0x1 << i);
1222                                         if (!prevhalt)
1223                                                 write_tc_c0_tchalt(0);
1224                                 }
1225                         }
1226                         if (!asid)              /* fix version if needed */
1227                                 asid = ASID_FIRST_VERSION;
1228                         local_flush_tlb_all();  /* start new asid cycle */
1229                 }
1230         } while (smtc_live_asid[tlb][(asid & ASID_MASK)]);
1231
1232         /*
1233          * SMTC shares the TLB within VPEs and possibly across all VPEs.
1234          */
1235         for (i = 0; i < num_online_cpus(); i++) {
1236                 if ((smtc_status & SMTC_TLB_SHARED) ||
1237                     (cpu_data[i].vpe_id == cpu_data[cpu].vpe_id))
1238                         cpu_context(i, mm) = asid_cache(i) = asid;
1239         }
1240
1241         if (smtc_status & SMTC_TLB_SHARED)
1242                 evpe(mtflags);
1243         else
1244                 emt(mtflags);
1245         local_irq_restore(flags);
1246 }
1247
1248 /*
1249  * Invoked from macros defined in mmu_context.h
1250  * which must already have disabled interrupts
1251  * and done a DVPE or DMT as appropriate.
1252  */
1253
1254 void smtc_flush_tlb_asid(unsigned long asid)
1255 {
1256         int entry;
1257         unsigned long ehi;
1258
1259         entry = read_c0_wired();
1260
1261         /* Traverse all non-wired entries */
1262         while (entry < current_cpu_data.tlbsize) {
1263                 write_c0_index(entry);
1264                 ehb();
1265                 tlb_read();
1266                 ehb();
1267                 ehi = read_c0_entryhi();
1268                 if ((ehi & ASID_MASK) == asid) {
1269                     /*
1270                      * Invalidate only entries with specified ASID,
1271                      * makiing sure all entries differ.
1272                      */
1273                     write_c0_entryhi(CKSEG0 + (entry << (PAGE_SHIFT + 1)));
1274                     write_c0_entrylo0(0);
1275                     write_c0_entrylo1(0);
1276                     mtc0_tlbw_hazard();
1277                     tlb_write_indexed();
1278                 }
1279                 entry++;
1280         }
1281         write_c0_index(PARKED_INDEX);
1282         tlbw_use_hazard();
1283 }
1284
1285 /*
1286  * Support for single-threading cache flush operations.
1287  */
1288
1289 int halt_state_save[NR_CPUS];
1290
1291 /*
1292  * To really, really be sure that nothing is being done
1293  * by other TCs, halt them all.  This code assumes that
1294  * a DVPE has already been done, so while their Halted
1295  * state is theoretically architecturally unstable, in
1296  * practice, it's not going to change while we're looking
1297  * at it.
1298  */
1299
1300 void smtc_cflush_lockdown(void)
1301 {
1302         int cpu;
1303
1304         for_each_online_cpu(cpu) {
1305                 if (cpu != smp_processor_id()) {
1306                         settc(cpu_data[cpu].tc_id);
1307                         halt_state_save[cpu] = read_tc_c0_tchalt();
1308                         write_tc_c0_tchalt(TCHALT_H);
1309                 }
1310         }
1311         mips_ihb();
1312 }
1313
1314 /* It would be cheating to change the cpu_online states during a flush! */
1315
1316 void smtc_cflush_release(void)
1317 {
1318         int cpu;
1319
1320         /*
1321          * Start with a hazard barrier to ensure
1322          * that all CACHE ops have played through.
1323          */
1324         mips_ihb();
1325
1326         for_each_online_cpu(cpu) {
1327                 if (cpu != smp_processor_id()) {
1328                         settc(cpu_data[cpu].tc_id);
1329                         write_tc_c0_tchalt(halt_state_save[cpu]);
1330                 }
1331         }
1332         mips_ihb();
1333 }