Linux Audio

Check our new training course

Loading...
v5.4
  1// SPDX-License-Identifier: GPL-2.0-only
  2/*
  3 * crash.c - kernel crash support code.
  4 * Copyright (C) 2002-2004 Eric Biederman  <ebiederm@xmission.com>
  5 */
  6
  7#include <linux/crash_core.h>
 
 
 
  8#include <linux/utsname.h>
  9#include <linux/vmalloc.h>
 
 
 
 
 
 
 
 
 
 
 
 10
 11#include <asm/page.h>
 12#include <asm/sections.h>
 13
 14/* vmcoreinfo stuff */
 15unsigned char *vmcoreinfo_data;
 16size_t vmcoreinfo_size;
 17u32 *vmcoreinfo_note;
 18
 19/* trusted vmcoreinfo, e.g. we can make a copy in the crash memory */
 20static unsigned char *vmcoreinfo_data_safecopy;
 21
 22/*
 23 * parsing the "crashkernel" commandline
 24 *
 25 * this code is intended to be called from architecture specific code
 26 */
 27
 28
 29/*
 30 * This function parses command lines in the format
 31 *
 32 *   crashkernel=ramsize-range:size[,...][@offset]
 33 *
 34 * The function returns 0 on success and -EINVAL on failure.
 35 */
 36static int __init parse_crashkernel_mem(char *cmdline,
 37					unsigned long long system_ram,
 38					unsigned long long *crash_size,
 39					unsigned long long *crash_base)
 40{
 41	char *cur = cmdline, *tmp;
 42
 43	/* for each entry of the comma-separated list */
 44	do {
 45		unsigned long long start, end = ULLONG_MAX, size;
 46
 47		/* get the start of the range */
 48		start = memparse(cur, &tmp);
 49		if (cur == tmp) {
 50			pr_warn("crashkernel: Memory value expected\n");
 51			return -EINVAL;
 52		}
 53		cur = tmp;
 54		if (*cur != '-') {
 55			pr_warn("crashkernel: '-' expected\n");
 56			return -EINVAL;
 57		}
 58		cur++;
 59
 60		/* if no ':' is here, than we read the end */
 61		if (*cur != ':') {
 62			end = memparse(cur, &tmp);
 63			if (cur == tmp) {
 64				pr_warn("crashkernel: Memory value expected\n");
 65				return -EINVAL;
 66			}
 67			cur = tmp;
 68			if (end <= start) {
 69				pr_warn("crashkernel: end <= start\n");
 70				return -EINVAL;
 71			}
 72		}
 73
 74		if (*cur != ':') {
 75			pr_warn("crashkernel: ':' expected\n");
 76			return -EINVAL;
 77		}
 78		cur++;
 79
 80		size = memparse(cur, &tmp);
 81		if (cur == tmp) {
 82			pr_warn("Memory value expected\n");
 83			return -EINVAL;
 84		}
 85		cur = tmp;
 86		if (size >= system_ram) {
 87			pr_warn("crashkernel: invalid size\n");
 88			return -EINVAL;
 89		}
 90
 91		/* match ? */
 92		if (system_ram >= start && system_ram < end) {
 93			*crash_size = size;
 94			break;
 95		}
 96	} while (*cur++ == ',');
 
 
 
 
 
 
 
 
 
 
 
 
 
 97
 98	if (*crash_size > 0) {
 99		while (*cur && *cur != ' ' && *cur != '@')
100			cur++;
101		if (*cur == '@') {
102			cur++;
103			*crash_base = memparse(cur, &tmp);
104			if (cur == tmp) {
105				pr_warn("Memory value expected after '@'\n");
106				return -EINVAL;
107			}
108		}
109	} else
110		pr_info("crashkernel size resulted in zero bytes\n");
111
112	return 0;
113}
114
115/*
116 * That function parses "simple" (old) crashkernel command lines like
117 *
118 *	crashkernel=size[@offset]
119 *
120 * It returns 0 on success and -EINVAL on failure.
121 */
122static int __init parse_crashkernel_simple(char *cmdline,
123					   unsigned long long *crash_size,
124					   unsigned long long *crash_base)
125{
126	char *cur = cmdline;
127
128	*crash_size = memparse(cmdline, &cur);
129	if (cmdline == cur) {
130		pr_warn("crashkernel: memory value expected\n");
131		return -EINVAL;
132	}
133
134	if (*cur == '@')
135		*crash_base = memparse(cur+1, &cur);
136	else if (*cur != ' ' && *cur != '\0') {
137		pr_warn("crashkernel: unrecognized char: %c\n", *cur);
138		return -EINVAL;
139	}
140
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
141	return 0;
142}
143
144#define SUFFIX_HIGH 0
145#define SUFFIX_LOW  1
146#define SUFFIX_NULL 2
147static __initdata char *suffix_tbl[] = {
148	[SUFFIX_HIGH] = ",high",
149	[SUFFIX_LOW]  = ",low",
150	[SUFFIX_NULL] = NULL,
151};
152
153/*
154 * That function parses "suffix"  crashkernel command lines like
155 *
156 *	crashkernel=size,[high|low]
157 *
158 * It returns 0 on success and -EINVAL on failure.
159 */
160static int __init parse_crashkernel_suffix(char *cmdline,
161					   unsigned long long	*crash_size,
162					   const char *suffix)
163{
164	char *cur = cmdline;
165
166	*crash_size = memparse(cmdline, &cur);
167	if (cmdline == cur) {
168		pr_warn("crashkernel: memory value expected\n");
169		return -EINVAL;
170	}
171
172	/* check with suffix */
173	if (strncmp(cur, suffix, strlen(suffix))) {
174		pr_warn("crashkernel: unrecognized char: %c\n", *cur);
175		return -EINVAL;
176	}
177	cur += strlen(suffix);
178	if (*cur != ' ' && *cur != '\0') {
179		pr_warn("crashkernel: unrecognized char: %c\n", *cur);
180		return -EINVAL;
181	}
182
183	return 0;
184}
 
