]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/amd64/amd64/mp_machdep.c
Merge sendmail 8.16.1 to HEAD: See contrib/sendmail/RELEASE_NOTES for details
[FreeBSD/FreeBSD.git] / sys / amd64 / amd64 / mp_machdep.c
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 1996, by Steve Passe
5  * Copyright (c) 2003, by Peter Wemm
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. The name of the developer may NOT be used to endorse or promote products
14  *    derived from this software without specific prior written permission.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
31
32 #include "opt_acpi.h"
33 #include "opt_cpu.h"
34 #include "opt_ddb.h"
35 #include "opt_kstack_pages.h"
36 #include "opt_sched.h"
37 #include "opt_smp.h"
38
39 #include <sys/param.h>
40 #include <sys/systm.h>
41 #include <sys/bus.h>
42 #include <sys/cpuset.h>
43 #include <sys/domainset.h>
44 #ifdef GPROF 
45 #include <sys/gmon.h>
46 #endif
47 #include <sys/kdb.h>
48 #include <sys/kernel.h>
49 #include <sys/ktr.h>
50 #include <sys/lock.h>
51 #include <sys/malloc.h>
52 #include <sys/memrange.h>
53 #include <sys/mutex.h>
54 #include <sys/pcpu.h>
55 #include <sys/proc.h>
56 #include <sys/sched.h>
57 #include <sys/smp.h>
58 #include <sys/sysctl.h>
59
60 #include <vm/vm.h>
61 #include <vm/vm_param.h>
62 #include <vm/pmap.h>
63 #include <vm/vm_kern.h>
64 #include <vm/vm_extern.h>
65 #include <vm/vm_page.h>
66 #include <vm/vm_phys.h>
67
68 #include <x86/apicreg.h>
69 #include <machine/clock.h>
70 #include <machine/cputypes.h>
71 #include <machine/cpufunc.h>
72 #include <x86/mca.h>
73 #include <machine/md_var.h>
74 #include <machine/pcb.h>
75 #include <machine/psl.h>
76 #include <machine/smp.h>
77 #include <machine/specialreg.h>
78 #include <machine/tss.h>
79 #include <x86/ucode.h>
80 #include <machine/cpu.h>
81 #include <x86/init.h>
82
83 #ifdef DEV_ACPI
84 #include <contrib/dev/acpica/include/acpi.h>
85 #include <dev/acpica/acpivar.h>
86 #endif
87
88 #define WARMBOOT_TARGET         0
89 #define WARMBOOT_OFF            (KERNBASE + 0x0467)
90 #define WARMBOOT_SEG            (KERNBASE + 0x0469)
91
92 #define CMOS_REG                (0x70)
93 #define CMOS_DATA               (0x71)
94 #define BIOS_RESET              (0x0f)
95 #define BIOS_WARM               (0x0a)
96
97 #define GiB(v)                  (v ## ULL << 30)
98
99 #define AP_BOOTPT_SZ            (PAGE_SIZE * 3)
100
101 /* Temporary variables for init_secondary()  */
102 char *doublefault_stack;
103 char *mce_stack;
104 char *nmi_stack;
105 char *dbg_stack;
106
107 /*
108  * Local data and functions.
109  */
110
111 static int      start_ap(int apic_id);
112
113 static bool
114 is_kernel_paddr(vm_paddr_t pa)
115 {
116
117         return (pa >= trunc_2mpage(btext - KERNBASE) &&
118            pa < round_page(_end - KERNBASE));
119 }
120
121 static bool
122 is_mpboot_good(vm_paddr_t start, vm_paddr_t end)
123 {
124
125         return (start + AP_BOOTPT_SZ <= GiB(4) && atop(end) < Maxmem);
126 }
127
128 /*
129  * Calculate usable address in base memory for AP trampoline code.
130  */
131 void
132 mp_bootaddress(vm_paddr_t *physmap, unsigned int *physmap_idx)
133 {
134         vm_paddr_t start, end;
135         unsigned int i;
136         bool allocated;
137
138         alloc_ap_trampoline(physmap, physmap_idx);
139
140         /*
141          * Find a memory region big enough below the 4GB boundary to
142          * store the initial page tables.  Region must be mapped by
143          * the direct map.
144          *
145          * Note that it needs to be aligned to a page boundary.
146          */
147         allocated = false;
148         for (i = *physmap_idx; i <= *physmap_idx; i -= 2) {
149                 /*
150                  * First, try to chomp at the start of the physmap region.
151                  * Kernel binary might claim it already.
152                  */
153                 start = round_page(physmap[i]);
154                 end = start + AP_BOOTPT_SZ;
155                 if (start < end && end <= physmap[i + 1] &&
156                     is_mpboot_good(start, end) &&
157                     !is_kernel_paddr(start) && !is_kernel_paddr(end - 1)) {
158                         allocated = true;
159                         physmap[i] = end;
160                         break;
161                 }
162
163                 /*
164                  * Second, try to chomp at the end.  Again, check
165                  * against kernel.
166                  */
167                 end = trunc_page(physmap[i + 1]);
168                 start = end - AP_BOOTPT_SZ;
169                 if (start < end && start >= physmap[i] &&
170                     is_mpboot_good(start, end) &&
171                     !is_kernel_paddr(start) && !is_kernel_paddr(end - 1)) {
172                         allocated = true;
173                         physmap[i + 1] = start;
174                         break;
175                 }
176         }
177         if (allocated) {
178                 mptramp_pagetables = start;
179                 if (physmap[i] == physmap[i + 1] && *physmap_idx != 0) {
180                         memmove(&physmap[i], &physmap[i + 2],
181                             sizeof(*physmap) * (*physmap_idx - i + 2));
182                         *physmap_idx -= 2;
183                 }
184         } else {
185                 mptramp_pagetables = trunc_page(boot_address) - AP_BOOTPT_SZ;
186                 if (bootverbose)
187                         printf(
188 "Cannot find enough space for the initial AP page tables, placing them at %#x",
189                             mptramp_pagetables);
190         }
191 }
192
193 /*
194  * Initialize the IPI handlers and start up the AP's.
195  */
196 void
197 cpu_mp_start(void)
198 {
199         int i;
200
201         /* Initialize the logical ID to APIC ID table. */
202         for (i = 0; i < MAXCPU; i++) {
203                 cpu_apic_ids[i] = -1;
204         }
205
206         /* Install an inter-CPU IPI for cache and TLB invalidations. */
207         setidt(IPI_INVLOP, pti ? IDTVEC(invlop_pti) : IDTVEC(invlop),
208             SDT_SYSIGT, SEL_KPL, 0);
209
210         /* Install an inter-CPU IPI for all-CPU rendezvous */
211         setidt(IPI_RENDEZVOUS, pti ? IDTVEC(rendezvous_pti) :
212             IDTVEC(rendezvous), SDT_SYSIGT, SEL_KPL, 0);
213
214         /* Install generic inter-CPU IPI handler */
215         setidt(IPI_BITMAP_VECTOR, pti ? IDTVEC(ipi_intr_bitmap_handler_pti) :
216             IDTVEC(ipi_intr_bitmap_handler), SDT_SYSIGT, SEL_KPL, 0);
217
218         /* Install an inter-CPU IPI for CPU stop/restart */
219         setidt(IPI_STOP, pti ? IDTVEC(cpustop_pti) : IDTVEC(cpustop),
220             SDT_SYSIGT, SEL_KPL, 0);
221
222         /* Install an inter-CPU IPI for CPU suspend/resume */
223         setidt(IPI_SUSPEND, pti ? IDTVEC(cpususpend_pti) : IDTVEC(cpususpend),
224             SDT_SYSIGT, SEL_KPL, 0);
225
226         /* Set boot_cpu_id if needed. */
227         if (boot_cpu_id == -1) {
228                 boot_cpu_id = PCPU_GET(apic_id);
229                 cpu_info[boot_cpu_id].cpu_bsp = 1;
230         } else
231                 KASSERT(boot_cpu_id == PCPU_GET(apic_id),
232                     ("BSP's APIC ID doesn't match boot_cpu_id"));
233
234         /* Probe logical/physical core configuration. */
235         topo_probe();
236
237         assign_cpu_ids();
238
239         /* Start each Application Processor */
240         init_ops.start_all_aps();
241
242         set_interrupt_apic_ids();
243
244 #if defined(DEV_ACPI) && MAXMEMDOM > 1
245         acpi_pxm_set_cpu_locality();
246 #endif
247 }
248
249 /*
250  * AP CPU's call this to initialize themselves.
251  */
252 void
253 init_secondary(void)
254 {
255         struct pcpu *pc;
256         struct nmi_pcpu *np;
257         struct user_segment_descriptor *gdt;
258         struct region_descriptor ap_gdt;
259         u_int64_t cr0;
260         int cpu, gsel_tss, x;
261
262         /* Set by the startup code for us to use */
263         cpu = bootAP;
264
265         /* Update microcode before doing anything else. */
266         ucode_load_ap(cpu);
267
268         /* Get per-cpu data and save  */
269         pc = &__pcpu[cpu];
270
271         /* prime data page for it to use */
272         pcpu_init(pc, cpu, sizeof(struct pcpu));
273         dpcpu_init(dpcpu, cpu);
274         pc->pc_apic_id = cpu_apic_ids[cpu];
275         pc->pc_prvspace = pc;
276         pc->pc_curthread = 0;
277         pc->pc_tssp = &pc->pc_common_tss;
278         pc->pc_rsp0 = 0;
279         pc->pc_pti_rsp0 = (((vm_offset_t)&pc->pc_pti_stack +
280             PC_PTI_STACK_SZ * sizeof(uint64_t)) & ~0xful);
281         gdt = pc->pc_gdt;
282         pc->pc_tss = (struct system_segment_descriptor *)&gdt[GPROC0_SEL];
283         pc->pc_fs32p = &gdt[GUFS32_SEL];
284         pc->pc_gs32p = &gdt[GUGS32_SEL];
285         pc->pc_ldt = (struct system_segment_descriptor *)&gdt[GUSERLDT_SEL];
286         /* See comment in pmap_bootstrap(). */
287         pc->pc_pcid_next = PMAP_PCID_KERN + 2;
288         pc->pc_pcid_gen = 1;
289
290         pc->pc_smp_tlb_gen = 1;
291
292         /* Init tss */
293         pc->pc_common_tss = __pcpu[0].pc_common_tss;
294         pc->pc_common_tss.tss_iobase = sizeof(struct amd64tss) +
295             IOPERM_BITMAP_SIZE;
296         pc->pc_common_tss.tss_rsp0 = 0;
297
298         /* The doublefault stack runs on IST1. */
299         np = ((struct nmi_pcpu *)&doublefault_stack[PAGE_SIZE]) - 1;
300         np->np_pcpu = (register_t)pc;
301         pc->pc_common_tss.tss_ist1 = (long)np;
302
303         /* The NMI stack runs on IST2. */
304         np = ((struct nmi_pcpu *) &nmi_stack[PAGE_SIZE]) - 1;
305         np->np_pcpu = (register_t)pc;
306         pc->pc_common_tss.tss_ist2 = (long)np;
307
308         /* The MC# stack runs on IST3. */
309         np = ((struct nmi_pcpu *) &mce_stack[PAGE_SIZE]) - 1;
310         np->np_pcpu = (register_t)pc;
311         pc->pc_common_tss.tss_ist3 = (long)np;
312
313         /* The DB# stack runs on IST4. */
314         np = ((struct nmi_pcpu *) &dbg_stack[PAGE_SIZE]) - 1;
315         np->np_pcpu = (register_t)pc;
316         pc->pc_common_tss.tss_ist4 = (long)np;
317
318         /* Prepare private GDT */
319         gdt_segs[GPROC0_SEL].ssd_base = (long)&pc->pc_common_tss;
320         for (x = 0; x < NGDT; x++) {
321                 if (x != GPROC0_SEL && x != GPROC0_SEL + 1 &&
322                     x != GUSERLDT_SEL && x != GUSERLDT_SEL + 1)
323                         ssdtosd(&gdt_segs[x], &gdt[x]);
324         }
325         ssdtosyssd(&gdt_segs[GPROC0_SEL],
326             (struct system_segment_descriptor *)&gdt[GPROC0_SEL]);
327         ap_gdt.rd_limit = NGDT * sizeof(gdt[0]) - 1;
328         ap_gdt.rd_base = (u_long)gdt;
329         lgdt(&ap_gdt);                  /* does magic intra-segment return */
330
331         wrmsr(MSR_FSBASE, 0);           /* User value */
332         wrmsr(MSR_GSBASE, (u_int64_t)pc);
333         wrmsr(MSR_KGSBASE, (u_int64_t)pc);      /* XXX User value while we're in the kernel */
334         fix_cpuid();
335
336         lidt(&r_idt);
337
338         gsel_tss = GSEL(GPROC0_SEL, SEL_KPL);
339         ltr(gsel_tss);
340
341         /*
342          * Set to a known state:
343          * Set by mpboot.s: CR0_PG, CR0_PE
344          * Set by cpu_setregs: CR0_NE, CR0_MP, CR0_TS, CR0_WP, CR0_AM
345          */
346         cr0 = rcr0();
347         cr0 &= ~(CR0_CD | CR0_NW | CR0_EM);
348         load_cr0(cr0);
349
350         amd64_conf_fast_syscall();
351
352         /* signal our startup to the BSP. */
353         mp_naps++;
354
355         /* Spin until the BSP releases the AP's. */
356         while (atomic_load_acq_int(&aps_ready) == 0)
357                 ia32_pause();
358
359         init_secondary_tail();
360 }
361
362 /*******************************************************************
363  * local functions and data
364  */
365
366 #ifdef NUMA
367 static void
368 mp_realloc_pcpu(int cpuid, int domain)
369 {
370         vm_page_t m;
371         vm_offset_t oa, na;
372
373         oa = (vm_offset_t)&__pcpu[cpuid];
374         if (_vm_phys_domain(pmap_kextract(oa)) == domain)
375                 return;
376         m = vm_page_alloc_domain(NULL, 0, domain,
377             VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ);
378         if (m == NULL)
379                 return;
380         na = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
381         pagecopy((void *)oa, (void *)na);
382         pmap_qenter((vm_offset_t)&__pcpu[cpuid], &m, 1);
383         /* XXX old pcpu page leaked. */
384 }
385 #endif
386
387 /*
388  * start each AP in our list
389  */
390 int
391 native_start_all_aps(void)
392 {
393         u_int64_t *pt4, *pt3, *pt2;
394         u_int32_t mpbioswarmvec;
395         int apic_id, cpu, domain, i;
396         u_char mpbiosreason;
397
398         mtx_init(&ap_boot_mtx, "ap boot", NULL, MTX_SPIN);
399
400         /* copy the AP 1st level boot code */
401         bcopy(mptramp_start, (void *)PHYS_TO_DMAP(boot_address), bootMP_size);
402
403         /* Locate the page tables, they'll be below the trampoline */
404         pt4 = (uint64_t *)PHYS_TO_DMAP(mptramp_pagetables);
405         pt3 = pt4 + (PAGE_SIZE) / sizeof(u_int64_t);
406         pt2 = pt3 + (PAGE_SIZE) / sizeof(u_int64_t);
407
408         /* Create the initial 1GB replicated page tables */
409         for (i = 0; i < 512; i++) {
410                 /* Each slot of the level 4 pages points to the same level 3 page */
411                 pt4[i] = (u_int64_t)(uintptr_t)(mptramp_pagetables + PAGE_SIZE);
412                 pt4[i] |= PG_V | PG_RW | PG_U;
413
414                 /* Each slot of the level 3 pages points to the same level 2 page */
415                 pt3[i] = (u_int64_t)(uintptr_t)(mptramp_pagetables + (2 * PAGE_SIZE));
416                 pt3[i] |= PG_V | PG_RW | PG_U;
417
418                 /* The level 2 page slots are mapped with 2MB pages for 1GB. */
419                 pt2[i] = i * (2 * 1024 * 1024);
420                 pt2[i] |= PG_V | PG_RW | PG_PS | PG_U;
421         }
422
423         /* save the current value of the warm-start vector */
424         mpbioswarmvec = *((u_int32_t *) WARMBOOT_OFF);
425         outb(CMOS_REG, BIOS_RESET);
426         mpbiosreason = inb(CMOS_DATA);
427
428         /* setup a vector to our boot code */
429         *((volatile u_short *) WARMBOOT_OFF) = WARMBOOT_TARGET;
430         *((volatile u_short *) WARMBOOT_SEG) = (boot_address >> 4);
431         outb(CMOS_REG, BIOS_RESET);
432         outb(CMOS_DATA, BIOS_WARM);     /* 'warm-start' */
433
434         /* Relocate pcpu areas to the correct domain. */
435 #ifdef NUMA
436         if (vm_ndomains > 1)
437                 for (cpu = 1; cpu < mp_ncpus; cpu++) {
438                         apic_id = cpu_apic_ids[cpu];
439                         domain = acpi_pxm_get_cpu_locality(apic_id);
440                         mp_realloc_pcpu(cpu, domain);
441                 }
442 #endif
443
444         /* start each AP */
445         domain = 0;
446         for (cpu = 1; cpu < mp_ncpus; cpu++) {
447                 apic_id = cpu_apic_ids[cpu];
448 #ifdef NUMA
449                 if (vm_ndomains > 1)
450                         domain = acpi_pxm_get_cpu_locality(apic_id);
451 #endif
452                 /* allocate and set up an idle stack data page */
453                 bootstacks[cpu] = (void *)kmem_malloc(kstack_pages * PAGE_SIZE,
454                     M_WAITOK | M_ZERO);
455                 doublefault_stack = (char *)kmem_malloc(PAGE_SIZE, M_WAITOK |
456                     M_ZERO);
457                 mce_stack = (char *)kmem_malloc(PAGE_SIZE, M_WAITOK | M_ZERO);
458                 nmi_stack = (char *)kmem_malloc_domainset(
459                     DOMAINSET_PREF(domain), PAGE_SIZE, M_WAITOK | M_ZERO);
460                 dbg_stack = (char *)kmem_malloc_domainset(
461                     DOMAINSET_PREF(domain), PAGE_SIZE, M_WAITOK | M_ZERO);
462                 dpcpu = (void *)kmem_malloc_domainset(DOMAINSET_PREF(domain),
463                     DPCPU_SIZE, M_WAITOK | M_ZERO);
464
465                 bootSTK = (char *)bootstacks[cpu] +
466                     kstack_pages * PAGE_SIZE - 8;
467                 bootAP = cpu;
468
469                 /* attempt to start the Application Processor */
470                 if (!start_ap(apic_id)) {
471                         /* restore the warmstart vector */
472                         *(u_int32_t *) WARMBOOT_OFF = mpbioswarmvec;
473                         panic("AP #%d (PHY# %d) failed!", cpu, apic_id);
474                 }
475
476                 CPU_SET(cpu, &all_cpus);        /* record AP in CPU map */
477         }
478
479         /* restore the warmstart vector */
480         *(u_int32_t *) WARMBOOT_OFF = mpbioswarmvec;
481
482         outb(CMOS_REG, BIOS_RESET);
483         outb(CMOS_DATA, mpbiosreason);
484
485         /* number of APs actually started */
486         return (mp_naps);
487 }
488
489
490 /*
491  * This function starts the AP (application processor) identified
492  * by the APIC ID 'physicalCpu'.  It does quite a "song and dance"
493  * to accomplish this.  This is necessary because of the nuances
494  * of the different hardware we might encounter.  It isn't pretty,
495  * but it seems to work.
496  */
497 static int
498 start_ap(int apic_id)
499 {
500         int vector, ms;
501         int cpus;
502
503         /* calculate the vector */
504         vector = (boot_address >> 12) & 0xff;
505
506         /* used as a watchpoint to signal AP startup */
507         cpus = mp_naps;
508
509         ipi_startup(apic_id, vector);
510
511         /* Wait up to 5 seconds for it to start. */
512         for (ms = 0; ms < 5000; ms++) {
513                 if (mp_naps > cpus)
514                         return 1;       /* return SUCCESS */
515                 DELAY(1000);
516         }
517         return 0;               /* return FAILURE */
518 }
519
520 /*
521  * Flush the TLB on other CPU's
522  */
523
524 /*
525  * Invalidation request.  PCPU pc_smp_tlb_op uses u_int instead of the
526  * enum to avoid both namespace and ABI issues (with enums).
527  */
528 enum invl_op_codes {
529       INVL_OP_TLB               = 1,
530       INVL_OP_TLB_INVPCID       = 2,
531       INVL_OP_TLB_INVPCID_PTI   = 3,
532       INVL_OP_TLB_PCID          = 4,
533       INVL_OP_PGRNG             = 5,
534       INVL_OP_PGRNG_INVPCID     = 6,
535       INVL_OP_PGRNG_PCID        = 7,
536       INVL_OP_PG                = 8,
537       INVL_OP_PG_INVPCID        = 9,
538       INVL_OP_PG_PCID           = 10,
539       INVL_OP_CACHE             = 11,
540 };
541
542 /*
543  * These variables are initialized at startup to reflect how each of
544  * the different kinds of invalidations should be performed on the
545  * current machine and environment.
546  */
547 static enum invl_op_codes invl_op_tlb;
548 static enum invl_op_codes invl_op_pgrng;
549 static enum invl_op_codes invl_op_pg;
550
551 /*
552  * Scoreboard of IPI completion notifications from target to IPI initiator.
553  *
554  * Each CPU can initiate shootdown IPI independently from other CPUs.
555  * Initiator enters critical section, then fills its local PCPU
556  * shootdown info (pc_smp_tlb_ vars), then clears scoreboard generation
557  * at location (cpu, my_cpuid) for each target cpu.  After that IPI is
558  * sent to all targets which scan for zeroed scoreboard generation
559  * words.  Upon finding such word the shootdown data is read from
560  * corresponding cpu's pcpu, and generation is set.  Meantime initiator
561  * loops waiting for all zeroed generations in scoreboard to update.
562  */
563 static uint32_t *invl_scoreboard;
564
565 static void
566 invl_scoreboard_init(void *arg __unused)
567 {
568         u_int i;
569
570         invl_scoreboard = malloc(sizeof(uint32_t) * (mp_maxid + 1) *
571             (mp_maxid + 1), M_DEVBUF, M_WAITOK);
572         for (i = 0; i < (mp_maxid + 1) * (mp_maxid + 1); i++)
573                 invl_scoreboard[i] = 1;
574
575         if (pmap_pcid_enabled) {
576                 if (invpcid_works) {
577                         if (pti)
578                                 invl_op_tlb = INVL_OP_TLB_INVPCID_PTI;
579                         else
580                                 invl_op_tlb = INVL_OP_TLB_INVPCID;
581                         invl_op_pgrng = INVL_OP_PGRNG_INVPCID;
582                         invl_op_pg = INVL_OP_PG_INVPCID;
583                 } else {
584                         invl_op_tlb = INVL_OP_TLB_PCID;
585                         invl_op_pgrng = INVL_OP_PGRNG_PCID;
586                         invl_op_pg = INVL_OP_PG_PCID;
587                 }
588         } else {
589                 invl_op_tlb = INVL_OP_TLB;
590                 invl_op_pgrng = INVL_OP_PGRNG;
591                 invl_op_pg = INVL_OP_PG;
592         }
593 }
594 SYSINIT(invl_ops, SI_SUB_SMP, SI_ORDER_FIRST, invl_scoreboard_init, NULL);
595
596 static uint32_t *
597 invl_scoreboard_getcpu(u_int cpu)
598 {
599         return (invl_scoreboard + cpu * (mp_maxid + 1));
600 }
601
602 static uint32_t *
603 invl_scoreboard_slot(u_int cpu)
604 {
605         return (invl_scoreboard_getcpu(cpu) + PCPU_GET(cpuid));
606 }
607
608 /*
609  * Used by pmap to request cache or TLB invalidation on local and
610  * remote processors.  Mask provides the set of remote CPUs which are
611  * to be signalled with the invalidation IPI.  As an optimization, the
612  * curcpu_cb callback is invoked on the calling CPU while waiting for
613  * remote CPUs to complete the operation.
614  *
615  * The callback function is called unconditionally on the caller's
616  * underlying processor, even when this processor is not set in the
617  * mask.  So, the callback function must be prepared to handle such
618  * spurious invocations.
619  *
620  * Interrupts must be enabled when calling the function with smp
621  * started, to avoid deadlock with other IPIs that are protected with
622  * smp_ipi_mtx spinlock at the initiator side.
623  */
624 static void
625 smp_targeted_tlb_shootdown(cpuset_t mask, pmap_t pmap, vm_offset_t addr1,
626     vm_offset_t addr2, smp_invl_cb_t curcpu_cb, enum invl_op_codes op)
627 {
628         cpuset_t other_cpus, mask1;
629         uint32_t generation, *p_cpudone;
630         int cpu;
631
632         /*
633          * It is not necessary to signal other CPUs while booting or
634          * when in the debugger.
635          */
636         if (kdb_active || KERNEL_PANICKED() || !smp_started) {
637                 curcpu_cb(pmap, addr1, addr2);
638                 return;
639         }
640
641         sched_pin();
642
643         /*
644          * Check for other cpus.  Return if none.
645          */
646         if (CPU_ISFULLSET(&mask)) {
647                 if (mp_ncpus <= 1)
648                         goto nospinexit;
649         } else {
650                 CPU_CLR(PCPU_GET(cpuid), &mask);
651                 if (CPU_EMPTY(&mask))
652                         goto nospinexit;
653         }
654
655         /*
656          * Initiator must have interrupts enabled, which prevents
657          * non-invalidation IPIs that take smp_ipi_mtx spinlock,
658          * from deadlocking with us.  On the other hand, preemption
659          * must be disabled to pin initiator to the instance of the
660          * pcpu pc_smp_tlb data and scoreboard line.
661          */
662         KASSERT((read_rflags() & PSL_I) != 0,
663             ("smp_targeted_tlb_shootdown: interrupts disabled"));
664         critical_enter();
665
666         PCPU_SET(smp_tlb_addr1, addr1);
667         PCPU_SET(smp_tlb_addr2, addr2);
668         PCPU_SET(smp_tlb_pmap, pmap);
669         generation = PCPU_GET(smp_tlb_gen);
670         if (++generation == 0)
671                 generation = 1;
672         PCPU_SET(smp_tlb_gen, generation);
673         PCPU_SET(smp_tlb_op, op);
674         /* Fence between filling smp_tlb fields and clearing scoreboard. */
675         atomic_thread_fence_rel();
676
677         mask1 = mask;
678         while ((cpu = CPU_FFS(&mask1)) != 0) {
679                 cpu--;
680                 CPU_CLR(cpu, &mask1);
681                 KASSERT(*invl_scoreboard_slot(cpu) != 0,
682                     ("IPI scoreboard is zero, initiator %d target %d",
683                     PCPU_GET(cpuid), cpu));
684                 *invl_scoreboard_slot(cpu) = 0;
685         }
686
687         /*
688          * IPI acts as a fence between writing to the scoreboard above
689          * (zeroing slot) and reading from it below (wait for
690          * acknowledgment).
691          */
692         if (CPU_ISFULLSET(&mask)) {
693                 ipi_all_but_self(IPI_INVLOP);
694                 other_cpus = all_cpus;
695                 CPU_CLR(PCPU_GET(cpuid), &other_cpus);
696         } else {
697                 other_cpus = mask;
698                 while ((cpu = CPU_FFS(&mask)) != 0) {
699                         cpu--;
700                         CPU_CLR(cpu, &mask);
701                         CTR3(KTR_SMP, "%s: cpu: %d invl ipi op: %x", __func__,
702                             cpu, op);
703                         ipi_send_cpu(cpu, IPI_INVLOP);
704                 }
705         }
706         curcpu_cb(pmap, addr1, addr2);
707         while ((cpu = CPU_FFS(&other_cpus)) != 0) {
708                 cpu--;
709                 CPU_CLR(cpu, &other_cpus);
710                 p_cpudone = invl_scoreboard_slot(cpu);
711                 while (atomic_load_int(p_cpudone) != generation)
712                         ia32_pause();
713         }
714         critical_exit();
715         sched_unpin();
716         return;
717
718 nospinexit:
719         curcpu_cb(pmap, addr1, addr2);
720         sched_unpin();
721 }
722
723 void
724 smp_masked_invltlb(cpuset_t mask, pmap_t pmap, smp_invl_cb_t curcpu_cb)
725 {
726         smp_targeted_tlb_shootdown(mask, pmap, 0, 0, curcpu_cb, invl_op_tlb);
727 #ifdef COUNT_XINVLTLB_HITS
728         ipi_global++;
729 #endif
730 }
731
732 void
733 smp_masked_invlpg(cpuset_t mask, vm_offset_t addr, pmap_t pmap,
734     smp_invl_cb_t curcpu_cb)
735 {
736         smp_targeted_tlb_shootdown(mask, pmap, addr, 0, curcpu_cb, invl_op_pg);
737 #ifdef COUNT_XINVLTLB_HITS
738         ipi_page++;
739 #endif
740 }
741
742 void
743 smp_masked_invlpg_range(cpuset_t mask, vm_offset_t addr1, vm_offset_t addr2,
744     pmap_t pmap, smp_invl_cb_t curcpu_cb)
745 {
746         smp_targeted_tlb_shootdown(mask, pmap, addr1, addr2, curcpu_cb,
747             invl_op_pgrng);
748 #ifdef COUNT_XINVLTLB_HITS
749         ipi_range++;
750         ipi_range_size += (addr2 - addr1) / PAGE_SIZE;
751 #endif
752 }
753
754 void
755 smp_cache_flush(smp_invl_cb_t curcpu_cb)
756 {
757         smp_targeted_tlb_shootdown(all_cpus, NULL, 0, 0, curcpu_cb,
758             INVL_OP_CACHE);
759 }
760
761 /*
762  * Handlers for TLB related IPIs
763  */
764 static void
765 invltlb_handler(pmap_t smp_tlb_pmap)
766 {
767 #ifdef COUNT_XINVLTLB_HITS
768         xhits_gbl[PCPU_GET(cpuid)]++;
769 #endif /* COUNT_XINVLTLB_HITS */
770 #ifdef COUNT_IPIS
771         (*ipi_invltlb_counts[PCPU_GET(cpuid)])++;
772 #endif /* COUNT_IPIS */
773
774         if (smp_tlb_pmap == kernel_pmap)
775                 invltlb_glob();
776         else
777                 invltlb();
778 }
779
780 static void
781 invltlb_invpcid_handler(pmap_t smp_tlb_pmap)
782 {
783         struct invpcid_descr d;
784
785 #ifdef COUNT_XINVLTLB_HITS
786         xhits_gbl[PCPU_GET(cpuid)]++;
787 #endif /* COUNT_XINVLTLB_HITS */
788 #ifdef COUNT_IPIS
789         (*ipi_invltlb_counts[PCPU_GET(cpuid)])++;
790 #endif /* COUNT_IPIS */
791
792         d.pcid = smp_tlb_pmap->pm_pcids[PCPU_GET(cpuid)].pm_pcid;
793         d.pad = 0;
794         d.addr = 0;
795         invpcid(&d, smp_tlb_pmap == kernel_pmap ? INVPCID_CTXGLOB :
796             INVPCID_CTX);
797 }
798
799 static void
800 invltlb_invpcid_pti_handler(pmap_t smp_tlb_pmap)
801 {
802         struct invpcid_descr d;
803
804 #ifdef COUNT_XINVLTLB_HITS
805         xhits_gbl[PCPU_GET(cpuid)]++;
806 #endif /* COUNT_XINVLTLB_HITS */
807 #ifdef COUNT_IPIS
808         (*ipi_invltlb_counts[PCPU_GET(cpuid)])++;
809 #endif /* COUNT_IPIS */
810
811         d.pcid = smp_tlb_pmap->pm_pcids[PCPU_GET(cpuid)].pm_pcid;
812         d.pad = 0;
813         d.addr = 0;
814         if (smp_tlb_pmap == kernel_pmap) {
815                 /*
816                  * This invalidation actually needs to clear kernel
817                  * mappings from the TLB in the current pmap, but
818                  * since we were asked for the flush in the kernel
819                  * pmap, achieve it by performing global flush.
820                  */
821                 invpcid(&d, INVPCID_CTXGLOB);
822         } else {
823                 invpcid(&d, INVPCID_CTX);
824                 d.pcid |= PMAP_PCID_USER_PT;
825                 invpcid(&d, INVPCID_CTX);
826         }
827 }
828
829 static void
830 invltlb_pcid_handler(pmap_t smp_tlb_pmap)
831 {
832         uint64_t kcr3, ucr3;
833         uint32_t pcid;
834   
835 #ifdef COUNT_XINVLTLB_HITS
836         xhits_gbl[PCPU_GET(cpuid)]++;
837 #endif /* COUNT_XINVLTLB_HITS */
838 #ifdef COUNT_IPIS
839         (*ipi_invltlb_counts[PCPU_GET(cpuid)])++;
840 #endif /* COUNT_IPIS */
841
842         if (smp_tlb_pmap == kernel_pmap) {
843                 invltlb_glob();
844         } else {
845                 /*
846                  * The current pmap might not be equal to
847                  * smp_tlb_pmap.  The clearing of the pm_gen in
848                  * pmap_invalidate_all() takes care of TLB
849                  * invalidation when switching to the pmap on this
850                  * CPU.
851                  */
852                 if (PCPU_GET(curpmap) == smp_tlb_pmap) {
853                         pcid = smp_tlb_pmap->pm_pcids[PCPU_GET(cpuid)].pm_pcid;
854                         kcr3 = smp_tlb_pmap->pm_cr3 | pcid;
855                         ucr3 = smp_tlb_pmap->pm_ucr3;
856                         if (ucr3 != PMAP_NO_CR3) {
857                                 ucr3 |= PMAP_PCID_USER_PT | pcid;
858                                 pmap_pti_pcid_invalidate(ucr3, kcr3);
859                         } else
860                                 load_cr3(kcr3);
861                 }
862         }
863 }
864
865 static void
866 invlpg_handler(vm_offset_t smp_tlb_addr1)
867 {
868 #ifdef COUNT_XINVLTLB_HITS
869         xhits_pg[PCPU_GET(cpuid)]++;
870 #endif /* COUNT_XINVLTLB_HITS */
871 #ifdef COUNT_IPIS
872         (*ipi_invlpg_counts[PCPU_GET(cpuid)])++;
873 #endif /* COUNT_IPIS */
874
875         invlpg(smp_tlb_addr1);
876 }
877
878 static void
879 invlpg_invpcid_handler(pmap_t smp_tlb_pmap, vm_offset_t smp_tlb_addr1)
880 {
881         struct invpcid_descr d;
882
883 #ifdef COUNT_XINVLTLB_HITS
884         xhits_pg[PCPU_GET(cpuid)]++;
885 #endif /* COUNT_XINVLTLB_HITS */
886 #ifdef COUNT_IPIS
887         (*ipi_invlpg_counts[PCPU_GET(cpuid)])++;
888 #endif /* COUNT_IPIS */
889
890         invlpg(smp_tlb_addr1);
891         if (smp_tlb_pmap->pm_ucr3 != PMAP_NO_CR3) {
892                 d.pcid = smp_tlb_pmap->pm_pcids[PCPU_GET(cpuid)].pm_pcid |
893                     PMAP_PCID_USER_PT;
894                 d.pad = 0;
895                 d.addr = smp_tlb_addr1;
896                 invpcid(&d, INVPCID_ADDR);
897         }
898 }
899
900 static void
901 invlpg_pcid_handler(pmap_t smp_tlb_pmap, vm_offset_t smp_tlb_addr1)
902 {
903         uint64_t kcr3, ucr3;
904         uint32_t pcid;
905
906 #ifdef COUNT_XINVLTLB_HITS
907         xhits_pg[PCPU_GET(cpuid)]++;
908 #endif /* COUNT_XINVLTLB_HITS */
909 #ifdef COUNT_IPIS
910         (*ipi_invlpg_counts[PCPU_GET(cpuid)])++;
911 #endif /* COUNT_IPIS */
912
913         invlpg(smp_tlb_addr1);
914         if (smp_tlb_pmap == PCPU_GET(curpmap) &&
915             (ucr3 = smp_tlb_pmap->pm_ucr3) != PMAP_NO_CR3) {
916                 pcid = smp_tlb_pmap->pm_pcids[PCPU_GET(cpuid)].pm_pcid;
917                 kcr3 = smp_tlb_pmap->pm_cr3 | pcid | CR3_PCID_SAVE;
918                 ucr3 |= pcid | PMAP_PCID_USER_PT | CR3_PCID_SAVE;
919                 pmap_pti_pcid_invlpg(ucr3, kcr3, smp_tlb_addr1);
920         }
921 }
922
923 static void
924 invlrng_handler(vm_offset_t smp_tlb_addr1, vm_offset_t smp_tlb_addr2)
925 {
926         vm_offset_t addr, addr2;
927
928 #ifdef COUNT_XINVLTLB_HITS
929         xhits_rng[PCPU_GET(cpuid)]++;
930 #endif /* COUNT_XINVLTLB_HITS */
931 #ifdef COUNT_IPIS
932         (*ipi_invlrng_counts[PCPU_GET(cpuid)])++;
933 #endif /* COUNT_IPIS */
934
935         addr = smp_tlb_addr1;
936         addr2 = smp_tlb_addr2;
937         do {
938                 invlpg(addr);
939                 addr += PAGE_SIZE;
940         } while (addr < addr2);
941 }
942
943 static void
944 invlrng_invpcid_handler(pmap_t smp_tlb_pmap, vm_offset_t smp_tlb_addr1,
945     vm_offset_t smp_tlb_addr2)
946 {
947         struct invpcid_descr d;
948         vm_offset_t addr, addr2;
949
950 #ifdef COUNT_XINVLTLB_HITS
951         xhits_rng[PCPU_GET(cpuid)]++;
952 #endif /* COUNT_XINVLTLB_HITS */
953 #ifdef COUNT_IPIS
954         (*ipi_invlrng_counts[PCPU_GET(cpuid)])++;
955 #endif /* COUNT_IPIS */
956
957         addr = smp_tlb_addr1;
958         addr2 = smp_tlb_addr2;
959         do {
960                 invlpg(addr);
961                 addr += PAGE_SIZE;
962         } while (addr < addr2);
963         if (smp_tlb_pmap->pm_ucr3 != PMAP_NO_CR3) {
964                 d.pcid = smp_tlb_pmap->pm_pcids[PCPU_GET(cpuid)].pm_pcid |
965                     PMAP_PCID_USER_PT;
966                 d.pad = 0;
967                 d.addr = smp_tlb_addr1;
968                 do {
969                         invpcid(&d, INVPCID_ADDR);
970                         d.addr += PAGE_SIZE;
971                 } while (d.addr < addr2);
972         }
973 }
974
975 static void
976 invlrng_pcid_handler(pmap_t smp_tlb_pmap, vm_offset_t smp_tlb_addr1,
977     vm_offset_t smp_tlb_addr2)
978 {
979         vm_offset_t addr, addr2;
980         uint64_t kcr3, ucr3;
981         uint32_t pcid;
982
983 #ifdef COUNT_XINVLTLB_HITS
984         xhits_rng[PCPU_GET(cpuid)]++;
985 #endif /* COUNT_XINVLTLB_HITS */
986 #ifdef COUNT_IPIS
987         (*ipi_invlrng_counts[PCPU_GET(cpuid)])++;
988 #endif /* COUNT_IPIS */
989
990         addr = smp_tlb_addr1;
991         addr2 = smp_tlb_addr2;
992         do {
993                 invlpg(addr);
994                 addr += PAGE_SIZE;
995         } while (addr < addr2);
996         if (smp_tlb_pmap == PCPU_GET(curpmap) &&
997             (ucr3 = smp_tlb_pmap->pm_ucr3) != PMAP_NO_CR3) {
998                 pcid = smp_tlb_pmap->pm_pcids[PCPU_GET(cpuid)].pm_pcid;
999                 kcr3 = smp_tlb_pmap->pm_cr3 | pcid | CR3_PCID_SAVE;
1000                 ucr3 |= pcid | PMAP_PCID_USER_PT | CR3_PCID_SAVE;
1001                 pmap_pti_pcid_invlrng(ucr3, kcr3, smp_tlb_addr1, addr2);
1002         }
1003 }
1004
1005 static void
1006 invlcache_handler(void)
1007 {
1008 #ifdef COUNT_IPIS
1009         (*ipi_invlcache_counts[PCPU_GET(cpuid)])++;
1010 #endif /* COUNT_IPIS */
1011         wbinvd();
1012 }
1013
1014 static void
1015 invlop_handler_one_req(enum invl_op_codes smp_tlb_op, pmap_t smp_tlb_pmap,
1016     vm_offset_t smp_tlb_addr1, vm_offset_t smp_tlb_addr2)
1017 {
1018         switch (smp_tlb_op) {
1019         case INVL_OP_TLB:
1020                 invltlb_handler(smp_tlb_pmap);
1021                 break;
1022         case INVL_OP_TLB_INVPCID:
1023                 invltlb_invpcid_handler(smp_tlb_pmap);
1024                 break;
1025         case INVL_OP_TLB_INVPCID_PTI:
1026                 invltlb_invpcid_pti_handler(smp_tlb_pmap);
1027                 break;
1028         case INVL_OP_TLB_PCID:
1029                 invltlb_pcid_handler(smp_tlb_pmap);
1030                 break;
1031         case INVL_OP_PGRNG:
1032                 invlrng_handler(smp_tlb_addr1, smp_tlb_addr2);
1033                 break;
1034         case INVL_OP_PGRNG_INVPCID:
1035                 invlrng_invpcid_handler(smp_tlb_pmap, smp_tlb_addr1,
1036                     smp_tlb_addr2);
1037                 break;
1038         case INVL_OP_PGRNG_PCID:
1039                 invlrng_pcid_handler(smp_tlb_pmap, smp_tlb_addr1,
1040                     smp_tlb_addr2);
1041                 break;
1042         case INVL_OP_PG:
1043                 invlpg_handler(smp_tlb_addr1);
1044                 break;
1045         case INVL_OP_PG_INVPCID:
1046                 invlpg_invpcid_handler(smp_tlb_pmap, smp_tlb_addr1);
1047                 break;
1048         case INVL_OP_PG_PCID:
1049                 invlpg_pcid_handler(smp_tlb_pmap, smp_tlb_addr1);
1050                 break;
1051         case INVL_OP_CACHE:
1052                 invlcache_handler();
1053                 break;
1054         default:
1055                 __assert_unreachable();
1056                 break;
1057         }
1058 }
1059
1060 void
1061 invlop_handler(void)
1062 {
1063         struct pcpu *initiator_pc;
1064         pmap_t smp_tlb_pmap;
1065         vm_offset_t smp_tlb_addr1, smp_tlb_addr2;
1066         u_int initiator_cpu_id;
1067         enum invl_op_codes smp_tlb_op;
1068         uint32_t *scoreboard, smp_tlb_gen;
1069
1070         scoreboard = invl_scoreboard_getcpu(PCPU_GET(cpuid));
1071         for (;;) {
1072                 for (initiator_cpu_id = 0; initiator_cpu_id <= mp_maxid;
1073                     initiator_cpu_id++) {
1074                         if (scoreboard[initiator_cpu_id] == 0)
1075                                 break;
1076                 }
1077                 if (initiator_cpu_id > mp_maxid)
1078                         break;
1079                 initiator_pc = cpuid_to_pcpu[initiator_cpu_id];
1080
1081                 /*
1082                  * This acquire fence and its corresponding release
1083                  * fence in smp_targeted_tlb_shootdown() is between
1084                  * reading zero scoreboard slot and accessing PCPU of
1085                  * initiator for pc_smp_tlb values.
1086                  */
1087                 atomic_thread_fence_acq();
1088                 smp_tlb_pmap = initiator_pc->pc_smp_tlb_pmap;
1089                 smp_tlb_addr1 = initiator_pc->pc_smp_tlb_addr1;
1090                 smp_tlb_addr2 = initiator_pc->pc_smp_tlb_addr2;
1091                 smp_tlb_op = initiator_pc->pc_smp_tlb_op;
1092                 smp_tlb_gen = initiator_pc->pc_smp_tlb_gen;
1093
1094                 /*
1095                  * Ensure that we do not make our scoreboard
1096                  * notification visible to the initiator until the
1097                  * pc_smp_tlb values are read.  The corresponding
1098                  * fence is implicitly provided by the barrier in the
1099                  * IPI send operation before the APIC ICR register
1100                  * write.
1101                  *
1102                  * As an optimization, the request is acknowledged
1103                  * before the actual invalidation is performed.  It is
1104                  * safe because target CPU cannot return to userspace
1105                  * before handler finishes. Only NMI can preempt the
1106                  * handler, but NMI would see the kernel handler frame
1107                  * and not touch not-invalidated user page table.
1108                  */
1109                 atomic_thread_fence_acq();
1110                 atomic_store_int(&scoreboard[initiator_cpu_id], smp_tlb_gen);
1111
1112                 invlop_handler_one_req(smp_tlb_op, smp_tlb_pmap, smp_tlb_addr1,
1113                     smp_tlb_addr2);
1114         }
1115 }