xref: /qemu/dump/dump.c (revision ac978771)
1 /*
2  * QEMU dump
3  *
4  * Copyright Fujitsu, Corp. 2011, 2012
5  *
6  * Authors:
7  *     Wen Congyang <wency@cn.fujitsu.com>
8  *
9  * This work is licensed under the terms of the GNU GPL, version 2 or later.
10  * See the COPYING file in the top-level directory.
11  *
12  */
13 
14 #include "qemu/osdep.h"
15 #include "qemu/cutils.h"
16 #include "elf.h"
17 #include "qemu/bswap.h"
18 #include "exec/target_page.h"
19 #include "monitor/monitor.h"
20 #include "sysemu/dump.h"
21 #include "sysemu/runstate.h"
22 #include "sysemu/cpus.h"
23 #include "qapi/error.h"
24 #include "qapi/qapi-commands-dump.h"
25 #include "qapi/qapi-events-dump.h"
26 #include "qapi/qmp/qerror.h"
27 #include "qemu/main-loop.h"
28 #include "hw/misc/vmcoreinfo.h"
29 #include "migration/blocker.h"
30 #include "hw/core/cpu.h"
31 
32 #ifdef TARGET_X86_64
33 #include "win_dump.h"
34 #endif
35 
36 #include <zlib.h>
37 #ifdef CONFIG_LZO
38 #include <lzo/lzo1x.h>
39 #endif
40 #ifdef CONFIG_SNAPPY
41 #include <snappy-c.h>
42 #endif
43 #ifndef ELF_MACHINE_UNAME
44 #define ELF_MACHINE_UNAME "Unknown"
45 #endif
46 
47 #define MAX_GUEST_NOTE_SIZE (1 << 20) /* 1MB should be enough */
48 
49 static Error *dump_migration_blocker;
50 
51 #define ELF_NOTE_SIZE(hdr_size, name_size, desc_size)   \
52     ((DIV_ROUND_UP((hdr_size), 4) +                     \
53       DIV_ROUND_UP((name_size), 4) +                    \
54       DIV_ROUND_UP((desc_size), 4)) * 4)
55 
56 static inline bool dump_is_64bit(DumpState *s)
57 {
58     return s->dump_info.d_class == ELFCLASS64;
59 }
60 
61 static inline bool dump_has_filter(DumpState *s)
62 {
63     return s->filter_area_length > 0;
64 }
65 
66 uint16_t cpu_to_dump16(DumpState *s, uint16_t val)
67 {
68     if (s->dump_info.d_endian == ELFDATA2LSB) {
69         val = cpu_to_le16(val);
70     } else {
71         val = cpu_to_be16(val);
72     }
73 
74     return val;
75 }
76 
77 uint32_t cpu_to_dump32(DumpState *s, uint32_t val)
78 {
79     if (s->dump_info.d_endian == ELFDATA2LSB) {
80         val = cpu_to_le32(val);
81     } else {
82         val = cpu_to_be32(val);
83     }
84 
85     return val;
86 }
87 
88 uint64_t cpu_to_dump64(DumpState *s, uint64_t val)
89 {
90     if (s->dump_info.d_endian == ELFDATA2LSB) {
91         val = cpu_to_le64(val);
92     } else {
93         val = cpu_to_be64(val);
94     }
95 
96     return val;
97 }
98 
99 static int dump_cleanup(DumpState *s)
100 {
101     guest_phys_blocks_free(&s->guest_phys_blocks);
102     memory_mapping_list_free(&s->list);
103     close(s->fd);
104     g_free(s->guest_note);
105     g_array_unref(s->string_table_buf);
106     s->guest_note = NULL;
107     if (s->resume) {
108         if (s->detached) {
109             qemu_mutex_lock_iothread();
110         }
111         vm_start();
112         if (s->detached) {
113             qemu_mutex_unlock_iothread();
114         }
115     }
116     migrate_del_blocker(dump_migration_blocker);
117 
118     return 0;
119 }
120 
121 static int fd_write_vmcore(const void *buf, size_t size, void *opaque)
122 {
123     DumpState *s = opaque;
124     size_t written_size;
125 
126     written_size = qemu_write_full(s->fd, buf, size);
127     if (written_size != size) {
128         return -errno;
129     }
130 
131     return 0;
132 }
133 
134 static void prepare_elf64_header(DumpState *s, Elf64_Ehdr *elf_header)
135 {
136     /*
137      * phnum in the elf header is 16 bit, if we have more segments we
138      * set phnum to PN_XNUM and write the real number of segments to a
139      * special section.
140      */
141     uint16_t phnum = MIN(s->phdr_num, PN_XNUM);
142 
143     memset(elf_header, 0, sizeof(Elf64_Ehdr));
144     memcpy(elf_header, ELFMAG, SELFMAG);
145     elf_header->e_ident[EI_CLASS] = ELFCLASS64;
146     elf_header->e_ident[EI_DATA] = s->dump_info.d_endian;
147     elf_header->e_ident[EI_VERSION] = EV_CURRENT;
148     elf_header->e_type = cpu_to_dump16(s, ET_CORE);
149     elf_header->e_machine = cpu_to_dump16(s, s->dump_info.d_machine);
150     elf_header->e_version = cpu_to_dump32(s, EV_CURRENT);
151     elf_header->e_ehsize = cpu_to_dump16(s, sizeof(elf_header));
152     elf_header->e_phoff = cpu_to_dump64(s, s->phdr_offset);
153     elf_header->e_phentsize = cpu_to_dump16(s, sizeof(Elf64_Phdr));
154     elf_header->e_phnum = cpu_to_dump16(s, phnum);
155     elf_header->e_shoff = cpu_to_dump64(s, s->shdr_offset);
156     elf_header->e_shentsize = cpu_to_dump16(s, sizeof(Elf64_Shdr));
157     elf_header->e_shnum = cpu_to_dump16(s, s->shdr_num);
158     elf_header->e_shstrndx = cpu_to_dump16(s, s->shdr_num - 1);
159 }
160 
161 static void prepare_elf32_header(DumpState *s, Elf32_Ehdr *elf_header)
162 {
163     /*
164      * phnum in the elf header is 16 bit, if we have more segments we
165      * set phnum to PN_XNUM and write the real number of segments to a
166      * special section.
167      */
168     uint16_t phnum = MIN(s->phdr_num, PN_XNUM);
169 
170     memset(elf_header, 0, sizeof(Elf32_Ehdr));
171     memcpy(elf_header, ELFMAG, SELFMAG);
172     elf_header->e_ident[EI_CLASS] = ELFCLASS32;
173     elf_header->e_ident[EI_DATA] = s->dump_info.d_endian;
174     elf_header->e_ident[EI_VERSION] = EV_CURRENT;
175     elf_header->e_type = cpu_to_dump16(s, ET_CORE);
176     elf_header->e_machine = cpu_to_dump16(s, s->dump_info.d_machine);
177     elf_header->e_version = cpu_to_dump32(s, EV_CURRENT);
178     elf_header->e_ehsize = cpu_to_dump16(s, sizeof(elf_header));
179     elf_header->e_phoff = cpu_to_dump32(s, s->phdr_offset);
180     elf_header->e_phentsize = cpu_to_dump16(s, sizeof(Elf32_Phdr));
181     elf_header->e_phnum = cpu_to_dump16(s, phnum);
182     elf_header->e_shoff = cpu_to_dump32(s, s->shdr_offset);
183     elf_header->e_shentsize = cpu_to_dump16(s, sizeof(Elf32_Shdr));
184     elf_header->e_shnum = cpu_to_dump16(s, s->shdr_num);
185     elf_header->e_shstrndx = cpu_to_dump16(s, s->shdr_num - 1);
186 }
187 
188 static void write_elf_header(DumpState *s, Error **errp)
189 {
190     Elf32_Ehdr elf32_header;
191     Elf64_Ehdr elf64_header;
192     size_t header_size;
193     void *header_ptr;
194     int ret;
195 
196     /* The NULL header and the shstrtab are always defined */
197     assert(s->shdr_num >= 2);
198     if (dump_is_64bit(s)) {
199         prepare_elf64_header(s, &elf64_header);
200         header_size = sizeof(elf64_header);
201         header_ptr = &elf64_header;
202     } else {
203         prepare_elf32_header(s, &elf32_header);
204         header_size = sizeof(elf32_header);
205         header_ptr = &elf32_header;
206     }
207 
208     ret = fd_write_vmcore(header_ptr, header_size, s);
209     if (ret < 0) {
210         error_setg_errno(errp, -ret, "dump: failed to write elf header");
211     }
212 }
213 
214 static void write_elf64_load(DumpState *s, MemoryMapping *memory_mapping,
215                              int phdr_index, hwaddr offset,
216                              hwaddr filesz, Error **errp)
217 {
218     Elf64_Phdr phdr;
219     int ret;
220 
221     memset(&phdr, 0, sizeof(Elf64_Phdr));
222     phdr.p_type = cpu_to_dump32(s, PT_LOAD);
223     phdr.p_offset = cpu_to_dump64(s, offset);
224     phdr.p_paddr = cpu_to_dump64(s, memory_mapping->phys_addr);
225     phdr.p_filesz = cpu_to_dump64(s, filesz);
226     phdr.p_memsz = cpu_to_dump64(s, memory_mapping->length);
227     phdr.p_vaddr = cpu_to_dump64(s, memory_mapping->virt_addr) ?: phdr.p_paddr;
228 
229     assert(memory_mapping->length >= filesz);
230 
231     ret = fd_write_vmcore(&phdr, sizeof(Elf64_Phdr), s);
232     if (ret < 0) {
233         error_setg_errno(errp, -ret,
234                          "dump: failed to write program header table");
235     }
236 }
237 
238 static void write_elf32_load(DumpState *s, MemoryMapping *memory_mapping,
239                              int phdr_index, hwaddr offset,
240                              hwaddr filesz, Error **errp)
241 {
242     Elf32_Phdr phdr;
243     int ret;
244 
245     memset(&phdr, 0, sizeof(Elf32_Phdr));
246     phdr.p_type = cpu_to_dump32(s, PT_LOAD);
247     phdr.p_offset = cpu_to_dump32(s, offset);
248     phdr.p_paddr = cpu_to_dump32(s, memory_mapping->phys_addr);
249     phdr.p_filesz = cpu_to_dump32(s, filesz);
250     phdr.p_memsz = cpu_to_dump32(s, memory_mapping->length);
251     phdr.p_vaddr =
252         cpu_to_dump32(s, memory_mapping->virt_addr) ?: phdr.p_paddr;
253 
254     assert(memory_mapping->length >= filesz);
255 
256     ret = fd_write_vmcore(&phdr, sizeof(Elf32_Phdr), s);
257     if (ret < 0) {
258         error_setg_errno(errp, -ret,
259                          "dump: failed to write program header table");
260     }
261 }
262 
263 static void prepare_elf64_phdr_note(DumpState *s, Elf64_Phdr *phdr)
264 {
265     memset(phdr, 0, sizeof(*phdr));
266     phdr->p_type = cpu_to_dump32(s, PT_NOTE);
267     phdr->p_offset = cpu_to_dump64(s, s->note_offset);
268     phdr->p_paddr = 0;
269     phdr->p_filesz = cpu_to_dump64(s, s->note_size);
270     phdr->p_memsz = cpu_to_dump64(s, s->note_size);
271     phdr->p_vaddr = 0;
272 }
273 
274 static inline int cpu_index(CPUState *cpu)
275 {
276     return cpu->cpu_index + 1;
277 }
278 
279 static void write_guest_note(WriteCoreDumpFunction f, DumpState *s,
280                              Error **errp)
281 {
282     int ret;
283 
284     if (s->guest_note) {
285         ret = f(s->guest_note, s->guest_note_size, s);
286         if (ret < 0) {
287             error_setg(errp, "dump: failed to write guest note");
288         }
289     }
290 }
291 
292 static void write_elf64_notes(WriteCoreDumpFunction f, DumpState *s,
293                               Error **errp)
294 {
295     CPUState *cpu;
296     int ret;
297     int id;
298 
299     CPU_FOREACH(cpu) {
300         id = cpu_index(cpu);
301         ret = cpu_write_elf64_note(f, cpu, id, s);
302         if (ret < 0) {
303             error_setg(errp, "dump: failed to write elf notes");
304             return;
305         }
306     }
307 
308     CPU_FOREACH(cpu) {
309         ret = cpu_write_elf64_qemunote(f, cpu, s);
310         if (ret < 0) {
311             error_setg(errp, "dump: failed to write CPU status");
312             return;
313         }
314     }
315 
316     write_guest_note(f, s, errp);
317 }
318 
319 static void prepare_elf32_phdr_note(DumpState *s, Elf32_Phdr *phdr)
320 {
321     memset(phdr, 0, sizeof(*phdr));
322     phdr->p_type = cpu_to_dump32(s, PT_NOTE);
323     phdr->p_offset = cpu_to_dump32(s, s->note_offset);
324     phdr->p_paddr = 0;
325     phdr->p_filesz = cpu_to_dump32(s, s->note_size);
326     phdr->p_memsz = cpu_to_dump32(s, s->note_size);
327     phdr->p_vaddr = 0;
328 }
329 
330 static void write_elf32_notes(WriteCoreDumpFunction f, DumpState *s,
331                               Error **errp)
332 {
333     CPUState *cpu;
334     int ret;
335     int id;
336 
337     CPU_FOREACH(cpu) {
338         id = cpu_index(cpu);
339         ret = cpu_write_elf32_note(f, cpu, id, s);
340         if (ret < 0) {
341             error_setg(errp, "dump: failed to write elf notes");
342             return;
343         }
344     }
345 
346     CPU_FOREACH(cpu) {
347         ret = cpu_write_elf32_qemunote(f, cpu, s);
348         if (ret < 0) {
349             error_setg(errp, "dump: failed to write CPU status");
350             return;
351         }
352     }
353 
354     write_guest_note(f, s, errp);
355 }
356 
357 static void write_elf_phdr_note(DumpState *s, Error **errp)
358 {
359     Elf32_Phdr phdr32;
360     Elf64_Phdr phdr64;
361     void *phdr;
362     size_t size;
363     int ret;
364 
365     if (dump_is_64bit(s)) {
366         prepare_elf64_phdr_note(s, &phdr64);
367         size = sizeof(phdr64);
368         phdr = &phdr64;
369     } else {
370         prepare_elf32_phdr_note(s, &phdr32);
371         size = sizeof(phdr32);
372         phdr = &phdr32;
373     }
374 
375     ret = fd_write_vmcore(phdr, size, s);
376     if (ret < 0) {
377         error_setg_errno(errp, -ret,
378                          "dump: failed to write program header table");
379     }
380 }
381 
382 static void prepare_elf_section_hdr_zero(DumpState *s)
383 {
384     if (dump_is_64bit(s)) {
385         Elf64_Shdr *shdr64 = s->elf_section_hdrs;
386 
387         shdr64->sh_info = cpu_to_dump32(s, s->phdr_num);
388     } else {
389         Elf32_Shdr *shdr32 = s->elf_section_hdrs;
390 
391         shdr32->sh_info = cpu_to_dump32(s, s->phdr_num);
392     }
393 }
394 
395 static void prepare_elf_section_hdr_string(DumpState *s, void *buff)
396 {
397     uint64_t index = s->string_table_buf->len;
398     const char strtab[] = ".shstrtab";
399     Elf32_Shdr shdr32 = {};
400     Elf64_Shdr shdr64 = {};
401     int shdr_size;
402     void *shdr;
403 
404     g_array_append_vals(s->string_table_buf, strtab, sizeof(strtab));
405     if (dump_is_64bit(s)) {
406         shdr_size = sizeof(Elf64_Shdr);
407         shdr64.sh_type = SHT_STRTAB;
408         shdr64.sh_offset = s->section_offset + s->elf_section_data_size;
409         shdr64.sh_name = index;
410         shdr64.sh_size = s->string_table_buf->len;
411         shdr = &shdr64;
412     } else {
413         shdr_size = sizeof(Elf32_Shdr);
414         shdr32.sh_type = SHT_STRTAB;
415         shdr32.sh_offset = s->section_offset + s->elf_section_data_size;
416         shdr32.sh_name = index;
417         shdr32.sh_size = s->string_table_buf->len;
418         shdr = &shdr32;
419     }
420     memcpy(buff, shdr, shdr_size);
421 }
422 
423 static bool prepare_elf_section_hdrs(DumpState *s, Error **errp)
424 {
425     size_t len, sizeof_shdr;
426     void *buff_hdr;
427 
428     /*
429      * Section ordering:
430      * - HDR zero
431      * - Arch section hdrs
432      * - String table hdr
433      */
434     sizeof_shdr = dump_is_64bit(s) ? sizeof(Elf64_Shdr) : sizeof(Elf32_Shdr);
435     len = sizeof_shdr * s->shdr_num;
436     s->elf_section_hdrs = g_malloc0(len);
437     buff_hdr = s->elf_section_hdrs;
438 
439     /*
440      * The first section header is ALWAYS a special initial section
441      * header.
442      *
443      * The header should be 0 with one exception being that if
444      * phdr_num is PN_XNUM then the sh_info field contains the real
445      * number of segment entries.
446      *
447      * As we zero allocate the buffer we will only need to modify
448      * sh_info for the PN_XNUM case.
449      */
450     if (s->phdr_num >= PN_XNUM) {
451         prepare_elf_section_hdr_zero(s);
452     }
453     buff_hdr += sizeof_shdr;
454 
455     /* Add architecture defined section headers */
456     if (s->dump_info.arch_sections_write_hdr_fn
457         && s->shdr_num > 2) {
458         buff_hdr += s->dump_info.arch_sections_write_hdr_fn(s, buff_hdr);
459 
460         if (s->shdr_num >= SHN_LORESERVE) {
461             error_setg_errno(errp, EINVAL,
462                              "dump: too many architecture defined sections");
463             return false;
464         }
465     }
466 
467     /*
468      * String table is the last section since strings are added via
469      * arch_sections_write_hdr().
470      */
471     prepare_elf_section_hdr_string(s, buff_hdr);
472     return true;
473 }
474 
475 static void write_elf_section_headers(DumpState *s, Error **errp)
476 {
477     size_t sizeof_shdr = dump_is_64bit(s) ? sizeof(Elf64_Shdr) : sizeof(Elf32_Shdr);
478     int ret;
479 
480     if (!prepare_elf_section_hdrs(s, errp)) {
481         return;
482     }
483 
484     ret = fd_write_vmcore(s->elf_section_hdrs, s->shdr_num * sizeof_shdr, s);
485     if (ret < 0) {
486         error_setg_errno(errp, -ret, "dump: failed to write section headers");
487     }
488 
489     g_free(s->elf_section_hdrs);
490 }
491 
492 static void write_elf_sections(DumpState *s, Error **errp)
493 {
494     int ret;
495 
496     if (s->elf_section_data_size) {
497         /* Write architecture section data */
498         ret = fd_write_vmcore(s->elf_section_data,
499                               s->elf_section_data_size, s);
500         if (ret < 0) {
501             error_setg_errno(errp, -ret,
502                              "dump: failed to write architecture section data");
503             return;
504         }
505     }
506 
507     /* Write string table */
508     ret = fd_write_vmcore(s->string_table_buf->data,
509                           s->string_table_buf->len, s);
510     if (ret < 0) {
511         error_setg_errno(errp, -ret, "dump: failed to write string table data");
512     }
513 }
514 
515 static void write_data(DumpState *s, void *buf, int length, Error **errp)
516 {
517     int ret;
518 
519     ret = fd_write_vmcore(buf, length, s);
520     if (ret < 0) {
521         error_setg_errno(errp, -ret, "dump: failed to save memory");
522     } else {
523         s->written_size += length;
524     }
525 }
526 
527 /* write the memory to vmcore. 1 page per I/O. */
528 static void write_memory(DumpState *s, GuestPhysBlock *block, ram_addr_t start,
529                          int64_t size, Error **errp)
530 {
531     ERRP_GUARD();
532     int64_t i;
533 
534     for (i = 0; i < size / s->dump_info.page_size; i++) {
535         write_data(s, block->host_addr + start + i * s->dump_info.page_size,
536                    s->dump_info.page_size, errp);
537         if (*errp) {
538             return;
539         }
540     }
541 
542     if ((size % s->dump_info.page_size) != 0) {
543         write_data(s, block->host_addr + start + i * s->dump_info.page_size,
544                    size % s->dump_info.page_size, errp);
545         if (*errp) {
546             return;
547         }
548     }
549 }
550 
551 /* get the memory's offset and size in the vmcore */
552 static void get_offset_range(hwaddr phys_addr,
553                              ram_addr_t mapping_length,
554                              DumpState *s,
555                              hwaddr *p_offset,
556                              hwaddr *p_filesz)
557 {
558     GuestPhysBlock *block;
559     hwaddr offset = s->memory_offset;
560     int64_t size_in_block, start;
561 
562     /* When the memory is not stored into vmcore, offset will be -1 */
563     *p_offset = -1;
564     *p_filesz = 0;
565 
566     if (dump_has_filter(s)) {
567         if (phys_addr < s->filter_area_begin ||
568             phys_addr >= s->filter_area_begin + s->filter_area_length) {
569             return;
570         }
571     }
572 
573     QTAILQ_FOREACH(block, &s->guest_phys_blocks.head, next) {
574         if (dump_has_filter(s)) {
575             if (block->target_start >= s->filter_area_begin + s->filter_area_length ||
576                 block->target_end <= s->filter_area_begin) {
577                 /* This block is out of the range */
578                 continue;
579             }
580 
581             if (s->filter_area_begin <= block->target_start) {
582                 start = block->target_start;
583             } else {
584                 start = s->filter_area_begin;
585             }
586 
587             size_in_block = block->target_end - start;
588             if (s->filter_area_begin + s->filter_area_length < block->target_end) {
589                 size_in_block -= block->target_end - (s->filter_area_begin + s->filter_area_length);
590             }
591         } else {
592             start = block->target_start;
593             size_in_block = block->target_end - block->target_start;
594         }
595 
596         if (phys_addr >= start && phys_addr < start + size_in_block) {
597             *p_offset = phys_addr - start + offset;
598 
599             /* The offset range mapped from the vmcore file must not spill over
600              * the GuestPhysBlock, clamp it. The rest of the mapping will be
601              * zero-filled in memory at load time; see
602              * <http://refspecs.linuxbase.org/elf/gabi4+/ch5.pheader.html>.
603              */
604             *p_filesz = phys_addr + mapping_length <= start + size_in_block ?
605                         mapping_length :
606                         size_in_block - (phys_addr - start);
607             return;
608         }
609 
610         offset += size_in_block;
611     }
612 }
613 
614 static void write_elf_phdr_loads(DumpState *s, Error **errp)
615 {
616     ERRP_GUARD();
617     hwaddr offset, filesz;
618     MemoryMapping *memory_mapping;
619     uint32_t phdr_index = 1;
620 
621     QTAILQ_FOREACH(memory_mapping, &s->list.head, next) {
622         get_offset_range(memory_mapping->phys_addr,
623                          memory_mapping->length,
624                          s, &offset, &filesz);
625         if (dump_is_64bit(s)) {
626             write_elf64_load(s, memory_mapping, phdr_index++, offset,
627                              filesz, errp);
628         } else {
629             write_elf32_load(s, memory_mapping, phdr_index++, offset,
630                              filesz, errp);
631         }
632 
633         if (*errp) {
634             return;
635         }
636 
637         if (phdr_index >= s->phdr_num) {
638             break;
639         }
640     }
641 }
642 
643 static void write_elf_notes(DumpState *s, Error **errp)
644 {
645     if (dump_is_64bit(s)) {
646         write_elf64_notes(fd_write_vmcore, s, errp);
647     } else {
648         write_elf32_notes(fd_write_vmcore, s, errp);
649     }
650 }
651 
652 /* write elf header, PT_NOTE and elf note to vmcore. */
653 static void dump_begin(DumpState *s, Error **errp)
654 {
655     ERRP_GUARD();
656 
657     /*
658      * the vmcore's format is:
659      *   --------------
660      *   |  elf header |
661      *   --------------
662      *   |  sctn_hdr   |
663      *   --------------
664      *   |  PT_NOTE    |
665      *   --------------
666      *   |  PT_LOAD    |
667      *   --------------
668      *   |  ......     |
669      *   --------------
670      *   |  PT_LOAD    |
671      *   --------------
672      *   |  elf note   |
673      *   --------------
674      *   |  memory     |
675      *   --------------
676      *
677      * we only know where the memory is saved after we write elf note into
678      * vmcore.
679      */
680 
681     /* write elf header to vmcore */
682     write_elf_header(s, errp);
683     if (*errp) {
684         return;
685     }
686 
687     /* write section headers to vmcore */
688     write_elf_section_headers(s, errp);
689     if (*errp) {
690         return;
691     }
692 
693     /* write PT_NOTE to vmcore */
694     write_elf_phdr_note(s, errp);
695     if (*errp) {
696         return;
697     }
698 
699     /* write all PT_LOADs to vmcore */
700     write_elf_phdr_loads(s, errp);
701     if (*errp) {
702         return;
703     }
704 
705     /* write notes to vmcore */
706     write_elf_notes(s, errp);
707 }
708 
709 int64_t dump_filtered_memblock_size(GuestPhysBlock *block,
710                                     int64_t filter_area_start,
711                                     int64_t filter_area_length)
712 {
713     int64_t size, left, right;
714 
715     /* No filter, return full size */
716     if (!filter_area_length) {
717         return block->target_end - block->target_start;
718     }
719 
720     /* calculate the overlapped region. */
721     left = MAX(filter_area_start, block->target_start);
722     right = MIN(filter_area_start + filter_area_length, block->target_end);
723     size = right - left;
724     size = size > 0 ? size : 0;
725 
726     return size;
727 }
728 
729 int64_t dump_filtered_memblock_start(GuestPhysBlock *block,
730                                      int64_t filter_area_start,
731                                      int64_t filter_area_length)
732 {
733     if (filter_area_length) {
734         /* return -1 if the block is not within filter area */
735         if (block->target_start >= filter_area_start + filter_area_length ||
736             block->target_end <= filter_area_start) {
737             return -1;
738         }
739 
740         if (filter_area_start > block->target_start) {
741             return filter_area_start - block->target_start;
742         }
743     }
744 
745     return 0;
746 }
747 
748 /* write all memory to vmcore */
749 static void dump_iterate(DumpState *s, Error **errp)
750 {
751     ERRP_GUARD();
752     GuestPhysBlock *block;
753     int64_t memblock_size, memblock_start;
754 
755     QTAILQ_FOREACH(block, &s->guest_phys_blocks.head, next) {
756         memblock_start = dump_filtered_memblock_start(block, s->filter_area_begin, s->filter_area_length);
757         if (memblock_start == -1) {
758             continue;
759         }
760 
761         memblock_size = dump_filtered_memblock_size(block, s->filter_area_begin, s->filter_area_length);
762 
763         /* Write the memory to file */
764         write_memory(s, block, memblock_start, memblock_size, errp);
765         if (*errp) {
766             return;
767         }
768     }
769 }
770 
771 static void dump_end(DumpState *s, Error **errp)
772 {
773     int rc;
774 
775     if (s->elf_section_data_size) {
776         s->elf_section_data = g_malloc0(s->elf_section_data_size);
777     }
778 
779     /* Adds the architecture defined section data to s->elf_section_data  */
780     if (s->dump_info.arch_sections_write_fn &&
781         s->elf_section_data_size) {
782         rc = s->dump_info.arch_sections_write_fn(s, s->elf_section_data);
783         if (rc) {
784             error_setg_errno(errp, rc,
785                              "dump: failed to get arch section data");
786             g_free(s->elf_section_data);
787             return;
788         }
789     }
790 
791     /* write sections to vmcore */
792     write_elf_sections(s, errp);
793 }
794 
795 static void create_vmcore(DumpState *s, Error **errp)
796 {
797     ERRP_GUARD();
798 
799     dump_begin(s, errp);
800     if (*errp) {
801         return;
802     }
803 
804     /* Iterate over memory and dump it to file */
805     dump_iterate(s, errp);
806     if (*errp) {
807         return;
808     }
809 
810     /* Write the section data */
811     dump_end(s, errp);
812 }
813 
814 static int write_start_flat_header(int fd)
815 {
816     MakedumpfileHeader *mh;
817     int ret = 0;
818 
819     QEMU_BUILD_BUG_ON(sizeof *mh > MAX_SIZE_MDF_HEADER);
820     mh = g_malloc0(MAX_SIZE_MDF_HEADER);
821 
822     memcpy(mh->signature, MAKEDUMPFILE_SIGNATURE,
823            MIN(sizeof mh->signature, sizeof MAKEDUMPFILE_SIGNATURE));
824 
825     mh->type = cpu_to_be64(TYPE_FLAT_HEADER);
826     mh->version = cpu_to_be64(VERSION_FLAT_HEADER);
827 
828     size_t written_size;
829     written_size = qemu_write_full(fd, mh, MAX_SIZE_MDF_HEADER);
830     if (written_size != MAX_SIZE_MDF_HEADER) {
831         ret = -1;
832     }
833 
834     g_free(mh);
835     return ret;
836 }
837 
838 static int write_end_flat_header(int fd)
839 {
840     MakedumpfileDataHeader mdh;
841 
842     mdh.offset = END_FLAG_FLAT_HEADER;
843     mdh.buf_size = END_FLAG_FLAT_HEADER;
844 
845     size_t written_size;
846     written_size = qemu_write_full(fd, &mdh, sizeof(mdh));
847     if (written_size != sizeof(mdh)) {
848         return -1;
849     }
850 
851     return 0;
852 }
853 
854 static int write_buffer(int fd, off_t offset, const void *buf, size_t size)
855 {
856     size_t written_size;
857     MakedumpfileDataHeader mdh;
858 
859     mdh.offset = cpu_to_be64(offset);
860     mdh.buf_size = cpu_to_be64(size);
861 
862     written_size = qemu_write_full(fd, &mdh, sizeof(mdh));
863     if (written_size != sizeof(mdh)) {
864         return -1;
865     }
866 
867     written_size = qemu_write_full(fd, buf, size);
868     if (written_size != size) {
869         return -1;
870     }
871 
872     return 0;
873 }
874 
875 static int buf_write_note(const void *buf, size_t size, void *opaque)
876 {
877     DumpState *s = opaque;
878 
879     /* note_buf is not enough */
880     if (s->note_buf_offset + size > s->note_size) {
881         return -1;
882     }
883 
884     memcpy(s->note_buf + s->note_buf_offset, buf, size);
885 
886     s->note_buf_offset += size;
887 
888     return 0;
889 }
890 
891 /*
892  * This function retrieves various sizes from an elf header.
893  *
894  * @note has to be a valid ELF note. The return sizes are unmodified
895  * (not padded or rounded up to be multiple of 4).
896  */
897 static void get_note_sizes(DumpState *s, const void *note,
898                            uint64_t *note_head_size,
899                            uint64_t *name_size,
900                            uint64_t *desc_size)
901 {
902     uint64_t note_head_sz;
903     uint64_t name_sz;
904     uint64_t desc_sz;
905 
906     if (dump_is_64bit(s)) {
907         const Elf64_Nhdr *hdr = note;
908         note_head_sz = sizeof(Elf64_Nhdr);
909         name_sz = cpu_to_dump64(s, hdr->n_namesz);
910         desc_sz = cpu_to_dump64(s, hdr->n_descsz);
911     } else {
912         const Elf32_Nhdr *hdr = note;
913         note_head_sz = sizeof(Elf32_Nhdr);
914         name_sz = cpu_to_dump32(s, hdr->n_namesz);
915         desc_sz = cpu_to_dump32(s, hdr->n_descsz);
916     }
917 
918     if (note_head_size) {
919         *note_head_size = note_head_sz;
920     }
921     if (name_size) {
922         *name_size = name_sz;
923     }
924     if (desc_size) {
925         *desc_size = desc_sz;
926     }
927 }
928 
929 static bool note_name_equal(DumpState *s,
930                             const uint8_t *note, const char *name)
931 {
932     int len = strlen(name) + 1;
933     uint64_t head_size, name_size;
934 
935     get_note_sizes(s, note, &head_size, &name_size, NULL);
936     head_size = ROUND_UP(head_size, 4);
937 
938     return name_size == len && memcmp(note + head_size, name, len) == 0;
939 }
940 
941 /* write common header, sub header and elf note to vmcore */
942 static void create_header32(DumpState *s, Error **errp)
943 {
944     ERRP_GUARD();
945     DiskDumpHeader32 *dh = NULL;
946     KdumpSubHeader32 *kh = NULL;
947     size_t size;
948     uint32_t block_size;
949     uint32_t sub_hdr_size;
950     uint32_t bitmap_blocks;
951     uint32_t status = 0;
952     uint64_t offset_note;
953 
954     /* write common header, the version of kdump-compressed format is 6th */
955     size = sizeof(DiskDumpHeader32);
956     dh = g_malloc0(size);
957 
958     memcpy(dh->signature, KDUMP_SIGNATURE, SIG_LEN);
959     dh->header_version = cpu_to_dump32(s, 6);
960     block_size = s->dump_info.page_size;
961     dh->block_size = cpu_to_dump32(s, block_size);
962     sub_hdr_size = sizeof(struct KdumpSubHeader32) + s->note_size;
963     sub_hdr_size = DIV_ROUND_UP(sub_hdr_size, block_size);
964     dh->sub_hdr_size = cpu_to_dump32(s, sub_hdr_size);
965     /* dh->max_mapnr may be truncated, full 64bit is in kh.max_mapnr_64 */
966     dh->max_mapnr = cpu_to_dump32(s, MIN(s->max_mapnr, UINT_MAX));
967     dh->nr_cpus = cpu_to_dump32(s, s->nr_cpus);
968     bitmap_blocks = DIV_ROUND_UP(s->len_dump_bitmap, block_size) * 2;
969     dh->bitmap_blocks = cpu_to_dump32(s, bitmap_blocks);
970     strncpy(dh->utsname.machine, ELF_MACHINE_UNAME, sizeof(dh->utsname.machine));
971 
972     if (s->flag_compress & DUMP_DH_COMPRESSED_ZLIB) {
973         status |= DUMP_DH_COMPRESSED_ZLIB;
974     }
975 #ifdef CONFIG_LZO
976     if (s->flag_compress & DUMP_DH_COMPRESSED_LZO) {
977         status |= DUMP_DH_COMPRESSED_LZO;
978     }
979 #endif
980 #ifdef CONFIG_SNAPPY
981     if (s->flag_compress & DUMP_DH_COMPRESSED_SNAPPY) {
982         status |= DUMP_DH_COMPRESSED_SNAPPY;
983     }
984 #endif
985     dh->status = cpu_to_dump32(s, status);
986 
987     if (write_buffer(s->fd, 0, dh, size) < 0) {
988         error_setg(errp, "dump: failed to write disk dump header");
989         goto out;
990     }
991 
992     /* write sub header */
993     size = sizeof(KdumpSubHeader32);
994     kh = g_malloc0(size);
995 
996     /* 64bit max_mapnr_64 */
997     kh->max_mapnr_64 = cpu_to_dump64(s, s->max_mapnr);
998     kh->phys_base = cpu_to_dump32(s, s->dump_info.phys_base);
999     kh->dump_level = cpu_to_dump32(s, DUMP_LEVEL);
1000 
1001     offset_note = DISKDUMP_HEADER_BLOCKS * block_size + size;
1002     if (s->guest_note &&
1003         note_name_equal(s, s->guest_note, "VMCOREINFO")) {
1004         uint64_t hsize, name_size, size_vmcoreinfo_desc, offset_vmcoreinfo;
1005 
1006         get_note_sizes(s, s->guest_note,
1007                        &hsize, &name_size, &size_vmcoreinfo_desc);
1008         offset_vmcoreinfo = offset_note + s->note_size - s->guest_note_size +
1009             (DIV_ROUND_UP(hsize, 4) + DIV_ROUND_UP(name_size, 4)) * 4;
1010         kh->offset_vmcoreinfo = cpu_to_dump64(s, offset_vmcoreinfo);
1011         kh->size_vmcoreinfo = cpu_to_dump32(s, size_vmcoreinfo_desc);
1012     }
1013 
1014     kh->offset_note = cpu_to_dump64(s, offset_note);
1015     kh->note_size = cpu_to_dump32(s, s->note_size);
1016 
1017     if (write_buffer(s->fd, DISKDUMP_HEADER_BLOCKS *
1018                      block_size, kh, size) < 0) {
1019         error_setg(errp, "dump: failed to write kdump sub header");
1020         goto out;
1021     }
1022 
1023     /* write note */
1024     s->note_buf = g_malloc0(s->note_size);
1025     s->note_buf_offset = 0;
1026 
1027     /* use s->note_buf to store notes temporarily */
1028     write_elf32_notes(buf_write_note, s, errp);
1029     if (*errp) {
1030         goto out;
1031     }
1032     if (write_buffer(s->fd, offset_note, s->note_buf,
1033                      s->note_size) < 0) {
1034         error_setg(errp, "dump: failed to write notes");
1035         goto out;
1036     }
1037 
1038     /* get offset of dump_bitmap */
1039     s->offset_dump_bitmap = (DISKDUMP_HEADER_BLOCKS + sub_hdr_size) *
1040                              block_size;
1041 
1042     /* get offset of page */
1043     s->offset_page = (DISKDUMP_HEADER_BLOCKS + sub_hdr_size + bitmap_blocks) *
1044                      block_size;
1045 
1046 out:
1047     g_free(dh);
1048     g_free(kh);
1049     g_free(s->note_buf);
1050 }
1051 
1052 /* write common header, sub header and elf note to vmcore */
1053 static void create_header64(DumpState *s, Error **errp)
1054 {
1055     ERRP_GUARD();
1056     DiskDumpHeader64 *dh = NULL;
1057     KdumpSubHeader64 *kh = NULL;
1058     size_t size;
1059     uint32_t block_size;
1060     uint32_t sub_hdr_size;
1061     uint32_t bitmap_blocks;
1062     uint32_t status = 0;
1063     uint64_t offset_note;
1064 
1065     /* write common header, the version of kdump-compressed format is 6th */
1066     size = sizeof(DiskDumpHeader64);
1067     dh = g_malloc0(size);
1068 
1069     memcpy(dh->signature, KDUMP_SIGNATURE, SIG_LEN);
1070     dh->header_version = cpu_to_dump32(s, 6);
1071     block_size = s->dump_info.page_size;
1072     dh->block_size = cpu_to_dump32(s, block_size);
1073     sub_hdr_size = sizeof(struct KdumpSubHeader64) + s->note_size;
1074     sub_hdr_size = DIV_ROUND_UP(sub_hdr_size, block_size);
1075     dh->sub_hdr_size = cpu_to_dump32(s, sub_hdr_size);
1076     /* dh->max_mapnr may be truncated, full 64bit is in kh.max_mapnr_64 */
1077     dh->max_mapnr = cpu_to_dump32(s, MIN(s->max_mapnr, UINT_MAX));
1078     dh->nr_cpus = cpu_to_dump32(s, s->nr_cpus);
1079     bitmap_blocks = DIV_ROUND_UP(s->len_dump_bitmap, block_size) * 2;
1080     dh->bitmap_blocks = cpu_to_dump32(s, bitmap_blocks);
1081     strncpy(dh->utsname.machine, ELF_MACHINE_UNAME, sizeof(dh->utsname.machine));
1082 
1083     if (s->flag_compress & DUMP_DH_COMPRESSED_ZLIB) {
1084         status |= DUMP_DH_COMPRESSED_ZLIB;
1085     }
1086 #ifdef CONFIG_LZO
1087     if (s->flag_compress & DUMP_DH_COMPRESSED_LZO) {
1088         status |= DUMP_DH_COMPRESSED_LZO;
1089     }
1090 #endif
1091 #ifdef CONFIG_SNAPPY
1092     if (s->flag_compress & DUMP_DH_COMPRESSED_SNAPPY) {
1093         status |= DUMP_DH_COMPRESSED_SNAPPY;
1094     }
1095 #endif
1096     dh->status = cpu_to_dump32(s, status);
1097 
1098     if (write_buffer(s->fd, 0, dh, size) < 0) {
1099         error_setg(errp, "dump: failed to write disk dump header");
1100         goto out;
1101     }
1102 
1103     /* write sub header */
1104     size = sizeof(KdumpSubHeader64);
1105     kh = g_malloc0(size);
1106 
1107     /* 64bit max_mapnr_64 */
1108     kh->max_mapnr_64 = cpu_to_dump64(s, s->max_mapnr);
1109     kh->phys_base = cpu_to_dump64(s, s->dump_info.phys_base);
1110     kh->dump_level = cpu_to_dump32(s, DUMP_LEVEL);
1111 
1112     offset_note = DISKDUMP_HEADER_BLOCKS * block_size + size;
1113     if (s->guest_note &&
1114         note_name_equal(s, s->guest_note, "VMCOREINFO")) {
1115         uint64_t hsize, name_size, size_vmcoreinfo_desc, offset_vmcoreinfo;
1116 
1117         get_note_sizes(s, s->guest_note,
1118                        &hsize, &name_size, &size_vmcoreinfo_desc);
1119         offset_vmcoreinfo = offset_note + s->note_size - s->guest_note_size +
1120             (DIV_ROUND_UP(hsize, 4) + DIV_ROUND_UP(name_size, 4)) * 4;
1121         kh->offset_vmcoreinfo = cpu_to_dump64(s, offset_vmcoreinfo);
1122         kh->size_vmcoreinfo = cpu_to_dump64(s, size_vmcoreinfo_desc);
1123     }
1124 
1125     kh->offset_note = cpu_to_dump64(s, offset_note);
1126     kh->note_size = cpu_to_dump64(s, s->note_size);
1127 
1128     if (write_buffer(s->fd, DISKDUMP_HEADER_BLOCKS *
1129                      block_size, kh, size) < 0) {
1130         error_setg(errp, "dump: failed to write kdump sub header");
1131         goto out;
1132     }
1133 
1134     /* write note */
1135     s->note_buf = g_malloc0(s->note_size);
1136     s->note_buf_offset = 0;
1137 
1138     /* use s->note_buf to store notes temporarily */
1139     write_elf64_notes(buf_write_note, s, errp);
1140     if (*errp) {
1141         goto out;
1142     }
1143 
1144     if (write_buffer(s->fd, offset_note, s->note_buf,
1145                      s->note_size) < 0) {
1146         error_setg(errp, "dump: failed to write notes");
1147         goto out;
1148     }
1149 
1150     /* get offset of dump_bitmap */
1151     s->offset_dump_bitmap = (DISKDUMP_HEADER_BLOCKS + sub_hdr_size) *
1152                              block_size;
1153 
1154     /* get offset of page */
1155     s->offset_page = (DISKDUMP_HEADER_BLOCKS + sub_hdr_size + bitmap_blocks) *
1156                      block_size;
1157 
1158 out:
1159     g_free(dh);
1160     g_free(kh);
1161     g_free(s->note_buf);
1162 }
1163 
1164 static void write_dump_header(DumpState *s, Error **errp)
1165 {
1166     if (dump_is_64bit(s)) {
1167         create_header64(s, errp);
1168     } else {
1169         create_header32(s, errp);
1170     }
1171 }
1172 
1173 static size_t dump_bitmap_get_bufsize(DumpState *s)
1174 {
1175     return s->dump_info.page_size;
1176 }
1177 
1178 /*
1179  * set dump_bitmap sequencely. the bit before last_pfn is not allowed to be
1180  * rewritten, so if need to set the first bit, set last_pfn and pfn to 0.
1181  * set_dump_bitmap will always leave the recently set bit un-sync. And setting
1182  * (last bit + sizeof(buf) * 8) to 0 will do flushing the content in buf into
1183  * vmcore, ie. synchronizing un-sync bit into vmcore.
1184  */
1185 static int set_dump_bitmap(uint64_t last_pfn, uint64_t pfn, bool value,
1186                            uint8_t *buf, DumpState *s)
1187 {
1188     off_t old_offset, new_offset;
1189     off_t offset_bitmap1, offset_bitmap2;
1190     uint32_t byte, bit;
1191     size_t bitmap_bufsize = dump_bitmap_get_bufsize(s);
1192     size_t bits_per_buf = bitmap_bufsize * CHAR_BIT;
1193 
1194     /* should not set the previous place */
1195     assert(last_pfn <= pfn);
1196 
1197     /*
1198      * if the bit needed to be set is not cached in buf, flush the data in buf
1199      * to vmcore firstly.
1200      * making new_offset be bigger than old_offset can also sync remained data
1201      * into vmcore.
1202      */
1203     old_offset = bitmap_bufsize * (last_pfn / bits_per_buf);
1204     new_offset = bitmap_bufsize * (pfn / bits_per_buf);
1205 
1206     while (old_offset < new_offset) {
1207         /* calculate the offset and write dump_bitmap */
1208         offset_bitmap1 = s->offset_dump_bitmap + old_offset;
1209         if (write_buffer(s->fd, offset_bitmap1, buf,
1210                          bitmap_bufsize) < 0) {
1211             return -1;
1212         }
1213 
1214         /* dump level 1 is chosen, so 1st and 2nd bitmap are same */
1215         offset_bitmap2 = s->offset_dump_bitmap + s->len_dump_bitmap +
1216                          old_offset;
1217         if (write_buffer(s->fd, offset_bitmap2, buf,
1218                          bitmap_bufsize) < 0) {
1219             return -1;
1220         }
1221 
1222         memset(buf, 0, bitmap_bufsize);
1223         old_offset += bitmap_bufsize;
1224     }
1225 
1226     /* get the exact place of the bit in the buf, and set it */
1227     byte = (pfn % bits_per_buf) / CHAR_BIT;
1228     bit = (pfn % bits_per_buf) % CHAR_BIT;
1229     if (value) {
1230         buf[byte] |= 1u << bit;
1231     } else {
1232         buf[byte] &= ~(1u << bit);
1233     }
1234 
1235     return 0;
1236 }
1237 
1238 static uint64_t dump_paddr_to_pfn(DumpState *s, uint64_t addr)
1239 {
1240     int target_page_shift = ctz32(s->dump_info.page_size);
1241 
1242     return (addr >> target_page_shift) - ARCH_PFN_OFFSET;
1243 }
1244 
1245 static uint64_t dump_pfn_to_paddr(DumpState *s, uint64_t pfn)
1246 {
1247     int target_page_shift = ctz32(s->dump_info.page_size);
1248 
1249     return (pfn + ARCH_PFN_OFFSET) << target_page_shift;
1250 }
1251 
1252 /*
1253  * Return the page frame number and the page content in *bufptr. bufptr can be
1254  * NULL. If not NULL, *bufptr must contains a target page size of pre-allocated
1255  * memory. This is not necessarily the memory returned.
1256  */
1257 static bool get_next_page(GuestPhysBlock **blockptr, uint64_t *pfnptr,
1258                           uint8_t **bufptr, DumpState *s)
1259 {
1260     GuestPhysBlock *block = *blockptr;
1261     uint32_t page_size = s->dump_info.page_size;
1262     uint8_t *buf = NULL, *hbuf;
1263     hwaddr addr;
1264 
1265     /* block == NULL means the start of the iteration */
1266     if (!block) {
1267         block = QTAILQ_FIRST(&s->guest_phys_blocks.head);
1268         *blockptr = block;
1269         addr = block->target_start;
1270         *pfnptr = dump_paddr_to_pfn(s, addr);
1271     } else {
1272         *pfnptr += 1;
1273         addr = dump_pfn_to_paddr(s, *pfnptr);
1274     }
1275     assert(block != NULL);
1276 
1277     while (1) {
1278         if (addr >= block->target_start && addr < block->target_end) {
1279             size_t n = MIN(block->target_end - addr, page_size - addr % page_size);
1280             hbuf = block->host_addr + (addr - block->target_start);
1281             if (!buf) {
1282                 if (n == page_size) {
1283                     /* this is a whole target page, go for it */
1284                     assert(addr % page_size == 0);
1285                     buf = hbuf;
1286                     break;
1287                 } else if (bufptr) {
1288                     assert(*bufptr);
1289                     buf = *bufptr;
1290                     memset(buf, 0, page_size);
1291                 } else {
1292                     return true;
1293                 }
1294             }
1295 
1296             memcpy(buf + addr % page_size, hbuf, n);
1297             addr += n;
1298             if (addr % page_size == 0) {
1299                 /* we filled up the page */
1300                 break;
1301             }
1302         } else {
1303             /* the next page is in the next block */
1304             *blockptr = block = QTAILQ_NEXT(block, next);
1305             if (!block) {
1306                 break;
1307             }
1308 
1309             addr = block->target_start;
1310             /* are we still in the same page? */
1311             if (dump_paddr_to_pfn(s, addr) != *pfnptr) {
1312                 if (buf) {
1313                     /* no, but we already filled something earlier, return it */
1314                     break;
1315                 } else {
1316                     /* else continue from there */
1317                     *pfnptr = dump_paddr_to_pfn(s, addr);
1318                 }
1319             }
1320         }
1321     }
1322 
1323     if (bufptr) {
1324         *bufptr = buf;
1325     }
1326 
1327     return buf != NULL;
1328 }
1329 
1330 static void write_dump_bitmap(DumpState *s, Error **errp)
1331 {
1332     int ret = 0;
1333     uint64_t last_pfn, pfn;
1334     void *dump_bitmap_buf;
1335     size_t num_dumpable;
1336     GuestPhysBlock *block_iter = NULL;
1337     size_t bitmap_bufsize = dump_bitmap_get_bufsize(s);
1338     size_t bits_per_buf = bitmap_bufsize * CHAR_BIT;
1339 
1340     /* dump_bitmap_buf is used to store dump_bitmap temporarily */
1341     dump_bitmap_buf = g_malloc0(bitmap_bufsize);
1342 
1343     num_dumpable = 0;
1344     last_pfn = 0;
1345 
1346     /*
1347      * exam memory page by page, and set the bit in dump_bitmap corresponded
1348      * to the existing page.
1349      */
1350     while (get_next_page(&block_iter, &pfn, NULL, s)) {
1351         ret = set_dump_bitmap(last_pfn, pfn, true, dump_bitmap_buf, s);
1352         if (ret < 0) {
1353             error_setg(errp, "dump: failed to set dump_bitmap");
1354             goto out;
1355         }
1356 
1357         last_pfn = pfn;
1358         num_dumpable++;
1359     }
1360 
1361     /*
1362      * set_dump_bitmap will always leave the recently set bit un-sync. Here we
1363      * set the remaining bits from last_pfn to the end of the bitmap buffer to
1364      * 0. With those set, the un-sync bit will be synchronized into the vmcore.
1365      */
1366     if (num_dumpable > 0) {
1367         ret = set_dump_bitmap(last_pfn, last_pfn + bits_per_buf, false,
1368                               dump_bitmap_buf, s);
1369         if (ret < 0) {
1370             error_setg(errp, "dump: failed to sync dump_bitmap");
1371             goto out;
1372         }
1373     }
1374 
1375     /* number of dumpable pages that will be dumped later */
1376     s->num_dumpable = num_dumpable;
1377 
1378 out:
1379     g_free(dump_bitmap_buf);
1380 }
1381 
1382 static void prepare_data_cache(DataCache *data_cache, DumpState *s,
1383                                off_t offset)
1384 {
1385     data_cache->fd = s->fd;
1386     data_cache->data_size = 0;
1387     data_cache->buf_size = 4 * dump_bitmap_get_bufsize(s);
1388     data_cache->buf = g_malloc0(data_cache->buf_size);
1389     data_cache->offset = offset;
1390 }
1391 
1392 static int write_cache(DataCache *dc, const void *buf, size_t size,
1393                        bool flag_sync)
1394 {
1395     /*
1396      * dc->buf_size should not be less than size, otherwise dc will never be
1397      * enough
1398      */
1399     assert(size <= dc->buf_size);
1400 
1401     /*
1402      * if flag_sync is set, synchronize data in dc->buf into vmcore.
1403      * otherwise check if the space is enough for caching data in buf, if not,
1404      * write the data in dc->buf to dc->fd and reset dc->buf
1405      */
1406     if ((!flag_sync && dc->data_size + size > dc->buf_size) ||
1407         (flag_sync && dc->data_size > 0)) {
1408         if (write_buffer(dc->fd, dc->offset, dc->buf, dc->data_size) < 0) {
1409             return -1;
1410         }
1411 
1412         dc->offset += dc->data_size;
1413         dc->data_size = 0;
1414     }
1415 
1416     if (!flag_sync) {
1417         memcpy(dc->buf + dc->data_size, buf, size);
1418         dc->data_size += size;
1419     }
1420 
1421     return 0;
1422 }
1423 
1424 static void free_data_cache(DataCache *data_cache)
1425 {
1426     g_free(data_cache->buf);
1427 }
1428 
1429 static size_t get_len_buf_out(size_t page_size, uint32_t flag_compress)
1430 {
1431     switch (flag_compress) {
1432     case DUMP_DH_COMPRESSED_ZLIB:
1433         return compressBound(page_size);
1434 
1435     case DUMP_DH_COMPRESSED_LZO:
1436         /*
1437          * LZO will expand incompressible data by a little amount. Please check
1438          * the following URL to see the expansion calculation:
1439          * http://www.oberhumer.com/opensource/lzo/lzofaq.php
1440          */
1441         return page_size + page_size / 16 + 64 + 3;
1442 
1443 #ifdef CONFIG_SNAPPY
1444     case DUMP_DH_COMPRESSED_SNAPPY:
1445         return snappy_max_compressed_length(page_size);
1446 #endif
1447     }
1448     return 0;
1449 }
1450 
1451 static void write_dump_pages(DumpState *s, Error **errp)
1452 {
1453     int ret = 0;
1454     DataCache page_desc, page_data;
1455     size_t len_buf_out, size_out;
1456 #ifdef CONFIG_LZO
1457     lzo_bytep wrkmem = NULL;
1458 #endif
1459     uint8_t *buf_out = NULL;
1460     off_t offset_desc, offset_data;
1461     PageDescriptor pd, pd_zero;
1462     uint8_t *buf;
1463     GuestPhysBlock *block_iter = NULL;
1464     uint64_t pfn_iter;
1465     g_autofree uint8_t *page = NULL;
1466 
1467     /* get offset of page_desc and page_data in dump file */
1468     offset_desc = s->offset_page;
1469     offset_data = offset_desc + sizeof(PageDescriptor) * s->num_dumpable;
1470 
1471     prepare_data_cache(&page_desc, s, offset_desc);
1472     prepare_data_cache(&page_data, s, offset_data);
1473 
1474     /* prepare buffer to store compressed data */
1475     len_buf_out = get_len_buf_out(s->dump_info.page_size, s->flag_compress);
1476     assert(len_buf_out != 0);
1477 
1478 #ifdef CONFIG_LZO
1479     wrkmem = g_malloc(LZO1X_1_MEM_COMPRESS);
1480 #endif
1481 
1482     buf_out = g_malloc(len_buf_out);
1483 
1484     /*
1485      * init zero page's page_desc and page_data, because every zero page
1486      * uses the same page_data
1487      */
1488     pd_zero.size = cpu_to_dump32(s, s->dump_info.page_size);
1489     pd_zero.flags = cpu_to_dump32(s, 0);
1490     pd_zero.offset = cpu_to_dump64(s, offset_data);
1491     pd_zero.page_flags = cpu_to_dump64(s, 0);
1492     buf = g_malloc0(s->dump_info.page_size);
1493     ret = write_cache(&page_data, buf, s->dump_info.page_size, false);
1494     g_free(buf);
1495     if (ret < 0) {
1496         error_setg(errp, "dump: failed to write page data (zero page)");
1497         goto out;
1498     }
1499 
1500     offset_data += s->dump_info.page_size;
1501     page = g_malloc(s->dump_info.page_size);
1502 
1503     /*
1504      * dump memory to vmcore page by page. zero page will all be resided in the
1505      * first page of page section
1506      */
1507     for (buf = page; get_next_page(&block_iter, &pfn_iter, &buf, s); buf = page) {
1508         /* check zero page */
1509         if (buffer_is_zero(buf, s->dump_info.page_size)) {
1510             ret = write_cache(&page_desc, &pd_zero, sizeof(PageDescriptor),
1511                               false);
1512             if (ret < 0) {
1513                 error_setg(errp, "dump: failed to write page desc");
1514                 goto out;
1515             }
1516         } else {
1517             /*
1518              * not zero page, then:
1519              * 1. compress the page
1520              * 2. write the compressed page into the cache of page_data
1521              * 3. get page desc of the compressed page and write it into the
1522              *    cache of page_desc
1523              *
1524              * only one compression format will be used here, for
1525              * s->flag_compress is set. But when compression fails to work,
1526              * we fall back to save in plaintext.
1527              */
1528              size_out = len_buf_out;
1529              if ((s->flag_compress & DUMP_DH_COMPRESSED_ZLIB) &&
1530                     (compress2(buf_out, (uLongf *)&size_out, buf,
1531                                s->dump_info.page_size, Z_BEST_SPEED) == Z_OK) &&
1532                     (size_out < s->dump_info.page_size)) {
1533                 pd.flags = cpu_to_dump32(s, DUMP_DH_COMPRESSED_ZLIB);
1534                 pd.size  = cpu_to_dump32(s, size_out);
1535 
1536                 ret = write_cache(&page_data, buf_out, size_out, false);
1537                 if (ret < 0) {
1538                     error_setg(errp, "dump: failed to write page data");
1539                     goto out;
1540                 }
1541 #ifdef CONFIG_LZO
1542             } else if ((s->flag_compress & DUMP_DH_COMPRESSED_LZO) &&
1543                     (lzo1x_1_compress(buf, s->dump_info.page_size, buf_out,
1544                     (lzo_uint *)&size_out, wrkmem) == LZO_E_OK) &&
1545                     (size_out < s->dump_info.page_size)) {
1546                 pd.flags = cpu_to_dump32(s, DUMP_DH_COMPRESSED_LZO);
1547                 pd.size  = cpu_to_dump32(s, size_out);
1548 
1549                 ret = write_cache(&page_data, buf_out, size_out, false);
1550                 if (ret < 0) {
1551                     error_setg(errp, "dump: failed to write page data");
1552                     goto out;
1553                 }
1554 #endif
1555 #ifdef CONFIG_SNAPPY
1556             } else if ((s->flag_compress & DUMP_DH_COMPRESSED_SNAPPY) &&
1557                     (snappy_compress((char *)buf, s->dump_info.page_size,
1558                     (char *)buf_out, &size_out) == SNAPPY_OK) &&
1559                     (size_out < s->dump_info.page_size)) {
1560                 pd.flags = cpu_to_dump32(s, DUMP_DH_COMPRESSED_SNAPPY);
1561                 pd.size  = cpu_to_dump32(s, size_out);
1562 
1563                 ret = write_cache(&page_data, buf_out, size_out, false);
1564                 if (ret < 0) {
1565                     error_setg(errp, "dump: failed to write page data");
1566                     goto out;
1567                 }
1568 #endif
1569             } else {
1570                 /*
1571                  * fall back to save in plaintext, size_out should be
1572                  * assigned the target's page size
1573                  */
1574                 pd.flags = cpu_to_dump32(s, 0);
1575                 size_out = s->dump_info.page_size;
1576                 pd.size = cpu_to_dump32(s, size_out);
1577 
1578                 ret = write_cache(&page_data, buf,
1579                                   s->dump_info.page_size, false);
1580                 if (ret < 0) {
1581                     error_setg(errp, "dump: failed to write page data");
1582                     goto out;
1583                 }
1584             }
1585 
1586             /* get and write page desc here */
1587             pd.page_flags = cpu_to_dump64(s, 0);
1588             pd.offset = cpu_to_dump64(s, offset_data);
1589             offset_data += size_out;
1590 
1591             ret = write_cache(&page_desc, &pd, sizeof(PageDescriptor), false);
1592             if (ret < 0) {
1593                 error_setg(errp, "dump: failed to write page desc");
1594                 goto out;
1595             }
1596         }
1597         s->written_size += s->dump_info.page_size;
1598     }
1599 
1600     ret = write_cache(&page_desc, NULL, 0, true);
1601     if (ret < 0) {
1602         error_setg(errp, "dump: failed to sync cache for page_desc");
1603         goto out;
1604     }
1605     ret = write_cache(&page_data, NULL, 0, true);
1606     if (ret < 0) {
1607         error_setg(errp, "dump: failed to sync cache for page_data");
1608         goto out;
1609     }
1610 
1611 out:
1612     free_data_cache(&page_desc);
1613     free_data_cache(&page_data);
1614 
1615 #ifdef CONFIG_LZO
1616     g_free(wrkmem);
1617 #endif
1618 
1619     g_free(buf_out);
1620 }
1621 
1622 static void create_kdump_vmcore(DumpState *s, Error **errp)
1623 {
1624     ERRP_GUARD();
1625     int ret;
1626 
1627     /*
1628      * the kdump-compressed format is:
1629      *                                               File offset
1630      *  +------------------------------------------+ 0x0
1631      *  |    main header (struct disk_dump_header) |
1632      *  |------------------------------------------+ block 1
1633      *  |    sub header (struct kdump_sub_header)  |
1634      *  |------------------------------------------+ block 2
1635      *  |            1st-dump_bitmap               |
1636      *  |------------------------------------------+ block 2 + X blocks
1637      *  |            2nd-dump_bitmap               | (aligned by block)
1638      *  |------------------------------------------+ block 2 + 2 * X blocks
1639      *  |  page desc for pfn 0 (struct page_desc)  | (aligned by block)
1640      *  |  page desc for pfn 1 (struct page_desc)  |
1641      *  |                    :                     |
1642      *  |------------------------------------------| (not aligned by block)
1643      *  |         page data (pfn 0)                |
1644      *  |         page data (pfn 1)                |
1645      *  |                    :                     |
1646      *  +------------------------------------------+
1647      */
1648 
1649     ret = write_start_flat_header(s->fd);
1650     if (ret < 0) {
1651         error_setg(errp, "dump: failed to write start flat header");
1652         return;
1653     }
1654 
1655     write_dump_header(s, errp);
1656     if (*errp) {
1657         return;
1658     }
1659 
1660     write_dump_bitmap(s, errp);
1661     if (*errp) {
1662         return;
1663     }
1664 
1665     write_dump_pages(s, errp);
1666     if (*errp) {
1667         return;
1668     }
1669 
1670     ret = write_end_flat_header(s->fd);
1671     if (ret < 0) {
1672         error_setg(errp, "dump: failed to write end flat header");
1673         return;
1674     }
1675 }
1676 
1677 static int validate_start_block(DumpState *s)
1678 {
1679     GuestPhysBlock *block;
1680 
1681     if (!dump_has_filter(s)) {
1682         return 0;
1683     }
1684 
1685     QTAILQ_FOREACH(block, &s->guest_phys_blocks.head, next) {
1686         /* This block is out of the range */
1687         if (block->target_start >= s->filter_area_begin + s->filter_area_length ||
1688             block->target_end <= s->filter_area_begin) {
1689             continue;
1690         }
1691         return 0;
1692    }
1693 
1694     return -1;
1695 }
1696 
1697 static void get_max_mapnr(DumpState *s)
1698 {
1699     GuestPhysBlock *last_block;
1700 
1701     last_block = QTAILQ_LAST(&s->guest_phys_blocks.head);
1702     s->max_mapnr = dump_paddr_to_pfn(s, last_block->target_end);
1703 }
1704 
1705 static DumpState dump_state_global = { .status = DUMP_STATUS_NONE };
1706 
1707 static void dump_state_prepare(DumpState *s)
1708 {
1709     /* zero the struct, setting status to active */
1710     *s = (DumpState) { .status = DUMP_STATUS_ACTIVE };
1711 }
1712 
1713 bool qemu_system_dump_in_progress(void)
1714 {
1715     DumpState *state = &dump_state_global;
1716     return (qatomic_read(&state->status) == DUMP_STATUS_ACTIVE);
1717 }
1718 
1719 /*
1720  * calculate total size of memory to be dumped (taking filter into
1721  * account.)
1722  */
1723 static int64_t dump_calculate_size(DumpState *s)
1724 {
1725     GuestPhysBlock *block;
1726     int64_t total = 0;
1727 
1728     QTAILQ_FOREACH(block, &s->guest_phys_blocks.head, next) {
1729         total += dump_filtered_memblock_size(block,
1730                                              s->filter_area_begin,
1731                                              s->filter_area_length);
1732     }
1733 
1734     return total;
1735 }
1736 
1737 static void vmcoreinfo_update_phys_base(DumpState *s)
1738 {
1739     uint64_t size, note_head_size, name_size, phys_base;
1740     char **lines;
1741     uint8_t *vmci;
1742     size_t i;
1743 
1744     if (!note_name_equal(s, s->guest_note, "VMCOREINFO")) {
1745         return;
1746     }
1747 
1748     get_note_sizes(s, s->guest_note, &note_head_size, &name_size, &size);
1749     note_head_size = ROUND_UP(note_head_size, 4);
1750 
1751     vmci = s->guest_note + note_head_size + ROUND_UP(name_size, 4);
1752     *(vmci + size) = '\0';
1753 
1754     lines = g_strsplit((char *)vmci, "\n", -1);
1755     for (i = 0; lines[i]; i++) {
1756         const char *prefix = NULL;
1757 
1758         if (s->dump_info.d_machine == EM_X86_64) {
1759             prefix = "NUMBER(phys_base)=";
1760         } else if (s->dump_info.d_machine == EM_AARCH64) {
1761             prefix = "NUMBER(PHYS_OFFSET)=";
1762         }
1763 
1764         if (prefix && g_str_has_prefix(lines[i], prefix)) {
1765             if (qemu_strtou64(lines[i] + strlen(prefix), NULL, 16,
1766                               &phys_base) < 0) {
1767                 warn_report("Failed to read %s", prefix);
1768             } else {
1769                 s->dump_info.phys_base = phys_base;
1770             }
1771             break;
1772         }
1773     }
1774 
1775     g_strfreev(lines);
1776 }
1777 
1778 static void dump_init(DumpState *s, int fd, bool has_format,
1779                       DumpGuestMemoryFormat format, bool paging, bool has_filter,
1780                       int64_t begin, int64_t length, Error **errp)
1781 {
1782     ERRP_GUARD();
1783     VMCoreInfoState *vmci = vmcoreinfo_find();
1784     CPUState *cpu;
1785     int nr_cpus;
1786     int ret;
1787 
1788     s->has_format = has_format;
1789     s->format = format;
1790     s->written_size = 0;
1791 
1792     /* kdump-compressed is conflict with paging and filter */
1793     if (has_format && format != DUMP_GUEST_MEMORY_FORMAT_ELF) {
1794         assert(!paging && !has_filter);
1795     }
1796 
1797     if (runstate_is_running()) {
1798         vm_stop(RUN_STATE_SAVE_VM);
1799         s->resume = true;
1800     } else {
1801         s->resume = false;
1802     }
1803 
1804     /* If we use KVM, we should synchronize the registers before we get dump
1805      * info or physmap info.
1806      */
1807     cpu_synchronize_all_states();
1808     nr_cpus = 0;
1809     CPU_FOREACH(cpu) {
1810         nr_cpus++;
1811     }
1812 
1813     s->fd = fd;
1814     if (has_filter && !length) {
1815         error_setg(errp, QERR_INVALID_PARAMETER, "length");
1816         goto cleanup;
1817     }
1818     s->filter_area_begin = begin;
1819     s->filter_area_length = length;
1820 
1821     /* First index is 0, it's the special null name */
1822     s->string_table_buf = g_array_new(FALSE, TRUE, 1);
1823     /*
1824      * Allocate the null name, due to the clearing option set to true
1825      * it will be 0.
1826      */
1827     g_array_set_size(s->string_table_buf, 1);
1828 
1829     memory_mapping_list_init(&s->list);
1830 
1831     guest_phys_blocks_init(&s->guest_phys_blocks);
1832     guest_phys_blocks_append(&s->guest_phys_blocks);
1833     s->total_size = dump_calculate_size(s);
1834 #ifdef DEBUG_DUMP_GUEST_MEMORY
1835     fprintf(stderr, "DUMP: total memory to dump: %lu\n", s->total_size);
1836 #endif
1837 
1838     /* it does not make sense to dump non-existent memory */
1839     if (!s->total_size) {
1840         error_setg(errp, "dump: no guest memory to dump");
1841         goto cleanup;
1842     }
1843 
1844     /* Is the filter filtering everything? */
1845     if (validate_start_block(s) == -1) {
1846         error_setg(errp, QERR_INVALID_PARAMETER, "begin");
1847         goto cleanup;
1848     }
1849 
1850     /* get dump info: endian, class and architecture.
1851      * If the target architecture is not supported, cpu_get_dump_info() will
1852      * return -1.
1853      */
1854     ret = cpu_get_dump_info(&s->dump_info, &s->guest_phys_blocks);
1855     if (ret < 0) {
1856         error_setg(errp,
1857                    "dumping guest memory is not supported on this target");
1858         goto cleanup;
1859     }
1860 
1861     if (!s->dump_info.page_size) {
1862         s->dump_info.page_size = qemu_target_page_size();
1863     }
1864 
1865     s->note_size = cpu_get_note_size(s->dump_info.d_class,
1866                                      s->dump_info.d_machine, nr_cpus);
1867     assert(s->note_size >= 0);
1868 
1869     /*
1870      * The goal of this block is to (a) update the previously guessed
1871      * phys_base, (b) copy the guest note out of the guest.
1872      * Failure to do so is not fatal for dumping.
1873      */
1874     if (vmci) {
1875         uint64_t addr, note_head_size, name_size, desc_size;
1876         uint32_t size;
1877         uint16_t format;
1878 
1879         note_head_size = dump_is_64bit(s) ?
1880             sizeof(Elf64_Nhdr) : sizeof(Elf32_Nhdr);
1881 
1882         format = le16_to_cpu(vmci->vmcoreinfo.guest_format);
1883         size = le32_to_cpu(vmci->vmcoreinfo.size);
1884         addr = le64_to_cpu(vmci->vmcoreinfo.paddr);
1885         if (!vmci->has_vmcoreinfo) {
1886             warn_report("guest note is not present");
1887         } else if (size < note_head_size || size > MAX_GUEST_NOTE_SIZE) {
1888             warn_report("guest note size is invalid: %" PRIu32, size);
1889         } else if (format != FW_CFG_VMCOREINFO_FORMAT_ELF) {
1890             warn_report("guest note format is unsupported: %" PRIu16, format);
1891         } else {
1892             s->guest_note = g_malloc(size + 1); /* +1 for adding \0 */
1893             cpu_physical_memory_read(addr, s->guest_note, size);
1894 
1895             get_note_sizes(s, s->guest_note, NULL, &name_size, &desc_size);
1896             s->guest_note_size = ELF_NOTE_SIZE(note_head_size, name_size,
1897                                                desc_size);
1898             if (name_size > MAX_GUEST_NOTE_SIZE ||
1899                 desc_size > MAX_GUEST_NOTE_SIZE ||
1900                 s->guest_note_size > size) {
1901                 warn_report("Invalid guest note header");
1902                 g_free(s->guest_note);
1903                 s->guest_note = NULL;
1904             } else {
1905                 vmcoreinfo_update_phys_base(s);
1906                 s->note_size += s->guest_note_size;
1907             }
1908         }
1909     }
1910 
1911     /* get memory mapping */
1912     if (paging) {
1913         qemu_get_guest_memory_mapping(&s->list, &s->guest_phys_blocks, errp);
1914         if (*errp) {
1915             goto cleanup;
1916         }
1917     } else {
1918         qemu_get_guest_simple_memory_mapping(&s->list, &s->guest_phys_blocks);
1919     }
1920 
1921     s->nr_cpus = nr_cpus;
1922 
1923     get_max_mapnr(s);
1924 
1925     uint64_t tmp;
1926     tmp = DIV_ROUND_UP(DIV_ROUND_UP(s->max_mapnr, CHAR_BIT),
1927                        s->dump_info.page_size);
1928     s->len_dump_bitmap = tmp * s->dump_info.page_size;
1929 
1930     /* init for kdump-compressed format */
1931     if (has_format && format != DUMP_GUEST_MEMORY_FORMAT_ELF) {
1932         switch (format) {
1933         case DUMP_GUEST_MEMORY_FORMAT_KDUMP_ZLIB:
1934             s->flag_compress = DUMP_DH_COMPRESSED_ZLIB;
1935             break;
1936 
1937         case DUMP_GUEST_MEMORY_FORMAT_KDUMP_LZO:
1938 #ifdef CONFIG_LZO
1939             if (lzo_init() != LZO_E_OK) {
1940                 error_setg(errp, "failed to initialize the LZO library");
1941                 goto cleanup;
1942             }
1943 #endif
1944             s->flag_compress = DUMP_DH_COMPRESSED_LZO;
1945             break;
1946 
1947         case DUMP_GUEST_MEMORY_FORMAT_KDUMP_SNAPPY:
1948             s->flag_compress = DUMP_DH_COMPRESSED_SNAPPY;
1949             break;
1950 
1951         default:
1952             s->flag_compress = 0;
1953         }
1954 
1955         return;
1956     }
1957 
1958     if (dump_has_filter(s)) {
1959         memory_mapping_filter(&s->list, s->filter_area_begin, s->filter_area_length);
1960     }
1961 
1962     /*
1963      * The first section header is always a special one in which most
1964      * fields are 0. The section header string table is also always
1965      * set.
1966      */
1967     s->shdr_num = 2;
1968 
1969     /*
1970      * Adds the number of architecture sections to shdr_num and sets
1971      * elf_section_data_size so we know the offsets and sizes of all
1972      * parts.
1973      */
1974     if (s->dump_info.arch_sections_add_fn) {
1975         s->dump_info.arch_sections_add_fn(s);
1976     }
1977 
1978     /*
1979      * calculate shdr_num so we know the offsets and sizes of all
1980      * parts.
1981      * Calculate phdr_num
1982      *
1983      * The absolute maximum amount of phdrs is UINT32_MAX - 1 as
1984      * sh_info is 32 bit. There's special handling once we go over
1985      * UINT16_MAX - 1 but that is handled in the ehdr and section
1986      * code.
1987      */
1988     s->phdr_num = 1; /* Reserve PT_NOTE */
1989     if (s->list.num <= UINT32_MAX - 1) {
1990         s->phdr_num += s->list.num;
1991     } else {
1992         s->phdr_num = UINT32_MAX;
1993     }
1994 
1995     /*
1996      * Now that the number of section and program headers is known we
1997      * can calculate the offsets of the headers and data.
1998      */
1999     if (dump_is_64bit(s)) {
2000         s->shdr_offset = sizeof(Elf64_Ehdr);
2001         s->phdr_offset = s->shdr_offset + sizeof(Elf64_Shdr) * s->shdr_num;
2002         s->note_offset = s->phdr_offset + sizeof(Elf64_Phdr) * s->phdr_num;
2003     } else {
2004         s->shdr_offset = sizeof(Elf32_Ehdr);
2005         s->phdr_offset = s->shdr_offset + sizeof(Elf32_Shdr) * s->shdr_num;
2006         s->note_offset = s->phdr_offset + sizeof(Elf32_Phdr) * s->phdr_num;
2007     }
2008     s->memory_offset = s->note_offset + s->note_size;
2009     s->section_offset = s->memory_offset + s->total_size;
2010 
2011     return;
2012 
2013 cleanup:
2014     dump_cleanup(s);
2015 }
2016 
2017 /* this operation might be time consuming. */
2018 static void dump_process(DumpState *s, Error **errp)
2019 {
2020     ERRP_GUARD();
2021     DumpQueryResult *result = NULL;
2022 
2023     if (s->has_format && s->format == DUMP_GUEST_MEMORY_FORMAT_WIN_DMP) {
2024 #ifdef TARGET_X86_64
2025         create_win_dump(s, errp);
2026 #endif
2027     } else if (s->has_format && s->format != DUMP_GUEST_MEMORY_FORMAT_ELF) {
2028         create_kdump_vmcore(s, errp);
2029     } else {
2030         create_vmcore(s, errp);
2031     }
2032 
2033     /* make sure status is written after written_size updates */
2034     smp_wmb();
2035     qatomic_set(&s->status,
2036                (*errp ? DUMP_STATUS_FAILED : DUMP_STATUS_COMPLETED));
2037 
2038     /* send DUMP_COMPLETED message (unconditionally) */
2039     result = qmp_query_dump(NULL);
2040     /* should never fail */
2041     assert(result);
2042     qapi_event_send_dump_completed(result,
2043                                    *errp ? error_get_pretty(*errp) : NULL);
2044     qapi_free_DumpQueryResult(result);
2045 
2046     dump_cleanup(s);
2047 }
2048 
2049 static void *dump_thread(void *data)
2050 {
2051     DumpState *s = (DumpState *)data;
2052     dump_process(s, NULL);
2053     return NULL;
2054 }
2055 
2056 DumpQueryResult *qmp_query_dump(Error **errp)
2057 {
2058     DumpQueryResult *result = g_new(DumpQueryResult, 1);
2059     DumpState *state = &dump_state_global;
2060     result->status = qatomic_read(&state->status);
2061     /* make sure we are reading status and written_size in order */
2062     smp_rmb();
2063     result->completed = state->written_size;
2064     result->total = state->total_size;
2065     return result;
2066 }
2067 
2068 void qmp_dump_guest_memory(bool paging, const char *file,
2069                            bool has_detach, bool detach,
2070                            bool has_begin, int64_t begin, bool has_length,
2071                            int64_t length, bool has_format,
2072                            DumpGuestMemoryFormat format, Error **errp)
2073 {
2074     ERRP_GUARD();
2075     const char *p;
2076     int fd = -1;
2077     DumpState *s;
2078     bool detach_p = false;
2079 
2080     if (runstate_check(RUN_STATE_INMIGRATE)) {
2081         error_setg(errp, "Dump not allowed during incoming migration.");
2082         return;
2083     }
2084 
2085     /* if there is a dump in background, we should wait until the dump
2086      * finished */
2087     if (qemu_system_dump_in_progress()) {
2088         error_setg(errp, "There is a dump in process, please wait.");
2089         return;
2090     }
2091 
2092     /*
2093      * kdump-compressed format need the whole memory dumped, so paging or
2094      * filter is not supported here.
2095      */
2096     if ((has_format && format != DUMP_GUEST_MEMORY_FORMAT_ELF) &&
2097         (paging || has_begin || has_length)) {
2098         error_setg(errp, "kdump-compressed format doesn't support paging or "
2099                          "filter");
2100         return;
2101     }
2102     if (has_begin && !has_length) {
2103         error_setg(errp, QERR_MISSING_PARAMETER, "length");
2104         return;
2105     }
2106     if (!has_begin && has_length) {
2107         error_setg(errp, QERR_MISSING_PARAMETER, "begin");
2108         return;
2109     }
2110     if (has_detach) {
2111         detach_p = detach;
2112     }
2113 
2114     /* check whether lzo/snappy is supported */
2115 #ifndef CONFIG_LZO
2116     if (has_format && format == DUMP_GUEST_MEMORY_FORMAT_KDUMP_LZO) {
2117         error_setg(errp, "kdump-lzo is not available now");
2118         return;
2119     }
2120 #endif
2121 
2122 #ifndef CONFIG_SNAPPY
2123     if (has_format && format == DUMP_GUEST_MEMORY_FORMAT_KDUMP_SNAPPY) {
2124         error_setg(errp, "kdump-snappy is not available now");
2125         return;
2126     }
2127 #endif
2128 
2129 #ifndef TARGET_X86_64
2130     if (has_format && format == DUMP_GUEST_MEMORY_FORMAT_WIN_DMP) {
2131         error_setg(errp, "Windows dump is only available for x86-64");
2132         return;
2133     }
2134 #endif
2135 
2136 #if !defined(WIN32)
2137     if (strstart(file, "fd:", &p)) {
2138         fd = monitor_get_fd(monitor_cur(), p, errp);
2139         if (fd == -1) {
2140             return;
2141         }
2142     }
2143 #endif
2144 
2145     if  (strstart(file, "file:", &p)) {
2146         fd = qemu_open_old(p, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, S_IRUSR);
2147         if (fd < 0) {
2148             error_setg_file_open(errp, errno, p);
2149             return;
2150         }
2151     }
2152 
2153     if (fd == -1) {
2154         error_setg(errp, QERR_INVALID_PARAMETER, "protocol");
2155         return;
2156     }
2157 
2158     if (!dump_migration_blocker) {
2159         error_setg(&dump_migration_blocker,
2160                    "Live migration disabled: dump-guest-memory in progress");
2161     }
2162 
2163     /*
2164      * Allows even for -only-migratable, but forbid migration during the
2165      * process of dump guest memory.
2166      */
2167     if (migrate_add_blocker_internal(dump_migration_blocker, errp)) {
2168         /* Remember to release the fd before passing it over to dump state */
2169         close(fd);
2170         return;
2171     }
2172 
2173     s = &dump_state_global;
2174     dump_state_prepare(s);
2175 
2176     dump_init(s, fd, has_format, format, paging, has_begin,
2177               begin, length, errp);
2178     if (*errp) {
2179         qatomic_set(&s->status, DUMP_STATUS_FAILED);
2180         return;
2181     }
2182 
2183     if (detach_p) {
2184         /* detached dump */
2185         s->detached = true;
2186         qemu_thread_create(&s->dump_thread, "dump_thread", dump_thread,
2187                            s, QEMU_THREAD_DETACHED);
2188     } else {
2189         /* sync dump */
2190         dump_process(s, errp);
2191     }
2192 }
2193 
2194 DumpGuestMemoryCapability *qmp_query_dump_guest_memory_capability(Error **errp)
2195 {
2196     DumpGuestMemoryCapability *cap =
2197                                   g_new0(DumpGuestMemoryCapability, 1);
2198     DumpGuestMemoryFormatList **tail = &cap->formats;
2199 
2200     /* elf is always available */
2201     QAPI_LIST_APPEND(tail, DUMP_GUEST_MEMORY_FORMAT_ELF);
2202 
2203     /* kdump-zlib is always available */
2204     QAPI_LIST_APPEND(tail, DUMP_GUEST_MEMORY_FORMAT_KDUMP_ZLIB);
2205 
2206     /* add new item if kdump-lzo is available */
2207 #ifdef CONFIG_LZO
2208     QAPI_LIST_APPEND(tail, DUMP_GUEST_MEMORY_FORMAT_KDUMP_LZO);
2209 #endif
2210 
2211     /* add new item if kdump-snappy is available */
2212 #ifdef CONFIG_SNAPPY
2213     QAPI_LIST_APPEND(tail, DUMP_GUEST_MEMORY_FORMAT_KDUMP_SNAPPY);
2214 #endif
2215 
2216     /* Windows dump is available only if target is x86_64 */
2217 #ifdef TARGET_X86_64
2218     QAPI_LIST_APPEND(tail, DUMP_GUEST_MEMORY_FORMAT_WIN_DMP);
2219 #endif
2220 
2221     return cap;
2222 }
2223