185
186static __init char *get_last_crashkernel(char *cmdline,
187			     const char *name,
188			     const char *suffix)
189{
190	char *p = cmdline, *ck_cmdline = NULL;
191
192	/* find crashkernel and use the last one if there are more */
193	p = strstr(p, name);
194	while (p) {
195		char *end_p = strchr(p, ' ');
196		char *q;
197
198		if (!end_p)
199			end_p = p + strlen(p);
200
201		if (!suffix) {
202			int i;
203
204			/* skip the one with any known suffix */
205			for (i = 0; suffix_tbl[i]; i++) {
206				q = end_p - strlen(suffix_tbl[i]);
207				if (!strncmp(q, suffix_tbl[i],
208					     strlen(suffix_tbl[i])))
209					goto next;
210			}
211			ck_cmdline = p;
212		} else {
213			q = end_p - strlen(suffix);
214			if (!strncmp(q, suffix, strlen(suffix)))
215				ck_cmdline = p;
216		}
217next:
218		p = strstr(p+1, name);
219	}
220
221	if (!ck_cmdline)
222		return NULL;
 
 
 
 
 
223
224	return ck_cmdline;
 
 
 
 
 
 
 
 
 
225}
226
227static int __init __parse_crashkernel(char *cmdline,
228			     unsigned long long system_ram,
229			     unsigned long long *crash_size,
230			     unsigned long long *crash_base,
231			     const char *name,
232			     const char *suffix)
233{
234	char	*first_colon, *first_space;
235	char	*ck_cmdline;
 
236
237	BUG_ON(!crash_size || !crash_base);
238	*crash_size = 0;
239	*crash_base = 0;
240
241	ck_cmdline = get_last_crashkernel(cmdline, name, suffix);
242
243	if (!ck_cmdline)
244		return -EINVAL;
 
 
 
 
 
 
 
 
245
246	ck_cmdline += strlen(name);
 
 
247
248	if (suffix)
249		return parse_crashkernel_suffix(ck_cmdline, crash_size,
250				suffix);
251	/*
252	 * if the commandline contains a ':', then that's the extended
253	 * syntax -- if not, it must be the classic syntax
 
 
 
254	 */
255	first_colon = strchr(ck_cmdline, ':');
256	first_space = strchr(ck_cmdline, ' ');
257	if (first_colon && (!first_space || first_colon < first_space))
258		return parse_crashkernel_mem(ck_cmdline, system_ram,
259				crash_size, crash_base);
260
261	return parse_crashkernel_simple(ck_cmdline, crash_size, crash_base);
262}
 
263
264/*
265 * That function is the entry point for command line parsing and should be
266 * called from the arch-specific code.
267 */
268int __init parse_crashkernel(char *cmdline,
269			     unsigned long long system_ram,
270			     unsigned long long *crash_size,
271			     unsigned long long *crash_base)
272{
273	return __parse_crashkernel(cmdline, system_ram, crash_size, crash_base,
274					"crashkernel=", NULL);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
275}
276
277int __init parse_crashkernel_high(char *cmdline,
278			     unsigned long long system_ram,
279			     unsigned long long *crash_size,
280			     unsigned long long *crash_base)
281{
282	return __parse_crashkernel(cmdline, system_ram, crash_size, crash_base,
283				"crashkernel=", suffix_tbl[SUFFIX_HIGH]);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
284}
285
286int __init parse_crashkernel_low(char *cmdline,
287			     unsigned long long system_ram,
288			     unsigned long long *crash_size,
289			     unsigned long long *crash_base)
290{
291	return __parse_crashkernel(cmdline, system_ram, crash_size, crash_base,
292				"crashkernel=", suffix_tbl[SUFFIX_LOW]);
 
 
 
 
 
 
 
 
293}
294
295Elf_Word *append_elf_note(Elf_Word *buf, char *name, unsigned int type,
296			  void *data, size_t data_len)
297{
298	struct elf_note *note = (struct elf_note *)buf;
299
300	note->n_namesz = strlen(name) + 1;
301	note->n_descsz = data_len;
302	note->n_type   = type;
303	buf += DIV_ROUND_UP(sizeof(*note), sizeof(Elf_Word));
304	memcpy(buf, name, note->n_namesz);
305	buf += DIV_ROUND_UP(note->n_namesz, sizeof(Elf_Word));
306	memcpy(buf, data, data_len);
307	buf += DIV_ROUND_UP(data_len, sizeof(Elf_Word));
 
 
 
 
 
 
 
 
308
309	return buf;
 
 
 
310}
311
312void final_note(Elf_Word *buf)
313{
314	memset(buf, 0, sizeof(struct elf_note));
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
315}
316
317static void update_vmcoreinfo_note(void)
318{
319	u32 *buf = vmcoreinfo_note;
 
320
321	if (!vmcoreinfo_size)
322		return;
323	buf = append_elf_note(buf, VMCOREINFO_NOTE_NAME, 0, vmcoreinfo_data,
324			      vmcoreinfo_size);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
325	final_note(buf);
326}
327
328void crash_update_vmcoreinfo_safecopy(void *ptr)
329{
330	if (ptr)
331		memcpy(ptr, vmcoreinfo_data, vmcoreinfo_size);
332
333	vmcoreinfo_data_safecopy = ptr;
334}
335
336void crash_save_vmcoreinfo(void)
337{
338	if (!vmcoreinfo_note)
339		return;
 
 
 
 
 
 
 
 
 
 
 
 
 
340
341	/* Use the safe copy to generate vmcoreinfo note if have */
342	if (vmcoreinfo_data_safecopy)
343		vmcoreinfo_data = vmcoreinfo_data_safecopy;
 
 
344
345	vmcoreinfo_append_str("CRASHTIME=%lld\n", ktime_get_real_seconds());
346	update_vmcoreinfo_note();
 
 
 
 
347}
 
