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