]> git.saurik.com Git - apple/xnu.git/blobdiff - osfmk/i386/mp.c
xnu-1699.32.7.tar.gz
[apple/xnu.git] / osfmk / i386 / mp.c
index 23ce618604ebff3a6b19ab069d38d99d0270cae2..f4221f9640c3f09d136682933cbe0118f2fb51d2 100644 (file)
@@ -1,5 +1,4 @@
 /*
- * Copyright (c) 2000-2007 Apple Inc. All rights reserved.
  *
  * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
  * 
 
 #include <kern/kern_types.h>
 #include <kern/startup.h>
+#include <kern/timer_queue.h>
 #include <kern/processor.h>
 #include <kern/cpu_number.h>
 #include <kern/cpu_data.h>
 #include <kern/assert.h>
 #include <kern/machine.h>
 #include <kern/pms.h>
+#include <kern/misc_protos.h>
+#include <kern/etimer.h>
+#include <kern/kalloc.h>
+#include <kern/queue.h>
 
 #include <vm/vm_map.h>
 #include <vm/vm_kern.h>
 
 #include <profiling/profile-mk.h>
 
-#include <i386/mp.h>
-#include <i386/mp_events.h>
-#include <i386/mp_slave_boot.h>
-#include <i386/apic.h>
-#include <i386/ipl.h>
-#include <i386/fpu.h>
-#include <i386/cpuid.h>
 #include <i386/proc_reg.h>
-#include <i386/machine_cpu.h>
-#include <i386/misc_protos.h>
-#include <i386/mtrr.h>
-#include <i386/vmx/vmx_cpu.h>
-#include <i386/postcode.h>
-#include <i386/perfmon.h>
 #include <i386/cpu_threads.h>
 #include <i386/mp_desc.h>
+#include <i386/misc_protos.h>
 #include <i386/trap.h>
+#include <i386/postcode.h>
 #include <i386/machine_routines.h>
+#include <i386/mp.h>
+#include <i386/mp_events.h>
+#include <i386/lapic.h>
+#include <i386/cpuid.h>
+#include <i386/fpu.h>
+#include <i386/machine_cpu.h>
 #include <i386/pmCPU.h>
-#include <i386/hpet.h>
+#if CONFIG_MCA
 #include <i386/machine_check.h>
+#endif
+#include <i386/acpi.h>
 
 #include <chud/chud_xnu.h>
 #include <chud/chud_xnu_private.h>
 
 #include <sys/kdebug.h>
 #if MACH_KDB
-#include <i386/db_machdep.h>
+#include <machine/db_machdep.h>
 #include <ddb/db_aout.h>
 #include <ddb/db_access.h>
 #include <ddb/db_sym.h>
 #define PAUSE
 #endif /* MP_DEBUG */
 
-/* Initialize lapic_id so cpu_number() works on non SMP systems */
-unsigned long  lapic_id_initdata = 0;
-unsigned long  lapic_id = (unsigned long)&lapic_id_initdata;
-vm_offset_t    lapic_start;
-
-static i386_intr_func_t        lapic_timer_func;
-static i386_intr_func_t        lapic_pmi_func;
-static i386_intr_func_t        lapic_thermal_func;
+/* Debugging/test trace events: */
+#define        TRACE_MP_TLB_FLUSH              MACHDBG_CODE(DBG_MACH_MP, 0)
+#define        TRACE_MP_CPUS_CALL              MACHDBG_CODE(DBG_MACH_MP, 1)
+#define        TRACE_MP_CPUS_CALL_LOCAL        MACHDBG_CODE(DBG_MACH_MP, 2)
+#define        TRACE_MP_CPUS_CALL_ACTION       MACHDBG_CODE(DBG_MACH_MP, 3)
+#define        TRACE_MP_CPUS_CALL_NOBUF        MACHDBG_CODE(DBG_MACH_MP, 4)
 
-/* TRUE if local APIC was enabled by the OS not by the BIOS */
-static boolean_t lapic_os_enabled = FALSE;
-
-/* Base vector for local APIC interrupt sources */
-int lapic_interrupt_base = LAPIC_DEFAULT_INTERRUPT_BASE;
+#define ABS(v)         (((v) > 0)?(v):-(v))
 
 void           slave_boot_init(void);
+void           i386_cpu_IPI(int cpu);
 
 #if MACH_KDB
 static void    mp_kdb_wait(void);
@@ -120,106 +116,72 @@ volatile boolean_t       mp_kdb_trap = FALSE;
 volatile long  mp_kdb_ncpus = 0;
 #endif
 
-static void    mp_kdp_wait(boolean_t flush);
+static void    mp_kdp_wait(boolean_t flush, boolean_t isNMI);
 static void    mp_rendezvous_action(void);
 static void    mp_broadcast_action(void);
 
-static int             NMIInterruptHandler(x86_saved_state_t *regs);
 static boolean_t       cpu_signal_pending(int cpu, mp_event_t event);
+static int             NMIInterruptHandler(x86_saved_state_t *regs);
 
-boolean_t      smp_initialized = FALSE;
+boolean_t              smp_initialized = FALSE;
+uint32_t               TSC_sync_margin = 0xFFF;
 volatile boolean_t     force_immediate_debugger_NMI = FALSE;
 volatile boolean_t     pmap_tlb_flush_timeout = FALSE;
-
 decl_simple_lock_data(,mp_kdp_lock);
 
-decl_mutex_data(static, mp_cpu_boot_lock);
+decl_lck_mtx_data(static, mp_cpu_boot_lock);
+lck_mtx_ext_t  mp_cpu_boot_lock_ext;
 
 /* Variables needed for MP rendezvous. */
 decl_simple_lock_data(,mp_rv_lock);
-static void            (*mp_rv_setup_func)(void *arg);
-static void            (*mp_rv_action_func)(void *arg);
-static void            (*mp_rv_teardown_func)(void *arg);
-static void            *mp_rv_func_arg;
-static int             mp_rv_ncpus;
+static void    (*mp_rv_setup_func)(void *arg);
+static void    (*mp_rv_action_func)(void *arg);
+static void    (*mp_rv_teardown_func)(void *arg);
+static void    *mp_rv_func_arg;
+static volatile int    mp_rv_ncpus;
                        /* Cache-aligned barriers: */
 static volatile long   mp_rv_entry    __attribute__((aligned(64)));
 static volatile long   mp_rv_exit     __attribute__((aligned(64)));
 static volatile long   mp_rv_complete __attribute__((aligned(64)));
 
+volatile       uint64_t        debugger_entry_time;
+volatile       uint64_t        debugger_exit_time;
+#if MACH_KDP
+#include <kdp/kdp.h>
+extern int kdp_snapshot;
+static struct _kdp_xcpu_call_func {
+       kdp_x86_xcpu_func_t func;
+       void     *arg0, *arg1;
+       volatile long     ret;
+       volatile uint16_t cpu;
+} kdp_xcpu_call_func = {
+       .cpu  = KDP_XCPU_NONE
+};
+
+#endif
+
 /* Variables needed for MP broadcast. */
 static void        (*mp_bc_action_func)(void *arg);
 static void        *mp_bc_func_arg;
-static int     mp_bc_ncpus;
+static int             mp_bc_ncpus;
 static volatile long   mp_bc_count;
-decl_mutex_data(static, mp_bc_lock);
+decl_lck_mtx_data(static, mp_bc_lock);
+lck_mtx_ext_t  mp_bc_lock_ext;
+static volatile int    debugger_cpu = -1;
+volatile long NMIPI_acks = 0;
 
+static void    mp_cpus_call_init(void); 
+static void    mp_cpus_call_cpu_init(void); 
 static void    mp_cpus_call_action(void); 
+static void    mp_call_PM(void);
 
-int            lapic_to_cpu[MAX_CPUS];
-int            cpu_to_lapic[MAX_CPUS];
-
-static void
-lapic_cpu_map_init(void)
-{
-       int     i;
-
-       for (i = 0; i < MAX_CPUS; i++) {
-               lapic_to_cpu[i] = -1;
-               cpu_to_lapic[i] = -1;
-       }
-}
-
-void
-lapic_cpu_map(int apic_id, int cpu)
-{
-       cpu_to_lapic[cpu] = apic_id;
-       lapic_to_cpu[apic_id] = cpu;
-}
-
-/*
- * Retrieve the local apic ID a cpu.
- *
- * Returns the local apic ID for the given processor.
- * If the processor does not exist or apic not configured, returns -1.
- */
-
-uint32_t
-ml_get_apicid(uint32_t cpu)
-{
-       if(cpu >= (uint32_t)MAX_CPUS)
-               return 0xFFFFFFFF;      /* Return -1 if cpu too big */
-       
-       /* Return the apic ID (or -1 if not configured) */
-       return (uint32_t)cpu_to_lapic[cpu];
-
-}
+char           mp_slave_stack[PAGE_SIZE] __attribute__((aligned(PAGE_SIZE))); // Temp stack for slave init
 
-#ifdef MP_DEBUG
-static void
-lapic_cpu_map_dump(void)
-{
-       int     i;
-
-       for (i = 0; i < MAX_CPUS; i++) {
-               if (cpu_to_lapic[i] == -1)
-                       continue;
-               kprintf("cpu_to_lapic[%d]: %d\n",
-                       i, cpu_to_lapic[i]);
-       }
-       for (i = 0; i < MAX_CPUS; i++) {
-               if (lapic_to_cpu[i] == -1)
-                       continue;
-               kprintf("lapic_to_cpu[%d]: %d\n",
-                       i, lapic_to_cpu[i]);
-       }
-}
-#define LAPIC_CPU_MAP_DUMP()   lapic_cpu_map_dump()
-#define LAPIC_DUMP()           lapic_dump()
-#else
-#define LAPIC_CPU_MAP_DUMP()
-#define LAPIC_DUMP()
-#endif /* MP_DEBUG */
+/* PAL-related routines */
+boolean_t i386_smp_init(int nmi_vector, i386_intr_func_t nmi_handler, 
+               int ipi_vector, i386_intr_func_t ipi_handler);
+void i386_start_cpu(int lapic_id, int cpu_num);
+void i386_send_NMI(int cpu);
 
 #if GPROF
 /*
@@ -240,562 +202,260 @@ struct profile_vars *_profile_vars_cpus[MAX_CPUS] = { &_profile_vars };
 #define GPROF_INIT()
 #endif /* GPROF */
 
