xref: /linux/fs/proc/vmcore.c (revision c5fd5e67c7812bc40cd897422c1e0d6dd9ed1e2e)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  *	fs/proc/vmcore.c Interface for accessing the crash
4  * 				 dump from the system's previous life.
5  * 	Heavily borrowed from fs/proc/kcore.c
6  *	Created by: Hariprasad Nellitheertha (hari@in.ibm.com)
7  *	Copyright (C) IBM Corporation, 2004. All rights reserved
8  *
9  */
10 
11 #define pr_fmt(fmt) "vmcore: " fmt
12 
13 #include <linux/mm.h>
14 #include <linux/kcore.h>
15 #include <linux/user.h>
16 #include <linux/elf.h>
17 #include <linux/elfcore.h>
18 #include <linux/export.h>
19 #include <linux/slab.h>
20 #include <linux/highmem.h>
21 #include <linux/printk.h>
22 #include <linux/memblock.h>
23 #include <linux/init.h>
24 #include <linux/crash_dump.h>
25 #include <linux/list.h>
26 #include <linux/moduleparam.h>
27 #include <linux/mutex.h>
28 #include <linux/vmalloc.h>
29 #include <linux/pagemap.h>
30 #include <linux/uio.h>
31 #include <linux/cc_platform.h>
32 #include <asm/io.h>
33 #include "internal.h"
34 
35 /* List representing chunks of contiguous memory areas and their offsets in
36  * vmcore file.
37  */
38 static LIST_HEAD(vmcore_list);
39 
40 /* Stores the pointer to the buffer containing kernel elf core headers. */
41 static char *elfcorebuf;
42 static size_t elfcorebuf_sz;
43 static size_t elfcorebuf_sz_orig;
44 
45 static char *elfnotes_buf;
46 static size_t elfnotes_sz;
47 /* Size of all notes minus the device dump notes */
48 static size_t elfnotes_orig_sz;
49 
50 /* Total size of vmcore file. */
51 static u64 vmcore_size;
52 
53 static struct proc_dir_entry *proc_vmcore;
54 
55 #ifdef CONFIG_PROC_VMCORE_DEVICE_DUMP
56 struct vmcoredd_node {
57 	struct list_head list;	/* List of dumps */
58 	void *buf;		/* Buffer containing device's dump */
59 	unsigned int size;	/* Size of the buffer */
60 };
61 
62 /* Device Dump list and mutex to synchronize access to list */
63 static LIST_HEAD(vmcoredd_list);
64 
65 static bool vmcoredd_disabled;
66 core_param(novmcoredd, vmcoredd_disabled, bool, 0);
67 #endif /* CONFIG_PROC_VMCORE_DEVICE_DUMP */
68 
69 /* Device Dump Size */
70 static size_t vmcoredd_orig_sz;
71 
72 static DEFINE_MUTEX(vmcore_mutex);
73 
74 DEFINE_STATIC_SRCU(vmcore_cb_srcu);
75 /* List of registered vmcore callbacks. */
76 static LIST_HEAD(vmcore_cb_list);
77 /* Whether the vmcore has been opened once. */
78 static bool vmcore_opened;
79 /* Whether the vmcore is currently open. */
80 static unsigned int vmcore_open;
81 
82 static void vmcore_process_device_ram(struct vmcore_cb *cb);
83 
84 void register_vmcore_cb(struct vmcore_cb *cb)
85 {
86 	INIT_LIST_HEAD(&cb->next);
87 	mutex_lock(&vmcore_mutex);
88 	list_add_tail(&cb->next, &vmcore_cb_list);
89 	/*
90 	 * Registering a vmcore callback after the vmcore was opened is
91 	 * very unusual (e.g., manual driver loading).
92 	 */
93 	if (vmcore_opened)
94 		pr_warn_once("Unexpected vmcore callback registration\n");
95 	if (!vmcore_open && cb->get_device_ram)
96 		vmcore_process_device_ram(cb);
97 	mutex_unlock(&vmcore_mutex);
98 }
99 EXPORT_SYMBOL_GPL(register_vmcore_cb);
100 
101 void unregister_vmcore_cb(struct vmcore_cb *cb)
102 {
103 	mutex_lock(&vmcore_mutex);
104 	list_del_rcu(&cb->next);
105 	/*
106 	 * Unregistering a vmcore callback after the vmcore was opened is
107 	 * very unusual (e.g., forced driver removal), but we cannot stop
108 	 * unregistering.
109 	 */
110 	if (vmcore_opened)
111 		pr_warn_once("Unexpected vmcore callback unregistration\n");
112 	mutex_unlock(&vmcore_mutex);
113 
114 	synchronize_srcu(&vmcore_cb_srcu);
115 }
116 EXPORT_SYMBOL_GPL(unregister_vmcore_cb);
117 
118 static bool pfn_is_ram(unsigned long pfn)
119 {
120 	struct vmcore_cb *cb;
121 	bool ret = true;
122 
123 	list_for_each_entry_srcu(cb, &vmcore_cb_list, next,
124 				 srcu_read_lock_held(&vmcore_cb_srcu)) {
125 		if (unlikely(!cb->pfn_is_ram))
126 			continue;
127 		ret = cb->pfn_is_ram(cb, pfn);
128 		if (!ret)
129 			break;
130 	}
131 
132 	return ret;
133 }
134 
135 static int open_vmcore(struct inode *inode, struct file *file)
136 {
137 	mutex_lock(&vmcore_mutex);
138 	vmcore_opened = true;
139 	if (vmcore_open + 1 == 0) {
140 		mutex_unlock(&vmcore_mutex);
141 		return -EBUSY;
142 	}
143 	vmcore_open++;
144 	mutex_unlock(&vmcore_mutex);
145 
146 	return 0;
147 }
148 
149 static int release_vmcore(struct inode *inode, struct file *file)
150 {
151 	mutex_lock(&vmcore_mutex);
152 	vmcore_open--;
153 	mutex_unlock(&vmcore_mutex);
154 
155 	return 0;
156 }
157 
158 /* Reads a page from the oldmem device from given offset. */
159 ssize_t read_from_oldmem(struct iov_iter *iter, size_t count,
160 			 u64 *ppos, bool encrypted)
161 {
162 	unsigned long pfn, offset;
163 	ssize_t nr_bytes;
164 	ssize_t read = 0, tmp;
165 	int idx;
166 
167 	if (!count)
168 		return 0;
169 
170 	offset = (unsigned long)(*ppos % PAGE_SIZE);
171 	pfn = (unsigned long)(*ppos / PAGE_SIZE);
172 
173 	idx = srcu_read_lock(&vmcore_cb_srcu);
174 	do {
175 		if (count > (PAGE_SIZE - offset))
176 			nr_bytes = PAGE_SIZE - offset;
177 		else
178 			nr_bytes = count;
179 
180 		/* If pfn is not ram, return zeros for sparse dump files */
181 		if (!pfn_is_ram(pfn)) {
182 			tmp = iov_iter_zero(nr_bytes, iter);
183 		} else {
184 			if (encrypted)
185 				tmp = copy_oldmem_page_encrypted(iter, pfn,
186 								 nr_bytes,
187 								 offset);
188 			else
189 				tmp = copy_oldmem_page(iter, pfn, nr_bytes,
190 						       offset);
191 		}
192 		if (tmp < nr_bytes) {
193 			srcu_read_unlock(&vmcore_cb_srcu, idx);
194 			return -EFAULT;
195 		}
196 
197 		*ppos += nr_bytes;
198 		count -= nr_bytes;
199 		read += nr_bytes;
200 		++pfn;
201 		offset = 0;
202 	} while (count);
203 	srcu_read_unlock(&vmcore_cb_srcu, idx);
204 
205 	return read;
206 }
207 
208 /*
209  * Architectures may override this function to allocate ELF header in 2nd kernel
210  */
211 int __weak elfcorehdr_alloc(unsigned long long *addr, unsigned long long *size)
212 {
213 	return 0;
214 }
215 
216 /*
217  * Architectures may override this function to free header
218  */
219 void __weak elfcorehdr_free(unsigned long long addr)
220 {}
221 
222 /*
223  * Architectures may override this function to read from ELF header
224  */
225 ssize_t __weak elfcorehdr_read(char *buf, size_t count, u64 *ppos)
226 {
227 	struct kvec kvec = { .iov_base = buf, .iov_len = count };
228 	struct iov_iter iter;
229 
230 	iov_iter_kvec(&iter, ITER_DEST, &kvec, 1, count);
231 
232 	return read_from_oldmem(&iter, count, ppos, false);
233 }
234 
235 /*
236  * Architectures may override this function to read from notes sections
237  */
238 ssize_t __weak elfcorehdr_read_notes(char *buf, size_t count, u64 *ppos)
239 {
240 	struct kvec kvec = { .iov_base = buf, .iov_len = count };
241 	struct iov_iter iter;
242 
243 	iov_iter_kvec(&iter, ITER_DEST, &kvec, 1, count);
244 
245 	return read_from_oldmem(&iter, count, ppos,
246 			cc_platform_has(CC_ATTR_MEM_ENCRYPT));
247 }
248 
249 /*
250  * Architectures may override this function to map oldmem
251  */
252 int __weak remap_oldmem_pfn_range(struct vm_area_struct *vma,
253 				  unsigned long from, unsigned long pfn,
254 				  unsigned long size, pgprot_t prot)
255 {
256 	prot = pgprot_encrypted(prot);
257 	return remap_pfn_range(vma, from, pfn, size, prot);
258 }
259 
260 /*
261  * Architectures which support memory encryption override this.
262  */
263 ssize_t __weak copy_oldmem_page_encrypted(struct iov_iter *iter,
264 		unsigned long pfn, size_t csize, unsigned long offset)
265 {
266 	return copy_oldmem_page(iter, pfn, csize, offset);
267 }
268 
269 #ifdef CONFIG_PROC_VMCORE_DEVICE_DUMP
270 static int vmcoredd_copy_dumps(struct iov_iter *iter, u64 start, size_t size)
271 {
272 	struct vmcoredd_node *dump;
273 	u64 offset = 0;
274 	size_t tsz;
275 	char *buf;
276 
277 	list_for_each_entry(dump, &vmcoredd_list, list) {
278 		if (start < offset + dump->size) {
279 			tsz = min(offset + (u64)dump->size - start, (u64)size);
280 			buf = dump->buf + start - offset;
281 			if (copy_to_iter(buf, tsz, iter) < tsz)
282 				return -EFAULT;
283 
284 			size -= tsz;
285 			start += tsz;
286 
287 			/* Leave now if buffer filled already */
288 			if (!size)
289 				return 0;
290 		}
291 		offset += dump->size;
292 	}
293 
294 	return 0;
295 }
296 
297 #ifdef CONFIG_MMU
298 static int vmcoredd_mmap_dumps(struct vm_area_struct *vma, unsigned long dst,
299 			       u64 start, size_t size)
300 {
301 	struct vmcoredd_node *dump;
302 	u64 offset = 0;
303 	size_t tsz;
304 	char *buf;
305 
306 	list_for_each_entry(dump, &vmcoredd_list, list) {
307 		if (start < offset + dump->size) {
308 			tsz = min(offset + (u64)dump->size - start, (u64)size);
309 			buf = dump->buf + start - offset;
310 			if (remap_vmalloc_range_partial(vma, dst, buf, 0,
311 							tsz))
312 				return -EFAULT;
313 
314 			size -= tsz;
315 			start += tsz;
316 			dst += tsz;
317 
318 			/* Leave now if buffer filled already */
319 			if (!size)
320 				return 0;
321 		}
322 		offset += dump->size;
323 	}
324 
325 	return 0;
326 }
327 #endif /* CONFIG_MMU */
328 #endif /* CONFIG_PROC_VMCORE_DEVICE_DUMP */
329 
330 /* Read from the ELF header and then the crash dump. On error, negative value is
331  * returned otherwise number of bytes read are returned.
332  */
333 static ssize_t __read_vmcore(struct iov_iter *iter, loff_t *fpos)
334 {
335 	struct vmcore_range *m = NULL;
336 	ssize_t acc = 0, tmp;
337 	size_t tsz;
338 	u64 start;
339 
340 	if (!iov_iter_count(iter) || *fpos >= vmcore_size)
341 		return 0;
342 
343 	iov_iter_truncate(iter, vmcore_size - *fpos);
344 
345 	/* Read ELF core header */
346 	if (*fpos < elfcorebuf_sz) {
347 		tsz = min(elfcorebuf_sz - (size_t)*fpos, iov_iter_count(iter));
348 		if (copy_to_iter(elfcorebuf + *fpos, tsz, iter) < tsz)
349 			return -EFAULT;
350 		*fpos += tsz;
351 		acc += tsz;
352 
353 		/* leave now if filled buffer already */
354 		if (!iov_iter_count(iter))
355 			return acc;
356 	}
357 
358 	/* Read ELF note segment */
359 	if (*fpos < elfcorebuf_sz + elfnotes_sz) {
360 		void *kaddr;
361 
362 		/* We add device dumps before other elf notes because the
363 		 * other elf notes may not fill the elf notes buffer
364 		 * completely and we will end up with zero-filled data
365 		 * between the elf notes and the device dumps. Tools will
366 		 * then try to decode this zero-filled data as valid notes
367 		 * and we don't want that. Hence, adding device dumps before
368 		 * the other elf notes ensure that zero-filled data can be
369 		 * avoided.
370 		 */
371 #ifdef CONFIG_PROC_VMCORE_DEVICE_DUMP
372 		/* Read device dumps */
373 		if (*fpos < elfcorebuf_sz + vmcoredd_orig_sz) {
374 			tsz = min(elfcorebuf_sz + vmcoredd_orig_sz -
375 				  (size_t)*fpos, iov_iter_count(iter));
376 			start = *fpos - elfcorebuf_sz;
377 			if (vmcoredd_copy_dumps(iter, start, tsz))
378 				return -EFAULT;
379 
380 			*fpos += tsz;
381 			acc += tsz;
382 
383 			/* leave now if filled buffer already */
384 			if (!iov_iter_count(iter))
385 				return acc;
386 		}
387 #endif /* CONFIG_PROC_VMCORE_DEVICE_DUMP */
388 
389 		/* Read remaining elf notes */
390 		tsz = min(elfcorebuf_sz + elfnotes_sz - (size_t)*fpos,
391 			  iov_iter_count(iter));
392 		kaddr = elfnotes_buf + *fpos - elfcorebuf_sz - vmcoredd_orig_sz;
393 		if (copy_to_iter(kaddr, tsz, iter) < tsz)
394 			return -EFAULT;
395 
396 		*fpos += tsz;
397 		acc += tsz;
398 
399 		/* leave now if filled buffer already */
400 		if (!iov_iter_count(iter))
401 			return acc;
402 
403 		cond_resched();
404 	}
405 
406 	list_for_each_entry(m, &vmcore_list, list) {
407 		if (*fpos < m->offset + m->size) {
408 			tsz = (size_t)min_t(unsigned long long,
409 					    m->offset + m->size - *fpos,
410 					    iov_iter_count(iter));
411 			start = m->paddr + *fpos - m->offset;
412 			tmp = read_from_oldmem(iter, tsz, &start,
413 					cc_platform_has(CC_ATTR_MEM_ENCRYPT));
414 			if (tmp < 0)
415 				return tmp;
416 			*fpos += tsz;
417 			acc += tsz;
418 
419 			/* leave now if filled buffer already */
420 			if (!iov_iter_count(iter))
421 				return acc;
422 		}
423 
424 		cond_resched();
425 	}
426 
427 	return acc;
428 }
429 
430 static ssize_t read_vmcore(struct kiocb *iocb, struct iov_iter *iter)
431 {
432 	return __read_vmcore(iter, &iocb->ki_pos);
433 }
434 
435 /**
436  * vmcore_alloc_buf - allocate buffer in vmalloc memory
437  * @size: size of buffer
438  *
439  * If CONFIG_MMU is defined, use vmalloc_user() to allow users to mmap
440  * the buffer to user-space by means of remap_vmalloc_range().
441  *
442  * If CONFIG_MMU is not defined, use vzalloc() since mmap_vmcore() is
443  * disabled and there's no need to allow users to mmap the buffer.
444  */
445 static inline char *vmcore_alloc_buf(size_t size)
446 {
447 #ifdef CONFIG_MMU
448 	return vmalloc_user(size);
449 #else
450 	return vzalloc(size);
451 #endif
452 }
453 
454 /*
455  * Disable mmap_vmcore() if CONFIG_MMU is not defined. MMU is
456  * essential for mmap_vmcore() in order to map physically
457  * non-contiguous objects (ELF header, ELF note segment and memory
458  * regions in the 1st kernel pointed to by PT_LOAD entries) into
459  * virtually contiguous user-space in ELF layout.
460  */
461 #ifdef CONFIG_MMU
462 
463 /*
464  * The vmcore fault handler uses the page cache and fills data using the
465  * standard __read_vmcore() function.
466  *
467  * On s390 the fault handler is used for memory regions that can't be mapped
468  * directly with remap_pfn_range().
469  */
470 static vm_fault_t mmap_vmcore_fault(struct vm_fault *vmf)
471 {
472 #ifdef CONFIG_S390
473 	struct address_space *mapping = vmf->vma->vm_file->f_mapping;
474 	pgoff_t index = vmf->pgoff;
475 	struct iov_iter iter;
476 	struct kvec kvec;
477 	struct folio *folio;
478 	loff_t offset;
479 	int rc;
480 
481 	folio = __filemap_get_folio(mapping, index,
482 			FGP_LOCK | FGP_ACCESSED | FGP_CREAT, GFP_KERNEL);
483 	if (IS_ERR(folio))
484 		return VM_FAULT_OOM;
485 	if (!folio_test_uptodate(folio)) {
486 		offset = folio_pos(folio);
487 		kvec.iov_base = folio_address(folio);
488 		kvec.iov_len = folio_size(folio);
489 		iov_iter_kvec(&iter, ITER_DEST, &kvec, 1, folio_size(folio));
490 
491 		rc = __read_vmcore(&iter, &offset);
492 		if (rc < 0) {
493 			folio_unlock(folio);
494 			folio_put(folio);
495 			return vmf_error(rc);
496 		}
497 		folio_mark_uptodate(folio);
498 	}
499 	folio_unlock(folio);
500 	vmf->page = folio_file_page(folio, index);
501 	return 0;
502 #else
503 	return VM_FAULT_SIGBUS;
504 #endif
505 }
506 
507 static const struct vm_operations_struct vmcore_mmap_ops = {
508 	.fault = mmap_vmcore_fault,
509 };
510 
511 /*
512  * remap_oldmem_pfn_checked - do remap_oldmem_pfn_range replacing all pages
513  * reported as not being ram with the zero page.
514  *
515  * @vma: vm_area_struct describing requested mapping
516  * @from: start remapping from
517  * @pfn: page frame number to start remapping to
518  * @size: remapping size
519  * @prot: protection bits
520  *
521  * Returns zero on success, -EAGAIN on failure.
522  */
523 static int remap_oldmem_pfn_checked(struct vm_area_struct *vma,
524 				    unsigned long from, unsigned long pfn,
525 				    unsigned long size, pgprot_t prot)
526 {
527 	unsigned long map_size;
528 	unsigned long pos_start, pos_end, pos;
529 	unsigned long zeropage_pfn = zero_pfn(0);
530 	size_t len = 0;
531 
532 	pos_start = pfn;
533 	pos_end = pfn + (size >> PAGE_SHIFT);
534 
535 	for (pos = pos_start; pos < pos_end; ++pos) {
536 		if (!pfn_is_ram(pos)) {
537 			/*
538 			 * We hit a page which is not ram. Remap the continuous
539 			 * region between pos_start and pos-1 and replace
540 			 * the non-ram page at pos with the zero page.
541 			 */
542 			if (pos > pos_start) {
543 				/* Remap continuous region */
544 				map_size = (pos - pos_start) << PAGE_SHIFT;
545 				if (remap_oldmem_pfn_range(vma, from + len,
546 							   pos_start, map_size,
547 							   prot))
548 					goto fail;
549 				len += map_size;
550 			}
551 			/* Remap the zero page */
552 			if (remap_oldmem_pfn_range(vma, from + len,
553 						   zeropage_pfn,
554 						   PAGE_SIZE, prot))
555 				goto fail;
556 			len += PAGE_SIZE;
557 			pos_start = pos + 1;
558 		}
559 	}
560 	if (pos > pos_start) {
561 		/* Remap the rest */
562 		map_size = (pos - pos_start) << PAGE_SHIFT;
563 		if (remap_oldmem_pfn_range(vma, from + len, pos_start,
564 					   map_size, prot))
565 			goto fail;
566 	}
567 	return 0;
568 fail:
569 	do_munmap(vma->vm_mm, from, len, NULL);
570 	return -EAGAIN;
571 }
572 
573 static int vmcore_remap_oldmem_pfn(struct vm_area_struct *vma,
574 			    unsigned long from, unsigned long pfn,
575 			    unsigned long size, pgprot_t prot)
576 {
577 	int ret, idx;
578 
579 	/*
580 	 * Check if a callback was registered to avoid looping over all
581 	 * pages without a reason.
582 	 */
583 	idx = srcu_read_lock(&vmcore_cb_srcu);
584 	if (!list_empty(&vmcore_cb_list))
585 		ret = remap_oldmem_pfn_checked(vma, from, pfn, size, prot);
586 	else
587 		ret = remap_oldmem_pfn_range(vma, from, pfn, size, prot);
588 	srcu_read_unlock(&vmcore_cb_srcu, idx);
589 	return ret;
590 }
591 
592 static int mmap_vmcore(struct file *file, struct vm_area_struct *vma)
593 {
594 	size_t size = vma->vm_end - vma->vm_start;
595 	u64 start, end, len, tsz;
596 	struct vmcore_range *m;
597 
598 	start = (u64)vma->vm_pgoff << PAGE_SHIFT;
599 	end = start + size;
600 
601 	if (size > vmcore_size || end > vmcore_size)
602 		return -EINVAL;
603 
604 	if (vma->vm_flags & (VM_WRITE | VM_EXEC))
605 		return -EPERM;
606 
607 	vm_flags_mod(vma, VM_MIXEDMAP, VM_MAYWRITE | VM_MAYEXEC);
608 	vma->vm_ops = &vmcore_mmap_ops;
609 
610 	len = 0;
611 
612 	if (start < elfcorebuf_sz) {
613 		u64 pfn;
614 
615 		tsz = min(elfcorebuf_sz - (size_t)start, size);
616 		pfn = __pa(elfcorebuf + start) >> PAGE_SHIFT;
617 		if (remap_pfn_range(vma, vma->vm_start, pfn, tsz,
618 				    vma->vm_page_prot))
619 			return -EAGAIN;
620 		size -= tsz;
621 		start += tsz;
622 		len += tsz;
623 
624 		if (size == 0)
625 			return 0;
626 	}
627 
628 	if (start < elfcorebuf_sz + elfnotes_sz) {
629 		void *kaddr;
630 
631 		/* We add device dumps before other elf notes because the
632 		 * other elf notes may not fill the elf notes buffer
633 		 * completely and we will end up with zero-filled data
634 		 * between the elf notes and the device dumps. Tools will
635 		 * then try to decode this zero-filled data as valid notes
636 		 * and we don't want that. Hence, adding device dumps before
637 		 * the other elf notes ensure that zero-filled data can be
638 		 * avoided. This also ensures that the device dumps and
639 		 * other elf notes can be properly mmaped at page aligned
640 		 * address.
641 		 */
642 #ifdef CONFIG_PROC_VMCORE_DEVICE_DUMP
643 		/* Read device dumps */
644 		if (start < elfcorebuf_sz + vmcoredd_orig_sz) {
645 			u64 start_off;
646 
647 			tsz = min(elfcorebuf_sz + vmcoredd_orig_sz -
648 				  (size_t)start, size);
649 			start_off = start - elfcorebuf_sz;
650 			if (vmcoredd_mmap_dumps(vma, vma->vm_start + len,
651 						start_off, tsz))
652 				goto fail;
653 
654 			size -= tsz;
655 			start += tsz;
656 			len += tsz;
657 
658 			/* leave now if filled buffer already */
659 			if (!size)
660 				return 0;
661 		}
662 #endif /* CONFIG_PROC_VMCORE_DEVICE_DUMP */
663 
664 		/* Read remaining elf notes */
665 		tsz = min(elfcorebuf_sz + elfnotes_sz - (size_t)start, size);
666 		kaddr = elfnotes_buf + start - elfcorebuf_sz - vmcoredd_orig_sz;
667 		if (remap_vmalloc_range_partial(vma, vma->vm_start + len,
668 						kaddr, 0, tsz))
669 			goto fail;
670 
671 		size -= tsz;
672 		start += tsz;
673 		len += tsz;
674 
675 		if (size == 0)
676 			return 0;
677 	}
678 
679 	list_for_each_entry(m, &vmcore_list, list) {
680 		if (start < m->offset + m->size) {
681 			u64 paddr = 0;
682 
683 			tsz = (size_t)min_t(unsigned long long,
684 					    m->offset + m->size - start, size);
685 			paddr = m->paddr + start - m->offset;
686 			if (vmcore_remap_oldmem_pfn(vma, vma->vm_start + len,
687 						    paddr >> PAGE_SHIFT, tsz,
688 						    vma->vm_page_prot))
689 				goto fail;
690 			size -= tsz;
691 			start += tsz;
692 			len += tsz;
693 
694 			if (size == 0)
695 				return 0;
696 		}
697 	}
698 
699 	return 0;
700 fail:
701 	do_munmap(vma->vm_mm, vma->vm_start, len, NULL);
702 	return -EAGAIN;
703 }
704 #else
705 static int mmap_vmcore(struct file *file, struct vm_area_struct *vma)
706 {
707 	return -ENOSYS;
708 }
709 #endif
710 
711 static const struct proc_ops vmcore_proc_ops = {
712 	.proc_open	= open_vmcore,
713 	.proc_release	= release_vmcore,
714 	.proc_read_iter	= read_vmcore,
715 	.proc_lseek	= default_llseek,
716 	.proc_mmap	= mmap_vmcore,
717 };
718 
719 static u64 get_vmcore_size(size_t elfsz, size_t elfnotesegsz,
720 			   struct list_head *vc_list)
721 {
722 	struct vmcore_range *m;
723 	u64 size;
724 
725 	size = elfsz + elfnotesegsz;
726 	list_for_each_entry(m, vc_list, list) {
727 		size += m->size;
728 	}
729 	return size;
730 }
731 
732 /**
733  * update_note_header_size_elf64 - update p_memsz member of each PT_NOTE entry
734  *
735  * @ehdr_ptr: ELF header
736  *
737  * This function updates p_memsz member of each PT_NOTE entry in the
738  * program header table pointed to by @ehdr_ptr to real size of ELF
739  * note segment.
740  */
741 static int __init update_note_header_size_elf64(const Elf64_Ehdr *ehdr_ptr)
742 {
743 	int i, rc=0;
744 	Elf64_Phdr *phdr_ptr;
745 	Elf64_Nhdr *nhdr_ptr;
746 
747 	phdr_ptr = (Elf64_Phdr *)(ehdr_ptr + 1);
748 	for (i = 0; i < ehdr_ptr->e_phnum; i++, phdr_ptr++) {
749 		void *notes_section;
750 		u64 offset, max_sz, sz, real_sz = 0;
751 		if (phdr_ptr->p_type != PT_NOTE)
752 			continue;
753 		max_sz = phdr_ptr->p_memsz;
754 		offset = phdr_ptr->p_offset;
755 		notes_section = kmalloc(max_sz, GFP_KERNEL);
756 		if (!notes_section)
757 			return -ENOMEM;
758 		rc = elfcorehdr_read_notes(notes_section, max_sz, &offset);
759 		if (rc < 0) {
760 			kfree(notes_section);
761 			return rc;
762 		}
763 		nhdr_ptr = notes_section;
764 		while (nhdr_ptr->n_namesz != 0) {
765 			sz = sizeof(Elf64_Nhdr) +
766 				(((u64)nhdr_ptr->n_namesz + 3) & ~3) +
767 				(((u64)nhdr_ptr->n_descsz + 3) & ~3);
768 			if ((real_sz + sz) > max_sz) {
769 				pr_warn("Warning: Exceeded p_memsz, dropping PT_NOTE entry n_namesz=0x%x, n_descsz=0x%x\n",
770 					nhdr_ptr->n_namesz, nhdr_ptr->n_descsz);
771 				break;
772 			}
773 			real_sz += sz;
774 			nhdr_ptr = (Elf64_Nhdr*)((char*)nhdr_ptr + sz);
775 		}
776 		kfree(notes_section);
777 		phdr_ptr->p_memsz = real_sz;
778 		if (real_sz == 0) {
779 			pr_warn("Warning: Zero PT_NOTE entries found\n");
780 		}
781 	}
782 
783 	return 0;
784 }
785 
786 /**
787  * get_note_number_and_size_elf64 - get the number of PT_NOTE program
788  * headers and sum of real size of their ELF note segment headers and
789  * data.
790  *
791  * @ehdr_ptr: ELF header
792  * @nr_ptnote: buffer for the number of PT_NOTE program headers
793  * @sz_ptnote: buffer for size of unique PT_NOTE program header
794  *
795  * This function is used to merge multiple PT_NOTE program headers
796  * into a unique single one. The resulting unique entry will have
797  * @sz_ptnote in its phdr->p_mem.
798  *
799  * It is assumed that program headers with PT_NOTE type pointed to by
800  * @ehdr_ptr has already been updated by update_note_header_size_elf64
801  * and each of PT_NOTE program headers has actual ELF note segment
802  * size in its p_memsz member.
803  */
804 static int __init get_note_number_and_size_elf64(const Elf64_Ehdr *ehdr_ptr,
805 						 int *nr_ptnote, u64 *sz_ptnote)
806 {
807 	int i;
808 	Elf64_Phdr *phdr_ptr;
809 
810 	*nr_ptnote = *sz_ptnote = 0;
811 
812 	phdr_ptr = (Elf64_Phdr *)(ehdr_ptr + 1);
813 	for (i = 0; i < ehdr_ptr->e_phnum; i++, phdr_ptr++) {
814 		if (phdr_ptr->p_type != PT_NOTE)
815 			continue;
816 		*nr_ptnote += 1;
817 		*sz_ptnote += phdr_ptr->p_memsz;
818 	}
819 
820 	return 0;
821 }
822 
823 /**
824  * copy_notes_elf64 - copy ELF note segments in a given buffer
825  *
826  * @ehdr_ptr: ELF header
827  * @notes_buf: buffer into which ELF note segments are copied
828  *
829  * This function is used to copy ELF note segment in the 1st kernel
830  * into the buffer @notes_buf in the 2nd kernel. It is assumed that
831  * size of the buffer @notes_buf is equal to or larger than sum of the
832  * real ELF note segment headers and data.
833  *
834  * It is assumed that program headers with PT_NOTE type pointed to by
835  * @ehdr_ptr has already been updated by update_note_header_size_elf64
836  * and each of PT_NOTE program headers has actual ELF note segment
837  * size in its p_memsz member.
838  */
839 static int __init copy_notes_elf64(const Elf64_Ehdr *ehdr_ptr, char *notes_buf)
840 {
841 	int i, rc=0;
842 	Elf64_Phdr *phdr_ptr;
843 
844 	phdr_ptr = (Elf64_Phdr*)(ehdr_ptr + 1);
845 
846 	for (i = 0; i < ehdr_ptr->e_phnum; i++, phdr_ptr++) {
847 		u64 offset;
848 		if (phdr_ptr->p_type != PT_NOTE)
849 			continue;
850 		offset = phdr_ptr->p_offset;
851 		rc = elfcorehdr_read_notes(notes_buf, phdr_ptr->p_memsz,
852 					   &offset);
853 		if (rc < 0)
854 			return rc;
855 		notes_buf += phdr_ptr->p_memsz;
856 	}
857 
858 	return 0;
859 }
860 
861 /* Merges all the PT_NOTE headers into one. */
862 static int __init merge_note_headers_elf64(char *elfptr, size_t *elfsz,
863 					   char **notes_buf, size_t *notes_sz)
864 {
865 	int i, nr_ptnote=0, rc=0;
866 	char *tmp;
867 	Elf64_Ehdr *ehdr_ptr;
868 	Elf64_Phdr phdr;
869 	u64 phdr_sz = 0, note_off;
870 
871 	ehdr_ptr = (Elf64_Ehdr *)elfptr;
872 
873 	rc = update_note_header_size_elf64(ehdr_ptr);
874 	if (rc < 0)
875 		return rc;
876 
877 	rc = get_note_number_and_size_elf64(ehdr_ptr, &nr_ptnote, &phdr_sz);
878 	if (rc < 0)
879 		return rc;
880 
881 	*notes_sz = roundup(phdr_sz, PAGE_SIZE);
882 	*notes_buf = vmcore_alloc_buf(*notes_sz);
883 	if (!*notes_buf)
884 		return -ENOMEM;
885 
886 	rc = copy_notes_elf64(ehdr_ptr, *notes_buf);
887 	if (rc < 0)
888 		return rc;
889 
890 	/* Prepare merged PT_NOTE program header. */
891 	phdr.p_type    = PT_NOTE;
892 	phdr.p_flags   = 0;
893 	note_off = sizeof(Elf64_Ehdr) +
894 			(ehdr_ptr->e_phnum - nr_ptnote +1) * sizeof(Elf64_Phdr);
895 	phdr.p_offset  = roundup(note_off, PAGE_SIZE);
896 	phdr.p_vaddr   = phdr.p_paddr = 0;
897 	phdr.p_filesz  = phdr.p_memsz = phdr_sz;
898 	phdr.p_align   = 4;
899 
900 	/* Add merged PT_NOTE program header*/
901 	tmp = elfptr + sizeof(Elf64_Ehdr);
902 	memcpy(tmp, &phdr, sizeof(phdr));
903 	tmp += sizeof(phdr);
904 
905 	/* Remove unwanted PT_NOTE program headers. */
906 	i = (nr_ptnote - 1) * sizeof(Elf64_Phdr);
907 	*elfsz = *elfsz - i;
908 	memmove(tmp, tmp+i, ((*elfsz)-sizeof(Elf64_Ehdr)-sizeof(Elf64_Phdr)));
909 	memset(elfptr + *elfsz, 0, i);
910 	*elfsz = roundup(*elfsz, PAGE_SIZE);
911 
912 	/* Modify e_phnum to reflect merged headers. */
913 	ehdr_ptr->e_phnum = ehdr_ptr->e_phnum - nr_ptnote + 1;
914 
915 	/* Store the size of all notes.  We need this to update the note
916 	 * header when the device dumps will be added.
917 	 */
918 	elfnotes_orig_sz = phdr.p_memsz;
919 
920 	return 0;
921 }
922 
923 /**
924  * update_note_header_size_elf32 - update p_memsz member of each PT_NOTE entry
925  *
926  * @ehdr_ptr: ELF header
927  *
928  * This function updates p_memsz member of each PT_NOTE entry in the
929  * program header table pointed to by @ehdr_ptr to real size of ELF
930  * note segment.
931  */
932 static int __init update_note_header_size_elf32(const Elf32_Ehdr *ehdr_ptr)
933 {
934 	int i, rc=0;
935 	Elf32_Phdr *phdr_ptr;
936 	Elf32_Nhdr *nhdr_ptr;
937 
938 	phdr_ptr = (Elf32_Phdr *)(ehdr_ptr + 1);
939 	for (i = 0; i < ehdr_ptr->e_phnum; i++, phdr_ptr++) {
940 		void *notes_section;
941 		u64 offset, max_sz, sz, real_sz = 0;
942 		if (phdr_ptr->p_type != PT_NOTE)
943 			continue;
944 		max_sz = phdr_ptr->p_memsz;
945 		offset = phdr_ptr->p_offset;
946 		notes_section = kmalloc(max_sz, GFP_KERNEL);
947 		if (!notes_section)
948 			return -ENOMEM;
949 		rc = elfcorehdr_read_notes(notes_section, max_sz, &offset);
950 		if (rc < 0) {
951 			kfree(notes_section);
952 			return rc;
953 		}
954 		nhdr_ptr = notes_section;
955 		while (nhdr_ptr->n_namesz != 0) {
956 			sz = sizeof(Elf32_Nhdr) +
957 				(((u64)nhdr_ptr->n_namesz + 3) & ~3) +
958 				(((u64)nhdr_ptr->n_descsz + 3) & ~3);
959 			if ((real_sz + sz) > max_sz) {
960 				pr_warn("Warning: Exceeded p_memsz, dropping PT_NOTE entry n_namesz=0x%x, n_descsz=0x%x\n",
961 					nhdr_ptr->n_namesz, nhdr_ptr->n_descsz);
962 				break;
963 			}
964 			real_sz += sz;
965 			nhdr_ptr = (Elf32_Nhdr*)((char*)nhdr_ptr + sz);
966 		}
967 		kfree(notes_section);
968 		phdr_ptr->p_memsz = real_sz;
969 		if (real_sz == 0) {
970 			pr_warn("Warning: Zero PT_NOTE entries found\n");
971 		}
972 	}
973 
974 	return 0;
975 }
976 
977 /**
978  * get_note_number_and_size_elf32 - get the number of PT_NOTE program
979  * headers and sum of real size of their ELF note segment headers and
980  * data.
981  *
982  * @ehdr_ptr: ELF header
983  * @nr_ptnote: buffer for the number of PT_NOTE program headers
984  * @sz_ptnote: buffer for size of unique PT_NOTE program header
985  *
986  * This function is used to merge multiple PT_NOTE program headers
987  * into a unique single one. The resulting unique entry will have
988  * @sz_ptnote in its phdr->p_mem.
989  *
990  * It is assumed that program headers with PT_NOTE type pointed to by
991  * @ehdr_ptr has already been updated by update_note_header_size_elf32
992  * and each of PT_NOTE program headers has actual ELF note segment
993  * size in its p_memsz member.
994  */
995 static int __init get_note_number_and_size_elf32(const Elf32_Ehdr *ehdr_ptr,
996 						 int *nr_ptnote, u64 *sz_ptnote)
997 {
998 	int i;
999 	Elf32_Phdr *phdr_ptr;
1000 
1001 	*nr_ptnote = *sz_ptnote = 0;
1002 
1003 	phdr_ptr = (Elf32_Phdr *)(ehdr_ptr + 1);
1004 	for (i = 0; i < ehdr_ptr->e_phnum; i++, phdr_ptr++) {
1005 		if (phdr_ptr->p_type != PT_NOTE)
1006 			continue;
1007 		*nr_ptnote += 1;
1008 		*sz_ptnote += phdr_ptr->p_memsz;
1009 	}
1010 
1011 	return 0;
1012 }
1013 
1014 /**
1015  * copy_notes_elf32 - copy ELF note segments in a given buffer
1016  *
1017  * @ehdr_ptr: ELF header
1018  * @notes_buf: buffer into which ELF note segments are copied
1019  *
1020  * This function is used to copy ELF note segment in the 1st kernel
1021  * into the buffer @notes_buf in the 2nd kernel. It is assumed that
1022  * size of the buffer @notes_buf is equal to or larger than sum of the
1023  * real ELF note segment headers and data.
1024  *
1025  * It is assumed that program headers with PT_NOTE type pointed to by
1026  * @ehdr_ptr has already been updated by update_note_header_size_elf32
1027  * and each of PT_NOTE program headers has actual ELF note segment
1028  * size in its p_memsz member.
1029  */
1030 static int __init copy_notes_elf32(const Elf32_Ehdr *ehdr_ptr, char *notes_buf)
1031 {
1032 	int i, rc=0;
1033 	Elf32_Phdr *phdr_ptr;
1034 
1035 	phdr_ptr = (Elf32_Phdr*)(ehdr_ptr + 1);
1036 
1037 	for (i = 0; i < ehdr_ptr->e_phnum; i++, phdr_ptr++) {
1038 		u64 offset;
1039 		if (phdr_ptr->p_type != PT_NOTE)
1040 			continue;
1041 		offset = phdr_ptr->p_offset;
1042 		rc = elfcorehdr_read_notes(notes_buf, phdr_ptr->p_memsz,
1043 					   &offset);
1044 		if (rc < 0)
1045 			return rc;
1046 		notes_buf += phdr_ptr->p_memsz;
1047 	}
1048 
1049 	return 0;
1050 }
1051 
1052 /* Merges all the PT_NOTE headers into one. */
1053 static int __init merge_note_headers_elf32(char *elfptr, size_t *elfsz,
1054 					   char **notes_buf, size_t *notes_sz)
1055 {
1056 	int i, nr_ptnote=0, rc=0;
1057 	char *tmp;
1058 	Elf32_Ehdr *ehdr_ptr;
1059 	Elf32_Phdr phdr;
1060 	u64 phdr_sz = 0, note_off;
1061 
1062 	ehdr_ptr = (Elf32_Ehdr *)elfptr;
1063 
1064 	rc = update_note_header_size_elf32(ehdr_ptr);
1065 	if (rc < 0)
1066 		return rc;
1067 
1068 	rc = get_note_number_and_size_elf32(ehdr_ptr, &nr_ptnote, &phdr_sz);
1069 	if (rc < 0)
1070 		return rc;
1071 
1072 	*notes_sz = roundup(phdr_sz, PAGE_SIZE);
1073 	*notes_buf = vmcore_alloc_buf(*notes_sz);
1074 	if (!*notes_buf)
1075 		return -ENOMEM;
1076 
1077 	rc = copy_notes_elf32(ehdr_ptr, *notes_buf);
1078 	if (rc < 0)
1079 		return rc;
1080 
1081 	/* Prepare merged PT_NOTE program header. */
1082 	phdr.p_type    = PT_NOTE;
1083 	phdr.p_flags   = 0;
1084 	note_off = sizeof(Elf32_Ehdr) +
1085 			(ehdr_ptr->e_phnum - nr_ptnote +1) * sizeof(Elf32_Phdr);
1086 	phdr.p_offset  = roundup(note_off, PAGE_SIZE);
1087 	phdr.p_vaddr   = phdr.p_paddr = 0;
1088 	phdr.p_filesz  = phdr.p_memsz = phdr_sz;
1089 	phdr.p_align   = 4;
1090 
1091 	/* Add merged PT_NOTE program header*/
1092 	tmp = elfptr + sizeof(Elf32_Ehdr);
1093 	memcpy(tmp, &phdr, sizeof(phdr));
1094 	tmp += sizeof(phdr);
1095 
1096 	/* Remove unwanted PT_NOTE program headers. */
1097 	i = (nr_ptnote - 1) * sizeof(Elf32_Phdr);
1098 	*elfsz = *elfsz - i;
1099 	memmove(tmp, tmp+i, ((*elfsz)-sizeof(Elf32_Ehdr)-sizeof(Elf32_Phdr)));
1100 	memset(elfptr + *elfsz, 0, i);
1101 	*elfsz = roundup(*elfsz, PAGE_SIZE);
1102 
1103 	/* Modify e_phnum to reflect merged headers. */
1104 	ehdr_ptr->e_phnum = ehdr_ptr->e_phnum - nr_ptnote + 1;
1105 
1106 	/* Store the size of all notes.  We need this to update the note
1107 	 * header when the device dumps will be added.
1108 	 */
1109 	elfnotes_orig_sz = phdr.p_memsz;
1110 
1111 	return 0;
1112 }
1113 
1114 /* Add memory chunks represented by program headers to vmcore list. Also update
1115  * the new offset fields of exported program headers. */
1116 static int __init process_ptload_program_headers_elf64(char *elfptr,
1117 						size_t elfsz,
1118 						size_t elfnotes_sz,
1119 						struct list_head *vc_list)
1120 {
1121 	int i;
1122 	Elf64_Ehdr *ehdr_ptr;
1123 	Elf64_Phdr *phdr_ptr;
1124 	loff_t vmcore_off;
1125 
1126 	ehdr_ptr = (Elf64_Ehdr *)elfptr;
1127 	phdr_ptr = (Elf64_Phdr*)(elfptr + sizeof(Elf64_Ehdr)); /* PT_NOTE hdr */
1128 
1129 	/* Skip ELF header, program headers and ELF note segment. */
1130 	vmcore_off = elfsz + elfnotes_sz;
1131 
1132 	for (i = 0; i < ehdr_ptr->e_phnum; i++, phdr_ptr++) {
1133 		u64 paddr, start, end, size;
1134 
1135 		if (phdr_ptr->p_type != PT_LOAD)
1136 			continue;
1137 
1138 		paddr = phdr_ptr->p_offset;
1139 		start = rounddown(paddr, PAGE_SIZE);
1140 		end = roundup(paddr + phdr_ptr->p_memsz, PAGE_SIZE);
1141 		size = end - start;
1142 
1143 		if (vmcore_alloc_add_range(vc_list, start, size))
1144 			return -ENOMEM;
1145 
1146 		/* Update the program header offset. */
1147 		phdr_ptr->p_offset = vmcore_off + (paddr - start);
1148 		vmcore_off = vmcore_off + size;
1149 	}
1150 	return 0;
1151 }
1152 
1153 static int __init process_ptload_program_headers_elf32(char *elfptr,
1154 						size_t elfsz,
1155 						size_t elfnotes_sz,
1156 						struct list_head *vc_list)
1157 {
1158 	int i;
1159 	Elf32_Ehdr *ehdr_ptr;
1160 	Elf32_Phdr *phdr_ptr;
1161 	loff_t vmcore_off;
1162 
1163 	ehdr_ptr = (Elf32_Ehdr *)elfptr;
1164 	phdr_ptr = (Elf32_Phdr*)(elfptr + sizeof(Elf32_Ehdr)); /* PT_NOTE hdr */
1165 
1166 	/* Skip ELF header, program headers and ELF note segment. */
1167 	vmcore_off = elfsz + elfnotes_sz;
1168 
1169 	for (i = 0; i < ehdr_ptr->e_phnum; i++, phdr_ptr++) {
1170 		u64 paddr, start, end, size;
1171 
1172 		if (phdr_ptr->p_type != PT_LOAD)
1173 			continue;
1174 
1175 		paddr = phdr_ptr->p_offset;
1176 		start = rounddown(paddr, PAGE_SIZE);
1177 		end = roundup(paddr + phdr_ptr->p_memsz, PAGE_SIZE);
1178 		size = end - start;
1179 
1180 		if (vmcore_alloc_add_range(vc_list, start, size))
1181 			return -ENOMEM;
1182 
1183 		/* Update the program header offset */
1184 		phdr_ptr->p_offset = vmcore_off + (paddr - start);
1185 		vmcore_off = vmcore_off + size;
1186 	}
1187 	return 0;
1188 }
1189 
1190 /* Sets offset fields of vmcore elements. */
1191 static void set_vmcore_list_offsets(size_t elfsz, size_t elfnotes_sz,
1192 				    struct list_head *vc_list)
1193 {
1194 	struct vmcore_range *m;
1195 	loff_t vmcore_off;
1196 
1197 	/* Skip ELF header, program headers and ELF note segment. */
1198 	vmcore_off = elfsz + elfnotes_sz;
1199 
1200 	list_for_each_entry(m, vc_list, list) {
1201 		m->offset = vmcore_off;
1202 		vmcore_off += m->size;
1203 	}
1204 }
1205 
1206 static void free_elfcorebuf(void)
1207 {
1208 	free_pages((unsigned long)elfcorebuf, get_order(elfcorebuf_sz_orig));
1209 	elfcorebuf = NULL;
1210 	vfree(elfnotes_buf);
1211 	elfnotes_buf = NULL;
1212 }
1213 
1214 static int __init parse_crash_elf64_headers(void)
1215 {
1216 	int rc=0;
1217 	Elf64_Ehdr ehdr;
1218 	u64 addr;
1219 
1220 	addr = elfcorehdr_addr;
1221 
1222 	/* Read ELF header */
1223 	rc = elfcorehdr_read((char *)&ehdr, sizeof(Elf64_Ehdr), &addr);
1224 	if (rc < 0)
1225 		return rc;
1226 
1227 	/* Do some basic Verification. */
1228 	if (memcmp(ehdr.e_ident, ELFMAG, SELFMAG) != 0 ||
1229 		(ehdr.e_type != ET_CORE) ||
1230 		!vmcore_elf64_check_arch(&ehdr) ||
1231 		ehdr.e_ident[EI_CLASS] != ELFCLASS64 ||
1232 		ehdr.e_ident[EI_VERSION] != EV_CURRENT ||
1233 		ehdr.e_version != EV_CURRENT ||
1234 		ehdr.e_ehsize != sizeof(Elf64_Ehdr) ||
1235 		ehdr.e_phentsize != sizeof(Elf64_Phdr) ||
1236 		ehdr.e_phnum == 0) {
1237 		pr_warn("Warning: Core image elf header is not sane\n");
1238 		return -EINVAL;
1239 	}
1240 
1241 	/* Read in all elf headers. */
1242 	elfcorebuf_sz_orig = sizeof(Elf64_Ehdr) +
1243 				ehdr.e_phnum * sizeof(Elf64_Phdr);
1244 	elfcorebuf_sz = elfcorebuf_sz_orig;
1245 	elfcorebuf = (void *)__get_free_pages(GFP_KERNEL | __GFP_ZERO,
1246 					      get_order(elfcorebuf_sz_orig));
1247 	if (!elfcorebuf)
1248 		return -ENOMEM;
1249 	addr = elfcorehdr_addr;
1250 	rc = elfcorehdr_read(elfcorebuf, elfcorebuf_sz_orig, &addr);
1251 	if (rc < 0)
1252 		goto fail;
1253 
1254 	/* Merge all PT_NOTE headers into one. */
1255 	rc = merge_note_headers_elf64(elfcorebuf, &elfcorebuf_sz,
1256 				      &elfnotes_buf, &elfnotes_sz);
1257 	if (rc)
1258 		goto fail;
1259 	rc = process_ptload_program_headers_elf64(elfcorebuf, elfcorebuf_sz,
1260 						  elfnotes_sz, &vmcore_list);
1261 	if (rc)
1262 		goto fail;
1263 	set_vmcore_list_offsets(elfcorebuf_sz, elfnotes_sz, &vmcore_list);
1264 	return 0;
1265 fail:
1266 	free_elfcorebuf();
1267 	return rc;
1268 }
1269 
1270 static int __init parse_crash_elf32_headers(void)
1271 {
1272 	int rc=0;
1273 	Elf32_Ehdr ehdr;
1274 	u64 addr;
1275 
1276 	addr = elfcorehdr_addr;
1277 
1278 	/* Read ELF header */
1279 	rc = elfcorehdr_read((char *)&ehdr, sizeof(Elf32_Ehdr), &addr);
1280 	if (rc < 0)
1281 		return rc;
1282 
1283 	/* Do some basic Verification. */
1284 	if (memcmp(ehdr.e_ident, ELFMAG, SELFMAG) != 0 ||
1285 		(ehdr.e_type != ET_CORE) ||
1286 		!vmcore_elf32_check_arch(&ehdr) ||
1287 		ehdr.e_ident[EI_CLASS] != ELFCLASS32||
1288 		ehdr.e_ident[EI_VERSION] != EV_CURRENT ||
1289 		ehdr.e_version != EV_CURRENT ||
1290 		ehdr.e_ehsize != sizeof(Elf32_Ehdr) ||
1291 		ehdr.e_phentsize != sizeof(Elf32_Phdr) ||
1292 		ehdr.e_phnum == 0) {
1293 		pr_warn("Warning: Core image elf header is not sane\n");
1294 		return -EINVAL;
1295 	}
1296 
1297 	/* Read in all elf headers. */
1298 	elfcorebuf_sz_orig = sizeof(Elf32_Ehdr) + ehdr.e_phnum * sizeof(Elf32_Phdr);
1299 	elfcorebuf_sz = elfcorebuf_sz_orig;
1300 	elfcorebuf = (void *)__get_free_pages(GFP_KERNEL | __GFP_ZERO,
1301 					      get_order(elfcorebuf_sz_orig));
1302 	if (!elfcorebuf)
1303 		return -ENOMEM;
1304 	addr = elfcorehdr_addr;
1305 	rc = elfcorehdr_read(elfcorebuf, elfcorebuf_sz_orig, &addr);
1306 	if (rc < 0)
1307 		goto fail;
1308 
1309 	/* Merge all PT_NOTE headers into one. */
1310 	rc = merge_note_headers_elf32(elfcorebuf, &elfcorebuf_sz,
1311 				      &elfnotes_buf, &elfnotes_sz);
1312 	if (rc)
1313 		goto fail;
1314 	rc = process_ptload_program_headers_elf32(elfcorebuf, elfcorebuf_sz,
1315 						  elfnotes_sz, &vmcore_list);
1316 	if (rc)
1317 		goto fail;
1318 	set_vmcore_list_offsets(elfcorebuf_sz, elfnotes_sz, &vmcore_list);
1319 	return 0;
1320 fail:
1321 	free_elfcorebuf();
1322 	return rc;
1323 }
1324 
1325 static int __init parse_crash_elf_headers(void)
1326 {
1327 	unsigned char e_ident[EI_NIDENT];
1328 	u64 addr;
1329 	int rc=0;
1330 
1331 	addr = elfcorehdr_addr;
1332 	rc = elfcorehdr_read(e_ident, EI_NIDENT, &addr);
1333 	if (rc < 0)
1334 		return rc;
1335 	if (memcmp(e_ident, ELFMAG, SELFMAG) != 0) {
1336 		pr_warn("Warning: Core image elf header not found\n");
1337 		return -EINVAL;
1338 	}
1339 
1340 	if (e_ident[EI_CLASS] == ELFCLASS64) {
1341 		rc = parse_crash_elf64_headers();
1342 		if (rc)
1343 			return rc;
1344 	} else if (e_ident[EI_CLASS] == ELFCLASS32) {
1345 		rc = parse_crash_elf32_headers();
1346 		if (rc)
1347 			return rc;
1348 	} else {
1349 		pr_warn("Warning: Core image elf header is not sane\n");
1350 		return -EINVAL;
1351 	}
1352 
1353 	/* Determine vmcore size. */
1354 	vmcore_size = get_vmcore_size(elfcorebuf_sz, elfnotes_sz,
1355 				      &vmcore_list);
1356 
1357 	return 0;
1358 }
1359 
1360 #ifdef CONFIG_PROC_VMCORE_DEVICE_DUMP
1361 /**
1362  * vmcoredd_write_header - Write vmcore device dump header at the
1363  * beginning of the dump's buffer.
1364  * @buf: Output buffer where the note is written
1365  * @data: Dump info
1366  * @size: Size of the dump
1367  *
1368  * Fills beginning of the dump's buffer with vmcore device dump header.
1369  */
1370 static void vmcoredd_write_header(void *buf, struct vmcoredd_data *data,
1371 				  u32 size)
1372 {
1373 	struct vmcoredd_header *vdd_hdr = (struct vmcoredd_header *)buf;
1374 
1375 	vdd_hdr->n_namesz = sizeof(vdd_hdr->name);
1376 	vdd_hdr->n_descsz = size + sizeof(vdd_hdr->dump_name);
1377 	vdd_hdr->n_type = NT_VMCOREDD;
1378 
1379 	strscpy_pad(vdd_hdr->name, VMCOREDD_NOTE_NAME);
1380 	strscpy_pad(vdd_hdr->dump_name, data->dump_name);
1381 }
1382 
1383 /**
1384  * vmcoredd_update_program_headers - Update all ELF program headers
1385  * @elfptr: Pointer to elf header
1386  * @elfnotesz: Size of elf notes aligned to page size
1387  * @vmcoreddsz: Size of device dumps to be added to elf note header
1388  *
1389  * Determine type of ELF header (Elf64 or Elf32) and update the elf note size.
1390  * Also update the offsets of all the program headers after the elf note header.
1391  */
1392 static void vmcoredd_update_program_headers(char *elfptr, size_t elfnotesz,
1393 					    size_t vmcoreddsz)
1394 {
1395 	unsigned char *e_ident = (unsigned char *)elfptr;
1396 	u64 start, end, size;
1397 	loff_t vmcore_off;
1398 	u32 i;
1399 
1400 	vmcore_off = elfcorebuf_sz + elfnotesz;
1401 
1402 	if (e_ident[EI_CLASS] == ELFCLASS64) {
1403 		Elf64_Ehdr *ehdr = (Elf64_Ehdr *)elfptr;
1404 		Elf64_Phdr *phdr = (Elf64_Phdr *)(elfptr + sizeof(Elf64_Ehdr));
1405 
1406 		/* Update all program headers */
1407 		for (i = 0; i < ehdr->e_phnum; i++, phdr++) {
1408 			if (phdr->p_type == PT_NOTE) {
1409 				/* Update note size */
1410 				phdr->p_memsz = elfnotes_orig_sz + vmcoreddsz;
1411 				phdr->p_filesz = phdr->p_memsz;
1412 				continue;
1413 			}
1414 
1415 			start = rounddown(phdr->p_offset, PAGE_SIZE);
1416 			end = roundup(phdr->p_offset + phdr->p_memsz,
1417 				      PAGE_SIZE);
1418 			size = end - start;
1419 			phdr->p_offset = vmcore_off + (phdr->p_offset - start);
1420 			vmcore_off += size;
1421 		}
1422 	} else {
1423 		Elf32_Ehdr *ehdr = (Elf32_Ehdr *)elfptr;
1424 		Elf32_Phdr *phdr = (Elf32_Phdr *)(elfptr + sizeof(Elf32_Ehdr));
1425 
1426 		/* Update all program headers */
1427 		for (i = 0; i < ehdr->e_phnum; i++, phdr++) {
1428 			if (phdr->p_type == PT_NOTE) {
1429 				/* Update note size */
1430 				phdr->p_memsz = elfnotes_orig_sz + vmcoreddsz;
1431 				phdr->p_filesz = phdr->p_memsz;
1432 				continue;
1433 			}
1434 
1435 			start = rounddown(phdr->p_offset, PAGE_SIZE);
1436 			end = roundup(phdr->p_offset + phdr->p_memsz,
1437 				      PAGE_SIZE);
1438 			size = end - start;
1439 			phdr->p_offset = vmcore_off + (phdr->p_offset - start);
1440 			vmcore_off += size;
1441 		}
1442 	}
1443 }
1444 
1445 /**
1446  * vmcoredd_update_size - Update the total size of the device dumps and update
1447  * ELF header
1448  * @dump_size: Size of the current device dump to be added to total size
1449  *
1450  * Update the total size of all the device dumps and update the ELF program
1451  * headers. Calculate the new offsets for the vmcore list and update the
1452  * total vmcore size.
1453  */
1454 static void vmcoredd_update_size(size_t dump_size)
1455 {
1456 	vmcoredd_orig_sz += dump_size;
1457 	elfnotes_sz = roundup(elfnotes_orig_sz, PAGE_SIZE) + vmcoredd_orig_sz;
1458 	vmcoredd_update_program_headers(elfcorebuf, elfnotes_sz,
1459 					vmcoredd_orig_sz);
1460 
1461 	/* Update vmcore list offsets */
1462 	set_vmcore_list_offsets(elfcorebuf_sz, elfnotes_sz, &vmcore_list);
1463 
1464 	vmcore_size = get_vmcore_size(elfcorebuf_sz, elfnotes_sz,
1465 				      &vmcore_list);
1466 	proc_vmcore->size = vmcore_size;
1467 }
1468 
1469 /**
1470  * vmcore_add_device_dump - Add a buffer containing device dump to vmcore
1471  * @data: dump info.
1472  *
1473  * Allocate a buffer and invoke the calling driver's dump collect routine.
1474  * Write ELF note at the beginning of the buffer to indicate vmcore device
1475  * dump and add the dump to global list.
1476  */
1477 int vmcore_add_device_dump(struct vmcoredd_data *data)
1478 {
1479 	struct vmcoredd_node *dump;
1480 	void *buf = NULL;
1481 	size_t data_size;
1482 	int ret;
1483 
1484 	if (vmcoredd_disabled) {
1485 		pr_err_once("Device dump is disabled\n");
1486 		return -EINVAL;
1487 	}
1488 
1489 	if (!data || !strlen(data->dump_name) ||
1490 	    !data->vmcoredd_callback || !data->size)
1491 		return -EINVAL;
1492 
1493 	dump = vzalloc(sizeof(*dump));
1494 	if (!dump)
1495 		return -ENOMEM;
1496 
1497 	/* Keep size of the buffer page aligned so that it can be mmaped */
1498 	data_size = roundup(sizeof(struct vmcoredd_header) + data->size,
1499 			    PAGE_SIZE);
1500 
1501 	/* Allocate buffer for driver's to write their dumps */
1502 	buf = vmcore_alloc_buf(data_size);
1503 	if (!buf) {
1504 		ret = -ENOMEM;
1505 		goto out_err;
1506 	}
1507 
1508 	vmcoredd_write_header(buf, data, data_size -
1509 			      sizeof(struct vmcoredd_header));
1510 
1511 	/* Invoke the driver's dump collection routing */
1512 	ret = data->vmcoredd_callback(data, buf +
1513 				      sizeof(struct vmcoredd_header));
1514 	if (ret)
1515 		goto out_err;
1516 
1517 	dump->buf = buf;
1518 	dump->size = data_size;
1519 
1520 	/* Add the dump to driver sysfs list and update the elfcore hdr */
1521 	scoped_guard(mutex, &vmcore_mutex) {
1522 		if (vmcore_opened)
1523 			pr_warn_once("Unexpected adding of device dump\n");
1524 		if (vmcore_open) {
1525 			ret = -EBUSY;
1526 			goto out_err;
1527 		}
1528 
1529 		list_add_tail(&dump->list, &vmcoredd_list);
1530 		vmcoredd_update_size(data_size);
1531 	}
1532 	return 0;
1533 
1534 out_err:
1535 	vfree(buf);
1536 	vfree(dump);
1537 
1538 	return ret;
1539 }
1540 EXPORT_SYMBOL(vmcore_add_device_dump);
1541 #endif /* CONFIG_PROC_VMCORE_DEVICE_DUMP */
1542 
1543 #ifdef CONFIG_PROC_VMCORE_DEVICE_RAM
1544 static int vmcore_realloc_elfcore_buffer_elf64(size_t new_size)
1545 {
1546 	char *elfcorebuf_new;
1547 
1548 	if (WARN_ON_ONCE(new_size < elfcorebuf_sz))
1549 		return -EINVAL;
1550 	if (get_order(elfcorebuf_sz_orig) == get_order(new_size)) {
1551 		elfcorebuf_sz_orig = new_size;
1552 		return 0;
1553 	}
1554 
1555 	elfcorebuf_new = (void *)__get_free_pages(GFP_KERNEL | __GFP_ZERO,
1556 						  get_order(new_size));
1557 	if (!elfcorebuf_new)
1558 		return -ENOMEM;
1559 	memcpy(elfcorebuf_new, elfcorebuf, elfcorebuf_sz);
1560 	free_pages((unsigned long)elfcorebuf, get_order(elfcorebuf_sz_orig));
1561 	elfcorebuf = elfcorebuf_new;
1562 	elfcorebuf_sz_orig = new_size;
1563 	return 0;
1564 }
1565 
1566 static void vmcore_reset_offsets_elf64(void)
1567 {
1568 	Elf64_Phdr *phdr_start = (Elf64_Phdr *)(elfcorebuf + sizeof(Elf64_Ehdr));
1569 	loff_t vmcore_off = elfcorebuf_sz + elfnotes_sz;
1570 	Elf64_Ehdr *ehdr = (Elf64_Ehdr *)elfcorebuf;
1571 	Elf64_Phdr *phdr;
1572 	int i;
1573 
1574 	for (i = 0, phdr = phdr_start; i < ehdr->e_phnum; i++, phdr++) {
1575 		u64 start, end;
1576 
1577 		/*
1578 		 * After merge_note_headers_elf64() we should only have a single
1579 		 * PT_NOTE entry that starts immediately after elfcorebuf_sz.
1580 		 */
1581 		if (phdr->p_type == PT_NOTE) {
1582 			phdr->p_offset = elfcorebuf_sz;
1583 			continue;
1584 		}
1585 
1586 		start = rounddown(phdr->p_offset, PAGE_SIZE);
1587 		end = roundup(phdr->p_offset + phdr->p_memsz, PAGE_SIZE);
1588 		phdr->p_offset = vmcore_off + (phdr->p_offset - start);
1589 		vmcore_off = vmcore_off + end - start;
1590 	}
1591 	set_vmcore_list_offsets(elfcorebuf_sz, elfnotes_sz, &vmcore_list);
1592 }
1593 
1594 static int vmcore_add_device_ram_elf64(struct list_head *list, size_t count)
1595 {
1596 	Elf64_Phdr *phdr_start = (Elf64_Phdr *)(elfcorebuf + sizeof(Elf64_Ehdr));
1597 	Elf64_Ehdr *ehdr = (Elf64_Ehdr *)elfcorebuf;
1598 	struct vmcore_range *cur;
1599 	Elf64_Phdr *phdr;
1600 	size_t new_size;
1601 	int rc;
1602 
1603 	if ((Elf32_Half)(ehdr->e_phnum + count) != ehdr->e_phnum + count) {
1604 		pr_err("too many device ram ranges\n");
1605 		return -ENOSPC;
1606 	}
1607 
1608 	/* elfcorebuf_sz must always cover full pages. */
1609 	new_size = sizeof(Elf64_Ehdr) +
1610 		   (ehdr->e_phnum + count) * sizeof(Elf64_Phdr);
1611 	new_size = roundup(new_size, PAGE_SIZE);
1612 
1613 	/*
1614 	 * Make sure we have sufficient space to include the new PT_LOAD
1615 	 * entries.
1616 	 */
1617 	rc = vmcore_realloc_elfcore_buffer_elf64(new_size);
1618 	if (rc) {
1619 		pr_err("resizing elfcore failed\n");
1620 		return rc;
1621 	}
1622 
1623 	/* Modify our used elfcore buffer size to cover the new entries. */
1624 	elfcorebuf_sz = new_size;
1625 
1626 	/* Fill the added PT_LOAD entries. */
1627 	phdr = phdr_start + ehdr->e_phnum;
1628 	list_for_each_entry(cur, list, list) {
1629 		WARN_ON_ONCE(!IS_ALIGNED(cur->paddr | cur->size, PAGE_SIZE));
1630 		elfcorehdr_fill_device_ram_ptload_elf64(phdr, cur->paddr, cur->size);
1631 
1632 		/* p_offset will be adjusted later. */
1633 		phdr++;
1634 		ehdr->e_phnum++;
1635 	}
1636 	list_splice_tail(list, &vmcore_list);
1637 
1638 	/* We changed elfcorebuf_sz and added new entries; reset all offsets. */
1639 	vmcore_reset_offsets_elf64();
1640 
1641 	/* Finally, recalculate the total vmcore size. */
1642 	vmcore_size = get_vmcore_size(elfcorebuf_sz, elfnotes_sz,
1643 				      &vmcore_list);
1644 	proc_vmcore->size = vmcore_size;
1645 	return 0;
1646 }
1647 
1648 static void vmcore_process_device_ram(struct vmcore_cb *cb)
1649 {
1650 	unsigned char *e_ident = (unsigned char *)elfcorebuf;
1651 	struct vmcore_range *first, *m;
1652 	LIST_HEAD(list);
1653 	int count;
1654 
1655 	/* We only support Elf64 dumps for now. */
1656 	if (WARN_ON_ONCE(e_ident[EI_CLASS] != ELFCLASS64)) {
1657 		pr_err("device ram ranges only support Elf64\n");
1658 		return;
1659 	}
1660 
1661 	if (cb->get_device_ram(cb, &list)) {
1662 		pr_err("obtaining device ram ranges failed\n");
1663 		return;
1664 	}
1665 	count = list_count_nodes(&list);
1666 	if (!count)
1667 		return;
1668 
1669 	/*
1670 	 * For some reason these ranges are already know? Might happen
1671 	 * with unusual register->unregister->register sequences; we'll simply
1672 	 * sanity check using the first range.
1673 	 */
1674 	first = list_first_entry(&list, struct vmcore_range, list);
1675 	list_for_each_entry(m, &vmcore_list, list) {
1676 		unsigned long long m_end = m->paddr + m->size;
1677 		unsigned long long first_end = first->paddr + first->size;
1678 
1679 		if (first->paddr < m_end && m->paddr < first_end)
1680 			goto out_free;
1681 	}
1682 
1683 	/* If adding the mem nodes succeeds, they must not be freed. */
1684 	if (!vmcore_add_device_ram_elf64(&list, count))
1685 		return;
1686 out_free:
1687 	vmcore_free_ranges(&list);
1688 }
1689 #else /* !CONFIG_PROC_VMCORE_DEVICE_RAM */
1690 static void vmcore_process_device_ram(struct vmcore_cb *cb)
1691 {
1692 }
1693 #endif /* CONFIG_PROC_VMCORE_DEVICE_RAM */
1694 
1695 /* Free all dumps in vmcore device dump list */
1696 static void vmcore_free_device_dumps(void)
1697 {
1698 #ifdef CONFIG_PROC_VMCORE_DEVICE_DUMP
1699 	mutex_lock(&vmcore_mutex);
1700 	while (!list_empty(&vmcoredd_list)) {
1701 		struct vmcoredd_node *dump;
1702 
1703 		dump = list_first_entry(&vmcoredd_list, struct vmcoredd_node,
1704 					list);
1705 		list_del(&dump->list);
1706 		vfree(dump->buf);
1707 		vfree(dump);
1708 	}
1709 	mutex_unlock(&vmcore_mutex);
1710 #endif /* CONFIG_PROC_VMCORE_DEVICE_DUMP */
1711 }
1712 
1713 #define VMCOREINFO_OSRELEASE_KEY	"OSRELEASE="
1714 
1715 static void __init vmcore_report_crashed_release(void)
1716 {
1717 	const char *ver, *eol;
1718 
1719 	ver = strnstr(elfnotes_buf, VMCOREINFO_OSRELEASE_KEY, elfnotes_sz);
1720 	if (!ver)
1721 		return;
1722 
1723 	ver += sizeof(VMCOREINFO_OSRELEASE_KEY) - 1;
1724 	eol = memchr(ver, '\n', elfnotes_buf + elfnotes_sz - ver);
1725 	if (!eol)
1726 		return;
1727 
1728 	pr_notice("dump is from kernel %.*s\n", (int)(eol - ver), ver);
1729 }
1730 
1731 /* Init function for vmcore module. */
1732 static int __init vmcore_init(void)
1733 {
1734 	int rc = 0;
1735 
1736 	/* Allow architectures to allocate ELF header in 2nd kernel */
1737 	rc = elfcorehdr_alloc(&elfcorehdr_addr, &elfcorehdr_size);
1738 	if (rc)
1739 		return rc;
1740 	/*
1741 	 * If elfcorehdr= has been passed in cmdline or created in 2nd kernel,
1742 	 * then capture the dump.
1743 	 */
1744 	if (!(is_vmcore_usable()))
1745 		return rc;
1746 	rc = parse_crash_elf_headers();
1747 	if (rc) {
1748 		elfcorehdr_free(elfcorehdr_addr);
1749 		pr_warn("not initialized\n");
1750 		return rc;
1751 	}
1752 	elfcorehdr_free(elfcorehdr_addr);
1753 	elfcorehdr_addr = ELFCORE_ADDR_ERR;
1754 
1755 	vmcore_report_crashed_release();
1756 
1757 	proc_vmcore = proc_create("vmcore", S_IRUSR, NULL, &vmcore_proc_ops);
1758 	if (proc_vmcore)
1759 		proc_vmcore->size = vmcore_size;
1760 	return 0;
1761 }
1762 fs_initcall(vmcore_init);
1763 
1764 /* Cleanup function for vmcore module. */
1765 void vmcore_cleanup(void)
1766 {
1767 	if (proc_vmcore) {
1768 		proc_remove(proc_vmcore);
1769 		proc_vmcore = NULL;
1770 	}
1771 
1772 	vmcore_free_ranges(&vmcore_list);
1773 	free_elfcorebuf();
1774 
1775 	/* clear vmcore device dump list */
1776 	vmcore_free_device_dumps();
1777 }
1778