summaryrefslogtreecommitdiffstats
path: root/target-i386/svm_helper.c
blob: 782b3f12f0ffbd7f92d6ec5b82bc906d5ab183fb (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
/*
 *  x86 SVM helpers
 *
 *  Copyright (c) 2003 Fabrice Bellard
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
 */

#include "qemu/osdep.h"
#include "cpu.h"
#include "exec/cpu-all.h"
#include "exec/helper-proto.h"
#include "exec/exec-all.h"
#include "exec/cpu_ldst.h"

/* Secure Virtual Machine helpers */

#if defined(CONFIG_USER_ONLY)

void helper_vmrun(CPUX86State *env, int aflag, int next_eip_addend)
{
}

void helper_vmmcall(CPUX86State *env)
{
}

void helper_vmload(CPUX86State *env, int aflag)
{
}

void helper_vmsave(CPUX86State *env, int aflag)
{
}

void helper_stgi(CPUX86State *env)
{
}

void helper_clgi(CPUX86State *env)
{
}

void helper_skinit(CPUX86State *env)
{
}

void helper_invlpga(CPUX86State *env, int aflag)
{
}

void helper_vmexit(CPUX86State *env, uint32_t exit_code, uint64_t exit_info_1)
{
}

void cpu_vmexit(CPUX86State *nenv, uint32_t exit_code, uint64_t exit_info_1)
{
}

void helper_svm_check_intercept_param(CPUX86State *env, uint32_t type,
                                      uint64_t param)
{
}

void cpu_svm_check_intercept_param(CPUX86State *env, uint32_t type,
                                   uint64_t param)
{
}

void helper_svm_check_io(CPUX86State *env, uint32_t port, uint32_t param,
                         uint32_t next_eip_addend)
{
}
#else

static inline void svm_save_seg(CPUX86State *env, hwaddr addr,
                                const SegmentCache *sc)
{
    CPUState *cs = CPU(x86_env_get_cpu(env));

    x86_stw_phys(cs, addr + offsetof(struct vmcb_seg, selector),
             sc->selector);
    x86_stq_phys(cs, addr + offsetof(struct vmcb_seg, base),
             sc->base);
    x86_stl_phys(cs, addr + offsetof(struct vmcb_seg, limit),
             sc->limit);
    x86_stw_phys(cs, addr + offsetof(struct vmcb_seg, attrib),
             ((sc->flags >> 8) & 0xff) | ((sc->flags >> 12) & 0x0f00));
}

static inline void svm_load_seg(CPUX86State *env, hwaddr addr,
                                SegmentCache *sc)
{
    CPUState *cs = CPU(x86_env_get_cpu(env));
    unsigned int flags;

    sc->selector = x86_lduw_phys(cs,
                             addr + offsetof(struct vmcb_seg, selector));
    sc->base = x86_ldq_phys(cs, addr + offsetof(struct vmcb_seg, base));
    sc->limit = x86_ldl_phys(cs, addr + offsetof(struct vmcb_seg, limit));
    flags = x86_lduw_phys(cs, addr + offsetof(struct vmcb_seg, attrib));
    sc->flags = ((flags & 0xff) << 8) | ((flags & 0x0f00) << 12);
}

static inline void svm_load_seg_cache(CPUX86State *env, hwaddr addr,
                                      int seg_reg)
{
    SegmentCache sc1, *sc = &sc1;

    svm_load_seg(env, addr, sc);
    cpu_x86_load_seg_cache(env, seg_reg, sc->selector,
                           sc->base, sc->limit, sc->flags);
}

void helper_vmrun(CPUX86State *env, int aflag, int next_eip_addend)
{
    CPUState *cs = CPU(x86_env_get_cpu(env));
    target_ulong addr;
    uint32_t event_inj;
    uint32_t int_ctl;

    cpu_svm_check_intercept_param(env, SVM_EXIT_VMRUN, 0);

    if (aflag == 2) {
        addr = env->regs[R_EAX];
    } else {
        addr = (uint32_t)env->regs[R_EAX];
    }

    qemu_log_mask(CPU_LOG_TB_IN_ASM, "vmrun! " TARGET_FMT_lx "\n", addr);

    env->vm_vmcb = addr;

    /* save the current CPU state in the hsave page */
    x86_stq_phys(cs, env->vm_hsave + offsetof(struct vmcb, save.gdtr.base),
             env->gdt.base);
    x86_stl_phys(cs, env->vm_hsave + offsetof(struct vmcb, save.gdtr.limit),
             env->gdt.limit);

    x86_stq_phys(cs, env->vm_hsave + offsetof(struct vmcb, save.idtr.base),
             env->idt.base);
    x86_stl_phys(cs, env->vm_hsave + offsetof(struct vmcb, save.idtr.limit),
             env->idt.limit);

    x86_stq_phys(cs,
             env->vm_hsave + offsetof(struct vmcb, save.cr0), env->cr[0]);
    x86_stq_phys(cs,
             env->vm_hsave + offsetof(struct vmcb, save.cr2), env->cr[2]);
    x86_stq_phys(cs,
             env->vm_hsave + offsetof(struct vmcb, save.cr3), env->cr[3]);
    x86_stq_phys(cs,
             env->vm_hsave + offsetof(struct vmcb, save.cr4), env->cr[4]);
    x86_stq_phys(cs,
             env->vm_hsave + offsetof(struct vmcb, save.dr6), env->dr[6]);
    x86_stq_phys(cs,
             env->vm_hsave + offsetof(struct vmcb, save.dr7), env->dr[7]);

    x86_stq_phys(cs,
             env->vm_hsave + offsetof(struct vmcb, save.efer), env->efer);
    x86_stq_phys(cs,
             env->vm_hsave + offsetof(struct vmcb, save.rflags),
             cpu_compute_eflags(env));

    svm_save_seg(env, env->vm_hsave + offsetof(struct vmcb, save.es),
                 &env->segs[R_ES]);
    svm_save_seg(env, env->vm_hsave + offsetof(struct vmcb, save.cs),
                 &env->segs[R_CS]);
    svm_save_seg(env, env->vm_hsave + offsetof(struct vmcb, save.ss),
                 &env->segs[R_SS]);
    svm_save_seg(env, env->vm_hsave + offsetof(struct vmcb, save.ds),
                 &env->segs[R_DS]);

    x86_stq_phys(cs, env->vm_hsave + offsetof(struct vmcb, save.rip),
             env->eip + next_eip_addend);
    x86_stq_phys(cs,
             env->vm_hsave + offsetof(struct vmcb, save.rsp), env->regs[R_ESP]);
    x86_stq_phys(cs,
             env->vm_hsave + offsetof(struct vmcb, save.rax), env->regs[R_EAX]);

    /* load the interception bitmaps so we do not need to access the
       vmcb in svm mode */
    env->intercept = x86_ldq_phys(cs, env->vm_vmcb + offsetof(struct vmcb,
                                                      control.intercept));
    env->intercept_cr_read = x86_lduw_phys(cs, env->vm_vmcb +
                                       offsetof(struct vmcb,
                                                control.intercept_cr_read));
    env->intercept_cr_write = x86_lduw_phys(cs, env->vm_vmcb +
                                        offsetof(struct vmcb,
                                                 control.intercept_cr_write));
    env->intercept_dr_read = x86_lduw_phys(cs, env->vm_vmcb +
                                       offsetof(struct vmcb,
                                                control.intercept_dr_read));
    env->intercept_dr_write = x86_lduw_phys(cs, env->vm_vmcb +
                                        offsetof(struct vmcb,
                                                 control.intercept_dr_write));
    env->intercept_exceptions = x86_ldl_phys(cs, env->vm_vmcb +
                                         offsetof(struct vmcb,
                                                  control.intercept_exceptions
                                                  ));

    /* enable intercepts */
    env->hflags |= HF_SVMI_MASK;

    env->tsc_offset = x86_ldq_phys(cs, env->vm_vmcb +
                               offsetof(struct vmcb, control.tsc_offset));

    env->gdt.base  = x86_ldq_phys(cs, env->vm_vmcb + offsetof(struct vmcb,
                                                      save.gdtr.base));
    env->gdt.limit = x86_ldl_phys(cs, env->vm_vmcb + offsetof(struct vmcb,
                                                      save.gdtr.limit));

    env->idt.base  = x86_ldq_phys(cs, env->vm_vmcb + offsetof(struct vmcb,
                                                      save.idtr.base));
    env->idt.limit = x86_ldl_phys(cs, env->vm_vmcb + offsetof(struct vmcb,
                                                      save.idtr.limit));

    /* clear exit_info_2 so we behave like the real hardware */
    x86_stq_phys(cs,
             env->vm_vmcb + offsetof(struct vmcb, control.exit_info_2), 0);

    cpu_x86_update_cr0(env, x86_ldq_phys(cs,
                                     env->vm_vmcb + offsetof(struct vmcb,
                                                             save.cr0)));
    cpu_x86_update_cr4(env, x86_ldq_phys(cs,
                                     env->vm_vmcb + offsetof(struct vmcb,
                                                             save.cr4)));
    cpu_x86_update_cr3(env, x86_ldq_phys(cs,
                                     env->vm_vmcb + offsetof(struct vmcb,
                                                             save.cr3)));
    env->cr[2] = x86_ldq_phys(cs,
                          env->vm_vmcb + offsetof(struct vmcb, save.cr2));
    int_ctl = x86_ldl_phys(cs,
                       env->vm_vmcb + offsetof(struct vmcb, control.int_ctl));
    env->hflags2 &= ~(HF2_HIF_MASK | HF2_VINTR_MASK);
    if (int_ctl & V_INTR_MASKING_MASK) {
        env->v_tpr = int_ctl & V_TPR_MASK;
        env->hflags2 |= HF2_VINTR_MASK;
        if (env->eflags & IF_MASK) {
            env->hflags2 |= HF2_HIF_MASK;
        }
    }

    cpu_load_efer(env,
                  x86_ldq_phys(cs,
                           env->vm_vmcb + offsetof(struct vmcb, save.efer)));
    env->eflags = 0;
    cpu_load_eflags(env, x86_ldq_phys(cs,
                                  env->vm_vmcb + offsetof(struct vmcb,
                                                          save.rflags)),
                    ~(CC_O | CC_S | CC_Z | CC_A | CC_P | CC_C | DF_MASK));

    svm_load_seg_cache(env, env->vm_vmcb + offsetof(struct vmcb, save.es),
                       R_ES);
    svm_load_seg_cache(env, env->vm_vmcb + offsetof(struct vmcb, save.cs),
                       R_CS);
    svm_load_seg_cache(env, env->vm_vmcb + offsetof(struct vmcb, save.ss),
                       R_SS);
    svm_load_seg_cache(env, env->vm_vmcb + offsetof(struct vmcb, save.ds),
                       R_DS);

    env->eip = x86_ldq_phys(cs,
                        env->vm_vmcb + offsetof(struct vmcb, save.rip));

    env->regs[R_ESP] = x86_ldq_phys(cs,
                                env->vm_vmcb + offsetof(struct vmcb, save.rsp));
    env->regs[R_EAX] = x86_ldq_phys(cs,
                                env->vm_vmcb + offsetof(struct vmcb, save.rax));
    env->dr[7] = x86_ldq_phys(cs,
                          env->vm_vmcb + offsetof(struct vmcb, save.dr7));
    env->dr[6] = x86_ldq_phys(cs,
                          env->vm_vmcb + offsetof(struct vmcb, save.dr6));

    /* FIXME: guest state consistency checks */

    switch (x86_ldub_phys(cs,
                      env->vm_vmcb + offsetof(struct vmcb, control.tlb_ctl))) {
    case TLB_CONTROL_DO_NOTHING:
        break;
    case TLB_CONTROL_FLUSH_ALL_ASID:
        /* FIXME: this is not 100% correct but should work for now */
        tlb_flush(cs, 1);
        break;
    }

    env->hflags2 |= HF2_GIF_MASK;

    if (int_ctl & V_IRQ_MASK) {
        CPUState *cs = CPU(x86_env_get_cpu(env));

        cs->interrupt_request |= CPU_INTERRUPT_VIRQ;
    }

    /* maybe we need to inject an event */
    event_inj = x86_ldl_phys(cs, env->vm_vmcb + offsetof(struct vmcb,
                                                 control.event_inj));
    if (event_inj & SVM_EVTINJ_VALID) {
        uint8_t vector = event_inj & SVM_EVTINJ_VEC_MASK;
        uint16_t valid_err = event_inj & SVM_EVTINJ_VALID_ERR;
        uint32_t event_inj_err = x86_ldl_phys(cs, env->vm_vmcb +
                                          offsetof(struct vmcb,
                                                   control.event_inj_err));

        qemu_log_mask(CPU_LOG_TB_IN_ASM, "Injecting(%#hx): ", valid_err);
        /* FIXME: need to implement valid_err */
        switch (event_inj & SVM_EVTINJ_TYPE_MASK) {
        case SVM_EVTINJ_TYPE_INTR:
            cs->exception_index = vector;
            env->error_code = event_inj_err;
            env->exception_is_int = 0;
            env->exception_next_eip = -1;
            qemu_log_mask(CPU_LOG_TB_IN_ASM, "INTR");
            /* XXX: is it always correct? */
            do_interrupt_x86_hardirq(env, vector, 1);
            break;
        case SVM_EVTINJ_TYPE_NMI:
            cs->exception_index = EXCP02_NMI;
            env->error_code = event_inj_err;
            env->exception_is_int = 0;
            env->exception_next_eip = env->eip;
            qemu_log_mask(CPU_LOG_TB_IN_ASM, "NMI");
            cpu_loop_exit(cs);
            break;
        case SVM_EVTINJ_TYPE_EXEPT:
            cs->exception_index = vector;
            env->error_code = event_inj_err;
            env->exception_is_int = 0;
            env->exception_next_eip = -1;
            qemu_log_mask(CPU_LOG_TB_IN_ASM, "EXEPT");
            cpu_loop_exit(cs);
            break;
        case SVM_EVTINJ_TYPE_SOFT:
            cs->exception_index = vector;
            env->error_code = event_inj_err;
            env->exception_is_int = 1;
            env->exception_next_eip = env->eip;
            qemu_log_mask(CPU_LOG_TB_IN_ASM, "SOFT");
            cpu_loop_exit(cs);
            break;
        }
        qemu_log_mask(CPU_LOG_TB_IN_ASM, " %#x %#x\n", cs->exception_index,
                      env->error_code);
    }
}

void helper_vmmcall(CPUX86State *env)
{
    cpu_svm_check_intercept_param(env, SVM_EXIT_VMMCALL, 0);
    raise_exception(env, EXCP06_ILLOP);
}

void helper_vmload(CPUX86State *env, int aflag)
{
    CPUState *cs = CPU(x86_env_get_cpu(env));
    target_ulong addr;

    cpu_svm_check_intercept_param(env, SVM_EXIT_VMLOAD, 0);

    if (aflag == 2) {
        addr = env->regs[R_EAX];
    } else {
        addr = (uint32_t)env->regs[R_EAX];
    }

    qemu_log_mask(CPU_LOG_TB_IN_ASM, "vmload! " TARGET_FMT_lx
                  "\nFS: %016" PRIx64 " | " TARGET_FMT_lx "\n",
                  addr, x86_ldq_phys(cs, addr + offsetof(struct vmcb,
                                                          save.fs.base)),
                  env->segs[R_FS].base);

    svm_load_seg_cache(env, addr + offsetof(struct vmcb, save.fs), R_FS);
    svm_load_seg_cache(env, addr + offsetof(struct vmcb, save.gs), R_GS);
    svm_load_seg(env, addr + offsetof(struct vmcb, save.tr), &env->tr);
    svm_load_seg(env, addr + offsetof(struct vmcb, save.ldtr), &env->ldt);

#ifdef TARGET_X86_64
    env->kernelgsbase = x86_ldq_phys(cs, addr + offsetof(struct vmcb,
                                                 save.kernel_gs_base));
    env->lstar = x86_ldq_phys(cs, addr + offsetof(struct vmcb, save.lstar));
    env->cstar = x86_ldq_phys(cs, addr + offsetof(struct vmcb, save.cstar));
    env->fmask = x86_ldq_phys(cs, addr + offsetof(struct vmcb, save.sfmask));
#endif
    env->star = x86_ldq_phys(cs, addr + offsetof(struct vmcb, save.star));
    env->sysenter_cs = x86_ldq_phys(cs,
                                addr + offsetof(struct vmcb, save.sysenter_cs));
    env->sysenter_esp = x86_ldq_phys(cs, addr + offsetof(struct vmcb,
                                                 save.sysenter_esp));
    env->sysenter_eip = x86_ldq_phys(cs, addr + offsetof(struct vmcb,
                                                 save.sysenter_eip));
}

void helper_vmsave(CPUX86State *env, int aflag)
{
    CPUState *cs = CPU(x86_env_get_cpu(env));
    target_ulong addr;

    cpu_svm_check_intercept_param(env, SVM_EXIT_VMSAVE, 0);

    if (aflag == 2) {
        addr = env->regs[R_EAX];
    } else {
        addr = (uint32_t)env->regs[R_EAX];
    }

    qemu_log_mask(CPU_LOG_TB_IN_ASM, "vmsave! " TARGET_FMT_lx
                  "\nFS: %016" PRIx64 " | " TARGET_FMT_lx "\n",
                  addr, x86_ldq_phys(cs,
                                 addr + offsetof(struct vmcb, save.fs.base)),
                  env->segs[R_FS].base);

    svm_save_seg(env, addr + offsetof(struct vmcb, save.fs),
                 &env->segs[R_FS]);
    svm_save_seg(env, addr + offsetof(struct vmcb, save.gs),
                 &env->segs[R_GS]);
    svm_save_seg(env, addr + offsetof(struct vmcb, save.tr),
                 &env->tr);
    svm_save_seg(env, addr + offsetof(struct vmcb, save.ldtr),
                 &env->ldt);

#ifdef TARGET_X86_64
    x86_stq_phys(cs, addr + offsetof(struct vmcb, save.kernel_gs_base),
             env->kernelgsbase);
    x86_stq_phys(cs, addr + offsetof(struct vmcb, save.lstar), env->lstar);
    x86_stq_phys(cs, addr + offsetof(struct vmcb, save.cstar), env->cstar);
    x86_stq_phys(cs, addr + offsetof(struct vmcb, save.sfmask), env->fmask);
#endif
    x86_stq_phys(cs, addr + offsetof(struct vmcb, save.star), env->star);
    x86_stq_phys(cs,
             addr + offsetof(struct vmcb, save.sysenter_cs), env->sysenter_cs);
    x86_stq_phys(cs, addr + offsetof(struct vmcb, save.sysenter_esp),
             env->sysenter_esp);
    x86_stq_phys(cs, addr + offsetof(struct vmcb, save.sysenter_eip),
             env->sysenter_eip);
}

void helper_stgi(CPUX86State *env)
{
    cpu_svm_check_intercept_param(env, SVM_EXIT_STGI, 0);
    env->hflags2 |= HF2_GIF_MASK;
}

void helper_clgi(CPUX86State *env)
{
    cpu_svm_check_intercept_param(env, SVM_EXIT_CLGI, 0);
    env->hflags2 &= ~HF2_GIF_MASK;
}

void helper_skinit(CPUX86State *env)
{
    cpu_svm_check_intercept_param(env, SVM_EXIT_SKINIT, 0);
    /* XXX: not implemented */
    raise_exception(env, EXCP06_ILLOP);
}

void helper_invlpga(CPUX86State *env, int aflag)
{
    X86CPU *cpu = x86_env_get_cpu(env);
    target_ulong addr;

    cpu_svm_check_intercept_param(env, SVM_EXIT_INVLPGA, 0);

    if (aflag == 2) {
        addr = env->regs[R_EAX];
    } else {
        addr = (uint32_t)env->regs[R_EAX];
    }

    /* XXX: could use the ASID to see if it is needed to do the
       flush */
    tlb_flush_page(CPU(cpu), addr);
}

void helper_svm_check_intercept_param(CPUX86State *env, uint32_t type,
                                      uint64_t param)
{
    CPUState *cs = CPU(x86_env_get_cpu(env));

    if (likely(!(env->hflags & HF_SVMI_MASK))) {
        return;
    }
    switch (type) {
    case SVM_EXIT_READ_CR0 ... SVM_EXIT_READ_CR0 + 8:
        if (env->intercept_cr_read & (1 << (type - SVM_EXIT_READ_CR0))) {
            helper_vmexit(env, type, param);
        }
        break;
    case SVM_EXIT_WRITE_CR0 ... SVM_EXIT_WRITE_CR0 + 8:
        if (env->intercept_cr_write & (1 << (type - SVM_EXIT_WRITE_CR0))) {
            helper_vmexit(env, type, param);
        }
        break;
    case SVM_EXIT_READ_DR0 ... SVM_EXIT_READ_DR0 + 7:
        if (env->intercept_dr_read & (1 << (type - SVM_EXIT_READ_DR0))) {
            helper_vmexit(env, type, param);
        }
        break;
    case SVM_EXIT_WRITE_DR0 ... SVM_EXIT_WRITE_DR0 + 7:
        if (env->intercept_dr_write & (1 << (type - SVM_EXIT_WRITE_DR0))) {
            helper_vmexit(env, type, param);
        }
        break;
    case SVM_EXIT_EXCP_BASE ... SVM_EXIT_EXCP_BASE + 31:
        if (env->intercept_exceptions & (1 << (type - SVM_EXIT_EXCP_BASE))) {
            helper_vmexit(env, type, param);
        }
        break;
    case SVM_EXIT_MSR:
        if (env->intercept & (1ULL << (SVM_EXIT_MSR - SVM_EXIT_INTR))) {
            /* FIXME: this should be read in at vmrun (faster this way?) */
            uint64_t addr = x86_ldq_phys(cs, env->vm_vmcb +
                                     offsetof(struct vmcb,
                                              control.msrpm_base_pa));
            uint32_t t0, t1;

            switch ((uint32_t)env->regs[R_ECX]) {
            case 0 ... 0x1fff:
                t0 = (env->regs[R_ECX] * 2) % 8;
                t1 = (env->regs[R_ECX] * 2) / 8;
                break;
            case 0xc0000000 ... 0xc0001fff:
                t0 = (8192 + env->regs[R_ECX] - 0xc0000000) * 2;
                t1 = (t0 / 8);
                t0 %= 8;
                break;
            case 0xc0010000 ... 0xc0011fff:
                t0 = (16384 + env->regs[R_ECX] - 0xc0010000) * 2;
                t1 = (t0 / 8);
                t0 %= 8;
                break;
            default:
                helper_vmexit(env, type, param);
                t0 = 0;
                t1 = 0;
                break;
            }
            if (x86_ldub_phys(cs, addr + t1) & ((1 << param) << t0)) {
                helper_vmexit(env, type, param);
            }
        }
        break;
    default:
        if (env->intercept & (1ULL << (type - SVM_EXIT_INTR))) {
            helper_vmexit(env, type, param);
        }
        break;
    }
}

void cpu_svm_check_intercept_param(CPUX86State *env, uint32_t type,
                                   uint64_t param)
{
    helper_svm_check_intercept_param(env, type, param);
}

void helper_svm_check_io(CPUX86State *env, uint32_t port, uint32_t param,
                         uint32_t next_eip_addend)
{
    CPUState *cs = CPU(x86_env_get_cpu(env));

    if (env->intercept & (1ULL << (SVM_EXIT_IOIO - SVM_EXIT_INTR))) {
        /* FIXME: this should be read in at vmrun (faster this way?) */
        uint64_t addr = x86_ldq_phys(cs, env->vm_vmcb +
                                 offsetof(struct vmcb, control.iopm_base_pa));
        uint16_t mask = (1 << ((param >> 4) & 7)) - 1;

        if (x86_lduw_phys(cs, addr + port / 8) & (mask << (port & 7))) {
            /* next env->eip */
            x86_stq_phys(cs,
                     env->vm_vmcb + offsetof(struct vmcb, control.exit_info_2),
                     env->eip + next_eip_addend);
            helper_vmexit(env, SVM_EXIT_IOIO, param | (port << 16));
        }
    }
}

/* Note: currently only 32 bits of exit_code are used */
void helper_vmexit(CPUX86State *env, uint32_t exit_code, uint64_t exit_info_1)
{
    CPUState *cs = CPU(x86_env_get_cpu(env));
    uint32_t int_ctl;

    qemu_log_mask(CPU_LOG_TB_IN_ASM, "vmexit(%08x, %016" PRIx64 ", %016"
                  PRIx64 ", " TARGET_FMT_lx ")!\n",
                  exit_code, exit_info_1,
                  x86_ldq_phys(cs, env->vm_vmcb + offsetof(struct vmcb,
                                                   control.exit_info_2)),
                  env->eip);

    if (env->hflags & HF_INHIBIT_IRQ_MASK) {
        x86_stl_phys(cs,
                 env->vm_vmcb + offsetof(struct vmcb, control.int_state),
                 SVM_INTERRUPT_SHADOW_MASK);
        env->hflags &= ~HF_INHIBIT_IRQ_MASK;
    } else {
        x86_stl_phys(cs,
                 env->vm_vmcb + offsetof(struct vmcb, control.int_state), 0);
    }

    /* Save the VM state in the vmcb */
    svm_save_seg(env, env->vm_vmcb + offsetof(struct vmcb, save.es),
                 &env->segs[R_ES]);
    svm_save_seg(env, env->vm_vmcb + offsetof(struct vmcb, save.cs),
                 &env->segs[R_CS]);
    svm_save_seg(env, env->vm_vmcb + offsetof(struct vmcb, save.ss),
                 &env->segs[R_SS]);
    svm_save_seg(env, env->vm_vmcb + offsetof(struct vmcb, save.ds),
                 &env->segs[R_DS]);

    x86_stq_phys(cs, env->vm_vmcb + offsetof(struct vmcb, save.gdtr.base),
             env->gdt.base);
    x86_stl_phys(cs, env->vm_vmcb + offsetof(struct vmcb, save.gdtr.limit),
             env->gdt.limit);

    x86_stq_phys(cs, env->vm_vmcb + offsetof(struct vmcb, save.idtr.base),
             env->idt.base);
    x86_stl_phys(cs, env->vm_vmcb + offsetof(struct vmcb, save.idtr.limit),
             env->idt.limit);

    x86_stq_phys(cs,
             env->vm_vmcb + offsetof(struct vmcb, save.efer), env->efer);
    x86_stq_phys(cs,
             env->vm_vmcb + offsetof(struct vmcb, save.cr0), env->cr[0]);
    x86_stq_phys(cs,
             env->vm_vmcb + offsetof(struct vmcb, save.cr2), env->cr[2]);
    x86_stq_phys(cs,
             env->vm_vmcb + offsetof(struct vmcb, save.cr3), env->cr[3]);
    x86_stq_phys(cs,
             env->vm_vmcb + offsetof(struct vmcb, save.cr4), env->cr[4]);

    int_ctl = x86_ldl_phys(cs,
                       env->vm_vmcb + offsetof(struct vmcb, control.int_ctl));
    int_ctl &= ~(V_TPR_MASK | V_IRQ_MASK);
    int_ctl |= env->v_tpr & V_TPR_MASK;
    if (cs->interrupt_request & CPU_INTERRUPT_VIRQ) {
        int_ctl |= V_IRQ_MASK;
    }
    x86_stl_phys(cs,
             env->vm_vmcb + offsetof(struct vmcb, control.int_ctl), int_ctl);

    x86_stq_phys(cs, env->vm_vmcb + offsetof(struct vmcb, save.rflags),
             cpu_compute_eflags(env));
    x86_stq_phys(cs, env->vm_vmcb + offsetof(struct vmcb, save.rip),
             env->eip);
    x86_stq_phys(cs,
             env->vm_vmcb + offsetof(struct vmcb, save.rsp), env->regs[R_ESP]);
    x86_stq_phys(cs,
             env->vm_vmcb + offsetof(struct vmcb, save.rax), env->regs[R_EAX]);
    x86_stq_phys(cs,
             env->vm_vmcb + offsetof(struct vmcb, save.dr7), env->dr[7]);
    x86_stq_phys(cs,
             env->vm_vmcb + offsetof(struct vmcb, save.dr6), env->dr[6]);
    x86_stb_phys(cs, env->vm_vmcb + offsetof(struct vmcb, save.cpl),
             env->hflags & HF_CPL_MASK);

    /* Reload the host state from vm_hsave */
    env->hflags2 &= ~(HF2_HIF_MASK | HF2_VINTR_MASK);
    env->hflags &= ~HF_SVMI_MASK;
    env->intercept = 0;
    env->intercept_exceptions = 0;
    cs->interrupt_request &= ~CPU_INTERRUPT_VIRQ;
    env->tsc_offset = 0;

    env->gdt.base  = x86_ldq_phys(cs, env->vm_hsave + offsetof(struct vmcb,
                                                       save.gdtr.base));
    env->gdt.limit = x86_ldl_phys(cs, env->vm_hsave + offsetof(struct vmcb,
                                                       save.gdtr.limit));

    env->idt.base  = x86_ldq_phys(cs, env->vm_hsave + offsetof(struct vmcb,
                                                       save.idtr.base));
    env->idt.limit = x86_ldl_phys(cs, env->vm_hsave + offsetof(struct vmcb,
                                                       save.idtr.limit));

    cpu_x86_update_cr0(env, x86_ldq_phys(cs,
                                     env->vm_hsave + offsetof(struct vmcb,
                                                              save.cr0)) |
                       CR0_PE_MASK);
    cpu_x86_update_cr4(env, x86_ldq_phys(cs,
                                     env->vm_hsave + offsetof(struct vmcb,
                                                              save.cr4)));
    cpu_x86_update_cr3(env, x86_ldq_phys(cs,
                                     env->vm_hsave + offsetof(struct vmcb,
                                                              save.cr3)));
    /* we need to set the efer after the crs so the hidden flags get
       set properly */
    cpu_load_efer(env, x86_ldq_phys(cs, env->vm_hsave + offsetof(struct vmcb,
                                                         save.efer)));
    env->eflags = 0;
    cpu_load_eflags(env, x86_ldq_phys(cs,
                                  env->vm_hsave + offsetof(struct vmcb,
                                                           save.rflags)),
                    ~(CC_O | CC_S | CC_Z | CC_A | CC_P | CC_C | DF_MASK |
                      VM_MASK));

    svm_load_seg_cache(env, env->vm_hsave + offsetof(struct vmcb, save.es),
                       R_ES);
    svm_load_seg_cache(env, env->vm_hsave + offsetof(struct vmcb, save.cs),
                       R_CS);
    svm_load_seg_cache(env, env->vm_hsave + offsetof(struct vmcb, save.ss),
                       R_SS);
    svm_load_seg_cache(env, env->vm_hsave + offsetof(struct vmcb, save.ds),
                       R_DS);

    env->eip = x86_ldq_phys(cs,
                        env->vm_hsave + offsetof(struct vmcb, save.rip));
    env->regs[R_ESP] = x86_ldq_phys(cs, env->vm_hsave +
                                offsetof(struct vmcb, save.rsp));
    env->regs[R_EAX] = x86_ldq_phys(cs, env->vm_hsave +
                                offsetof(struct vmcb, save.rax));

    env->dr[6] = x86_ldq_phys(cs,
                          env->vm_hsave + offsetof(struct vmcb, save.dr6));
    env->dr[7] = x86_ldq_phys(cs,
                          env->vm_hsave + offsetof(struct vmcb, save.dr7));

    /* other setups */
    x86_stq_phys(cs, env->vm_vmcb + offsetof(struct vmcb, control.exit_code),
             exit_code);
    x86_stq_phys(cs, env->vm_vmcb + offsetof(struct vmcb, control.exit_info_1),
             exit_info_1);

    x86_stl_phys(cs,
             env->vm_vmcb + offsetof(struct vmcb, control.exit_int_info),
             x86_ldl_phys(cs, env->vm_vmcb + offsetof(struct vmcb,
                                              control.event_inj)));
    x86_stl_phys(cs,
             env->vm_vmcb + offsetof(struct vmcb, control.exit_int_info_err),
             x86_ldl_phys(cs, env->vm_vmcb + offsetof(struct vmcb,
                                              control.event_inj_err)));
    x86_stl_phys(cs,
             env->vm_vmcb + offsetof(struct vmcb, control.event_inj), 0);

    env->hflags2 &= ~HF2_GIF_MASK;
    /* FIXME: Resets the current ASID register to zero (host ASID). */

    /* Clears the V_IRQ and V_INTR_MASKING bits inside the processor. */

    /* Clears the TSC_OFFSET inside the processor. */

    /* If the host is in PAE mode, the processor reloads the host's PDPEs
       from the page table indicated the host's CR3. If the PDPEs contain
       illegal state, the processor causes a shutdown. */

    /* Disables all breakpoints in the host DR7 register. */

    /* Checks the reloaded host state for consistency. */

    /* If the host's rIP reloaded by #VMEXIT is outside the limit of the
       host's code segment or non-canonical (in the case of long mode), a
       #GP fault is delivered inside the host. */

    /* remove any pending exception */
    cs->exception_index = -1;
    env->error_code = 0;
    env->old_exception = -1;

    cpu_loop_exit(cs);
}

void cpu_vmexit(CPUX86State *env, uint32_t exit_code, uint64_t exit_info_1)
{
    helper_vmexit(env, exit_code, exit_info_1);
}

#endif
hl kwb">void *opaque, int ret) { *(int *)opaque = ret; } static int do_aio_readv(BlockBackend *blk, QEMUIOVector *qiov, int64_t offset, int *total) { int async_ret = NOT_DONE; blk_aio_readv(blk, offset >> 9, qiov, qiov->size >> 9, aio_rw_done, &async_ret); while (async_ret == NOT_DONE) { main_loop_wait(false); } *total = qiov->size; return async_ret < 0 ? async_ret : 1; } static int do_aio_writev(BlockBackend *blk, QEMUIOVector *qiov, int64_t offset, int *total) { int async_ret = NOT_DONE; blk_aio_writev(blk, offset >> 9, qiov, qiov->size >> 9, aio_rw_done, &async_ret); while (async_ret == NOT_DONE) { main_loop_wait(false); } *total = qiov->size; return async_ret < 0 ? async_ret : 1; } struct multiwrite_async_ret { int num_done; int error; }; static void multiwrite_cb(void *opaque, int ret) { struct multiwrite_async_ret *async_ret = opaque; async_ret->num_done++; if (ret < 0) { async_ret->error = ret; } } static int do_aio_multiwrite(BlockBackend *blk, BlockRequest* reqs, int num_reqs, int *total) { int i, ret; struct multiwrite_async_ret async_ret = { .num_done = 0, .error = 0, }; *total = 0; for (i = 0; i < num_reqs; i++) { reqs[i].cb = multiwrite_cb; reqs[i].opaque = &async_ret; *total += reqs[i].qiov->size; } ret = blk_aio_multiwrite(blk, reqs, num_reqs); if (ret < 0) { return ret; } while (async_ret.num_done < num_reqs) { main_loop_wait(false); } return async_ret.error < 0 ? async_ret.error : 1; } static void read_help(void) { printf( "\n" " reads a range of bytes from the given offset\n" "\n" " Example:\n" " 'read -v 512 1k' - dumps 1 kilobyte read from 512 bytes into the file\n" "\n" " Reads a segment of the currently open file, optionally dumping it to the\n" " standard output stream (with -v option) for subsequent inspection.\n" " -b, -- read from the VM state rather than the virtual disk\n" " -C, -- report statistics in a machine parsable format\n" " -l, -- length for pattern verification (only with -P)\n" " -p, -- use blk_pread to read the file\n" " -P, -- use a pattern to verify read data\n" " -q, -- quiet mode, do not show I/O statistics\n" " -s, -- start offset for pattern verification (only with -P)\n" " -v, -- dump buffer to standard output\n" "\n"); } static int read_f(BlockBackend *blk, int argc, char **argv); static const cmdinfo_t read_cmd = { .name = "read", .altname = "r", .cfunc = read_f, .argmin = 2, .argmax = -1, .args = "[-abCpqv] [-P pattern [-s off] [-l len]] off len", .oneline = "reads a number of bytes at a specified offset", .help = read_help, }; static int read_f(BlockBackend *blk, int argc, char **argv) { struct timeval t1, t2; int Cflag = 0, pflag = 0, qflag = 0, vflag = 0; int Pflag = 0, sflag = 0, lflag = 0, bflag = 0; int c, cnt; char *buf; int64_t offset; int count; /* Some compilers get confused and warn if this is not initialized. */ int total = 0; int pattern = 0, pattern_offset = 0, pattern_count = 0; while ((c = getopt(argc, argv, "bCl:pP:qs:v")) != EOF) { switch (c) { case 'b': bflag = 1; break; case 'C': Cflag = 1; break; case 'l': lflag = 1; pattern_count = cvtnum(optarg); if (pattern_count < 0) { printf("non-numeric length argument -- %s\n", optarg); return 0; } break; case 'p': pflag = 1; break; case 'P': Pflag = 1; pattern = parse_pattern(optarg); if (pattern < 0) { return 0; } break; case 'q': qflag = 1; break; case 's': sflag = 1; pattern_offset = cvtnum(optarg); if (pattern_offset < 0) { printf("non-numeric length argument -- %s\n", optarg); return 0; } break; case 'v': vflag = 1; break; default: return qemuio_command_usage(&read_cmd); } } if (optind != argc - 2) { return qemuio_command_usage(&read_cmd); } if (bflag && pflag) { printf("-b and -p cannot be specified at the same time\n"); return 0; } offset = cvtnum(argv[optind]); if (offset < 0) { printf("non-numeric length argument -- %s\n", argv[optind]); return 0; } optind++; count = cvtnum(argv[optind]); if (count < 0) { printf("non-numeric length argument -- %s\n", argv[optind]); return 0; } if (!Pflag && (lflag || sflag)) { return qemuio_command_usage(&read_cmd); } if (!lflag) { pattern_count = count - pattern_offset; } if ((pattern_count < 0) || (pattern_count + pattern_offset > count)) { printf("pattern verification range exceeds end of read data\n"); return 0; } if (!pflag) { if (offset & 0x1ff) { printf("offset %" PRId64 " is not sector aligned\n", offset); return 0; } if (count & 0x1ff) { printf("count %d is not sector aligned\n", count); return 0; } } buf = qemu_io_alloc(blk, count, 0xab); gettimeofday(&t1, NULL); if (pflag) { cnt = do_pread(blk, buf, offset, count, &total); } else if (bflag) { cnt = do_load_vmstate(blk, buf, offset, count, &total); } else { cnt = do_read(blk, buf, offset, count, &total); } gettimeofday(&t2, NULL); if (cnt < 0) { printf("read failed: %s\n", strerror(-cnt)); goto out; } if (Pflag) { void *cmp_buf = g_malloc(pattern_count); memset(cmp_buf, pattern, pattern_count); if (memcmp(buf + pattern_offset, cmp_buf, pattern_count)) { printf("Pattern verification failed at offset %" PRId64 ", %d bytes\n", offset + pattern_offset, pattern_count); } g_free(cmp_buf); } if (qflag) { goto out; } if (vflag) { dump_buffer(buf, offset, count); } /* Finally, report back -- -C gives a parsable format */ t2 = tsub(t2, t1); print_report("read", &t2, offset, count, total, cnt, Cflag); out: qemu_io_free(buf); return 0; } static void readv_help(void) { printf( "\n" " reads a range of bytes from the given offset into multiple buffers\n" "\n" " Example:\n" " 'readv -v 512 1k 1k ' - dumps 2 kilobytes read from 512 bytes into the file\n" "\n" " Reads a segment of the currently open file, optionally dumping it to the\n" " standard output stream (with -v option) for subsequent inspection.\n" " Uses multiple iovec buffers if more than one byte range is specified.\n" " -C, -- report statistics in a machine parsable format\n" " -P, -- use a pattern to verify read data\n" " -v, -- dump buffer to standard output\n" " -q, -- quiet mode, do not show I/O statistics\n" "\n"); } static int readv_f(BlockBackend *blk, int argc, char **argv); static const cmdinfo_t readv_cmd = { .name = "readv", .cfunc = readv_f, .argmin = 2, .argmax = -1, .args = "[-Cqv] [-P pattern ] off len [len..]", .oneline = "reads a number of bytes at a specified offset", .help = readv_help, }; static int readv_f(BlockBackend *blk, int argc, char **argv) { struct timeval t1, t2; int Cflag = 0, qflag = 0, vflag = 0; int c, cnt; char *buf; int64_t offset; /* Some compilers get confused and warn if this is not initialized. */ int total = 0; int nr_iov; QEMUIOVector qiov; int pattern = 0; int Pflag = 0; while ((c = getopt(argc, argv, "CP:qv")) != EOF) { switch (c) { case 'C': Cflag = 1; break; case 'P': Pflag = 1; pattern = parse_pattern(optarg); if (pattern < 0) { return 0; } break; case 'q': qflag = 1; break; case 'v': vflag = 1; break; default: return qemuio_command_usage(&readv_cmd); } } if (optind > argc - 2) { return qemuio_command_usage(&readv_cmd); } offset = cvtnum(argv[optind]); if (offset < 0) { printf("non-numeric length argument -- %s\n", argv[optind]); return 0; } optind++; if (offset & 0x1ff) { printf("offset %" PRId64 " is not sector aligned\n", offset); return 0; } nr_iov = argc - optind; buf = create_iovec(blk, &qiov, &argv[optind], nr_iov, 0xab); if (buf == NULL) { return 0; } gettimeofday(&t1, NULL); cnt = do_aio_readv(blk, &qiov, offset, &total); gettimeofday(&t2, NULL); if (cnt < 0) { printf("readv failed: %s\n", strerror(-cnt)); goto out; } if (Pflag) { void *cmp_buf = g_malloc(qiov.size); memset(cmp_buf, pattern, qiov.size); if (memcmp(buf, cmp_buf, qiov.size)) { printf("Pattern verification failed at offset %" PRId64 ", %zd bytes\n", offset, qiov.size); } g_free(cmp_buf); } if (qflag) { goto out; } if (vflag) { dump_buffer(buf, offset, qiov.size); } /* Finally, report back -- -C gives a parsable format */ t2 = tsub(t2, t1); print_report("read", &t2, offset, qiov.size, total, cnt, Cflag); out: qemu_iovec_destroy(&qiov); qemu_io_free(buf); return 0; } static void write_help(void) { printf( "\n" " writes a range of bytes from the given offset\n" "\n" " Example:\n" " 'write 512 1k' - writes 1 kilobyte at 512 bytes into the open file\n" "\n" " Writes into a segment of the currently open file, using a buffer\n" " filled with a set pattern (0xcdcdcdcd).\n" " -b, -- write to the VM state rather than the virtual disk\n" " -c, -- write compressed data with blk_write_compressed\n" " -p, -- use blk_pwrite to write the file\n" " -P, -- use different pattern to fill file\n" " -C, -- report statistics in a machine parsable format\n" " -q, -- quiet mode, do not show I/O statistics\n" " -z, -- write zeroes using blk_co_write_zeroes\n" "\n"); } static int write_f(BlockBackend *blk, int argc, char **argv); static const cmdinfo_t write_cmd = { .name = "write", .altname = "w", .cfunc = write_f, .argmin = 2, .argmax = -1, .args = "[-bcCpqz] [-P pattern ] off len", .oneline = "writes a number of bytes at a specified offset", .help = write_help, }; static int write_f(BlockBackend *blk, int argc, char **argv) { struct timeval t1, t2; int Cflag = 0, pflag = 0, qflag = 0, bflag = 0, Pflag = 0, zflag = 0; int cflag = 0; int c, cnt; char *buf = NULL; int64_t offset; int count; /* Some compilers get confused and warn if this is not initialized. */ int total = 0; int pattern = 0xcd; while ((c = getopt(argc, argv, "bcCpP:qz")) != EOF) { switch (c) { case 'b': bflag = 1; break; case 'c': cflag = 1; break; case 'C': Cflag = 1; break; case 'p': pflag = 1; break; case 'P': Pflag = 1; pattern = parse_pattern(optarg); if (pattern < 0) { return 0; } break; case 'q': qflag = 1; break; case 'z': zflag = 1; break; default: return qemuio_command_usage(&write_cmd); } } if (optind != argc - 2) { return qemuio_command_usage(&write_cmd); } if (bflag + pflag + zflag > 1) { printf("-b, -p, or -z cannot be specified at the same time\n"); return 0; } if (zflag && Pflag) { printf("-z and -P cannot be specified at the same time\n"); return 0; } offset = cvtnum(argv[optind]); if (offset < 0) { printf("non-numeric length argument -- %s\n", argv[optind]); return 0; } optind++; count = cvtnum(argv[optind]); if (count < 0) { printf("non-numeric length argument -- %s\n", argv[optind]); return 0; } if (!pflag) { if (offset & 0x1ff) { printf("offset %" PRId64 " is not sector aligned\n", offset); return 0; } if (count & 0x1ff) { printf("count %d is not sector aligned\n", count); return 0; } } if (!zflag) { buf = qemu_io_alloc(blk, count, pattern); } gettimeofday(&t1, NULL); if (pflag) { cnt = do_pwrite(blk, buf, offset, count, &total); } else if (bflag) { cnt = do_save_vmstate(blk, buf, offset, count, &total); } else if (zflag) { cnt = do_co_write_zeroes(blk, offset, count, &total); } else if (cflag) { cnt = do_write_compressed(blk, buf, offset, count, &total); } else { cnt = do_write(blk, buf, offset, count, &total); } gettimeofday(&t2, NULL); if (cnt < 0) { printf("write failed: %s\n", strerror(-cnt)); goto out; } if (qflag) { goto out; } /* Finally, report back -- -C gives a parsable format */ t2 = tsub(t2, t1); print_report("wrote", &t2, offset, count, total, cnt, Cflag); out: if (!zflag) { qemu_io_free(buf); } return 0; } static void writev_help(void) { printf( "\n" " writes a range of bytes from the given offset source from multiple buffers\n" "\n" " Example:\n" " 'writev 512 1k 1k' - writes 2 kilobytes at 512 bytes into the open file\n" "\n" " Writes into a segment of the currently open file, using a buffer\n" " filled with a set pattern (0xcdcdcdcd).\n" " -P, -- use different pattern to fill file\n" " -C, -- report statistics in a machine parsable format\n" " -q, -- quiet mode, do not show I/O statistics\n" "\n"); } static int writev_f(BlockBackend *blk, int argc, char **argv); static const cmdinfo_t writev_cmd = { .name = "writev", .cfunc = writev_f, .argmin = 2, .argmax = -1, .args = "[-Cq] [-P pattern ] off len [len..]", .oneline = "writes a number of bytes at a specified offset", .help = writev_help, }; static int writev_f(BlockBackend *blk, int argc, char **argv) { struct timeval t1, t2; int Cflag = 0, qflag = 0; int c, cnt; char *buf; int64_t offset; /* Some compilers get confused and warn if this is not initialized. */ int total = 0; int nr_iov; int pattern = 0xcd; QEMUIOVector qiov; while ((c = getopt(argc, argv, "CqP:")) != EOF) { switch (c) { case 'C': Cflag = 1; break; case 'q': qflag = 1; break; case 'P': pattern = parse_pattern(optarg); if (pattern < 0) { return 0; } break; default: return qemuio_command_usage(&writev_cmd); } } if (optind > argc - 2) { return qemuio_command_usage(&writev_cmd); } offset = cvtnum(argv[optind]); if (offset < 0) { printf("non-numeric length argument -- %s\n", argv[optind]); return 0; } optind++; if (offset & 0x1ff) { printf("offset %" PRId64 " is not sector aligned\n", offset); return 0; } nr_iov = argc - optind; buf = create_iovec(blk, &qiov, &argv[optind], nr_iov, pattern); if (buf == NULL) { return 0; } gettimeofday(&t1, NULL); cnt = do_aio_writev(blk, &qiov, offset, &total); gettimeofday(&t2, NULL); if (cnt < 0) { printf("writev failed: %s\n", strerror(-cnt)); goto out; } if (qflag) { goto out; } /* Finally, report back -- -C gives a parsable format */ t2 = tsub(t2, t1); print_report("wrote", &t2, offset, qiov.size, total, cnt, Cflag); out: qemu_iovec_destroy(&qiov); qemu_io_free(buf); return 0; } static void multiwrite_help(void) { printf( "\n" " writes a range of bytes from the given offset source from multiple buffers,\n" " in a batch of requests that may be merged by qemu\n" "\n" " Example:\n" " 'multiwrite 512 1k 1k ; 4k 1k'\n" " writes 2 kB at 512 bytes and 1 kB at 4 kB into the open file\n" "\n" " Writes into a segment of the currently open file, using a buffer\n" " filled with a set pattern (0xcdcdcdcd). The pattern byte is increased\n" " by one for each request contained in the multiwrite command.\n" " -P, -- use different pattern to fill file\n" " -C, -- report statistics in a machine parsable format\n" " -q, -- quiet mode, do not show I/O statistics\n" "\n"); } static int multiwrite_f(BlockBackend *blk, int argc, char **argv); static const cmdinfo_t multiwrite_cmd = { .name = "multiwrite", .cfunc = multiwrite_f, .argmin = 2, .argmax = -1, .args = "[-Cq] [-P pattern ] off len [len..] [; off len [len..]..]", .oneline = "issues multiple write requests at once", .help = multiwrite_help, }; static int multiwrite_f(BlockBackend *blk, int argc, char **argv) { struct timeval t1, t2; int Cflag = 0, qflag = 0; int c, cnt; char **buf; int64_t offset, first_offset = 0; /* Some compilers get confused and warn if this is not initialized. */ int total = 0; int nr_iov; int nr_reqs; int pattern = 0xcd; QEMUIOVector *qiovs; int i; BlockRequest *reqs; while ((c = getopt(argc, argv, "CqP:")) != EOF) { switch (c) { case 'C': Cflag = 1; break; case 'q': qflag = 1; break; case 'P': pattern = parse_pattern(optarg); if (pattern < 0) { return 0; } break; default: return qemuio_command_usage(&writev_cmd); } } if (optind > argc - 2) { return qemuio_command_usage(&writev_cmd); } nr_reqs = 1; for (i = optind; i < argc; i++) { if (!strcmp(argv[i], ";")) { nr_reqs++; } } reqs = g_new0(BlockRequest, nr_reqs); buf = g_new0(char *, nr_reqs); qiovs = g_new(QEMUIOVector, nr_reqs); for (i = 0; i < nr_reqs && optind < argc; i++) { int j; /* Read the offset of the request */ offset = cvtnum(argv[optind]); if (offset < 0) { printf("non-numeric offset argument -- %s\n", argv[optind]); goto out; } optind++; if (offset & 0x1ff) { printf("offset %lld is not sector aligned\n", (long long)offset); goto out; } if (i == 0) { first_offset = offset; } /* Read lengths for qiov entries */ for (j = optind; j < argc; j++) { if (!strcmp(argv[j], ";")) { break; } } nr_iov = j - optind; /* Build request */ buf[i] = create_iovec(blk, &qiovs[i], &argv[optind], nr_iov, pattern); if (buf[i] == NULL) { goto out; } reqs[i].qiov = &qiovs[i]; reqs[i].sector = offset >> 9; reqs[i].nb_sectors = reqs[i].qiov->size >> 9; optind = j + 1; pattern++; } /* If there were empty requests at the end, ignore them */ nr_reqs = i; gettimeofday(&t1, NULL); cnt = do_aio_multiwrite(blk, reqs, nr_reqs, &total); gettimeofday(&t2, NULL); if (cnt < 0) { printf("aio_multiwrite failed: %s\n", strerror(-cnt)); goto out; } if (qflag) { goto out; } /* Finally, report back -- -C gives a parsable format */ t2 = tsub(t2, t1); print_report("wrote", &t2, first_offset, total, total, cnt, Cflag); out: for (i = 0; i < nr_reqs; i++) { qemu_io_free(buf[i]); if (reqs[i].qiov != NULL) { qemu_iovec_destroy(&qiovs[i]); } } g_free(buf); g_free(reqs); g_free(qiovs); return 0; } struct aio_ctx { BlockBackend *blk; QEMUIOVector qiov; int64_t offset; char *buf; int qflag; int vflag; int Cflag; int Pflag; BlockAcctCookie acct; int pattern; struct timeval t1; }; static void aio_write_done(void *opaque, int ret) { struct aio_ctx *ctx = opaque; struct timeval t2; gettimeofday(&t2, NULL); if (ret < 0) { printf("aio_write failed: %s\n", strerror(-ret)); goto out; } block_acct_done(blk_get_stats(ctx->blk), &ctx->acct); if (ctx->qflag) { goto out; } /* Finally, report back -- -C gives a parsable format */ t2 = tsub(t2, ctx->t1); print_report("wrote", &t2, ctx->offset, ctx->qiov.size, ctx->qiov.size, 1, ctx->Cflag); out: qemu_io_free(ctx->buf); qemu_iovec_destroy(&ctx->qiov); g_free(ctx); } static void aio_read_done(void *opaque, int ret) { struct aio_ctx *ctx = opaque; struct timeval t2; gettimeofday(&t2, NULL); if (ret < 0) { printf("readv failed: %s\n", strerror(-ret)); goto out; } if (ctx->Pflag) { void *cmp_buf = g_malloc(ctx->qiov.size); memset(cmp_buf, ctx->pattern, ctx->qiov.size); if (memcmp(ctx->buf, cmp_buf, ctx->qiov.size)) { printf("Pattern verification failed at offset %" PRId64 ", %zd bytes\n", ctx->offset, ctx->qiov.size); } g_free(cmp_buf); } block_acct_done(blk_get_stats(ctx->blk), &ctx->acct); if (ctx->qflag) { goto out; } if (ctx->vflag) { dump_buffer(ctx->buf, ctx->offset, ctx->qiov.size); } /* Finally, report back -- -C gives a parsable format */ t2 = tsub(t2, ctx->t1); print_report("read", &t2, ctx->offset, ctx->qiov.size, ctx->qiov.size, 1, ctx->Cflag); out: qemu_io_free(ctx->buf); qemu_iovec_destroy(&ctx->qiov); g_free(ctx); } static void aio_read_help(void) { printf( "\n" " asynchronously reads a range of bytes from the given offset\n" "\n" " Example:\n" " 'aio_read -v 512 1k 1k ' - dumps 2 kilobytes read from 512 bytes into the file\n" "\n" " Reads a segment of the currently open file, optionally dumping it to the\n" " standard output stream (with -v option) for subsequent inspection.\n" " The read is performed asynchronously and the aio_flush command must be\n" " used to ensure all outstanding aio requests have been completed.\n" " -C, -- report statistics in a machine parsable format\n" " -P, -- use a pattern to verify read data\n" " -v, -- dump buffer to standard output\n" " -q, -- quiet mode, do not show I/O statistics\n" "\n"); } static int aio_read_f(BlockBackend *blk, int argc, char **argv); static const cmdinfo_t aio_read_cmd = { .name = "aio_read", .cfunc = aio_read_f, .argmin = 2, .argmax = -1, .args = "[-Cqv] [-P pattern ] off len [len..]", .oneline = "asynchronously reads a number of bytes", .help = aio_read_help, }; static int aio_read_f(BlockBackend *blk, int argc, char **argv) { int nr_iov, c; struct aio_ctx *ctx = g_new0(struct aio_ctx, 1); ctx->blk = blk; while ((c = getopt(argc, argv, "CP:qv")) != EOF) { switch (c) { case 'C': ctx->Cflag = 1; break; case 'P': ctx->Pflag = 1; ctx->pattern = parse_pattern(optarg); if (ctx->pattern < 0) { g_free(ctx); return 0; } break; case 'q': ctx->qflag = 1; break; case 'v': ctx->vflag = 1; break; default: g_free(ctx); return qemuio_command_usage(&aio_read_cmd); } } if (optind > argc - 2) { g_free(ctx); return qemuio_command_usage(&aio_read_cmd); } ctx->offset = cvtnum(argv[optind]); if (ctx->offset < 0) { printf("non-numeric length argument -- %s\n", argv[optind]); g_free(ctx); return 0; } optind++; if (ctx->offset & 0x1ff) { printf("offset %" PRId64 " is not sector aligned\n", ctx->offset); g_free(ctx); return 0; } nr_iov = argc - optind; ctx->buf = create_iovec(blk, &ctx->qiov, &argv[optind], nr_iov, 0xab); if (ctx->buf == NULL) { g_free(ctx); return 0; } gettimeofday(&ctx->t1, NULL); block_acct_start(blk_get_stats(blk), &ctx->acct, ctx->qiov.size, BLOCK_ACCT_READ); blk_aio_readv(blk, ctx->offset >> 9, &ctx->qiov, ctx->qiov.size >> 9, aio_read_done, ctx); return 0; } static void aio_write_help(void) { printf( "\n" " asynchronously writes a range of bytes from the given offset source\n" " from multiple buffers\n" "\n" " Example:\n" " 'aio_write 512 1k 1k' - writes 2 kilobytes at 512 bytes into the open file\n" "\n" " Writes into a segment of the currently open file, using a buffer\n" " filled with a set pattern (0xcdcdcdcd).\n" " The write is performed asynchronously and the aio_flush command must be\n" " used to ensure all outstanding aio requests have been completed.\n" " -P, -- use different pattern to fill file\n" " -C, -- report statistics in a machine parsable format\n" " -q, -- quiet mode, do not show I/O statistics\n" "\n"); } static int aio_write_f(BlockBackend *blk, int argc, char **argv); static const cmdinfo_t aio_write_cmd = { .name = "aio_write", .cfunc = aio_write_f, .argmin = 2, .argmax = -1, .args = "[-Cq] [-P pattern ] off len [len..]", .oneline = "asynchronously writes a number of bytes", .help = aio_write_help, }; static int aio_write_f(BlockBackend *blk, int argc, char **argv) { int nr_iov, c; int pattern = 0xcd; struct aio_ctx *ctx = g_new0(struct aio_ctx, 1); ctx->blk = blk; while ((c = getopt(argc, argv, "CqP:")) != EOF) { switch (c) { case 'C': ctx->Cflag = 1; break; case 'q': ctx->qflag = 1; break; case 'P': pattern = parse_pattern(optarg); if (pattern < 0) { g_free(ctx); return 0; } break; default: g_free(ctx); return qemuio_command_usage(&aio_write_cmd); } } if (optind > argc - 2) { g_free(ctx); return qemuio_command_usage(&aio_write_cmd); } ctx->offset = cvtnum(argv[optind]); if (ctx->offset < 0) { printf("non-numeric length argument -- %s\n", argv[optind]); g_free(ctx); return 0; } optind++; if (ctx->offset & 0x1ff) { printf("offset %" PRId64 " is not sector aligned\n", ctx->offset); g_free(ctx); return 0; } nr_iov = argc - optind; ctx->buf = create_iovec(blk, &ctx->qiov, &argv[optind], nr_iov, pattern); if (ctx->buf == NULL) { g_free(ctx); return 0; } gettimeofday(&ctx->t1, NULL); block_acct_start(blk_get_stats(blk), &ctx->acct, ctx->qiov.size, BLOCK_ACCT_WRITE); blk_aio_writev(blk, ctx->offset >> 9, &ctx->qiov, ctx->qiov.size >> 9, aio_write_done, ctx); return 0; } static int aio_flush_f(BlockBackend *blk, int argc, char **argv) { blk_drain_all(); return 0; } static const cmdinfo_t aio_flush_cmd = { .name = "aio_flush", .cfunc = aio_flush_f, .oneline = "completes all outstanding aio requests" }; static int flush_f(BlockBackend *blk, int argc, char **argv) { blk_flush(blk); return 0; } static const cmdinfo_t flush_cmd = { .name = "flush", .altname = "f", .cfunc = flush_f, .oneline = "flush all in-core file state to disk", }; static int truncate_f(BlockBackend *blk, int argc, char **argv) { int64_t offset; int ret; offset = cvtnum(argv[1]); if (offset < 0) { printf("non-numeric truncate argument -- %s\n", argv[1]); return 0; } ret = blk_truncate(blk, offset); if (ret < 0) { printf("truncate: %s\n", strerror(-ret)); return 0; } return 0; } static const cmdinfo_t truncate_cmd = { .name = "truncate", .altname = "t", .cfunc = truncate_f, .argmin = 1, .argmax = 1, .args = "off", .oneline = "truncates the current file at the given offset", }; static int length_f(BlockBackend *blk, int argc, char **argv) { int64_t size; char s1[64]; size = blk_getlength(blk); if (size < 0) { printf("getlength: %s\n", strerror(-size)); return 0; } cvtstr(size, s1, sizeof(s1)); printf("%s\n", s1); return 0; } static const cmdinfo_t length_cmd = { .name = "length", .altname = "l", .cfunc = length_f, .oneline = "gets the length of the current file", }; static int info_f(BlockBackend *blk, int argc, char **argv) { BlockDriverState *bs = blk_bs(blk); BlockDriverInfo bdi; ImageInfoSpecific *spec_info; char s1[64], s2[64]; int ret; if (bs->drv && bs->drv->format_name) { printf("format name: %s\n", bs->drv->format_name); } if (bs->drv && bs->drv->protocol_name) { printf("format name: %s\n", bs->drv->protocol_name); } ret = bdrv_get_info(bs, &bdi); if (ret) { return 0; } cvtstr(bdi.cluster_size, s1, sizeof(s1)); cvtstr(bdi.vm_state_offset, s2, sizeof(s2)); printf("cluster size: %s\n", s1); printf("vm state offset: %s\n", s2); spec_info = bdrv_get_specific_info(bs); if (spec_info) { printf("Format specific information:\n"); bdrv_image_info_specific_dump(fprintf, stdout, spec_info); qapi_free_ImageInfoSpecific(spec_info); } return 0; } static const cmdinfo_t info_cmd = { .name = "info", .altname = "i", .cfunc = info_f, .oneline = "prints information about the current file", }; static void discard_help(void) { printf( "\n" " discards a range of bytes from the given offset\n" "\n" " Example:\n" " 'discard 512 1k' - discards 1 kilobyte from 512 bytes into the file\n" "\n" " Discards a segment of the currently open file.\n" " -C, -- report statistics in a machine parsable format\n" " -q, -- quiet mode, do not show I/O statistics\n" "\n"); } static int discard_f(BlockBackend *blk, int argc, char **argv); static const cmdinfo_t discard_cmd = { .name = "discard", .altname = "d", .cfunc = discard_f, .argmin = 2, .argmax = -1, .args = "[-Cq] off len", .oneline = "discards a number of bytes at a specified offset", .help = discard_help, }; static int discard_f(BlockBackend *blk, int argc, char **argv) { struct timeval t1, t2; int Cflag = 0, qflag = 0; int c, ret; int64_t offset; int count; while ((c = getopt(argc, argv, "Cq")) != EOF) { switch (c) { case 'C': Cflag = 1; break; case 'q': qflag = 1; break; default: return qemuio_command_usage(&discard_cmd); } } if (optind != argc - 2) { return qemuio_command_usage(&discard_cmd); } offset = cvtnum(argv[optind]); if (offset < 0) { printf("non-numeric length argument -- %s\n", argv[optind]); return 0; } optind++; count = cvtnum(argv[optind]); if (count < 0) { printf("non-numeric length argument -- %s\n", argv[optind]); return 0; } gettimeofday(&t1, NULL); ret = blk_discard(blk, offset >> BDRV_SECTOR_BITS, count >> BDRV_SECTOR_BITS); gettimeofday(&t2, NULL); if (ret < 0) { printf("discard failed: %s\n", strerror(-ret)); goto out; } /* Finally, report back -- -C gives a parsable format */ if (!qflag) { t2 = tsub(t2, t1); print_report("discard", &t2, offset, count, count, 1, Cflag); } out: return 0; } static int alloc_f(BlockBackend *blk, int argc, char **argv) { BlockDriverState *bs = blk_bs(blk); int64_t offset, sector_num; int nb_sectors, remaining; char s1[64]; int num, sum_alloc; int ret; offset = cvtnum(argv[1]); if (offset < 0) { printf("non-numeric offset argument -- %s\n", argv[1]); return 0; } else if (offset & 0x1ff) { printf("offset %" PRId64 " is not sector aligned\n", offset); return 0; } if (argc == 3) { nb_sectors = cvtnum(argv[2]); if (nb_sectors < 0) { printf("non-numeric length argument -- %s\n", argv[2]); return 0; } } else { nb_sectors = 1; } remaining = nb_sectors; sum_alloc = 0; sector_num = offset >> 9; while (remaining) { ret = bdrv_is_allocated(bs, sector_num, remaining, &num); if (ret < 0) { printf("is_allocated failed: %s\n", strerror(-ret)); return 0; } sector_num += num; remaining -= num; if (ret) { sum_alloc += num; } if (num == 0) { nb_sectors -= remaining; remaining = 0; } } cvtstr(offset, s1, sizeof(s1)); printf("%d/%d sectors allocated at offset %s\n", sum_alloc, nb_sectors, s1); return 0; } static const cmdinfo_t alloc_cmd = { .name = "alloc", .altname = "a", .argmin = 1, .argmax = 2, .cfunc = alloc_f, .args = "off [sectors]", .oneline = "checks if a sector is present in the file", }; static int map_is_allocated(BlockDriverState *bs, int64_t sector_num, int64_t nb_sectors, int64_t *pnum) { int num, num_checked; int ret, firstret; num_checked = MIN(nb_sectors, INT_MAX); ret = bdrv_is_allocated(bs, sector_num, num_checked, &num); if (ret < 0) { return ret; } firstret = ret; *pnum = num; while (nb_sectors > 0 && ret == firstret) { sector_num += num; nb_sectors -= num; num_checked = MIN(nb_sectors, INT_MAX); ret = bdrv_is_allocated(bs, sector_num, num_checked, &num); if (ret == firstret && num) { *pnum += num; } else { break; } } return firstret; } static int map_f(BlockBackend *blk, int argc, char **argv) { int64_t offset; int64_t nb_sectors, total_sectors; char s1[64]; int64_t num; int ret; const char *retstr; offset = 0; total_sectors = blk_nb_sectors(blk); if (total_sectors < 0) { error_report("Failed to query image length: %s", strerror(-total_sectors)); return 0; } nb_sectors = total_sectors; do { ret = map_is_allocated(blk_bs(blk), offset, nb_sectors, &num); if (ret < 0) { error_report("Failed to get allocation status: %s", strerror(-ret)); return 0; } else if (!num) { error_report("Unexpected end of image"); return 0; } retstr = ret ? " allocated" : "not allocated"; cvtstr(offset << 9ULL, s1, sizeof(s1)); printf("[% 24" PRId64 "] % 8" PRId64 "/% 8" PRId64 " sectors %s " "at offset %s (%d)\n", offset << 9ULL, num, nb_sectors, retstr, s1, ret); offset += num; nb_sectors -= num; } while (offset < total_sectors); return 0; } static const cmdinfo_t map_cmd = { .name = "map", .argmin = 0, .argmax = 0, .cfunc = map_f, .args = "", .oneline = "prints the allocated areas of a file", }; static int break_f(BlockBackend *blk, int argc, char **argv) { int ret; ret = bdrv_debug_breakpoint(blk_bs(blk), argv[1], argv[2]); if (ret < 0) { printf("Could not set breakpoint: %s\n", strerror(-ret)); } return 0; } static int remove_break_f(BlockBackend *blk, int argc, char **argv) { int ret; ret = bdrv_debug_remove_breakpoint(blk_bs(blk), argv[1]); if (ret < 0) { printf("Could not remove breakpoint %s: %s\n", argv[1], strerror(-ret)); } return 0; } static const cmdinfo_t break_cmd = { .name = "break", .argmin = 2, .argmax = 2, .cfunc = break_f, .args = "event tag", .oneline = "sets a breakpoint on event and tags the stopped " "request as tag", }; static const cmdinfo_t remove_break_cmd = { .name = "remove_break", .argmin = 1, .argmax = 1, .cfunc = remove_break_f, .args = "tag", .oneline = "remove a breakpoint by tag", }; static int resume_f(BlockBackend *blk, int argc, char **argv) { int ret; ret = bdrv_debug_resume(blk_bs(blk), argv[1]); if (ret < 0) { printf("Could not resume request: %s\n", strerror(-ret)); } return 0; } static const cmdinfo_t resume_cmd = { .name = "resume", .argmin = 1, .argmax = 1, .cfunc = resume_f, .args = "tag", .oneline = "resumes the request tagged as tag", }; static int wait_break_f(BlockBackend *blk, int argc, char **argv) { while (!bdrv_debug_is_suspended(blk_bs(blk), argv[1])) { aio_poll(blk_get_aio_context(blk), true); } return 0; } static const cmdinfo_t wait_break_cmd = { .name = "wait_break", .argmin = 1, .argmax = 1, .cfunc = wait_break_f, .args = "tag", .oneline = "waits for the suspension of a request", }; static int abort_f(BlockBackend *blk, int argc, char **argv) { abort(); } static const cmdinfo_t abort_cmd = { .name = "abort", .cfunc = abort_f, .flags = CMD_NOFILE_OK, .oneline = "simulate a program crash using abort(3)", }; static void sigraise_help(void) { printf( "\n" " raises the given signal\n" "\n" " Example:\n" " 'sigraise %i' - raises SIGTERM\n" "\n" " Invokes raise(signal), where \"signal\" is the mandatory integer argument\n" " given to sigraise.\n" "\n", SIGTERM); } static int sigraise_f(BlockBackend *blk, int argc, char **argv); static const cmdinfo_t sigraise_cmd = { .name = "sigraise", .cfunc = sigraise_f, .argmin = 1, .argmax = 1, .flags = CMD_NOFILE_OK, .args = "signal", .oneline = "raises a signal", .help = sigraise_help, }; static int sigraise_f(BlockBackend *blk, int argc, char **argv) { int sig = cvtnum(argv[1]); if (sig < 0) { printf("non-numeric signal number argument -- %s\n", argv[1]); return 0; } /* Using raise() to kill this process does not necessarily flush all open * streams. At least stdout and stderr (although the latter should be * non-buffered anyway) should be flushed, though. */ fflush(stdout); fflush(stderr); raise(sig); return 0; } static void sleep_cb(void *opaque) { bool *expired = opaque; *expired = true; } static int sleep_f(BlockBackend *blk, int argc, char **argv) { char *endptr; long ms; struct QEMUTimer *timer; bool expired = false; ms = strtol(argv[1], &endptr, 0); if (ms < 0 || *endptr != '\0') { printf("%s is not a valid number\n", argv[1]); return 0; } timer = timer_new_ns(QEMU_CLOCK_HOST, sleep_cb, &expired); timer_mod(timer, qemu_clock_get_ns(QEMU_CLOCK_HOST) + SCALE_MS * ms); while (!expired) { main_loop_wait(false); } timer_free(timer); return 0; } static const cmdinfo_t sleep_cmd = { .name = "sleep", .argmin = 1, .argmax = 1, .cfunc = sleep_f, .flags = CMD_NOFILE_OK, .oneline = "waits for the given value in milliseconds", }; static void help_oneline(const char *cmd, const cmdinfo_t *ct) { if (cmd) { printf("%s ", cmd); } else { printf("%s ", ct->name); if (ct->altname) { printf("(or %s) ", ct->altname); } } if (ct->args) { printf("%s ", ct->args); } printf("-- %s\n", ct->oneline); } static void help_onecmd(const char *cmd, const cmdinfo_t *ct) { help_oneline(cmd, ct); if (ct->help) { ct->help(); } } static void help_all(void) { const cmdinfo_t *ct; for (ct = cmdtab; ct < &cmdtab[ncmds]; ct++) { help_oneline(ct->name, ct); } printf("\nUse 'help commandname' for extended help.\n"); } static int help_f(BlockBackend *blk, int argc, char **argv) { const cmdinfo_t *ct; if (argc == 1) { help_all(); return 0; } ct = find_command(argv[1]); if (ct == NULL) { printf("command %s not found\n", argv[1]); return 0; } help_onecmd(argv[1], ct); return 0; } static const cmdinfo_t help_cmd = { .name = "help", .altname = "?", .cfunc = help_f, .argmin = 0, .argmax = 1, .flags = CMD_FLAG_GLOBAL, .args = "[command]", .oneline = "help for one or all commands", }; bool qemuio_command(BlockBackend *blk, const char *cmd) { char *input; const cmdinfo_t *ct; char **v; int c; bool done = false; input = g_strdup(cmd); v = breakline(input, &c); if (c) { ct = find_command(v[0]); if (ct) { done = command(blk, ct, c, v); } else { fprintf(stderr, "command \"%s\" not found\n", v[0]); } } g_free(input); g_free(v); return done; } static void __attribute((constructor)) init_qemuio_commands(void) { /* initialize commands */ qemuio_add_command(&help_cmd); qemuio_add_command(&read_cmd); qemuio_add_command(&readv_cmd); qemuio_add_command(&write_cmd); qemuio_add_command(&writev_cmd); qemuio_add_command(&multiwrite_cmd); qemuio_add_command(&aio_read_cmd); qemuio_add_command(&aio_write_cmd); qemuio_add_command(&aio_flush_cmd); qemuio_add_command(&flush_cmd); qemuio_add_command(&truncate_cmd); qemuio_add_command(&length_cmd); qemuio_add_command(&info_cmd); qemuio_add_command(&discard_cmd); qemuio_add_command(&alloc_cmd); qemuio_add_command(&map_cmd); qemuio_add_command(&break_cmd); qemuio_add_command(&remove_break_cmd); qemuio_add_command(&resume_cmd); qemuio_add_command(&wait_break_cmd); qemuio_add_command(&abort_cmd); qemuio_add_command(&sleep_cmd); qemuio_add_command(&sigraise_cmd); }