+static lck_grp_t       smp_lck_grp;
+static lck_grp_attr_t  smp_lck_grp_attr;
+
+#define NUM_CPU_WARM_CALLS     20
+struct timer_call      cpu_warm_call_arr[NUM_CPU_WARM_CALLS];
+queue_head_t           cpu_warm_call_list;
+decl_simple_lock_data(static, cpu_warm_lock);
+
+typedef struct cpu_warm_data {
+       timer_call_t    cwd_call;
+       uint64_t        cwd_deadline;
+       int             cwd_result;
+} *cpu_warm_data_t;
+
+static void            cpu_prewarm_init(void);
+static void            cpu_warm_timer_call_func(call_entry_param_t p0, call_entry_param_t p1);
+static void            _cpu_warm_setup(void *arg);
+static timer_call_t    grab_warm_timer_call(void);
+static void            free_warm_timer_call(timer_call_t call);
+
 void
 smp_init(void)
 {
-       int             result;
-       vm_map_entry_t  entry;
-       uint32_t        lo;
-       uint32_t        hi;
-       boolean_t       is_boot_processor;
-       boolean_t       is_lapic_enabled;
-       vm_offset_t     lapic_base;
-
        simple_lock_init(&mp_kdp_lock, 0);
        simple_lock_init(&mp_rv_lock, 0);
-       mutex_init(&mp_cpu_boot_lock, 0);
-       mutex_init(&mp_bc_lock, 0);
+       lck_grp_attr_setdefault(&smp_lck_grp_attr);
+       lck_grp_init(&smp_lck_grp, "i386_smp", &smp_lck_grp_attr);
+       lck_mtx_init_ext(&mp_cpu_boot_lock, &mp_cpu_boot_lock_ext, &smp_lck_grp, LCK_ATTR_NULL);
+       lck_mtx_init_ext(&mp_bc_lock, &mp_bc_lock_ext, &smp_lck_grp, LCK_ATTR_NULL);
        console_init();
 
-       /* Local APIC? */
-       if (!lapic_probe())
+       if(!i386_smp_init(LAPIC_NMI_INTERRUPT, NMIInterruptHandler, 
+                               LAPIC_VECTOR(INTERPROCESSOR), cpu_signal_handler))
                return;
 
-       /* Examine the local APIC state */
-       rdmsr(MSR_IA32_APIC_BASE, lo, hi);
-       is_boot_processor = (lo & MSR_IA32_APIC_BASE_BSP) != 0;
-       is_lapic_enabled  = (lo & MSR_IA32_APIC_BASE_ENABLE) != 0;
-       lapic_base = (lo &  MSR_IA32_APIC_BASE_BASE);
-       kprintf("MSR_IA32_APIC_BASE 0x%x %s %s\n", lapic_base,
-               is_lapic_enabled ? "enabled" : "disabled",
-               is_boot_processor ? "BSP" : "AP");
-       if (!is_boot_processor || !is_lapic_enabled)
-               panic("Unexpected local APIC state\n");
-
-       /* Establish a map to the local apic */
-       lapic_start = vm_map_min(kernel_map);
-       result = vm_map_find_space(kernel_map,
-                                  (vm_map_address_t *) &lapic_start,
-                                  round_page(LAPIC_SIZE), 0,
-                                  VM_MAKE_TAG(VM_MEMORY_IOKIT), &entry);
-       if (result != KERN_SUCCESS) {
-               panic("smp_init: vm_map_find_entry FAILED (err=%d)", result);
-       }
-       vm_map_unlock(kernel_map);
-/* Map in the local APIC non-cacheable, as recommended by Intel
- * in section 8.4.1 of the "System Programming Guide".
- */
-       pmap_enter(pmap_kernel(),
-                       lapic_start,
-                       (ppnum_t) i386_btop(lapic_base),
-                       VM_PROT_READ|VM_PROT_WRITE,
-                       VM_WIMG_IO,
-                       TRUE);
-       lapic_id = (unsigned long)(lapic_start + LAPIC_ID);
-
-       if ((LAPIC_REG(VERSION)&LAPIC_VERSION_MASK) != 0x14) {
-               printf("Local APIC version not 0x14 as expected\n");
-       }
-
-       /* Set up the lapic_id <-> cpu_number map and add this boot processor */
-       lapic_cpu_map_init();
-       lapic_cpu_map((LAPIC_REG(ID)>>LAPIC_ID_SHIFT)&LAPIC_ID_MASK, 0);
-       kprintf("Boot cpu local APIC id 0x%x\n", cpu_to_lapic[0]);
-
-       lapic_init();
-
        cpu_thread_init();
 
        GPROF_INIT();
        DBGLOG_CPU_INIT(master_cpu);
 
-       slave_boot_init();
+       mp_cpus_call_init();
+       mp_cpus_call_cpu_init();
 
+       if (PE_parse_boot_argn("TSC_sync_margin",
+                               &TSC_sync_margin, sizeof(TSC_sync_margin)))
+               kprintf("TSC sync Margin 0x%x\n", TSC_sync_margin);
        smp_initialized = TRUE;
 
-       return;
-}
-
-
-static int
-lapic_esr_read(void)
-{
-       /* write-read register */
-       LAPIC_REG(ERROR_STATUS) = 0;
-       return LAPIC_REG(ERROR_STATUS);
-}
+       cpu_prewarm_init();
 
-static void 
-lapic_esr_clear(void)
-{
-       LAPIC_REG(ERROR_STATUS) = 0;
-       LAPIC_REG(ERROR_STATUS) = 0;
+       return;
 }
 
-static const char *DM[8] = {
-       "Fixed",
-       "Lowest Priority",
-       "Invalid",
-       "Invalid",
-       "NMI",
-       "Reset",
-       "Invalid",
-       "ExtINT"};
+typedef struct {
+       int                     target_cpu;
+       int                     target_lapic;
+       int                     starter_cpu;
+} processor_start_info_t;
+static processor_start_info_t  start_info        __attribute__((aligned(64)));
 
-void
-lapic_dump(void)
-{
-       int     i;
-
-#define BOOL(a) ((a)?' ':'!')
-
-       kprintf("LAPIC %d at 0x%x version 0x%x\n", 
-               (LAPIC_REG(ID)>>LAPIC_ID_SHIFT)&LAPIC_ID_MASK,
-               lapic_start,
-               LAPIC_REG(VERSION)&LAPIC_VERSION_MASK);
-       kprintf("Priorities: Task 0x%x  Arbitration 0x%x  Processor 0x%x\n",
-               LAPIC_REG(TPR)&LAPIC_TPR_MASK,
-               LAPIC_REG(APR)&LAPIC_APR_MASK,
-               LAPIC_REG(PPR)&LAPIC_PPR_MASK);
-       kprintf("Destination Format 0x%x Logical Destination 0x%x\n",
-               LAPIC_REG(DFR)>>LAPIC_DFR_SHIFT,
-               LAPIC_REG(LDR)>>LAPIC_LDR_SHIFT);
-       kprintf("%cEnabled %cFocusChecking SV 0x%x\n",
-               BOOL(LAPIC_REG(SVR)&LAPIC_SVR_ENABLE),
-               BOOL(!(LAPIC_REG(SVR)&LAPIC_SVR_FOCUS_OFF)),
-               LAPIC_REG(SVR) & LAPIC_SVR_MASK);
-       kprintf("LVT_TIMER:   Vector 0x%02x %s %cmasked %s\n",
-               LAPIC_REG(LVT_TIMER)&LAPIC_LVT_VECTOR_MASK,
-               (LAPIC_REG(LVT_TIMER)&LAPIC_LVT_DS_PENDING)?"SendPending":"Idle",
-               BOOL(LAPIC_REG(LVT_TIMER)&LAPIC_LVT_MASKED),
-               (LAPIC_REG(LVT_TIMER)&LAPIC_LVT_PERIODIC)?"Periodic":"OneShot");
-       kprintf("  Initial Count: 0x%08x \n", LAPIC_REG(TIMER_INITIAL_COUNT));
-       kprintf("  Current Count: 0x%08x \n", LAPIC_REG(TIMER_CURRENT_COUNT));
-       kprintf("  Divide Config: 0x%08x \n", LAPIC_REG(TIMER_DIVIDE_CONFIG));
-       kprintf("LVT_PERFCNT: Vector 0x%02x [%s] %s %cmasked\n",
-               LAPIC_REG(LVT_PERFCNT)&LAPIC_LVT_VECTOR_MASK,
-               DM[(LAPIC_REG(LVT_PERFCNT)>>LAPIC_LVT_DM_SHIFT)&LAPIC_LVT_DM_MASK],
-               (LAPIC_REG(LVT_PERFCNT)&LAPIC_LVT_DS_PENDING)?"SendPending":"Idle",
-               BOOL(LAPIC_REG(LVT_PERFCNT)&LAPIC_LVT_MASKED));
-       kprintf("LVT_THERMAL: Vector 0x%02x [%s] %s %cmasked\n",
-               LAPIC_REG(LVT_THERMAL)&LAPIC_LVT_VECTOR_MASK,
-               DM[(LAPIC_REG(LVT_THERMAL)>>LAPIC_LVT_DM_SHIFT)&LAPIC_LVT_DM_MASK],
-               (LAPIC_REG(LVT_THERMAL)&LAPIC_LVT_DS_PENDING)?"SendPending":"Idle",
-               BOOL(LAPIC_REG(LVT_THERMAL)&LAPIC_LVT_MASKED));
-       kprintf("LVT_LINT0:   Vector 0x%02x [%s][%s][%s] %s %cmasked\n",
-               LAPIC_REG(LVT_LINT0)&LAPIC_LVT_VECTOR_MASK,
-               DM[(LAPIC_REG(LVT_LINT0)>>LAPIC_LVT_DM_SHIFT)&LAPIC_LVT_DM_MASK],
-               (LAPIC_REG(LVT_LINT0)&LAPIC_LVT_TM_LEVEL)?"Level":"Edge ",
-               (LAPIC_REG(LVT_LINT0)&LAPIC_LVT_IP_PLRITY_LOW)?"Low ":"High",
-               (LAPIC_REG(LVT_LINT0)&LAPIC_LVT_DS_PENDING)?"SendPending":"Idle",
-               BOOL(LAPIC_REG(LVT_LINT0)&LAPIC_LVT_MASKED));
-       kprintf("LVT_LINT1:   Vector 0x%02x [%s][%s][%s] %s %cmasked\n",
-               LAPIC_REG(LVT_LINT1)&LAPIC_LVT_VECTOR_MASK,
-               DM[(LAPIC_REG(LVT_LINT1)>>LAPIC_LVT_DM_SHIFT)&LAPIC_LVT_DM_MASK],
-               (LAPIC_REG(LVT_LINT1)&LAPIC_LVT_TM_LEVEL)?"Level":"Edge ",
-               (LAPIC_REG(LVT_LINT1)&LAPIC_LVT_IP_PLRITY_LOW)?"Low ":"High",
-               (LAPIC_REG(LVT_LINT1)&LAPIC_LVT_DS_PENDING)?"SendPending":"Idle",
-               BOOL(LAPIC_REG(LVT_LINT1)&LAPIC_LVT_MASKED));
-       kprintf("LVT_ERROR:   Vector 0x%02x %s %cmasked\n",
-               LAPIC_REG(LVT_ERROR)&LAPIC_LVT_VECTOR_MASK,
-               (LAPIC_REG(LVT_ERROR)&LAPIC_LVT_DS_PENDING)?"SendPending":"Idle",
-               BOOL(LAPIC_REG(LVT_ERROR)&LAPIC_LVT_MASKED));
-       kprintf("ESR: %08x \n", lapic_esr_read());
-       kprintf("       ");
-       for(i=0xf; i>=0; i--)
-               kprintf("%x%x%x%x",i,i,i,i);
-       kprintf("\n");
-       kprintf("TMR: 0x");
-       for(i=7; i>=0; i--)
-               kprintf("%08x",LAPIC_REG_OFFSET(TMR_BASE, i*0x10));
-       kprintf("\n");
-       kprintf("IRR: 0x");
-       for(i=7; i>=0; i--)
-               kprintf("%08x",LAPIC_REG_OFFSET(IRR_BASE, i*0x10));
-       kprintf("\n");
-       kprintf("ISR: 0x");
-       for(i=7; i >= 0; i--)
-               kprintf("%08x",LAPIC_REG_OFFSET(ISR_BASE, i*0x10));
-       kprintf("\n");
-}
+/* 
+ * Cache-alignment is to avoid cross-cpu false-sharing interference.
+ */
+static volatile long           tsc_entry_barrier __attribute__((aligned(64)));
+static volatile long           tsc_exit_barrier  __attribute__((aligned(64)));
+static volatile uint64_t       tsc_target        __attribute__((aligned(64)));
 
