[PATCH] i386: move apic init in init_IRQs
[safe/jmp/linux-2.6] / arch / i386 / kernel / apic.c
1 /*
2  *      Local APIC handling, local APIC timers
3  *
4  *      (c) 1999, 2000 Ingo Molnar <mingo@redhat.com>
5  *
6  *      Fixes
7  *      Maciej W. Rozycki       :       Bits for genuine 82489DX APICs;
8  *                                      thanks to Eric Gilmore
9  *                                      and Rolf G. Tews
10  *                                      for testing these extensively.
11  *      Maciej W. Rozycki       :       Various updates and fixes.
12  *      Mikael Pettersson       :       Power Management for UP-APIC.
13  *      Pavel Machek and
14  *      Mikael Pettersson       :       PM converted to driver model.
15  */
16
17 #include <linux/config.h>
18 #include <linux/init.h>
19
20 #include <linux/mm.h>
21 #include <linux/delay.h>
22 #include <linux/bootmem.h>
23 #include <linux/smp_lock.h>
24 #include <linux/interrupt.h>
25 #include <linux/mc146818rtc.h>
26 #include <linux/kernel_stat.h>
27 #include <linux/sysdev.h>
28 #include <linux/cpu.h>
29
30 #include <asm/atomic.h>
31 #include <asm/smp.h>
32 #include <asm/mtrr.h>
33 #include <asm/mpspec.h>
34 #include <asm/desc.h>
35 #include <asm/arch_hooks.h>
36 #include <asm/hpet.h>
37 #include <asm/i8253.h>
38
39 #include <mach_apic.h>
40
41 #include "io_ports.h"
42
43 /*
44  * Knob to control our willingness to enable the local APIC.
45  */
46 int enable_local_apic __initdata = 0; /* -1=force-disable, +1=force-enable */
47
48 /*
49  * Debug level
50  */
51 int apic_verbosity;
52
53
54 static void apic_pm_activate(void);
55
56 /*
57  * 'what should we do if we get a hw irq event on an illegal vector'.
58  * each architecture has to answer this themselves.
59  */
60 void ack_bad_irq(unsigned int irq)
61 {
62         printk("unexpected IRQ trap at vector %02x\n", irq);
63         /*
64          * Currently unexpected vectors happen only on SMP and APIC.
65          * We _must_ ack these because every local APIC has only N
66          * irq slots per priority level, and a 'hanging, unacked' IRQ
67          * holds up an irq slot - in excessive cases (when multiple
68          * unexpected vectors occur) that might lock up the APIC
69          * completely.
70          */
71         ack_APIC_irq();
72 }
73
74 void __init apic_intr_init(void)
75 {
76 #ifdef CONFIG_SMP
77         smp_intr_init();
78 #endif
79         /* self generated IPI for local APIC timer */
80         set_intr_gate(LOCAL_TIMER_VECTOR, apic_timer_interrupt);
81
82         /* IPI vectors for APIC spurious and error interrupts */
83         set_intr_gate(SPURIOUS_APIC_VECTOR, spurious_interrupt);
84         set_intr_gate(ERROR_APIC_VECTOR, error_interrupt);
85
86         /* thermal monitor LVT interrupt */
87 #ifdef CONFIG_X86_MCE_P4THERMAL
88         set_intr_gate(THERMAL_APIC_VECTOR, thermal_interrupt);
89 #endif
90 }
91
92 /* Using APIC to generate smp_local_timer_interrupt? */
93 int using_apic_timer = 0;
94
95 static DEFINE_PER_CPU(int, prof_multiplier) = 1;
96 static DEFINE_PER_CPU(int, prof_old_multiplier) = 1;
97 static DEFINE_PER_CPU(int, prof_counter) = 1;
98
99 static int enabled_via_apicbase;
100
101 void enable_NMI_through_LVT0 (void * dummy)
102 {
103         unsigned int v, ver;
104
105         ver = apic_read(APIC_LVR);
106         ver = GET_APIC_VERSION(ver);
107         v = APIC_DM_NMI;                        /* unmask and set to NMI */
108         if (!APIC_INTEGRATED(ver))              /* 82489DX */
109                 v |= APIC_LVT_LEVEL_TRIGGER;
110         apic_write_around(APIC_LVT0, v);
111 }
112
113 int get_physical_broadcast(void)
114 {
115         unsigned int lvr, version;
116         lvr = apic_read(APIC_LVR);
117         version = GET_APIC_VERSION(lvr);
118         if (!APIC_INTEGRATED(version) || version >= 0x14)
119                 return 0xff;
120         else
121                 return 0xf;
122 }
123
124 int get_maxlvt(void)
125 {
126         unsigned int v, ver, maxlvt;
127
128         v = apic_read(APIC_LVR);
129         ver = GET_APIC_VERSION(v);
130         /* 82489DXs do not report # of LVT entries. */
131         maxlvt = APIC_INTEGRATED(ver) ? GET_APIC_MAXLVT(v) : 2;
132         return maxlvt;
133 }
134
135 void clear_local_APIC(void)
136 {
137         int maxlvt;
138         unsigned long v;
139
140         maxlvt = get_maxlvt();
141
142         /*
143          * Masking an LVT entry on a P6 can trigger a local APIC error
144          * if the vector is zero. Mask LVTERR first to prevent this.
145          */
146         if (maxlvt >= 3) {
147                 v = ERROR_APIC_VECTOR; /* any non-zero vector will do */
148                 apic_write_around(APIC_LVTERR, v | APIC_LVT_MASKED);
149         }
150         /*
151          * Careful: we have to set masks only first to deassert
152          * any level-triggered sources.
153          */
154         v = apic_read(APIC_LVTT);
155         apic_write_around(APIC_LVTT, v | APIC_LVT_MASKED);
156         v = apic_read(APIC_LVT0);
157         apic_write_around(APIC_LVT0, v | APIC_LVT_MASKED);
158         v = apic_read(APIC_LVT1);
159         apic_write_around(APIC_LVT1, v | APIC_LVT_MASKED);
160         if (maxlvt >= 4) {
161                 v = apic_read(APIC_LVTPC);
162                 apic_write_around(APIC_LVTPC, v | APIC_LVT_MASKED);
163         }
164
165 /* lets not touch this if we didn't frob it */
166 #ifdef CONFIG_X86_MCE_P4THERMAL
167         if (maxlvt >= 5) {
168                 v = apic_read(APIC_LVTTHMR);
169                 apic_write_around(APIC_LVTTHMR, v | APIC_LVT_MASKED);
170         }
171 #endif
172         /*
173          * Clean APIC state for other OSs:
174          */
175         apic_write_around(APIC_LVTT, APIC_LVT_MASKED);
176         apic_write_around(APIC_LVT0, APIC_LVT_MASKED);
177         apic_write_around(APIC_LVT1, APIC_LVT_MASKED);
178         if (maxlvt >= 3)
179                 apic_write_around(APIC_LVTERR, APIC_LVT_MASKED);
180         if (maxlvt >= 4)
181                 apic_write_around(APIC_LVTPC, APIC_LVT_MASKED);
182
183 #ifdef CONFIG_X86_MCE_P4THERMAL
184         if (maxlvt >= 5)
185                 apic_write_around(APIC_LVTTHMR, APIC_LVT_MASKED);
186 #endif
187         v = GET_APIC_VERSION(apic_read(APIC_LVR));
188         if (APIC_INTEGRATED(v)) {       /* !82489DX */
189                 if (maxlvt > 3)         /* Due to Pentium errata 3AP and 11AP. */
190                         apic_write(APIC_ESR, 0);
191                 apic_read(APIC_ESR);
192         }
193 }
194
195 void __init connect_bsp_APIC(void)
196 {
197         if (pic_mode) {
198                 /*
199                  * Do not trust the local APIC being empty at bootup.
200                  */
201                 clear_local_APIC();
202                 /*
203                  * PIC mode, enable APIC mode in the IMCR, i.e.
204                  * connect BSP's local APIC to INT and NMI lines.
205                  */
206                 apic_printk(APIC_VERBOSE, "leaving PIC mode, "
207                                 "enabling APIC mode.\n");
208                 outb(0x70, 0x22);
209                 outb(0x01, 0x23);
210         }
211         enable_apic_mode();
212 }
213
214 void disconnect_bsp_APIC(int virt_wire_setup)
215 {
216         if (pic_mode) {
217                 /*
218                  * Put the board back into PIC mode (has an effect
219                  * only on certain older boards).  Note that APIC
220                  * interrupts, including IPIs, won't work beyond
221                  * this point!  The only exception are INIT IPIs.
222                  */
223                 apic_printk(APIC_VERBOSE, "disabling APIC mode, "
224                                 "entering PIC mode.\n");
225                 outb(0x70, 0x22);
226                 outb(0x00, 0x23);
227         }
228         else {
229                 /* Go back to Virtual Wire compatibility mode */
230                 unsigned long value;
231
232                 /* For the spurious interrupt use vector F, and enable it */
233                 value = apic_read(APIC_SPIV);
234                 value &= ~APIC_VECTOR_MASK;
235                 value |= APIC_SPIV_APIC_ENABLED;
236                 value |= 0xf;
237                 apic_write_around(APIC_SPIV, value);
238
239                 if (!virt_wire_setup) {
240                         /* For LVT0 make it edge triggered, active high, external and enabled */
241                         value = apic_read(APIC_LVT0);
242                         value &= ~(APIC_MODE_MASK | APIC_SEND_PENDING |
243                                 APIC_INPUT_POLARITY | APIC_LVT_REMOTE_IRR |
244                                 APIC_LVT_LEVEL_TRIGGER | APIC_LVT_MASKED );
245                         value |= APIC_LVT_REMOTE_IRR | APIC_SEND_PENDING;
246                         value = SET_APIC_DELIVERY_MODE(value, APIC_MODE_EXTINT);
247                         apic_write_around(APIC_LVT0, value);
248                 }
249                 else {
250                         /* Disable LVT0 */
251                         apic_write_around(APIC_LVT0, APIC_LVT_MASKED);
252                 }
253
254                 /* For LVT1 make it edge triggered, active high, nmi and enabled */
255                 value = apic_read(APIC_LVT1);
256                 value &= ~(
257                         APIC_MODE_MASK | APIC_SEND_PENDING |
258                         APIC_INPUT_POLARITY | APIC_LVT_REMOTE_IRR |
259                         APIC_LVT_LEVEL_TRIGGER | APIC_LVT_MASKED);
260                 value |= APIC_LVT_REMOTE_IRR | APIC_SEND_PENDING;
261                 value = SET_APIC_DELIVERY_MODE(value, APIC_MODE_NMI);
262                 apic_write_around(APIC_LVT1, value);
263         }
264 }
265
266 void disable_local_APIC(void)
267 {
268         unsigned long value;
269
270         clear_local_APIC();
271
272         /*
273          * Disable APIC (implies clearing of registers
274          * for 82489DX!).
275          */
276         value = apic_read(APIC_SPIV);
277         value &= ~APIC_SPIV_APIC_ENABLED;
278         apic_write_around(APIC_SPIV, value);
279
280         if (enabled_via_apicbase) {
281                 unsigned int l, h;
282                 rdmsr(MSR_IA32_APICBASE, l, h);
283                 l &= ~MSR_IA32_APICBASE_ENABLE;
284                 wrmsr(MSR_IA32_APICBASE, l, h);
285         }
286 }
287
288 /*
289  * This is to verify that we're looking at a real local APIC.
290  * Check these against your board if the CPUs aren't getting
291  * started for no apparent reason.
292  */
293 int __init verify_local_APIC(void)
294 {
295         unsigned int reg0, reg1;
296
297         /*
298          * The version register is read-only in a real APIC.
299          */
300         reg0 = apic_read(APIC_LVR);
301         apic_printk(APIC_DEBUG, "Getting VERSION: %x\n", reg0);
302         apic_write(APIC_LVR, reg0 ^ APIC_LVR_MASK);
303         reg1 = apic_read(APIC_LVR);
304         apic_printk(APIC_DEBUG, "Getting VERSION: %x\n", reg1);
305
306         /*
307          * The two version reads above should print the same
308          * numbers.  If the second one is different, then we
309          * poke at a non-APIC.
310          */
311         if (reg1 != reg0)
312                 return 0;
313
314         /*
315          * Check if the version looks reasonably.
316          */
317         reg1 = GET_APIC_VERSION(reg0);
318         if (reg1 == 0x00 || reg1 == 0xff)
319                 return 0;
320         reg1 = get_maxlvt();
321         if (reg1 < 0x02 || reg1 == 0xff)
322                 return 0;
323
324         /*
325          * The ID register is read/write in a real APIC.
326          */
327         reg0 = apic_read(APIC_ID);
328         apic_printk(APIC_DEBUG, "Getting ID: %x\n", reg0);
329
330         /*
331          * The next two are just to see if we have sane values.
332          * They're only really relevant if we're in Virtual Wire
333          * compatibility mode, but most boxes are anymore.
334          */
335         reg0 = apic_read(APIC_LVT0);
336         apic_printk(APIC_DEBUG, "Getting LVT0: %x\n", reg0);
337         reg1 = apic_read(APIC_LVT1);
338         apic_printk(APIC_DEBUG, "Getting LVT1: %x\n", reg1);
339
340         return 1;
341 }
342
343 void __init sync_Arb_IDs(void)
344 {
345         /* Unsupported on P4 - see Intel Dev. Manual Vol. 3, Ch. 8.6.1 */
346         unsigned int ver = GET_APIC_VERSION(apic_read(APIC_LVR));
347         if (ver >= 0x14)        /* P4 or higher */
348                 return;
349         /*
350          * Wait for idle.
351          */
352         apic_wait_icr_idle();
353
354         apic_printk(APIC_DEBUG, "Synchronizing Arb IDs.\n");
355         apic_write_around(APIC_ICR, APIC_DEST_ALLINC | APIC_INT_LEVELTRIG
356                                 | APIC_DM_INIT);
357 }
358
359 extern void __error_in_apic_c (void);
360
361 /*
362  * An initial setup of the virtual wire mode.
363  */
364 void __init init_bsp_APIC(void)
365 {
366         unsigned long value, ver;
367
368         /*
369          * Don't do the setup now if we have a SMP BIOS as the
370          * through-I/O-APIC virtual wire mode might be active.
371          */
372         if (smp_found_config || !cpu_has_apic)
373                 return;
374
375         value = apic_read(APIC_LVR);
376         ver = GET_APIC_VERSION(value);
377
378         /*
379          * Do not trust the local APIC being empty at bootup.
380          */
381         clear_local_APIC();
382
383         /*
384          * Enable APIC.
385          */
386         value = apic_read(APIC_SPIV);
387         value &= ~APIC_VECTOR_MASK;
388         value |= APIC_SPIV_APIC_ENABLED;
389         
390         /* This bit is reserved on P4/Xeon and should be cleared */
391         if ((boot_cpu_data.x86_vendor == X86_VENDOR_INTEL) && (boot_cpu_data.x86 == 15))
392                 value &= ~APIC_SPIV_FOCUS_DISABLED;
393         else
394                 value |= APIC_SPIV_FOCUS_DISABLED;
395         value |= SPURIOUS_APIC_VECTOR;
396         apic_write_around(APIC_SPIV, value);
397
398         /*
399          * Set up the virtual wire mode.
400          */
401         apic_write_around(APIC_LVT0, APIC_DM_EXTINT);
402         value = APIC_DM_NMI;
403         if (!APIC_INTEGRATED(ver))              /* 82489DX */
404                 value |= APIC_LVT_LEVEL_TRIGGER;
405         apic_write_around(APIC_LVT1, value);
406 }
407
408 void __devinit setup_local_APIC(void)
409 {
410         unsigned long oldvalue, value, ver, maxlvt;
411
412         /* Pound the ESR really hard over the head with a big hammer - mbligh */
413         if (esr_disable) {
414                 apic_write(APIC_ESR, 0);
415                 apic_write(APIC_ESR, 0);
416                 apic_write(APIC_ESR, 0);
417                 apic_write(APIC_ESR, 0);
418         }
419
420         value = apic_read(APIC_LVR);
421         ver = GET_APIC_VERSION(value);
422
423         if ((SPURIOUS_APIC_VECTOR & 0x0f) != 0x0f)
424                 __error_in_apic_c();
425
426         /*
427          * Double-check whether this APIC is really registered.
428          */
429         if (!apic_id_registered())
430                 BUG();
431
432         /*
433          * Intel recommends to set DFR, LDR and TPR before enabling
434          * an APIC.  See e.g. "AP-388 82489DX User's Manual" (Intel
435          * document number 292116).  So here it goes...
436          */
437         init_apic_ldr();
438
439         /*
440          * Set Task Priority to 'accept all'. We never change this
441          * later on.
442          */
443         value = apic_read(APIC_TASKPRI);
444         value &= ~APIC_TPRI_MASK;
445         apic_write_around(APIC_TASKPRI, value);
446
447         /*
448          * Now that we are all set up, enable the APIC
449          */
450         value = apic_read(APIC_SPIV);
451         value &= ~APIC_VECTOR_MASK;
452         /*
453          * Enable APIC
454          */
455         value |= APIC_SPIV_APIC_ENABLED;
456
457         /*
458          * Some unknown Intel IO/APIC (or APIC) errata is biting us with
459          * certain networking cards. If high frequency interrupts are
460          * happening on a particular IOAPIC pin, plus the IOAPIC routing
461          * entry is masked/unmasked at a high rate as well then sooner or
462          * later IOAPIC line gets 'stuck', no more interrupts are received
463          * from the device. If focus CPU is disabled then the hang goes
464          * away, oh well :-(
465          *
466          * [ This bug can be reproduced easily with a level-triggered
467          *   PCI Ne2000 networking cards and PII/PIII processors, dual
468          *   BX chipset. ]
469          */
470         /*
471          * Actually disabling the focus CPU check just makes the hang less
472          * frequent as it makes the interrupt distributon model be more
473          * like LRU than MRU (the short-term load is more even across CPUs).
474          * See also the comment in end_level_ioapic_irq().  --macro
475          */
476 #if 1
477         /* Enable focus processor (bit==0) */
478         value &= ~APIC_SPIV_FOCUS_DISABLED;
479 #else
480         /* Disable focus processor (bit==1) */
481         value |= APIC_SPIV_FOCUS_DISABLED;
482 #endif
483         /*
484          * Set spurious IRQ vector
485          */
486         value |= SPURIOUS_APIC_VECTOR;
487         apic_write_around(APIC_SPIV, value);
488
489         /*
490          * Set up LVT0, LVT1:
491          *
492          * set up through-local-APIC on the BP's LINT0. This is not
493          * strictly necessery in pure symmetric-IO mode, but sometimes
494          * we delegate interrupts to the 8259A.
495          */
496         /*
497          * TODO: set up through-local-APIC from through-I/O-APIC? --macro
498          */
499         value = apic_read(APIC_LVT0) & APIC_LVT_MASKED;
500         if (!smp_processor_id() && (pic_mode || !value)) {
501                 value = APIC_DM_EXTINT;
502                 apic_printk(APIC_VERBOSE, "enabled ExtINT on CPU#%d\n",
503                                 smp_processor_id());
504         } else {
505                 value = APIC_DM_EXTINT | APIC_LVT_MASKED;
506                 apic_printk(APIC_VERBOSE, "masked ExtINT on CPU#%d\n",
507                                 smp_processor_id());
508         }
509         apic_write_around(APIC_LVT0, value);
510
511         /*
512          * only the BP should see the LINT1 NMI signal, obviously.
513          */
514         if (!smp_processor_id())
515                 value = APIC_DM_NMI;
516         else
517                 value = APIC_DM_NMI | APIC_LVT_MASKED;
518         if (!APIC_INTEGRATED(ver))              /* 82489DX */
519                 value |= APIC_LVT_LEVEL_TRIGGER;
520         apic_write_around(APIC_LVT1, value);
521
522         if (APIC_INTEGRATED(ver) && !esr_disable) {             /* !82489DX */
523                 maxlvt = get_maxlvt();
524                 if (maxlvt > 3)         /* Due to the Pentium erratum 3AP. */
525                         apic_write(APIC_ESR, 0);
526                 oldvalue = apic_read(APIC_ESR);
527
528                 value = ERROR_APIC_VECTOR;      // enables sending errors
529                 apic_write_around(APIC_LVTERR, value);
530                 /*
531                  * spec says clear errors after enabling vector.
532                  */
533                 if (maxlvt > 3)
534                         apic_write(APIC_ESR, 0);
535                 value = apic_read(APIC_ESR);
536                 if (value != oldvalue)
537                         apic_printk(APIC_VERBOSE, "ESR value before enabling "
538                                 "vector: 0x%08lx  after: 0x%08lx\n",
539                                 oldvalue, value);
540         } else {
541                 if (esr_disable)        
542                         /* 
543                          * Something untraceble is creating bad interrupts on 
544                          * secondary quads ... for the moment, just leave the
545                          * ESR disabled - we can't do anything useful with the
546                          * errors anyway - mbligh
547                          */
548                         printk("Leaving ESR disabled.\n");
549                 else 
550                         printk("No ESR for 82489DX.\n");
551         }
552
553         if (nmi_watchdog == NMI_LOCAL_APIC)
554                 setup_apic_nmi_watchdog();
555         apic_pm_activate();
556 }
557
558 /*
559  * If Linux enabled the LAPIC against the BIOS default
560  * disable it down before re-entering the BIOS on shutdown.
561  * Otherwise the BIOS may get confused and not power-off.
562  */
563 void lapic_shutdown(void)
564 {
565         if (!cpu_has_apic || !enabled_via_apicbase)
566                 return;
567
568         local_irq_disable();
569         disable_local_APIC();
570         local_irq_enable();
571 }
572
573 #ifdef CONFIG_PM
574
575 static struct {
576         int active;
577         /* r/w apic fields */
578         unsigned int apic_id;
579         unsigned int apic_taskpri;
580         unsigned int apic_ldr;
581         unsigned int apic_dfr;
582         unsigned int apic_spiv;
583         unsigned int apic_lvtt;
584         unsigned int apic_lvtpc;
585         unsigned int apic_lvt0;
586         unsigned int apic_lvt1;
587         unsigned int apic_lvterr;
588         unsigned int apic_tmict;
589         unsigned int apic_tdcr;
590         unsigned int apic_thmr;
591 } apic_pm_state;
592
593 static int lapic_suspend(struct sys_device *dev, pm_message_t state)
594 {
595         unsigned long flags;
596
597         if (!apic_pm_state.active)
598                 return 0;
599
600         apic_pm_state.apic_id = apic_read(APIC_ID);
601         apic_pm_state.apic_taskpri = apic_read(APIC_TASKPRI);
602         apic_pm_state.apic_ldr = apic_read(APIC_LDR);
603         apic_pm_state.apic_dfr = apic_read(APIC_DFR);
604         apic_pm_state.apic_spiv = apic_read(APIC_SPIV);
605         apic_pm_state.apic_lvtt = apic_read(APIC_LVTT);
606         apic_pm_state.apic_lvtpc = apic_read(APIC_LVTPC);
607         apic_pm_state.apic_lvt0 = apic_read(APIC_LVT0);
608         apic_pm_state.apic_lvt1 = apic_read(APIC_LVT1);
609         apic_pm_state.apic_lvterr = apic_read(APIC_LVTERR);
610         apic_pm_state.apic_tmict = apic_read(APIC_TMICT);
611         apic_pm_state.apic_tdcr = apic_read(APIC_TDCR);
612         apic_pm_state.apic_thmr = apic_read(APIC_LVTTHMR);
613         
614         local_irq_save(flags);
615         disable_local_APIC();
616         local_irq_restore(flags);
617         return 0;
618 }
619
620 static int lapic_resume(struct sys_device *dev)
621 {
622         unsigned int l, h;
623         unsigned long flags;
624
625         if (!apic_pm_state.active)
626                 return 0;
627
628         local_irq_save(flags);
629
630         /*
631          * Make sure the APICBASE points to the right address
632          *
633          * FIXME! This will be wrong if we ever support suspend on
634          * SMP! We'll need to do this as part of the CPU restore!
635          */
636         rdmsr(MSR_IA32_APICBASE, l, h);
637         l &= ~MSR_IA32_APICBASE_BASE;
638         l |= MSR_IA32_APICBASE_ENABLE | mp_lapic_addr;
639         wrmsr(MSR_IA32_APICBASE, l, h);
640
641         apic_write(APIC_LVTERR, ERROR_APIC_VECTOR | APIC_LVT_MASKED);
642         apic_write(APIC_ID, apic_pm_state.apic_id);
643         apic_write(APIC_DFR, apic_pm_state.apic_dfr);
644         apic_write(APIC_LDR, apic_pm_state.apic_ldr);
645         apic_write(APIC_TASKPRI, apic_pm_state.apic_taskpri);
646         apic_write(APIC_SPIV, apic_pm_state.apic_spiv);
647         apic_write(APIC_LVT0, apic_pm_state.apic_lvt0);
648         apic_write(APIC_LVT1, apic_pm_state.apic_lvt1);
649         apic_write(APIC_LVTTHMR, apic_pm_state.apic_thmr);
650         apic_write(APIC_LVTPC, apic_pm_state.apic_lvtpc);
651         apic_write(APIC_LVTT, apic_pm_state.apic_lvtt);
652         apic_write(APIC_TDCR, apic_pm_state.apic_tdcr);
653         apic_write(APIC_TMICT, apic_pm_state.apic_tmict);
654         apic_write(APIC_ESR, 0);
655         apic_read(APIC_ESR);
656         apic_write(APIC_LVTERR, apic_pm_state.apic_lvterr);
657         apic_write(APIC_ESR, 0);
658         apic_read(APIC_ESR);
659         local_irq_restore(flags);
660         return 0;
661 }
662
663 /*
664  * This device has no shutdown method - fully functioning local APICs
665  * are needed on every CPU up until machine_halt/restart/poweroff.
666  */
667
668 static struct sysdev_class lapic_sysclass = {
669         set_kset_name("lapic"),
670         .resume         = lapic_resume,
671         .suspend        = lapic_suspend,
672 };
673
674 static struct sys_device device_lapic = {
675         .id     = 0,
676         .cls    = &lapic_sysclass,
677 };
678
679 static void __devinit apic_pm_activate(void)
680 {
681         apic_pm_state.active = 1;
682 }
683
684 static int __init init_lapic_sysfs(void)
685 {
686         int error;
687
688         if (!cpu_has_apic)
689                 return 0;
690         /* XXX: remove suspend/resume procs if !apic_pm_state.active? */
691
692         error = sysdev_class_register(&lapic_sysclass);
693         if (!error)
694                 error = sysdev_register(&device_lapic);
695         return error;
696 }
697 device_initcall(init_lapic_sysfs);
698
699 #else   /* CONFIG_PM */
700
701 static void apic_pm_activate(void) { }
702
703 #endif  /* CONFIG_PM */
704
705 /*
706  * Detect and enable local APICs on non-SMP boards.
707  * Original code written by Keir Fraser.
708  */
709
710 static int __init apic_set_verbosity(char *str)
711 {
712         if (strcmp("debug", str) == 0)
713                 apic_verbosity = APIC_DEBUG;
714         else if (strcmp("verbose", str) == 0)
715                 apic_verbosity = APIC_VERBOSE;
716         else
717                 printk(KERN_WARNING "APIC Verbosity level %s not recognised"
718                                 " use apic=verbose or apic=debug", str);
719
720         return 0;
721 }
722
723 __setup("apic=", apic_set_verbosity);
724
725 static int __init detect_init_APIC (void)
726 {
727         u32 h, l, features;
728
729         /* Disabled by kernel option? */
730         if (enable_local_apic < 0)
731                 return -1;
732
733         switch (boot_cpu_data.x86_vendor) {
734         case X86_VENDOR_AMD:
735                 if ((boot_cpu_data.x86 == 6 && boot_cpu_data.x86_model > 1) ||
736                     (boot_cpu_data.x86 == 15))      
737                         break;
738                 goto no_apic;
739         case X86_VENDOR_INTEL:
740                 if (boot_cpu_data.x86 == 6 || boot_cpu_data.x86 == 15 ||
741                     (boot_cpu_data.x86 == 5 && cpu_has_apic))
742                         break;
743                 goto no_apic;
744         default:
745                 goto no_apic;
746         }
747
748         if (!cpu_has_apic) {
749                 /*
750                  * Over-ride BIOS and try to enable the local
751                  * APIC only if "lapic" specified.
752                  */
753                 if (enable_local_apic <= 0) {
754                         printk("Local APIC disabled by BIOS -- "
755                                "you can enable it with \"lapic\"\n");
756                         return -1;
757                 }
758                 /*
759                  * Some BIOSes disable the local APIC in the
760                  * APIC_BASE MSR. This can only be done in
761                  * software for Intel P6 or later and AMD K7
762                  * (Model > 1) or later.
763                  */
764                 rdmsr(MSR_IA32_APICBASE, l, h);
765                 if (!(l & MSR_IA32_APICBASE_ENABLE)) {
766                         printk("Local APIC disabled by BIOS -- reenabling.\n");
767                         l &= ~MSR_IA32_APICBASE_BASE;
768                         l |= MSR_IA32_APICBASE_ENABLE | APIC_DEFAULT_PHYS_BASE;
769                         wrmsr(MSR_IA32_APICBASE, l, h);
770                         enabled_via_apicbase = 1;
771                 }
772         }
773         /*
774          * The APIC feature bit should now be enabled
775          * in `cpuid'
776          */
777         features = cpuid_edx(1);
778         if (!(features & (1 << X86_FEATURE_APIC))) {
779                 printk("Could not enable APIC!\n");
780                 return -1;
781         }
782         set_bit(X86_FEATURE_APIC, boot_cpu_data.x86_capability);
783         mp_lapic_addr = APIC_DEFAULT_PHYS_BASE;
784
785         /* The BIOS may have set up the APIC at some other address */
786         rdmsr(MSR_IA32_APICBASE, l, h);
787         if (l & MSR_IA32_APICBASE_ENABLE)
788                 mp_lapic_addr = l & MSR_IA32_APICBASE_BASE;
789
790         if (nmi_watchdog != NMI_NONE)
791                 nmi_watchdog = NMI_LOCAL_APIC;
792
793         printk("Found and enabled local APIC!\n");
794
795         apic_pm_activate();
796
797         return 0;
798
799 no_apic:
800         printk("No local APIC present or hardware disabled\n");
801         return -1;
802 }
803
804 void __init init_apic_mappings(void)
805 {
806         unsigned int orig_apicid;
807         unsigned long apic_phys;
808
809         /*
810          * If no local APIC can be found then set up a fake all
811          * zeroes page to simulate the local APIC and another
812          * one for the IO-APIC.
813          */
814         if (!smp_found_config && detect_init_APIC()) {
815                 apic_phys = (unsigned long) alloc_bootmem_pages(PAGE_SIZE);
816                 apic_phys = __pa(apic_phys);
817         } else
818                 apic_phys = mp_lapic_addr;
819
820         set_fixmap_nocache(FIX_APIC_BASE, apic_phys);
821         printk(KERN_DEBUG "mapped APIC to %08lx (%08lx)\n", APIC_BASE,
822                apic_phys);
823
824         /*
825          * Fetch the APIC ID of the BSP in case we have a
826          * default configuration (or the MP table is broken).
827          */
828         orig_apicid = boot_cpu_physical_apicid;
829         boot_cpu_physical_apicid = GET_APIC_ID(apic_read(APIC_ID));
830         if ((orig_apicid != -1U) && (orig_apicid != boot_cpu_physical_apicid))
831                 printk(KERN_WARNING "Boot APIC ID in local APIC unexpected (%d vs %d)",
832                         orig_apicid, boot_cpu_physical_apicid);
833
834 #ifdef CONFIG_X86_IO_APIC
835         {
836                 unsigned long ioapic_phys, idx = FIX_IO_APIC_BASE_0;
837                 int i;
838
839                 for (i = 0; i < nr_ioapics; i++) {
840                         if (smp_found_config) {
841                                 ioapic_phys = mp_ioapics[i].mpc_apicaddr;
842                                 if (!ioapic_phys) {
843                                         printk(KERN_ERR
844                                                "WARNING: bogus zero IO-APIC "
845                                                "address found in MPTABLE, "
846                                                "disabling IO/APIC support!\n");
847                                         smp_found_config = 0;
848                                         skip_ioapic_setup = 1;
849                                         goto fake_ioapic_page;
850                                 }
851                         } else {
852 fake_ioapic_page:
853                                 ioapic_phys = (unsigned long)
854                                               alloc_bootmem_pages(PAGE_SIZE);
855                                 ioapic_phys = __pa(ioapic_phys);
856                         }
857                         set_fixmap_nocache(idx, ioapic_phys);
858                         printk(KERN_DEBUG "mapped IOAPIC to %08lx (%08lx)\n",
859                                __fix_to_virt(idx), ioapic_phys);
860                         idx++;
861                 }
862         }
863 #endif
864 }
865
866 /*
867  * This part sets up the APIC 32 bit clock in LVTT1, with HZ interrupts
868  * per second. We assume that the caller has already set up the local
869  * APIC.
870  *
871  * The APIC timer is not exactly sync with the external timer chip, it
872  * closely follows bus clocks.
873  */
874
875 /*
876  * The timer chip is already set up at HZ interrupts per second here,
877  * but we do not accept timer interrupts yet. We only allow the BP
878  * to calibrate.
879  */
880 static unsigned int __devinit get_8254_timer_count(void)
881 {
882         unsigned long flags;
883
884         unsigned int count;
885
886         spin_lock_irqsave(&i8253_lock, flags);
887
888         outb_p(0x00, PIT_MODE);
889         count = inb_p(PIT_CH0);
890         count |= inb_p(PIT_CH0) << 8;
891
892         spin_unlock_irqrestore(&i8253_lock, flags);
893
894         return count;
895 }
896
897 /* next tick in 8254 can be caught by catching timer wraparound */
898 static void __devinit wait_8254_wraparound(void)
899 {
900         unsigned int curr_count, prev_count;
901
902         curr_count = get_8254_timer_count();
903         do {
904                 prev_count = curr_count;
905                 curr_count = get_8254_timer_count();
906
907                 /* workaround for broken Mercury/Neptune */
908                 if (prev_count >= curr_count + 0x100)
909                         curr_count = get_8254_timer_count();
910
911         } while (prev_count >= curr_count);
912 }
913
914 /*
915  * Default initialization for 8254 timers. If we use other timers like HPET,
916  * we override this later
917  */
918 void (*wait_timer_tick)(void) __devinitdata = wait_8254_wraparound;
919
920 /*
921  * This function sets up the local APIC timer, with a timeout of
922  * 'clocks' APIC bus clock. During calibration we actually call
923  * this function twice on the boot CPU, once with a bogus timeout
924  * value, second time for real. The other (noncalibrating) CPUs
925  * call this function only once, with the real, calibrated value.
926  *
927  * We do reads before writes even if unnecessary, to get around the
928  * P5 APIC double write bug.
929  */
930
931 #define APIC_DIVISOR 16
932
933 static void __setup_APIC_LVTT(unsigned int clocks)
934 {
935         unsigned int lvtt_value, tmp_value, ver;
936
937         ver = GET_APIC_VERSION(apic_read(APIC_LVR));
938         lvtt_value = APIC_LVT_TIMER_PERIODIC | LOCAL_TIMER_VECTOR;
939         if (!APIC_INTEGRATED(ver))
940                 lvtt_value |= SET_APIC_TIMER_BASE(APIC_TIMER_BASE_DIV);
941         apic_write_around(APIC_LVTT, lvtt_value);
942
943         /*
944          * Divide PICLK by 16
945          */
946         tmp_value = apic_read(APIC_TDCR);
947         apic_write_around(APIC_TDCR, (tmp_value
948                                 & ~(APIC_TDR_DIV_1 | APIC_TDR_DIV_TMBASE))
949                                 | APIC_TDR_DIV_16);
950
951         apic_write_around(APIC_TMICT, clocks/APIC_DIVISOR);
952 }
953
954 static void __devinit setup_APIC_timer(unsigned int clocks)
955 {
956         unsigned long flags;
957
958         local_irq_save(flags);
959
960         /*
961          * Wait for IRQ0's slice:
962          */
963         wait_timer_tick();
964
965         __setup_APIC_LVTT(clocks);
966
967         local_irq_restore(flags);
968 }
969
970 /*
971  * In this function we calibrate APIC bus clocks to the external
972  * timer. Unfortunately we cannot use jiffies and the timer irq
973  * to calibrate, since some later bootup code depends on getting
974  * the first irq? Ugh.
975  *
976  * We want to do the calibration only once since we
977  * want to have local timer irqs syncron. CPUs connected
978  * by the same APIC bus have the very same bus frequency.
979  * And we want to have irqs off anyways, no accidental
980  * APIC irq that way.
981  */
982
983 static int __init calibrate_APIC_clock(void)
984 {
985         unsigned long long t1 = 0, t2 = 0;
986         long tt1, tt2;
987         long result;
988         int i;
989         const int LOOPS = HZ/10;
990
991         apic_printk(APIC_VERBOSE, "calibrating APIC timer ...\n");
992
993         /*
994          * Put whatever arbitrary (but long enough) timeout
995          * value into the APIC clock, we just want to get the
996          * counter running for calibration.
997          */
998         __setup_APIC_LVTT(1000000000);
999
1000         /*
1001          * The timer chip counts down to zero. Let's wait
1002          * for a wraparound to start exact measurement:
1003          * (the current tick might have been already half done)
1004          */
1005
1006         wait_timer_tick();
1007
1008         /*
1009          * We wrapped around just now. Let's start:
1010          */
1011         if (cpu_has_tsc)
1012                 rdtscll(t1);
1013         tt1 = apic_read(APIC_TMCCT);
1014
1015         /*
1016          * Let's wait LOOPS wraprounds:
1017          */
1018         for (i = 0; i < LOOPS; i++)
1019                 wait_timer_tick();
1020
1021         tt2 = apic_read(APIC_TMCCT);
1022         if (cpu_has_tsc)
1023                 rdtscll(t2);
1024
1025         /*
1026          * The APIC bus clock counter is 32 bits only, it
1027          * might have overflown, but note that we use signed
1028          * longs, thus no extra care needed.
1029          *
1030          * underflown to be exact, as the timer counts down ;)
1031          */
1032
1033         result = (tt1-tt2)*APIC_DIVISOR/LOOPS;
1034
1035         if (cpu_has_tsc)
1036                 apic_printk(APIC_VERBOSE, "..... CPU clock speed is "
1037                         "%ld.%04ld MHz.\n",
1038                         ((long)(t2-t1)/LOOPS)/(1000000/HZ),
1039                         ((long)(t2-t1)/LOOPS)%(1000000/HZ));
1040
1041         apic_printk(APIC_VERBOSE, "..... host bus clock speed is "
1042                 "%ld.%04ld MHz.\n",
1043                 result/(1000000/HZ),
1044                 result%(1000000/HZ));
1045
1046         return result;
1047 }
1048
1049 static unsigned int calibration_result;
1050
1051 void __init setup_boot_APIC_clock(void)
1052 {
1053         unsigned long flags;
1054         apic_printk(APIC_VERBOSE, "Using local APIC timer interrupts.\n");
1055         using_apic_timer = 1;
1056
1057         local_irq_save(flags);
1058         local_irq_disable();
1059
1060         calibration_result = calibrate_APIC_clock();
1061         /*
1062          * Now set up the timer for real.
1063          */
1064         setup_APIC_timer(calibration_result);
1065
1066         local_irq_restore(flags);
1067 }
1068
1069 void __devinit setup_secondary_APIC_clock(void)
1070 {
1071         setup_APIC_timer(calibration_result);
1072 }
1073
1074 void __devinit disable_APIC_timer(void)
1075 {
1076         if (using_apic_timer) {
1077                 unsigned long v;
1078
1079                 v = apic_read(APIC_LVTT);
1080                 apic_write_around(APIC_LVTT, v | APIC_LVT_MASKED);
1081         }
1082 }
1083
1084 void enable_APIC_timer(void)
1085 {
1086         if (using_apic_timer) {
1087                 unsigned long v;
1088
1089                 v = apic_read(APIC_LVTT);
1090                 apic_write_around(APIC_LVTT, v & ~APIC_LVT_MASKED);
1091         }
1092 }
1093
1094 /*
1095  * the frequency of the profiling timer can be changed
1096  * by writing a multiplier value into /proc/profile.
1097  */
1098 int setup_profiling_timer(unsigned int multiplier)
1099 {
1100         int i;
1101
1102         /*
1103          * Sanity check. [at least 500 APIC cycles should be
1104          * between APIC interrupts as a rule of thumb, to avoid
1105          * irqs flooding us]
1106          */
1107         if ( (!multiplier) || (calibration_result/multiplier < 500))
1108                 return -EINVAL;
1109
1110         /* 
1111          * Set the new multiplier for each CPU. CPUs don't start using the
1112          * new values until the next timer interrupt in which they do process
1113          * accounting. At that time they also adjust their APIC timers
1114          * accordingly.
1115          */
1116         for (i = 0; i < NR_CPUS; ++i)
1117                 per_cpu(prof_multiplier, i) = multiplier;
1118
1119         return 0;
1120 }
1121
1122 #undef APIC_DIVISOR
1123
1124 /*
1125  * Local timer interrupt handler. It does both profiling and
1126  * process statistics/rescheduling.
1127  *
1128  * We do profiling in every local tick, statistics/rescheduling
1129  * happen only every 'profiling multiplier' ticks. The default
1130  * multiplier is 1 and it can be changed by writing the new multiplier
1131  * value into /proc/profile.
1132  */
1133
1134 inline void smp_local_timer_interrupt(struct pt_regs * regs)
1135 {
1136         int cpu = smp_processor_id();
1137
1138         profile_tick(CPU_PROFILING, regs);
1139         if (--per_cpu(prof_counter, cpu) <= 0) {
1140                 /*
1141                  * The multiplier may have changed since the last time we got
1142                  * to this point as a result of the user writing to
1143                  * /proc/profile. In this case we need to adjust the APIC
1144                  * timer accordingly.
1145                  *
1146                  * Interrupts are already masked off at this point.
1147                  */
1148                 per_cpu(prof_counter, cpu) = per_cpu(prof_multiplier, cpu);
1149                 if (per_cpu(prof_counter, cpu) !=
1150                                         per_cpu(prof_old_multiplier, cpu)) {
1151                         __setup_APIC_LVTT(
1152                                         calibration_result/
1153                                         per_cpu(prof_counter, cpu));
1154                         per_cpu(prof_old_multiplier, cpu) =
1155                                                 per_cpu(prof_counter, cpu);
1156                 }
1157
1158 #ifdef CONFIG_SMP
1159                 update_process_times(user_mode_vm(regs));
1160 #endif
1161         }
1162
1163         /*
1164          * We take the 'long' return path, and there every subsystem
1165          * grabs the apropriate locks (kernel lock/ irq lock).
1166          *
1167          * we might want to decouple profiling from the 'long path',
1168          * and do the profiling totally in assembly.
1169          *
1170          * Currently this isn't too much of an issue (performance wise),
1171          * we can take more than 100K local irqs per second on a 100 MHz P5.
1172          */
1173 }
1174
1175 /*
1176  * Local APIC timer interrupt. This is the most natural way for doing
1177  * local interrupts, but local timer interrupts can be emulated by
1178  * broadcast interrupts too. [in case the hw doesn't support APIC timers]
1179  *
1180  * [ if a single-CPU system runs an SMP kernel then we call the local
1181  *   interrupt as well. Thus we cannot inline the local irq ... ]
1182  */
1183
1184 fastcall void smp_apic_timer_interrupt(struct pt_regs *regs)
1185 {
1186         int cpu = smp_processor_id();
1187
1188         /*
1189          * the NMI deadlock-detector uses this.
1190          */
1191         per_cpu(irq_stat, cpu).apic_timer_irqs++;
1192
1193         /*
1194          * NOTE! We'd better ACK the irq immediately,
1195          * because timer handling can be slow.
1196          */
1197         ack_APIC_irq();
1198         /*
1199          * update_process_times() expects us to have done irq_enter().
1200          * Besides, if we don't timer interrupts ignore the global
1201          * interrupt lock, which is the WrongThing (tm) to do.
1202          */
1203         irq_enter();
1204         smp_local_timer_interrupt(regs);
1205         irq_exit();
1206 }
1207
1208 /*
1209  * This interrupt should _never_ happen with our APIC/SMP architecture
1210  */
1211 fastcall void smp_spurious_interrupt(struct pt_regs *regs)
1212 {
1213         unsigned long v;
1214
1215         irq_enter();
1216         /*
1217          * Check if this really is a spurious interrupt and ACK it
1218          * if it is a vectored one.  Just in case...
1219          * Spurious interrupts should not be ACKed.
1220          */
1221         v = apic_read(APIC_ISR + ((SPURIOUS_APIC_VECTOR & ~0x1f) >> 1));
1222         if (v & (1 << (SPURIOUS_APIC_VECTOR & 0x1f)))
1223                 ack_APIC_irq();
1224
1225         /* see sw-dev-man vol 3, chapter 7.4.13.5 */
1226         printk(KERN_INFO "spurious APIC interrupt on CPU#%d, should never happen.\n",
1227                         smp_processor_id());
1228         irq_exit();
1229 }
1230
1231 /*
1232  * This interrupt should never happen with our APIC/SMP architecture
1233  */
1234
1235 fastcall void smp_error_interrupt(struct pt_regs *regs)
1236 {
1237         unsigned long v, v1;
1238
1239         irq_enter();
1240         /* First tickle the hardware, only then report what went on. -- REW */
1241         v = apic_read(APIC_ESR);
1242         apic_write(APIC_ESR, 0);
1243         v1 = apic_read(APIC_ESR);
1244         ack_APIC_irq();
1245         atomic_inc(&irq_err_count);
1246
1247         /* Here is what the APIC error bits mean:
1248            0: Send CS error
1249            1: Receive CS error
1250            2: Send accept error
1251            3: Receive accept error
1252            4: Reserved
1253            5: Send illegal vector
1254            6: Received illegal vector
1255            7: Illegal register address
1256         */
1257         printk (KERN_DEBUG "APIC error on CPU%d: %02lx(%02lx)\n",
1258                 smp_processor_id(), v , v1);
1259         irq_exit();
1260 }
1261
1262 /*
1263  * This initializes the IO-APIC and APIC hardware.
1264  */
1265 int __init APIC_init(void)
1266 {
1267         if (enable_local_apic < 0) {
1268                 printk(KERN_INFO "APIC disabled\n");
1269                 return -1;
1270         }
1271
1272         /* See if we have a SMP configuration or have forced enabled
1273          * the local apic.
1274          */
1275         if (!smp_found_config && !acpi_lapic && !cpu_has_apic) {
1276                 enable_local_apic = -1;
1277                 return -1;
1278         }
1279
1280         /*
1281          * Complain if the BIOS pretends there is an apic.
1282          * Then get out because we don't have an a local apic.
1283          */
1284         if (!cpu_has_apic && APIC_INTEGRATED(apic_version[boot_cpu_physical_apicid])) {
1285                 printk(KERN_ERR "BIOS bug, local APIC #%d not detected!...\n",
1286                         boot_cpu_physical_apicid);
1287                 printk(KERN_ERR "... forcing use of dummy APIC emulation. (tell your hw vendor)\n");
1288                 enable_local_apic = -1;
1289                 return -1;
1290         }
1291
1292         verify_local_APIC();
1293
1294         /*
1295          * Should not be necessary because the MP table should list the boot
1296          * CPU too, but we do it for the sake of robustness anyway.
1297          * Makes no sense to do this check in clustered apic mode, so skip it
1298          */
1299         if (!check_phys_apicid_present(boot_cpu_physical_apicid)) {
1300                 printk("weird, boot CPU (#%d) not listed by the BIOS.\n",
1301                                 boot_cpu_physical_apicid);
1302                 physid_set(hard_smp_processor_id(), phys_cpu_present_map);
1303         }
1304
1305         /*
1306          * Switch from PIC to APIC mode.
1307          */
1308         connect_bsp_APIC();
1309         setup_local_APIC();
1310
1311 #ifdef CONFIG_X86_IO_APIC
1312         /*
1313          * Now start the IO-APICs
1314          */
1315         if (smp_found_config && !skip_ioapic_setup && nr_ioapics)
1316                 setup_IO_APIC();
1317 #endif
1318         return 0;
1319 }
1320
1321 void __init APIC_late_time_init(void)
1322 {
1323         /* Improve our loops per jiffy estimate */
1324         loops_per_jiffy = ((1000 + HZ - 1)/HZ)*cpu_khz;
1325         boot_cpu_data.loops_per_jiffy = loops_per_jiffy;
1326         cpu_data[0].loops_per_jiffy = loops_per_jiffy;
1327
1328         /* setup_apic_nmi_watchdog doesn't work properly before cpu_khz is
1329          * initialized.  So redo it here to ensure the boot cpu is setup
1330          * properly.
1331          */
1332         if (nmi_watchdog == NMI_LOCAL_APIC)
1333                 setup_apic_nmi_watchdog();
1334
1335 #ifdef CONFIG_X86_IO_APIC
1336         if (smp_found_config && !skip_ioapic_setup && nr_ioapics)
1337                 IO_APIC_late_time_init();
1338 #endif
1339         setup_boot_APIC_clock();
1340 }