xref: /linux/arch/x86/kernel/nmi.c (revision 889dd44491b37c890b1b4ef40876cf19032ca897)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  *  Copyright (C) 1991, 1992  Linus Torvalds
4  *  Copyright (C) 2000, 2001, 2002 Andi Kleen, SuSE Labs
5  *  Copyright (C) 2011	Don Zickus Red Hat, Inc.
6  *
7  *  Pentium III FXSR, SSE support
8  *	Gareth Hughes <gareth@valinux.com>, May 2000
9  */
10 
11 /*
12  * Handle hardware traps and faults.
13  */
14 #include <linux/spinlock.h>
15 #include <linux/kprobes.h>
16 #include <linux/kdebug.h>
17 #include <linux/sched/debug.h>
18 #include <linux/nmi.h>
19 #include <linux/debugfs.h>
20 #include <linux/delay.h>
21 #include <linux/hardirq.h>
22 #include <linux/ratelimit.h>
23 #include <linux/slab.h>
24 #include <linux/export.h>
25 #include <linux/atomic.h>
26 #include <linux/sched/clock.h>
27 #include <linux/kvm_types.h>
28 
29 #include <asm/cpu_entry_area.h>
30 #include <asm/traps.h>
31 #include <asm/mach_traps.h>
32 #include <asm/nmi.h>
33 #include <asm/x86_init.h>
34 #include <asm/reboot.h>
35 #include <asm/cache.h>
36 #include <asm/nospec-branch.h>
37 #include <asm/microcode.h>
38 #include <asm/sev.h>
39 #include <asm/fred.h>
40 
41 #define CREATE_TRACE_POINTS
42 #include <trace/events/nmi.h>
43 
44 /*
45  * An emergency handler can be set in any context including NMI
46  */
47 struct nmi_desc {
48 	raw_spinlock_t lock;
49 	nmi_handler_t emerg_handler;
50 	struct list_head head;
51 };
52 
53 #define NMI_DESC_INIT(type) { \
54 	.lock = __RAW_SPIN_LOCK_UNLOCKED(&nmi_desc[type].lock), \
55 	.head = LIST_HEAD_INIT(nmi_desc[type].head), \
56 }
57 
58 static struct nmi_desc nmi_desc[NMI_MAX] = {
59 	NMI_DESC_INIT(NMI_LOCAL),
60 	NMI_DESC_INIT(NMI_UNKNOWN),
61 	NMI_DESC_INIT(NMI_SERR),
62 	NMI_DESC_INIT(NMI_IO_CHECK),
63 };
64 
65 #define nmi_to_desc(type) (&nmi_desc[type])
66 
67 struct nmi_stats {
68 	unsigned int normal;
69 	unsigned int unknown;
70 	unsigned int external;
71 	unsigned int swallow;
72 	unsigned long recv_jiffies;
73 	unsigned long idt_seq;
74 	unsigned long idt_nmi_seq;
75 	unsigned long idt_ignored;
76 	atomic_long_t idt_calls;
77 	unsigned long idt_seq_snap;
78 	unsigned long idt_nmi_seq_snap;
79 	unsigned long idt_ignored_snap;
80 	long idt_calls_snap;
81 };
82 
83 static DEFINE_PER_CPU(struct nmi_stats, nmi_stats);
84 
85 static int ignore_nmis __read_mostly;
86 
87 int unknown_nmi_panic;
88 int panic_on_unrecovered_nmi;
89 int panic_on_io_nmi;
90 
91 /*
92  * Prevent NMI reason port (0x61) being accessed simultaneously, can
93  * only be used in NMI handler.
94  */
95 static DEFINE_RAW_SPINLOCK(nmi_reason_lock);
96 
97 static int __init setup_unknown_nmi_panic(char *str)
98 {
99 	unknown_nmi_panic = 1;
100 	return 1;
101 }
102 __setup("unknown_nmi_panic", setup_unknown_nmi_panic);
103 
104 static u64 nmi_longest_ns = 1 * NSEC_PER_MSEC;
105 
106 static int __init nmi_warning_debugfs(void)
107 {
108 	debugfs_create_u64("nmi_longest_ns", 0644,
109 			arch_debugfs_dir, &nmi_longest_ns);
110 	return 0;
111 }
112 fs_initcall(nmi_warning_debugfs);
113 
114 static void nmi_check_duration(struct nmiaction *action, u64 duration)
115 {
116 	int remainder_ns, decimal_msecs;
117 
118 	/* sched_clock() went backwards? */
119 	if ((s64)duration < 0) {
120 		pr_warn_once("NMI handler (%ps): sched_clock() went backwards by %lld ns on CPU%d\n",
121 			     action->handler, -(s64)duration,
122 			     smp_processor_id());
123 		return;
124 	}
125 
126 	if (duration < nmi_longest_ns || duration < action->max_duration)
127 		return;
128 
129 	action->max_duration = duration;
130 
131 	/* Convert duration from nsec to msec */
132 	remainder_ns = do_div(duration, NSEC_PER_MSEC);
133 	decimal_msecs = remainder_ns / NSEC_PER_USEC;
134 
135 	pr_info_ratelimited("INFO: NMI handler (%ps) took too long to run: %lld.%03d msecs\n",
136 			    action->handler, duration, decimal_msecs);
137 }
138 
139 static int nmi_handle(unsigned int type, struct pt_regs *regs)
140 {
141 	struct nmi_desc *desc = nmi_to_desc(type);
142 	nmi_handler_t ehandler;
143 	struct nmiaction *a;
144 	int handled=0;
145 
146 	/*
147 	 * Call the emergency handler, if set
148 	 *
149 	 * In the case of crash_nmi_callback() emergency handler, it will
150 	 * return in the case of the crashing CPU to enable it to complete
151 	 * other necessary crashing actions ASAP. Other handlers in the
152 	 * linked list won't need to be run.
153 	 */
154 	ehandler = desc->emerg_handler;
155 	if (ehandler)
156 		return ehandler(type, regs);
157 
158 	rcu_read_lock();
159 
160 	/*
161 	 * NMIs are edge-triggered, which means if you have enough
162 	 * of them concurrently, you can lose some because only one
163 	 * can be latched at any given time.  Walk the whole list
164 	 * to handle those situations.
165 	 */
166 	list_for_each_entry_rcu(a, &desc->head, list) {
167 		int thishandled;
168 		u64 delta;
169 
170 		delta = sched_clock();
171 		thishandled = a->handler(type, regs);
172 		handled += thishandled;
173 		delta = sched_clock() - delta;
174 		trace_nmi_handler(a->handler, (int)delta, thishandled);
175 
176 		nmi_check_duration(a, delta);
177 	}
178 
179 	rcu_read_unlock();
180 
181 	/* return total number of NMI events handled */
182 	return handled;
183 }
184 NOKPROBE_SYMBOL(nmi_handle);
185 
186 int __register_nmi_handler(unsigned int type, struct nmiaction *action)
187 {
188 	struct nmi_desc *desc = nmi_to_desc(type);
189 	unsigned long flags;
190 
191 	if (WARN_ON_ONCE(!action->handler || !list_empty(&action->list)))
192 		return -EINVAL;
193 
194 	raw_spin_lock_irqsave(&desc->lock, flags);
195 
196 	/*
197 	 * Indicate if there are multiple registrations on the
198 	 * internal NMI handler call chains (SERR and IO_CHECK).
199 	 */
200 	WARN_ON_ONCE(type == NMI_SERR && !list_empty(&desc->head));
201 	WARN_ON_ONCE(type == NMI_IO_CHECK && !list_empty(&desc->head));
202 
203 	/*
204 	 * some handlers need to be executed first otherwise a fake
205 	 * event confuses some handlers (kdump uses this flag)
206 	 */
207 	if (action->flags & NMI_FLAG_FIRST)
208 		list_add_rcu(&action->list, &desc->head);
209 	else
210 		list_add_tail_rcu(&action->list, &desc->head);
211 
212 	raw_spin_unlock_irqrestore(&desc->lock, flags);
213 	return 0;
214 }
215 EXPORT_SYMBOL(__register_nmi_handler);
216 
217 void unregister_nmi_handler(unsigned int type, const char *name)
218 {
219 	struct nmi_desc *desc = nmi_to_desc(type);
220 	struct nmiaction *n, *found = NULL;
221 	unsigned long flags;
222 
223 	raw_spin_lock_irqsave(&desc->lock, flags);
224 
225 	list_for_each_entry_rcu(n, &desc->head, list) {
226 		/*
227 		 * the name passed in to describe the nmi handler
228 		 * is used as the lookup key
229 		 */
230 		if (!strcmp(n->name, name)) {
231 			WARN(in_nmi(),
232 				"Trying to free NMI (%s) from NMI context!\n", n->name);
233 			list_del_rcu(&n->list);
234 			found = n;
235 			break;
236 		}
237 	}
238 
239 	raw_spin_unlock_irqrestore(&desc->lock, flags);
240 	if (found) {
241 		synchronize_rcu();
242 		INIT_LIST_HEAD(&found->list);
243 	}
244 }
245 EXPORT_SYMBOL_GPL(unregister_nmi_handler);
246 
247 /**
248  * set_emergency_nmi_handler - Set emergency handler
249  * @type:    NMI type
250  * @handler: the emergency handler to be stored
251  *
252  * Set an emergency NMI handler which, if set, will preempt all the other
253  * handlers in the linked list. If a NULL handler is passed in, it will clear
254  * it. It is expected that concurrent calls to this function will not happen
255  * or the system is screwed beyond repair.
256  */
257 void set_emergency_nmi_handler(unsigned int type, nmi_handler_t handler)
258 {
259 	struct nmi_desc *desc = nmi_to_desc(type);
260 
261 	if (WARN_ON_ONCE(desc->emerg_handler == handler))
262 		return;
263 	desc->emerg_handler = handler;
264 
265 	/*
266 	 * Ensure the emergency handler is visible to other CPUs before
267 	 * function return
268 	 */
269 	smp_wmb();
270 }
271 
272 static void
273 pci_serr_error(unsigned char reason, struct pt_regs *regs)
274 {
275 	/* check to see if anyone registered against these types of errors */
276 	if (nmi_handle(NMI_SERR, regs))
277 		return;
278 
279 	pr_emerg("NMI: PCI system error (SERR) for reason %02x on CPU %d.\n",
280 		 reason, smp_processor_id());
281 
282 	if (panic_on_unrecovered_nmi)
283 		nmi_panic(regs, "NMI: Not continuing");
284 
285 	pr_emerg("Dazed and confused, but trying to continue\n");
286 
287 	/* Clear and disable the PCI SERR error line. */
288 	reason = (reason & NMI_REASON_CLEAR_MASK) | NMI_REASON_CLEAR_SERR;
289 	outb(reason, NMI_REASON_PORT);
290 }
291 NOKPROBE_SYMBOL(pci_serr_error);
292 
293 static void
294 io_check_error(unsigned char reason, struct pt_regs *regs)
295 {
296 	unsigned long i;
297 
298 	/* check to see if anyone registered against these types of errors */
299 	if (nmi_handle(NMI_IO_CHECK, regs))
300 		return;
301 
302 	pr_emerg(
303 	"NMI: IOCK error (debug interrupt?) for reason %02x on CPU %d.\n",
304 		 reason, smp_processor_id());
305 	show_regs(regs);
306 
307 	if (panic_on_io_nmi) {
308 		nmi_panic(regs, "NMI IOCK error: Not continuing");
309 
310 		/*
311 		 * If we end up here, it means we have received an NMI while
312 		 * processing panic(). Simply return without delaying and
313 		 * re-enabling NMIs.
314 		 */
315 		return;
316 	}
317 
318 	/* Re-enable the IOCK line, wait for a few seconds */
319 	reason = (reason & NMI_REASON_CLEAR_MASK) | NMI_REASON_CLEAR_IOCHK;
320 	outb(reason, NMI_REASON_PORT);
321 
322 	i = 20000;
323 	while (--i) {
324 		touch_nmi_watchdog();
325 		udelay(100);
326 	}
327 
328 	reason &= ~NMI_REASON_CLEAR_IOCHK;
329 	outb(reason, NMI_REASON_PORT);
330 }
331 NOKPROBE_SYMBOL(io_check_error);
332 
333 static void
334 unknown_nmi_error(unsigned char reason, struct pt_regs *regs)
335 {
336 	int handled;
337 
338 	/*
339 	 * As a last resort, let the "unknown" handlers make a
340 	 * best-effort attempt to figure out if they can claim
341 	 * responsibility for this Unknown NMI.
342 	 */
343 	handled = nmi_handle(NMI_UNKNOWN, regs);
344 	if (handled) {
345 		__this_cpu_add(nmi_stats.unknown, handled);
346 		return;
347 	}
348 
349 	__this_cpu_add(nmi_stats.unknown, 1);
350 
351 	pr_emerg_ratelimited("Uhhuh. NMI received for unknown reason %02x on CPU %d.\n",
352 			     reason, smp_processor_id());
353 
354 	if (unknown_nmi_panic || panic_on_unrecovered_nmi)
355 		nmi_panic(regs, "NMI: Not continuing");
356 
357 	pr_emerg_ratelimited("Dazed and confused, but trying to continue\n");
358 }
359 NOKPROBE_SYMBOL(unknown_nmi_error);
360 
361 static DEFINE_PER_CPU(bool, swallow_nmi);
362 static DEFINE_PER_CPU(unsigned long, last_nmi_rip);
363 
364 static noinstr void default_do_nmi(struct pt_regs *regs)
365 {
366 	unsigned char reason = 0;
367 	int handled;
368 	bool b2b = false;
369 
370 	/*
371 	 * Back-to-back NMIs are detected by comparing the RIP of the
372 	 * current NMI with that of the previous NMI. If it is the same,
373 	 * it is assumed that the CPU did not have a chance to jump back
374 	 * into a non-NMI context and execute code in between the two
375 	 * NMIs.
376 	 *
377 	 * They are interesting because even if there are more than two,
378 	 * only a maximum of two can be detected (anything over two is
379 	 * dropped due to NMI being edge-triggered). If this is the
380 	 * second half of the back-to-back NMI, assume we dropped things
381 	 * and process more handlers. Otherwise, reset the 'swallow' NMI
382 	 * behavior.
383 	 */
384 	if (regs->ip == __this_cpu_read(last_nmi_rip))
385 		b2b = true;
386 	else
387 		__this_cpu_write(swallow_nmi, false);
388 
389 	__this_cpu_write(last_nmi_rip, regs->ip);
390 
391 	instrumentation_begin();
392 
393 	if (microcode_nmi_handler_enabled() && microcode_nmi_handler())
394 		goto out;
395 
396 	/*
397 	 * CPU-specific NMI must be processed before non-CPU-specific
398 	 * NMI, otherwise we may lose it, because the CPU-specific
399 	 * NMI can not be detected/processed on other CPUs.
400 	 */
401 	handled = nmi_handle(NMI_LOCAL, regs);
402 	__this_cpu_add(nmi_stats.normal, handled);
403 	if (handled) {
404 		/*
405 		 * There are cases when a NMI handler handles multiple
406 		 * events in the current NMI.  One of these events may
407 		 * be queued for in the next NMI.  Because the event is
408 		 * already handled, the next NMI will result in an unknown
409 		 * NMI.  Instead lets flag this for a potential NMI to
410 		 * swallow.
411 		 */
412 		if (handled > 1)
413 			__this_cpu_write(swallow_nmi, true);
414 		goto out;
415 	}
416 
417 	/*
418 	 * Non-CPU-specific NMI: NMI sources can be processed on any CPU.
419 	 *
420 	 * Another CPU may be processing panic routines while holding
421 	 * nmi_reason_lock. Check if the CPU issued the IPI for crash dumping,
422 	 * and if so, call its callback directly.  If there is no CPU preparing
423 	 * crash dump, we simply loop here.
424 	 */
425 	while (!raw_spin_trylock(&nmi_reason_lock)) {
426 		run_crash_ipi_callback(regs);
427 		cpu_relax();
428 	}
429 
430 	reason = x86_platform.get_nmi_reason();
431 
432 	if (reason & NMI_REASON_MASK) {
433 		if (reason & NMI_REASON_SERR)
434 			pci_serr_error(reason, regs);
435 		else if (reason & NMI_REASON_IOCHK)
436 			io_check_error(reason, regs);
437 
438 		/*
439 		 * Reassert NMI in case it became active
440 		 * meanwhile as it's edge-triggered:
441 		 */
442 		if (IS_ENABLED(CONFIG_X86_32))
443 			reassert_nmi();
444 
445 		__this_cpu_add(nmi_stats.external, 1);
446 		raw_spin_unlock(&nmi_reason_lock);
447 		goto out;
448 	}
449 	raw_spin_unlock(&nmi_reason_lock);
450 
451 	/*
452 	 * Only one NMI can be latched at a time.  To handle
453 	 * this we may process multiple nmi handlers at once to
454 	 * cover the case where an NMI is dropped.  The downside
455 	 * to this approach is we may process an NMI prematurely,
456 	 * while its real NMI is sitting latched.  This will cause
457 	 * an unknown NMI on the next run of the NMI processing.
458 	 *
459 	 * We tried to flag that condition above, by setting the
460 	 * swallow_nmi flag when we process more than one event.
461 	 * This condition is also only present on the second half
462 	 * of a back-to-back NMI, so we flag that condition too.
463 	 *
464 	 * If both are true, we assume we already processed this
465 	 * NMI previously and we swallow it.  Otherwise we reset
466 	 * the logic.
467 	 *
468 	 * There are scenarios where we may accidentally swallow
469 	 * a 'real' unknown NMI.  For example, while processing
470 	 * a perf NMI another perf NMI comes in along with a
471 	 * 'real' unknown NMI.  These two NMIs get combined into
472 	 * one (as described above).  When the next NMI gets
473 	 * processed, it will be flagged by perf as handled, but
474 	 * no one will know that there was a 'real' unknown NMI sent
475 	 * also.  As a result it gets swallowed.  Or if the first
476 	 * perf NMI returns two events handled then the second
477 	 * NMI will get eaten by the logic below, again losing a
478 	 * 'real' unknown NMI.  But this is the best we can do
479 	 * for now.
480 	 */
481 	if (b2b && __this_cpu_read(swallow_nmi))
482 		__this_cpu_add(nmi_stats.swallow, 1);
483 	else
484 		unknown_nmi_error(reason, regs);
485 
486 out:
487 	instrumentation_end();
488 }
489 
490 /*
491  * NMIs can page fault or hit breakpoints which will cause it to lose
492  * its NMI context with the CPU when the breakpoint or page fault does an IRET.
493  *
494  * As a result, NMIs can nest if NMIs get unmasked due an IRET during
495  * NMI processing.  On x86_64, the asm glue protects us from nested NMIs
496  * if the outer NMI came from kernel mode, but we can still nest if the
497  * outer NMI came from user mode.
498  *
499  * To handle these nested NMIs, we have three states:
500  *
501  *  1) not running
502  *  2) executing
503  *  3) latched
504  *
505  * When no NMI is in progress, it is in the "not running" state.
506  * When an NMI comes in, it goes into the "executing" state.
507  * Normally, if another NMI is triggered, it does not interrupt
508  * the running NMI and the HW will simply latch it so that when
509  * the first NMI finishes, it will restart the second NMI.
510  * (Note, the latch is binary, thus multiple NMIs triggering,
511  *  when one is running, are ignored. Only one NMI is restarted.)
512  *
513  * If an NMI executes an iret, another NMI can preempt it. We do not
514  * want to allow this new NMI to run, but we want to execute it when the
515  * first one finishes.  We set the state to "latched", and the exit of
516  * the first NMI will perform a dec_return, if the result is zero
517  * (NOT_RUNNING), then it will simply exit the NMI handler. If not, the
518  * dec_return would have set the state to NMI_EXECUTING (what we want it
519  * to be when we are running). In this case, we simply jump back to
520  * rerun the NMI handler again, and restart the 'latched' NMI.
521  *
522  * No trap (breakpoint or page fault) should be hit before nmi_restart,
523  * thus there is no race between the first check of state for NOT_RUNNING
524  * and setting it to NMI_EXECUTING. The HW will prevent nested NMIs
525  * at this point.
526  *
527  * In case the NMI takes a page fault, we need to save off the CR2
528  * because the NMI could have preempted another page fault and corrupt
529  * the CR2 that is about to be read. As nested NMIs must be restarted
530  * and they can not take breakpoints or page faults, the update of the
531  * CR2 must be done before converting the nmi state back to NOT_RUNNING.
532  * Otherwise, there would be a race of another nested NMI coming in
533  * after setting state to NOT_RUNNING but before updating the nmi_cr2.
534  */
535 enum nmi_states {
536 	NMI_NOT_RUNNING = 0,
537 	NMI_EXECUTING,
538 	NMI_LATCHED,
539 };
540 static DEFINE_PER_CPU(enum nmi_states, nmi_state);
541 static DEFINE_PER_CPU(unsigned long, nmi_cr2);
542 static DEFINE_PER_CPU(unsigned long, nmi_dr7);
543 
544 DEFINE_IDTENTRY_RAW(exc_nmi)
545 {
546 	irqentry_state_t irq_state;
547 	struct nmi_stats *nsp = this_cpu_ptr(&nmi_stats);
548 
549 	/*
550 	 * Re-enable NMIs right here when running as an SEV-ES guest. This might
551 	 * cause nested NMIs, but those can be handled safely.
552 	 */
553 	sev_es_nmi_complete();
554 	if (IS_ENABLED(CONFIG_NMI_CHECK_CPU))
555 		raw_atomic_long_inc(&nsp->idt_calls);
556 
557 	if (arch_cpu_is_offline(smp_processor_id())) {
558 		if (microcode_nmi_handler_enabled())
559 			microcode_offline_nmi_handler();
560 		return;
561 	}
562 
563 	if (this_cpu_read(nmi_state) != NMI_NOT_RUNNING) {
564 		this_cpu_write(nmi_state, NMI_LATCHED);
565 		return;
566 	}
567 	this_cpu_write(nmi_state, NMI_EXECUTING);
568 	this_cpu_write(nmi_cr2, read_cr2());
569 
570 nmi_restart:
571 	if (IS_ENABLED(CONFIG_NMI_CHECK_CPU)) {
572 		WRITE_ONCE(nsp->idt_seq, nsp->idt_seq + 1);
573 		WARN_ON_ONCE(!(nsp->idt_seq & 0x1));
574 		WRITE_ONCE(nsp->recv_jiffies, jiffies);
575 	}
576 
577 	/*
578 	 * Needs to happen before DR7 is accessed, because the hypervisor can
579 	 * intercept DR7 reads/writes, turning those into #VC exceptions.
580 	 */
581 	sev_es_ist_enter(regs);
582 
583 	this_cpu_write(nmi_dr7, local_db_save());
584 
585 	irq_state = irqentry_nmi_enter(regs);
586 
587 	inc_irq_stat(NMI);
588 
589 	if (IS_ENABLED(CONFIG_NMI_CHECK_CPU) && ignore_nmis) {
590 		WRITE_ONCE(nsp->idt_ignored, nsp->idt_ignored + 1);
591 	} else if (!ignore_nmis) {
592 		if (IS_ENABLED(CONFIG_NMI_CHECK_CPU)) {
593 			WRITE_ONCE(nsp->idt_nmi_seq, nsp->idt_nmi_seq + 1);
594 			WARN_ON_ONCE(!(nsp->idt_nmi_seq & 0x1));
595 		}
596 		default_do_nmi(regs);
597 		if (IS_ENABLED(CONFIG_NMI_CHECK_CPU)) {
598 			WRITE_ONCE(nsp->idt_nmi_seq, nsp->idt_nmi_seq + 1);
599 			WARN_ON_ONCE(nsp->idt_nmi_seq & 0x1);
600 		}
601 	}
602 
603 	irqentry_nmi_exit(regs, irq_state);
604 
605 	local_db_restore(this_cpu_read(nmi_dr7));
606 
607 	sev_es_ist_exit();
608 
609 	if (unlikely(this_cpu_read(nmi_cr2) != read_cr2()))
610 		write_cr2(this_cpu_read(nmi_cr2));
611 	if (IS_ENABLED(CONFIG_NMI_CHECK_CPU)) {
612 		WRITE_ONCE(nsp->idt_seq, nsp->idt_seq + 1);
613 		WARN_ON_ONCE(nsp->idt_seq & 0x1);
614 		WRITE_ONCE(nsp->recv_jiffies, jiffies);
615 	}
616 	if (this_cpu_dec_return(nmi_state))
617 		goto nmi_restart;
618 }
619 
620 #if IS_ENABLED(CONFIG_KVM_INTEL)
621 DEFINE_IDTENTRY_RAW(exc_nmi_kvm_vmx)
622 {
623 	exc_nmi(regs);
624 }
625 #endif
626 
627 #ifdef CONFIG_NMI_CHECK_CPU
628 
629 static char *nmi_check_stall_msg[] = {
630 /*									*/
631 /* +--------- nmi_seq & 0x1: CPU is currently in NMI handler.		*/
632 /* | +------ cpu_is_offline(cpu)					*/
633 /* | | +--- nsp->idt_calls_snap != atomic_long_read(&nsp->idt_calls):	*/
634 /* | | |	NMI handler has been invoked.				*/
635 /* | | |								*/
636 /* V V V								*/
637 /* 0 0 0 */ "NMIs are not reaching exc_nmi() handler",
638 /* 0 0 1 */ "exc_nmi() handler is ignoring NMIs",
639 /* 0 1 0 */ "CPU is offline and NMIs are not reaching exc_nmi() handler",
640 /* 0 1 1 */ "CPU is offline and exc_nmi() handler is legitimately ignoring NMIs",
641 /* 1 0 0 */ "CPU is in exc_nmi() handler and no further NMIs are reaching handler",
642 /* 1 0 1 */ "CPU is in exc_nmi() handler which is legitimately ignoring NMIs",
643 /* 1 1 0 */ "CPU is offline in exc_nmi() handler and no more NMIs are reaching exc_nmi() handler",
644 /* 1 1 1 */ "CPU is offline in exc_nmi() handler which is legitimately ignoring NMIs",
645 };
646 
647 void nmi_backtrace_stall_snap(const struct cpumask *btp)
648 {
649 	int cpu;
650 	struct nmi_stats *nsp;
651 
652 	for_each_cpu(cpu, btp) {
653 		nsp = per_cpu_ptr(&nmi_stats, cpu);
654 		nsp->idt_seq_snap = READ_ONCE(nsp->idt_seq);
655 		nsp->idt_nmi_seq_snap = READ_ONCE(nsp->idt_nmi_seq);
656 		nsp->idt_ignored_snap = READ_ONCE(nsp->idt_ignored);
657 		nsp->idt_calls_snap = atomic_long_read(&nsp->idt_calls);
658 	}
659 }
660 
661 void nmi_backtrace_stall_check(const struct cpumask *btp)
662 {
663 	int cpu;
664 	int idx;
665 	unsigned long nmi_seq;
666 	unsigned long j = jiffies;
667 	char *modp;
668 	char *msgp;
669 	char *msghp;
670 	struct nmi_stats *nsp;
671 
672 	for_each_cpu(cpu, btp) {
673 		nsp = per_cpu_ptr(&nmi_stats, cpu);
674 		modp = "";
675 		msghp = "";
676 		nmi_seq = READ_ONCE(nsp->idt_nmi_seq);
677 		if (nsp->idt_nmi_seq_snap + 1 == nmi_seq && (nmi_seq & 0x1)) {
678 			msgp = "CPU entered NMI handler function, but has not exited";
679 		} else if (nsp->idt_nmi_seq_snap == nmi_seq ||
680 			   nsp->idt_nmi_seq_snap + 1 == nmi_seq) {
681 			idx = ((nmi_seq & 0x1) << 2) |
682 			      (cpu_is_offline(cpu) << 1) |
683 			      (nsp->idt_calls_snap != atomic_long_read(&nsp->idt_calls));
684 			msgp = nmi_check_stall_msg[idx];
685 			if (nsp->idt_ignored_snap != READ_ONCE(nsp->idt_ignored) && (idx & 0x1))
686 				modp = ", but OK because ignore_nmis was set";
687 			if (nsp->idt_nmi_seq_snap + 1 == nmi_seq)
688 				msghp = " (CPU exited one NMI handler function)";
689 			else if (nmi_seq & 0x1)
690 				msghp = " (CPU currently in NMI handler function)";
691 			else
692 				msghp = " (CPU was never in an NMI handler function)";
693 		} else {
694 			msgp = "CPU is handling NMIs";
695 		}
696 		pr_alert("%s: CPU %d: %s%s%s\n", __func__, cpu, msgp, modp, msghp);
697 		pr_alert("%s: last activity: %lu jiffies ago.\n",
698 			 __func__, j - READ_ONCE(nsp->recv_jiffies));
699 	}
700 }
701 
702 #endif
703 
704 #ifdef CONFIG_X86_FRED
705 /*
706  * With FRED, CR2/DR6 is pushed to #PF/#DB stack frame during FRED
707  * event delivery, i.e., there is no problem of transient states.
708  * And NMI unblocking only happens when the stack frame indicates
709  * that so should happen.
710  *
711  * Thus, the NMI entry stub for FRED is really straightforward and
712  * as simple as most exception handlers. As such, #DB is allowed
713  * during NMI handling.
714  */
715 DEFINE_FREDENTRY_NMI(exc_nmi)
716 {
717 	irqentry_state_t irq_state;
718 
719 	if (arch_cpu_is_offline(smp_processor_id())) {
720 		if (microcode_nmi_handler_enabled())
721 			microcode_offline_nmi_handler();
722 		return;
723 	}
724 
725 	/*
726 	 * Save CR2 for eventual restore to cover the case where the NMI
727 	 * hits the VMENTER/VMEXIT region where guest CR2 is life. This
728 	 * prevents guest state corruption in case that the NMI handler
729 	 * takes a page fault.
730 	 */
731 	this_cpu_write(nmi_cr2, read_cr2());
732 
733 	irq_state = irqentry_nmi_enter(regs);
734 
735 	inc_irq_stat(NMI);
736 	default_do_nmi(regs);
737 
738 	irqentry_nmi_exit(regs, irq_state);
739 
740 	if (unlikely(this_cpu_read(nmi_cr2) != read_cr2()))
741 		write_cr2(this_cpu_read(nmi_cr2));
742 }
743 #endif
744 
745 void stop_nmi(void)
746 {
747 	ignore_nmis++;
748 }
749 
750 void restart_nmi(void)
751 {
752 	ignore_nmis--;
753 }
754 
755 /* reset the back-to-back NMI logic */
756 void local_touch_nmi(void)
757 {
758 	__this_cpu_write(last_nmi_rip, 0);
759 }
760