-#if MACH_KDB
 /*
- *     Displays apic junk
- *
- *     da
+ * Poll a CPU to see when it has marked itself as running.
  */
-void 
-db_apic(__unused db_expr_t addr,
-       __unused int have_addr,
-       __unused db_expr_t count,
-       __unused char *modif)
+static void
+mp_wait_for_cpu_up(int slot_num, unsigned int iters, unsigned int usecdelay)
 {
-
-       lapic_dump();
-
-       return;
+       while (iters-- > 0) {
+               if (cpu_datap(slot_num)->cpu_running)
+                       break;
+               delay(usecdelay);
+       }
 }
 
-#endif
-
-boolean_t
-lapic_probe(void)
+/*
+ * Quickly bring a CPU back online which has been halted.
+ */
+kern_return_t
+intel_startCPU_fast(int slot_num)
 {
-       uint32_t        lo;
-       uint32_t        hi;
-
-       if (cpuid_features() & CPUID_FEATURE_APIC)
-               return TRUE;
-
-       if (cpuid_family() == 6 || cpuid_family() == 15) {
-               /*
-                * Mobile Pentiums:
-                * There may be a local APIC which wasn't enabled by BIOS.
-                * So we try to enable it explicitly.
-                */
-               rdmsr(MSR_IA32_APIC_BASE, lo, hi);
-               lo &= ~MSR_IA32_APIC_BASE_BASE;
-               lo |= MSR_IA32_APIC_BASE_ENABLE | LAPIC_START;
-               lo |= MSR_IA32_APIC_BASE_ENABLE;
-               wrmsr(MSR_IA32_APIC_BASE, lo, hi);
+       kern_return_t   rc;
 
+       /*
+        * Try to perform a fast restart
+        */
+       rc = pmCPUExitHalt(slot_num);
+       if (rc != KERN_SUCCESS)
                /*
-                * Re-initialize cpu features info and re-check.
+                * The CPU was not eligible for a fast restart.
                 */
-               cpuid_set_info();
-               if (cpuid_features() & CPUID_FEATURE_APIC) {
-                       printf("Local APIC discovered and enabled\n");
-                       lapic_os_enabled = TRUE;
-                       lapic_interrupt_base = LAPIC_REDUCED_INTERRUPT_BASE;
-                       return TRUE;
-               }
-       }
-
-       return FALSE;
-}
-
-void
-lapic_shutdown(void)
-{
-       uint32_t lo;
-       uint32_t hi;
-       uint32_t value;
-
-       /* Shutdown if local APIC was enabled by OS */
-       if (lapic_os_enabled == FALSE)
-               return;
+               return(rc);
 
+       /*
+        * Wait until the CPU is back online.
+        */
        mp_disable_preemption();
+    
+       /*
+        * We use short pauses (1us) for low latency.  30,000 iterations is
+        * longer than a full restart would require so it should be more
+        * than long enough.
+        */
 
-       /* ExtINT: masked */
-       if (get_cpu_number() == master_cpu) {
-               value = LAPIC_REG(LVT_LINT0);
-               value |= LAPIC_LVT_MASKED;
-               LAPIC_REG(LVT_LINT0) = value;
-       }
-
-       /* Timer: masked */
-       LAPIC_REG(LVT_TIMER) |= LAPIC_LVT_MASKED;
-
-       /* Perfmon: masked */
-       LAPIC_REG(LVT_PERFCNT) |= LAPIC_LVT_MASKED;
-
-       /* Error: masked */
-       LAPIC_REG(LVT_ERROR) |= LAPIC_LVT_MASKED;
-
-       /* APIC software disabled */
-       LAPIC_REG(SVR) &= ~LAPIC_SVR_ENABLE;
-
-       /* Bypass the APIC completely and update cpu features */
-       rdmsr(MSR_IA32_APIC_BASE, lo, hi);
-       lo &= ~MSR_IA32_APIC_BASE_ENABLE;
-       wrmsr(MSR_IA32_APIC_BASE, lo, hi);
-       cpuid_set_info();
-
+       mp_wait_for_cpu_up(slot_num, 30000, 1);
        mp_enable_preemption();
-}
-
-void
-lapic_init(void)
-{
-       int     value;
-
-       /* Set flat delivery model, logical processor id */
-       LAPIC_REG(DFR) = LAPIC_DFR_FLAT;
-       LAPIC_REG(LDR) = (get_cpu_number()) << LAPIC_LDR_SHIFT;
-
-       /* Accept all */
-       LAPIC_REG(TPR) =  0;
-
-       LAPIC_REG(SVR) = LAPIC_VECTOR(SPURIOUS) | LAPIC_SVR_ENABLE;
-
-       /* ExtINT */
-       if (get_cpu_number() == master_cpu) {
-               value = LAPIC_REG(LVT_LINT0);
-               value &= ~LAPIC_LVT_MASKED;
-               value |= LAPIC_LVT_DM_EXTINT;
-               LAPIC_REG(LVT_LINT0) = value;
-       }
-
-       /* Timer: unmasked, one-shot */
-       LAPIC_REG(LVT_TIMER) = LAPIC_VECTOR(TIMER);
-
-       /* Perfmon: unmasked */
-       LAPIC_REG(LVT_PERFCNT) = LAPIC_VECTOR(PERFCNT);
-
-       /* Thermal: unmasked */
-       LAPIC_REG(LVT_THERMAL) = LAPIC_VECTOR(THERMAL);
-
-       lapic_esr_clear();
-
-       LAPIC_REG(LVT_ERROR) = LAPIC_VECTOR(ERROR);
-}
-
-void
-lapic_set_timer_func(i386_intr_func_t func)
-{
-       lapic_timer_func = func;
-}
-
-void
-lapic_set_timer(
-       boolean_t               interrupt,
-       lapic_timer_mode_t      mode,
-       lapic_timer_divide_t    divisor,
-       lapic_timer_count_t     initial_count)
-{
-       boolean_t       state;
-       uint32_t        timer_vector;
-
-       state = ml_set_interrupts_enabled(FALSE);
-       timer_vector = LAPIC_REG(LVT_TIMER);
-       timer_vector &= ~(LAPIC_LVT_MASKED|LAPIC_LVT_PERIODIC);;
-       timer_vector |= interrupt ? 0 : LAPIC_LVT_MASKED;
-       timer_vector |= (mode == periodic) ? LAPIC_LVT_PERIODIC : 0;
-       LAPIC_REG(LVT_TIMER) = timer_vector;
-       LAPIC_REG(TIMER_DIVIDE_CONFIG) = divisor;
-       LAPIC_REG(TIMER_INITIAL_COUNT) = initial_count;
-       ml_set_interrupts_enabled(state);
-}
 
-void
-lapic_get_timer(
-       lapic_timer_mode_t      *mode,
-       lapic_timer_divide_t    *divisor,
-       lapic_timer_count_t     *initial_count,
-       lapic_timer_count_t     *current_count)
-{
-       boolean_t       state;
-
-       state = ml_set_interrupts_enabled(FALSE);
-       if (mode)
-               *mode = (LAPIC_REG(LVT_TIMER) & LAPIC_LVT_PERIODIC) ?
-                               periodic : one_shot;
-       if (divisor)
-               *divisor = LAPIC_REG(TIMER_DIVIDE_CONFIG) & LAPIC_TIMER_DIVIDE_MASK;
-       if (initial_count)
-               *initial_count = LAPIC_REG(TIMER_INITIAL_COUNT);
-       if (current_count)
-               *current_count = LAPIC_REG(TIMER_CURRENT_COUNT);
-       ml_set_interrupts_enabled(state);
-} 
-
-void
-lapic_set_pmi_func(i386_intr_func_t func)
-{
-       lapic_pmi_func = func;
-}
-
-void
-lapic_set_thermal_func(i386_intr_func_t func)
-{
-        lapic_thermal_func = func;
-}
-
-static inline void
-_lapic_end_of_interrupt(void)
-{
-       LAPIC_REG(EOI) = 0;
-}
-
-void
-lapic_end_of_interrupt(void)
-{
-       _lapic_end_of_interrupt();
+       /*
+        * Check to make sure that the CPU is really running.  If not,
+        * go through the slow path.
+        */
+       if (cpu_datap(slot_num)->cpu_running)
+               return(KERN_SUCCESS);
+       else
+               return(KERN_FAILURE);
 }
 
