]> git.kernelconcepts.de Git - karo-tx-linux.git/blob - arch/x86/kernel/apic/apic.c
Merge ath-next from ath.git
[karo-tx-linux.git] / arch / x86 / kernel / apic / apic.c
1 /*
2  *      Local APIC handling, local APIC timers
3  *
4  *      (c) 1999, 2000, 2009 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/perf_event.h>
18 #include <linux/kernel_stat.h>
19 #include <linux/mc146818rtc.h>
20 #include <linux/acpi_pmtmr.h>
21 #include <linux/clockchips.h>
22 #include <linux/interrupt.h>
23 #include <linux/bootmem.h>
24 #include <linux/ftrace.h>
25 #include <linux/ioport.h>
26 #include <linux/module.h>
27 #include <linux/syscore_ops.h>
28 #include <linux/delay.h>
29 #include <linux/timex.h>
30 #include <linux/i8253.h>
31 #include <linux/dmar.h>
32 #include <linux/init.h>
33 #include <linux/cpu.h>
34 #include <linux/dmi.h>
35 #include <linux/smp.h>
36 #include <linux/mm.h>
37
38 #include <asm/trace/irq_vectors.h>
39 #include <asm/irq_remapping.h>
40 #include <asm/perf_event.h>
41 #include <asm/x86_init.h>
42 #include <asm/pgalloc.h>
43 #include <linux/atomic.h>
44 #include <asm/mpspec.h>
45 #include <asm/i8259.h>
46 #include <asm/proto.h>
47 #include <asm/apic.h>
48 #include <asm/io_apic.h>
49 #include <asm/desc.h>
50 #include <asm/hpet.h>
51 #include <asm/idle.h>
52 #include <asm/mtrr.h>
53 #include <asm/time.h>
54 #include <asm/smp.h>
55 #include <asm/mce.h>
56 #include <asm/tsc.h>
57 #include <asm/hypervisor.h>
58
59 unsigned int num_processors;
60
61 unsigned disabled_cpus;
62
63 /* Processor that is doing the boot up */
64 unsigned int boot_cpu_physical_apicid = -1U;
65 EXPORT_SYMBOL_GPL(boot_cpu_physical_apicid);
66
67 /*
68  * The highest APIC ID seen during enumeration.
69  */
70 static unsigned int max_physical_apicid;
71
72 /*
73  * Bitmask of physically existing CPUs:
74  */
75 physid_mask_t phys_cpu_present_map;
76
77 /*
78  * Processor to be disabled specified by kernel parameter
79  * disable_cpu_apicid=<int>, mostly used for the kdump 2nd kernel to
80  * avoid undefined behaviour caused by sending INIT from AP to BSP.
81  */
82 static unsigned int disabled_cpu_apicid __read_mostly = BAD_APICID;
83
84 /*
85  * Map cpu index to physical APIC ID
86  */
87 DEFINE_EARLY_PER_CPU_READ_MOSTLY(u16, x86_cpu_to_apicid, BAD_APICID);
88 DEFINE_EARLY_PER_CPU_READ_MOSTLY(u16, x86_bios_cpu_apicid, BAD_APICID);
89 EXPORT_EARLY_PER_CPU_SYMBOL(x86_cpu_to_apicid);
90 EXPORT_EARLY_PER_CPU_SYMBOL(x86_bios_cpu_apicid);
91
92 #ifdef CONFIG_X86_32
93
94 /*
95  * On x86_32, the mapping between cpu and logical apicid may vary
96  * depending on apic in use.  The following early percpu variable is
97  * used for the mapping.  This is where the behaviors of x86_64 and 32
98  * actually diverge.  Let's keep it ugly for now.
99  */
100 DEFINE_EARLY_PER_CPU_READ_MOSTLY(int, x86_cpu_to_logical_apicid, BAD_APICID);
101
102 /* Local APIC was disabled by the BIOS and enabled by the kernel */
103 static int enabled_via_apicbase;
104
105 /*
106  * Handle interrupt mode configuration register (IMCR).
107  * This register controls whether the interrupt signals
108  * that reach the BSP come from the master PIC or from the
109  * local APIC. Before entering Symmetric I/O Mode, either
110  * the BIOS or the operating system must switch out of
111  * PIC Mode by changing the IMCR.
112  */
113 static inline void imcr_pic_to_apic(void)
114 {
115         /* select IMCR register */
116         outb(0x70, 0x22);
117         /* NMI and 8259 INTR go through APIC */
118         outb(0x01, 0x23);
119 }
120
121 static inline void imcr_apic_to_pic(void)
122 {
123         /* select IMCR register */
124         outb(0x70, 0x22);
125         /* NMI and 8259 INTR go directly to BSP */
126         outb(0x00, 0x23);
127 }
128 #endif
129
130 /*
131  * Knob to control our willingness to enable the local APIC.
132  *
133  * +1=force-enable
134  */
135 static int force_enable_local_apic __initdata;
136
137 /*
138  * APIC command line parameters
139  */
140 static int __init parse_lapic(char *arg)
141 {
142         if (config_enabled(CONFIG_X86_32) && !arg)
143                 force_enable_local_apic = 1;
144         else if (arg && !strncmp(arg, "notscdeadline", 13))
145                 setup_clear_cpu_cap(X86_FEATURE_TSC_DEADLINE_TIMER);
146         return 0;
147 }
148 early_param("lapic", parse_lapic);
149
150 #ifdef CONFIG_X86_64
151 static int apic_calibrate_pmtmr __initdata;
152 static __init int setup_apicpmtimer(char *s)
153 {
154         apic_calibrate_pmtmr = 1;
155         notsc_setup(NULL);
156         return 0;
157 }
158 __setup("apicpmtimer", setup_apicpmtimer);
159 #endif
160
161 unsigned long mp_lapic_addr;
162 int disable_apic;
163 /* Disable local APIC timer from the kernel commandline or via dmi quirk */
164 static int disable_apic_timer __initdata;
165 /* Local APIC timer works in C2 */
166 int local_apic_timer_c2_ok;
167 EXPORT_SYMBOL_GPL(local_apic_timer_c2_ok);
168
169 int first_system_vector = FIRST_SYSTEM_VECTOR;
170
171 /*
172  * Debug level, exported for io_apic.c
173  */
174 unsigned int apic_verbosity;
175
176 int pic_mode;
177
178 /* Have we found an MP table */
179 int smp_found_config;
180
181 static struct resource lapic_resource = {
182         .name = "Local APIC",
183         .flags = IORESOURCE_MEM | IORESOURCE_BUSY,
184 };
185
186 unsigned int lapic_timer_frequency = 0;
187
188 static void apic_pm_activate(void);
189
190 static unsigned long apic_phys;
191
192 /*
193  * Get the LAPIC version
194  */
195 static inline int lapic_get_version(void)
196 {
197         return GET_APIC_VERSION(apic_read(APIC_LVR));
198 }
199
200 /*
201  * Check, if the APIC is integrated or a separate chip
202  */
203 static inline int lapic_is_integrated(void)
204 {
205 #ifdef CONFIG_X86_64
206         return 1;
207 #else
208         return APIC_INTEGRATED(lapic_get_version());
209 #endif
210 }
211
212 /*
213  * Check, whether this is a modern or a first generation APIC
214  */
215 static int modern_apic(void)
216 {
217         /* AMD systems use old APIC versions, so check the CPU */
218         if (boot_cpu_data.x86_vendor == X86_VENDOR_AMD &&
219             boot_cpu_data.x86 >= 0xf)
220                 return 1;
221         return lapic_get_version() >= 0x14;
222 }
223
224 /*
225  * right after this call apic become NOOP driven
226  * so apic->write/read doesn't do anything
227  */
228 static void __init apic_disable(void)
229 {
230         pr_info("APIC: switched to apic NOOP\n");
231         apic = &apic_noop;
232 }
233
234 void native_apic_wait_icr_idle(void)
235 {
236         while (apic_read(APIC_ICR) & APIC_ICR_BUSY)
237                 cpu_relax();
238 }
239
240 u32 native_safe_apic_wait_icr_idle(void)
241 {
242         u32 send_status;
243         int timeout;
244
245         timeout = 0;
246         do {
247                 send_status = apic_read(APIC_ICR) & APIC_ICR_BUSY;
248                 if (!send_status)
249                         break;
250                 inc_irq_stat(icr_read_retry_count);
251                 udelay(100);
252         } while (timeout++ < 1000);
253
254         return send_status;
255 }
256
257 void native_apic_icr_write(u32 low, u32 id)
258 {
259         unsigned long flags;
260
261         local_irq_save(flags);
262         apic_write(APIC_ICR2, SET_APIC_DEST_FIELD(id));
263         apic_write(APIC_ICR, low);
264         local_irq_restore(flags);
265 }
266
267 u64 native_apic_icr_read(void)
268 {
269         u32 icr1, icr2;
270
271         icr2 = apic_read(APIC_ICR2);
272         icr1 = apic_read(APIC_ICR);
273
274         return icr1 | ((u64)icr2 << 32);
275 }
276
277 #ifdef CONFIG_X86_32
278 /**
279  * get_physical_broadcast - Get number of physical broadcast IDs
280  */
281 int get_physical_broadcast(void)
282 {
283         return modern_apic() ? 0xff : 0xf;
284 }
285 #endif
286
287 /**
288  * lapic_get_maxlvt - get the maximum number of local vector table entries
289  */
290 int lapic_get_maxlvt(void)
291 {
292         unsigned int v;
293
294         v = apic_read(APIC_LVR);
295         /*
296          * - we always have APIC integrated on 64bit mode
297          * - 82489DXs do not report # of LVT entries
298          */
299         return APIC_INTEGRATED(GET_APIC_VERSION(v)) ? GET_APIC_MAXLVT(v) : 2;
300 }
301
302 /*
303  * Local APIC timer
304  */
305
306 /* Clock divisor */
307 #define APIC_DIVISOR 16
308 #define TSC_DIVISOR  32
309
310 /*
311  * This function sets up the local APIC timer, with a timeout of
312  * 'clocks' APIC bus clock. During calibration we actually call
313  * this function twice on the boot CPU, once with a bogus timeout
314  * value, second time for real. The other (noncalibrating) CPUs
315  * call this function only once, with the real, calibrated value.
316  *
317  * We do reads before writes even if unnecessary, to get around the
318  * P5 APIC double write bug.
319  */
320 static void __setup_APIC_LVTT(unsigned int clocks, int oneshot, int irqen)
321 {
322         unsigned int lvtt_value, tmp_value;
323
324         lvtt_value = LOCAL_TIMER_VECTOR;
325         if (!oneshot)
326                 lvtt_value |= APIC_LVT_TIMER_PERIODIC;
327         else if (boot_cpu_has(X86_FEATURE_TSC_DEADLINE_TIMER))
328                 lvtt_value |= APIC_LVT_TIMER_TSCDEADLINE;
329
330         if (!lapic_is_integrated())
331                 lvtt_value |= SET_APIC_TIMER_BASE(APIC_TIMER_BASE_DIV);
332
333         if (!irqen)
334                 lvtt_value |= APIC_LVT_MASKED;
335
336         apic_write(APIC_LVTT, lvtt_value);
337
338         if (lvtt_value & APIC_LVT_TIMER_TSCDEADLINE) {
339                 printk_once(KERN_DEBUG "TSC deadline timer enabled\n");
340                 return;
341         }
342
343         /*
344          * Divide PICLK by 16
345          */
346         tmp_value = apic_read(APIC_TDCR);
347         apic_write(APIC_TDCR,
348                 (tmp_value & ~(APIC_TDR_DIV_1 | APIC_TDR_DIV_TMBASE)) |
349                 APIC_TDR_DIV_16);
350
351         if (!oneshot)
352                 apic_write(APIC_TMICT, clocks / APIC_DIVISOR);
353 }
354
355 /*
356  * Setup extended LVT, AMD specific
357  *
358  * Software should use the LVT offsets the BIOS provides.  The offsets
359  * are determined by the subsystems using it like those for MCE
360  * threshold or IBS.  On K8 only offset 0 (APIC500) and MCE interrupts
361  * are supported. Beginning with family 10h at least 4 offsets are
362  * available.
363  *
364  * Since the offsets must be consistent for all cores, we keep track
365  * of the LVT offsets in software and reserve the offset for the same
366  * vector also to be used on other cores. An offset is freed by
367  * setting the entry to APIC_EILVT_MASKED.
368  *
369  * If the BIOS is right, there should be no conflicts. Otherwise a
370  * "[Firmware Bug]: ..." error message is generated. However, if
371  * software does not properly determines the offsets, it is not
372  * necessarily a BIOS bug.
373  */
374
375 static atomic_t eilvt_offsets[APIC_EILVT_NR_MAX];
376
377 static inline int eilvt_entry_is_changeable(unsigned int old, unsigned int new)
378 {
379         return (old & APIC_EILVT_MASKED)
380                 || (new == APIC_EILVT_MASKED)
381                 || ((new & ~APIC_EILVT_MASKED) == old);
382 }
383
384 static unsigned int reserve_eilvt_offset(int offset, unsigned int new)
385 {
386         unsigned int rsvd, vector;
387
388         if (offset >= APIC_EILVT_NR_MAX)
389                 return ~0;
390
391         rsvd = atomic_read(&eilvt_offsets[offset]);
392         do {
393                 vector = rsvd & ~APIC_EILVT_MASKED;     /* 0: unassigned */
394                 if (vector && !eilvt_entry_is_changeable(vector, new))
395                         /* may not change if vectors are different */
396                         return rsvd;
397                 rsvd = atomic_cmpxchg(&eilvt_offsets[offset], rsvd, new);
398         } while (rsvd != new);
399
400         rsvd &= ~APIC_EILVT_MASKED;
401         if (rsvd && rsvd != vector)
402                 pr_info("LVT offset %d assigned for vector 0x%02x\n",
403                         offset, rsvd);
404
405         return new;
406 }
407
408 /*
409  * If mask=1, the LVT entry does not generate interrupts while mask=0
410  * enables the vector. See also the BKDGs. Must be called with
411  * preemption disabled.
412  */
413
414 int setup_APIC_eilvt(u8 offset, u8 vector, u8 msg_type, u8 mask)
415 {
416         unsigned long reg = APIC_EILVTn(offset);
417         unsigned int new, old, reserved;
418
419         new = (mask << 16) | (msg_type << 8) | vector;
420         old = apic_read(reg);
421         reserved = reserve_eilvt_offset(offset, new);
422
423         if (reserved != new) {
424                 pr_err(FW_BUG "cpu %d, try to use APIC%lX (LVT offset %d) for "
425                        "vector 0x%x, but the register is already in use for "
426                        "vector 0x%x on another cpu\n",
427                        smp_processor_id(), reg, offset, new, reserved);
428                 return -EINVAL;
429         }
430
431         if (!eilvt_entry_is_changeable(old, new)) {
432                 pr_err(FW_BUG "cpu %d, try to use APIC%lX (LVT offset %d) for "
433                        "vector 0x%x, but the register is already in use for "
434                        "vector 0x%x on this cpu\n",
435                        smp_processor_id(), reg, offset, new, old);
436                 return -EBUSY;
437         }
438
439         apic_write(reg, new);
440
441         return 0;
442 }
443 EXPORT_SYMBOL_GPL(setup_APIC_eilvt);
444
445 /*
446  * Program the next event, relative to now
447  */
448 static int lapic_next_event(unsigned long delta,
449                             struct clock_event_device *evt)
450 {
451         apic_write(APIC_TMICT, delta);
452         return 0;
453 }
454
455 static int lapic_next_deadline(unsigned long delta,
456                                struct clock_event_device *evt)
457 {
458         u64 tsc;
459
460         tsc = rdtsc();
461         wrmsrl(MSR_IA32_TSC_DEADLINE, tsc + (((u64) delta) * TSC_DIVISOR));
462         return 0;
463 }
464
465 static int lapic_timer_shutdown(struct clock_event_device *evt)
466 {
467         unsigned int v;
468
469         /* Lapic used as dummy for broadcast ? */
470         if (evt->features & CLOCK_EVT_FEAT_DUMMY)
471                 return 0;
472
473         v = apic_read(APIC_LVTT);
474         v |= (APIC_LVT_MASKED | LOCAL_TIMER_VECTOR);
475         apic_write(APIC_LVTT, v);
476         apic_write(APIC_TMICT, 0);
477         return 0;
478 }
479
480 static inline int
481 lapic_timer_set_periodic_oneshot(struct clock_event_device *evt, bool oneshot)
482 {
483         /* Lapic used as dummy for broadcast ? */
484         if (evt->features & CLOCK_EVT_FEAT_DUMMY)
485                 return 0;
486
487         __setup_APIC_LVTT(lapic_timer_frequency, oneshot, 1);
488         return 0;
489 }
490
491 static int lapic_timer_set_periodic(struct clock_event_device *evt)
492 {
493         return lapic_timer_set_periodic_oneshot(evt, false);
494 }
495
496 static int lapic_timer_set_oneshot(struct clock_event_device *evt)
497 {
498         return lapic_timer_set_periodic_oneshot(evt, true);
499 }
500
501 /*
502  * Local APIC timer broadcast function
503  */
504 static void lapic_timer_broadcast(const struct cpumask *mask)
505 {
506 #ifdef CONFIG_SMP
507         apic->send_IPI_mask(mask, LOCAL_TIMER_VECTOR);
508 #endif
509 }
510
511
512 /*
513  * The local apic timer can be used for any function which is CPU local.
514  */
515 static struct clock_event_device lapic_clockevent = {
516         .name                   = "lapic",
517         .features               = CLOCK_EVT_FEAT_PERIODIC |
518                                   CLOCK_EVT_FEAT_ONESHOT | CLOCK_EVT_FEAT_C3STOP
519                                   | CLOCK_EVT_FEAT_DUMMY,
520         .shift                  = 32,
521         .set_state_shutdown     = lapic_timer_shutdown,
522         .set_state_periodic     = lapic_timer_set_periodic,
523         .set_state_oneshot      = lapic_timer_set_oneshot,
524         .set_next_event         = lapic_next_event,
525         .broadcast              = lapic_timer_broadcast,
526         .rating                 = 100,
527         .irq                    = -1,
528 };
529 static DEFINE_PER_CPU(struct clock_event_device, lapic_events);
530
531 /*
532  * Setup the local APIC timer for this CPU. Copy the initialized values
533  * of the boot CPU and register the clock event in the framework.
534  */
535 static void setup_APIC_timer(void)
536 {
537         struct clock_event_device *levt = this_cpu_ptr(&lapic_events);
538
539         if (this_cpu_has(X86_FEATURE_ARAT)) {
540                 lapic_clockevent.features &= ~CLOCK_EVT_FEAT_C3STOP;
541                 /* Make LAPIC timer preferrable over percpu HPET */
542                 lapic_clockevent.rating = 150;
543         }
544
545         memcpy(levt, &lapic_clockevent, sizeof(*levt));
546         levt->cpumask = cpumask_of(smp_processor_id());
547
548         if (this_cpu_has(X86_FEATURE_TSC_DEADLINE_TIMER)) {
549                 levt->features &= ~(CLOCK_EVT_FEAT_PERIODIC |
550                                     CLOCK_EVT_FEAT_DUMMY);
551                 levt->set_next_event = lapic_next_deadline;
552                 clockevents_config_and_register(levt,
553                                                 (tsc_khz / TSC_DIVISOR) * 1000,
554                                                 0xF, ~0UL);
555         } else
556                 clockevents_register_device(levt);
557 }
558
559 /*
560  * In this functions we calibrate APIC bus clocks to the external timer.
561  *
562  * We want to do the calibration only once since we want to have local timer
563  * irqs syncron. CPUs connected by the same APIC bus have the very same bus
564  * frequency.
565  *
566  * This was previously done by reading the PIT/HPET and waiting for a wrap
567  * around to find out, that a tick has elapsed. I have a box, where the PIT
568  * readout is broken, so it never gets out of the wait loop again. This was
569  * also reported by others.
570  *
571  * Monitoring the jiffies value is inaccurate and the clockevents
572  * infrastructure allows us to do a simple substitution of the interrupt
573  * handler.
574  *
575  * The calibration routine also uses the pm_timer when possible, as the PIT
576  * happens to run way too slow (factor 2.3 on my VAIO CoreDuo, which goes
577  * back to normal later in the boot process).
578  */
579
580 #define LAPIC_CAL_LOOPS         (HZ/10)
581
582 static __initdata int lapic_cal_loops = -1;
583 static __initdata long lapic_cal_t1, lapic_cal_t2;
584 static __initdata unsigned long long lapic_cal_tsc1, lapic_cal_tsc2;
585 static __initdata unsigned long lapic_cal_pm1, lapic_cal_pm2;
586 static __initdata unsigned long lapic_cal_j1, lapic_cal_j2;
587
588 /*
589  * Temporary interrupt handler.
590  */
591 static void __init lapic_cal_handler(struct clock_event_device *dev)
592 {
593         unsigned long long tsc = 0;
594         long tapic = apic_read(APIC_TMCCT);
595         unsigned long pm = acpi_pm_read_early();
596
597         if (cpu_has_tsc)
598                 tsc = rdtsc();
599
600         switch (lapic_cal_loops++) {
601         case 0:
602                 lapic_cal_t1 = tapic;
603                 lapic_cal_tsc1 = tsc;
604                 lapic_cal_pm1 = pm;
605                 lapic_cal_j1 = jiffies;
606                 break;
607
608         case LAPIC_CAL_LOOPS:
609                 lapic_cal_t2 = tapic;
610                 lapic_cal_tsc2 = tsc;
611                 if (pm < lapic_cal_pm1)
612                         pm += ACPI_PM_OVRRUN;
613                 lapic_cal_pm2 = pm;
614                 lapic_cal_j2 = jiffies;
615                 break;
616         }
617 }
618
619 static int __init
620 calibrate_by_pmtimer(long deltapm, long *delta, long *deltatsc)
621 {
622         const long pm_100ms = PMTMR_TICKS_PER_SEC / 10;
623         const long pm_thresh = pm_100ms / 100;
624         unsigned long mult;
625         u64 res;
626
627 #ifndef CONFIG_X86_PM_TIMER
628         return -1;
629 #endif
630
631         apic_printk(APIC_VERBOSE, "... PM-Timer delta = %ld\n", deltapm);
632
633         /* Check, if the PM timer is available */
634         if (!deltapm)
635                 return -1;
636
637         mult = clocksource_hz2mult(PMTMR_TICKS_PER_SEC, 22);
638
639         if (deltapm > (pm_100ms - pm_thresh) &&
640             deltapm < (pm_100ms + pm_thresh)) {
641                 apic_printk(APIC_VERBOSE, "... PM-Timer result ok\n");
642                 return 0;
643         }
644
645         res = (((u64)deltapm) *  mult) >> 22;
646         do_div(res, 1000000);
647         pr_warning("APIC calibration not consistent "
648                    "with PM-Timer: %ldms instead of 100ms\n",(long)res);
649
650         /* Correct the lapic counter value */
651         res = (((u64)(*delta)) * pm_100ms);
652         do_div(res, deltapm);
653         pr_info("APIC delta adjusted to PM-Timer: "
654                 "%lu (%ld)\n", (unsigned long)res, *delta);
655         *delta = (long)res;
656
657         /* Correct the tsc counter value */
658         if (cpu_has_tsc) {
659                 res = (((u64)(*deltatsc)) * pm_100ms);
660                 do_div(res, deltapm);
661                 apic_printk(APIC_VERBOSE, "TSC delta adjusted to "
662                                           "PM-Timer: %lu (%ld)\n",
663                                         (unsigned long)res, *deltatsc);
664                 *deltatsc = (long)res;
665         }
666
667         return 0;
668 }
669
670 static int __init calibrate_APIC_clock(void)
671 {
672         struct clock_event_device *levt = this_cpu_ptr(&lapic_events);
673         void (*real_handler)(struct clock_event_device *dev);
674         unsigned long deltaj;
675         long delta, deltatsc;
676         int pm_referenced = 0;
677
678         /**
679          * check if lapic timer has already been calibrated by platform
680          * specific routine, such as tsc calibration code. if so, we just fill
681          * in the clockevent structure and return.
682          */
683
684         if (boot_cpu_has(X86_FEATURE_TSC_DEADLINE_TIMER)) {
685                 return 0;
686         } else if (lapic_timer_frequency) {
687                 apic_printk(APIC_VERBOSE, "lapic timer already calibrated %d\n",
688                                 lapic_timer_frequency);
689                 lapic_clockevent.mult = div_sc(lapic_timer_frequency/APIC_DIVISOR,
690                                         TICK_NSEC, lapic_clockevent.shift);
691                 lapic_clockevent.max_delta_ns =
692                         clockevent_delta2ns(0x7FFFFF, &lapic_clockevent);
693                 lapic_clockevent.min_delta_ns =
694                         clockevent_delta2ns(0xF, &lapic_clockevent);
695                 lapic_clockevent.features &= ~CLOCK_EVT_FEAT_DUMMY;
696                 return 0;
697         }
698
699         apic_printk(APIC_VERBOSE, "Using local APIC timer interrupts.\n"
700                     "calibrating APIC timer ...\n");
701
702         local_irq_disable();
703
704         /* Replace the global interrupt handler */
705         real_handler = global_clock_event->event_handler;
706         global_clock_event->event_handler = lapic_cal_handler;
707
708         /*
709          * Setup the APIC counter to maximum. There is no way the lapic
710          * can underflow in the 100ms detection time frame
711          */
712         __setup_APIC_LVTT(0xffffffff, 0, 0);
713
714         /* Let the interrupts run */
715         local_irq_enable();
716
717         while (lapic_cal_loops <= LAPIC_CAL_LOOPS)
718                 cpu_relax();
719
720         local_irq_disable();
721
722         /* Restore the real event handler */
723         global_clock_event->event_handler = real_handler;
724
725         /* Build delta t1-t2 as apic timer counts down */
726         delta = lapic_cal_t1 - lapic_cal_t2;
727         apic_printk(APIC_VERBOSE, "... lapic delta = %ld\n", delta);
728
729         deltatsc = (long)(lapic_cal_tsc2 - lapic_cal_tsc1);
730
731         /* we trust the PM based calibration if possible */
732         pm_referenced = !calibrate_by_pmtimer(lapic_cal_pm2 - lapic_cal_pm1,
733                                         &delta, &deltatsc);
734
735         /* Calculate the scaled math multiplication factor */
736         lapic_clockevent.mult = div_sc(delta, TICK_NSEC * LAPIC_CAL_LOOPS,
737                                        lapic_clockevent.shift);
738         lapic_clockevent.max_delta_ns =
739                 clockevent_delta2ns(0x7FFFFFFF, &lapic_clockevent);
740         lapic_clockevent.min_delta_ns =
741                 clockevent_delta2ns(0xF, &lapic_clockevent);
742
743         lapic_timer_frequency = (delta * APIC_DIVISOR) / LAPIC_CAL_LOOPS;
744
745         apic_printk(APIC_VERBOSE, "..... delta %ld\n", delta);
746         apic_printk(APIC_VERBOSE, "..... mult: %u\n", lapic_clockevent.mult);
747         apic_printk(APIC_VERBOSE, "..... calibration result: %u\n",
748                     lapic_timer_frequency);
749
750         if (cpu_has_tsc) {
751                 apic_printk(APIC_VERBOSE, "..... CPU clock speed is "
752                             "%ld.%04ld MHz.\n",
753                             (deltatsc / LAPIC_CAL_LOOPS) / (1000000 / HZ),
754                             (deltatsc / LAPIC_CAL_LOOPS) % (1000000 / HZ));
755         }
756
757         apic_printk(APIC_VERBOSE, "..... host bus clock speed is "
758                     "%u.%04u MHz.\n",
759                     lapic_timer_frequency / (1000000 / HZ),
760                     lapic_timer_frequency % (1000000 / HZ));
761
762         /*
763          * Do a sanity check on the APIC calibration result
764          */
765         if (lapic_timer_frequency < (1000000 / HZ)) {
766                 local_irq_enable();
767                 pr_warning("APIC frequency too slow, disabling apic timer\n");
768                 return -1;
769         }
770
771         levt->features &= ~CLOCK_EVT_FEAT_DUMMY;
772
773         /*
774          * PM timer calibration failed or not turned on
775          * so lets try APIC timer based calibration
776          */
777         if (!pm_referenced) {
778                 apic_printk(APIC_VERBOSE, "... verify APIC timer\n");
779
780                 /*
781                  * Setup the apic timer manually
782                  */
783                 levt->event_handler = lapic_cal_handler;
784                 lapic_timer_set_periodic(levt);
785                 lapic_cal_loops = -1;
786
787                 /* Let the interrupts run */
788                 local_irq_enable();
789
790                 while (lapic_cal_loops <= LAPIC_CAL_LOOPS)
791                         cpu_relax();
792
793                 /* Stop the lapic timer */
794                 local_irq_disable();
795                 lapic_timer_shutdown(levt);
796
797                 /* Jiffies delta */
798                 deltaj = lapic_cal_j2 - lapic_cal_j1;
799                 apic_printk(APIC_VERBOSE, "... jiffies delta = %lu\n", deltaj);
800
801                 /* Check, if the jiffies result is consistent */
802                 if (deltaj >= LAPIC_CAL_LOOPS-2 && deltaj <= LAPIC_CAL_LOOPS+2)
803                         apic_printk(APIC_VERBOSE, "... jiffies result ok\n");
804                 else
805                         levt->features |= CLOCK_EVT_FEAT_DUMMY;
806         }
807         local_irq_enable();
808
809         if (levt->features & CLOCK_EVT_FEAT_DUMMY) {
810                 pr_warning("APIC timer disabled due to verification failure\n");
811                         return -1;
812         }
813
814         return 0;
815 }
816
817 /*
818  * Setup the boot APIC
819  *
820  * Calibrate and verify the result.
821  */
822 void __init setup_boot_APIC_clock(void)
823 {
824         /*
825          * The local apic timer can be disabled via the kernel
826          * commandline or from the CPU detection code. Register the lapic
827          * timer as a dummy clock event source on SMP systems, so the
828          * broadcast mechanism is used. On UP systems simply ignore it.
829          */
830         if (disable_apic_timer) {
831                 pr_info("Disabling APIC timer\n");
832                 /* No broadcast on UP ! */
833                 if (num_possible_cpus() > 1) {
834                         lapic_clockevent.mult = 1;
835                         setup_APIC_timer();
836                 }
837                 return;
838         }
839
840         if (calibrate_APIC_clock()) {
841                 /* No broadcast on UP ! */
842                 if (num_possible_cpus() > 1)
843                         setup_APIC_timer();
844                 return;
845         }
846
847         /*
848          * If nmi_watchdog is set to IO_APIC, we need the
849          * PIT/HPET going.  Otherwise register lapic as a dummy
850          * device.
851          */
852         lapic_clockevent.features &= ~CLOCK_EVT_FEAT_DUMMY;
853
854         /* Setup the lapic or request the broadcast */
855         setup_APIC_timer();
856 }
857
858 void setup_secondary_APIC_clock(void)
859 {
860         setup_APIC_timer();
861 }
862
863 /*
864  * The guts of the apic timer interrupt
865  */
866 static void local_apic_timer_interrupt(void)
867 {
868         int cpu = smp_processor_id();
869         struct clock_event_device *evt = &per_cpu(lapic_events, cpu);
870
871         /*
872          * Normally we should not be here till LAPIC has been initialized but
873          * in some cases like kdump, its possible that there is a pending LAPIC
874          * timer interrupt from previous kernel's context and is delivered in
875          * new kernel the moment interrupts are enabled.
876          *
877          * Interrupts are enabled early and LAPIC is setup much later, hence
878          * its possible that when we get here evt->event_handler is NULL.
879          * Check for event_handler being NULL and discard the interrupt as
880          * spurious.
881          */
882         if (!evt->event_handler) {
883                 pr_warning("Spurious LAPIC timer interrupt on cpu %d\n", cpu);
884                 /* Switch it off */
885                 lapic_timer_shutdown(evt);
886                 return;
887         }
888
889         /*
890          * the NMI deadlock-detector uses this.
891          */
892         inc_irq_stat(apic_timer_irqs);
893
894         evt->event_handler(evt);
895 }
896
897 /*
898  * Local APIC timer interrupt. This is the most natural way for doing
899  * local interrupts, but local timer interrupts can be emulated by
900  * broadcast interrupts too. [in case the hw doesn't support APIC timers]
901  *
902  * [ if a single-CPU system runs an SMP kernel then we call the local
903  *   interrupt as well. Thus we cannot inline the local irq ... ]
904  */
905 __visible void __irq_entry smp_apic_timer_interrupt(struct pt_regs *regs)
906 {
907         struct pt_regs *old_regs = set_irq_regs(regs);
908
909         /*
910          * NOTE! We'd better ACK the irq immediately,
911          * because timer handling can be slow.
912          *
913          * update_process_times() expects us to have done irq_enter().
914          * Besides, if we don't timer interrupts ignore the global
915          * interrupt lock, which is the WrongThing (tm) to do.
916          */
917         entering_ack_irq();
918         local_apic_timer_interrupt();
919         exiting_irq();
920
921         set_irq_regs(old_regs);
922 }
923
924 __visible void __irq_entry smp_trace_apic_timer_interrupt(struct pt_regs *regs)
925 {
926         struct pt_regs *old_regs = set_irq_regs(regs);
927
928         /*
929          * NOTE! We'd better ACK the irq immediately,
930          * because timer handling can be slow.
931          *
932          * update_process_times() expects us to have done irq_enter().
933          * Besides, if we don't timer interrupts ignore the global
934          * interrupt lock, which is the WrongThing (tm) to do.
935          */
936         entering_ack_irq();
937         trace_local_timer_entry(LOCAL_TIMER_VECTOR);
938         local_apic_timer_interrupt();
939         trace_local_timer_exit(LOCAL_TIMER_VECTOR);
940         exiting_irq();
941
942         set_irq_regs(old_regs);
943 }
944
945 int setup_profiling_timer(unsigned int multiplier)
946 {
947         return -EINVAL;
948 }
949
950 /*
951  * Local APIC start and shutdown
952  */
953
954 /**
955  * clear_local_APIC - shutdown the local APIC
956  *
957  * This is called, when a CPU is disabled and before rebooting, so the state of
958  * the local APIC has no dangling leftovers. Also used to cleanout any BIOS
959  * leftovers during boot.
960  */
961 void clear_local_APIC(void)
962 {
963         int maxlvt;
964         u32 v;
965
966         /* APIC hasn't been mapped yet */
967         if (!x2apic_mode && !apic_phys)
968                 return;
969
970         maxlvt = lapic_get_maxlvt();
971         /*
972          * Masking an LVT entry can trigger a local APIC error
973          * if the vector is zero. Mask LVTERR first to prevent this.
974          */
975         if (maxlvt >= 3) {
976                 v = ERROR_APIC_VECTOR; /* any non-zero vector will do */
977                 apic_write(APIC_LVTERR, v | APIC_LVT_MASKED);
978         }
979         /*
980          * Careful: we have to set masks only first to deassert
981          * any level-triggered sources.
982          */
983         v = apic_read(APIC_LVTT);
984         apic_write(APIC_LVTT, v | APIC_LVT_MASKED);
985         v = apic_read(APIC_LVT0);
986         apic_write(APIC_LVT0, v | APIC_LVT_MASKED);
987         v = apic_read(APIC_LVT1);
988         apic_write(APIC_LVT1, v | APIC_LVT_MASKED);
989         if (maxlvt >= 4) {
990                 v = apic_read(APIC_LVTPC);
991                 apic_write(APIC_LVTPC, v | APIC_LVT_MASKED);
992         }
993
994         /* lets not touch this if we didn't frob it */
995 #ifdef CONFIG_X86_THERMAL_VECTOR
996         if (maxlvt >= 5) {
997                 v = apic_read(APIC_LVTTHMR);
998                 apic_write(APIC_LVTTHMR, v | APIC_LVT_MASKED);
999         }
1000 #endif
1001 #ifdef CONFIG_X86_MCE_INTEL
1002         if (maxlvt >= 6) {
1003                 v = apic_read(APIC_LVTCMCI);
1004                 if (!(v & APIC_LVT_MASKED))
1005                         apic_write(APIC_LVTCMCI, v | APIC_LVT_MASKED);
1006         }
1007 #endif
1008
1009         /*
1010          * Clean APIC state for other OSs:
1011          */
1012         apic_write(APIC_LVTT, APIC_LVT_MASKED);
1013         apic_write(APIC_LVT0, APIC_LVT_MASKED);
1014         apic_write(APIC_LVT1, APIC_LVT_MASKED);
1015         if (maxlvt >= 3)
1016                 apic_write(APIC_LVTERR, APIC_LVT_MASKED);
1017         if (maxlvt >= 4)
1018                 apic_write(APIC_LVTPC, APIC_LVT_MASKED);
1019
1020         /* Integrated APIC (!82489DX) ? */
1021         if (lapic_is_integrated()) {
1022                 if (maxlvt > 3)
1023                         /* Clear ESR due to Pentium errata 3AP and 11AP */
1024                         apic_write(APIC_ESR, 0);
1025                 apic_read(APIC_ESR);
1026         }
1027 }
1028
1029 /**
1030  * disable_local_APIC - clear and disable the local APIC
1031  */
1032 void disable_local_APIC(void)
1033 {
1034         unsigned int value;
1035
1036         /* APIC hasn't been mapped yet */
1037         if (!x2apic_mode && !apic_phys)
1038                 return;
1039
1040         clear_local_APIC();
1041
1042         /*
1043          * Disable APIC (implies clearing of registers
1044          * for 82489DX!).
1045          */
1046         value = apic_read(APIC_SPIV);
1047         value &= ~APIC_SPIV_APIC_ENABLED;
1048         apic_write(APIC_SPIV, value);
1049
1050 #ifdef CONFIG_X86_32
1051         /*
1052          * When LAPIC was disabled by the BIOS and enabled by the kernel,
1053          * restore the disabled state.
1054          */
1055         if (enabled_via_apicbase) {
1056                 unsigned int l, h;
1057
1058                 rdmsr(MSR_IA32_APICBASE, l, h);
1059                 l &= ~MSR_IA32_APICBASE_ENABLE;
1060                 wrmsr(MSR_IA32_APICBASE, l, h);
1061         }
1062 #endif
1063 }
1064
1065 /*
1066  * If Linux enabled the LAPIC against the BIOS default disable it down before
1067  * re-entering the BIOS on shutdown.  Otherwise the BIOS may get confused and
1068  * not power-off.  Additionally clear all LVT entries before disable_local_APIC
1069  * for the case where Linux didn't enable the LAPIC.
1070  */
1071 void lapic_shutdown(void)
1072 {
1073         unsigned long flags;
1074
1075         if (!cpu_has_apic && !apic_from_smp_config())
1076                 return;
1077
1078         local_irq_save(flags);
1079
1080 #ifdef CONFIG_X86_32
1081         if (!enabled_via_apicbase)
1082                 clear_local_APIC();
1083         else
1084 #endif
1085                 disable_local_APIC();
1086
1087
1088         local_irq_restore(flags);
1089 }
1090
1091 /**
1092  * sync_Arb_IDs - synchronize APIC bus arbitration IDs
1093  */
1094 void __init sync_Arb_IDs(void)
1095 {
1096         /*
1097          * Unsupported on P4 - see Intel Dev. Manual Vol. 3, Ch. 8.6.1 And not
1098          * needed on AMD.
1099          */
1100         if (modern_apic() || boot_cpu_data.x86_vendor == X86_VENDOR_AMD)
1101                 return;
1102
1103         /*
1104          * Wait for idle.
1105          */
1106         apic_wait_icr_idle();
1107
1108         apic_printk(APIC_DEBUG, "Synchronizing Arb IDs.\n");
1109         apic_write(APIC_ICR, APIC_DEST_ALLINC |
1110                         APIC_INT_LEVELTRIG | APIC_DM_INIT);
1111 }
1112
1113 /*
1114  * An initial setup of the virtual wire mode.
1115  */
1116 void __init init_bsp_APIC(void)
1117 {
1118         unsigned int value;
1119
1120         /*
1121          * Don't do the setup now if we have a SMP BIOS as the
1122          * through-I/O-APIC virtual wire mode might be active.
1123          */
1124         if (smp_found_config || !cpu_has_apic)
1125                 return;
1126
1127         /*
1128          * Do not trust the local APIC being empty at bootup.
1129          */
1130         clear_local_APIC();
1131
1132         /*
1133          * Enable APIC.
1134          */
1135         value = apic_read(APIC_SPIV);
1136         value &= ~APIC_VECTOR_MASK;
1137         value |= APIC_SPIV_APIC_ENABLED;
1138
1139 #ifdef CONFIG_X86_32
1140         /* This bit is reserved on P4/Xeon and should be cleared */
1141         if ((boot_cpu_data.x86_vendor == X86_VENDOR_INTEL) &&
1142             (boot_cpu_data.x86 == 15))
1143                 value &= ~APIC_SPIV_FOCUS_DISABLED;
1144         else
1145 #endif
1146                 value |= APIC_SPIV_FOCUS_DISABLED;
1147         value |= SPURIOUS_APIC_VECTOR;
1148         apic_write(APIC_SPIV, value);
1149
1150         /*
1151          * Set up the virtual wire mode.
1152          */
1153         apic_write(APIC_LVT0, APIC_DM_EXTINT);
1154         value = APIC_DM_NMI;
1155         if (!lapic_is_integrated())             /* 82489DX */
1156                 value |= APIC_LVT_LEVEL_TRIGGER;
1157         apic_write(APIC_LVT1, value);
1158 }
1159
1160 static void lapic_setup_esr(void)
1161 {
1162         unsigned int oldvalue, value, maxlvt;
1163
1164         if (!lapic_is_integrated()) {
1165                 pr_info("No ESR for 82489DX.\n");
1166                 return;
1167         }
1168
1169         if (apic->disable_esr) {
1170                 /*
1171                  * Something untraceable is creating bad interrupts on
1172                  * secondary quads ... for the moment, just leave the
1173                  * ESR disabled - we can't do anything useful with the
1174                  * errors anyway - mbligh
1175                  */
1176                 pr_info("Leaving ESR disabled.\n");
1177                 return;
1178         }
1179
1180         maxlvt = lapic_get_maxlvt();
1181         if (maxlvt > 3)         /* Due to the Pentium erratum 3AP. */
1182                 apic_write(APIC_ESR, 0);
1183         oldvalue = apic_read(APIC_ESR);
1184
1185         /* enables sending errors */
1186         value = ERROR_APIC_VECTOR;
1187         apic_write(APIC_LVTERR, value);
1188
1189         /*
1190          * spec says clear errors after enabling vector.
1191          */
1192         if (maxlvt > 3)
1193                 apic_write(APIC_ESR, 0);
1194         value = apic_read(APIC_ESR);
1195         if (value != oldvalue)
1196                 apic_printk(APIC_VERBOSE, "ESR value before enabling "
1197                         "vector: 0x%08x  after: 0x%08x\n",
1198                         oldvalue, value);
1199 }
1200
1201 /**
1202  * setup_local_APIC - setup the local APIC
1203  *
1204  * Used to setup local APIC while initializing BSP or bringin up APs.
1205  * Always called with preemption disabled.
1206  */
1207 void setup_local_APIC(void)
1208 {
1209         int cpu = smp_processor_id();
1210         unsigned int value, queued;
1211         int i, j, acked = 0;
1212         unsigned long long tsc = 0, ntsc;
1213         long long max_loops = cpu_khz ? cpu_khz : 1000000;
1214
1215         if (cpu_has_tsc)
1216                 tsc = rdtsc();
1217
1218         if (disable_apic) {
1219                 disable_ioapic_support();
1220                 return;
1221         }
1222
1223 #ifdef CONFIG_X86_32
1224         /* Pound the ESR really hard over the head with a big hammer - mbligh */
1225         if (lapic_is_integrated() && apic->disable_esr) {
1226                 apic_write(APIC_ESR, 0);
1227                 apic_write(APIC_ESR, 0);
1228                 apic_write(APIC_ESR, 0);
1229                 apic_write(APIC_ESR, 0);
1230         }
1231 #endif
1232         perf_events_lapic_init();
1233
1234         /*
1235          * Double-check whether this APIC is really registered.
1236          * This is meaningless in clustered apic mode, so we skip it.
1237          */
1238         BUG_ON(!apic->apic_id_registered());
1239
1240         /*
1241          * Intel recommends to set DFR, LDR and TPR before enabling
1242          * an APIC.  See e.g. "AP-388 82489DX User's Manual" (Intel
1243          * document number 292116).  So here it goes...
1244          */
1245         apic->init_apic_ldr();
1246
1247 #ifdef CONFIG_X86_32
1248         /*
1249          * APIC LDR is initialized.  If logical_apicid mapping was
1250          * initialized during get_smp_config(), make sure it matches the
1251          * actual value.
1252          */
1253         i = early_per_cpu(x86_cpu_to_logical_apicid, cpu);
1254         WARN_ON(i != BAD_APICID && i != logical_smp_processor_id());
1255         /* always use the value from LDR */
1256         early_per_cpu(x86_cpu_to_logical_apicid, cpu) =
1257                 logical_smp_processor_id();
1258 #endif
1259
1260         /*
1261          * Set Task Priority to 'accept all'. We never change this
1262          * later on.
1263          */
1264         value = apic_read(APIC_TASKPRI);
1265         value &= ~APIC_TPRI_MASK;
1266         apic_write(APIC_TASKPRI, value);
1267
1268         /*
1269          * After a crash, we no longer service the interrupts and a pending
1270          * interrupt from previous kernel might still have ISR bit set.
1271          *
1272          * Most probably by now CPU has serviced that pending interrupt and
1273          * it might not have done the ack_APIC_irq() because it thought,
1274          * interrupt came from i8259 as ExtInt. LAPIC did not get EOI so it
1275          * does not clear the ISR bit and cpu thinks it has already serivced
1276          * the interrupt. Hence a vector might get locked. It was noticed
1277          * for timer irq (vector 0x31). Issue an extra EOI to clear ISR.
1278          */
1279         do {
1280                 queued = 0;
1281                 for (i = APIC_ISR_NR - 1; i >= 0; i--)
1282                         queued |= apic_read(APIC_IRR + i*0x10);
1283
1284                 for (i = APIC_ISR_NR - 1; i >= 0; i--) {
1285                         value = apic_read(APIC_ISR + i*0x10);
1286                         for (j = 31; j >= 0; j--) {
1287                                 if (value & (1<<j)) {
1288                                         ack_APIC_irq();
1289                                         acked++;
1290                                 }
1291                         }
1292                 }
1293                 if (acked > 256) {
1294                         printk(KERN_ERR "LAPIC pending interrupts after %d EOI\n",
1295                                acked);
1296                         break;
1297                 }
1298                 if (queued) {
1299                         if (cpu_has_tsc && cpu_khz) {
1300                                 ntsc = rdtsc();
1301                                 max_loops = (cpu_khz << 10) - (ntsc - tsc);
1302                         } else
1303                                 max_loops--;
1304                 }
1305         } while (queued && max_loops > 0);
1306         WARN_ON(max_loops <= 0);
1307
1308         /*
1309          * Now that we are all set up, enable the APIC
1310          */
1311         value = apic_read(APIC_SPIV);
1312         value &= ~APIC_VECTOR_MASK;
1313         /*
1314          * Enable APIC
1315          */
1316         value |= APIC_SPIV_APIC_ENABLED;
1317
1318 #ifdef CONFIG_X86_32
1319         /*
1320          * Some unknown Intel IO/APIC (or APIC) errata is biting us with
1321          * certain networking cards. If high frequency interrupts are
1322          * happening on a particular IOAPIC pin, plus the IOAPIC routing
1323          * entry is masked/unmasked at a high rate as well then sooner or
1324          * later IOAPIC line gets 'stuck', no more interrupts are received
1325          * from the device. If focus CPU is disabled then the hang goes
1326          * away, oh well :-(
1327          *
1328          * [ This bug can be reproduced easily with a level-triggered
1329          *   PCI Ne2000 networking cards and PII/PIII processors, dual
1330          *   BX chipset. ]
1331          */
1332         /*
1333          * Actually disabling the focus CPU check just makes the hang less
1334          * frequent as it makes the interrupt distributon model be more
1335          * like LRU than MRU (the short-term load is more even across CPUs).
1336          * See also the comment in end_level_ioapic_irq().  --macro
1337          */
1338
1339         /*
1340          * - enable focus processor (bit==0)
1341          * - 64bit mode always use processor focus
1342          *   so no need to set it
1343          */
1344         value &= ~APIC_SPIV_FOCUS_DISABLED;
1345 #endif
1346
1347         /*
1348          * Set spurious IRQ vector
1349          */
1350         value |= SPURIOUS_APIC_VECTOR;
1351         apic_write(APIC_SPIV, value);
1352
1353         /*
1354          * Set up LVT0, LVT1:
1355          *
1356          * set up through-local-APIC on the BP's LINT0. This is not
1357          * strictly necessary in pure symmetric-IO mode, but sometimes
1358          * we delegate interrupts to the 8259A.
1359          */
1360         /*
1361          * TODO: set up through-local-APIC from through-I/O-APIC? --macro
1362          */
1363         value = apic_read(APIC_LVT0) & APIC_LVT_MASKED;
1364         if (!cpu && (pic_mode || !value)) {
1365                 value = APIC_DM_EXTINT;
1366                 apic_printk(APIC_VERBOSE, "enabled ExtINT on CPU#%d\n", cpu);
1367         } else {
1368                 value = APIC_DM_EXTINT | APIC_LVT_MASKED;
1369                 apic_printk(APIC_VERBOSE, "masked ExtINT on CPU#%d\n", cpu);
1370         }
1371         apic_write(APIC_LVT0, value);
1372
1373         /*
1374          * only the BP should see the LINT1 NMI signal, obviously.
1375          */
1376         if (!cpu)
1377                 value = APIC_DM_NMI;
1378         else
1379                 value = APIC_DM_NMI | APIC_LVT_MASKED;
1380         if (!lapic_is_integrated())             /* 82489DX */
1381                 value |= APIC_LVT_LEVEL_TRIGGER;
1382         apic_write(APIC_LVT1, value);
1383
1384 #ifdef CONFIG_X86_MCE_INTEL
1385         /* Recheck CMCI information after local APIC is up on CPU #0 */
1386         if (!cpu)
1387                 cmci_recheck();
1388 #endif
1389 }
1390
1391 static void end_local_APIC_setup(void)
1392 {
1393         lapic_setup_esr();
1394
1395 #ifdef CONFIG_X86_32
1396         {
1397                 unsigned int value;
1398                 /* Disable the local apic timer */
1399                 value = apic_read(APIC_LVTT);
1400                 value |= (APIC_LVT_MASKED | LOCAL_TIMER_VECTOR);
1401                 apic_write(APIC_LVTT, value);
1402         }
1403 #endif
1404
1405         apic_pm_activate();
1406 }
1407
1408 /*
1409  * APIC setup function for application processors. Called from smpboot.c
1410  */
1411 void apic_ap_setup(void)
1412 {
1413         setup_local_APIC();
1414         end_local_APIC_setup();
1415 }
1416
1417 #ifdef CONFIG_X86_X2APIC
1418 int x2apic_mode;
1419
1420 enum {
1421         X2APIC_OFF,
1422         X2APIC_ON,
1423         X2APIC_DISABLED,
1424 };
1425 static int x2apic_state;
1426
1427 static inline void __x2apic_disable(void)
1428 {
1429         u64 msr;
1430
1431         if (!cpu_has_apic)
1432                 return;
1433
1434         rdmsrl(MSR_IA32_APICBASE, msr);
1435         if (!(msr & X2APIC_ENABLE))
1436                 return;
1437         /* Disable xapic and x2apic first and then reenable xapic mode */
1438         wrmsrl(MSR_IA32_APICBASE, msr & ~(X2APIC_ENABLE | XAPIC_ENABLE));
1439         wrmsrl(MSR_IA32_APICBASE, msr & ~X2APIC_ENABLE);
1440         printk_once(KERN_INFO "x2apic disabled\n");
1441 }
1442
1443 static inline void __x2apic_enable(void)
1444 {
1445         u64 msr;
1446
1447         rdmsrl(MSR_IA32_APICBASE, msr);
1448         if (msr & X2APIC_ENABLE)
1449                 return;
1450         wrmsrl(MSR_IA32_APICBASE, msr | X2APIC_ENABLE);
1451         printk_once(KERN_INFO "x2apic enabled\n");
1452 }
1453
1454 static int __init setup_nox2apic(char *str)
1455 {
1456         if (x2apic_enabled()) {
1457                 int apicid = native_apic_msr_read(APIC_ID);
1458
1459                 if (apicid >= 255) {
1460                         pr_warning("Apicid: %08x, cannot enforce nox2apic\n",
1461                                    apicid);
1462                         return 0;
1463                 }
1464                 pr_warning("x2apic already enabled.\n");
1465                 __x2apic_disable();
1466         }
1467         setup_clear_cpu_cap(X86_FEATURE_X2APIC);
1468         x2apic_state = X2APIC_DISABLED;
1469         x2apic_mode = 0;
1470         return 0;
1471 }
1472 early_param("nox2apic", setup_nox2apic);
1473
1474 /* Called from cpu_init() to enable x2apic on (secondary) cpus */
1475 void x2apic_setup(void)
1476 {
1477         /*
1478          * If x2apic is not in ON state, disable it if already enabled
1479          * from BIOS.
1480          */
1481         if (x2apic_state != X2APIC_ON) {
1482                 __x2apic_disable();
1483                 return;
1484         }
1485         __x2apic_enable();
1486 }
1487
1488 static __init void x2apic_disable(void)
1489 {
1490         u32 x2apic_id, state = x2apic_state;
1491
1492         x2apic_mode = 0;
1493         x2apic_state = X2APIC_DISABLED;
1494
1495         if (state != X2APIC_ON)
1496                 return;
1497
1498         x2apic_id = read_apic_id();
1499         if (x2apic_id >= 255)
1500                 panic("Cannot disable x2apic, id: %08x\n", x2apic_id);
1501
1502         __x2apic_disable();
1503         register_lapic_address(mp_lapic_addr);
1504 }
1505
1506 static __init void x2apic_enable(void)
1507 {
1508         if (x2apic_state != X2APIC_OFF)
1509                 return;
1510
1511         x2apic_mode = 1;
1512         x2apic_state = X2APIC_ON;
1513         __x2apic_enable();
1514 }
1515
1516 static __init void try_to_enable_x2apic(int remap_mode)
1517 {
1518         if (x2apic_state == X2APIC_DISABLED)
1519                 return;
1520
1521         if (remap_mode != IRQ_REMAP_X2APIC_MODE) {
1522                 /* IR is required if there is APIC ID > 255 even when running
1523                  * under KVM
1524                  */
1525                 if (max_physical_apicid > 255 ||
1526                     !hypervisor_x2apic_available()) {
1527                         pr_info("x2apic: IRQ remapping doesn't support X2APIC mode\n");
1528                         x2apic_disable();
1529                         return;
1530                 }
1531
1532                 /*
1533                  * without IR all CPUs can be addressed by IOAPIC/MSI
1534                  * only in physical mode
1535                  */
1536                 x2apic_phys = 1;
1537         }
1538         x2apic_enable();
1539 }
1540
1541 void __init check_x2apic(void)
1542 {
1543         if (x2apic_enabled()) {
1544                 pr_info("x2apic: enabled by BIOS, switching to x2apic ops\n");
1545                 x2apic_mode = 1;
1546                 x2apic_state = X2APIC_ON;
1547         } else if (!cpu_has_x2apic) {
1548                 x2apic_state = X2APIC_DISABLED;
1549         }
1550 }
1551 #else /* CONFIG_X86_X2APIC */
1552 static int __init validate_x2apic(void)
1553 {
1554         if (!apic_is_x2apic_enabled())
1555                 return 0;
1556         /*
1557          * Checkme: Can we simply turn off x2apic here instead of panic?
1558          */
1559         panic("BIOS has enabled x2apic but kernel doesn't support x2apic, please disable x2apic in BIOS.\n");
1560 }
1561 early_initcall(validate_x2apic);
1562
1563 static inline void try_to_enable_x2apic(int remap_mode) { }
1564 static inline void __x2apic_enable(void) { }
1565 #endif /* !CONFIG_X86_X2APIC */
1566
1567 static int __init try_to_enable_IR(void)
1568 {
1569 #ifdef CONFIG_X86_IO_APIC
1570         if (!x2apic_enabled() && skip_ioapic_setup) {
1571                 pr_info("Not enabling interrupt remapping due to skipped IO-APIC setup\n");
1572                 return -1;
1573         }
1574 #endif
1575         return irq_remapping_enable();
1576 }
1577
1578 void __init enable_IR_x2apic(void)
1579 {
1580         unsigned long flags;
1581         int ret, ir_stat;
1582
1583         ir_stat = irq_remapping_prepare();
1584         if (ir_stat < 0 && !x2apic_supported())
1585                 return;
1586
1587         ret = save_ioapic_entries();
1588         if (ret) {
1589                 pr_info("Saving IO-APIC state failed: %d\n", ret);
1590                 return;
1591         }
1592
1593         local_irq_save(flags);
1594         legacy_pic->mask_all();
1595         mask_ioapic_entries();
1596
1597         /* If irq_remapping_prepare() succeded, try to enable it */
1598         if (ir_stat >= 0)
1599                 ir_stat = try_to_enable_IR();
1600         /* ir_stat contains the remap mode or an error code */
1601         try_to_enable_x2apic(ir_stat);
1602
1603         if (ir_stat < 0)
1604                 restore_ioapic_entries();
1605         legacy_pic->restore_mask();
1606         local_irq_restore(flags);
1607 }
1608
1609 #ifdef CONFIG_X86_64
1610 /*
1611  * Detect and enable local APICs on non-SMP boards.
1612  * Original code written by Keir Fraser.
1613  * On AMD64 we trust the BIOS - if it says no APIC it is likely
1614  * not correctly set up (usually the APIC timer won't work etc.)
1615  */
1616 static int __init detect_init_APIC(void)
1617 {
1618         if (!cpu_has_apic) {
1619                 pr_info("No local APIC present\n");
1620                 return -1;
1621         }
1622
1623         mp_lapic_addr = APIC_DEFAULT_PHYS_BASE;
1624         return 0;
1625 }
1626 #else
1627
1628 static int __init apic_verify(void)
1629 {
1630         u32 features, h, l;
1631
1632         /*
1633          * The APIC feature bit should now be enabled
1634          * in `cpuid'
1635          */
1636         features = cpuid_edx(1);
1637         if (!(features & (1 << X86_FEATURE_APIC))) {
1638                 pr_warning("Could not enable APIC!\n");
1639                 return -1;
1640         }
1641         set_cpu_cap(&boot_cpu_data, X86_FEATURE_APIC);
1642         mp_lapic_addr = APIC_DEFAULT_PHYS_BASE;
1643
1644         /* The BIOS may have set up the APIC at some other address */
1645         if (boot_cpu_data.x86 >= 6) {
1646                 rdmsr(MSR_IA32_APICBASE, l, h);
1647                 if (l & MSR_IA32_APICBASE_ENABLE)
1648                         mp_lapic_addr = l & MSR_IA32_APICBASE_BASE;
1649         }
1650
1651         pr_info("Found and enabled local APIC!\n");
1652         return 0;
1653 }
1654
1655 int __init apic_force_enable(unsigned long addr)
1656 {
1657         u32 h, l;
1658
1659         if (disable_apic)
1660                 return -1;
1661
1662         /*
1663          * Some BIOSes disable the local APIC in the APIC_BASE
1664          * MSR. This can only be done in software for Intel P6 or later
1665          * and AMD K7 (Model > 1) or later.
1666          */
1667         if (boot_cpu_data.x86 >= 6) {
1668                 rdmsr(MSR_IA32_APICBASE, l, h);
1669                 if (!(l & MSR_IA32_APICBASE_ENABLE)) {
1670                         pr_info("Local APIC disabled by BIOS -- reenabling.\n");
1671                         l &= ~MSR_IA32_APICBASE_BASE;
1672                         l |= MSR_IA32_APICBASE_ENABLE | addr;
1673                         wrmsr(MSR_IA32_APICBASE, l, h);
1674                         enabled_via_apicbase = 1;
1675                 }
1676         }
1677         return apic_verify();
1678 }
1679
1680 /*
1681  * Detect and initialize APIC
1682  */
1683 static int __init detect_init_APIC(void)
1684 {
1685         /* Disabled by kernel option? */
1686         if (disable_apic)
1687                 return -1;
1688
1689         switch (boot_cpu_data.x86_vendor) {
1690         case X86_VENDOR_AMD:
1691                 if ((boot_cpu_data.x86 == 6 && boot_cpu_data.x86_model > 1) ||
1692                     (boot_cpu_data.x86 >= 15))
1693                         break;
1694                 goto no_apic;
1695         case X86_VENDOR_INTEL:
1696                 if (boot_cpu_data.x86 == 6 || boot_cpu_data.x86 == 15 ||
1697                     (boot_cpu_data.x86 == 5 && cpu_has_apic))
1698                         break;
1699                 goto no_apic;
1700         default:
1701                 goto no_apic;
1702         }
1703
1704         if (!cpu_has_apic) {
1705                 /*
1706                  * Over-ride BIOS and try to enable the local APIC only if
1707                  * "lapic" specified.
1708                  */
1709                 if (!force_enable_local_apic) {
1710                         pr_info("Local APIC disabled by BIOS -- "
1711                                 "you can enable it with \"lapic\"\n");
1712                         return -1;
1713                 }
1714                 if (apic_force_enable(APIC_DEFAULT_PHYS_BASE))
1715                         return -1;
1716         } else {
1717                 if (apic_verify())
1718                         return -1;
1719         }
1720
1721         apic_pm_activate();
1722
1723         return 0;
1724
1725 no_apic:
1726         pr_info("No local APIC present or hardware disabled\n");
1727         return -1;
1728 }
1729 #endif
1730
1731 /**
1732  * init_apic_mappings - initialize APIC mappings
1733  */
1734 void __init init_apic_mappings(void)
1735 {
1736         unsigned int new_apicid;
1737
1738         if (x2apic_mode) {
1739                 boot_cpu_physical_apicid = read_apic_id();
1740                 return;
1741         }
1742
1743         /* If no local APIC can be found return early */
1744         if (!smp_found_config && detect_init_APIC()) {
1745                 /* lets NOP'ify apic operations */
1746                 pr_info("APIC: disable apic facility\n");
1747                 apic_disable();
1748         } else {
1749                 apic_phys = mp_lapic_addr;
1750
1751                 /*
1752                  * acpi lapic path already maps that address in
1753                  * acpi_register_lapic_address()
1754                  */
1755                 if (!acpi_lapic && !smp_found_config)
1756                         register_lapic_address(apic_phys);
1757         }
1758
1759         /*
1760          * Fetch the APIC ID of the BSP in case we have a
1761          * default configuration (or the MP table is broken).
1762          */
1763         new_apicid = read_apic_id();
1764         if (boot_cpu_physical_apicid != new_apicid) {
1765                 boot_cpu_physical_apicid = new_apicid;
1766                 /*
1767                  * yeah -- we lie about apic_version
1768                  * in case if apic was disabled via boot option
1769                  * but it's not a problem for SMP compiled kernel
1770                  * since smp_sanity_check is prepared for such a case
1771                  * and disable smp mode
1772                  */
1773                 apic_version[new_apicid] =
1774                          GET_APIC_VERSION(apic_read(APIC_LVR));
1775         }
1776 }
1777
1778 void __init register_lapic_address(unsigned long address)
1779 {
1780         mp_lapic_addr = address;
1781
1782         if (!x2apic_mode) {
1783                 set_fixmap_nocache(FIX_APIC_BASE, address);
1784                 apic_printk(APIC_VERBOSE, "mapped APIC to %16lx (%16lx)\n",
1785                             APIC_BASE, mp_lapic_addr);
1786         }
1787         if (boot_cpu_physical_apicid == -1U) {
1788                 boot_cpu_physical_apicid  = read_apic_id();
1789                 apic_version[boot_cpu_physical_apicid] =
1790                          GET_APIC_VERSION(apic_read(APIC_LVR));
1791         }
1792 }
1793
1794 int apic_version[MAX_LOCAL_APIC];
1795
1796 /*
1797  * Local APIC interrupts
1798  */
1799
1800 /*
1801  * This interrupt should _never_ happen with our APIC/SMP architecture
1802  */
1803 static inline void __smp_spurious_interrupt(u8 vector)
1804 {
1805         u32 v;
1806
1807         /*
1808          * Check if this really is a spurious interrupt and ACK it
1809          * if it is a vectored one.  Just in case...
1810          * Spurious interrupts should not be ACKed.
1811          */
1812         v = apic_read(APIC_ISR + ((vector & ~0x1f) >> 1));
1813         if (v & (1 << (vector & 0x1f)))
1814                 ack_APIC_irq();
1815
1816         inc_irq_stat(irq_spurious_count);
1817
1818         /* see sw-dev-man vol 3, chapter 7.4.13.5 */
1819         pr_info("spurious APIC interrupt through vector %02x on CPU#%d, "
1820                 "should never happen.\n", vector, smp_processor_id());
1821 }
1822
1823 __visible void smp_spurious_interrupt(struct pt_regs *regs)
1824 {
1825         entering_irq();
1826         __smp_spurious_interrupt(~regs->orig_ax);
1827         exiting_irq();
1828 }
1829
1830 __visible void smp_trace_spurious_interrupt(struct pt_regs *regs)
1831 {
1832         u8 vector = ~regs->orig_ax;
1833
1834         entering_irq();
1835         trace_spurious_apic_entry(vector);
1836         __smp_spurious_interrupt(vector);
1837         trace_spurious_apic_exit(vector);
1838         exiting_irq();
1839 }
1840
1841 /*
1842  * This interrupt should never happen with our APIC/SMP architecture
1843  */
1844 static inline void __smp_error_interrupt(struct pt_regs *regs)
1845 {
1846         u32 v;
1847         u32 i = 0;
1848         static const char * const error_interrupt_reason[] = {
1849                 "Send CS error",                /* APIC Error Bit 0 */
1850                 "Receive CS error",             /* APIC Error Bit 1 */
1851                 "Send accept error",            /* APIC Error Bit 2 */
1852                 "Receive accept error",         /* APIC Error Bit 3 */
1853                 "Redirectable IPI",             /* APIC Error Bit 4 */
1854                 "Send illegal vector",          /* APIC Error Bit 5 */
1855                 "Received illegal vector",      /* APIC Error Bit 6 */
1856                 "Illegal register address",     /* APIC Error Bit 7 */
1857         };
1858
1859         /* First tickle the hardware, only then report what went on. -- REW */
1860         if (lapic_get_maxlvt() > 3)     /* Due to the Pentium erratum 3AP. */
1861                 apic_write(APIC_ESR, 0);
1862         v = apic_read(APIC_ESR);
1863         ack_APIC_irq();
1864         atomic_inc(&irq_err_count);
1865
1866         apic_printk(APIC_DEBUG, KERN_DEBUG "APIC error on CPU%d: %02x",
1867                     smp_processor_id(), v);
1868
1869         v &= 0xff;
1870         while (v) {
1871                 if (v & 0x1)
1872                         apic_printk(APIC_DEBUG, KERN_CONT " : %s", error_interrupt_reason[i]);
1873                 i++;
1874                 v >>= 1;
1875         }
1876
1877         apic_printk(APIC_DEBUG, KERN_CONT "\n");
1878
1879 }
1880
1881 __visible void smp_error_interrupt(struct pt_regs *regs)
1882 {
1883         entering_irq();
1884         __smp_error_interrupt(regs);
1885         exiting_irq();
1886 }
1887
1888 __visible void smp_trace_error_interrupt(struct pt_regs *regs)
1889 {
1890         entering_irq();
1891         trace_error_apic_entry(ERROR_APIC_VECTOR);
1892         __smp_error_interrupt(regs);
1893         trace_error_apic_exit(ERROR_APIC_VECTOR);
1894         exiting_irq();
1895 }
1896
1897 /**
1898  * connect_bsp_APIC - attach the APIC to the interrupt system
1899  */
1900 static void __init connect_bsp_APIC(void)
1901 {
1902 #ifdef CONFIG_X86_32
1903         if (pic_mode) {
1904                 /*
1905                  * Do not trust the local APIC being empty at bootup.
1906                  */
1907                 clear_local_APIC();
1908                 /*
1909                  * PIC mode, enable APIC mode in the IMCR, i.e.  connect BSP's
1910                  * local APIC to INT and NMI lines.
1911                  */
1912                 apic_printk(APIC_VERBOSE, "leaving PIC mode, "
1913                                 "enabling APIC mode.\n");
1914                 imcr_pic_to_apic();
1915         }
1916 #endif
1917 }
1918
1919 /**
1920  * disconnect_bsp_APIC - detach the APIC from the interrupt system
1921  * @virt_wire_setup:    indicates, whether virtual wire mode is selected
1922  *
1923  * Virtual wire mode is necessary to deliver legacy interrupts even when the
1924  * APIC is disabled.
1925  */
1926 void disconnect_bsp_APIC(int virt_wire_setup)
1927 {
1928         unsigned int value;
1929
1930 #ifdef CONFIG_X86_32
1931         if (pic_mode) {
1932                 /*
1933                  * Put the board back into PIC mode (has an effect only on
1934                  * certain older boards).  Note that APIC interrupts, including
1935                  * IPIs, won't work beyond this point!  The only exception are
1936                  * INIT IPIs.
1937                  */
1938                 apic_printk(APIC_VERBOSE, "disabling APIC mode, "
1939                                 "entering PIC mode.\n");
1940                 imcr_apic_to_pic();
1941                 return;
1942         }
1943 #endif
1944
1945         /* Go back to Virtual Wire compatibility mode */
1946
1947         /* For the spurious interrupt use vector F, and enable it */
1948         value = apic_read(APIC_SPIV);
1949         value &= ~APIC_VECTOR_MASK;
1950         value |= APIC_SPIV_APIC_ENABLED;
1951         value |= 0xf;
1952         apic_write(APIC_SPIV, value);
1953
1954         if (!virt_wire_setup) {
1955                 /*
1956                  * For LVT0 make it edge triggered, active high,
1957                  * external and enabled
1958                  */
1959                 value = apic_read(APIC_LVT0);
1960                 value &= ~(APIC_MODE_MASK | APIC_SEND_PENDING |
1961                         APIC_INPUT_POLARITY | APIC_LVT_REMOTE_IRR |
1962                         APIC_LVT_LEVEL_TRIGGER | APIC_LVT_MASKED);
1963                 value |= APIC_LVT_REMOTE_IRR | APIC_SEND_PENDING;
1964                 value = SET_APIC_DELIVERY_MODE(value, APIC_MODE_EXTINT);
1965                 apic_write(APIC_LVT0, value);
1966         } else {
1967                 /* Disable LVT0 */
1968                 apic_write(APIC_LVT0, APIC_LVT_MASKED);
1969         }
1970
1971         /*
1972          * For LVT1 make it edge triggered, active high,
1973          * nmi and enabled
1974          */
1975         value = apic_read(APIC_LVT1);
1976         value &= ~(APIC_MODE_MASK | APIC_SEND_PENDING |
1977                         APIC_INPUT_POLARITY | APIC_LVT_REMOTE_IRR |
1978                         APIC_LVT_LEVEL_TRIGGER | APIC_LVT_MASKED);
1979         value |= APIC_LVT_REMOTE_IRR | APIC_SEND_PENDING;
1980         value = SET_APIC_DELIVERY_MODE(value, APIC_MODE_NMI);
1981         apic_write(APIC_LVT1, value);
1982 }
1983
1984 int generic_processor_info(int apicid, int version)
1985 {
1986         int cpu, max = nr_cpu_ids;
1987         bool boot_cpu_detected = physid_isset(boot_cpu_physical_apicid,
1988                                 phys_cpu_present_map);
1989
1990         /*
1991          * boot_cpu_physical_apicid is designed to have the apicid
1992          * returned by read_apic_id(), i.e, the apicid of the
1993          * currently booting-up processor. However, on some platforms,
1994          * it is temporarily modified by the apicid reported as BSP
1995          * through MP table. Concretely:
1996          *
1997          * - arch/x86/kernel/mpparse.c: MP_processor_info()
1998          * - arch/x86/mm/amdtopology.c: amd_numa_init()
1999          *
2000          * This function is executed with the modified
2001          * boot_cpu_physical_apicid. So, disabled_cpu_apicid kernel
2002          * parameter doesn't work to disable APs on kdump 2nd kernel.
2003          *
2004          * Since fixing handling of boot_cpu_physical_apicid requires
2005          * another discussion and tests on each platform, we leave it
2006          * for now and here we use read_apic_id() directly in this
2007          * function, generic_processor_info().
2008          */
2009         if (disabled_cpu_apicid != BAD_APICID &&
2010             disabled_cpu_apicid != read_apic_id() &&
2011             disabled_cpu_apicid == apicid) {
2012                 int thiscpu = num_processors + disabled_cpus;
2013
2014                 pr_warning("APIC: Disabling requested cpu."
2015                            " Processor %d/0x%x ignored.\n",
2016                            thiscpu, apicid);
2017
2018                 disabled_cpus++;
2019                 return -ENODEV;
2020         }
2021
2022         /*
2023          * If boot cpu has not been detected yet, then only allow upto
2024          * nr_cpu_ids - 1 processors and keep one slot free for boot cpu
2025          */
2026         if (!boot_cpu_detected && num_processors >= nr_cpu_ids - 1 &&
2027             apicid != boot_cpu_physical_apicid) {
2028                 int thiscpu = max + disabled_cpus - 1;
2029
2030                 pr_warning(
2031                         "ACPI: NR_CPUS/possible_cpus limit of %i almost"
2032                         " reached. Keeping one slot for boot cpu."
2033                         "  Processor %d/0x%x ignored.\n", max, thiscpu, apicid);
2034
2035                 disabled_cpus++;
2036                 return -ENODEV;
2037         }
2038
2039         if (num_processors >= nr_cpu_ids) {
2040                 int thiscpu = max + disabled_cpus;
2041
2042                 pr_warning(
2043                         "ACPI: NR_CPUS/possible_cpus limit of %i reached."
2044                         "  Processor %d/0x%x ignored.\n", max, thiscpu, apicid);
2045
2046                 disabled_cpus++;
2047                 return -EINVAL;
2048         }
2049
2050         num_processors++;
2051         if (apicid == boot_cpu_physical_apicid) {
2052                 /*
2053                  * x86_bios_cpu_apicid is required to have processors listed
2054                  * in same order as logical cpu numbers. Hence the first
2055                  * entry is BSP, and so on.
2056                  * boot_cpu_init() already hold bit 0 in cpu_present_mask
2057                  * for BSP.
2058                  */
2059                 cpu = 0;
2060         } else
2061                 cpu = cpumask_next_zero(-1, cpu_present_mask);
2062
2063         /*
2064          * Validate version
2065          */
2066         if (version == 0x0) {
2067                 pr_warning("BIOS bug: APIC version is 0 for CPU %d/0x%x, fixing up to 0x10\n",
2068                            cpu, apicid);
2069                 version = 0x10;
2070         }
2071         apic_version[apicid] = version;
2072
2073         if (version != apic_version[boot_cpu_physical_apicid]) {
2074                 pr_warning("BIOS bug: APIC version mismatch, boot CPU: %x, CPU %d: version %x\n",
2075                         apic_version[boot_cpu_physical_apicid], cpu, version);
2076         }
2077
2078         physid_set(apicid, phys_cpu_present_map);
2079         if (apicid > max_physical_apicid)
2080                 max_physical_apicid = apicid;
2081
2082 #if defined(CONFIG_SMP) || defined(CONFIG_X86_64)
2083         early_per_cpu(x86_cpu_to_apicid, cpu) = apicid;
2084         early_per_cpu(x86_bios_cpu_apicid, cpu) = apicid;
2085 #endif
2086 #ifdef CONFIG_X86_32
2087         early_per_cpu(x86_cpu_to_logical_apicid, cpu) =
2088                 apic->x86_32_early_logical_apicid(cpu);
2089 #endif
2090         set_cpu_possible(cpu, true);
2091         set_cpu_present(cpu, true);
2092
2093         return cpu;
2094 }
2095
2096 int hard_smp_processor_id(void)
2097 {
2098         return read_apic_id();
2099 }
2100
2101 void default_init_apic_ldr(void)
2102 {
2103         unsigned long val;
2104
2105         apic_write(APIC_DFR, APIC_DFR_VALUE);
2106         val = apic_read(APIC_LDR) & ~APIC_LDR_MASK;
2107         val |= SET_APIC_LOGICAL_ID(1UL << smp_processor_id());
2108         apic_write(APIC_LDR, val);
2109 }
2110
2111 int default_cpu_mask_to_apicid_and(const struct cpumask *cpumask,
2112                                    const struct cpumask *andmask,
2113                                    unsigned int *apicid)
2114 {
2115         unsigned int cpu;
2116
2117         for_each_cpu_and(cpu, cpumask, andmask) {
2118                 if (cpumask_test_cpu(cpu, cpu_online_mask))
2119                         break;
2120         }
2121
2122         if (likely(cpu < nr_cpu_ids)) {
2123                 *apicid = per_cpu(x86_cpu_to_apicid, cpu);
2124                 return 0;
2125         }
2126
2127         return -EINVAL;
2128 }
2129
2130 /*
2131  * Override the generic EOI implementation with an optimized version.
2132  * Only called during early boot when only one CPU is active and with
2133  * interrupts disabled, so we know this does not race with actual APIC driver
2134  * use.
2135  */
2136 void __init apic_set_eoi_write(void (*eoi_write)(u32 reg, u32 v))
2137 {
2138         struct apic **drv;
2139
2140         for (drv = __apicdrivers; drv < __apicdrivers_end; drv++) {
2141                 /* Should happen once for each apic */
2142                 WARN_ON((*drv)->eoi_write == eoi_write);
2143                 (*drv)->eoi_write = eoi_write;
2144         }
2145 }
2146
2147 static void __init apic_bsp_up_setup(void)
2148 {
2149 #ifdef CONFIG_X86_64
2150         apic_write(APIC_ID, SET_APIC_ID(boot_cpu_physical_apicid));
2151 #else
2152         /*
2153          * Hack: In case of kdump, after a crash, kernel might be booting
2154          * on a cpu with non-zero lapic id. But boot_cpu_physical_apicid
2155          * might be zero if read from MP tables. Get it from LAPIC.
2156          */
2157 # ifdef CONFIG_CRASH_DUMP
2158         boot_cpu_physical_apicid = read_apic_id();
2159 # endif
2160 #endif
2161         physid_set_mask_of_physid(boot_cpu_physical_apicid, &phys_cpu_present_map);
2162 }
2163
2164 /**
2165  * apic_bsp_setup - Setup function for local apic and io-apic
2166  * @upmode:             Force UP mode (for APIC_init_uniprocessor)
2167  *
2168  * Returns:
2169  * apic_id of BSP APIC
2170  */
2171 int __init apic_bsp_setup(bool upmode)
2172 {
2173         int id;
2174
2175         connect_bsp_APIC();
2176         if (upmode)
2177                 apic_bsp_up_setup();
2178         setup_local_APIC();
2179
2180         if (x2apic_mode)
2181                 id = apic_read(APIC_LDR);
2182         else
2183                 id = GET_APIC_LOGICAL_ID(apic_read(APIC_LDR));
2184
2185         enable_IO_APIC();
2186         end_local_APIC_setup();
2187         irq_remap_enable_fault_handling();
2188         setup_IO_APIC();
2189         /* Setup local timer */
2190         x86_init.timers.setup_percpu_clockev();
2191         return id;
2192 }
2193
2194 /*
2195  * This initializes the IO-APIC and APIC hardware if this is
2196  * a UP kernel.
2197  */
2198 int __init APIC_init_uniprocessor(void)
2199 {
2200         if (disable_apic) {
2201                 pr_info("Apic disabled\n");
2202                 return -1;
2203         }
2204 #ifdef CONFIG_X86_64
2205         if (!cpu_has_apic) {
2206                 disable_apic = 1;
2207                 pr_info("Apic disabled by BIOS\n");
2208                 return -1;
2209         }
2210 #else
2211         if (!smp_found_config && !cpu_has_apic)
2212                 return -1;
2213
2214         /*
2215          * Complain if the BIOS pretends there is one.
2216          */
2217         if (!cpu_has_apic &&
2218             APIC_INTEGRATED(apic_version[boot_cpu_physical_apicid])) {
2219                 pr_err("BIOS bug, local APIC 0x%x not detected!...\n",
2220                         boot_cpu_physical_apicid);
2221                 return -1;
2222         }
2223 #endif
2224
2225         if (!smp_found_config)
2226                 disable_ioapic_support();
2227
2228         default_setup_apic_routing();
2229         apic_bsp_setup(true);
2230         return 0;
2231 }
2232
2233 #ifdef CONFIG_UP_LATE_INIT
2234 void __init up_late_init(void)
2235 {
2236         APIC_init_uniprocessor();
2237 }
2238 #endif
2239
2240 /*
2241  * Power management
2242  */
2243 #ifdef CONFIG_PM
2244
2245 static struct {
2246         /*
2247          * 'active' is true if the local APIC was enabled by us and
2248          * not the BIOS; this signifies that we are also responsible
2249          * for disabling it before entering apm/acpi suspend
2250          */
2251         int active;
2252         /* r/w apic fields */
2253         unsigned int apic_id;
2254         unsigned int apic_taskpri;
2255         unsigned int apic_ldr;
2256         unsigned int apic_dfr;
2257         unsigned int apic_spiv;
2258         unsigned int apic_lvtt;
2259         unsigned int apic_lvtpc;
2260         unsigned int apic_lvt0;
2261         unsigned int apic_lvt1;
2262         unsigned int apic_lvterr;
2263         unsigned int apic_tmict;
2264         unsigned int apic_tdcr;
2265         unsigned int apic_thmr;
2266 } apic_pm_state;
2267
2268 static int lapic_suspend(void)
2269 {
2270         unsigned long flags;
2271         int maxlvt;
2272
2273         if (!apic_pm_state.active)
2274                 return 0;
2275
2276         maxlvt = lapic_get_maxlvt();
2277
2278         apic_pm_state.apic_id = apic_read(APIC_ID);
2279         apic_pm_state.apic_taskpri = apic_read(APIC_TASKPRI);
2280         apic_pm_state.apic_ldr = apic_read(APIC_LDR);
2281         apic_pm_state.apic_dfr = apic_read(APIC_DFR);
2282         apic_pm_state.apic_spiv = apic_read(APIC_SPIV);
2283         apic_pm_state.apic_lvtt = apic_read(APIC_LVTT);
2284         if (maxlvt >= 4)
2285                 apic_pm_state.apic_lvtpc = apic_read(APIC_LVTPC);
2286         apic_pm_state.apic_lvt0 = apic_read(APIC_LVT0);
2287         apic_pm_state.apic_lvt1 = apic_read(APIC_LVT1);
2288         apic_pm_state.apic_lvterr = apic_read(APIC_LVTERR);
2289         apic_pm_state.apic_tmict = apic_read(APIC_TMICT);
2290         apic_pm_state.apic_tdcr = apic_read(APIC_TDCR);
2291 #ifdef CONFIG_X86_THERMAL_VECTOR
2292         if (maxlvt >= 5)
2293                 apic_pm_state.apic_thmr = apic_read(APIC_LVTTHMR);
2294 #endif
2295
2296         local_irq_save(flags);
2297         disable_local_APIC();
2298
2299         irq_remapping_disable();
2300
2301         local_irq_restore(flags);
2302         return 0;
2303 }
2304
2305 static void lapic_resume(void)
2306 {
2307         unsigned int l, h;
2308         unsigned long flags;
2309         int maxlvt;
2310
2311         if (!apic_pm_state.active)
2312                 return;
2313
2314         local_irq_save(flags);
2315
2316         /*
2317          * IO-APIC and PIC have their own resume routines.
2318          * We just mask them here to make sure the interrupt
2319          * subsystem is completely quiet while we enable x2apic
2320          * and interrupt-remapping.
2321          */
2322         mask_ioapic_entries();
2323         legacy_pic->mask_all();
2324
2325         if (x2apic_mode) {
2326                 __x2apic_enable();
2327         } else {
2328                 /*
2329                  * Make sure the APICBASE points to the right address
2330                  *
2331                  * FIXME! This will be wrong if we ever support suspend on
2332                  * SMP! We'll need to do this as part of the CPU restore!
2333                  */
2334                 if (boot_cpu_data.x86 >= 6) {
2335                         rdmsr(MSR_IA32_APICBASE, l, h);
2336                         l &= ~MSR_IA32_APICBASE_BASE;
2337                         l |= MSR_IA32_APICBASE_ENABLE | mp_lapic_addr;
2338                         wrmsr(MSR_IA32_APICBASE, l, h);
2339                 }
2340         }
2341
2342         maxlvt = lapic_get_maxlvt();
2343         apic_write(APIC_LVTERR, ERROR_APIC_VECTOR | APIC_LVT_MASKED);
2344         apic_write(APIC_ID, apic_pm_state.apic_id);
2345         apic_write(APIC_DFR, apic_pm_state.apic_dfr);
2346         apic_write(APIC_LDR, apic_pm_state.apic_ldr);
2347         apic_write(APIC_TASKPRI, apic_pm_state.apic_taskpri);
2348         apic_write(APIC_SPIV, apic_pm_state.apic_spiv);
2349         apic_write(APIC_LVT0, apic_pm_state.apic_lvt0);
2350         apic_write(APIC_LVT1, apic_pm_state.apic_lvt1);
2351 #if defined(CONFIG_X86_MCE_INTEL)
2352         if (maxlvt >= 5)
2353                 apic_write(APIC_LVTTHMR, apic_pm_state.apic_thmr);
2354 #endif
2355         if (maxlvt >= 4)
2356                 apic_write(APIC_LVTPC, apic_pm_state.apic_lvtpc);
2357         apic_write(APIC_LVTT, apic_pm_state.apic_lvtt);
2358         apic_write(APIC_TDCR, apic_pm_state.apic_tdcr);
2359         apic_write(APIC_TMICT, apic_pm_state.apic_tmict);
2360         apic_write(APIC_ESR, 0);
2361         apic_read(APIC_ESR);
2362         apic_write(APIC_LVTERR, apic_pm_state.apic_lvterr);
2363         apic_write(APIC_ESR, 0);
2364         apic_read(APIC_ESR);
2365
2366         irq_remapping_reenable(x2apic_mode);
2367
2368         local_irq_restore(flags);
2369 }
2370
2371 /*
2372  * This device has no shutdown method - fully functioning local APICs
2373  * are needed on every CPU up until machine_halt/restart/poweroff.
2374  */
2375
2376 static struct syscore_ops lapic_syscore_ops = {
2377         .resume         = lapic_resume,
2378         .suspend        = lapic_suspend,
2379 };
2380
2381 static void apic_pm_activate(void)
2382 {
2383         apic_pm_state.active = 1;
2384 }
2385
2386 static int __init init_lapic_sysfs(void)
2387 {
2388         /* XXX: remove suspend/resume procs if !apic_pm_state.active? */
2389         if (cpu_has_apic)
2390                 register_syscore_ops(&lapic_syscore_ops);
2391
2392         return 0;
2393 }
2394
2395 /* local apic needs to resume before other devices access its registers. */
2396 core_initcall(init_lapic_sysfs);
2397
2398 #else   /* CONFIG_PM */
2399
2400 static void apic_pm_activate(void) { }
2401
2402 #endif  /* CONFIG_PM */
2403
2404 #ifdef CONFIG_X86_64
2405
2406 static int multi_checked;
2407 static int multi;
2408
2409 static int set_multi(const struct dmi_system_id *d)
2410 {
2411         if (multi)
2412                 return 0;
2413         pr_info("APIC: %s detected, Multi Chassis\n", d->ident);
2414         multi = 1;
2415         return 0;
2416 }
2417
2418 static const struct dmi_system_id multi_dmi_table[] = {
2419         {
2420                 .callback = set_multi,
2421                 .ident = "IBM System Summit2",
2422                 .matches = {
2423                         DMI_MATCH(DMI_SYS_VENDOR, "IBM"),
2424                         DMI_MATCH(DMI_PRODUCT_NAME, "Summit2"),
2425                 },
2426         },
2427         {}
2428 };
2429
2430 static void dmi_check_multi(void)
2431 {
2432         if (multi_checked)
2433                 return;
2434
2435         dmi_check_system(multi_dmi_table);
2436         multi_checked = 1;
2437 }
2438
2439 /*
2440  * apic_is_clustered_box() -- Check if we can expect good TSC
2441  *
2442  * Thus far, the major user of this is IBM's Summit2 series:
2443  * Clustered boxes may have unsynced TSC problems if they are
2444  * multi-chassis.
2445  * Use DMI to check them
2446  */
2447 int apic_is_clustered_box(void)
2448 {
2449         dmi_check_multi();
2450         return multi;
2451 }
2452 #endif
2453
2454 /*
2455  * APIC command line parameters
2456  */
2457 static int __init setup_disableapic(char *arg)
2458 {
2459         disable_apic = 1;
2460         setup_clear_cpu_cap(X86_FEATURE_APIC);
2461         return 0;
2462 }
2463 early_param("disableapic", setup_disableapic);
2464
2465 /* same as disableapic, for compatibility */
2466 static int __init setup_nolapic(char *arg)
2467 {
2468         return setup_disableapic(arg);
2469 }
2470 early_param("nolapic", setup_nolapic);
2471
2472 static int __init parse_lapic_timer_c2_ok(char *arg)
2473 {
2474         local_apic_timer_c2_ok = 1;
2475         return 0;
2476 }
2477 early_param("lapic_timer_c2_ok", parse_lapic_timer_c2_ok);
2478
2479 static int __init parse_disable_apic_timer(char *arg)
2480 {
2481         disable_apic_timer = 1;
2482         return 0;
2483 }
2484 early_param("noapictimer", parse_disable_apic_timer);
2485
2486 static int __init parse_nolapic_timer(char *arg)
2487 {
2488         disable_apic_timer = 1;
2489         return 0;
2490 }
2491 early_param("nolapic_timer", parse_nolapic_timer);
2492
2493 static int __init apic_set_verbosity(char *arg)
2494 {
2495         if (!arg)  {
2496 #ifdef CONFIG_X86_64
2497                 skip_ioapic_setup = 0;
2498                 return 0;
2499 #endif
2500                 return -EINVAL;
2501         }
2502
2503         if (strcmp("debug", arg) == 0)
2504                 apic_verbosity = APIC_DEBUG;
2505         else if (strcmp("verbose", arg) == 0)
2506                 apic_verbosity = APIC_VERBOSE;
2507         else {
2508                 pr_warning("APIC Verbosity level %s not recognised"
2509                         " use apic=verbose or apic=debug\n", arg);
2510                 return -EINVAL;
2511         }
2512
2513         return 0;
2514 }
2515 early_param("apic", apic_set_verbosity);
2516
2517 static int __init lapic_insert_resource(void)
2518 {
2519         if (!apic_phys)
2520                 return -1;
2521
2522         /* Put local APIC into the resource map. */
2523         lapic_resource.start = apic_phys;
2524         lapic_resource.end = lapic_resource.start + PAGE_SIZE - 1;
2525         insert_resource(&iomem_resource, &lapic_resource);
2526
2527         return 0;
2528 }
2529
2530 /*
2531  * need call insert after e820_reserve_resources()
2532  * that is using request_resource
2533  */
2534 late_initcall(lapic_insert_resource);
2535
2536 static int __init apic_set_disabled_cpu_apicid(char *arg)
2537 {
2538         if (!arg || !get_option(&arg, &disabled_cpu_apicid))
2539                 return -EINVAL;
2540
2541         return 0;
2542 }
2543 early_param("disable_cpu_apicid", apic_set_disabled_cpu_apicid);