348
349void vmcoreinfo_append_str(const char *fmt, ...)
350{
351	va_list args;
352	char buf[0x50];
353	size_t r;
354
355	va_start(args, fmt);
356	r = vscnprintf(buf, sizeof(buf), fmt, args);
357	va_end(args);
358
359	r = min(r, (size_t)VMCOREINFO_BYTES - vmcoreinfo_size);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
360
361	memcpy(&vmcoreinfo_data[vmcoreinfo_size], buf, r);
 
 
 
 
 
 
 
 
 
 
 
 
 
362
363	vmcoreinfo_size += r;
364}
365
366/*
367 * provide an empty default implementation here -- architecture
368 * code may override this
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
369 */
370void __weak arch_crash_save_vmcoreinfo(void)
371{}
372
373phys_addr_t __weak paddr_vmcoreinfo_note(void)
374{
375	return __pa(vmcoreinfo_note);
376}
377EXPORT_SYMBOL(paddr_vmcoreinfo_note);
378
379static int __init crash_save_vmcoreinfo_init(void)
380{
381	vmcoreinfo_data = (unsigned char *)get_zeroed_page(GFP_KERNEL);
382	if (!vmcoreinfo_data) {
383		pr_warn("Memory allocation for vmcoreinfo_data failed\n");
384		return -ENOMEM;
 
385	}
386
387	vmcoreinfo_note = alloc_pages_exact(VMCOREINFO_NOTE_SIZE,
388						GFP_KERNEL | __GFP_ZERO);
389	if (!vmcoreinfo_note) {
390		free_page((unsigned long)vmcoreinfo_data);
391		vmcoreinfo_data = NULL;
392		pr_warn("Memory allocation for vmcoreinfo_note failed\n");
393		return -ENOMEM;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
394	}
395
396	VMCOREINFO_OSRELEASE(init_uts_ns.name.release);
397	VMCOREINFO_PAGESIZE(PAGE_SIZE);
 
 
398
399	VMCOREINFO_SYMBOL(init_uts_ns);
400	VMCOREINFO_SYMBOL(node_online_map);
401#ifdef CONFIG_MMU
402	VMCOREINFO_SYMBOL_ARRAY(swapper_pg_dir);
403#endif
404	VMCOREINFO_SYMBOL(_stext);
405	VMCOREINFO_SYMBOL(vmap_area_list);
406
407#ifndef CONFIG_NEED_MULTIPLE_NODES
408	VMCOREINFO_SYMBOL(mem_map);
409	VMCOREINFO_SYMBOL(contig_page_data);
410#endif
411#ifdef CONFIG_SPARSEMEM
412	VMCOREINFO_SYMBOL_ARRAY(mem_section);
413	VMCOREINFO_LENGTH(mem_section, NR_SECTION_ROOTS);
414	VMCOREINFO_STRUCT_SIZE(mem_section);
415	VMCOREINFO_OFFSET(mem_section, section_mem_map);
416#endif
417	VMCOREINFO_STRUCT_SIZE(page);
418	VMCOREINFO_STRUCT_SIZE(pglist_data);
419	VMCOREINFO_STRUCT_SIZE(zone);
420	VMCOREINFO_STRUCT_SIZE(free_area);
421	VMCOREINFO_STRUCT_SIZE(list_head);
422	VMCOREINFO_SIZE(nodemask_t);
423	VMCOREINFO_OFFSET(page, flags);
424	VMCOREINFO_OFFSET(page, _refcount);
425	VMCOREINFO_OFFSET(page, mapping);
426	VMCOREINFO_OFFSET(page, lru);
427	VMCOREINFO_OFFSET(page, _mapcount);
428	VMCOREINFO_OFFSET(page, private);
429	VMCOREINFO_OFFSET(page, compound_dtor);
430	VMCOREINFO_OFFSET(page, compound_order);
431	VMCOREINFO_OFFSET(page, compound_head);
432	VMCOREINFO_OFFSET(pglist_data, node_zones);
433	VMCOREINFO_OFFSET(pglist_data, nr_zones);
434#ifdef CONFIG_FLAT_NODE_MEM_MAP
435	VMCOREINFO_OFFSET(pglist_data, node_mem_map);
436#endif
437	VMCOREINFO_OFFSET(pglist_data, node_start_pfn);
438	VMCOREINFO_OFFSET(pglist_data, node_spanned_pages);
439	VMCOREINFO_OFFSET(pglist_data, node_id);
440	VMCOREINFO_OFFSET(zone, free_area);
441	VMCOREINFO_OFFSET(zone, vm_stat);
442	VMCOREINFO_OFFSET(zone, spanned_pages);
443	VMCOREINFO_OFFSET(free_area, free_list);
444	VMCOREINFO_OFFSET(list_head, next);
445	VMCOREINFO_OFFSET(list_head, prev);
446	VMCOREINFO_OFFSET(vmap_area, va_start);
447	VMCOREINFO_OFFSET(vmap_area, list);
448	VMCOREINFO_LENGTH(zone.free_area, MAX_ORDER);
449	log_buf_vmcoreinfo_setup();
450	VMCOREINFO_LENGTH(free_area.free_list, MIGRATE_TYPES);
451	VMCOREINFO_NUMBER(NR_FREE_PAGES);
452	VMCOREINFO_NUMBER(PG_lru);
453	VMCOREINFO_NUMBER(PG_private);
454	VMCOREINFO_NUMBER(PG_swapcache);
455	VMCOREINFO_NUMBER(PG_swapbacked);
456	VMCOREINFO_NUMBER(PG_slab);
457#ifdef CONFIG_MEMORY_FAILURE
458	VMCOREINFO_NUMBER(PG_hwpoison);
459#endif
460	VMCOREINFO_NUMBER(PG_head_mask);
461#define PAGE_BUDDY_MAPCOUNT_VALUE	(~PG_buddy)
462	VMCOREINFO_NUMBER(PAGE_BUDDY_MAPCOUNT_VALUE);
463#ifdef CONFIG_HUGETLB_PAGE
464	VMCOREINFO_NUMBER(HUGETLB_PAGE_DTOR);
465#define PAGE_OFFLINE_MAPCOUNT_VALUE	(~PG_offline)
466	VMCOREINFO_NUMBER(PAGE_OFFLINE_MAPCOUNT_VALUE);
467#endif
468
469	arch_crash_save_vmcoreinfo();
470	update_vmcoreinfo_note();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
471
 
 
 
 
 
 
 
 
472	return 0;
473}
474
475subsys_initcall(crash_save_vmcoreinfo_init);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
v6.13.7
  1// SPDX-License-Identifier: GPL-2.0-only
  2/*
  3 * crash.c - kernel crash support code.
  4 * Copyright (C) 2002-2004 Eric Biederman  <ebiederm@xmission.com>
  5 */
  6
  7#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
  8
  9#include <linux/buildid.h>
 10#include <linux/init.h>
 11#include <linux/utsname.h>
 12#include <linux/vmalloc.h>
 13#include <linux/sizes.h>
 14#include <linux/kexec.h>
 15#include <linux/memory.h>
 16#include <linux/mm.h>
 17#include <linux/cpuhotplug.h>
 18#include <linux/memblock.h>
 19#include <linux/kmemleak.h>
 20#include <linux/crash_core.h>
 21#include <linux/reboot.h>
 22#include <linux/btf.h>
 23#include <linux/objtool.h>
 24
 25#include <asm/page.h>
 26#include <asm/sections.h>
 27
 28#include <crypto/sha1.h>
 
 
 
 29
 30#include "kallsyms_internal.h"
 31#include "kexec_internal.h"
 32
 33/* Per cpu memory for storing cpu states in case of system crash. */
 34note_buf_t __percpu *crash_notes;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 35
 36#ifdef CONFIG_CRASH_DUMP
 
 
 
 
 
 
 
 
 
 
 
 
 37
 38int kimage_crash_copy_vmcoreinfo(struct kimage *image)
 39{
 40	struct page *vmcoreinfo_page;
 41	void *safecopy;
 
 42
 43	if (!IS_ENABLED(CONFIG_CRASH_DUMP))
 44		return 0;
 45	if (image->type != KEXEC_TYPE_CRASH)
 46		return 0;
 
 
 
 
 
 
 47
 48	/*
 49	 * For kdump, allocate one vmcoreinfo safe copy from the
 50	 * crash memory. as we have arch_kexec_protect_crashkres()
 51	 * after kexec syscall, we naturally protect it from write
 52	 * (even read) access under kernel direct mapping. But on
 53	 * the other hand, we still need to operate it when crash
 54	 * happens to generate vmcoreinfo note, hereby we rely on
 55	 * vmap for this purpose.
 56	 */
 57	vmcoreinfo_page = kimage_alloc_control_pages(image, 0);
 58	if (!vmcoreinfo_page) {
 59		pr_warn("Could not allocate vmcoreinfo buffer\n");
 60		return -ENOMEM;
 61	}
 62	safecopy = vmap(&vmcoreinfo_page, 1, VM_MAP, PAGE_KERNEL);
 63	if (!safecopy) {
 64		pr_warn("Could not vmap vmcoreinfo buffer\n");
 65		return -ENOMEM;
 66	}
 67
 68	image->vmcoreinfo_data_copy = safecopy;
 69	crash_update_vmcoreinfo_safecopy(safecopy);
 
 
 
 
 
 
 
 
 
 
 
 70
 71	return 0;
 72}
 73
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 74
 75
 76int kexec_should_crash(struct task_struct *p)
 77{
 78	/*
 79	 * If crash_kexec_post_notifiers is enabled, don't run
 80	 * crash_kexec() here yet, which must be run after panic
 81	 * notifiers in panic().
 82	 */
 83	if (crash_kexec_post_notifiers)
 84		return 0;
 85	/*
 86	 * There are 4 panic() calls in make_task_dead() path, each of which
 87	 * corresponds to each of these 4 conditions.
 88	 */
 89	if (in_interrupt() || !p->pid || is_global_init(p) || panic_on_oops)
 90		return 1;
 91	return 0;
 92}
 93
 94int kexec_crash_loaded(void)
 95{
 96	return !!kexec_crash_image;
 97}
 98EXPORT_SYMBOL_GPL(kexec_crash_loaded);
 
 
 
 99