-int
-lapic_interrupt(int interrupt, x86_saved_state_t *state)
+static void
+started_cpu(void)
 {
-       int     retval = 0;
-
-       /* Did we just field an interruption for the HPET comparator? */
-       if(x86_core()->HpetVec == ((uint32_t)interrupt - 0x40)) {
-               /* Yes, go handle it... */
-               retval = HPETInterrupt();
-               /* Was it really handled? */
-               if(retval) {
-                       /* If so, EOI the 'rupt */
-                       _lapic_end_of_interrupt();
-                       /*
-                        * and then leave,
-                        * indicating that this has been handled
-                        */
-                       return 1;
-               }
-       }
-
-       interrupt -= lapic_interrupt_base;
-       if (interrupt < 0) {
-               if (interrupt == (LAPIC_NMI_INTERRUPT - lapic_interrupt_base)) {
-                       retval = NMIInterruptHandler(state);
-                       _lapic_end_of_interrupt();
-                       return retval;
-               }
-               else
-                       return 0;
-       }
+       /* Here on the started cpu with cpu_running set TRUE */
 
-       switch(interrupt) {
-       case LAPIC_PERFCNT_INTERRUPT:
-               if (lapic_pmi_func != NULL)
-                       (*lapic_pmi_func)(NULL);
-               /* Clear interrupt masked */
-               LAPIC_REG(LVT_PERFCNT) = LAPIC_VECTOR(PERFCNT);
-               _lapic_end_of_interrupt();
-               retval = 1;
-               break;
-       case LAPIC_TIMER_INTERRUPT:
-               _lapic_end_of_interrupt();
-               if (lapic_timer_func != NULL)
-                       (*lapic_timer_func)(state);
-               retval = 1;
-               break;
-       case LAPIC_THERMAL_INTERRUPT:
-               if (lapic_thermal_func != NULL)
-                       (*lapic_thermal_func)(NULL);
-               _lapic_end_of_interrupt();
-               retval = 1;
-               break;
-       case LAPIC_ERROR_INTERRUPT:
-               lapic_dump();
-               panic("Local APIC error\n");
-               _lapic_end_of_interrupt();
-               retval = 1;
-               break;
-       case LAPIC_SPURIOUS_INTERRUPT:
-               kprintf("SPIV\n");
-               /* No EOI required here */
-               retval = 1;
-               break;
-       case LAPIC_INTERPROCESSOR_INTERRUPT:
-               _lapic_end_of_interrupt();
-               cpu_signal_handler(state);
-               retval = 1;
-               break;
+       if (TSC_sync_margin &&
+           start_info.target_cpu == cpu_number()) {
+               /*
+                * I've just started-up, synchronize again with the starter cpu
+                * and then snap my TSC.
+                */
+               tsc_target   = 0;
+               atomic_decl(&tsc_entry_barrier, 1);
+               while (tsc_entry_barrier != 0)
+                       ;       /* spin for starter and target at barrier */
+               tsc_target = rdtsc64();
+               atomic_decl(&tsc_exit_barrier, 1);
        }
-
-       return retval;
 }
 
-void
-lapic_smm_restore(void)
+static void
+start_cpu(void *arg)
 {
-       boolean_t state;
+       int                     i = 1000;
+       processor_start_info_t  *psip = (processor_start_info_t *) arg;
 
-       if (lapic_os_enabled == FALSE)
+       /* Ignore this if the current processor is not the starter */
+       if (cpu_number() != psip->starter_cpu)
                return;
 
-       state = ml_set_interrupts_enabled(FALSE);
-
-       if (LAPIC_ISR_IS_SET(LAPIC_REDUCED_INTERRUPT_BASE, TIMER)) {
-               /*
-                * Bogus SMI handler enables interrupts but does not know about
-                * local APIC interrupt sources. When APIC timer counts down to
-                * zero while in SMM, local APIC will end up waiting for an EOI
-                * but no interrupt was delivered to the OS.
-                */
-               _lapic_end_of_interrupt();
+       i386_start_cpu(psip->target_lapic, psip->target_cpu);
 
+#ifdef POSTCODE_DELAY
+       /* Wait much longer if postcodes are displayed for a delay period. */
+       i *= 10000;
+#endif
+       mp_wait_for_cpu_up(psip->target_cpu, i*100, 100);
+       if (TSC_sync_margin &&
+           cpu_datap(psip->target_cpu)->cpu_running) {
                /*
-                * timer is one-shot, trigger another quick countdown to trigger
-                * another timer interrupt.
+                * Compare the TSC from the started processor with ours.
+                * Report and log/panic if it diverges by more than
+                * TSC_sync_margin (TSC_SYNC_MARGIN) ticks. This margin
+                * can be overriden by boot-arg (with 0 meaning no checking).
                 */
-               if (LAPIC_REG(TIMER_CURRENT_COUNT) == 0) {
-                       LAPIC_REG(TIMER_INITIAL_COUNT) = 1;
+               uint64_t        tsc_starter;
+               int64_t         tsc_delta;
+               atomic_decl(&tsc_entry_barrier, 1);
+               while (tsc_entry_barrier != 0)
+                       ;       /* spin for both processors at barrier */
+               tsc_starter = rdtsc64();
+               atomic_decl(&tsc_exit_barrier, 1);
+               while (tsc_exit_barrier != 0)
+                       ;       /* spin for target to store its TSC */
+               tsc_delta = tsc_target - tsc_starter;
+               kprintf("TSC sync for cpu %d: 0x%016llx delta 0x%llx (%lld)\n",
+                       psip->target_cpu, tsc_target, tsc_delta, tsc_delta);
+               if (ABS(tsc_delta) > (int64_t) TSC_sync_margin) { 
+#if DEBUG
+                       panic(
+#else
+                       printf(
+#endif
+                               "Unsynchronized  TSC for cpu %d: "
+                                       "0x%016llx, delta 0x%llx\n",
+                               psip->target_cpu, tsc_target, tsc_delta);
                }
-
-               kprintf("lapic_smm_restore\n");
        }
-
-       ml_set_interrupts_enabled(state);
 }
 
+extern char    prot_mode_gdt[];
+extern char    slave_boot_base[];
+extern char real_mode_bootstrap_base[];
+extern char real_mode_bootstrap_end[];
+extern char    slave_boot_end[];
+
 kern_return_t
 intel_startCPU(
        int     slot_num)
 {
-
-       int     i = 1000;
-       int     lapic = cpu_to_lapic[slot_num];
+       int             lapic = cpu_to_lapic[slot_num];
+       boolean_t       istate;
 
        assert(lapic != -1);
 
        DBGLOG_CPU_INIT(slot_num);
 
        DBG("intel_startCPU(%d) lapic_id=%d\n", slot_num, lapic);
-       DBG("IdlePTD(%p): 0x%x\n", &IdlePTD, (int) IdlePTD);
+       DBG("IdlePTD(%p): 0x%x\n", &IdlePTD, (int) (uintptr_t)IdlePTD);
 
        /*
         * Initialize (or re-initialize) the descriptor tables for this cpu.
         * Propagate processor mode to slave.
         */
        if (cpu_mode_is64bit())
-               cpu_desc_init64(cpu_datap(slot_num), FALSE);
+               cpu_desc_init64(cpu_datap(slot_num));
        else
-               cpu_desc_init(cpu_datap(slot_num), FALSE);
+               cpu_desc_init(cpu_datap(slot_num));
 
-       /* Serialize use of the slave boot stack. */
-       mutex_lock(&mp_cpu_boot_lock);
+       /* Serialize use of the slave boot stack, etc. */
+       lck_mtx_lock(&mp_cpu_boot_lock);
 
-       mp_disable_preemption();
+       istate = ml_set_interrupts_enabled(FALSE);
        if (slot_num == get_cpu_number()) {
-               mp_enable_preemption();
-               mutex_unlock(&mp_cpu_boot_lock);
+               ml_set_interrupts_enabled(istate);
+               lck_mtx_unlock(&mp_cpu_boot_lock);
                return KERN_SUCCESS;
        }
 
-       LAPIC_REG(ICRD) = lapic << LAPIC_ICRD_DEST_SHIFT;
-       LAPIC_REG(ICR) = LAPIC_ICR_DM_INIT;
-       delay(10000);
+       start_info.starter_cpu  = cpu_number();
+       start_info.target_cpu   = slot_num;
+       start_info.target_lapic = lapic;
+       tsc_entry_barrier = 2;
+       tsc_exit_barrier = 2;
 
-       LAPIC_REG(ICRD) = lapic << LAPIC_ICRD_DEST_SHIFT;
-       LAPIC_REG(ICR) = LAPIC_ICR_DM_STARTUP|(MP_BOOT>>12);
-       delay(200);
-
-       LAPIC_REG(ICRD) = lapic << LAPIC_ICRD_DEST_SHIFT;
-       LAPIC_REG(ICR) = LAPIC_ICR_DM_STARTUP|(MP_BOOT>>12);
-       delay(200);
+       /*
+        * Perform the processor startup sequence with all running
+        * processors rendezvous'ed. This is required during periods when
+        * the cache-disable bit is set for MTRR/PAT initialization.
+        */
+       mp_rendezvous_no_intrs(start_cpu, (void *) &start_info);
 
-#ifdef POSTCODE_DELAY
-       /* Wait much longer if postcodes are displayed for a delay period. */
-       i *= 10000;
-#endif
-       while(i-- > 0) {
-               if (cpu_datap(slot_num)->cpu_running)
-                       break;
-               delay(10000);
-       }
+       start_info.target_cpu = 0;
 
-       mp_enable_preemption();
-       mutex_unlock(&mp_cpu_boot_lock);
+       ml_set_interrupts_enabled(istate);
+       lck_mtx_unlock(&mp_cpu_boot_lock);
 
        if (!cpu_datap(slot_num)->cpu_running) {
                kprintf("Failed to start CPU %02d\n", slot_num);
                printf("Failed to start CPU %02d, rebooting...\n", slot_num);
                delay(1000000);
-               cpu_shutdown();
+               halt_cpu();
                return KERN_SUCCESS;
        } else {
                kprintf("Started cpu %d (lapic id %08x)\n", slot_num, lapic);
@@ -803,49 +463,6 @@ intel_startCPU(
        }
 }
 
-extern char    slave_boot_base[];
-extern char    slave_boot_end[];
-extern void    slave_pstart(void);
-
-void
-slave_boot_init(void)
-{
-       DBG("V(slave_boot_base)=%p P(slave_boot_base)=%p MP_BOOT=%p sz=0x%x\n",
-               slave_boot_base,
-               kvtophys((vm_offset_t) slave_boot_base),
-               MP_BOOT,
-               slave_boot_end-slave_boot_base);
-
-       /*
-        * Copy the boot entry code to the real-mode vector area MP_BOOT.
-        * This is in page 1 which has been reserved for this purpose by
-        * machine_startup() from the boot processor.
-        * The slave boot code is responsible for switching to protected
-        * mode and then jumping to the common startup, _start().
-        */
-       bcopy_phys(kvtophys((vm_offset_t) slave_boot_base),
-                  (addr64_t) MP_BOOT,
-                  slave_boot_end-slave_boot_base);
-
-       /*
-        * Zero a stack area above the boot code.
-        */
-       DBG("bzero_phys 0x%x sz 0x%x\n",MP_BOOTSTACK+MP_BOOT-0x400, 0x400);
-       bzero_phys((addr64_t)MP_BOOTSTACK+MP_BOOT-0x400, 0x400);
-
-       /*
-        * Set the location at the base of the stack to point to the
-        * common startup entry.
-        */
-       DBG("writing 0x%x at phys 0x%x\n",
-               kvtophys((vm_offset_t) &slave_pstart), MP_MACH_START+MP_BOOT);
-       ml_phys_write_word(MP_MACH_START+MP_BOOT,
-                          (unsigned int)kvtophys((vm_offset_t) &slave_pstart));
-       
-       /* Flush caches */
-       __asm__("wbinvd");
-}
-
 #if    MP_DEBUG
 cpu_signal_event_log_t *cpu_signal[MAX_CPUS];
 cpu_signal_event_log_t *cpu_handle[MAX_CPUS];
@@ -854,7 +471,7 @@ MP_EVENT_NAME_DECL();
 
 #endif /* MP_DEBUG */
 
-void
+int
 cpu_signal_handler(x86_saved_state_t *regs)
 {
        int             my_cpu;
@@ -863,10 +480,16 @@ cpu_signal_handler(x86_saved_state_t *regs)
        int             i=100;
 #endif /* MACH_KDB && MACH_ASSERT */
 
-       mp_disable_preemption();
+       SCHED_STATS_IPI(current_processor());
 
        my_cpu = cpu_number();
-       my_word = &current_cpu_datap()->cpu_signals;
+       my_word = &cpu_data_ptr[my_cpu]->cpu_signals;
+       /* Store the initial set of signals for diagnostics. New
+        * signals could arrive while these are being processed
+        * so it's no more than a hint.
+        */
+
+       cpu_data_ptr[my_cpu]->cpu_prior_signals = *my_word;
 
        do {
 #if    MACH_KDB && MACH_ASSERT
@@ -881,10 +504,13 @@ cpu_signal_handler(x86_saved_state_t *regs)
  * current thread's stack (if any) is synchronized with the
  * context at the moment of the interrupt, to facilitate
  * access through the debugger.
- * XXX 64-bit state?
  */
-                       sync_iss_to_iks(saved_state32(regs));
-                       mp_kdp_wait(TRUE);
+                       sync_iss_to_iks(regs);
+                       if (pmsafe_debug && !kdp_snapshot)
+                               pmSafeMode(&current_cpu_datap()->lcpu, PM_SAFE_FL_SAFE);
+                       mp_kdp_wait(TRUE, FALSE);
+                       if (pmsafe_debug && !kdp_snapshot)
+                               pmSafeMode(&current_cpu_datap()->lcpu, PM_SAFE_FL_NORMAL);
                } else
 #endif /* MACH_KDP */
                if (i_bit(MP_TLB_FLUSH, my_word)) {
@@ -919,85 +545,62 @@ cpu_signal_handler(x86_saved_state_t *regs)
                        DBGLOG(cpu_handle,my_cpu,MP_CALL);
                        i_bit_clear(MP_CALL, my_word);
                        mp_cpus_call_action();
+               } else if (i_bit(MP_CALL_PM, my_word)) {
+                       DBGLOG(cpu_handle,my_cpu,MP_CALL_PM);
+                       i_bit_clear(MP_CALL_PM, my_word);
+                       mp_call_PM();
                }
        } while (*my_word);
 
-       mp_enable_preemption();
-
+       return 0;
 }
 
-/* We want this to show up in backtraces, hence marked noinline.
- */
-static int __attribute__((noinline))
+static int
 NMIInterruptHandler(x86_saved_state_t *regs)
 {
        void    *stackptr;
-       
-       sync_iss_to_iks_unconditionally(regs);
-       __asm__ volatile("movl %%ebp, %0" : "=m" (stackptr));
 
-       if (pmap_tlb_flush_timeout == TRUE && current_cpu_datap()->cpu_tlb_invalid) {
-               panic_i386_backtrace(stackptr, 10, "Panic: Unresponsive processor\n", TRUE, regs);
-               panic_io_port_read();
-               mca_check_save();
+       if (panic_active() && !panicDebugging) {
                if (pmsafe_debug)
                        pmSafeMode(&current_cpu_datap()->lcpu, PM_SAFE_FL_SAFE);
-               for(;;) {
+               for(;;)
                        cpu_pause();
-               }
        }
-       mp_kdp_wait(FALSE);
-       return 1;
-}
 
-#ifdef MP_DEBUG
-extern int     max_lock_loops;
-int            trappedalready = 0;     /* (BRINGUP */
-#endif /* MP_DEBUG */
-
-static void
-i386_cpu_IPI(int cpu)
-{
-       boolean_t       state;
-       
-#ifdef MP_DEBUG
-       if(cpu_datap(cpu)->cpu_signals & 6) {   /* (BRINGUP) */
-               kprintf("i386_cpu_IPI: sending enter debugger signal (%08X) to cpu %d\n", cpu_datap(cpu)->cpu_signals, cpu);
-       }
-#endif /* MP_DEBUG */
-
-#if MACH_KDB
-#ifdef MP_DEBUG
-       if(!trappedalready && (cpu_datap(cpu)->cpu_signals & 6)) {      /* (BRINGUP) */
-               if(kdb_cpu != cpu_number()) {
-                       trappedalready = 1;
-                       panic("i386_cpu_IPI: sending enter debugger signal (%08X) to cpu %d and I do not own debugger, owner = %08X\n", 
-                               cpu_datap(cpu)->cpu_signals, cpu, kdb_cpu);
-               }
-       }
-#endif /* MP_DEBUG */
+       atomic_incl(&NMIPI_acks, 1);
+       sync_iss_to_iks_unconditionally(regs);
+#if defined (__i386__)
+       __asm__ volatile("movl %%ebp, %0" : "=m" (stackptr));
+#elif defined (__x86_64__)
+       __asm__ volatile("movq %%rbp, %0" : "=m" (stackptr));
 #endif
 
-       /* Wait for previous interrupt to be delivered... */
-#ifdef MP_DEBUG
-       int     pending_busy_count = 0;
-       while (LAPIC_REG(ICR) & LAPIC_ICR_DS_PENDING) {
-               if (++pending_busy_count > max_lock_loops)
-                       panic("i386_cpu_IPI() deadlock\n");
-#else
-       while (LAPIC_REG(ICR) & LAPIC_ICR_DS_PENDING) {
-#endif /* MP_DEBUG */
-               cpu_pause();
+       if (cpu_number() == debugger_cpu)
+                       goto NMExit;
+
+       if (spinlock_timed_out) {
+               char pstr[192];
+               snprintf(&pstr[0], sizeof(pstr), "Panic(CPU %d): NMIPI for spinlock acquisition timeout, spinlock: %p, spinlock owner: %p, current_thread: %p, spinlock_owner_cpu: 0x%x\n", cpu_number(), spinlock_timed_out, (void *) spinlock_timed_out->interlock.lock_data, current_thread(), spinlock_owner_cpu);
+               panic_i386_backtrace(stackptr, 64, &pstr[0], TRUE, regs);
+       } else if (pmap_tlb_flush_timeout == TRUE) {
+               char pstr[128];
+               snprintf(&pstr[0], sizeof(pstr), "Panic(CPU %d): Unresponsive processor (this CPU did not acknowledge interrupts) TLB state:0x%x\n", cpu_number(), current_cpu_datap()->cpu_tlb_invalid);
+               panic_i386_backtrace(stackptr, 48, &pstr[0], TRUE, regs);
        }
 
-       state = ml_set_interrupts_enabled(FALSE);
-       LAPIC_REG(ICRD) =
-               cpu_to_lapic[cpu] << LAPIC_ICRD_DEST_SHIFT;
-       LAPIC_REG(ICR)  =
-               LAPIC_VECTOR(INTERPROCESSOR) | LAPIC_ICR_DM_FIXED;
-       (void) ml_set_interrupts_enabled(state);
+#if MACH_KDP
+       if (pmsafe_debug && !kdp_snapshot)
+               pmSafeMode(&current_cpu_datap()->lcpu, PM_SAFE_FL_SAFE);
+       current_cpu_datap()->cpu_NMI_acknowledged = TRUE;
+       mp_kdp_wait(FALSE, pmap_tlb_flush_timeout || spinlock_timed_out || panic_active());
+       if (pmsafe_debug && !kdp_snapshot)
+               pmSafeMode(&current_cpu_datap()->lcpu, PM_SAFE_FL_NORMAL);
+#endif
+NMExit:        
+       return 1;
 }
 
+
 /*
  * cpu_interrupt is really just to be used by the scheduler to
  * get a CPU's attention it may not always issue an IPI.  If an
@@ -1006,10 +609,15 @@ i386_cpu_IPI(int cpu)
 void
 cpu_interrupt(int cpu)
 {
+       boolean_t did_IPI = FALSE;
+
        if (smp_initialized
            && pmCPUExitIdle(cpu_datap(cpu))) {
                i386_cpu_IPI(cpu);
+               did_IPI = TRUE;
        }
+
+       KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_SCHED, MACH_REMOTE_AST), cpu, did_IPI, 0, 0, 0);
 }
 
 /*
@@ -1018,22 +626,41 @@ cpu_interrupt(int cpu)
 void
 cpu_NMI_interrupt(int cpu)
 {
-       boolean_t       state;
-
        if (smp_initialized) {
-               state = ml_set_interrupts_enabled(FALSE);
-/* Program the interrupt command register */
-               LAPIC_REG(ICRD) =
-                       cpu_to_lapic[cpu] << LAPIC_ICRD_DEST_SHIFT;
-/* The vector is ignored in this case--the target CPU will enter on the
- * NMI vector.
- */
-               LAPIC_REG(ICR)  =
-                       LAPIC_VECTOR(INTERPROCESSOR) | LAPIC_ICR_DM_NMI;
-               (void) ml_set_interrupts_enabled(state);
+               i386_send_NMI(cpu);
        }
 }
 
+static void    (* volatile mp_PM_func)(void) = NULL;
+
+static void
+mp_call_PM(void)
+{
+       assert(!ml_get_interrupts_enabled());
+
+       if (mp_PM_func != NULL)
+               mp_PM_func();
+}
+
+void
+cpu_PM_interrupt(int cpu)
+{
+       assert(!ml_get_interrupts_enabled());
+
+       if (mp_PM_func != NULL) {
+               if (cpu == cpu_number())
+                       mp_PM_func();
+               else
+                       i386_signal_cpu(cpu, MP_CALL_PM, ASYNC);
+       }
+}
+
+void
+PM_interrupt_register(void (*fn)(void))
+{
+       mp_PM_func = fn;
+}
+
 void
 i386_signal_cpu(int cpu, mp_event_t event, mp_sync_t mode)
 {
@@ -1045,7 +672,7 @@ i386_signal_cpu(int cpu, mp_event_t event, mp_sync_t mode)
                return;
 
        if (event == MP_TLB_FLUSH)
-               KERNEL_DEBUG(0xef800020 | DBG_FUNC_START, cpu, 0, 0, 0, 0);
+               KERNEL_DEBUG(TRACE_MP_TLB_FLUSH | DBG_FUNC_START, cpu, 0, 0, 0, 0);
 
        DBGLOG(cpu_signal, cpu, event);
        
@@ -1064,7 +691,7 @@ i386_signal_cpu(int cpu, mp_event_t event, mp_sync_t mode)
                }
        }
        if (event == MP_TLB_FLUSH)
-               KERNEL_DEBUG(0xef800020 | DBG_FUNC_END, cpu, 0, 0, 0, 0);
+               KERNEL_DEBUG(TRACE_MP_TLB_FLUSH | DBG_FUNC_END, cpu, 0, 0, 0, 0);
 }
 
 /*
@@ -1077,7 +704,7 @@ i386_signal_cpus(mp_event_t event, mp_sync_t mode)
        unsigned int    cpu;
        unsigned int    my_cpu = cpu_number();
 
-       assert(hw_lock_held(&x86_topo_lock));
+       assert(hw_lock_held((hw_lock_t)&x86_topo_lock));
 
        for (cpu = 0; cpu < real_ncpus; cpu++) {
                if (cpu == my_cpu || !cpu_datap(cpu)->cpu_running)
@@ -1096,7 +723,7 @@ i386_active_cpus(void)
        unsigned int    cpu;
        unsigned int    ncpus = 0;
 
-       assert(hw_lock_held(&x86_topo_lock));
+       assert(hw_lock_held((hw_lock_t)&x86_topo_lock));
 
        for (cpu = 0; cpu < real_ncpus; cpu++) {
                if (cpu_datap(cpu)->cpu_running)
@@ -1138,9 +765,11 @@ mp_rendezvous_action(void)
                        handle_pending_TLB_flushes();
                cpu_pause();
        }
+
        /* action function */
        if (mp_rv_action_func != NULL)
                mp_rv_action_func(mp_rv_func_arg);
+
        /* spin on exit rendezvous */
        atomic_incl(&mp_rv_exit, 1);
        while (mp_rv_exit < mp_rv_ncpus) {
@@ -1257,38 +886,186 @@ mp_rendezvous_no_intrs(
                      arg);     
 }
 
-void
-handle_pending_TLB_flushes(void)
+
+typedef struct {
+       queue_chain_t   link;                   /* queue linkage */
+       void            (*func)(void *,void *); /* routine to call */
+       void            *arg0;                  /* routine's 1st arg */
+       void            *arg1;                  /* routine's 2nd arg */
+       volatile long   *countp;                /* completion counter */
+} mp_call_t;
+       
+#define MP_CPUS_CALL_BUFS_PER_CPU      MAX_CPUS
+static queue_head_t    mp_cpus_call_freelist;
+static queue_head_t    mp_cpus_call_queue[MAX_CPUS];
+/*
+ * The free list and the per-cpu call queues are protected by the following
+ * lock which is taken wil interrupts disabled.
+ */
+decl_simple_lock_data(,mp_cpus_call_lock);
+
+static inline boolean_t
+mp_call_lock(void)
+{
+       boolean_t       intrs_enabled;
+
+       intrs_enabled = ml_set_interrupts_enabled(FALSE);
+       simple_lock(&mp_cpus_call_lock);
+
+       return intrs_enabled;
+}
+
+static inline boolean_t
+mp_call_is_locked(void)
+{
+       return !ml_get_interrupts_enabled() &&
+               hw_lock_held((hw_lock_t)&mp_cpus_call_lock);
+}
+
+static inline void
+mp_call_unlock(boolean_t intrs_enabled)
 {
-       volatile int    *my_word = &current_cpu_datap()->cpu_signals;
+       simple_unlock(&mp_cpus_call_lock);
+       ml_set_interrupts_enabled(intrs_enabled);
+}
+
+static inline mp_call_t *
+mp_call_alloc(void)
+{
+       mp_call_t       *callp;
+
+       assert(mp_call_is_locked());
+       if (queue_empty(&mp_cpus_call_freelist))
+               return NULL;
+       queue_remove_first(&mp_cpus_call_freelist, callp, typeof(callp), link);
+       return callp;
+}
+
+static inline void
+mp_call_free(mp_call_t *callp)
+{
+       assert(mp_call_is_locked());
+       queue_enter_first(&mp_cpus_call_freelist, callp, typeof(callp), link);
+}
+
+static inline mp_call_t *
+mp_call_dequeue(queue_t call_queue)
+{
+       mp_call_t       *callp;
+
+       assert(mp_call_is_locked());
+       if (queue_empty(call_queue))
+               return NULL;
+       queue_remove_first(call_queue, callp, typeof(callp), link);
+       return callp;
+}
+
+/* Called on the boot processor to initialize global structures */
+static void
+mp_cpus_call_init(void)
+{
+       DBG("mp_cpus_call_init()\n");
+       simple_lock_init(&mp_cpus_call_lock, 0);
+       queue_init(&mp_cpus_call_freelist);
+}
 
-       if (i_bit(MP_TLB_FLUSH, my_word)) {
-               DBGLOG(cpu_handle, cpu_number(), MP_TLB_FLUSH);
-               i_bit_clear(MP_TLB_FLUSH, my_word);
-               pmap_update_interrupt();
+/*
+ * Called by each processor to add call buffers to the free list
+ * and to initialize the per-cpu call queue.
+ * Also called but ignored on slave processors on re-start/wake.
+ */
+static void
+mp_cpus_call_cpu_init(void)
+{
+       boolean_t       intrs_enabled;
+       int             i;
+       mp_call_t       *callp;
+
+       if (mp_cpus_call_queue[cpu_number()].next != NULL)
+               return; /* restart/wake case: called already */
+
+       queue_init(&mp_cpus_call_queue[cpu_number()]);
+       for (i = 0; i < MP_CPUS_CALL_BUFS_PER_CPU; i++) {
+               callp = (mp_call_t *) kalloc(sizeof(mp_call_t));
+               intrs_enabled = mp_call_lock();
+               mp_call_free(callp);
+               mp_call_unlock(intrs_enabled);
        }
+
+       DBG("mp_cpus_call_init() done on cpu %d\n", cpu_number());
 }
 
 /*
  * This is called from cpu_signal_handler() to process an MP_CALL signal.
+ * And also from i386_deactivate_cpu() when a cpu is being taken offline.
  */
 static void
 mp_cpus_call_action(void)
 {
-       if (mp_rv_action_func != NULL)
-               mp_rv_action_func(mp_rv_func_arg);
-       atomic_incl(&mp_rv_complete, 1);
+       queue_t         cpu_head;
+       boolean_t       intrs_enabled;
+       mp_call_t       *callp;
+       mp_call_t       call;
+
+       assert(!ml_get_interrupts_enabled());
+       cpu_head = &mp_cpus_call_queue[cpu_number()];
+       intrs_enabled = mp_call_lock();
+       while ((callp = mp_call_dequeue(cpu_head)) != NULL) {
+               /* Copy call request to the stack to free buffer */
+               call = *callp;
+               mp_call_free(callp);
+               if (call.func != NULL) {
+                       mp_call_unlock(intrs_enabled);
+                       KERNEL_DEBUG_CONSTANT(
+                               TRACE_MP_CPUS_CALL_ACTION,
+                               call.func, call.arg0, call.arg1, call.countp, 0);
+                       call.func(call.arg0, call.arg1);
+                       (void) mp_call_lock();
+               }
+               if (call.countp != NULL)
+                       atomic_incl(call.countp, 1);
+       }
+       mp_call_unlock(intrs_enabled);
+}
+
+static boolean_t
+mp_call_queue(
+       int             cpu, 
+        void           (*action_func)(void *, void *),
+        void           *arg0,
+        void           *arg1,
+       volatile long   *countp)
+{
+       queue_t         cpu_head = &mp_cpus_call_queue[cpu];
+       mp_call_t       *callp;
+
+       assert(mp_call_is_locked());
+       callp = mp_call_alloc();
+       if (callp == NULL)
+               return FALSE;
+
+       callp->func = action_func;
+       callp->arg0 = arg0;
+       callp->arg1 = arg1;
+       callp->countp = countp;
+
+       queue_enter(cpu_head, callp, typeof(callp), link);
+
+       return TRUE;
 }
 
 /*
  * mp_cpus_call() runs a given function on cpus specified in a given cpu mask.
- * If the mode is SYNC, the function is called serially on the target cpus
- * in logical cpu order. If the mode is ASYNC, the function is called in
- * parallel over the specified cpus.
+ * Possible modes are:
+ *  SYNC:   function is called serially on target cpus in logical cpu order
+ *         waiting for each call to be acknowledged before proceeding
+ *  ASYNC:  function call is queued to the specified cpus
+ *         waiting for all calls to complete in parallel before returning
+ *  NOSYNC: function calls are queued
+ *         but we return before confirmation of calls completing. 
  * The action function may be NULL.
  * The cpu mask may include the local cpu. Offline cpus are ignored.
- * Return does not occur until the function has completed on all cpus.
- * The return value is the number of cpus on which the function was called.
+ * The return value is the number of cpus on which the call was made or queued.
  */
 cpu_t
 mp_cpus_call(
@@ -1296,32 +1073,77 @@ mp_cpus_call(
        mp_sync_t       mode,
         void           (*action_func)(void *),
         void           *arg)
+{
+       return mp_cpus_call1(
+                       cpus,
+                       mode,
+                       (void (*)(void *,void *))action_func,
+                       arg,
+                       NULL,
+                       NULL,
+                       NULL);
+}
+
+static void
+mp_cpus_call_wait(boolean_t intrs_enabled,
+                 long mp_cpus_signals,
+                 volatile long *mp_cpus_calls)
+{
+       queue_t         cpu_head;
+
+       cpu_head = &mp_cpus_call_queue[cpu_number()];
+
+       while (*mp_cpus_calls < mp_cpus_signals) {
+               if (!intrs_enabled) {
+                       if (!queue_empty(cpu_head))
+                               mp_cpus_call_action();
+
+                       handle_pending_TLB_flushes();
+               }
+               cpu_pause();
+       }
+}
+
+cpu_t
+mp_cpus_call1(
+       cpumask_t       cpus,
+       mp_sync_t       mode,
+        void           (*action_func)(void *, void *),
+        void           *arg0,
+        void           *arg1,
+       cpumask_t       *cpus_calledp,
+       cpumask_t       *cpus_notcalledp)
 {
        cpu_t           cpu;
-       boolean_t       intrs_enabled = ml_get_interrupts_enabled();
+       boolean_t       intrs_enabled = FALSE;
        boolean_t       call_self = FALSE;
+       cpumask_t       cpus_called = 0;
+       cpumask_t       cpus_notcalled = 0;
+       long            mp_cpus_signals = 0;
+       volatile long   mp_cpus_calls = 0;
+
+       KERNEL_DEBUG_CONSTANT(
+               TRACE_MP_CPUS_CALL | DBG_FUNC_START,
+               cpus, mode, action_func, arg0, arg1);
 
        if (!smp_initialized) {
                if ((cpus & CPUMASK_SELF) == 0)
-                       return 0;
+                       goto out;
                if (action_func != NULL) {
-                       (void) ml_set_interrupts_enabled(FALSE);
-                       action_func(arg);
+                       intrs_enabled = ml_set_interrupts_enabled(FALSE);
+                       action_func(arg0, arg1);
                        ml_set_interrupts_enabled(intrs_enabled);
                }
-               return 1;
+               call_self = TRUE;
+               goto out;
        }
-               
-       /* obtain rendezvous lock */
-       simple_lock(&mp_rv_lock);
-
-       /* Use the rendezvous data structures for this call */
-       mp_rv_action_func = action_func;
-       mp_rv_func_arg = arg;
-       mp_rv_ncpus = 0;
-       mp_rv_complete = 0;
 
-       simple_lock(&x86_topo_lock);
+       /*
+        * Queue the call for each non-local requested cpu.
+        * The topo lock is not taken. Instead we sniff the cpu_running state
+        * and then re-check it after taking the call lock. A cpu being taken
+        * offline runs the action function after clearing the cpu_running.
+        */ 
        for (cpu = 0; cpu < (cpu_t) real_ncpus; cpu++) {
                if (((cpu_to_cpumask(cpu) & cpus) == 0) ||
                    !cpu_datap(cpu)->cpu_running)
@@ -1332,61 +1154,92 @@ mp_cpus_call(
                         * we defer our call until we have signalled all others.
                         */
                        call_self = TRUE;
+                       cpus_called |= cpu_to_cpumask(cpu);
                        if (mode == SYNC && action_func != NULL) {
-                               (void) ml_set_interrupts_enabled(FALSE);
-                               action_func(arg);
-                               ml_set_interrupts_enabled(intrs_enabled);
+                               KERNEL_DEBUG_CONSTANT(
+                                       TRACE_MP_CPUS_CALL_LOCAL,
+                                       action_func, arg0, arg1, 0, 0);
+                               action_func(arg0, arg1);
                        }
                } else {
                        /*
-                        * Bump count of other cpus called and signal this cpu.
-                        * Note: we signal asynchronously regardless of mode
-                        * because we wait on mp_rv_complete either here
-                        * (if mode == SYNC) or later (if mode == ASYNC).
-                        * While spinning, poll for TLB flushes if interrupts
-                        * are disabled.
+                        * Here to queue a call to cpu and IPI.
+                        * Spinning for request buffer unless NOSYNC.
                         */
-                       mp_rv_ncpus++;
-                       i386_signal_cpu(cpu, MP_CALL, ASYNC);
-                       if (mode == SYNC) {
-                               simple_unlock(&x86_topo_lock);
-                               while (mp_rv_complete < mp_rv_ncpus) {
-                                       if (!intrs_enabled)
+               queue_call:
+                       intrs_enabled = mp_call_lock();
+                       if (!cpu_datap(cpu)->cpu_running) {
+                               mp_call_unlock(intrs_enabled);
+                               continue;
+                       }
+                       if (mode == NOSYNC) {
+                               if (!mp_call_queue(cpu, action_func, arg0, arg1,
+                                                  NULL)) {
+                                       cpus_notcalled |= cpu_to_cpumask(cpu);
+                                       mp_call_unlock(intrs_enabled);
+                                       KERNEL_DEBUG_CONSTANT(
+                                               TRACE_MP_CPUS_CALL_NOBUF,
+                                               cpu, 0, 0, 0, 0);
+                                       continue;
+                               }
+                       } else {
+                               if (!mp_call_queue(cpu, action_func, arg0, arg1,
+                                                     &mp_cpus_calls)) {
+                                       mp_call_unlock(intrs_enabled);
+                                       KERNEL_DEBUG_CONSTANT(
+                                               TRACE_MP_CPUS_CALL_NOBUF,
+                                               cpu, 0, 0, 0, 0);
+                                       if (!intrs_enabled) {
+                                               mp_cpus_call_action();
                                                handle_pending_TLB_flushes();
+                                       }
                                        cpu_pause();
+                                       goto queue_call;
                                }
-                               simple_lock(&x86_topo_lock);
+                       }
+                       mp_cpus_signals++;
+                       cpus_called |= cpu_to_cpumask(cpu);
+                       i386_signal_cpu(cpu, MP_CALL, ASYNC);
+                       mp_call_unlock(intrs_enabled);
+                       if (mode == SYNC) {
+                               mp_cpus_call_wait(intrs_enabled, mp_cpus_signals, &mp_cpus_calls);
                        }
                }
        }
-       simple_unlock(&x86_topo_lock);
 
-       /*
-        * If calls are being made asynchronously,
-        * make the local call now if needed, and then
-        * wait for all other cpus to finish their calls.
-        */
-       if (mode == ASYNC) {
-               if (call_self && action_func != NULL) {
-                       (void) ml_set_interrupts_enabled(FALSE);
-                       action_func(arg);
+       /* Call locally if mode not SYNC */
+       if (mode != SYNC && call_self ) {
+               KERNEL_DEBUG_CONSTANT(
+                       TRACE_MP_CPUS_CALL_LOCAL,
+                       action_func, arg0, arg1, 0, 0);
+               if (action_func != NULL) {
+                       ml_set_interrupts_enabled(FALSE);
+                       action_func(arg0, arg1);
                        ml_set_interrupts_enabled(intrs_enabled);
                }
-               while (mp_rv_complete < mp_rv_ncpus) {
-                       if (!intrs_enabled)
-                               handle_pending_TLB_flushes();
-                       cpu_pause();
-               }
        }
-       
-       /* Determine the number of cpus called */
-       cpu = mp_rv_ncpus + (call_self ? 1 : 0);
 
-       simple_unlock(&mp_rv_lock);
+       /* For ASYNC, now wait for all signaled cpus to complete their calls */
+       if (mode == ASYNC) {
+               mp_cpus_call_wait(intrs_enabled, mp_cpus_signals, &mp_cpus_calls);
+       }
+
+out:
+       cpu = (cpu_t) mp_cpus_signals + (call_self ? 1 : 0);
+
+       if (cpus_calledp)
+               *cpus_calledp = cpus_called;
+       if (cpus_notcalledp)
+               *cpus_notcalledp = cpus_notcalled;
+
+       KERNEL_DEBUG_CONSTANT(
+               TRACE_MP_CPUS_CALL | DBG_FUNC_END,
+               cpu, cpus_called, cpus_notcalled, 0, 0);
 
        return cpu;
 }
 
+
 static void
 mp_broadcast_action(void)
 {
@@ -1395,8 +1248,8 @@ mp_broadcast_action(void)
        mp_bc_action_func(mp_bc_func_arg);
 
    /* if we're the last one through, wake up the instigator */
-   if (atomic_decl_and_test((volatile long *)&mp_bc_count, 1))
-       thread_wakeup(((event_t)(unsigned int *) &mp_bc_count));
+   if (atomic_decl_and_test(&mp_bc_count, 1))
+       thread_wakeup(((event_t)(uintptr_t) &mp_bc_count));
 }
 
 /*
@@ -1416,13 +1269,13 @@ mp_broadcast(
    }
        
    /* obtain broadcast lock */
-   mutex_lock(&mp_bc_lock);
+   lck_mtx_lock(&mp_bc_lock);
 
    /* set static function pointers */
    mp_bc_action_func = action_func;
    mp_bc_func_arg = arg;
 
-   assert_wait(&mp_bc_count, THREAD_UNINT);
+   assert_wait((event_t)(uintptr_t)&mp_bc_count, THREAD_UNINT);
 
    /*
     * signal other processors, which will call mp_broadcast_action()
@@ -1443,7 +1296,7 @@ mp_broadcast(
        clear_wait(current_thread(), THREAD_AWAKENED);
        
    /* release lock */
-   mutex_unlock(&mp_bc_lock);
+   lck_mtx_unlock(&mp_bc_lock);
 }
 
 void
@@ -1460,9 +1313,13 @@ i386_activate_cpu(void)
 
        simple_lock(&x86_topo_lock);
        cdp->cpu_running = TRUE;
+       started_cpu();
        simple_unlock(&x86_topo_lock);
+       flush_tlb_raw();
 }
 
+extern void etimer_timer_expire(void   *arg);
+
 void
 i386_deactivate_cpu(void)
 {
@@ -1474,6 +1331,10 @@ i386_deactivate_cpu(void)
        cdp->cpu_running = FALSE;
        simple_unlock(&x86_topo_lock);
 
+       timer_queue_shutdown(&cdp->rtclock_timer.queue);
+       cdp->rtclock_timer.deadline = EndOfAllTime;
+       mp_cpus_call(cpu_to_cpumask(master_cpu), ASYNC, etimer_timer_expire, NULL);
+
        /*
         * In case a rendezvous/braodcast/call was initiated to this cpu
         * before we cleared cpu_running, we must perform any actions due.
@@ -1491,7 +1352,7 @@ int       pmsafe_debug    = 1;
 
 #if    MACH_KDP
 volatile boolean_t     mp_kdp_trap = FALSE;
-volatile unsigned long         mp_kdp_ncpus;
+volatile unsigned long mp_kdp_ncpus;
 boolean_t              mp_kdp_state;
 
 
@@ -1499,8 +1360,8 @@ void
 mp_kdp_enter(void)
 {
        unsigned int    cpu;
-       unsigned int    ncpus;
-       unsigned int    my_cpu = cpu_number();
+       unsigned int    ncpus = 0;
+       unsigned int    my_cpu;
        uint64_t        tsc_timeout;
 
        DBG("mp_kdp_enter()\n");
@@ -1511,19 +1372,33 @@ mp_kdp_enter(void)
         * stopping others.
         */
        mp_kdp_state = ml_set_interrupts_enabled(FALSE);
+       my_cpu = cpu_number();
+
+       if (my_cpu == (unsigned) debugger_cpu) {
+               kprintf("\n\nRECURSIVE DEBUGGER ENTRY DETECTED\n\n");
+               kdp_reset();
+               return;
+       }
+
+       cpu_datap(my_cpu)->debugger_entry_time = mach_absolute_time();
        simple_lock(&mp_kdp_lock);
 
-       if (pmsafe_debug)
+       if (pmsafe_debug && !kdp_snapshot)
            pmSafeMode(&current_cpu_datap()->lcpu, PM_SAFE_FL_SAFE);
 
        while (mp_kdp_trap) {
                simple_unlock(&mp_kdp_lock);
                DBG("mp_kdp_enter() race lost\n");
-               mp_kdp_wait(TRUE);
+#if MACH_KDP
+               mp_kdp_wait(TRUE, FALSE);
+#endif
                simple_lock(&mp_kdp_lock);
        }
+       debugger_cpu = my_cpu;
+       ncpus = 1;
        mp_kdp_ncpus = 1;       /* self */
        mp_kdp_trap = TRUE;
+       debugger_entry_time = cpu_datap(my_cpu)->debugger_entry_time;
        simple_unlock(&mp_kdp_lock);
 
        /*
@@ -1531,7 +1406,7 @@ mp_kdp_enter(void)
         */
        DBG("mp_kdp_enter() signaling other processors\n");
        if (force_immediate_debugger_NMI == FALSE) {
-               for (ncpus = 1, cpu = 0; cpu < real_ncpus; cpu++) {
+               for (cpu = 0; cpu < real_ncpus; cpu++) {
                        if (cpu == my_cpu || !cpu_datap(cpu)->cpu_running)
                                continue;
                        ncpus++;
@@ -1579,8 +1454,8 @@ mp_kdp_enter(void)
                        cpu_NMI_interrupt(cpu);
                }
 
-       DBG("mp_kdp_enter() %u processors done %s\n",
-           mp_kdp_ncpus, (mp_kdp_ncpus == ncpus) ? "OK" : "timed out");
+       DBG("mp_kdp_enter() %lu processors done %s\n",
+           (int)mp_kdp_ncpus, (mp_kdp_ncpus == ncpus) ? "OK" : "timed out");
        
        postcode(MP_KDP_ENTER);
 }
@@ -1595,23 +1470,53 @@ cpu_signal_pending(int cpu, mp_event_t event)
                retval = TRUE;
        return retval;
 }
+
+long kdp_x86_xcpu_invoke(const uint16_t lcpu, kdp_x86_xcpu_func_t func,
+                        void *arg0, void *arg1)
+{
+       if (lcpu > (real_ncpus - 1))
+               return -1;
+
+        if (func == NULL)
+               return -1;
+
+       kdp_xcpu_call_func.func = func;
+        kdp_xcpu_call_func.ret  = -1;
+       kdp_xcpu_call_func.arg0 = arg0;
+       kdp_xcpu_call_func.arg1 = arg1;
+       kdp_xcpu_call_func.cpu  = lcpu;
+       DBG("Invoking function %p on CPU %d\n", func, (int32_t)lcpu);
+       while (kdp_xcpu_call_func.cpu != KDP_XCPU_NONE)
+               cpu_pause();
+        return kdp_xcpu_call_func.ret;
+}
+
+static void
+kdp_x86_xcpu_poll(void)
+{
+       if ((uint16_t)cpu_number() == kdp_xcpu_call_func.cpu) {
+            kdp_xcpu_call_func.ret = 
+                   kdp_xcpu_call_func.func(kdp_xcpu_call_func.arg0,
+                                           kdp_xcpu_call_func.arg1,
+                                           cpu_number());
+               kdp_xcpu_call_func.cpu = KDP_XCPU_NONE;
+       }
+}
 
 static void
-mp_kdp_wait(boolean_t flush)
+mp_kdp_wait(boolean_t flush, boolean_t isNMI)
 {
        DBG("mp_kdp_wait()\n");
        /* If an I/O port has been specified as a debugging aid, issue a read */
        panic_io_port_read();
 
+#if CONFIG_MCA
        /* If we've trapped due to a machine-check, save MCA registers */
        mca_check_save();
-
-       if (pmsafe_debug)
-           pmSafeMode(&current_cpu_datap()->lcpu, PM_SAFE_FL_SAFE);
+#endif
 
        atomic_incl((volatile long *)&mp_kdp_ncpus, 1);
-       while (mp_kdp_trap) {
+       while (mp_kdp_trap || (isNMI == TRUE)) {
                /*
                 * A TLB shootdown request may be pending--this would result
                 * in the requesting processor waiting in PMAP_UPDATE_TLBS()
@@ -1620,12 +1525,11 @@ mp_kdp_wait(boolean_t flush)
                 */
                if (flush)
                        handle_pending_TLB_flushes();
+
+               kdp_x86_xcpu_poll();
                cpu_pause();
        }
 
-       if (pmsafe_debug)
-           pmSafeMode(&current_cpu_datap()->lcpu, PM_SAFE_FL_NORMAL);
-
        atomic_decl((volatile long *)&mp_kdp_ncpus, 1);
        DBG("mp_kdp_wait() done\n");
 }
@@ -1634,7 +1538,11 @@ void
 mp_kdp_exit(void)
 {
        DBG("mp_kdp_exit()\n");
+       debugger_cpu = -1;
        atomic_decl((volatile long *)&mp_kdp_ncpus, 1);
+
+       debugger_exit_time = mach_absolute_time();
+
        mp_kdp_trap = FALSE;
        __asm__ volatile("mfence");
 
@@ -1651,15 +1559,24 @@ mp_kdp_exit(void)
                cpu_pause();
        }
 
-       if (pmsafe_debug)
+       if (pmsafe_debug && !kdp_snapshot)
            pmSafeMode(&current_cpu_datap()->lcpu, PM_SAFE_FL_NORMAL);
 
+       debugger_exit_time = mach_absolute_time();
+
        DBG("mp_kdp_exit() done\n");
        (void) ml_set_interrupts_enabled(mp_kdp_state);
        postcode(0);
 }
 #endif /* MACH_KDP */
 
+boolean_t
+mp_recent_debugger_activity() {
+       uint64_t abstime = mach_absolute_time();
+       return (((abstime - debugger_entry_time) < LastDebuggerEntryAllowance) ||
+           ((abstime - debugger_exit_time) < LastDebuggerEntryAllowance));
+}
+
 /*ARGSUSED*/
 void
 init_ast_check(
@@ -1671,10 +1588,11 @@ void
 cause_ast_check(
        processor_t     processor)
 {
-       int     cpu = PROCESSOR_DATA(processor, slot_num);
+       int     cpu = processor->cpu_id;
 
        if (cpu != cpu_number()) {
                i386_signal_cpu(cpu, MP_AST, ASYNC);
+               KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_SCHED, MACH_REMOTE_AST), cpu, 1, 0, 0, 0);
        }
 }
 
@@ -1713,7 +1631,7 @@ remote_kdb(void)
 
                cpu_pause();
        }
-       DBG("mp_kdp_enter() %d processors done %s\n",
+       DBG("mp_kdp_enter() %lu processors done %s\n",
                mp_kdb_ncpus, (mp_kdb_ncpus == kdb_ncpus) ? "OK" : "timed out");
 }
 
@@ -1776,65 +1694,25 @@ mp_kdb_exit(void)
 
 #endif /* MACH_KDB */
 
-/*
- * i386_init_slave() is called from pstart.
- * We're in the cpu's interrupt stack with interrupts disabled.
- * At this point we are in legacy mode. We need to switch on IA32e
- * if the mode is set to 64-bits.
- */
 void
-i386_init_slave(void)
-{
-       postcode(I386_INIT_SLAVE);
-
-       /* Ensure that caching and write-through are enabled */
-       set_cr0(get_cr0() & ~(CR0_NW|CR0_CD));
-
-       DBG("i386_init_slave() CPU%d: phys (%d) active.\n",
-               get_cpu_number(), get_cpu_phys_number());
-
-       assert(!ml_get_interrupts_enabled());
-
-       cpu_mode_init(current_cpu_datap());
-
-       mca_cpu_init();
-
-       lapic_init();
-       LAPIC_DUMP();
-       LAPIC_CPU_MAP_DUMP();
-
-       init_fpu();
-
-       mtrr_update_cpu();
-
-       /* resume VT operation */
-       vmx_resume();
-
-       pat_init();
-
-       cpu_thread_init();      /* not strictly necessary */
-
-       cpu_init();     /* Sets cpu_running which starter cpu waits for */ 
-
-       slave_main();
-
-       panic("i386_init_slave() returned from slave_main()");
-}
-
-void
-slave_machine_init(void)
+slave_machine_init(void *param)
 {
        /*
         * Here in process context, but with interrupts disabled.
         */
        DBG("slave_machine_init() CPU%d\n", get_cpu_number());
 
-       clock_init();
-
-       cpu_machine_init();             /* Interrupts enabled hereafter */
+       if (param == FULL_SLAVE_INIT) {
+               /*
+                * Cold start
+                */
+               clock_init();
+               cpu_machine_init();     /* Interrupts enabled hereafter */
+               mp_cpus_call_cpu_init();
+       }
 }
 
-#undef cpu_number()
+#undef cpu_number
 int cpu_number(void)
 {
        return get_cpu_number();
@@ -1888,3 +1766,117 @@ db_trap_hist(void)
 #endif /* TRAP_DEBUG */
 #endif /* MACH_KDB */
 
+static void
+cpu_prewarm_init()
+{
+       int i;
+
+       simple_lock_init(&cpu_warm_lock, 0);
+       queue_init(&cpu_warm_call_list);
+       for (i = 0; i < NUM_CPU_WARM_CALLS; i++) {
+               enqueue_head(&cpu_warm_call_list, (queue_entry_t)&cpu_warm_call_arr[i]);
+       }
+}
+
+static timer_call_t
+grab_warm_timer_call()
+{
+       spl_t x;
+       timer_call_t call = NULL;
+
+       x = splsched();
+       simple_lock(&cpu_warm_lock);
+       if (!queue_empty(&cpu_warm_call_list)) {
+               call = (timer_call_t) dequeue_head(&cpu_warm_call_list);
+       }
+       simple_unlock(&cpu_warm_lock);
+       splx(x);
+
+       return call;
+}
+
+static void
+free_warm_timer_call(timer_call_t call)
+{
+       spl_t x;
+
+       x = splsched();
+       simple_lock(&cpu_warm_lock);
+       enqueue_head(&cpu_warm_call_list, (queue_entry_t)call);
+       simple_unlock(&cpu_warm_lock);
+       splx(x);
+}
+
+/*
+ * Runs in timer call context (interrupts disabled).
+ */
+static void
+cpu_warm_timer_call_func(
+               call_entry_param_t p0,
+               __unused call_entry_param_t p1)
+{
+       free_warm_timer_call((timer_call_t)p0);
+       return;
+}
+
+/*
+ * Runs with interrupts disabled on the CPU we wish to warm (i.e. CPU 0).
+ */
+static void
+_cpu_warm_setup(
+               void *arg)
+{
+       cpu_warm_data_t cwdp = (cpu_warm_data_t)arg;
+
+       timer_call_enter(cwdp->cwd_call, cwdp->cwd_deadline, TIMER_CALL_CRITICAL | TIMER_CALL_LOCAL);
+       cwdp->cwd_result = 0;
+
+       return;
+}
+
+/*
+ * Not safe to call with interrupts disabled.
+ */
+kern_return_t
+ml_interrupt_prewarm(
+       uint64_t        deadline)
+{
+       struct cpu_warm_data cwd;
+       timer_call_t call;
+       cpu_t ct;
+
+       if (ml_get_interrupts_enabled() == FALSE) {
+               panic("%s: Interrupts disabled?\n", __FUNCTION__);
+       }
+
+       /* 
+        * If the platform doesn't need our help, say that we succeeded. 
+        */
+       if (!ml_get_interrupt_prewake_applicable()) {
+               return KERN_SUCCESS;
+       }
+
+       /*
+        * Grab a timer call to use.
+        */
+       call = grab_warm_timer_call();
+       if (call == NULL) {
+               return KERN_RESOURCE_SHORTAGE;
+       }
+
+       timer_call_setup(call, cpu_warm_timer_call_func, call);
+       cwd.cwd_call = call;
+       cwd.cwd_deadline = deadline;
+       cwd.cwd_result = 0;
+
+       /*
+        * For now, non-local interrupts happen on the master processor.
+        */
+       ct = mp_cpus_call(cpu_to_cpumask(master_cpu), SYNC, _cpu_warm_setup, &cwd);
+       if (ct == 0) {
+               free_warm_timer_call(call);
+               return KERN_FAILURE;
+       } else {
+               return cwd.cwd_result;
+       }
+}