ftp://ftp.kernel.org/pub/linux/kernel/v2.6/linux-2.6.6.tar.bz2
[linux-2.6.git] / arch / i386 / kernel / io_apic.c
1 /*
2  *      Intel IO-APIC support for multi-Pentium hosts.
3  *
4  *      Copyright (C) 1997, 1998, 1999, 2000 Ingo Molnar, Hajnalka Szabo
5  *
6  *      Many thanks to Stig Venaas for trying out countless experimental
7  *      patches and reporting/debugging problems patiently!
8  *
9  *      (c) 1999, Multiple IO-APIC support, developed by
10  *      Ken-ichi Yaku <yaku@css1.kbnes.nec.co.jp> and
11  *      Hidemi Kishimoto <kisimoto@css1.kbnes.nec.co.jp>,
12  *      further tested and cleaned up by Zach Brown <zab@redhat.com>
13  *      and Ingo Molnar <mingo@redhat.com>
14  *
15  *      Fixes
16  *      Maciej W. Rozycki       :       Bits for genuine 82489DX APICs;
17  *                                      thanks to Eric Gilmore
18  *                                      and Rolf G. Tews
19  *                                      for testing these extensively
20  *      Paul Diefenbaugh        :       Added full ACPI support
21  */
22
23 #include <linux/mm.h>
24 #include <linux/irq.h>
25 #include <linux/interrupt.h>
26 #include <linux/init.h>
27 #include <linux/delay.h>
28 #include <linux/sched.h>
29 #include <linux/config.h>
30 #include <linux/smp_lock.h>
31 #include <linux/mc146818rtc.h>
32 #include <linux/compiler.h>
33 #include <linux/acpi.h>
34
35 #include <asm/io.h>
36 #include <asm/smp.h>
37 #include <asm/desc.h>
38 #include <asm/timer.h>
39
40 #include <mach_apic.h>
41
42 #include "io_ports.h"
43
44 #undef APIC_LOCKUP_DEBUG
45
46 #define APIC_LOCKUP_DEBUG
47
48 static spinlock_t ioapic_lock = SPIN_LOCK_UNLOCKED;
49
50 /*
51  *      Is the SiS APIC rmw bug present ?
52  *      -1 = don't know, 0 = no, 1 = yes
53  */
54 int sis_apic_bug = -1;
55
56 /*
57  * # of IRQ routing registers
58  */
59 int nr_ioapic_registers[MAX_IO_APICS];
60
61 /*
62  * Rough estimation of how many shared IRQs there are, can
63  * be changed anytime.
64  */
65 #define MAX_PLUS_SHARED_IRQS NR_IRQS
66 #define PIN_MAP_SIZE (MAX_PLUS_SHARED_IRQS + NR_IRQS)
67
68 /*
69  * This is performance-critical, we want to do it O(1)
70  *
71  * the indexing order of this array favors 1:1 mappings
72  * between pins and IRQs.
73  */
74
75 static struct irq_pin_list {
76         int apic, pin, next;
77 } irq_2_pin[PIN_MAP_SIZE];
78
79 int vector_irq[NR_VECTORS] = { [0 ... NR_VECTORS - 1] = -1};
80 #ifdef CONFIG_PCI_USE_VECTOR
81 #define vector_to_irq(vector)   \
82         (platform_legacy_irq(vector) ? vector : vector_irq[vector])
83 #else
84 #define vector_to_irq(vector)   (vector)
85 #endif
86
87 /*
88  * The common case is 1:1 IRQ<->pin mappings. Sometimes there are
89  * shared ISA-space IRQs, so we have to support them. We are super
90  * fast in the common case, and fast for shared ISA-space IRQs.
91  */
92 static void __init add_pin_to_irq(unsigned int irq, int apic, int pin)
93 {
94         static int first_free_entry = NR_IRQS;
95         struct irq_pin_list *entry = irq_2_pin + irq;
96
97         while (entry->next)
98                 entry = irq_2_pin + entry->next;
99
100         if (entry->pin != -1) {
101                 entry->next = first_free_entry;
102                 entry = irq_2_pin + entry->next;
103                 if (++first_free_entry >= PIN_MAP_SIZE)
104                         panic("io_apic.c: whoops");
105         }
106         entry->apic = apic;
107         entry->pin = pin;
108 }
109
110 /*
111  * Reroute an IRQ to a different pin.
112  */
113 static void __init replace_pin_at_irq(unsigned int irq,
114                                       int oldapic, int oldpin,
115                                       int newapic, int newpin)
116 {
117         struct irq_pin_list *entry = irq_2_pin + irq;
118
119         while (1) {
120                 if (entry->apic == oldapic && entry->pin == oldpin) {
121                         entry->apic = newapic;
122                         entry->pin = newpin;
123                 }
124                 if (!entry->next)
125                         break;
126                 entry = irq_2_pin + entry->next;
127         }
128 }
129
130 /* mask = 1 */
131 static void __mask_IO_APIC_irq (unsigned int irq)
132 {
133         int pin;
134         struct irq_pin_list *entry = irq_2_pin + irq;
135
136         for (;;) {
137                 unsigned int reg;
138                 pin = entry->pin;
139                 if (pin == -1)
140                         break;
141                 reg = io_apic_read(entry->apic, 0x10 + pin*2);
142                 io_apic_modify(entry->apic, 0x10 + pin*2, reg |= 0x00010000);
143                 if (!entry->next)
144                         break;
145                 entry = irq_2_pin + entry->next;
146         }
147         io_apic_sync(entry->apic);
148 }
149
150 /* mask = 0 */
151 static void __unmask_IO_APIC_irq (unsigned int irq)
152 {
153         int pin;
154         struct irq_pin_list *entry = irq_2_pin + irq;
155
156         for (;;) {
157                 unsigned int reg;
158                 pin = entry->pin;
159                 if (pin == -1)
160                         break;
161                 reg = io_apic_read(entry->apic, 0x10 + pin*2);
162                 io_apic_modify(entry->apic, 0x10 + pin*2, reg &= 0xfffeffff);
163                 if (!entry->next)
164                         break;
165                 entry = irq_2_pin + entry->next;
166         }
167 }
168
169 /* mask = 1, trigger = 0 */
170 static void __mask_and_edge_IO_APIC_irq (unsigned int irq)
171 {
172         int pin;
173         struct irq_pin_list *entry = irq_2_pin + irq;
174
175         for (;;) {
176                 unsigned int reg;
177                 pin = entry->pin;
178                 if (pin == -1)
179                         break;
180                 reg = io_apic_read(entry->apic, 0x10 + pin*2);
181                 reg = (reg & 0xffff7fff) | 0x00010000;
182                 io_apic_modify(entry->apic, 0x10 + pin*2, reg);
183                 if (!entry->next)
184                         break;
185                 entry = irq_2_pin + entry->next;
186         }
187 }
188
189 /* mask = 0, trigger = 1 */
190 static void __unmask_and_level_IO_APIC_irq (unsigned int irq)
191 {
192         int pin;
193         struct irq_pin_list *entry = irq_2_pin + irq;
194
195         for (;;) {
196                 unsigned int reg;
197                 pin = entry->pin;
198                 if (pin == -1)
199                         break;
200                 reg = io_apic_read(entry->apic, 0x10 + pin*2);
201                 reg = (reg & 0xfffeffff) | 0x00008000;
202                 io_apic_modify(entry->apic, 0x10 + pin*2, reg);
203                 if (!entry->next)
204                         break;
205                 entry = irq_2_pin + entry->next;
206         }
207 }
208
209 static void mask_IO_APIC_irq (unsigned int irq)
210 {
211         unsigned long flags;
212
213         spin_lock_irqsave(&ioapic_lock, flags);
214         __mask_IO_APIC_irq(irq);
215         spin_unlock_irqrestore(&ioapic_lock, flags);
216 }
217
218 static void unmask_IO_APIC_irq (unsigned int irq)
219 {
220         unsigned long flags;
221
222         spin_lock_irqsave(&ioapic_lock, flags);
223         __unmask_IO_APIC_irq(irq);
224         spin_unlock_irqrestore(&ioapic_lock, flags);
225 }
226
227 void clear_IO_APIC_pin(unsigned int apic, unsigned int pin)
228 {
229         struct IO_APIC_route_entry entry;
230         unsigned long flags;
231         
232         /* Check delivery_mode to be sure we're not clearing an SMI pin */
233         spin_lock_irqsave(&ioapic_lock, flags);
234         *(((int*)&entry) + 0) = io_apic_read(apic, 0x10 + 2 * pin);
235         *(((int*)&entry) + 1) = io_apic_read(apic, 0x11 + 2 * pin);
236         spin_unlock_irqrestore(&ioapic_lock, flags);
237         if (entry.delivery_mode == dest_SMI)
238                 return;
239
240         /*
241          * Disable it in the IO-APIC irq-routing table:
242          */
243         memset(&entry, 0, sizeof(entry));
244         entry.mask = 1;
245         spin_lock_irqsave(&ioapic_lock, flags);
246         io_apic_write(apic, 0x10 + 2 * pin, *(((int *)&entry) + 0));
247         io_apic_write(apic, 0x11 + 2 * pin, *(((int *)&entry) + 1));
248         spin_unlock_irqrestore(&ioapic_lock, flags);
249 }
250
251 static void clear_IO_APIC (void)
252 {
253         int apic, pin;
254
255         for (apic = 0; apic < nr_ioapics; apic++)
256                 for (pin = 0; pin < nr_ioapic_registers[apic]; pin++)
257                         clear_IO_APIC_pin(apic, pin);
258 }
259
260 static void set_ioapic_affinity_irq(unsigned int irq, cpumask_t cpumask)
261 {
262         unsigned long flags;
263         int pin;
264         struct irq_pin_list *entry = irq_2_pin + irq;
265         unsigned int apicid_value;
266         
267         apicid_value = cpu_mask_to_apicid(mk_cpumask_const(cpumask));
268         /* Prepare to do the io_apic_write */
269         apicid_value = apicid_value << 24;
270         spin_lock_irqsave(&ioapic_lock, flags);
271         for (;;) {
272                 pin = entry->pin;
273                 if (pin == -1)
274                         break;
275                 io_apic_write(entry->apic, 0x10 + 1 + pin*2, apicid_value);
276                 if (!entry->next)
277                         break;
278                 entry = irq_2_pin + entry->next;
279         }
280         spin_unlock_irqrestore(&ioapic_lock, flags);
281 }
282
283 #if defined(CONFIG_IRQBALANCE)
284 # include <asm/processor.h>     /* kernel_thread() */
285 # include <linux/kernel_stat.h> /* kstat */
286 # include <linux/slab.h>                /* kmalloc() */
287 # include <linux/timer.h>       /* time_after() */
288  
289 # ifdef CONFIG_BALANCED_IRQ_DEBUG
290 #  define TDprintk(x...) do { printk("<%ld:%s:%d>: ", jiffies, __FILE__, __LINE__); printk(x); } while (0)
291 #  define Dprintk(x...) do { TDprintk(x); } while (0)
292 # else
293 #  define TDprintk(x...) 
294 #  define Dprintk(x...) 
295 # endif
296
297 extern cpumask_t irq_affinity[NR_IRQS];
298
299 cpumask_t __cacheline_aligned pending_irq_balance_cpumask[NR_IRQS];
300
301 #define IRQBALANCE_CHECK_ARCH -999
302 static int irqbalance_disabled = IRQBALANCE_CHECK_ARCH;
303 static int physical_balance = 0;
304
305 struct irq_cpu_info {
306         unsigned long * last_irq;
307         unsigned long * irq_delta;
308         unsigned long irq;
309 } irq_cpu_data[NR_CPUS];
310
311 #define CPU_IRQ(cpu)            (irq_cpu_data[cpu].irq)
312 #define LAST_CPU_IRQ(cpu,irq)   (irq_cpu_data[cpu].last_irq[irq])
313 #define IRQ_DELTA(cpu,irq)      (irq_cpu_data[cpu].irq_delta[irq])
314
315 #define IDLE_ENOUGH(cpu,now) \
316                 (idle_cpu(cpu) && ((now) - irq_stat[(cpu)].idle_timestamp > 1))
317
318 #define IRQ_ALLOWED(cpu, allowed_mask)  cpu_isset(cpu, allowed_mask)
319
320 #define CPU_TO_PACKAGEINDEX(i) \
321                 ((physical_balance && i > cpu_sibling_map[i]) ? cpu_sibling_map[i] : i)
322
323 #define MAX_BALANCED_IRQ_INTERVAL       (5*HZ)
324 #define MIN_BALANCED_IRQ_INTERVAL       (HZ/2)
325 #define BALANCED_IRQ_MORE_DELTA         (HZ/10)
326 #define BALANCED_IRQ_LESS_DELTA         (HZ)
327
328 long balanced_irq_interval = MAX_BALANCED_IRQ_INTERVAL;
329
330 static unsigned long move(int curr_cpu, cpumask_t allowed_mask,
331                         unsigned long now, int direction)
332 {
333         int search_idle = 1;
334         int cpu = curr_cpu;
335
336         goto inside;
337
338         do {
339                 if (unlikely(cpu == curr_cpu))
340                         search_idle = 0;
341 inside:
342                 if (direction == 1) {
343                         cpu++;
344                         if (cpu >= NR_CPUS)
345                                 cpu = 0;
346                 } else {
347                         cpu--;
348                         if (cpu == -1)
349                                 cpu = NR_CPUS-1;
350                 }
351         } while (!cpu_online(cpu) || !IRQ_ALLOWED(cpu,allowed_mask) ||
352                         (search_idle && !IDLE_ENOUGH(cpu,now)));
353
354         return cpu;
355 }
356
357 static inline void balance_irq(int cpu, int irq)
358 {
359         unsigned long now = jiffies;
360         cpumask_t allowed_mask;
361         unsigned int new_cpu;
362                 
363         if (irqbalance_disabled)
364                 return; 
365
366         cpus_and(allowed_mask, cpu_online_map, irq_affinity[irq]);
367         new_cpu = move(cpu, allowed_mask, now, 1);
368         if (cpu != new_cpu) {
369                 irq_desc_t *desc = irq_desc + irq;
370                 unsigned long flags;
371
372                 spin_lock_irqsave(&desc->lock, flags);
373                 pending_irq_balance_cpumask[irq] = cpumask_of_cpu(new_cpu);
374                 spin_unlock_irqrestore(&desc->lock, flags);
375         }
376 }
377
378 static inline void rotate_irqs_among_cpus(unsigned long useful_load_threshold)
379 {
380         int i, j;
381         Dprintk("Rotating IRQs among CPUs.\n");
382         for (i = 0; i < NR_CPUS; i++) {
383                 for (j = 0; cpu_online(i) && (j < NR_IRQS); j++) {
384                         if (!irq_desc[j].action)
385                                 continue;
386                         /* Is it a significant load ?  */
387                         if (IRQ_DELTA(CPU_TO_PACKAGEINDEX(i),j) <
388                                                 useful_load_threshold)
389                                 continue;
390                         balance_irq(i, j);
391                 }
392         }
393         balanced_irq_interval = max((long)MIN_BALANCED_IRQ_INTERVAL,
394                 balanced_irq_interval - BALANCED_IRQ_LESS_DELTA);       
395         return;
396 }
397
398 static void do_irq_balance(void)
399 {
400         int i, j;
401         unsigned long max_cpu_irq = 0, min_cpu_irq = (~0);
402         unsigned long move_this_load = 0;
403         int max_loaded = 0, min_loaded = 0;
404         unsigned long useful_load_threshold = balanced_irq_interval + 10;
405         int selected_irq;
406         int tmp_loaded, first_attempt = 1;
407         unsigned long tmp_cpu_irq;
408         unsigned long imbalance = 0;
409         cpumask_t allowed_mask, target_cpu_mask, tmp;
410
411         for (i = 0; i < NR_CPUS; i++) {
412                 int package_index;
413                 CPU_IRQ(i) = 0;
414                 if (!cpu_online(i))
415                         continue;
416                 package_index = CPU_TO_PACKAGEINDEX(i);
417                 for (j = 0; j < NR_IRQS; j++) {
418                         unsigned long value_now, delta;
419                         /* Is this an active IRQ? */
420                         if (!irq_desc[j].action)
421                                 continue;
422                         if ( package_index == i )
423                                 IRQ_DELTA(package_index,j) = 0;
424                         /* Determine the total count per processor per IRQ */
425                         value_now = (unsigned long) kstat_cpu(i).irqs[j];
426
427                         /* Determine the activity per processor per IRQ */
428                         delta = value_now - LAST_CPU_IRQ(i,j);
429
430                         /* Update last_cpu_irq[][] for the next time */
431                         LAST_CPU_IRQ(i,j) = value_now;
432
433                         /* Ignore IRQs whose rate is less than the clock */
434                         if (delta < useful_load_threshold)
435                                 continue;
436                         /* update the load for the processor or package total */
437                         IRQ_DELTA(package_index,j) += delta;
438
439                         /* Keep track of the higher numbered sibling as well */
440                         if (i != package_index)
441                                 CPU_IRQ(i) += delta;
442                         /*
443                          * We have sibling A and sibling B in the package
444                          *
445                          * cpu_irq[A] = load for cpu A + load for cpu B
446                          * cpu_irq[B] = load for cpu B
447                          */
448                         CPU_IRQ(package_index) += delta;
449                 }
450         }
451         /* Find the least loaded processor package */
452         for (i = 0; i < NR_CPUS; i++) {
453                 if (!cpu_online(i))
454                         continue;
455                 if (physical_balance && i > cpu_sibling_map[i])
456                         continue;
457                 if (min_cpu_irq > CPU_IRQ(i)) {
458                         min_cpu_irq = CPU_IRQ(i);
459                         min_loaded = i;
460                 }
461         }
462         max_cpu_irq = ULONG_MAX;
463
464 tryanothercpu:
465         /* Look for heaviest loaded processor.
466          * We may come back to get the next heaviest loaded processor.
467          * Skip processors with trivial loads.
468          */
469         tmp_cpu_irq = 0;
470         tmp_loaded = -1;
471         for (i = 0; i < NR_CPUS; i++) {
472                 if (!cpu_online(i))
473                         continue;
474                 if (physical_balance && i > cpu_sibling_map[i])
475                         continue;
476                 if (max_cpu_irq <= CPU_IRQ(i)) 
477                         continue;
478                 if (tmp_cpu_irq < CPU_IRQ(i)) {
479                         tmp_cpu_irq = CPU_IRQ(i);
480                         tmp_loaded = i;
481                 }
482         }
483
484         if (tmp_loaded == -1) {
485          /* In the case of small number of heavy interrupt sources, 
486           * loading some of the cpus too much. We use Ingo's original 
487           * approach to rotate them around.
488           */
489                 if (!first_attempt && imbalance >= useful_load_threshold) {
490                         rotate_irqs_among_cpus(useful_load_threshold);
491                         return;
492                 }
493                 goto not_worth_the_effort;
494         }
495         
496         first_attempt = 0;              /* heaviest search */
497         max_cpu_irq = tmp_cpu_irq;      /* load */
498         max_loaded = tmp_loaded;        /* processor */
499         imbalance = (max_cpu_irq - min_cpu_irq) / 2;
500         
501         Dprintk("max_loaded cpu = %d\n", max_loaded);
502         Dprintk("min_loaded cpu = %d\n", min_loaded);
503         Dprintk("max_cpu_irq load = %ld\n", max_cpu_irq);
504         Dprintk("min_cpu_irq load = %ld\n", min_cpu_irq);
505         Dprintk("load imbalance = %lu\n", imbalance);
506
507         /* if imbalance is less than approx 10% of max load, then
508          * observe diminishing returns action. - quit
509          */
510         if (imbalance < (max_cpu_irq >> 3)) {
511                 Dprintk("Imbalance too trivial\n");
512                 goto not_worth_the_effort;
513         }
514
515 tryanotherirq:
516         /* if we select an IRQ to move that can't go where we want, then
517          * see if there is another one to try.
518          */
519         move_this_load = 0;
520         selected_irq = -1;
521         for (j = 0; j < NR_IRQS; j++) {
522                 /* Is this an active IRQ? */
523                 if (!irq_desc[j].action)
524                         continue;
525                 if (imbalance <= IRQ_DELTA(max_loaded,j))
526                         continue;
527                 /* Try to find the IRQ that is closest to the imbalance
528                  * without going over.
529                  */
530                 if (move_this_load < IRQ_DELTA(max_loaded,j)) {
531                         move_this_load = IRQ_DELTA(max_loaded,j);
532                         selected_irq = j;
533                 }
534         }
535         if (selected_irq == -1) {
536                 goto tryanothercpu;
537         }
538
539         imbalance = move_this_load;
540         
541         /* For physical_balance case, we accumlated both load
542          * values in the one of the siblings cpu_irq[],
543          * to use the same code for physical and logical processors
544          * as much as possible. 
545          *
546          * NOTE: the cpu_irq[] array holds the sum of the load for
547          * sibling A and sibling B in the slot for the lowest numbered
548          * sibling (A), _AND_ the load for sibling B in the slot for
549          * the higher numbered sibling.
550          *
551          * We seek the least loaded sibling by making the comparison
552          * (A+B)/2 vs B
553          */
554         if (physical_balance && (CPU_IRQ(min_loaded) >> 1) >
555                                         CPU_IRQ(cpu_sibling_map[min_loaded]))
556                 min_loaded = cpu_sibling_map[min_loaded];
557
558         cpus_and(allowed_mask, cpu_online_map, irq_affinity[selected_irq]);
559         target_cpu_mask = cpumask_of_cpu(min_loaded);
560         cpus_and(tmp, target_cpu_mask, allowed_mask);
561
562         if (!cpus_empty(tmp)) {
563                 irq_desc_t *desc = irq_desc + selected_irq;
564                 unsigned long flags;
565
566                 Dprintk("irq = %d moved to cpu = %d\n",
567                                 selected_irq, min_loaded);
568                 /* mark for change destination */
569                 spin_lock_irqsave(&desc->lock, flags);
570                 pending_irq_balance_cpumask[selected_irq] =
571                                         cpumask_of_cpu(min_loaded);
572                 spin_unlock_irqrestore(&desc->lock, flags);
573                 /* Since we made a change, come back sooner to 
574                  * check for more variation.
575                  */
576                 balanced_irq_interval = max((long)MIN_BALANCED_IRQ_INTERVAL,
577                         balanced_irq_interval - BALANCED_IRQ_LESS_DELTA);       
578                 return;
579         }
580         goto tryanotherirq;
581
582 not_worth_the_effort:
583         /*
584          * if we did not find an IRQ to move, then adjust the time interval
585          * upward
586          */
587         balanced_irq_interval = min((long)MAX_BALANCED_IRQ_INTERVAL,
588                 balanced_irq_interval + BALANCED_IRQ_MORE_DELTA);       
589         Dprintk("IRQ worth rotating not found\n");
590         return;
591 }
592
593 int balanced_irq(void *unused)
594 {
595         int i;
596         unsigned long prev_balance_time = jiffies;
597         long time_remaining = balanced_irq_interval;
598
599         daemonize("kirqd");
600         
601         /* push everything to CPU 0 to give us a starting point.  */
602         for (i = 0 ; i < NR_IRQS ; i++) {
603                 pending_irq_balance_cpumask[i] = cpumask_of_cpu(0);
604         }
605
606 repeat:
607         set_current_state(TASK_INTERRUPTIBLE);
608         time_remaining = schedule_timeout(time_remaining);
609         if (time_after(jiffies, prev_balance_time+balanced_irq_interval)) {
610                 Dprintk("balanced_irq: calling do_irq_balance() %lu\n",
611                                         jiffies);
612                 do_irq_balance();
613                 prev_balance_time = jiffies;
614                 time_remaining = balanced_irq_interval;
615         }
616         goto repeat;
617 }
618
619 static int __init balanced_irq_init(void)
620 {
621         int i;
622         struct cpuinfo_x86 *c;
623         cpumask_t tmp;
624
625         cpus_shift_right(tmp, cpu_online_map, 2);
626         c = &boot_cpu_data;
627         /* When not overwritten by the command line ask subarchitecture. */
628         if (irqbalance_disabled == IRQBALANCE_CHECK_ARCH)
629                 irqbalance_disabled = NO_BALANCE_IRQ;
630         if (irqbalance_disabled)
631                 return 0;
632         
633          /* disable irqbalance completely if there is only one processor online */
634         if (num_online_cpus() < 2) {
635                 irqbalance_disabled = 1;
636                 return 0;
637         }
638         /*
639          * Enable physical balance only if more than 1 physical processor
640          * is present
641          */
642         if (smp_num_siblings > 1 && !cpus_empty(tmp))
643                 physical_balance = 1;
644
645         for (i = 0; i < NR_CPUS; i++) {
646                 if (!cpu_online(i))
647                         continue;
648                 irq_cpu_data[i].irq_delta = kmalloc(sizeof(unsigned long) * NR_IRQS, GFP_KERNEL);
649                 irq_cpu_data[i].last_irq = kmalloc(sizeof(unsigned long) * NR_IRQS, GFP_KERNEL);
650                 if (irq_cpu_data[i].irq_delta == NULL || irq_cpu_data[i].last_irq == NULL) {
651                         printk(KERN_ERR "balanced_irq_init: out of memory");
652                         goto failed;
653                 }
654                 memset(irq_cpu_data[i].irq_delta,0,sizeof(unsigned long) * NR_IRQS);
655                 memset(irq_cpu_data[i].last_irq,0,sizeof(unsigned long) * NR_IRQS);
656         }
657         
658         printk(KERN_INFO "Starting balanced_irq\n");
659         if (kernel_thread(balanced_irq, NULL, CLONE_KERNEL) >= 0) 
660                 return 0;
661         else 
662                 printk(KERN_ERR "balanced_irq_init: failed to spawn balanced_irq");
663 failed:
664         for (i = 0; i < NR_CPUS; i++) {
665                 if(irq_cpu_data[i].irq_delta)
666                         kfree(irq_cpu_data[i].irq_delta);
667                 if(irq_cpu_data[i].last_irq)
668                         kfree(irq_cpu_data[i].last_irq);
669         }
670         return 0;
671 }
672
673 static int __init irqbalance_disable(char *str)
674 {
675         irqbalance_disabled = 1;
676         return 0;
677 }
678
679 __setup("noirqbalance", irqbalance_disable);
680
681 static inline void move_irq(int irq)
682 {
683         /* note - we hold the desc->lock */
684         if (unlikely(!cpus_empty(pending_irq_balance_cpumask[irq]))) {
685                 set_ioapic_affinity_irq(irq, pending_irq_balance_cpumask[irq]);
686                 cpus_clear(pending_irq_balance_cpumask[irq]);
687         }
688 }
689
690 __initcall(balanced_irq_init);
691
692 #else /* !CONFIG_IRQBALANCE */
693 static inline void move_irq(int irq) { }
694 #endif /* CONFIG_IRQBALANCE */
695
696 #ifndef CONFIG_SMP
697 void fastcall send_IPI_self(int vector)
698 {
699         unsigned int cfg;
700
701         /*
702          * Wait for idle.
703          */
704         apic_wait_icr_idle();
705         cfg = APIC_DM_FIXED | APIC_DEST_SELF | vector | APIC_DEST_LOGICAL;
706         /*
707          * Send the IPI. The write to APIC_ICR fires this off.
708          */
709         apic_write_around(APIC_ICR, cfg);
710 }
711 #endif /* !CONFIG_SMP */
712
713
714 /*
715  * support for broken MP BIOSs, enables hand-redirection of PIRQ0-7 to
716  * specific CPU-side IRQs.
717  */
718
719 #define MAX_PIRQS 8
720 int pirq_entries [MAX_PIRQS];
721 int pirqs_enabled;
722 int skip_ioapic_setup;
723
724 static int __init ioapic_setup(char *str)
725 {
726         skip_ioapic_setup = 1;
727         return 1;
728 }
729
730 __setup("noapic", ioapic_setup);
731
732 static int __init ioapic_pirq_setup(char *str)
733 {
734         int i, max;
735         int ints[MAX_PIRQS+1];
736
737         get_options(str, ARRAY_SIZE(ints), ints);
738
739         for (i = 0; i < MAX_PIRQS; i++)
740                 pirq_entries[i] = -1;
741
742         pirqs_enabled = 1;
743         printk(KERN_INFO "PIRQ redirection, working around broken MP-BIOS.\n");
744         max = MAX_PIRQS;
745         if (ints[0] < MAX_PIRQS)
746                 max = ints[0];
747
748         for (i = 0; i < max; i++) {
749                 printk(KERN_DEBUG "... PIRQ%d -> IRQ %d\n", i, ints[i+1]);
750                 /*
751                  * PIRQs are mapped upside down, usually.
752                  */
753                 pirq_entries[MAX_PIRQS-i-1] = ints[i+1];
754         }
755         return 1;
756 }
757
758 __setup("pirq=", ioapic_pirq_setup);
759
760 /*
761  * Find the IRQ entry number of a certain pin.
762  */
763 static int __init find_irq_entry(int apic, int pin, int type)
764 {
765         int i;
766
767         for (i = 0; i < mp_irq_entries; i++)
768                 if (mp_irqs[i].mpc_irqtype == type &&
769                     (mp_irqs[i].mpc_dstapic == mp_ioapics[apic].mpc_apicid ||
770                      mp_irqs[i].mpc_dstapic == MP_APIC_ALL) &&
771                     mp_irqs[i].mpc_dstirq == pin)
772                         return i;
773
774         return -1;
775 }
776
777 /*
778  * Find the pin to which IRQ[irq] (ISA) is connected
779  */
780 static int __init find_isa_irq_pin(int irq, int type)
781 {
782         int i;
783
784         for (i = 0; i < mp_irq_entries; i++) {
785                 int lbus = mp_irqs[i].mpc_srcbus;
786
787                 if ((mp_bus_id_to_type[lbus] == MP_BUS_ISA ||
788                      mp_bus_id_to_type[lbus] == MP_BUS_EISA ||
789                      mp_bus_id_to_type[lbus] == MP_BUS_MCA ||
790                      mp_bus_id_to_type[lbus] == MP_BUS_NEC98
791                     ) &&
792                     (mp_irqs[i].mpc_irqtype == type) &&
793                     (mp_irqs[i].mpc_srcbusirq == irq))
794
795                         return mp_irqs[i].mpc_dstirq;
796         }
797         return -1;
798 }
799
800 /*
801  * Find a specific PCI IRQ entry.
802  * Not an __init, possibly needed by modules
803  */
804 static int pin_2_irq(int idx, int apic, int pin);
805
806 int IO_APIC_get_PCI_irq_vector(int bus, int slot, int pin)
807 {
808         int apic, i, best_guess = -1;
809
810         Dprintk("querying PCI -> IRQ mapping bus:%d, slot:%d, pin:%d.\n",
811                 bus, slot, pin);
812         if (mp_bus_id_to_pci_bus[bus] == -1) {
813                 printk(KERN_WARNING "PCI BIOS passed nonexistent PCI bus %d!\n", bus);
814                 return -1;
815         }
816         for (i = 0; i < mp_irq_entries; i++) {
817                 int lbus = mp_irqs[i].mpc_srcbus;
818
819                 for (apic = 0; apic < nr_ioapics; apic++)
820                         if (mp_ioapics[apic].mpc_apicid == mp_irqs[i].mpc_dstapic ||
821                             mp_irqs[i].mpc_dstapic == MP_APIC_ALL)
822                                 break;
823
824                 if ((mp_bus_id_to_type[lbus] == MP_BUS_PCI) &&
825                     !mp_irqs[i].mpc_irqtype &&
826                     (bus == lbus) &&
827                     (slot == ((mp_irqs[i].mpc_srcbusirq >> 2) & 0x1f))) {
828                         int irq = pin_2_irq(i,apic,mp_irqs[i].mpc_dstirq);
829
830                         if (!(apic || IO_APIC_IRQ(irq)))
831                                 continue;
832
833                         if (pin == (mp_irqs[i].mpc_srcbusirq & 3))
834                                 return irq;
835                         /*
836                          * Use the first all-but-pin matching entry as a
837                          * best-guess fuzzy result for broken mptables.
838                          */
839                         if (best_guess < 0)
840                                 best_guess = irq;
841                 }
842         }
843         return best_guess;
844 }
845
846 /*
847  * This function currently is only a helper for the i386 smp boot process where 
848  * we need to reprogram the ioredtbls to cater for the cpus which have come online
849  * so mask in all cases should simply be TARGET_CPUS
850  */
851 void __init setup_ioapic_dest(cpumask_t mask)
852 {
853         int pin, ioapic, irq, irq_entry;
854
855         if (skip_ioapic_setup == 1)
856                 return;
857
858         for (ioapic = 0; ioapic < nr_ioapics; ioapic++) {
859                 for (pin = 0; pin < nr_ioapic_registers[ioapic]; pin++) {
860                         irq_entry = find_irq_entry(ioapic, pin, mp_INT);
861                         if (irq_entry == -1)
862                                 continue;
863                         irq = pin_2_irq(irq_entry, ioapic, pin);
864                         set_ioapic_affinity_irq(irq, mask);
865                 }
866
867         }
868 }
869
870 /*
871  * EISA Edge/Level control register, ELCR
872  */
873 static int __init EISA_ELCR(unsigned int irq)
874 {
875         if (irq < 16) {
876                 unsigned int port = 0x4d0 + (irq >> 3);
877                 return (inb(port) >> (irq & 7)) & 1;
878         }
879         printk(KERN_INFO "Broken MPtable reports ISA irq %d\n", irq);
880         return 0;
881 }
882
883 /* EISA interrupts are always polarity zero and can be edge or level
884  * trigger depending on the ELCR value.  If an interrupt is listed as
885  * EISA conforming in the MP table, that means its trigger type must
886  * be read in from the ELCR */
887
888 #define default_EISA_trigger(idx)       (EISA_ELCR(mp_irqs[idx].mpc_srcbusirq))
889 #define default_EISA_polarity(idx)      (0)
890
891 /* ISA interrupts are always polarity zero edge triggered,
892  * when listed as conforming in the MP table. */
893
894 #define default_ISA_trigger(idx)        (0)
895 #define default_ISA_polarity(idx)       (0)
896
897 /* PCI interrupts are always polarity one level triggered,
898  * when listed as conforming in the MP table. */
899
900 #define default_PCI_trigger(idx)        (1)
901 #define default_PCI_polarity(idx)       (1)
902
903 /* MCA interrupts are always polarity zero level triggered,
904  * when listed as conforming in the MP table. */
905
906 #define default_MCA_trigger(idx)        (1)
907 #define default_MCA_polarity(idx)       (0)
908
909 /* NEC98 interrupts are always polarity zero edge triggered,
910  * when listed as conforming in the MP table. */
911
912 #define default_NEC98_trigger(idx)     (0)
913 #define default_NEC98_polarity(idx)    (0)
914
915 static int __init MPBIOS_polarity(int idx)
916 {
917         int bus = mp_irqs[idx].mpc_srcbus;
918         int polarity;
919
920         /*
921          * Determine IRQ line polarity (high active or low active):
922          */
923         switch (mp_irqs[idx].mpc_irqflag & 3)
924         {
925                 case 0: /* conforms, ie. bus-type dependent polarity */
926                 {
927                         switch (mp_bus_id_to_type[bus])
928                         {
929                                 case MP_BUS_ISA: /* ISA pin */
930                                 {
931                                         polarity = default_ISA_polarity(idx);
932                                         break;
933                                 }
934                                 case MP_BUS_EISA: /* EISA pin */
935                                 {
936                                         polarity = default_EISA_polarity(idx);
937                                         break;
938                                 }
939                                 case MP_BUS_PCI: /* PCI pin */
940                                 {
941                                         polarity = default_PCI_polarity(idx);
942                                         break;
943                                 }
944                                 case MP_BUS_MCA: /* MCA pin */
945                                 {
946                                         polarity = default_MCA_polarity(idx);
947                                         break;
948                                 }
949                                 case MP_BUS_NEC98: /* NEC 98 pin */
950                                 {
951                                         polarity = default_NEC98_polarity(idx);
952                                         break;
953                                 }
954                                 default:
955                                 {
956                                         printk(KERN_WARNING "broken BIOS!!\n");
957                                         polarity = 1;
958                                         break;
959                                 }
960                         }
961                         break;
962                 }
963                 case 1: /* high active */
964                 {
965                         polarity = 0;
966                         break;
967                 }
968                 case 2: /* reserved */
969                 {
970                         printk(KERN_WARNING "broken BIOS!!\n");
971                         polarity = 1;
972                         break;
973                 }
974                 case 3: /* low active */
975                 {
976                         polarity = 1;
977                         break;
978                 }
979                 default: /* invalid */
980                 {
981                         printk(KERN_WARNING "broken BIOS!!\n");
982                         polarity = 1;
983                         break;
984                 }
985         }
986         return polarity;
987 }
988
989 static int __init MPBIOS_trigger(int idx)
990 {
991         int bus = mp_irqs[idx].mpc_srcbus;
992         int trigger;
993
994         /*
995          * Determine IRQ trigger mode (edge or level sensitive):
996          */
997         switch ((mp_irqs[idx].mpc_irqflag>>2) & 3)
998         {
999                 case 0: /* conforms, ie. bus-type dependent */
1000                 {
1001                         switch (mp_bus_id_to_type[bus])
1002                         {
1003                                 case MP_BUS_ISA: /* ISA pin */
1004                                 {
1005                                         trigger = default_ISA_trigger(idx);
1006                                         break;
1007                                 }
1008                                 case MP_BUS_EISA: /* EISA pin */
1009                                 {
1010                                         trigger = default_EISA_trigger(idx);
1011                                         break;
1012                                 }
1013                                 case MP_BUS_PCI: /* PCI pin */
1014                                 {
1015                                         trigger = default_PCI_trigger(idx);
1016                                         break;
1017                                 }
1018                                 case MP_BUS_MCA: /* MCA pin */
1019                                 {
1020                                         trigger = default_MCA_trigger(idx);
1021                                         break;
1022                                 }
1023                                 case MP_BUS_NEC98: /* NEC 98 pin */
1024                                 {
1025                                         trigger = default_NEC98_trigger(idx);
1026                                         break;
1027                                 }
1028                                 default:
1029                                 {
1030                                         printk(KERN_WARNING "broken BIOS!!\n");
1031                                         trigger = 1;
1032                                         break;
1033                                 }
1034                         }
1035                         break;
1036                 }
1037                 case 1: /* edge */
1038                 {
1039                         trigger = 0;
1040                         break;
1041                 }
1042                 case 2: /* reserved */
1043                 {
1044                         printk(KERN_WARNING "broken BIOS!!\n");
1045                         trigger = 1;
1046                         break;
1047                 }
1048                 case 3: /* level */
1049                 {
1050                         trigger = 1;
1051                         break;
1052                 }
1053                 default: /* invalid */
1054                 {
1055                         printk(KERN_WARNING "broken BIOS!!\n");
1056                         trigger = 0;
1057                         break;
1058                 }
1059         }
1060         return trigger;
1061 }
1062
1063 static inline int irq_polarity(int idx)
1064 {
1065         return MPBIOS_polarity(idx);
1066 }
1067
1068 static inline int irq_trigger(int idx)
1069 {
1070         return MPBIOS_trigger(idx);
1071 }
1072
1073 static int pin_2_irq(int idx, int apic, int pin)
1074 {
1075         int irq, i;
1076         int bus = mp_irqs[idx].mpc_srcbus;
1077
1078         /*
1079          * Debugging check, we are in big trouble if this message pops up!
1080          */
1081         if (mp_irqs[idx].mpc_dstirq != pin)
1082                 printk(KERN_ERR "broken BIOS or MPTABLE parser, ayiee!!\n");
1083
1084         switch (mp_bus_id_to_type[bus])
1085         {
1086                 case MP_BUS_ISA: /* ISA pin */
1087                 case MP_BUS_EISA:
1088                 case MP_BUS_MCA:
1089                 case MP_BUS_NEC98:
1090                 {
1091                         irq = mp_irqs[idx].mpc_srcbusirq;
1092                         break;
1093                 }
1094                 case MP_BUS_PCI: /* PCI pin */
1095                 {
1096                         /*
1097                          * PCI IRQs are mapped in order
1098                          */
1099                         i = irq = 0;
1100                         while (i < apic)
1101                                 irq += nr_ioapic_registers[i++];
1102                         irq += pin;
1103                         if ((!apic) && (irq < 16)) 
1104                                 irq += 16;
1105                         break;
1106                 }
1107                 default:
1108                 {
1109                         printk(KERN_ERR "unknown bus type %d.\n",bus); 
1110                         irq = 0;
1111                         break;
1112                 }
1113         }
1114
1115         /*
1116          * PCI IRQ command line redirection. Yes, limits are hardcoded.
1117          */
1118         if ((pin >= 16) && (pin <= 23)) {
1119                 if (pirq_entries[pin-16] != -1) {
1120                         if (!pirq_entries[pin-16]) {
1121                                 printk(KERN_DEBUG "disabling PIRQ%d\n", pin-16);
1122                         } else {
1123                                 irq = pirq_entries[pin-16];
1124                                 printk(KERN_DEBUG "using PIRQ%d -> IRQ %d\n",
1125                                                 pin-16, irq);
1126                         }
1127                 }
1128         }
1129         return irq;
1130 }
1131
1132 static inline int IO_APIC_irq_trigger(int irq)
1133 {
1134         int apic, idx, pin;
1135
1136         for (apic = 0; apic < nr_ioapics; apic++) {
1137                 for (pin = 0; pin < nr_ioapic_registers[apic]; pin++) {
1138                         idx = find_irq_entry(apic,pin,mp_INT);
1139                         if ((idx != -1) && (irq == pin_2_irq(idx,apic,pin)))
1140                                 return irq_trigger(idx);
1141                 }
1142         }
1143         /*
1144          * nonexistent IRQs are edge default
1145          */
1146         return 0;
1147 }
1148
1149 /* irq_vectors is indexed by the sum of all RTEs in all I/O APICs. */
1150 u8 irq_vector[NR_IRQ_VECTORS] = { FIRST_DEVICE_VECTOR , 0 };
1151
1152 #ifdef CONFIG_PCI_USE_VECTOR
1153 int assign_irq_vector(int irq)
1154 #else
1155 int __init assign_irq_vector(int irq)
1156 #endif
1157 {
1158         static int current_vector = FIRST_DEVICE_VECTOR, offset = 0;
1159
1160         BUG_ON(irq >= NR_IRQ_VECTORS);
1161         if (irq != AUTO_ASSIGN && IO_APIC_VECTOR(irq) > 0)
1162                 return IO_APIC_VECTOR(irq);
1163 next:
1164         current_vector += 8;
1165         if (current_vector == SYSCALL_VECTOR)
1166                 goto next;
1167
1168         if (current_vector >= FIRST_SYSTEM_VECTOR) {
1169                 offset++;
1170                 if (!(offset%8))
1171                         return -ENOSPC;
1172                 current_vector = FIRST_DEVICE_VECTOR + offset;
1173         }
1174
1175         vector_irq[current_vector] = irq;
1176         if (irq != AUTO_ASSIGN)
1177                 IO_APIC_VECTOR(irq) = current_vector;
1178
1179         return current_vector;
1180 }
1181
1182 static struct hw_interrupt_type ioapic_level_type;
1183 static struct hw_interrupt_type ioapic_edge_type;
1184
1185 #define IOAPIC_AUTO     -1
1186 #define IOAPIC_EDGE     0
1187 #define IOAPIC_LEVEL    1
1188
1189 static inline void ioapic_register_intr(int irq, int vector, unsigned long trigger)
1190 {
1191         if (use_pci_vector() && !platform_legacy_irq(irq)) {
1192                 if ((trigger == IOAPIC_AUTO && IO_APIC_irq_trigger(irq)) ||
1193                                 trigger == IOAPIC_LEVEL)
1194                         irq_desc[vector].handler = &ioapic_level_type;
1195                 else
1196                         irq_desc[vector].handler = &ioapic_edge_type;
1197                 set_intr_gate(vector, interrupt[vector]);
1198         } else  {
1199                 if ((trigger == IOAPIC_AUTO && IO_APIC_irq_trigger(irq)) ||
1200                                 trigger == IOAPIC_LEVEL)
1201                         irq_desc[irq].handler = &ioapic_level_type;
1202                 else
1203                         irq_desc[irq].handler = &ioapic_edge_type;
1204                 set_intr_gate(vector, interrupt[irq]);
1205         }
1206 }
1207
1208 void __init setup_IO_APIC_irqs(void)
1209 {
1210         struct IO_APIC_route_entry entry;
1211         int apic, pin, idx, irq, first_notcon = 1, vector;
1212         unsigned long flags;
1213
1214         printk(KERN_DEBUG "init IO_APIC IRQs\n");
1215
1216         for (apic = 0; apic < nr_ioapics; apic++) {
1217         for (pin = 0; pin < nr_ioapic_registers[apic]; pin++) {
1218
1219                 /*
1220                  * add it to the IO-APIC irq-routing table:
1221                  */
1222                 memset(&entry,0,sizeof(entry));
1223
1224                 entry.delivery_mode = INT_DELIVERY_MODE;
1225                 entry.dest_mode = INT_DEST_MODE;
1226                 entry.mask = 0;                         /* enable IRQ */
1227                 entry.dest.logical.logical_dest = 
1228                                         cpu_mask_to_apicid(TARGET_CPUS);
1229
1230                 idx = find_irq_entry(apic,pin,mp_INT);
1231                 if (idx == -1) {
1232                         if (first_notcon) {
1233                                 printk(KERN_DEBUG " IO-APIC (apicid-pin) %d-%d", mp_ioapics[apic].mpc_apicid, pin);
1234                                 first_notcon = 0;
1235                         } else
1236                                 printk(", %d-%d", mp_ioapics[apic].mpc_apicid, pin);
1237                         continue;
1238                 }
1239
1240                 entry.trigger = irq_trigger(idx);
1241                 entry.polarity = irq_polarity(idx);
1242
1243                 if (irq_trigger(idx)) {
1244                         entry.trigger = 1;
1245                         entry.mask = 1;
1246                 }
1247
1248                 irq = pin_2_irq(idx, apic, pin);
1249                 /*
1250                  * skip adding the timer int on secondary nodes, which causes
1251                  * a small but painful rift in the time-space continuum
1252                  */
1253                 if (multi_timer_check(apic, irq))
1254                         continue;
1255                 else
1256                         add_pin_to_irq(irq, apic, pin);
1257
1258                 if (!apic && !IO_APIC_IRQ(irq))
1259                         continue;
1260
1261                 if (IO_APIC_IRQ(irq)) {
1262                         vector = assign_irq_vector(irq);
1263                         entry.vector = vector;
1264                         ioapic_register_intr(irq, vector, IOAPIC_AUTO);
1265                 
1266                         if (!apic && (irq < 16))
1267                                 disable_8259A_irq(irq);
1268                 }
1269                 spin_lock_irqsave(&ioapic_lock, flags);
1270                 io_apic_write(apic, 0x11+2*pin, *(((int *)&entry)+1));
1271                 io_apic_write(apic, 0x10+2*pin, *(((int *)&entry)+0));
1272                 spin_unlock_irqrestore(&ioapic_lock, flags);
1273         }
1274         }
1275
1276         if (!first_notcon)
1277                 printk(" not connected.\n");
1278 }
1279
1280 /*
1281  * Set up the 8259A-master output pin:
1282  */
1283 void __init setup_ExtINT_IRQ0_pin(unsigned int pin, int vector)
1284 {
1285         struct IO_APIC_route_entry entry;
1286         unsigned long flags;
1287
1288         memset(&entry,0,sizeof(entry));
1289
1290         disable_8259A_irq(0);
1291
1292         /* mask LVT0 */
1293         apic_write_around(APIC_LVT0, APIC_LVT_MASKED | APIC_DM_EXTINT);
1294
1295         /*
1296          * We use logical delivery to get the timer IRQ
1297          * to the first CPU.
1298          */
1299         entry.dest_mode = INT_DEST_MODE;
1300         entry.mask = 0;                                 /* unmask IRQ now */
1301         entry.dest.logical.logical_dest = cpu_mask_to_apicid(TARGET_CPUS);
1302         entry.delivery_mode = INT_DELIVERY_MODE;
1303         entry.polarity = 0;
1304         entry.trigger = 0;
1305         entry.vector = vector;
1306
1307         /*
1308          * The timer IRQ doesn't have to know that behind the
1309          * scene we have a 8259A-master in AEOI mode ...
1310          */
1311         irq_desc[0].handler = &ioapic_edge_type;
1312
1313         /*
1314          * Add it to the IO-APIC irq-routing table:
1315          */
1316         spin_lock_irqsave(&ioapic_lock, flags);
1317         io_apic_write(0, 0x11+2*pin, *(((int *)&entry)+1));
1318         io_apic_write(0, 0x10+2*pin, *(((int *)&entry)+0));
1319         spin_unlock_irqrestore(&ioapic_lock, flags);
1320
1321         enable_8259A_irq(0);
1322 }
1323
1324 static inline void UNEXPECTED_IO_APIC(void)
1325 {
1326 }
1327
1328 void __init print_IO_APIC(void)
1329 {
1330         int apic, i;
1331         union IO_APIC_reg_00 reg_00;
1332         union IO_APIC_reg_01 reg_01;
1333         union IO_APIC_reg_02 reg_02;
1334         union IO_APIC_reg_03 reg_03;
1335         unsigned long flags;
1336
1337         printk(KERN_DEBUG "number of MP IRQ sources: %d.\n", mp_irq_entries);
1338         for (i = 0; i < nr_ioapics; i++)
1339                 printk(KERN_DEBUG "number of IO-APIC #%d registers: %d.\n",
1340                        mp_ioapics[i].mpc_apicid, nr_ioapic_registers[i]);
1341
1342         /*
1343          * We are a bit conservative about what we expect.  We have to
1344          * know about every hardware change ASAP.
1345          */
1346         printk(KERN_INFO "testing the IO APIC.......................\n");
1347
1348         for (apic = 0; apic < nr_ioapics; apic++) {
1349
1350         spin_lock_irqsave(&ioapic_lock, flags);
1351         reg_00.raw = io_apic_read(apic, 0);
1352         reg_01.raw = io_apic_read(apic, 1);
1353         if (reg_01.bits.version >= 0x10)
1354                 reg_02.raw = io_apic_read(apic, 2);
1355         if (reg_01.bits.version >= 0x20)
1356                 reg_03.raw = io_apic_read(apic, 3);
1357         spin_unlock_irqrestore(&ioapic_lock, flags);
1358
1359         printk(KERN_DEBUG "IO APIC #%d......\n", mp_ioapics[apic].mpc_apicid);
1360         printk(KERN_DEBUG ".... register #00: %08X\n", reg_00.raw);
1361         printk(KERN_DEBUG ".......    : physical APIC id: %02X\n", reg_00.bits.ID);
1362         printk(KERN_DEBUG ".......    : Delivery Type: %X\n", reg_00.bits.delivery_type);
1363         printk(KERN_DEBUG ".......    : LTS          : %X\n", reg_00.bits.LTS);
1364         if (reg_00.bits.ID >= APIC_BROADCAST_ID)
1365                 UNEXPECTED_IO_APIC();
1366         if (reg_00.bits.__reserved_1 || reg_00.bits.__reserved_2)
1367                 UNEXPECTED_IO_APIC();
1368
1369         printk(KERN_DEBUG ".... register #01: %08X\n", reg_01.raw);
1370         printk(KERN_DEBUG ".......     : max redirection entries: %04X\n", reg_01.bits.entries);
1371         if (    (reg_01.bits.entries != 0x0f) && /* older (Neptune) boards */
1372                 (reg_01.bits.entries != 0x17) && /* typical ISA+PCI boards */
1373                 (reg_01.bits.entries != 0x1b) && /* Compaq Proliant boards */
1374                 (reg_01.bits.entries != 0x1f) && /* dual Xeon boards */
1375                 (reg_01.bits.entries != 0x22) && /* bigger Xeon boards */
1376                 (reg_01.bits.entries != 0x2E) &&
1377                 (reg_01.bits.entries != 0x3F)
1378         )
1379                 UNEXPECTED_IO_APIC();
1380
1381         printk(KERN_DEBUG ".......     : PRQ implemented: %X\n", reg_01.bits.PRQ);
1382         printk(KERN_DEBUG ".......     : IO APIC version: %04X\n", reg_01.bits.version);
1383         if (    (reg_01.bits.version != 0x01) && /* 82489DX IO-APICs */
1384                 (reg_01.bits.version != 0x10) && /* oldest IO-APICs */
1385                 (reg_01.bits.version != 0x11) && /* Pentium/Pro IO-APICs */
1386                 (reg_01.bits.version != 0x13) && /* Xeon IO-APICs */
1387                 (reg_01.bits.version != 0x20)    /* Intel P64H (82806 AA) */
1388         )
1389                 UNEXPECTED_IO_APIC();
1390         if (reg_01.bits.__reserved_1 || reg_01.bits.__reserved_2)
1391                 UNEXPECTED_IO_APIC();
1392
1393         /*
1394          * Some Intel chipsets with IO APIC VERSION of 0x1? don't have reg_02,
1395          * but the value of reg_02 is read as the previous read register
1396          * value, so ignore it if reg_02 == reg_01.
1397          */
1398         if (reg_01.bits.version >= 0x10 && reg_02.raw != reg_01.raw) {
1399                 printk(KERN_DEBUG ".... register #02: %08X\n", reg_02.raw);
1400                 printk(KERN_DEBUG ".......     : arbitration: %02X\n", reg_02.bits.arbitration);
1401                 if (reg_02.bits.__reserved_1 || reg_02.bits.__reserved_2)
1402                         UNEXPECTED_IO_APIC();
1403         }
1404
1405         /*
1406          * Some Intel chipsets with IO APIC VERSION of 0x2? don't have reg_02
1407          * or reg_03, but the value of reg_0[23] is read as the previous read
1408          * register value, so ignore it if reg_03 == reg_0[12].
1409          */
1410         if (reg_01.bits.version >= 0x20 && reg_03.raw != reg_02.raw &&
1411             reg_03.raw != reg_01.raw) {
1412                 printk(KERN_DEBUG ".... register #03: %08X\n", reg_03.raw);
1413                 printk(KERN_DEBUG ".......     : Boot DT    : %X\n", reg_03.bits.boot_DT);
1414                 if (reg_03.bits.__reserved_1)
1415                         UNEXPECTED_IO_APIC();
1416         }
1417
1418         printk(KERN_DEBUG ".... IRQ redirection table:\n");
1419
1420         printk(KERN_DEBUG " NR Log Phy Mask Trig IRR Pol"
1421                           " Stat Dest Deli Vect:   \n");
1422
1423         for (i = 0; i <= reg_01.bits.entries; i++) {
1424                 struct IO_APIC_route_entry entry;
1425
1426                 spin_lock_irqsave(&ioapic_lock, flags);
1427                 *(((int *)&entry)+0) = io_apic_read(apic, 0x10+i*2);
1428                 *(((int *)&entry)+1) = io_apic_read(apic, 0x11+i*2);
1429                 spin_unlock_irqrestore(&ioapic_lock, flags);
1430
1431                 printk(KERN_DEBUG " %02x %03X %02X  ",
1432                         i,
1433                         entry.dest.logical.logical_dest,
1434                         entry.dest.physical.physical_dest
1435                 );
1436
1437                 printk("%1d    %1d    %1d   %1d   %1d    %1d    %1d    %02X\n",
1438                         entry.mask,
1439                         entry.trigger,
1440                         entry.irr,
1441                         entry.polarity,
1442                         entry.delivery_status,
1443                         entry.dest_mode,
1444                         entry.delivery_mode,
1445                         entry.vector
1446                 );
1447         }
1448         }
1449         printk(KERN_DEBUG "IRQ to pin mappings:\n");
1450         for (i = 0; i < NR_IRQS; i++) {
1451                 struct irq_pin_list *entry = irq_2_pin + i;
1452                 if (entry->pin < 0)
1453                         continue;
1454                 printk(KERN_DEBUG "IRQ%d ", i);
1455                 for (;;) {
1456                         printk("-> %d:%d", entry->apic, entry->pin);
1457                         if (!entry->next)
1458                                 break;
1459                         entry = irq_2_pin + entry->next;
1460                 }
1461                 printk("\n");
1462         }
1463
1464         printk(KERN_INFO ".................................... done.\n");
1465
1466         return;
1467 }
1468
1469 static void print_APIC_bitfield (int base)
1470 {
1471         unsigned int v;
1472         int i, j;
1473
1474         printk(KERN_DEBUG "0123456789abcdef0123456789abcdef\n" KERN_DEBUG);
1475         for (i = 0; i < 8; i++) {
1476                 v = apic_read(base + i*0x10);
1477                 for (j = 0; j < 32; j++) {
1478                         if (v & (1<<j))
1479                                 printk("1");
1480                         else
1481                                 printk("0");
1482                 }
1483                 printk("\n");
1484         }
1485 }
1486
1487 void /*__init*/ print_local_APIC(void * dummy)
1488 {
1489         unsigned int v, ver, maxlvt;
1490
1491         printk("\n" KERN_DEBUG "printing local APIC contents on CPU#%d/%d:\n",
1492                 smp_processor_id(), hard_smp_processor_id());
1493         v = apic_read(APIC_ID);
1494         printk(KERN_INFO "... APIC ID:      %08x (%01x)\n", v, GET_APIC_ID(v));
1495         v = apic_read(APIC_LVR);
1496         printk(KERN_INFO "... APIC VERSION: %08x\n", v);
1497         ver = GET_APIC_VERSION(v);
1498         maxlvt = get_maxlvt();
1499
1500         v = apic_read(APIC_TASKPRI);
1501         printk(KERN_DEBUG "... APIC TASKPRI: %08x (%02x)\n", v, v & APIC_TPRI_MASK);
1502
1503         if (APIC_INTEGRATED(ver)) {                     /* !82489DX */
1504                 v = apic_read(APIC_ARBPRI);
1505                 printk(KERN_DEBUG "... APIC ARBPRI: %08x (%02x)\n", v,
1506                         v & APIC_ARBPRI_MASK);
1507                 v = apic_read(APIC_PROCPRI);
1508                 printk(KERN_DEBUG "... APIC PROCPRI: %08x\n", v);
1509         }
1510
1511         v = apic_read(APIC_EOI);
1512         printk(KERN_DEBUG "... APIC EOI: %08x\n", v);
1513         v = apic_read(APIC_RRR);
1514         printk(KERN_DEBUG "... APIC RRR: %08x\n", v);
1515         v = apic_read(APIC_LDR);
1516         printk(KERN_DEBUG "... APIC LDR: %08x\n", v);
1517         v = apic_read(APIC_DFR);
1518         printk(KERN_DEBUG "... APIC DFR: %08x\n", v);
1519         v = apic_read(APIC_SPIV);
1520         printk(KERN_DEBUG "... APIC SPIV: %08x\n", v);
1521
1522         printk(KERN_DEBUG "... APIC ISR field:\n");
1523         print_APIC_bitfield(APIC_ISR);
1524         printk(KERN_DEBUG "... APIC TMR field:\n");
1525         print_APIC_bitfield(APIC_TMR);
1526         printk(KERN_DEBUG "... APIC IRR field:\n");
1527         print_APIC_bitfield(APIC_IRR);
1528
1529         if (APIC_INTEGRATED(ver)) {             /* !82489DX */
1530                 if (maxlvt > 3)         /* Due to the Pentium erratum 3AP. */
1531                         apic_write(APIC_ESR, 0);
1532                 v = apic_read(APIC_ESR);
1533                 printk(KERN_DEBUG "... APIC ESR: %08x\n", v);
1534         }
1535
1536         v = apic_read(APIC_ICR);
1537         printk(KERN_DEBUG "... APIC ICR: %08x\n", v);
1538         v = apic_read(APIC_ICR2);
1539         printk(KERN_DEBUG "... APIC ICR2: %08x\n", v);
1540
1541         v = apic_read(APIC_LVTT);
1542         printk(KERN_DEBUG "... APIC LVTT: %08x\n", v);
1543
1544         if (maxlvt > 3) {                       /* PC is LVT#4. */
1545                 v = apic_read(APIC_LVTPC);
1546                 printk(KERN_DEBUG "... APIC LVTPC: %08x\n", v);
1547         }
1548         v = apic_read(APIC_LVT0);
1549         printk(KERN_DEBUG "... APIC LVT0: %08x\n", v);
1550         v = apic_read(APIC_LVT1);
1551         printk(KERN_DEBUG "... APIC LVT1: %08x\n", v);
1552
1553         if (maxlvt > 2) {                       /* ERR is LVT#3. */
1554                 v = apic_read(APIC_LVTERR);
1555                 printk(KERN_DEBUG "... APIC LVTERR: %08x\n", v);
1556         }
1557
1558         v = apic_read(APIC_TMICT);
1559         printk(KERN_DEBUG "... APIC TMICT: %08x\n", v);
1560         v = apic_read(APIC_TMCCT);
1561         printk(KERN_DEBUG "... APIC TMCCT: %08x\n", v);
1562         v = apic_read(APIC_TDCR);
1563         printk(KERN_DEBUG "... APIC TDCR: %08x\n", v);
1564         printk("\n");
1565 }
1566
1567 void print_all_local_APICs (void)
1568 {
1569         on_each_cpu(print_local_APIC, NULL, 1, 1);
1570 }
1571
1572 void /*__init*/ print_PIC(void)
1573 {
1574         extern spinlock_t i8259A_lock;
1575         unsigned int v;
1576         unsigned long flags;
1577
1578         printk(KERN_DEBUG "\nprinting PIC contents\n");
1579
1580         spin_lock_irqsave(&i8259A_lock, flags);
1581
1582         v = inb(0xa1) << 8 | inb(0x21);
1583         printk(KERN_DEBUG "... PIC  IMR: %04x\n", v);
1584
1585         v = inb(0xa0) << 8 | inb(0x20);
1586         printk(KERN_DEBUG "... PIC  IRR: %04x\n", v);
1587
1588         outb(0x0b,0xa0);
1589         outb(0x0b,0x20);
1590         v = inb(0xa0) << 8 | inb(0x20);
1591         outb(0x0a,0xa0);
1592         outb(0x0a,0x20);
1593
1594         spin_unlock_irqrestore(&i8259A_lock, flags);
1595
1596         printk(KERN_DEBUG "... PIC  ISR: %04x\n", v);
1597
1598         v = inb(0x4d1) << 8 | inb(0x4d0);
1599         printk(KERN_DEBUG "... PIC ELCR: %04x\n", v);
1600 }
1601
1602 static void __init enable_IO_APIC(void)
1603 {
1604         union IO_APIC_reg_01 reg_01;
1605         int i;
1606         unsigned long flags;
1607
1608         for (i = 0; i < PIN_MAP_SIZE; i++) {
1609                 irq_2_pin[i].pin = -1;
1610                 irq_2_pin[i].next = 0;
1611         }
1612         if (!pirqs_enabled)
1613                 for (i = 0; i < MAX_PIRQS; i++)
1614                         pirq_entries[i] = -1;
1615
1616         /*
1617          * The number of IO-APIC IRQ registers (== #pins):
1618          */
1619         for (i = 0; i < nr_ioapics; i++) {
1620                 spin_lock_irqsave(&ioapic_lock, flags);
1621                 reg_01.raw = io_apic_read(i, 1);
1622                 spin_unlock_irqrestore(&ioapic_lock, flags);
1623                 nr_ioapic_registers[i] = reg_01.bits.entries+1;
1624         }
1625
1626         /*
1627          * Do not trust the IO-APIC being empty at bootup
1628          */
1629         clear_IO_APIC();
1630 }
1631
1632 /*
1633  * Not an __init, needed by the reboot code
1634  */
1635 void disable_IO_APIC(void)
1636 {
1637         /*
1638          * Clear the IO-APIC before rebooting:
1639          */
1640         clear_IO_APIC();
1641
1642         disconnect_bsp_APIC();
1643 }
1644
1645 /*
1646  * function to set the IO-APIC physical IDs based on the
1647  * values stored in the MPC table.
1648  *
1649  * by Matt Domsch <Matt_Domsch@dell.com>  Tue Dec 21 12:25:05 CST 1999
1650  */
1651
1652 #ifndef CONFIG_X86_NUMAQ
1653 static void __init setup_ioapic_ids_from_mpc(void)
1654 {
1655         union IO_APIC_reg_00 reg_00;
1656         physid_mask_t phys_id_present_map;
1657         int apic;
1658         int i;
1659         unsigned char old_id;
1660         unsigned long flags;
1661
1662         /*
1663          * This is broken; anything with a real cpu count has to
1664          * circumvent this idiocy regardless.
1665          */
1666         phys_id_present_map = ioapic_phys_id_map(phys_cpu_present_map);
1667
1668         /*
1669          * Set the IOAPIC ID to the value stored in the MPC table.
1670          */
1671         for (apic = 0; apic < nr_ioapics; apic++) {
1672
1673                 /* Read the register 0 value */
1674                 spin_lock_irqsave(&ioapic_lock, flags);
1675                 reg_00.raw = io_apic_read(apic, 0);
1676                 spin_unlock_irqrestore(&ioapic_lock, flags);
1677                 
1678                 old_id = mp_ioapics[apic].mpc_apicid;
1679
1680                 if (mp_ioapics[apic].mpc_apicid >= APIC_BROADCAST_ID) {
1681                         printk(KERN_ERR "BIOS bug, IO-APIC#%d ID is %d in the MPC table!...\n",
1682                                 apic, mp_ioapics[apic].mpc_apicid);
1683                         printk(KERN_ERR "... fixing up to %d. (tell your hw vendor)\n",
1684                                 reg_00.bits.ID);
1685                         mp_ioapics[apic].mpc_apicid = reg_00.bits.ID;
1686                 }
1687
1688                 /* Don't check I/O APIC IDs for some xAPIC systems.  They have
1689                  * no meaning without the serial APIC bus. */
1690                 if (NO_IOAPIC_CHECK)
1691                         continue;
1692                 /*
1693                  * Sanity check, is the ID really free? Every APIC in a
1694                  * system must have a unique ID or we get lots of nice
1695                  * 'stuck on smp_invalidate_needed IPI wait' messages.
1696                  */
1697                 if (check_apicid_used(phys_id_present_map,
1698                                         mp_ioapics[apic].mpc_apicid)) {
1699                         printk(KERN_ERR "BIOS bug, IO-APIC#%d ID %d is already used!...\n",
1700                                 apic, mp_ioapics[apic].mpc_apicid);
1701                         for (i = 0; i < APIC_BROADCAST_ID; i++)
1702                                 if (!physid_isset(i, phys_id_present_map))
1703                                         break;
1704                         if (i >= APIC_BROADCAST_ID)
1705                                 panic("Max APIC ID exceeded!\n");
1706                         printk(KERN_ERR "... fixing up to %d. (tell your hw vendor)\n",
1707                                 i);
1708                         physid_set(i, phys_id_present_map);
1709                         mp_ioapics[apic].mpc_apicid = i;
1710                 } else {
1711                         physid_mask_t tmp;
1712                         tmp = apicid_to_cpu_present(mp_ioapics[apic].mpc_apicid);
1713                         printk("Setting %d in the phys_id_present_map\n", mp_ioapics[apic].mpc_apicid);
1714                         physids_or(phys_id_present_map, phys_id_present_map, tmp);
1715                 }
1716
1717
1718                 /*
1719                  * We need to adjust the IRQ routing table
1720                  * if the ID changed.
1721                  */
1722                 if (old_id != mp_ioapics[apic].mpc_apicid)
1723                         for (i = 0; i < mp_irq_entries; i++)
1724                                 if (mp_irqs[i].mpc_dstapic == old_id)
1725                                         mp_irqs[i].mpc_dstapic
1726                                                 = mp_ioapics[apic].mpc_apicid;
1727
1728                 /*
1729                  * Read the right value from the MPC table and
1730                  * write it into the ID register.
1731                  */
1732                 printk(KERN_INFO "...changing IO-APIC physical APIC ID to %d ...",
1733                                         mp_ioapics[apic].mpc_apicid);
1734
1735                 reg_00.bits.ID = mp_ioapics[apic].mpc_apicid;
1736                 spin_lock_irqsave(&ioapic_lock, flags);
1737                 io_apic_write(apic, 0, reg_00.raw);
1738                 spin_unlock_irqrestore(&ioapic_lock, flags);
1739
1740                 /*
1741                  * Sanity check
1742                  */
1743                 spin_lock_irqsave(&ioapic_lock, flags);
1744                 reg_00.raw = io_apic_read(apic, 0);
1745                 spin_unlock_irqrestore(&ioapic_lock, flags);
1746                 if (reg_00.bits.ID != mp_ioapics[apic].mpc_apicid)
1747                         panic("could not set ID!\n");
1748                 else
1749                         printk(" ok.\n");
1750         }
1751 }
1752 #else
1753 static void __init setup_ioapic_ids_from_mpc(void) { }
1754 #endif
1755
1756 /*
1757  * There is a nasty bug in some older SMP boards, their mptable lies
1758  * about the timer IRQ. We do the following to work around the situation:
1759  *
1760  *      - timer IRQ defaults to IO-APIC IRQ
1761  *      - if this function detects that timer IRQs are defunct, then we fall
1762  *        back to ISA timer IRQs
1763  */
1764 static int __init timer_irq_works(void)
1765 {
1766         unsigned long t1 = jiffies;
1767
1768         local_irq_enable();
1769         /* Let ten ticks pass... */
1770         mdelay((10 * 1000) / HZ);
1771
1772         /*
1773          * Expect a few ticks at least, to be sure some possible
1774          * glue logic does not lock up after one or two first
1775          * ticks in a non-ExtINT mode.  Also the local APIC
1776          * might have cached one ExtINT interrupt.  Finally, at
1777          * least one tick may be lost due to delays.
1778          */
1779         if (jiffies - t1 > 4)
1780                 return 1;
1781
1782         return 0;
1783 }
1784
1785 /*
1786  * In the SMP+IOAPIC case it might happen that there are an unspecified
1787  * number of pending IRQ events unhandled. These cases are very rare,
1788  * so we 'resend' these IRQs via IPIs, to the same CPU. It's much
1789  * better to do it this way as thus we do not have to be aware of
1790  * 'pending' interrupts in the IRQ path, except at this point.
1791  */
1792 /*
1793  * Edge triggered needs to resend any interrupt
1794  * that was delayed but this is now handled in the device
1795  * independent code.
1796  */
1797
1798 /*
1799  * Starting up a edge-triggered IO-APIC interrupt is
1800  * nasty - we need to make sure that we get the edge.
1801  * If it is already asserted for some reason, we need
1802  * return 1 to indicate that is was pending.
1803  *
1804  * This is not complete - we should be able to fake
1805  * an edge even if it isn't on the 8259A...
1806  */
1807 static unsigned int startup_edge_ioapic_irq(unsigned int irq)
1808 {
1809         int was_pending = 0;
1810         unsigned long flags;
1811
1812         spin_lock_irqsave(&ioapic_lock, flags);
1813         if (irq < 16) {
1814                 disable_8259A_irq(irq);
1815                 if (i8259A_irq_pending(irq))
1816                         was_pending = 1;
1817         }
1818         __unmask_IO_APIC_irq(irq);
1819         spin_unlock_irqrestore(&ioapic_lock, flags);
1820
1821         return was_pending;
1822 }
1823
1824 /*
1825  * Once we have recorded IRQ_PENDING already, we can mask the
1826  * interrupt for real. This prevents IRQ storms from unhandled
1827  * devices.
1828  */
1829 static void ack_edge_ioapic_irq(unsigned int irq)
1830 {
1831         move_irq(irq);
1832         if ((irq_desc[irq].status & (IRQ_PENDING | IRQ_DISABLED))
1833                                         == (IRQ_PENDING | IRQ_DISABLED))
1834                 mask_IO_APIC_irq(irq);
1835         ack_APIC_irq();
1836 }
1837
1838 /*
1839  * Level triggered interrupts can just be masked,
1840  * and shutting down and starting up the interrupt
1841  * is the same as enabling and disabling them -- except
1842  * with a startup need to return a "was pending" value.
1843  *
1844  * Level triggered interrupts are special because we
1845  * do not touch any IO-APIC register while handling
1846  * them. We ack the APIC in the end-IRQ handler, not
1847  * in the start-IRQ-handler. Protection against reentrance
1848  * from the same interrupt is still provided, both by the
1849  * generic IRQ layer and by the fact that an unacked local
1850  * APIC does not accept IRQs.
1851  */
1852 static unsigned int startup_level_ioapic_irq (unsigned int irq)
1853 {
1854         unmask_IO_APIC_irq(irq);
1855
1856         return 0; /* don't check for pending */
1857 }
1858
1859 static void end_level_ioapic_irq (unsigned int irq)
1860 {
1861         unsigned long v;
1862         int i;
1863
1864         move_irq(irq);
1865 /*
1866  * It appears there is an erratum which affects at least version 0x11
1867  * of I/O APIC (that's the 82093AA and cores integrated into various
1868  * chipsets).  Under certain conditions a level-triggered interrupt is
1869  * erroneously delivered as edge-triggered one but the respective IRR
1870  * bit gets set nevertheless.  As a result the I/O unit expects an EOI
1871  * message but it will never arrive and further interrupts are blocked
1872  * from the source.  The exact reason is so far unknown, but the
1873  * phenomenon was observed when two consecutive interrupt requests
1874  * from a given source get delivered to the same CPU and the source is
1875  * temporarily disabled in between.
1876  *
1877  * A workaround is to simulate an EOI message manually.  We achieve it
1878  * by setting the trigger mode to edge and then to level when the edge
1879  * trigger mode gets detected in the TMR of a local APIC for a
1880  * level-triggered interrupt.  We mask the source for the time of the
1881  * operation to prevent an edge-triggered interrupt escaping meanwhile.
1882  * The idea is from Manfred Spraul.  --macro
1883  */
1884         i = IO_APIC_VECTOR(irq);
1885
1886         v = apic_read(APIC_TMR + ((i & ~0x1f) >> 1));
1887
1888         ack_APIC_irq();
1889
1890         if (!(v & (1 << (i & 0x1f)))) {
1891 #ifdef APIC_LOCKUP_DEBUG
1892                 struct irq_pin_list *entry;
1893 #endif
1894
1895 #ifdef APIC_MISMATCH_DEBUG
1896                 atomic_inc(&irq_mis_count);
1897 #endif
1898                 spin_lock(&ioapic_lock);
1899                 __mask_and_edge_IO_APIC_irq(irq);
1900 #ifdef APIC_LOCKUP_DEBUG
1901                 for (entry = irq_2_pin + irq;;) {
1902                         unsigned int reg;
1903
1904                         if (entry->pin == -1)
1905                                 break;
1906                         reg = io_apic_read(entry->apic, 0x10 + entry->pin * 2);
1907                         if (reg & 0x00004000)
1908                                 printk(KERN_CRIT "Aieee!!!  Remote IRR"
1909                                         " still set after unlock!\n");
1910                         if (!entry->next)
1911                                 break;
1912                         entry = irq_2_pin + entry->next;
1913                 }
1914 #endif
1915                 __unmask_and_level_IO_APIC_irq(irq);
1916                 spin_unlock(&ioapic_lock);
1917         }
1918 }
1919
1920 #ifdef CONFIG_PCI_USE_VECTOR
1921 static unsigned int startup_edge_ioapic_vector(unsigned int vector)
1922 {
1923         int irq = vector_to_irq(vector);
1924
1925         return startup_edge_ioapic_irq(irq);
1926 }
1927
1928 static void ack_edge_ioapic_vector(unsigned int vector)
1929 {
1930         int irq = vector_to_irq(vector);
1931
1932         ack_edge_ioapic_irq(irq);
1933 }
1934
1935 static unsigned int startup_level_ioapic_vector (unsigned int vector)
1936 {
1937         int irq = vector_to_irq(vector);
1938
1939         return startup_level_ioapic_irq (irq);
1940 }
1941
1942 static void end_level_ioapic_vector (unsigned int vector)
1943 {
1944         int irq = vector_to_irq(vector);
1945
1946         end_level_ioapic_irq(irq);
1947 }
1948
1949 static void mask_IO_APIC_vector (unsigned int vector)
1950 {
1951         int irq = vector_to_irq(vector);
1952
1953         mask_IO_APIC_irq(irq);
1954 }
1955
1956 static void unmask_IO_APIC_vector (unsigned int vector)
1957 {
1958         int irq = vector_to_irq(vector);
1959
1960         unmask_IO_APIC_irq(irq);
1961 }
1962
1963 static void set_ioapic_affinity_vector (unsigned int vector,
1964                                         cpumask_t cpu_mask)
1965 {
1966         int irq = vector_to_irq(vector);
1967
1968         set_ioapic_affinity_irq(irq, cpu_mask);
1969 }
1970 #endif
1971
1972 /*
1973  * Level and edge triggered IO-APIC interrupts need different handling,
1974  * so we use two separate IRQ descriptors. Edge triggered IRQs can be
1975  * handled with the level-triggered descriptor, but that one has slightly
1976  * more overhead. Level-triggered interrupts cannot be handled with the
1977  * edge-triggered handler, without risking IRQ storms and other ugly
1978  * races.
1979  */
1980 static struct hw_interrupt_type ioapic_edge_type = {
1981         .typename       = "IO-APIC-edge",
1982         .startup        = startup_edge_ioapic,
1983         .shutdown       = shutdown_edge_ioapic,
1984         .enable         = enable_edge_ioapic,
1985         .disable        = disable_edge_ioapic,
1986         .ack            = ack_edge_ioapic,
1987         .end            = end_edge_ioapic,
1988         .set_affinity   = set_ioapic_affinity,
1989 };
1990
1991 static struct hw_interrupt_type ioapic_level_type = {
1992         .typename       = "IO-APIC-level",
1993         .startup        = startup_level_ioapic,
1994         .shutdown       = shutdown_level_ioapic,
1995         .enable         = enable_level_ioapic,
1996         .disable        = disable_level_ioapic,
1997         .ack            = mask_and_ack_level_ioapic,
1998         .end            = end_level_ioapic,
1999         .set_affinity   = set_ioapic_affinity,
2000 };
2001
2002 static inline void init_IO_APIC_traps(void)
2003 {
2004         int irq;
2005
2006         /*
2007          * NOTE! The local APIC isn't very good at handling
2008          * multiple interrupts at the same interrupt level.
2009          * As the interrupt level is determined by taking the
2010          * vector number and shifting that right by 4, we
2011          * want to spread these out a bit so that they don't
2012          * all fall in the same interrupt level.
2013          *
2014          * Also, we've got to be careful not to trash gate
2015          * 0x80, because int 0x80 is hm, kind of importantish. ;)
2016          */
2017         for (irq = 0; irq < NR_IRQS ; irq++) {
2018                 int tmp = irq;
2019                 if (use_pci_vector()) {
2020                         if (!platform_legacy_irq(tmp))
2021                                 if ((tmp = vector_to_irq(tmp)) == -1)
2022                                         continue;
2023                 }
2024                 if (IO_APIC_IRQ(tmp) && !IO_APIC_VECTOR(tmp)) {
2025                         /*
2026                          * Hmm.. We don't have an entry for this,
2027                          * so default to an old-fashioned 8259
2028                          * interrupt if we can..
2029                          */
2030                         if (irq < 16)
2031                                 make_8259A_irq(irq);
2032                         else
2033                                 /* Strange. Oh, well.. */
2034                                 irq_desc[irq].handler = &no_irq_type;
2035                 }
2036         }
2037 }
2038
2039 static void enable_lapic_irq (unsigned int irq)
2040 {
2041         unsigned long v;
2042
2043         v = apic_read(APIC_LVT0);
2044         apic_write_around(APIC_LVT0, v & ~APIC_LVT_MASKED);
2045 }
2046
2047 static void disable_lapic_irq (unsigned int irq)
2048 {
2049         unsigned long v;
2050
2051         v = apic_read(APIC_LVT0);
2052         apic_write_around(APIC_LVT0, v | APIC_LVT_MASKED);
2053 }
2054
2055 static void ack_lapic_irq (unsigned int irq)
2056 {
2057         ack_APIC_irq();
2058 }
2059
2060 static void end_lapic_irq (unsigned int i) { /* nothing */ }
2061
2062 static struct hw_interrupt_type lapic_irq_type = {
2063         .typename       = "local-APIC-edge",
2064         .startup        = NULL, /* startup_irq() not used for IRQ0 */
2065         .shutdown       = NULL, /* shutdown_irq() not used for IRQ0 */
2066         .enable         = enable_lapic_irq,
2067         .disable        = disable_lapic_irq,
2068         .ack            = ack_lapic_irq,
2069         .end            = end_lapic_irq
2070 };
2071
2072 static void setup_nmi (void)
2073 {
2074         /*
2075          * Dirty trick to enable the NMI watchdog ...
2076          * We put the 8259A master into AEOI mode and
2077          * unmask on all local APICs LVT0 as NMI.
2078          *
2079          * The idea to use the 8259A in AEOI mode ('8259A Virtual Wire')
2080          * is from Maciej W. Rozycki - so we do not have to EOI from
2081          * the NMI handler or the timer interrupt.
2082          */ 
2083         printk(KERN_INFO "activating NMI Watchdog ...");
2084
2085         on_each_cpu(enable_NMI_through_LVT0, NULL, 1, 1);
2086
2087         printk(" done.\n");
2088 }
2089
2090 /*
2091  * This looks a bit hackish but it's about the only one way of sending
2092  * a few INTA cycles to 8259As and any associated glue logic.  ICR does
2093  * not support the ExtINT mode, unfortunately.  We need to send these
2094  * cycles as some i82489DX-based boards have glue logic that keeps the
2095  * 8259A interrupt line asserted until INTA.  --macro
2096  */
2097 static inline void unlock_ExtINT_logic(void)
2098 {
2099         int pin, i;
2100         struct IO_APIC_route_entry entry0, entry1;
2101         unsigned char save_control, save_freq_select;
2102         unsigned long flags;
2103
2104         pin = find_isa_irq_pin(8, mp_INT);
2105         if (pin == -1)
2106                 return;
2107
2108         spin_lock_irqsave(&ioapic_lock, flags);
2109         *(((int *)&entry0) + 1) = io_apic_read(0, 0x11 + 2 * pin);
2110         *(((int *)&entry0) + 0) = io_apic_read(0, 0x10 + 2 * pin);
2111         spin_unlock_irqrestore(&ioapic_lock, flags);
2112         clear_IO_APIC_pin(0, pin);
2113
2114         memset(&entry1, 0, sizeof(entry1));
2115
2116         entry1.dest_mode = 0;                   /* physical delivery */
2117         entry1.mask = 0;                        /* unmask IRQ now */
2118         entry1.dest.physical.physical_dest = hard_smp_processor_id();
2119         entry1.delivery_mode = dest_ExtINT;
2120         entry1.polarity = entry0.polarity;
2121         entry1.trigger = 0;
2122         entry1.vector = 0;
2123
2124         spin_lock_irqsave(&ioapic_lock, flags);
2125         io_apic_write(0, 0x11 + 2 * pin, *(((int *)&entry1) + 1));
2126         io_apic_write(0, 0x10 + 2 * pin, *(((int *)&entry1) + 0));
2127         spin_unlock_irqrestore(&ioapic_lock, flags);
2128
2129         save_control = CMOS_READ(RTC_CONTROL);
2130         save_freq_select = CMOS_READ(RTC_FREQ_SELECT);
2131         CMOS_WRITE((save_freq_select & ~RTC_RATE_SELECT) | 0x6,
2132                    RTC_FREQ_SELECT);
2133         CMOS_WRITE(save_control | RTC_PIE, RTC_CONTROL);
2134
2135         i = 100;
2136         while (i-- > 0) {
2137                 mdelay(10);
2138                 if ((CMOS_READ(RTC_INTR_FLAGS) & RTC_PF) == RTC_PF)
2139                         i -= 10;
2140         }
2141
2142         CMOS_WRITE(save_control, RTC_CONTROL);
2143         CMOS_WRITE(save_freq_select, RTC_FREQ_SELECT);
2144         clear_IO_APIC_pin(0, pin);
2145
2146         spin_lock_irqsave(&ioapic_lock, flags);
2147         io_apic_write(0, 0x11 + 2 * pin, *(((int *)&entry0) + 1));
2148         io_apic_write(0, 0x10 + 2 * pin, *(((int *)&entry0) + 0));
2149         spin_unlock_irqrestore(&ioapic_lock, flags);
2150 }
2151
2152 /*
2153  * This code may look a bit paranoid, but it's supposed to cooperate with
2154  * a wide range of boards and BIOS bugs.  Fortunately only the timer IRQ
2155  * is so screwy.  Thanks to Brian Perkins for testing/hacking this beast
2156  * fanatically on his truly buggy board.
2157  */
2158 static inline void check_timer(void)
2159 {
2160         int pin1, pin2;
2161         int vector;
2162
2163         /*
2164          * get/set the timer IRQ vector:
2165          */
2166         disable_8259A_irq(0);
2167         vector = assign_irq_vector(0);
2168         set_intr_gate(vector, interrupt[0]);
2169
2170         /*
2171          * Subtle, code in do_timer_interrupt() expects an AEOI
2172          * mode for the 8259A whenever interrupts are routed
2173          * through I/O APICs.  Also IRQ0 has to be enabled in
2174          * the 8259A which implies the virtual wire has to be
2175          * disabled in the local APIC.
2176          */
2177         apic_write_around(APIC_LVT0, APIC_LVT_MASKED | APIC_DM_EXTINT);
2178         init_8259A(1);
2179         timer_ack = 1;
2180         enable_8259A_irq(0);
2181
2182         pin1 = find_isa_irq_pin(0, mp_INT);
2183         pin2 = find_isa_irq_pin(0, mp_ExtINT);
2184
2185         printk(KERN_INFO "..TIMER: vector=0x%02X pin1=%d pin2=%d\n", vector, pin1, pin2);
2186
2187         if (pin1 != -1) {
2188                 /*
2189                  * Ok, does IRQ0 through the IOAPIC work?
2190                  */
2191                 unmask_IO_APIC_irq(0);
2192                 if (timer_irq_works()) {
2193                         if (nmi_watchdog == NMI_IO_APIC) {
2194                                 disable_8259A_irq(0);
2195                                 setup_nmi();
2196                                 enable_8259A_irq(0);
2197                                 check_nmi_watchdog();
2198                         }
2199                         return;
2200                 }
2201                 clear_IO_APIC_pin(0, pin1);
2202                 printk(KERN_ERR "..MP-BIOS bug: 8254 timer not connected to IO-APIC\n");
2203         }
2204
2205         printk(KERN_INFO "...trying to set up timer (IRQ0) through the 8259A ... ");
2206         if (pin2 != -1) {
2207                 printk("\n..... (found pin %d) ...", pin2);
2208                 /*
2209                  * legacy devices should be connected to IO APIC #0
2210                  */
2211                 setup_ExtINT_IRQ0_pin(pin2, vector);
2212                 if (timer_irq_works()) {
2213                         printk("works.\n");
2214                         if (pin1 != -1)
2215                                 replace_pin_at_irq(0, 0, pin1, 0, pin2);
2216                         else
2217                                 add_pin_to_irq(0, 0, pin2);
2218                         if (nmi_watchdog == NMI_IO_APIC) {
2219                                 setup_nmi();
2220                                 check_nmi_watchdog();
2221                         }
2222                         return;
2223                 }
2224                 /*
2225                  * Cleanup, just in case ...
2226                  */
2227                 clear_IO_APIC_pin(0, pin2);
2228         }
2229         printk(" failed.\n");
2230
2231         if (nmi_watchdog == NMI_IO_APIC) {
2232                 printk(KERN_WARNING "timer doesn't work through the IO-APIC - disabling NMI Watchdog!\n");
2233                 nmi_watchdog = 0;
2234         }
2235
2236         printk(KERN_INFO "...trying to set up timer as Virtual Wire IRQ...");
2237
2238         disable_8259A_irq(0);
2239         irq_desc[0].handler = &lapic_irq_type;
2240         apic_write_around(APIC_LVT0, APIC_DM_FIXED | vector);   /* Fixed mode */
2241         enable_8259A_irq(0);
2242
2243         if (timer_irq_works()) {
2244                 printk(" works.\n");
2245                 return;
2246         }
2247         apic_write_around(APIC_LVT0, APIC_LVT_MASKED | APIC_DM_FIXED | vector);
2248         printk(" failed.\n");
2249
2250         printk(KERN_INFO "...trying to set up timer as ExtINT IRQ...");
2251
2252         timer_ack = 0;
2253         init_8259A(0);
2254         make_8259A_irq(0);
2255         apic_write_around(APIC_LVT0, APIC_DM_EXTINT);
2256
2257         unlock_ExtINT_logic();
2258
2259         if (timer_irq_works()) {
2260                 printk(" works.\n");
2261                 return;
2262         }
2263         printk(" failed :(.\n");
2264         panic("IO-APIC + timer doesn't work! pester mingo@redhat.com");
2265 }
2266
2267 /*
2268  *
2269  * IRQ's that are handled by the PIC in the MPS IOAPIC case.
2270  * - IRQ2 is the cascade IRQ, and cannot be a io-apic IRQ.
2271  *   Linux doesn't really care, as it's not actually used
2272  *   for any interrupt handling anyway.
2273  */
2274 #define PIC_IRQS        (1 << PIC_CASCADE_IR)
2275
2276 void __init setup_IO_APIC(void)
2277 {
2278         enable_IO_APIC();
2279
2280         if (acpi_ioapic)
2281                 io_apic_irqs = ~0;      /* all IRQs go through IOAPIC */
2282         else
2283                 io_apic_irqs = ~PIC_IRQS;
2284
2285         printk("ENABLING IO-APIC IRQs\n");
2286
2287         /*
2288          * Set up IO-APIC IRQ routing.
2289          */
2290         if (!acpi_ioapic)
2291                 setup_ioapic_ids_from_mpc();
2292         sync_Arb_IDs();
2293         setup_IO_APIC_irqs();
2294         init_IO_APIC_traps();
2295         check_timer();
2296         if (!acpi_ioapic)
2297                 print_IO_APIC();
2298 }
2299
2300 /*
2301  *      Called after all the initialization is done. If we didnt find any
2302  *      APIC bugs then we can allow the modify fast path
2303  */
2304  
2305 static int __init io_apic_bug_finalize(void)
2306 {
2307         if(sis_apic_bug == -1)
2308                 sis_apic_bug = 0;
2309         return 0;
2310 }
2311
2312 late_initcall(io_apic_bug_finalize);
2313
2314 /* --------------------------------------------------------------------------
2315                           ACPI-based IOAPIC Configuration
2316    -------------------------------------------------------------------------- */
2317
2318 #ifdef CONFIG_ACPI_BOOT
2319
2320 #define IO_APIC_MAX_ID APIC_BROADCAST_ID
2321
2322 int __init io_apic_get_unique_id (int ioapic, int apic_id)
2323 {
2324         union IO_APIC_reg_00 reg_00;
2325         static physid_mask_t apic_id_map = PHYSID_MASK_NONE;
2326         physid_mask_t tmp;
2327         unsigned long flags;
2328         int i = 0;
2329
2330         /*
2331          * The P4 platform supports up to 256 APIC IDs on two separate APIC 
2332          * buses (one for LAPICs, one for IOAPICs), where predecessors only 
2333          * supports up to 16 on one shared APIC bus.
2334          * 
2335          * TBD: Expand LAPIC/IOAPIC support on P4-class systems to take full
2336          *      advantage of new APIC bus architecture.
2337          */
2338
2339         if (physids_empty(apic_id_map))
2340                 apic_id_map = ioapic_phys_id_map(phys_cpu_present_map);
2341
2342         spin_lock_irqsave(&ioapic_lock, flags);
2343         reg_00.raw = io_apic_read(ioapic, 0);
2344         spin_unlock_irqrestore(&ioapic_lock, flags);
2345
2346         if (apic_id >= IO_APIC_MAX_ID) {
2347                 printk(KERN_WARNING "IOAPIC[%d]: Invalid apic_id %d, trying "
2348                         "%d\n", ioapic, apic_id, reg_00.bits.ID);
2349                 apic_id = reg_00.bits.ID;
2350         }
2351
2352         /*
2353          * Every APIC in a system must have a unique ID or we get lots of nice 
2354          * 'stuck on smp_invalidate_needed IPI wait' messages.
2355          */
2356         if (check_apicid_used(apic_id_map, apic_id)) {
2357
2358                 for (i = 0; i < IO_APIC_MAX_ID; i++) {
2359                         if (!check_apicid_used(apic_id_map, i))
2360                                 break;
2361                 }
2362
2363                 if (i == IO_APIC_MAX_ID)
2364                         panic("Max apic_id exceeded!\n");
2365
2366                 printk(KERN_WARNING "IOAPIC[%d]: apic_id %d already used, "
2367                         "trying %d\n", ioapic, apic_id, i);
2368
2369                 apic_id = i;
2370         } 
2371
2372         tmp = apicid_to_cpu_present(apic_id);
2373         physids_or(apic_id_map, apic_id_map, tmp);
2374
2375         if (reg_00.bits.ID != apic_id) {
2376                 reg_00.bits.ID = apic_id;
2377
2378                 spin_lock_irqsave(&ioapic_lock, flags);
2379                 io_apic_write(ioapic, 0, reg_00.raw);
2380                 reg_00.raw = io_apic_read(ioapic, 0);
2381                 spin_unlock_irqrestore(&ioapic_lock, flags);
2382
2383                 /* Sanity check */
2384                 if (reg_00.bits.ID != apic_id)
2385                         panic("IOAPIC[%d]: Unable change apic_id!\n", ioapic);
2386         }
2387
2388         printk(KERN_INFO "IOAPIC[%d]: Assigned apic_id %d\n", ioapic, apic_id);
2389
2390         return apic_id;
2391 }
2392
2393
2394 int __init io_apic_get_version (int ioapic)
2395 {
2396         union IO_APIC_reg_01    reg_01;
2397         unsigned long flags;
2398
2399         spin_lock_irqsave(&ioapic_lock, flags);
2400         reg_01.raw = io_apic_read(ioapic, 1);
2401         spin_unlock_irqrestore(&ioapic_lock, flags);
2402
2403         return reg_01.bits.version;
2404 }
2405
2406
2407 int __init io_apic_get_redir_entries (int ioapic)
2408 {
2409         union IO_APIC_reg_01    reg_01;
2410         unsigned long flags;
2411
2412         spin_lock_irqsave(&ioapic_lock, flags);
2413         reg_01.raw = io_apic_read(ioapic, 1);
2414         spin_unlock_irqrestore(&ioapic_lock, flags);
2415
2416         return reg_01.bits.entries;
2417 }
2418
2419
2420 int io_apic_set_pci_routing (int ioapic, int pin, int irq, int edge_level, int active_high_low)
2421 {
2422         struct IO_APIC_route_entry entry;
2423         unsigned long flags;
2424
2425         if (!IO_APIC_IRQ(irq)) {
2426                 printk(KERN_ERR "IOAPIC[%d]: Invalid reference to IRQ 0\n",
2427                         ioapic);
2428                 return -EINVAL;
2429         }
2430
2431         /*
2432          * Generate a PCI IRQ routing entry and program the IOAPIC accordingly.
2433          * Note that we mask (disable) IRQs now -- these get enabled when the
2434          * corresponding device driver registers for this IRQ.
2435          */
2436
2437         memset(&entry,0,sizeof(entry));
2438
2439         entry.delivery_mode = INT_DELIVERY_MODE;
2440         entry.dest_mode = INT_DEST_MODE;
2441         entry.dest.logical.logical_dest = cpu_mask_to_apicid(TARGET_CPUS);
2442         entry.trigger = edge_level;
2443         entry.polarity = active_high_low;
2444         entry.mask  = 1;
2445
2446         /*
2447          * IRQs < 16 are already in the irq_2_pin[] map
2448          */
2449         if (irq >= 16)
2450                 add_pin_to_irq(irq, ioapic, pin);
2451
2452         entry.vector = assign_irq_vector(irq);
2453
2454         Dprintk(KERN_DEBUG "IOAPIC[%d]: Set PCI routing entry (%d-%d -> 0x%x -> "
2455                 "IRQ %d Mode:%i Active:%i)\n", ioapic, 
2456                 mp_ioapics[ioapic].mpc_apicid, pin, entry.vector, irq, edge_level, active_high_low);
2457
2458         if (use_pci_vector() && !platform_legacy_irq(irq))
2459                 irq = IO_APIC_VECTOR(irq);
2460         if (edge_level) {
2461                 irq_desc[irq].handler = &ioapic_level_type;
2462         } else {
2463                 irq_desc[irq].handler = &ioapic_edge_type;
2464         }
2465
2466         set_intr_gate(entry.vector, interrupt[irq]);
2467
2468         if (!ioapic && (irq < 16))
2469                 disable_8259A_irq(irq);
2470
2471         spin_lock_irqsave(&ioapic_lock, flags);
2472         io_apic_write(ioapic, 0x11+2*pin, *(((int *)&entry)+1));
2473         io_apic_write(ioapic, 0x10+2*pin, *(((int *)&entry)+0));
2474         spin_unlock_irqrestore(&ioapic_lock, flags);
2475
2476         return 0;
2477 }
2478
2479 #endif /*CONFIG_ACPI_BOOT*/