100/*
101 * No panic_cpu check version of crash_kexec().  This function is called
102 * only when panic_cpu holds the current CPU number; this is the only CPU
103 * which processes crash_kexec routines.
 
 
104 */
105void __noclone __crash_kexec(struct pt_regs *regs)
106{
107	/* Take the kexec_lock here to prevent sys_kexec_load
108	 * running on one cpu from replacing the crash kernel
109	 * we are using after a panic on a different cpu.
110	 *
111	 * If the crash kernel was not located in a fixed area
112	 * of memory the xchg(&kexec_crash_image) would be
113	 * sufficient.  But since I reuse the memory...
114	 */
115	if (kexec_trylock()) {
116		if (kexec_crash_image) {
117			struct pt_regs fixed_regs;
118
119			crash_setup_regs(&fixed_regs, regs);
120			crash_save_vmcoreinfo();
121			machine_crash_shutdown(&fixed_regs);
122			machine_kexec(kexec_crash_image);
123		}
124		kexec_unlock();
 
125	}
 
 
126}
127STACK_FRAME_NON_STANDARD(__crash_kexec);
128
129__bpf_kfunc void crash_kexec(struct pt_regs *regs)
130{
131	int old_cpu, this_cpu;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
132
133	/*
134	 * Only one CPU is allowed to execute the crash_kexec() code as with
135	 * panic().  Otherwise parallel calls of panic() and crash_kexec()
136	 * may stop each other.  To exclude them, we use panic_cpu here too.
137	 */
138	old_cpu = PANIC_CPU_INVALID;
139	this_cpu = raw_smp_processor_id();
140
141	if (atomic_try_cmpxchg(&panic_cpu, &old_cpu, this_cpu)) {
142		/* This is the 1st CPU which comes here, so go ahead. */
143		__crash_kexec(regs);
144
145		/*
146		 * Reset panic_cpu to allow another panic()/crash_kexec()
147		 * call.
148		 */
149		atomic_set(&panic_cpu, PANIC_CPU_INVALID);
150	}
151}
152
153static inline resource_size_t crash_resource_size(const struct resource *res)
 
 
 
 
 
