1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Suspend support specific for i386/x86-64.
4  *
5  * Copyright (c) 2007 Rafael J. Wysocki <rjw@sisk.pl>
6  * Copyright (c) 2002 Pavel Machek <pavel@ucw.cz>
7  * Copyright (c) 2001 Patrick Mochel <mochel@osdl.org>
8  */
9 
10 #include <linux/suspend.h>
11 #include <linux/export.h>
12 #include <linux/smp.h>
13 #include <linux/perf_event.h>
14 #include <linux/tboot.h>
15 #include <linux/dmi.h>
16 #include <linux/pgtable.h>
17 
18 #include <asm/proto.h>
19 #include <asm/mtrr.h>
20 #include <asm/page.h>
21 #include <asm/mce.h>
22 #include <asm/suspend.h>
23 #include <asm/fpu/api.h>
24 #include <asm/debugreg.h>
25 #include <asm/cpu.h>
26 #include <asm/cacheinfo.h>
27 #include <asm/mmu_context.h>
28 #include <asm/cpu_device_id.h>
29 #include <asm/microcode.h>
30 #include <asm/fred.h>
31 
32 #ifdef CONFIG_X86_32
33 __visible unsigned long saved_context_ebx;
34 __visible unsigned long saved_context_esp, saved_context_ebp;
35 __visible unsigned long saved_context_esi, saved_context_edi;
36 __visible unsigned long saved_context_eflags;
37 #endif
38 struct saved_context saved_context;
39 
msr_save_context(struct saved_context * ctxt)40 static void msr_save_context(struct saved_context *ctxt)
41 {
42 	struct saved_msr *msr = ctxt->saved_msrs.array;
43 	struct saved_msr *end = msr + ctxt->saved_msrs.num;
44 
45 	while (msr < end) {
46 		if (msr->valid)
47 			rdmsrl(msr->info.msr_no, msr->info.reg.q);
48 		msr++;
49 	}
50 }
51 
msr_restore_context(struct saved_context * ctxt)52 static void msr_restore_context(struct saved_context *ctxt)
53 {
54 	struct saved_msr *msr = ctxt->saved_msrs.array;
55 	struct saved_msr *end = msr + ctxt->saved_msrs.num;
56 
57 	while (msr < end) {
58 		if (msr->valid)
59 			wrmsrl(msr->info.msr_no, msr->info.reg.q);
60 		msr++;
61 	}
62 }
63 
64 /**
65  * __save_processor_state() - Save CPU registers before creating a
66  *                             hibernation image and before restoring
67  *                             the memory state from it
68  * @ctxt: Structure to store the registers contents in.
69  *
70  * NOTE: If there is a CPU register the modification of which by the
71  * boot kernel (ie. the kernel used for loading the hibernation image)
72  * might affect the operations of the restored target kernel (ie. the one
73  * saved in the hibernation image), then its contents must be saved by this
74  * function.  In other words, if kernel A is hibernated and different
75  * kernel B is used for loading the hibernation image into memory, the
76  * kernel A's __save_processor_state() function must save all registers
77  * needed by kernel A, so that it can operate correctly after the resume
78  * regardless of what kernel B does in the meantime.
79  */
__save_processor_state(struct saved_context * ctxt)80 static void __save_processor_state(struct saved_context *ctxt)
81 {
82 #ifdef CONFIG_X86_32
83 	mtrr_save_fixed_ranges(NULL);
84 #endif
85 	kernel_fpu_begin();
86 
87 	/*
88 	 * descriptor tables
89 	 */
90 	store_idt(&ctxt->idt);
91 
92 	/*
93 	 * We save it here, but restore it only in the hibernate case.
94 	 * For ACPI S3 resume, this is loaded via 'early_gdt_desc' in 64-bit
95 	 * mode in "secondary_startup_64". In 32-bit mode it is done via
96 	 * 'pmode_gdt' in wakeup_start.
97 	 */
98 	ctxt->gdt_desc.size = GDT_SIZE - 1;
99 	ctxt->gdt_desc.address = (unsigned long)get_cpu_gdt_rw(smp_processor_id());
100 
101 	store_tr(ctxt->tr);
102 
103 	/* XMM0..XMM15 should be handled by kernel_fpu_begin(). */
104 	/*
105 	 * segment registers
106 	 */
107 	savesegment(gs, ctxt->gs);
108 #ifdef CONFIG_X86_64
109 	savesegment(fs, ctxt->fs);
110 	savesegment(ds, ctxt->ds);
111 	savesegment(es, ctxt->es);
112 
113 	rdmsrl(MSR_FS_BASE, ctxt->fs_base);
114 	rdmsrl(MSR_GS_BASE, ctxt->kernelmode_gs_base);
115 	rdmsrl(MSR_KERNEL_GS_BASE, ctxt->usermode_gs_base);
116 	mtrr_save_fixed_ranges(NULL);
117 
118 	rdmsrl(MSR_EFER, ctxt->efer);
119 #endif
120 
121 	/*
122 	 * control registers
123 	 */
124 	ctxt->cr0 = read_cr0();
125 	ctxt->cr2 = read_cr2();
126 	ctxt->cr3 = __read_cr3();
127 	ctxt->cr4 = __read_cr4();
128 	ctxt->misc_enable_saved = !rdmsrl_safe(MSR_IA32_MISC_ENABLE,
129 					       &ctxt->misc_enable);
130 	msr_save_context(ctxt);
131 }
132 
133 /* Needed by apm.c */
save_processor_state(void)134 void save_processor_state(void)
135 {
136 	__save_processor_state(&saved_context);
137 	x86_platform.save_sched_clock_state();
138 }
139 #ifdef CONFIG_X86_32
140 EXPORT_SYMBOL(save_processor_state);
141 #endif
142 
do_fpu_end(void)143 static void do_fpu_end(void)
144 {
145 	/*
146 	 * Restore FPU regs if necessary.
147 	 */
148 	kernel_fpu_end();
149 }
150 
fix_processor_context(void)151 static void fix_processor_context(void)
152 {
153 	int cpu = smp_processor_id();
154 #ifdef CONFIG_X86_64
155 	struct desc_struct *desc = get_cpu_gdt_rw(cpu);
156 	tss_desc tss;
157 #endif
158 
159 	/*
160 	 * We need to reload TR, which requires that we change the
161 	 * GDT entry to indicate "available" first.
162 	 *
163 	 * XXX: This could probably all be replaced by a call to
164 	 * force_reload_TR().
165 	 */
166 	set_tss_desc(cpu, &get_cpu_entry_area(cpu)->tss.x86_tss);
167 
168 #ifdef CONFIG_X86_64
169 	memcpy(&tss, &desc[GDT_ENTRY_TSS], sizeof(tss_desc));
170 	tss.type = 0x9; /* The available 64-bit TSS (see AMD vol 2, pg 91 */
171 	write_gdt_entry(desc, GDT_ENTRY_TSS, &tss, DESC_TSS);
172 
173 	syscall_init();				/* This sets MSR_*STAR and related */
174 #else
175 	if (boot_cpu_has(X86_FEATURE_SEP))
176 		enable_sep_cpu();
177 #endif
178 	load_TR_desc();				/* This does ltr */
179 	load_mm_ldt(current->active_mm);	/* This does lldt */
180 	initialize_tlbstate_and_flush();
181 
182 	fpu__resume_cpu();
183 
184 	/* The processor is back on the direct GDT, load back the fixmap */
185 	load_fixmap_gdt(cpu);
186 }
187 
188 /**
189  * __restore_processor_state() - Restore the contents of CPU registers saved
190  *                               by __save_processor_state()
191  * @ctxt: Structure to load the registers contents from.
192  *
193  * The asm code that gets us here will have restored a usable GDT, although
194  * it will be pointing to the wrong alias.
195  */
__restore_processor_state(struct saved_context * ctxt)196 static void notrace __restore_processor_state(struct saved_context *ctxt)
197 {
198 	struct cpuinfo_x86 *c;
199 
200 	if (ctxt->misc_enable_saved)
201 		wrmsrl(MSR_IA32_MISC_ENABLE, ctxt->misc_enable);
202 	/*
203 	 * control registers
204 	 */
205 	/* cr4 was introduced in the Pentium CPU */
206 #ifdef CONFIG_X86_32
207 	if (ctxt->cr4)
208 		__write_cr4(ctxt->cr4);
209 #else
210 /* CONFIG X86_64 */
211 	wrmsrl(MSR_EFER, ctxt->efer);
212 	__write_cr4(ctxt->cr4);
213 #endif
214 	write_cr3(ctxt->cr3);
215 	write_cr2(ctxt->cr2);
216 	write_cr0(ctxt->cr0);
217 
218 	/* Restore the IDT. */
219 	load_idt(&ctxt->idt);
220 
221 	/*
222 	 * Just in case the asm code got us here with the SS, DS, or ES
223 	 * out of sync with the GDT, update them.
224 	 */
225 	loadsegment(ss, __KERNEL_DS);
226 	loadsegment(ds, __USER_DS);
227 	loadsegment(es, __USER_DS);
228 
229 	/*
230 	 * Restore percpu access.  Percpu access can happen in exception
231 	 * handlers or in complicated helpers like load_gs_index().
232 	 */
233 #ifdef CONFIG_X86_64
234 	wrmsrl(MSR_GS_BASE, ctxt->kernelmode_gs_base);
235 
236 	/*
237 	 * Reinitialize FRED to ensure the FRED MSRs contain the same values
238 	 * as before hibernation.
239 	 *
240 	 * Note, the setup of FRED RSPs requires access to percpu data
241 	 * structures.  Therefore, FRED reinitialization can only occur after
242 	 * the percpu access pointer (i.e., MSR_GS_BASE) is restored.
243 	 */
244 	if (ctxt->cr4 & X86_CR4_FRED) {
245 		cpu_init_fred_exceptions();
246 		cpu_init_fred_rsps();
247 	}
248 #else
249 	loadsegment(fs, __KERNEL_PERCPU);
250 #endif
251 
252 	/* Restore the TSS, RO GDT, LDT, and usermode-relevant MSRs. */
253 	fix_processor_context();
254 
255 	/*
256 	 * Now that we have descriptor tables fully restored and working
257 	 * exception handling, restore the usermode segments.
258 	 */
259 #ifdef CONFIG_X86_64
260 	loadsegment(ds, ctxt->es);
261 	loadsegment(es, ctxt->es);
262 	loadsegment(fs, ctxt->fs);
263 	load_gs_index(ctxt->gs);
264 
265 	/*
266 	 * Restore FSBASE and GSBASE after restoring the selectors, since
267 	 * restoring the selectors clobbers the bases.  Keep in mind
268 	 * that MSR_KERNEL_GS_BASE is horribly misnamed.
269 	 */
270 	wrmsrl(MSR_FS_BASE, ctxt->fs_base);
271 	wrmsrl(MSR_KERNEL_GS_BASE, ctxt->usermode_gs_base);
272 #else
273 	loadsegment(gs, ctxt->gs);
274 #endif
275 
276 	do_fpu_end();
277 	tsc_verify_tsc_adjust(true);
278 	x86_platform.restore_sched_clock_state();
279 	cache_bp_restore();
280 	perf_restore_debug_store();
281 
282 	c = &cpu_data(smp_processor_id());
283 	if (cpu_has(c, X86_FEATURE_MSR_IA32_FEAT_CTL))
284 		init_ia32_feat_ctl(c);
285 
286 	microcode_bsp_resume();
287 
288 	/*
289 	 * This needs to happen after the microcode has been updated upon resume
290 	 * because some of the MSRs are "emulated" in microcode.
291 	 */
292 	msr_restore_context(ctxt);
293 }
294 
295 /* Needed by apm.c */
restore_processor_state(void)296 void notrace restore_processor_state(void)
297 {
298 	__restore_processor_state(&saved_context);
299 }
300 #ifdef CONFIG_X86_32
301 EXPORT_SYMBOL(restore_processor_state);
302 #endif
303 
304 #if defined(CONFIG_HIBERNATION) && defined(CONFIG_HOTPLUG_CPU)
resume_play_dead(void)305 static void __noreturn resume_play_dead(void)
306 {
307 	play_dead_common();
308 	tboot_shutdown(TB_SHUTDOWN_WFS);
309 	hlt_play_dead();
310 }
311 
hibernate_resume_nonboot_cpu_disable(void)312 int hibernate_resume_nonboot_cpu_disable(void)
313 {
314 	void (*play_dead)(void) = smp_ops.play_dead;
315 	int ret;
316 
317 	/*
318 	 * Ensure that MONITOR/MWAIT will not be used in the "play dead" loop
319 	 * during hibernate image restoration, because it is likely that the
320 	 * monitored address will be actually written to at that time and then
321 	 * the "dead" CPU will attempt to execute instructions again, but the
322 	 * address in its instruction pointer may not be possible to resolve
323 	 * any more at that point (the page tables used by it previously may
324 	 * have been overwritten by hibernate image data).
325 	 *
326 	 * First, make sure that we wake up all the potentially disabled SMT
327 	 * threads which have been initially brought up and then put into
328 	 * mwait/cpuidle sleep.
329 	 * Those will be put to proper (not interfering with hibernation
330 	 * resume) sleep afterwards, and the resumed kernel will decide itself
331 	 * what to do with them.
332 	 */
333 	ret = cpuhp_smt_enable();
334 	if (ret)
335 		return ret;
336 	smp_ops.play_dead = resume_play_dead;
337 	ret = freeze_secondary_cpus(0);
338 	smp_ops.play_dead = play_dead;
339 	return ret;
340 }
341 #endif
342 
343 /*
344  * When bsp_check() is called in hibernate and suspend, cpu hotplug
345  * is disabled already. So it's unnecessary to handle race condition between
346  * cpumask query and cpu hotplug.
347  */
bsp_check(void)348 static int bsp_check(void)
349 {
350 	if (cpumask_first(cpu_online_mask) != 0) {
351 		pr_warn("CPU0 is offline.\n");
352 		return -ENODEV;
353 	}
354 
355 	return 0;
356 }
357 
bsp_pm_callback(struct notifier_block * nb,unsigned long action,void * ptr)358 static int bsp_pm_callback(struct notifier_block *nb, unsigned long action,
359 			   void *ptr)
360 {
361 	int ret = 0;
362 
363 	switch (action) {
364 	case PM_SUSPEND_PREPARE:
365 	case PM_HIBERNATION_PREPARE:
366 		ret = bsp_check();
367 		break;
368 	default:
369 		break;
370 	}
371 	return notifier_from_errno(ret);
372 }
373 
bsp_pm_check_init(void)374 static int __init bsp_pm_check_init(void)
375 {
376 	/*
377 	 * Set this bsp_pm_callback as lower priority than
378 	 * cpu_hotplug_pm_callback. So cpu_hotplug_pm_callback will be called
379 	 * earlier to disable cpu hotplug before bsp online check.
380 	 */
381 	pm_notifier(bsp_pm_callback, -INT_MAX);
382 	return 0;
383 }
384 
385 core_initcall(bsp_pm_check_init);
386 
msr_build_context(const u32 * msr_id,const int num)387 static int msr_build_context(const u32 *msr_id, const int num)
388 {
389 	struct saved_msrs *saved_msrs = &saved_context.saved_msrs;
390 	struct saved_msr *msr_array;
391 	int total_num;
392 	int i, j;
393 
394 	total_num = saved_msrs->num + num;
395 
396 	msr_array = kmalloc_array(total_num, sizeof(struct saved_msr), GFP_KERNEL);
397 	if (!msr_array) {
398 		pr_err("x86/pm: Can not allocate memory to save/restore MSRs during suspend.\n");
399 		return -ENOMEM;
400 	}
401 
402 	if (saved_msrs->array) {
403 		/*
404 		 * Multiple callbacks can invoke this function, so copy any
405 		 * MSR save requests from previous invocations.
406 		 */
407 		memcpy(msr_array, saved_msrs->array,
408 		       sizeof(struct saved_msr) * saved_msrs->num);
409 
410 		kfree(saved_msrs->array);
411 	}
412 
413 	for (i = saved_msrs->num, j = 0; i < total_num; i++, j++) {
414 		u64 dummy;
415 
416 		msr_array[i].info.msr_no	= msr_id[j];
417 		msr_array[i].valid		= !rdmsrl_safe(msr_id[j], &dummy);
418 		msr_array[i].info.reg.q		= 0;
419 	}
420 	saved_msrs->num   = total_num;
421 	saved_msrs->array = msr_array;
422 
423 	return 0;
424 }
425 
426 /*
427  * The following sections are a quirk framework for problematic BIOSen:
428  * Sometimes MSRs are modified by the BIOSen after suspended to
429  * RAM, this might cause unexpected behavior after wakeup.
430  * Thus we save/restore these specified MSRs across suspend/resume
431  * in order to work around it.
432  *
433  * For any further problematic BIOSen/platforms,
434  * please add your own function similar to msr_initialize_bdw.
435  */
msr_initialize_bdw(const struct dmi_system_id * d)436 static int msr_initialize_bdw(const struct dmi_system_id *d)
437 {
438 	/* Add any extra MSR ids into this array. */
439 	u32 bdw_msr_id[] = { MSR_IA32_THERM_CONTROL };
440 
441 	pr_info("x86/pm: %s detected, MSR saving is needed during suspending.\n", d->ident);
442 	return msr_build_context(bdw_msr_id, ARRAY_SIZE(bdw_msr_id));
443 }
444 
445 static const struct dmi_system_id msr_save_dmi_table[] = {
446 	{
447 	 .callback = msr_initialize_bdw,
448 	 .ident = "BROADWELL BDX_EP",
449 	 .matches = {
450 		DMI_MATCH(DMI_PRODUCT_NAME, "GRANTLEY"),
451 		DMI_MATCH(DMI_PRODUCT_VERSION, "E63448-400"),
452 		},
453 	},
454 	{}
455 };
456 
msr_save_cpuid_features(const struct x86_cpu_id * c)457 static int msr_save_cpuid_features(const struct x86_cpu_id *c)
458 {
459 	u32 cpuid_msr_id[] = {
460 		MSR_AMD64_CPUID_FN_1,
461 	};
462 
463 	pr_info("x86/pm: family %#hx cpu detected, MSR saving is needed during suspending.\n",
464 		c->family);
465 
466 	return msr_build_context(cpuid_msr_id, ARRAY_SIZE(cpuid_msr_id));
467 }
468 
469 static const struct x86_cpu_id msr_save_cpu_table[] = {
470 	X86_MATCH_VENDOR_FAM(AMD, 0x15, &msr_save_cpuid_features),
471 	X86_MATCH_VENDOR_FAM(AMD, 0x16, &msr_save_cpuid_features),
472 	{}
473 };
474 
475 typedef int (*pm_cpu_match_t)(const struct x86_cpu_id *);
pm_cpu_check(const struct x86_cpu_id * c)476 static int pm_cpu_check(const struct x86_cpu_id *c)
477 {
478 	const struct x86_cpu_id *m;
479 	int ret = 0;
480 
481 	m = x86_match_cpu(msr_save_cpu_table);
482 	if (m) {
483 		pm_cpu_match_t fn;
484 
485 		fn = (pm_cpu_match_t)m->driver_data;
486 		ret = fn(m);
487 	}
488 
489 	return ret;
490 }
491 
pm_save_spec_msr(void)492 static void pm_save_spec_msr(void)
493 {
494 	struct msr_enumeration {
495 		u32 msr_no;
496 		u32 feature;
497 	} msr_enum[] = {
498 		{ MSR_IA32_SPEC_CTRL,	 X86_FEATURE_MSR_SPEC_CTRL },
499 		{ MSR_IA32_TSX_CTRL,	 X86_FEATURE_MSR_TSX_CTRL },
500 		{ MSR_TSX_FORCE_ABORT,	 X86_FEATURE_TSX_FORCE_ABORT },
501 		{ MSR_IA32_MCU_OPT_CTRL, X86_FEATURE_SRBDS_CTRL },
502 		{ MSR_AMD64_LS_CFG,	 X86_FEATURE_LS_CFG_SSBD },
503 		{ MSR_AMD64_DE_CFG,	 X86_FEATURE_LFENCE_RDTSC },
504 	};
505 	int i;
506 
507 	for (i = 0; i < ARRAY_SIZE(msr_enum); i++) {
508 		if (boot_cpu_has(msr_enum[i].feature))
509 			msr_build_context(&msr_enum[i].msr_no, 1);
510 	}
511 }
512 
pm_check_save_msr(void)513 static int pm_check_save_msr(void)
514 {
515 	dmi_check_system(msr_save_dmi_table);
516 	pm_cpu_check(msr_save_cpu_table);
517 	pm_save_spec_msr();
518 
519 	return 0;
520 }
521 
522 device_initcall(pm_check_save_msr);
523