x86_64: Move apic calibration code around
[safe/jmp/linux-2.6] / arch / x86 / kernel / apic_64.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/init.h>
18
19 #include <linux/mm.h>
20 #include <linux/delay.h>
21 #include <linux/bootmem.h>
22 #include <linux/interrupt.h>
23 #include <linux/mc146818rtc.h>
24 #include <linux/kernel_stat.h>
25 #include <linux/sysdev.h>
26 #include <linux/module.h>
27 #include <linux/ioport.h>
28
29 #include <asm/atomic.h>
30 #include <asm/smp.h>
31 #include <asm/mtrr.h>
32 #include <asm/mpspec.h>
33 #include <asm/pgalloc.h>
34 #include <asm/mach_apic.h>
35 #include <asm/nmi.h>
36 #include <asm/idle.h>
37 #include <asm/proto.h>
38 #include <asm/timex.h>
39 #include <asm/hpet.h>
40 #include <asm/apic.h>
41
42 int apic_verbosity;
43 int apic_runs_main_timer;
44 int apic_calibrate_pmtmr __initdata;
45
46 int disable_apic_timer __initdata;
47
48 /* Local APIC timer works in C2? */
49 int local_apic_timer_c2_ok;
50 EXPORT_SYMBOL_GPL(local_apic_timer_c2_ok);
51
52 static struct resource *ioapic_resources;
53 static struct resource lapic_resource = {
54         .name = "Local APIC",
55         .flags = IORESOURCE_MEM | IORESOURCE_BUSY,
56 };
57
58 static unsigned int calibration_result;
59
60 /*
61  * cpu_mask that denotes the CPUs that needs timer interrupt coming in as
62  * IPIs in place of local APIC timers
63  */
64 static cpumask_t timer_interrupt_broadcast_ipi_mask;
65
66 /* Using APIC to generate smp_local_timer_interrupt? */
67 int using_apic_timer __read_mostly = 0;
68
69 static void apic_pm_activate(void);
70
71 void apic_wait_icr_idle(void)
72 {
73         while (apic_read(APIC_ICR) & APIC_ICR_BUSY)
74                 cpu_relax();
75 }
76
77 unsigned int safe_apic_wait_icr_idle(void)
78 {
79         unsigned int send_status;
80         int timeout;
81
82         timeout = 0;
83         do {
84                 send_status = apic_read(APIC_ICR) & APIC_ICR_BUSY;
85                 if (!send_status)
86                         break;
87                 udelay(100);
88         } while (timeout++ < 1000);
89
90         return send_status;
91 }
92
93 void enable_NMI_through_LVT0 (void * dummy)
94 {
95         unsigned int v;
96
97         /* unmask and set to NMI */
98         v = APIC_DM_NMI;
99         apic_write(APIC_LVT0, v);
100 }
101
102 int get_maxlvt(void)
103 {
104         unsigned int v, maxlvt;
105
106         v = apic_read(APIC_LVR);
107         maxlvt = GET_APIC_MAXLVT(v);
108         return maxlvt;
109 }
110
111 /*
112  * 'what should we do if we get a hw irq event on an illegal vector'.
113  * each architecture has to answer this themselves.
114  */
115 void ack_bad_irq(unsigned int irq)
116 {
117         printk("unexpected IRQ trap at vector %02x\n", irq);
118         /*
119          * Currently unexpected vectors happen only on SMP and APIC.
120          * We _must_ ack these because every local APIC has only N
121          * irq slots per priority level, and a 'hanging, unacked' IRQ
122          * holds up an irq slot - in excessive cases (when multiple
123          * unexpected vectors occur) that might lock up the APIC
124          * completely.
125          * But don't ack when the APIC is disabled. -AK
126          */
127         if (!disable_apic)
128                 ack_APIC_irq();
129 }
130
131 void clear_local_APIC(void)
132 {
133         int maxlvt;
134         unsigned int v;
135
136         maxlvt = get_maxlvt();
137
138         /*
139          * Masking an LVT entry can trigger a local APIC error
140          * if the vector is zero. Mask LVTERR first to prevent this.
141          */
142         if (maxlvt >= 3) {
143                 v = ERROR_APIC_VECTOR; /* any non-zero vector will do */
144                 apic_write(APIC_LVTERR, v | APIC_LVT_MASKED);
145         }
146         /*
147          * Careful: we have to set masks only first to deassert
148          * any level-triggered sources.
149          */
150         v = apic_read(APIC_LVTT);
151         apic_write(APIC_LVTT, v | APIC_LVT_MASKED);
152         v = apic_read(APIC_LVT0);
153         apic_write(APIC_LVT0, v | APIC_LVT_MASKED);
154         v = apic_read(APIC_LVT1);
155         apic_write(APIC_LVT1, v | APIC_LVT_MASKED);
156         if (maxlvt >= 4) {
157                 v = apic_read(APIC_LVTPC);
158                 apic_write(APIC_LVTPC, v | APIC_LVT_MASKED);
159         }
160
161         /*
162          * Clean APIC state for other OSs:
163          */
164         apic_write(APIC_LVTT, APIC_LVT_MASKED);
165         apic_write(APIC_LVT0, APIC_LVT_MASKED);
166         apic_write(APIC_LVT1, APIC_LVT_MASKED);
167         if (maxlvt >= 3)
168                 apic_write(APIC_LVTERR, APIC_LVT_MASKED);
169         if (maxlvt >= 4)
170                 apic_write(APIC_LVTPC, APIC_LVT_MASKED);
171         apic_write(APIC_ESR, 0);
172         apic_read(APIC_ESR);
173 }
174
175 void disconnect_bsp_APIC(int virt_wire_setup)
176 {
177         /* Go back to Virtual Wire compatibility mode */
178         unsigned long value;
179
180         /* For the spurious interrupt use vector F, and enable it */
181         value = apic_read(APIC_SPIV);
182         value &= ~APIC_VECTOR_MASK;
183         value |= APIC_SPIV_APIC_ENABLED;
184         value |= 0xf;
185         apic_write(APIC_SPIV, value);
186
187         if (!virt_wire_setup) {
188                 /* For LVT0 make it edge triggered, active high, external and enabled */
189                 value = apic_read(APIC_LVT0);
190                 value &= ~(APIC_MODE_MASK | APIC_SEND_PENDING |
191                         APIC_INPUT_POLARITY | APIC_LVT_REMOTE_IRR |
192                         APIC_LVT_LEVEL_TRIGGER | APIC_LVT_MASKED );
193                 value |= APIC_LVT_REMOTE_IRR | APIC_SEND_PENDING;
194                 value = SET_APIC_DELIVERY_MODE(value, APIC_MODE_EXTINT);
195                 apic_write(APIC_LVT0, value);
196         } else {
197                 /* Disable LVT0 */
198                 apic_write(APIC_LVT0, APIC_LVT_MASKED);
199         }
200
201         /* For LVT1 make it edge triggered, active high, nmi and enabled */
202         value = apic_read(APIC_LVT1);
203         value &= ~(APIC_MODE_MASK | APIC_SEND_PENDING |
204                         APIC_INPUT_POLARITY | APIC_LVT_REMOTE_IRR |
205                         APIC_LVT_LEVEL_TRIGGER | APIC_LVT_MASKED);
206         value |= APIC_LVT_REMOTE_IRR | APIC_SEND_PENDING;
207         value = SET_APIC_DELIVERY_MODE(value, APIC_MODE_NMI);
208         apic_write(APIC_LVT1, value);
209 }
210
211 void disable_local_APIC(void)
212 {
213         unsigned int value;
214
215         clear_local_APIC();
216
217         /*
218          * Disable APIC (implies clearing of registers
219          * for 82489DX!).
220          */
221         value = apic_read(APIC_SPIV);
222         value &= ~APIC_SPIV_APIC_ENABLED;
223         apic_write(APIC_SPIV, value);
224 }
225
226 /*
227  * This is to verify that we're looking at a real local APIC.
228  * Check these against your board if the CPUs aren't getting
229  * started for no apparent reason.
230  */
231 int __init verify_local_APIC(void)
232 {
233         unsigned int reg0, reg1;
234
235         /*
236          * The version register is read-only in a real APIC.
237          */
238         reg0 = apic_read(APIC_LVR);
239         apic_printk(APIC_DEBUG, "Getting VERSION: %x\n", reg0);
240         apic_write(APIC_LVR, reg0 ^ APIC_LVR_MASK);
241         reg1 = apic_read(APIC_LVR);
242         apic_printk(APIC_DEBUG, "Getting VERSION: %x\n", reg1);
243
244         /*
245          * The two version reads above should print the same
246          * numbers.  If the second one is different, then we
247          * poke at a non-APIC.
248          */
249         if (reg1 != reg0)
250                 return 0;
251
252         /*
253          * Check if the version looks reasonably.
254          */
255         reg1 = GET_APIC_VERSION(reg0);
256         if (reg1 == 0x00 || reg1 == 0xff)
257                 return 0;
258         reg1 = get_maxlvt();
259         if (reg1 < 0x02 || reg1 == 0xff)
260                 return 0;
261
262         /*
263          * The ID register is read/write in a real APIC.
264          */
265         reg0 = apic_read(APIC_ID);
266         apic_printk(APIC_DEBUG, "Getting ID: %x\n", reg0);
267         apic_write(APIC_ID, reg0 ^ APIC_ID_MASK);
268         reg1 = apic_read(APIC_ID);
269         apic_printk(APIC_DEBUG, "Getting ID: %x\n", reg1);
270         apic_write(APIC_ID, reg0);
271         if (reg1 != (reg0 ^ APIC_ID_MASK))
272                 return 0;
273
274         /*
275          * The next two are just to see if we have sane values.
276          * They're only really relevant if we're in Virtual Wire
277          * compatibility mode, but most boxes are anymore.
278          */
279         reg0 = apic_read(APIC_LVT0);
280         apic_printk(APIC_DEBUG,"Getting LVT0: %x\n", reg0);
281         reg1 = apic_read(APIC_LVT1);
282         apic_printk(APIC_DEBUG, "Getting LVT1: %x\n", reg1);
283
284         return 1;
285 }
286
287 void __init sync_Arb_IDs(void)
288 {
289         /* Unsupported on P4 - see Intel Dev. Manual Vol. 3, Ch. 8.6.1 */
290         unsigned int ver = GET_APIC_VERSION(apic_read(APIC_LVR));
291         if (ver >= 0x14)        /* P4 or higher */
292                 return;
293
294         /*
295          * Wait for idle.
296          */
297         apic_wait_icr_idle();
298
299         apic_printk(APIC_DEBUG, "Synchronizing Arb IDs.\n");
300         apic_write(APIC_ICR, APIC_DEST_ALLINC | APIC_INT_LEVELTRIG
301                                 | APIC_DM_INIT);
302 }
303
304 /*
305  * An initial setup of the virtual wire mode.
306  */
307 void __init init_bsp_APIC(void)
308 {
309         unsigned int value;
310
311         /*
312          * Don't do the setup now if we have a SMP BIOS as the
313          * through-I/O-APIC virtual wire mode might be active.
314          */
315         if (smp_found_config || !cpu_has_apic)
316                 return;
317
318         value = apic_read(APIC_LVR);
319
320         /*
321          * Do not trust the local APIC being empty at bootup.
322          */
323         clear_local_APIC();
324
325         /*
326          * Enable APIC.
327          */
328         value = apic_read(APIC_SPIV);
329         value &= ~APIC_VECTOR_MASK;
330         value |= APIC_SPIV_APIC_ENABLED;
331         value |= APIC_SPIV_FOCUS_DISABLED;
332         value |= SPURIOUS_APIC_VECTOR;
333         apic_write(APIC_SPIV, value);
334
335         /*
336          * Set up the virtual wire mode.
337          */
338         apic_write(APIC_LVT0, APIC_DM_EXTINT);
339         value = APIC_DM_NMI;
340         apic_write(APIC_LVT1, value);
341 }
342
343 void __cpuinit setup_local_APIC (void)
344 {
345         unsigned int value, maxlvt;
346         int i, j;
347
348         value = apic_read(APIC_LVR);
349
350         BUILD_BUG_ON((SPURIOUS_APIC_VECTOR & 0x0f) != 0x0f);
351
352         /*
353          * Double-check whether this APIC is really registered.
354          * This is meaningless in clustered apic mode, so we skip it.
355          */
356         if (!apic_id_registered())
357                 BUG();
358
359         /*
360          * Intel recommends to set DFR, LDR and TPR before enabling
361          * an APIC.  See e.g. "AP-388 82489DX User's Manual" (Intel
362          * document number 292116).  So here it goes...
363          */
364         init_apic_ldr();
365
366         /*
367          * Set Task Priority to 'accept all'. We never change this
368          * later on.
369          */
370         value = apic_read(APIC_TASKPRI);
371         value &= ~APIC_TPRI_MASK;
372         apic_write(APIC_TASKPRI, value);
373
374         /*
375          * After a crash, we no longer service the interrupts and a pending
376          * interrupt from previous kernel might still have ISR bit set.
377          *
378          * Most probably by now CPU has serviced that pending interrupt and
379          * it might not have done the ack_APIC_irq() because it thought,
380          * interrupt came from i8259 as ExtInt. LAPIC did not get EOI so it
381          * does not clear the ISR bit and cpu thinks it has already serivced
382          * the interrupt. Hence a vector might get locked. It was noticed
383          * for timer irq (vector 0x31). Issue an extra EOI to clear ISR.
384          */
385         for (i = APIC_ISR_NR - 1; i >= 0; i--) {
386                 value = apic_read(APIC_ISR + i*0x10);
387                 for (j = 31; j >= 0; j--) {
388                         if (value & (1<<j))
389                                 ack_APIC_irq();
390                 }
391         }
392
393         /*
394          * Now that we are all set up, enable the APIC
395          */
396         value = apic_read(APIC_SPIV);
397         value &= ~APIC_VECTOR_MASK;
398         /*
399          * Enable APIC
400          */
401         value |= APIC_SPIV_APIC_ENABLED;
402
403         /* We always use processor focus */
404
405         /*
406          * Set spurious IRQ vector
407          */
408         value |= SPURIOUS_APIC_VECTOR;
409         apic_write(APIC_SPIV, value);
410
411         /*
412          * Set up LVT0, LVT1:
413          *
414          * set up through-local-APIC on the BP's LINT0. This is not
415          * strictly necessary in pure symmetric-IO mode, but sometimes
416          * we delegate interrupts to the 8259A.
417          */
418         /*
419          * TODO: set up through-local-APIC from through-I/O-APIC? --macro
420          */
421         value = apic_read(APIC_LVT0) & APIC_LVT_MASKED;
422         if (!smp_processor_id() && !value) {
423                 value = APIC_DM_EXTINT;
424                 apic_printk(APIC_VERBOSE, "enabled ExtINT on CPU#%d\n", smp_processor_id());
425         } else {
426                 value = APIC_DM_EXTINT | APIC_LVT_MASKED;
427                 apic_printk(APIC_VERBOSE, "masked ExtINT on CPU#%d\n", smp_processor_id());
428         }
429         apic_write(APIC_LVT0, value);
430
431         /*
432          * only the BP should see the LINT1 NMI signal, obviously.
433          */
434         if (!smp_processor_id())
435                 value = APIC_DM_NMI;
436         else
437                 value = APIC_DM_NMI | APIC_LVT_MASKED;
438         apic_write(APIC_LVT1, value);
439
440         {
441                 unsigned oldvalue;
442                 maxlvt = get_maxlvt();
443                 oldvalue = apic_read(APIC_ESR);
444                 value = ERROR_APIC_VECTOR;      // enables sending errors
445                 apic_write(APIC_LVTERR, value);
446                 /*
447                  * spec says clear errors after enabling vector.
448                  */
449                 if (maxlvt > 3)
450                         apic_write(APIC_ESR, 0);
451                 value = apic_read(APIC_ESR);
452                 if (value != oldvalue)
453                         apic_printk(APIC_VERBOSE,
454                         "ESR value after enabling vector: %08x, after %08x\n",
455                         oldvalue, value);
456         }
457
458         nmi_watchdog_default();
459         setup_apic_nmi_watchdog(NULL);
460         apic_pm_activate();
461 }
462
463 #ifdef CONFIG_PM
464
465 static struct {
466         /* 'active' is true if the local APIC was enabled by us and
467            not the BIOS; this signifies that we are also responsible
468            for disabling it before entering apm/acpi suspend */
469         int active;
470         /* r/w apic fields */
471         unsigned int apic_id;
472         unsigned int apic_taskpri;
473         unsigned int apic_ldr;
474         unsigned int apic_dfr;
475         unsigned int apic_spiv;
476         unsigned int apic_lvtt;
477         unsigned int apic_lvtpc;
478         unsigned int apic_lvt0;
479         unsigned int apic_lvt1;
480         unsigned int apic_lvterr;
481         unsigned int apic_tmict;
482         unsigned int apic_tdcr;
483         unsigned int apic_thmr;
484 } apic_pm_state;
485
486 static int lapic_suspend(struct sys_device *dev, pm_message_t state)
487 {
488         unsigned long flags;
489         int maxlvt;
490
491         if (!apic_pm_state.active)
492                 return 0;
493
494         maxlvt = get_maxlvt();
495
496         apic_pm_state.apic_id = apic_read(APIC_ID);
497         apic_pm_state.apic_taskpri = apic_read(APIC_TASKPRI);
498         apic_pm_state.apic_ldr = apic_read(APIC_LDR);
499         apic_pm_state.apic_dfr = apic_read(APIC_DFR);
500         apic_pm_state.apic_spiv = apic_read(APIC_SPIV);
501         apic_pm_state.apic_lvtt = apic_read(APIC_LVTT);
502         if (maxlvt >= 4)
503                 apic_pm_state.apic_lvtpc = apic_read(APIC_LVTPC);
504         apic_pm_state.apic_lvt0 = apic_read(APIC_LVT0);
505         apic_pm_state.apic_lvt1 = apic_read(APIC_LVT1);
506         apic_pm_state.apic_lvterr = apic_read(APIC_LVTERR);
507         apic_pm_state.apic_tmict = apic_read(APIC_TMICT);
508         apic_pm_state.apic_tdcr = apic_read(APIC_TDCR);
509 #ifdef CONFIG_X86_MCE_INTEL
510         if (maxlvt >= 5)
511                 apic_pm_state.apic_thmr = apic_read(APIC_LVTTHMR);
512 #endif
513         local_irq_save(flags);
514         disable_local_APIC();
515         local_irq_restore(flags);
516         return 0;
517 }
518
519 static int lapic_resume(struct sys_device *dev)
520 {
521         unsigned int l, h;
522         unsigned long flags;
523         int maxlvt;
524
525         if (!apic_pm_state.active)
526                 return 0;
527
528         maxlvt = get_maxlvt();
529
530         local_irq_save(flags);
531         rdmsr(MSR_IA32_APICBASE, l, h);
532         l &= ~MSR_IA32_APICBASE_BASE;
533         l |= MSR_IA32_APICBASE_ENABLE | mp_lapic_addr;
534         wrmsr(MSR_IA32_APICBASE, l, h);
535         apic_write(APIC_LVTERR, ERROR_APIC_VECTOR | APIC_LVT_MASKED);
536         apic_write(APIC_ID, apic_pm_state.apic_id);
537         apic_write(APIC_DFR, apic_pm_state.apic_dfr);
538         apic_write(APIC_LDR, apic_pm_state.apic_ldr);
539         apic_write(APIC_TASKPRI, apic_pm_state.apic_taskpri);
540         apic_write(APIC_SPIV, apic_pm_state.apic_spiv);
541         apic_write(APIC_LVT0, apic_pm_state.apic_lvt0);
542         apic_write(APIC_LVT1, apic_pm_state.apic_lvt1);
543 #ifdef CONFIG_X86_MCE_INTEL
544         if (maxlvt >= 5)
545                 apic_write(APIC_LVTTHMR, apic_pm_state.apic_thmr);
546 #endif
547         if (maxlvt >= 4)
548                 apic_write(APIC_LVTPC, apic_pm_state.apic_lvtpc);
549         apic_write(APIC_LVTT, apic_pm_state.apic_lvtt);
550         apic_write(APIC_TDCR, apic_pm_state.apic_tdcr);
551         apic_write(APIC_TMICT, apic_pm_state.apic_tmict);
552         apic_write(APIC_ESR, 0);
553         apic_read(APIC_ESR);
554         apic_write(APIC_LVTERR, apic_pm_state.apic_lvterr);
555         apic_write(APIC_ESR, 0);
556         apic_read(APIC_ESR);
557         local_irq_restore(flags);
558         return 0;
559 }
560
561 static struct sysdev_class lapic_sysclass = {
562         set_kset_name("lapic"),
563         .resume         = lapic_resume,
564         .suspend        = lapic_suspend,
565 };
566
567 static struct sys_device device_lapic = {
568         .id             = 0,
569         .cls            = &lapic_sysclass,
570 };
571
572 static void __cpuinit apic_pm_activate(void)
573 {
574         apic_pm_state.active = 1;
575 }
576
577 static int __init init_lapic_sysfs(void)
578 {
579         int error;
580         if (!cpu_has_apic)
581                 return 0;
582         /* XXX: remove suspend/resume procs if !apic_pm_state.active? */
583         error = sysdev_class_register(&lapic_sysclass);
584         if (!error)
585                 error = sysdev_register(&device_lapic);
586         return error;
587 }
588 device_initcall(init_lapic_sysfs);
589
590 #else   /* CONFIG_PM */
591
592 static void apic_pm_activate(void) { }
593
594 #endif  /* CONFIG_PM */
595
596 static int __init apic_set_verbosity(char *str)
597 {
598         if (str == NULL)  {
599                 skip_ioapic_setup = 0;
600                 ioapic_force = 1;
601                 return 0;
602         }
603         if (strcmp("debug", str) == 0)
604                 apic_verbosity = APIC_DEBUG;
605         else if (strcmp("verbose", str) == 0)
606                 apic_verbosity = APIC_VERBOSE;
607         else {
608                 printk(KERN_WARNING "APIC Verbosity level %s not recognised"
609                                 " use apic=verbose or apic=debug\n", str);
610                 return -EINVAL;
611         }
612
613         return 0;
614 }
615 early_param("apic", apic_set_verbosity);
616
617 /*
618  * Detect and enable local APICs on non-SMP boards.
619  * Original code written by Keir Fraser.
620  * On AMD64 we trust the BIOS - if it says no APIC it is likely
621  * not correctly set up (usually the APIC timer won't work etc.)
622  */
623
624 static int __init detect_init_APIC (void)
625 {
626         if (!cpu_has_apic) {
627                 printk(KERN_INFO "No local APIC present\n");
628                 return -1;
629         }
630
631         mp_lapic_addr = APIC_DEFAULT_PHYS_BASE;
632         boot_cpu_id = 0;
633         return 0;
634 }
635
636 #ifdef CONFIG_X86_IO_APIC
637 static struct resource * __init ioapic_setup_resources(void)
638 {
639 #define IOAPIC_RESOURCE_NAME_SIZE 11
640         unsigned long n;
641         struct resource *res;
642         char *mem;
643         int i;
644
645         if (nr_ioapics <= 0)
646                 return NULL;
647
648         n = IOAPIC_RESOURCE_NAME_SIZE + sizeof(struct resource);
649         n *= nr_ioapics;
650
651         mem = alloc_bootmem(n);
652         res = (void *)mem;
653
654         if (mem != NULL) {
655                 memset(mem, 0, n);
656                 mem += sizeof(struct resource) * nr_ioapics;
657
658                 for (i = 0; i < nr_ioapics; i++) {
659                         res[i].name = mem;
660                         res[i].flags = IORESOURCE_MEM | IORESOURCE_BUSY;
661                         sprintf(mem,  "IOAPIC %u", i);
662                         mem += IOAPIC_RESOURCE_NAME_SIZE;
663                 }
664         }
665
666         ioapic_resources = res;
667
668         return res;
669 }
670
671 static int __init ioapic_insert_resources(void)
672 {
673         int i;
674         struct resource *r = ioapic_resources;
675
676         if (!r) {
677                 printk("IO APIC resources could be not be allocated.\n");
678                 return -1;
679         }
680
681         for (i = 0; i < nr_ioapics; i++) {
682                 insert_resource(&iomem_resource, r);
683                 r++;
684         }
685
686         return 0;
687 }
688
689 /* Insert the IO APIC resources after PCI initialization has occured to handle
690  * IO APICS that are mapped in on a BAR in PCI space. */
691 late_initcall(ioapic_insert_resources);
692 #endif
693
694 void __init init_apic_mappings(void)
695 {
696         unsigned long apic_phys;
697
698         /*
699          * If no local APIC can be found then set up a fake all
700          * zeroes page to simulate the local APIC and another
701          * one for the IO-APIC.
702          */
703         if (!smp_found_config && detect_init_APIC()) {
704                 apic_phys = (unsigned long) alloc_bootmem_pages(PAGE_SIZE);
705                 apic_phys = __pa(apic_phys);
706         } else
707                 apic_phys = mp_lapic_addr;
708
709         set_fixmap_nocache(FIX_APIC_BASE, apic_phys);
710         apic_printk(APIC_VERBOSE, "mapped APIC to %16lx (%16lx)\n",
711                                 APIC_BASE, apic_phys);
712
713         /* Put local APIC into the resource map. */
714         lapic_resource.start = apic_phys;
715         lapic_resource.end = lapic_resource.start + PAGE_SIZE - 1;
716         insert_resource(&iomem_resource, &lapic_resource);
717
718         /*
719          * Fetch the APIC ID of the BSP in case we have a
720          * default configuration (or the MP table is broken).
721          */
722         boot_cpu_id = GET_APIC_ID(apic_read(APIC_ID));
723
724         {
725                 unsigned long ioapic_phys, idx = FIX_IO_APIC_BASE_0;
726                 int i;
727                 struct resource *ioapic_res;
728
729                 ioapic_res = ioapic_setup_resources();
730                 for (i = 0; i < nr_ioapics; i++) {
731                         if (smp_found_config) {
732                                 ioapic_phys = mp_ioapics[i].mpc_apicaddr;
733                         } else {
734                                 ioapic_phys = (unsigned long) alloc_bootmem_pages(PAGE_SIZE);
735                                 ioapic_phys = __pa(ioapic_phys);
736                         }
737                         set_fixmap_nocache(idx, ioapic_phys);
738                         apic_printk(APIC_VERBOSE,"mapped IOAPIC to %016lx (%016lx)\n",
739                                         __fix_to_virt(idx), ioapic_phys);
740                         idx++;
741
742                         if (ioapic_res != NULL) {
743                                 ioapic_res->start = ioapic_phys;
744                                 ioapic_res->end = ioapic_phys + (4 * 1024) - 1;
745                                 ioapic_res++;
746                         }
747                 }
748         }
749 }
750
751 /*
752  * This function sets up the local APIC timer, with a timeout of
753  * 'clocks' APIC bus clock. During calibration we actually call
754  * this function twice on the boot CPU, once with a bogus timeout
755  * value, second time for real. The other (noncalibrating) CPUs
756  * call this function only once, with the real, calibrated value.
757  *
758  * We do reads before writes even if unnecessary, to get around the
759  * P5 APIC double write bug.
760  */
761
762 #define APIC_DIVISOR 16
763
764 static void __setup_APIC_LVTT(unsigned int clocks, int oneshot, int irqen)
765 {
766         unsigned int lvtt_value, tmp_value;
767
768         lvtt_value = LOCAL_TIMER_VECTOR;
769         if (!oneshot)
770                 lvtt_value |= APIC_LVT_TIMER_PERIODIC;
771         if (!irqen)
772                 lvtt_value |= APIC_LVT_MASKED;
773
774         apic_write(APIC_LVTT, lvtt_value);
775
776         /*
777          * Divide PICLK by 16
778          */
779         tmp_value = apic_read(APIC_TDCR);
780         apic_write(APIC_TDCR, (tmp_value
781                                 & ~(APIC_TDR_DIV_1 | APIC_TDR_DIV_TMBASE))
782                                 | APIC_TDR_DIV_16);
783
784         if (!oneshot)
785                 apic_write(APIC_TMICT, clocks/APIC_DIVISOR);
786 }
787
788 static void setup_APIC_timer(unsigned int clocks)
789 {
790         unsigned long flags;
791         int irqen;
792
793         local_irq_save(flags);
794
795         irqen = ! cpu_isset(smp_processor_id(),
796                             timer_interrupt_broadcast_ipi_mask);
797         __setup_APIC_LVTT(clocks, 0, irqen);
798         /* Turn off PIT interrupt if we use APIC timer as main timer.
799            Only works with the PM timer right now
800            TBD fix it for HPET too. */
801         if ((pmtmr_ioport != 0) &&
802                 smp_processor_id() == boot_cpu_id &&
803                 apic_runs_main_timer == 1 &&
804                 !cpu_isset(boot_cpu_id, timer_interrupt_broadcast_ipi_mask)) {
805                 stop_timer_interrupt();
806                 apic_runs_main_timer++;
807         }
808         local_irq_restore(flags);
809 }
810
811 /*
812  * In this function we calibrate APIC bus clocks to the external
813  * timer. Unfortunately we cannot use jiffies and the timer irq
814  * to calibrate, since some later bootup code depends on getting
815  * the first irq? Ugh.
816  *
817  * We want to do the calibration only once since we
818  * want to have local timer irqs syncron. CPUs connected
819  * by the same APIC bus have the very same bus frequency.
820  * And we want to have irqs off anyways, no accidental
821  * APIC irq that way.
822  */
823
824 #define TICK_COUNT 100000000
825
826 static void __init calibrate_APIC_clock(void)
827 {
828         unsigned apic, apic_start;
829         unsigned long tsc, tsc_start;
830         int result;
831         /*
832          * Put whatever arbitrary (but long enough) timeout
833          * value into the APIC clock, we just want to get the
834          * counter running for calibration.
835          *
836          * No interrupt enable !
837          */
838         __setup_APIC_LVTT(4000000000, 0, 0);
839
840         apic_start = apic_read(APIC_TMCCT);
841 #ifdef CONFIG_X86_PM_TIMER
842         if (apic_calibrate_pmtmr && pmtmr_ioport) {
843                 pmtimer_wait(5000);  /* 5ms wait */
844                 apic = apic_read(APIC_TMCCT);
845                 result = (apic_start - apic) * 1000L / 5;
846         } else
847 #endif
848         {
849                 rdtscll(tsc_start);
850
851                 do {
852                         apic = apic_read(APIC_TMCCT);
853                         rdtscll(tsc);
854                 } while ((tsc - tsc_start) < TICK_COUNT &&
855                                 (apic_start - apic) < TICK_COUNT);
856
857                 result = (apic_start - apic) * 1000L * tsc_khz /
858                                         (tsc - tsc_start);
859         }
860         printk(KERN_DEBUG "APIC timer calibration result %d\n", result);
861
862         printk(KERN_INFO "Detected %d.%03d MHz APIC timer.\n",
863                 result / 1000 / 1000, result / 1000 % 1000);
864
865         calibration_result = result * APIC_DIVISOR / HZ;
866 }
867
868 void __init setup_boot_APIC_clock (void)
869 {
870         if (disable_apic_timer) {
871                 printk(KERN_INFO "Disabling APIC timer\n");
872                 return;
873         }
874
875         printk(KERN_INFO "Using local APIC timer interrupts.\n");
876         using_apic_timer = 1;
877
878         local_irq_disable();
879
880         calibrate_APIC_clock();
881         /*
882          * Now set up the timer for real.
883          */
884         setup_APIC_timer(calibration_result);
885
886         local_irq_enable();
887 }
888
889 void __cpuinit setup_secondary_APIC_clock(void)
890 {
891         local_irq_disable(); /* FIXME: Do we need this? --RR */
892         setup_APIC_timer(calibration_result);
893         local_irq_enable();
894 }
895
896 void disable_APIC_timer(void)
897 {
898         if (using_apic_timer) {
899                 unsigned long v;
900
901                 v = apic_read(APIC_LVTT);
902                 /*
903                  * When an illegal vector value (0-15) is written to an LVT
904                  * entry and delivery mode is Fixed, the APIC may signal an
905                  * illegal vector error, with out regard to whether the mask
906                  * bit is set or whether an interrupt is actually seen on input.
907                  *
908                  * Boot sequence might call this function when the LVTT has
909                  * '0' vector value. So make sure vector field is set to
910                  * valid value.
911                  */
912                 v |= (APIC_LVT_MASKED | LOCAL_TIMER_VECTOR);
913                 apic_write(APIC_LVTT, v);
914         }
915 }
916
917 void enable_APIC_timer(void)
918 {
919         int cpu = smp_processor_id();
920
921         if (using_apic_timer &&
922             !cpu_isset(cpu, timer_interrupt_broadcast_ipi_mask)) {
923                 unsigned long v;
924
925                 v = apic_read(APIC_LVTT);
926                 apic_write(APIC_LVTT, v & ~APIC_LVT_MASKED);
927         }
928 }
929
930 void switch_APIC_timer_to_ipi(void *cpumask)
931 {
932         cpumask_t mask = *(cpumask_t *)cpumask;
933         int cpu = smp_processor_id();
934
935         if (cpu_isset(cpu, mask) &&
936             !cpu_isset(cpu, timer_interrupt_broadcast_ipi_mask)) {
937                 disable_APIC_timer();
938                 cpu_set(cpu, timer_interrupt_broadcast_ipi_mask);
939         }
940 }
941 EXPORT_SYMBOL(switch_APIC_timer_to_ipi);
942
943 void smp_send_timer_broadcast_ipi(void)
944 {
945         int cpu = smp_processor_id();
946         cpumask_t mask;
947
948         cpus_and(mask, cpu_online_map, timer_interrupt_broadcast_ipi_mask);
949
950         if (cpu_isset(cpu, mask)) {
951                 cpu_clear(cpu, mask);
952                 add_pda(apic_timer_irqs, 1);
953                 smp_local_timer_interrupt();
954         }
955
956         if (!cpus_empty(mask)) {
957                 send_IPI_mask(mask, LOCAL_TIMER_VECTOR);
958         }
959 }
960
961 void switch_ipi_to_APIC_timer(void *cpumask)
962 {
963         cpumask_t mask = *(cpumask_t *)cpumask;
964         int cpu = smp_processor_id();
965
966         if (cpu_isset(cpu, mask) &&
967             cpu_isset(cpu, timer_interrupt_broadcast_ipi_mask)) {
968                 cpu_clear(cpu, timer_interrupt_broadcast_ipi_mask);
969                 enable_APIC_timer();
970         }
971 }
972 EXPORT_SYMBOL(switch_ipi_to_APIC_timer);
973
974 int setup_profiling_timer(unsigned int multiplier)
975 {
976         return -EINVAL;
977 }
978
979 void setup_APIC_extended_lvt(unsigned char lvt_off, unsigned char vector,
980                              unsigned char msg_type, unsigned char mask)
981 {
982         unsigned long reg = (lvt_off << 4) + K8_APIC_EXT_LVT_BASE;
983         unsigned int  v   = (mask << 16) | (msg_type << 8) | vector;
984         apic_write(reg, v);
985 }
986
987 /*
988  * Local timer interrupt handler. It does both profiling and
989  * process statistics/rescheduling.
990  *
991  * We do profiling in every local tick, statistics/rescheduling
992  * happen only every 'profiling multiplier' ticks. The default
993  * multiplier is 1 and it can be changed by writing the new multiplier
994  * value into /proc/profile.
995  */
996
997 void smp_local_timer_interrupt(void)
998 {
999         profile_tick(CPU_PROFILING);
1000 #ifdef CONFIG_SMP
1001         update_process_times(user_mode(get_irq_regs()));
1002 #endif
1003         if (apic_runs_main_timer > 1 && smp_processor_id() == boot_cpu_id)
1004                 main_timer_handler();
1005         /*
1006          * We take the 'long' return path, and there every subsystem
1007          * grabs the appropriate locks (kernel lock/ irq lock).
1008          *
1009          * We might want to decouple profiling from the 'long path',
1010          * and do the profiling totally in assembly.
1011          *
1012          * Currently this isn't too much of an issue (performance wise),
1013          * we can take more than 100K local irqs per second on a 100 MHz P5.
1014          */
1015 }
1016
1017 /*
1018  * Local APIC timer interrupt. This is the most natural way for doing
1019  * local interrupts, but local timer interrupts can be emulated by
1020  * broadcast interrupts too. [in case the hw doesn't support APIC timers]
1021  *
1022  * [ if a single-CPU system runs an SMP kernel then we call the local
1023  *   interrupt as well. Thus we cannot inline the local irq ... ]
1024  */
1025 void smp_apic_timer_interrupt(struct pt_regs *regs)
1026 {
1027         struct pt_regs *old_regs = set_irq_regs(regs);
1028
1029         /*
1030          * the NMI deadlock-detector uses this.
1031          */
1032         add_pda(apic_timer_irqs, 1);
1033
1034         /*
1035          * NOTE! We'd better ACK the irq immediately,
1036          * because timer handling can be slow.
1037          */
1038         ack_APIC_irq();
1039         /*
1040          * update_process_times() expects us to have done irq_enter().
1041          * Besides, if we don't timer interrupts ignore the global
1042          * interrupt lock, which is the WrongThing (tm) to do.
1043          */
1044         exit_idle();
1045         irq_enter();
1046         smp_local_timer_interrupt();
1047         irq_exit();
1048         set_irq_regs(old_regs);
1049 }
1050
1051 /*
1052  * apic_is_clustered_box() -- Check if we can expect good TSC
1053  *
1054  * Thus far, the major user of this is IBM's Summit2 series:
1055  *
1056  * Clustered boxes may have unsynced TSC problems if they are
1057  * multi-chassis. Use available data to take a good guess.
1058  * If in doubt, go HPET.
1059  */
1060 __cpuinit int apic_is_clustered_box(void)
1061 {
1062         int i, clusters, zeros;
1063         unsigned id;
1064         DECLARE_BITMAP(clustermap, NUM_APIC_CLUSTERS);
1065
1066         bitmap_zero(clustermap, NUM_APIC_CLUSTERS);
1067
1068         for (i = 0; i < NR_CPUS; i++) {
1069                 id = bios_cpu_apicid[i];
1070                 if (id != BAD_APICID)
1071                         __set_bit(APIC_CLUSTERID(id), clustermap);
1072         }
1073
1074         /* Problem:  Partially populated chassis may not have CPUs in some of
1075          * the APIC clusters they have been allocated.  Only present CPUs have
1076          * bios_cpu_apicid entries, thus causing zeroes in the bitmap.  Since
1077          * clusters are allocated sequentially, count zeros only if they are
1078          * bounded by ones.
1079          */
1080         clusters = 0;
1081         zeros = 0;
1082         for (i = 0; i < NUM_APIC_CLUSTERS; i++) {
1083                 if (test_bit(i, clustermap)) {
1084                         clusters += 1 + zeros;
1085                         zeros = 0;
1086                 } else
1087                         ++zeros;
1088         }
1089
1090         /*
1091          * If clusters > 2, then should be multi-chassis.
1092          * May have to revisit this when multi-core + hyperthreaded CPUs come
1093          * out, but AFAIK this will work even for them.
1094          */
1095         return (clusters > 2);
1096 }
1097
1098 /*
1099  * This interrupt should _never_ happen with our APIC/SMP architecture
1100  */
1101 asmlinkage void smp_spurious_interrupt(void)
1102 {
1103         unsigned int v;
1104         exit_idle();
1105         irq_enter();
1106         /*
1107          * Check if this really is a spurious interrupt and ACK it
1108          * if it is a vectored one.  Just in case...
1109          * Spurious interrupts should not be ACKed.
1110          */
1111         v = apic_read(APIC_ISR + ((SPURIOUS_APIC_VECTOR & ~0x1f) >> 1));
1112         if (v & (1 << (SPURIOUS_APIC_VECTOR & 0x1f)))
1113                 ack_APIC_irq();
1114
1115         irq_exit();
1116 }
1117
1118 /*
1119  * This interrupt should never happen with our APIC/SMP architecture
1120  */
1121
1122 asmlinkage void smp_error_interrupt(void)
1123 {
1124         unsigned int v, v1;
1125
1126         exit_idle();
1127         irq_enter();
1128         /* First tickle the hardware, only then report what went on. -- REW */
1129         v = apic_read(APIC_ESR);
1130         apic_write(APIC_ESR, 0);
1131         v1 = apic_read(APIC_ESR);
1132         ack_APIC_irq();
1133         atomic_inc(&irq_err_count);
1134
1135         /* Here is what the APIC error bits mean:
1136            0: Send CS error
1137            1: Receive CS error
1138            2: Send accept error
1139            3: Receive accept error
1140            4: Reserved
1141            5: Send illegal vector
1142            6: Received illegal vector
1143            7: Illegal register address
1144         */
1145         printk (KERN_DEBUG "APIC error on CPU%d: %02x(%02x)\n",
1146                 smp_processor_id(), v , v1);
1147         irq_exit();
1148 }
1149
1150 int disable_apic;
1151
1152 /*
1153  * This initializes the IO-APIC and APIC hardware if this is
1154  * a UP kernel.
1155  */
1156 int __init APIC_init_uniprocessor (void)
1157 {
1158         if (disable_apic) {
1159                 printk(KERN_INFO "Apic disabled\n");
1160                 return -1;
1161         }
1162         if (!cpu_has_apic) {
1163                 disable_apic = 1;
1164                 printk(KERN_INFO "Apic disabled by BIOS\n");
1165                 return -1;
1166         }
1167
1168         verify_local_APIC();
1169
1170         phys_cpu_present_map = physid_mask_of_physid(boot_cpu_id);
1171         apic_write(APIC_ID, SET_APIC_ID(boot_cpu_id));
1172
1173         setup_local_APIC();
1174
1175         if (smp_found_config && !skip_ioapic_setup && nr_ioapics)
1176                 setup_IO_APIC();
1177         else
1178                 nr_ioapics = 0;
1179         setup_boot_APIC_clock();
1180         check_nmi_watchdog();
1181         return 0;
1182 }
1183
1184 static __init int setup_disableapic(char *str)
1185 {
1186         disable_apic = 1;
1187         clear_bit(X86_FEATURE_APIC, boot_cpu_data.x86_capability);
1188         return 0;
1189 }
1190 early_param("disableapic", setup_disableapic);
1191
1192 /* same as disableapic, for compatibility */
1193 static __init int setup_nolapic(char *str)
1194 {
1195         return setup_disableapic(str);
1196 }
1197 early_param("nolapic", setup_nolapic);
1198
1199 static int __init parse_lapic_timer_c2_ok(char *arg)
1200 {
1201         local_apic_timer_c2_ok = 1;
1202         return 0;
1203 }
1204 early_param("lapic_timer_c2_ok", parse_lapic_timer_c2_ok);
1205
1206 static __init int setup_noapictimer(char *str)
1207 {
1208         if (str[0] != ' ' && str[0] != 0)
1209                 return 0;
1210         disable_apic_timer = 1;
1211         return 1;
1212 }
1213
1214 static __init int setup_apicmaintimer(char *str)
1215 {
1216         apic_runs_main_timer = 1;
1217         nohpet = 1;
1218         return 1;
1219 }
1220 __setup("apicmaintimer", setup_apicmaintimer);
1221
1222 static __init int setup_noapicmaintimer(char *str)
1223 {
1224         apic_runs_main_timer = -1;
1225         return 1;
1226 }
1227 __setup("noapicmaintimer", setup_noapicmaintimer);
1228
1229 static __init int setup_apicpmtimer(char *s)
1230 {
1231         apic_calibrate_pmtmr = 1;
1232         notsc_setup(NULL);
1233         return setup_apicmaintimer(NULL);
1234 }
1235 __setup("apicpmtimer", setup_apicpmtimer);
1236
1237 __setup("noapictimer", setup_noapictimer);
1238