154{
155	return !res->end ? 0 : resource_size(res);
156}
157
158
 
 
 
159
 
160
161int crash_prepare_elf64_headers(struct crash_mem *mem, int need_kernel_map,
162			  void **addr, unsigned long *sz)
163{
164	Elf64_Ehdr *ehdr;
165	Elf64_Phdr *phdr;
166	unsigned long nr_cpus = num_possible_cpus(), nr_phdr, elf_sz;
167	unsigned char *buf;
168	unsigned int cpu, i;
169	unsigned long long notes_addr;
170	unsigned long mstart, mend;
171
172	/* extra phdr for vmcoreinfo ELF note */
173	nr_phdr = nr_cpus + 1;
174	nr_phdr += mem->nr_ranges;
175
 
 
 
176	/*
177	 * kexec-tools creates an extra PT_LOAD phdr for kernel text mapping
178	 * area (for example, ffffffff80000000 - ffffffffa0000000 on x86_64).
179	 * I think this is required by tools like gdb. So same physical
180	 * memory will be mapped in two ELF headers. One will contain kernel
181	 * text virtual addresses and other will have __va(physical) addresses.
182	 */
 
 
 
 
 
183
184	nr_phdr++;
185	elf_sz = sizeof(Elf64_Ehdr) + nr_phdr * sizeof(Elf64_Phdr);
186	elf_sz = ALIGN(elf_sz, ELF_CORE_HEADER_ALIGN);
187
188	buf = vzalloc(elf_sz);
189	if (!buf)
190		return -ENOMEM;
191
192	ehdr = (Elf64_Ehdr *)buf;
193	phdr = (Elf64_Phdr *)(ehdr + 1);
194	memcpy(ehdr->e_ident, ELFMAG, SELFMAG);
195	ehdr->e_ident[EI_CLASS] = ELFCLASS64;
196	ehdr->e_ident[EI_DATA] = ELFDATA2LSB;
197	ehdr->e_ident[EI_VERSION] = EV_CURRENT;
198	ehdr->e_ident[EI_OSABI] = ELF_OSABI;
199	memset(ehdr->e_ident + EI_PAD, 0, EI_NIDENT - EI_PAD);
200	ehdr->e_type = ET_CORE;
201	ehdr->e_machine = ELF_ARCH;
202	ehdr->e_version = EV_CURRENT;
203	ehdr->e_phoff = sizeof(Elf64_Ehdr);
204	ehdr->e_ehsize = sizeof(Elf64_Ehdr);
205	ehdr->e_phentsize = sizeof(Elf64_Phdr);
206
207	/* Prepare one phdr of type PT_NOTE for each possible CPU */
208	for_each_possible_cpu(cpu) {
209		phdr->p_type = PT_NOTE;
210		notes_addr = per_cpu_ptr_to_phys(per_cpu_ptr(crash_notes, cpu));
211		phdr->p_offset = phdr->p_paddr = notes_addr;
212		phdr->p_filesz = phdr->p_memsz = sizeof(note_buf_t);
213		(ehdr->e_phnum)++;
214		phdr++;
215	}
216
217	/* Prepare one PT_NOTE header for vmcoreinfo */
218	phdr->p_type = PT_NOTE;
219	phdr->p_offset = phdr->p_paddr = paddr_vmcoreinfo_note();
220	phdr->p_filesz = phdr->p_memsz = VMCOREINFO_NOTE_SIZE;
221	(ehdr->e_phnum)++;
222	phdr++;
223
224	/* Prepare PT_LOAD type program header for kernel text region */
225	if (need_kernel_map) {
226		phdr->p_type = PT_LOAD;
227		phdr->p_flags = PF_R|PF_W|PF_X;
228		phdr->p_vaddr = (unsigned long) _text;
229		phdr->p_filesz = phdr->p_memsz = _end - _text;
230		phdr->p_offset = phdr->p_paddr = __pa_symbol(_text);
231		ehdr->e_phnum++;
232		phdr++;
233	}
234
235	/* Go through all the ranges in mem->ranges[] and prepare phdr */
236	for (i = 0; i < mem->nr_ranges; i++) {
237		mstart = mem->ranges[i].start;
238		mend = mem->ranges[i].end;
239
240		phdr->p_type = PT_LOAD;
241		phdr->p_flags = PF_R|PF_W|PF_X;
242		phdr->p_offset  = mstart;
243
244		phdr->p_paddr = mstart;
245		phdr->p_vaddr = (unsigned long) __va(mstart);
246		phdr->p_filesz = phdr->p_memsz = mend - mstart + 1;
247		phdr->p_align = 0;
248		ehdr->e_phnum++;
249#ifdef CONFIG_KEXEC_FILE
250		kexec_dprintk("Crash PT_LOAD ELF header. phdr=%p vaddr=0x%llx, paddr=0x%llx, sz=0x%llx e_phnum=%d p_offset=0x%llx\n",
251			      phdr, phdr->p_vaddr, phdr->p_paddr, phdr->p_filesz,
252			      ehdr->e_phnum, phdr->p_offset);
253#endif
254		phdr++;
255	}
256
257	*addr = buf;
258	*sz = elf_sz;
259	return 0;
260}
261
262int crash_exclude_mem_range(struct crash_mem *mem,
263			    unsigned long long mstart, unsigned long long mend)
 
 
264{
265	int i;
266	unsigned long long start, end, p_start, p_end;
267
268	for (i = 0; i < mem->nr_ranges; i++) {
269		start = mem->ranges[i].start;
270		end = mem->ranges[i].end;
271		p_start = mstart;
272		p_end = mend;
273
274		if (p_start > end)
275			continue;
276
277		/*
278		 * Because the memory ranges in mem->ranges are stored in
279		 * ascending order, when we detect `p_end < start`, we can
280		 * immediately exit the for loop, as the subsequent memory
281		 * ranges will definitely be outside the range we are looking
282		 * for.
283		 */
284		if (p_end < start)
285			break;
286
287		/* Truncate any area outside of range */
288		if (p_start < start)
289			p_start = start;
290		if (p_end > end)
291			p_end = end;
292
293		/* Found completely overlapping range */
294		if (p_start == start && p_end == end) {
295			memmove(&mem->ranges[i], &mem->ranges[i + 1],
296				(mem->nr_ranges - (i + 1)) * sizeof(mem->ranges[i]));
297			i--;
298			mem->nr_ranges--;
299		} else if (p_start > start && p_end < end) {
300			/* Split original range */
301			if (mem->nr_ranges >= mem->max_nr_ranges)
302				return -ENOMEM;
303
304			memmove(&mem->ranges[i + 2], &mem->ranges[i + 1],
305				(mem->nr_ranges - (i + 1)) * sizeof(mem->ranges[i]));
306
307			mem->ranges[i].end = p_start - 1;
308			mem->ranges[i + 1].start = p_end + 1;
309			mem->ranges[i + 1].end = end;
310
311			i++;
312			mem->nr_ranges++;
313		} else if (p_start != start)
314			mem->ranges[i].end = p_start - 1;
315		else
316			mem->ranges[i].start = p_end + 1;
317	}
318
319	return 0;
320}
321
322ssize_t crash_get_memory_size(void)
 
 
 
