xref: /dragonfly/sys/platform/vkernel64/x86_64/mp.c (revision 207ba670)
1 /*
2  * Copyright (c) 2007 The DragonFly Project.  All rights reserved.
3  *
4  * This code is derived from software contributed to The DragonFly Project
5  * by Matthew Dillon <dillon@backplane.com>
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in
15  *    the documentation and/or other materials provided with the
16  *    distribution.
17  * 3. Neither the name of The DragonFly Project nor the names of its
18  *    contributors may be used to endorse or promote products derived
19  *    from this software without specific, prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
24  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
25  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
26  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
27  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
28  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
29  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
30  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
31  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34 
35 #include <sys/cpumask.h>
36 #include <sys/interrupt.h>
37 #include <sys/kernel.h>
38 #include <sys/memrange.h>
39 #include <sys/tls.h>
40 #include <sys/types.h>
41 #include <sys/vmm.h>
42 
43 #include <vm/vm_extern.h>
44 #include <vm/vm_kern.h>
45 #include <vm/vm_object.h>
46 #include <vm/vm_page.h>
47 
48 #include <sys/mplock2.h>
49 #include <sys/thread2.h>
50 
51 #include <machine/cpu.h>
52 #include <machine/cpufunc.h>
53 #include <machine/globaldata.h>
54 #include <machine/md_var.h>
55 #include <machine/pmap.h>
56 #include <machine/smp.h>
57 #include <machine/tls.h>
58 #include <machine/param.h>
59 
60 #include <unistd.h>
61 #include <pthread.h>
62 #include <signal.h>
63 #include <stdio.h>
64 
65 extern pt_entry_t *KPTphys;
66 
67 extern int vmm_enabled;
68 
69 volatile cpumask_t stopped_cpus;
70 /* which cpus are ready for IPIs etc? */
71 cpumask_t	smp_active_mask = CPUMASK_INITIALIZER_ONLYONE;
72 static int	boot_address;
73 /* which cpus have been started */
74 static cpumask_t smp_startup_mask = CPUMASK_INITIALIZER_ONLYONE;
75 static int  mp_finish;
76 
77 /* Local data for detecting CPU TOPOLOGY */
78 static int core_bits = 0;
79 static int logical_CPU_bits = 0;
80 
81 /* function prototypes XXX these should go elsewhere */
82 void bootstrap_idle(void);
83 void single_cpu_ipi(int, int, int);
84 void selected_cpu_ipi(cpumask_t, int, int);
85 #if 0
86 void ipi_handler(int);
87 #endif
88 
89 pt_entry_t *SMPpt;
90 
91 /* AP uses this during bootstrap.  Do not staticize.  */
92 char *bootSTK;
93 static int bootAP;
94 
95 
96 /* XXX these need to go into the appropriate header file */
97 static int start_all_aps(u_int);
98 void init_secondary(void);
99 void *start_ap(void *);
100 
101 /*
102  * Get SMP fully working before we start initializing devices.
103  */
104 static
105 void
106 ap_finish(void)
107 {
108         mp_finish = 1;
109         if (bootverbose)
110                 kprintf("Finish MP startup\n");
111 
112 	/* build our map of 'other' CPUs */
113 	mycpu->gd_other_cpus = smp_startup_mask;
114 	CPUMASK_NANDBIT(mycpu->gd_other_cpus, mycpu->gd_cpuid);
115 
116 	/*
117 	 * Let the other cpu's finish initializing and build their map
118 	 * of 'other' CPUs.
119 	 */
120         rel_mplock();
121         while (CPUMASK_CMPMASKNEQ(smp_active_mask,smp_startup_mask)) {
122 		DELAY(100000);
123                 cpu_lfence();
124 	}
125 
126         while (try_mplock() == 0)
127 		DELAY(100000);
128         if (bootverbose)
129                 kprintf("Active CPU Mask: %08lx\n",
130 			(long)CPUMASK_LOWMASK(smp_active_mask));
131 }
132 
133 SYSINIT(finishsmp, SI_BOOT2_FINISH_SMP, SI_ORDER_FIRST, ap_finish, NULL);
134 
135 void *
136 start_ap(void *arg __unused)
137 {
138 	init_secondary();
139 	setrealcpu();
140 	bootstrap_idle();
141 
142 	return(NULL); /* NOTREACHED */
143 }
144 
145 /* storage for AP thread IDs */
146 pthread_t ap_tids[MAXCPU];
147 
148 int naps;
149 
150 void
151 mp_start(void)
152 {
153 	size_t ipiq_size;
154 	int shift;
155 
156 	ncpus = optcpus;
157 	naps = ncpus - 1;
158 
159 	for (shift = 0; (1 << shift) <= ncpus; ++shift)
160 		;
161 	--shift;
162 
163         /* ncpus_fit -- ncpus rounded up to the nearest power of 2 */
164         if ((1 << shift) < ncpus)
165                 ++shift;
166         ncpus_fit = 1 << shift;
167         ncpus_fit_mask = ncpus_fit - 1;
168 
169 	malloc_reinit_ncpus();
170 
171 	/*
172 	 * cpu0 initialization
173 	 */
174 	ipiq_size = sizeof(struct lwkt_ipiq) * ncpus;
175 	mycpu->gd_ipiq = (void *)kmem_alloc(&kernel_map, ipiq_size,
176 					    VM_SUBSYS_IPIQ);
177 	bzero(mycpu->gd_ipiq, ipiq_size);
178 
179 	/* initialize arc4random. */
180 	arc4_init_pcpu(0);
181 
182 	/*
183 	 * cpu 1-(n-1)
184 	 */
185 	start_all_aps(boot_address);
186 
187 }
188 
189 void
190 mp_announce(void)
191 {
192 	int x;
193 
194 	kprintf("DragonFly/MP: Multiprocessor\n");
195 	kprintf(" cpu0 (BSP)\n");
196 
197 	for (x = 1; x <= naps; ++x)
198 		kprintf(" cpu%d (AP)\n", x);
199 }
200 
201 void
202 cpu_send_ipiq(int dcpu)
203 {
204 	if (CPUMASK_TESTBIT(smp_active_mask, dcpu)) {
205 		if (pthread_kill(ap_tids[dcpu], SIGUSR1) != 0)
206 			panic("pthread_kill failed in cpu_send_ipiq");
207 	}
208 #if 0
209 	panic("XXX cpu_send_ipiq()");
210 #endif
211 }
212 
213 void
214 single_cpu_ipi(int cpu, int vector, int delivery_mode)
215 {
216 	kprintf("XXX single_cpu_ipi\n");
217 }
218 
219 void
220 selected_cpu_ipi(cpumask_t target, int vector, int delivery_mode)
221 {
222 	crit_enter();
223 	while (CPUMASK_TESTNZERO(target)) {
224 		int n = BSFCPUMASK(target);
225 		CPUMASK_NANDBIT(target, n);
226 		single_cpu_ipi(n, vector, delivery_mode);
227 	}
228 	crit_exit();
229 }
230 
231 int
232 stop_cpus(cpumask_t map)
233 {
234 	CPUMASK_ANDMASK(map, smp_active_mask);
235 
236 	crit_enter();
237 	while (CPUMASK_TESTNZERO(map)) {
238 		int n = BSFCPUMASK(map);
239 		CPUMASK_NANDBIT(map, n);
240 		ATOMIC_CPUMASK_ORBIT(stopped_cpus, n);
241 		if (pthread_kill(ap_tids[n], SIGXCPU) != 0)
242 			panic("stop_cpus: pthread_kill failed");
243 	}
244 	crit_exit();
245 #if 0
246 	panic("XXX stop_cpus()");
247 #endif
248 
249 	return(1);
250 }
251 
252 int
253 restart_cpus(cpumask_t map)
254 {
255 	CPUMASK_ANDMASK(map, smp_active_mask);
256 
257 	crit_enter();
258 	while (CPUMASK_TESTNZERO(map)) {
259 		int n = BSFCPUMASK(map);
260 		CPUMASK_NANDBIT(map, n);
261 		ATOMIC_CPUMASK_NANDBIT(stopped_cpus, n);
262 		if (pthread_kill(ap_tids[n], SIGXCPU) != 0)
263 			panic("restart_cpus: pthread_kill failed");
264 	}
265 	crit_exit();
266 #if 0
267 	panic("XXX restart_cpus()");
268 #endif
269 
270 	return(1);
271 }
272 void
273 ap_init(void)
274 {
275         /*
276          * Adjust smp_startup_mask to signal the BSP that we have started
277          * up successfully.  Note that we do not yet hold the BGL.  The BSP
278          * is waiting for our signal.
279          *
280          * We can't set our bit in smp_active_mask yet because we are holding
281          * interrupts physically disabled and remote cpus could deadlock
282          * trying to send us an IPI.
283          */
284 	ATOMIC_CPUMASK_ORBIT(smp_startup_mask, mycpu->gd_cpuid);
285 	cpu_mfence();
286 
287         /*
288          * Interlock for finalization.  Wait until mp_finish is non-zero,
289          * then get the MP lock.
290          *
291          * Note: We are in a critical section.
292          *
293          * Note: we are the idle thread, we can only spin.
294          *
295          * Note: The load fence is memory volatile and prevents the compiler
296          * from improperly caching mp_finish, and the cpu from improperly
297          * caching it.
298          */
299 
300 	while (mp_finish == 0) {
301 		cpu_lfence();
302 		DELAY(500000);
303 	}
304         while (try_mplock() == 0)
305 		DELAY(100000);
306 
307         /* BSP may have changed PTD while we're waiting for the lock */
308         cpu_invltlb();
309 
310         /* Build our map of 'other' CPUs. */
311         mycpu->gd_other_cpus = smp_startup_mask;
312 	CPUMASK_NANDBIT(mycpu->gd_other_cpus, mycpu->gd_cpuid);
313 
314         kprintf("SMP: AP CPU #%d Launched!\n", mycpu->gd_cpuid);
315 
316 
317         /* Set memory range attributes for this CPU to match the BSP */
318         mem_range_AP_init();
319         /*
320          * Once we go active we must process any IPIQ messages that may
321          * have been queued, because no actual IPI will occur until we
322          * set our bit in the smp_active_mask.  If we don't the IPI
323          * message interlock could be left set which would also prevent
324          * further IPIs.
325          *
326          * The idle loop doesn't expect the BGL to be held and while
327          * lwkt_switch() normally cleans things up this is a special case
328          * because we returning almost directly into the idle loop.
329          *
330          * The idle thread is never placed on the runq, make sure
331          * nothing we've done put it there.
332          */
333 	KKASSERT(get_mplock_count(curthread) == 1);
334 	ATOMIC_CPUMASK_ORBIT(smp_active_mask, mycpu->gd_cpuid);
335 
336 	mdcpu->gd_fpending = 0;
337 	mdcpu->gd_ipending = 0;
338 	initclocks_pcpu();	/* clock interrupts (via IPIs) */
339 
340 	/*
341 	 * Since we may have cleaned up the interrupt triggers, manually
342 	 * process any pending IPIs before exiting our critical section.
343 	 * Once the critical section has exited, normal interrupt processing
344 	 * may occur.
345 	 */
346 	atomic_swap_int(&mycpu->gd_npoll, 0);
347 	lwkt_process_ipiq();
348 
349         /*
350          * Releasing the mp lock lets the BSP finish up the SMP init
351          */
352         rel_mplock();
353         KKASSERT((curthread->td_flags & TDF_RUNQ) == 0);
354 }
355 
356 void
357 init_secondary(void)
358 {
359         int     myid = bootAP;
360         struct mdglobaldata *md;
361         struct privatespace *ps;
362 
363         ps = &CPU_prvspace[myid];
364 
365 	KKASSERT(ps->mdglobaldata.mi.gd_prvspace == ps);
366 
367 	/*
368 	 * Setup the %gs for cpu #n.  The mycpu macro works after this
369 	 * point.  Note that %fs is used by pthreads.
370 	 */
371 	tls_set_gs(&CPU_prvspace[myid], sizeof(struct privatespace));
372 
373         md = mdcpu;     /* loaded through %gs:0 (mdglobaldata.mi.gd_prvspace)*/
374 
375 	/* JG */
376         md->gd_common_tss.tss_rsp0 = 0; /* not used until after switch */
377         //md->gd_common_tss.tss_ss0 = GSEL(GDATA_SEL, SEL_KPL);
378         //md->gd_common_tss.tss_ioopt = (sizeof md->gd_common_tss) << 16;
379 
380         /*
381          * Set to a known state:
382          * Set by mpboot.s: CR0_PG, CR0_PE
383          * Set by cpu_setregs: CR0_NE, CR0_MP, CR0_TS, CR0_WP, CR0_AM
384          */
385 }
386 
387 static int
388 start_all_aps(u_int boot_addr)
389 {
390 	int x, i;
391 	struct mdglobaldata *gd;
392 	struct privatespace *ps;
393 	vm_page_t m;
394 	vm_offset_t va;
395 	void *stack;
396 	pthread_attr_t attr;
397 	size_t ipiq_size;
398 #if 0
399 	struct lwp_params params;
400 #endif
401 
402 	/*
403 	 * needed for ipis to initial thread
404 	 * FIXME: rename ap_tids?
405 	 */
406 	ap_tids[0] = pthread_self();
407 	pthread_attr_init(&attr);
408 
409 	vm_object_hold(&kernel_object);
410 	for (x = 1; x <= naps; ++x) {
411 		/* Allocate space for the CPU's private space. */
412 		for (i = 0; i < sizeof(struct mdglobaldata); i += PAGE_SIZE) {
413 			va =(vm_offset_t)&CPU_prvspace[x].mdglobaldata + i;
414 			m = vm_page_alloc(&kernel_object, va, VM_ALLOC_SYSTEM);
415 			pmap_kenter_quick(va, m->phys_addr);
416 		}
417 
418 		for (i = 0; i < sizeof(CPU_prvspace[x].idlestack); i += PAGE_SIZE) {
419 			va =(vm_offset_t)&CPU_prvspace[x].idlestack + i;
420 			m = vm_page_alloc(&kernel_object, va, VM_ALLOC_SYSTEM);
421 			pmap_kenter_quick(va, m->phys_addr);
422 		}
423 
424                 gd = &CPU_prvspace[x].mdglobaldata;     /* official location */
425                 bzero(gd, sizeof(*gd));
426                 gd->mi.gd_prvspace = ps = &CPU_prvspace[x];
427 
428                 /* prime data page for it to use */
429                 mi_gdinit(&gd->mi, x);
430                 cpu_gdinit(gd, x);
431 
432 #if 0
433                 gd->gd_CMAP1 = pmap_kpte((vm_offset_t)CPU_prvspace[x].CPAGE1);
434                 gd->gd_CMAP2 = pmap_kpte((vm_offset_t)CPU_prvspace[x].CPAGE2);
435                 gd->gd_CMAP3 = pmap_kpte((vm_offset_t)CPU_prvspace[x].CPAGE3);
436                 gd->gd_PMAP1 = pmap_kpte((vm_offset_t)CPU_prvspace[x].PPAGE1);
437                 gd->gd_CADDR1 = ps->CPAGE1;
438                 gd->gd_CADDR2 = ps->CPAGE2;
439                 gd->gd_CADDR3 = ps->CPAGE3;
440                 gd->gd_PADDR1 = (vpte_t *)ps->PPAGE1;
441 #endif
442 
443 		ipiq_size = sizeof(struct lwkt_ipiq) * (naps + 1);
444                 gd->mi.gd_ipiq = (void *)kmem_alloc(&kernel_map, ipiq_size,
445 						    VM_SUBSYS_IPIQ);
446                 bzero(gd->mi.gd_ipiq, ipiq_size);
447 
448 		/* initialize arc4random. */
449 		arc4_init_pcpu(x);
450 
451                 /*
452                  * Setup the AP boot stack
453                  */
454                 bootSTK = &ps->idlestack[UPAGES*PAGE_SIZE/2];
455                 bootAP = x;
456 
457 		/*
458 		 * Setup the AP's lwp, this is the 'cpu'
459 		 *
460 		 * We have to make sure our signals are masked or the new LWP
461 		 * may pick up a signal that it isn't ready for yet.  SMP
462 		 * startup occurs after SI_BOOT2_LEAVE_CRIT so interrupts
463 		 * have already been enabled.
464 		 */
465 		cpu_disable_intr();
466 
467 		if (vmm_enabled) {
468 			stack = mmap(NULL, KERNEL_STACK_SIZE,
469 				     PROT_READ|PROT_WRITE|PROT_EXEC,
470 				     MAP_ANON, -1, 0);
471 			if (stack == MAP_FAILED) {
472 				panic("Unable to allocate stack for thread %d\n", x);
473 			}
474 			pthread_attr_setstack(&attr, stack, KERNEL_STACK_SIZE);
475 		}
476 
477 		pthread_create(&ap_tids[x], &attr, start_ap, NULL);
478 		cpu_enable_intr();
479 
480 		while (CPUMASK_TESTBIT(smp_startup_mask, x) == 0) {
481 			cpu_lfence(); /* XXX spin until the AP has started */
482 			DELAY(1000);
483 		}
484 	}
485 	vm_object_drop(&kernel_object);
486 	pthread_attr_destroy(&attr);
487 
488 	return(ncpus - 1);
489 }
490 
491 /*
492  * CPU TOPOLOGY DETECTION FUNCTIONS.
493  */
494 void
495 detect_cpu_topology(void)
496 {
497 	logical_CPU_bits = vkernel_b_arg;
498 	core_bits = vkernel_B_arg;
499 }
500 
501 int
502 get_chip_ID(int cpuid)
503 {
504 	return get_apicid_from_cpuid(cpuid) >>
505 	    (logical_CPU_bits + core_bits);
506 }
507 
508 int
509 get_chip_ID_from_APICID(int apicid)
510 {
511         return apicid >> (logical_CPU_bits + core_bits);
512 }
513 
514 int
515 get_core_number_within_chip(int cpuid)
516 {
517 	return ((get_apicid_from_cpuid(cpuid) >> logical_CPU_bits) &
518 		((1 << core_bits) - 1));
519 }
520 
521 int
522 get_logical_CPU_number_within_core(int cpuid)
523 {
524 	return (get_apicid_from_cpuid(cpuid) &
525 		((1 << logical_CPU_bits) - 1));
526 }
527