323{
324	ssize_t size = 0;
325
326	if (!kexec_trylock())
327		return -EBUSY;
328
329	size += crash_resource_size(&crashk_res);
330	size += crash_resource_size(&crashk_low_res);
331
332	kexec_unlock();
333	return size;
334}
335
336static int __crash_shrink_memory(struct resource *old_res,
337				 unsigned long new_size)
338{
339	struct resource *ram_res;
340
341	ram_res = kzalloc(sizeof(*ram_res), GFP_KERNEL);
342	if (!ram_res)
343		return -ENOMEM;
344
345	ram_res->start = old_res->start + new_size;
346	ram_res->end   = old_res->end;
347	ram_res->flags = IORESOURCE_BUSY | IORESOURCE_SYSTEM_RAM;
348	ram_res->name  = "System RAM";
349
350	if (!new_size) {
351		release_resource(old_res);
352		old_res->start = 0;
353		old_res->end   = 0;
354	} else {
355		crashk_res.end = ram_res->start - 1;
356	}
357
358	crash_free_reserved_phys_range(ram_res->start, ram_res->end);
359	insert_resource(&iomem_resource, ram_res);
360
361	return 0;
362}
363
364int crash_shrink_memory(unsigned long new_size)
365{
366	int ret = 0;
367	unsigned long old_size, low_size;
368
369	if (!kexec_trylock())
370		return -EBUSY;
371
372	if (kexec_crash_image) {
373		ret = -ENOENT;
374		goto unlock;
375	}
376
377	low_size = crash_resource_size(&crashk_low_res);
378	old_size = crash_resource_size(&crashk_res) + low_size;
379	new_size = roundup(new_size, KEXEC_CRASH_MEM_ALIGN);
380	if (new_size >= old_size) {
381		ret = (new_size == old_size) ? 0 : -EINVAL;
382		goto unlock;
383	}
384
385	/*
386	 * (low_size > new_size) implies that low_size is greater than zero.
387	 * This also means that if low_size is zero, the else branch is taken.
388	 *
389	 * If low_size is greater than 0, (low_size > new_size) indicates that
390	 * crashk_low_res also needs to be shrunken. Otherwise, only crashk_res
391	 * needs to be shrunken.
392	 */
393	if (low_size > new_size) {
394		ret = __crash_shrink_memory(&crashk_res, 0);
395		if (ret)
396			goto unlock;
397
398		ret = __crash_shrink_memory(&crashk_low_res, new_size);
399	} else {
400		ret = __crash_shrink_memory(&crashk_res, new_size - low_size);
401	}
402
403	/* Swap crashk_res and crashk_low_res if needed */
404	if (!crashk_res.end && crashk_low_res.end) {
405		crashk_res.start = crashk_low_res.start;
406		crashk_res.end   = crashk_low_res.end;
407		release_resource(&crashk_low_res);
408		crashk_low_res.start = 0;
409		crashk_low_res.end   = 0;
410		insert_resource(&iomem_resource, &crashk_res);
411	}
412
413unlock:
414	kexec_unlock();
415	return ret;
416}
417
418void crash_save_cpu(struct pt_regs *regs, int cpu)
419{
420	struct elf_prstatus prstatus;
421	u32 *buf;
422
423	if ((cpu < 0) || (cpu >= nr_cpu_ids))
424		return;
425
426	/* Using ELF notes here is opportunistic.
427	 * I need a well defined structure format
428	 * for the data I pass, and I need tags
429	 * on the data to indicate what information I have
430	 * squirrelled away.  ELF notes happen to provide
431	 * all of that, so there is no need to invent something new.
432	 */
433	buf = (u32 *)per_cpu_ptr(crash_notes, cpu);
434	if (!buf)
435		return;
436	memset(&prstatus, 0, sizeof(prstatus));
437	prstatus.common.pr_pid = current->pid;
438	elf_core_copy_regs(&prstatus.pr_reg, regs);
439	buf = append_elf_note(buf, KEXEC_CORE_NOTE_NAME, NT_PRSTATUS,
440			      &prstatus, sizeof(prstatus));
441	final_note(buf);
442}
443
 
 
 
 
444
 
 
445
446static int __init crash_notes_memory_init(void)
447{
448	/* Allocate memory for saving cpu registers. */
449	size_t size, align;
450
451	/*
452	 * crash_notes could be allocated across 2 vmalloc pages when percpu
453	 * is vmalloc based . vmalloc doesn't guarantee 2 continuous vmalloc
454	 * pages are also on 2 continuous physical pages. In this case the
455	 * 2nd part of crash_notes in 2nd page could be lost since only the
456	 * starting address and size of crash_notes are exported through sysfs.
457	 * Here round up the size of crash_notes to the nearest power of two
458	 * and pass it to __alloc_percpu as align value. This can make sure
459	 * crash_notes is allocated inside one physical page.
460	 */
461	size = sizeof(note_buf_t);
462	align = min(roundup_pow_of_two(sizeof(note_buf_t)), PAGE_SIZE);
463
464	/*
465	 * Break compile if size is bigger than PAGE_SIZE since crash_notes
466	 * definitely will be in 2 pages with that.
467	 */
468	BUILD_BUG_ON(size > PAGE_SIZE);
469
470	crash_notes = __alloc_percpu(size, align);
471	if (!crash_notes) {
472		pr_warn("Memory allocation for saving cpu register states failed\n");
473		return -ENOMEM;
474	}
475	return 0;
476}
477subsys_initcall(crash_notes_memory_init);
478
479#endif /*CONFIG_CRASH_DUMP*/
 
 
 
 
480
481#ifdef CONFIG_CRASH_HOTPLUG
482#undef pr_fmt
483#define pr_fmt(fmt) "crash hp: " fmt
484
485/*
486 * Different than kexec/kdump loading/unloading/jumping/shrinking which
487 * usually rarely happen, there will be many crash hotplug events notified
488 * during one short period, e.g one memory board is hot added and memory
489 * regions are online. So mutex lock  __crash_hotplug_lock is used to
490 * serialize the crash hotplug handling specifically.
491 */
492static DEFINE_MUTEX(__crash_hotplug_lock);
493#define crash_hotplug_lock() mutex_lock(&__crash_hotplug_lock)
494#define crash_hotplug_unlock() mutex_unlock(&__crash_hotplug_lock)
495
496/*
497 * This routine utilized when the crash_hotplug sysfs node is read.
498 * It reflects the kernel's ability/permission to update the kdump
499 * image directly.
500 */
501int crash_check_hotplug_support(void)
502{
503	int rc = 0;
504
505	crash_hotplug_lock();
506	/* Obtain lock while reading crash information */
507	if (!kexec_trylock()) {
508		if (!kexec_in_progress)
509			pr_info("kexec_trylock() failed, kdump image may be inaccurate\n");
510		crash_hotplug_unlock();
511		return 0;
512	}
513	if (kexec_crash_image) {
514		rc = kexec_crash_image->hotplug_support;
515	}
516	/* Release lock now that update complete */
517	kexec_unlock();
518	crash_hotplug_unlock();
519
520	return rc;
521}
522
523/*
524 * To accurately reflect hot un/plug changes of CPU and Memory resources
525 * (including onling and offlining of those resources), the relevant
526 * kexec segments must be updated with latest CPU and Memory resources.
527 *
528 * Architectures must ensure two things for all segments that need
529 * updating during hotplug events:
530 *
531 * 1. Segments must be large enough to accommodate a growing number of
532 *    resources.
533 * 2. Exclude the segments from SHA verification.
534 *
535 * For example, on most architectures, the elfcorehdr (which is passed
536 * to the crash kernel via the elfcorehdr= parameter) must include the
537 * new list of CPUs and memory. To make changes to the elfcorehdr, it
538 * should be large enough to permit a growing number of CPU and Memory
539 * resources. One can estimate the elfcorehdr memory size based on
540 * NR_CPUS_DEFAULT and CRASH_MAX_MEMORY_RANGES. The elfcorehdr is
541 * excluded from SHA verification by default if the architecture
542 * supports crash hotplug.
543 */
544static void crash_handle_hotplug_event(unsigned int hp_action, unsigned int cpu, void *arg)
 
 
 
545{
546	struct kimage *image;
 
 
547
548	crash_hotplug_lock();
549	/* Obtain lock while changing crash information */
550	if (!kexec_trylock()) {
551		if (!kexec_in_progress)
552			pr_info("kexec_trylock() failed, kdump image may be inaccurate\n");
553		crash_hotplug_unlock();
554		return;
555	}
556
557	/* Check kdump is not loaded */
558	if (!kexec_crash_image)
559		goto out;
560
561	image = kexec_crash_image;
562
563	/* Check that kexec segments update is permitted */
564	if (!image->hotplug_support)
565		goto out;
566
567	if (hp_action == KEXEC_CRASH_HP_ADD_CPU ||
568		hp_action == KEXEC_CRASH_HP_REMOVE_CPU)
569		pr_debug("hp_action %u, cpu %u\n", hp_action, cpu);
570	else
571		pr_debug("hp_action %u\n", hp_action);
572
573	/*
574	 * The elfcorehdr_index is set to -1 when the struct kimage
575	 * is allocated. Find the segment containing the elfcorehdr,
576	 * if not already found.
577	 */
578	if (image->elfcorehdr_index < 0) {
579		unsigned long mem;
580		unsigned char *ptr;
581		unsigned int n;
582
583		for (n = 0; n < image->nr_segments; n++) {
584			mem = image->segment[n].mem;
585			ptr = kmap_local_page(pfn_to_page(mem >> PAGE_SHIFT));
586			if (ptr) {
587				/* The segment containing elfcorehdr */
588				if (memcmp(ptr, ELFMAG, SELFMAG) == 0)
589					image->elfcorehdr_index = (int)n;
590				kunmap_local(ptr);
591			}
592		}
593	}
594
595	if (image->elfcorehdr_index < 0) {
596		pr_err("unable to locate elfcorehdr segment");
597		goto out;
598	}
599
600	/* Needed in order for the segments to be updated */
601	arch_kexec_unprotect_crashkres();
 
 
 
 
 
602
603	/* Differentiate between normal load and hotplug update */
604	image->hp_action = hp_action;
605
606	/* Now invoke arch-specific update handler */
607	arch_crash_handle_hotplug_event(image, arg);
608
609	/* No longer handling a hotplug event */
610	image->hp_action = KEXEC_CRASH_HP_NONE;
611	image->elfcorehdr_updated = true;
612
613	/* Change back to read-only */
614	arch_kexec_protect_crashkres();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
615
616	/* Errors in the callback is not a reason to rollback state */
617out:
618	/* Release lock now that update complete */
619	kexec_unlock();
620	crash_hotplug_unlock();
621}
622
623static int crash_memhp_notifier(struct notifier_block *nb, unsigned long val, void *arg)
624{
625	switch (val) {
626	case MEM_ONLINE:
627		crash_handle_hotplug_event(KEXEC_CRASH_HP_ADD_MEMORY,
628			KEXEC_CRASH_HP_INVALID_CPU, arg);
629		break;
630
631	case MEM_OFFLINE:
632		crash_handle_hotplug_event(KEXEC_CRASH_HP_REMOVE_MEMORY,
633			KEXEC_CRASH_HP_INVALID_CPU, arg);
634		break;
635	}
636	return NOTIFY_OK;
637}
638
639static struct notifier_block crash_memhp_nb = {
640	.notifier_call = crash_memhp_notifier,
641	.priority = 0
642};
643
644static int crash_cpuhp_online(unsigned int cpu)
645{
646	crash_handle_hotplug_event(KEXEC_CRASH_HP_ADD_CPU, cpu, NULL);
647	return 0;
648}
649
650static int crash_cpuhp_offline(unsigned int cpu)
651{
652	crash_handle_hotplug_event(KEXEC_CRASH_HP_REMOVE_CPU, cpu, NULL);
653	return 0;
654}
655
656static int __init crash_hotplug_init(void)
657{
658	int result = 0;
659
660	if (IS_ENABLED(CONFIG_MEMORY_HOTPLUG))
661		register_memory_notifier(&crash_memhp_nb);
662
663	if (IS_ENABLED(CONFIG_HOTPLUG_CPU)) {
664		result = cpuhp_setup_state_nocalls(CPUHP_BP_PREPARE_DYN,
665			"crash/cpuhp", crash_cpuhp_online, crash_cpuhp_offline);
666	}
667
668	return result;
669}
670
671subsys_initcall(crash_hotplug_init);
672#endif