forked from TritonDataCenter/illumos-kvm
-
Notifications
You must be signed in to change notification settings - Fork 2
/
kvm.c
2853 lines (2378 loc) · 64.6 KB
/
kvm.c
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
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* GPL HEADER START
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License.
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
* GPL HEADER END
*
* Originally implemented on Linux:
* Copyright (C) 2006 Qumranet, Inc.
*
* Authors:
* Avi Kivity <[email protected]>
* Yaniv Kamay <[email protected]>
*
* Ported to illumos by Joyent
* Copyright 2019 Joyent, Inc.
*
* Authors:
* Max Bruning <[email protected]>
* Bryan Cantrill <[email protected]>
* Robert Mustacchi <[email protected]>
*/
/*
* KVM -- Kernel Virtual Machine Driver
* ------------------------------------
*
* The kvm driver's purpose it to provide an interface for accelerating virtual
* machines. To that end the kernel implements and provides emulation for
* various pieces of hardware. The kernel also interacts directly with
* extensions to the x86 instruction set via VT-x and related technologies on
* Intel processors. The system is designed to support SVM (now marketed as
* AMD-V); however, it is not currently implemented in the illumos version. KVM
* does not provide all the pieces necessary for vitalization, nor is that a
* part of its design.
*
* KVM is a psuedo-device presented to userland as a character device. Consumers
* open the device and interact primarily through ioctl(2) and mmap(2).
*
* General Theory
* --------------
*
* A consumer will open up the KVM driver and perform ioctls to set up initial
* state and create virtual CPUs (VCPU). To run a specific VCPU an ioctl is
* performed. When the ioctl occurs we use the instruction set extensions to try
* and run that CPU in the current thread. This is run for as long as possible
* until an instruction that needs to be emulated by the host, e.g. a write to
* emulated hardware, or some external event brings us out e.g. an interrupt,
* the schedular descheduling the thread, etc.. Each VCPU is modeled as a
* thread. The KVM driver notes the exit reason and either handles it and
* emulates it or returns to the guest to handle it. This loop generally follows
* this flowchart:
*
*
* Userland Kernel
* |
* |-----------| |
* | VCPU_RUN |--------|-----------------|
* | ioctl(2) | | |
* |-----------| | \|/
* ^ | |---------|
* | | | Run CPU |
* | | |--->| for the |
* | | | | guest |
* | | | |---------|
* | | | |
* | | | |
* | | | |
* | | | | Stop execution of
* | | | | guest
* | | | |------------|
* | | |---------| |
* | | | Handle | |
* | | | guest | \|/
* | | | exit | / \
* |---------| | |---------| / \
* | Handle | | ^ / Can the \
* | guest | | |--------------/ Kernel handle \
* | exit | | Yes \ the exit /
* |---------| | \ reason? /
* ^ | \ /
* | | \ /
* | | |
* | | | No
* |--------------|------------------------------|
* |
*
* The data regarding the state of the VCPU and of the overall virtual machine
* is available via mmap(2) of the file descriptor corresponding to the VCPU of
* interest.
*
* All the memory for the guest is handled in the userspace of the guest. This
* includes mapping in the BIOS, the program text for the guest, and providing
* devices. To communicate about this information, get and set kernel device
* state, and interact in various ways,
*
* Kernel Emulated and Assisted Hardware
* -------------------------------------
*
* CPUs
*
* Intel and AMD provide hardware acceleration that allows for a CPU to run in
* various execution and addressing modes:
* + Real Mode - 8086 style 16-bit operands and 20-bit addressing
* + Protected Mode - 80286 style 32-bit operands and addressing and Virtual
* Memory
* + Protected Mode with PAE - Physical Address Extensions to allow 36-bits of
* addressing for physical memory. Only 32-bits of
* addressing for virtual memory are available.
*
* + Long Mode - amd64 style 64-bit operands and 64-bit virtual addressing.
* Currently only 48 bits of physical memory can be addressed.
*
* + System Management mode is unsupported and untested. It may work. It may
* cause a panic.
*
* Other Hardware
*
* The kernel emulates various pieces of additional hardware that are necessary
* for an x86 system to function. These include:
*
* + i8254 PIT - Intel Programmable Interval Timer
* + i8259 PIC - Intel Programmable Interrupt Controller
* + Modern APIC architecture consisting of:
* - Local APIC
* - I/O APIC
* + IRQ routing table
* + MMU - Memory Management Unit
*
* The following diagram shows how the different pieces of emulated hardware fit
* together. An arrow pointing to something denotes that the pointed to item is
* contained within the object.
*
* Up to KVM_MAX_VCPUS (64) cpus
*
* |---------| |-------|
* |-------------| | Virtual | | Local | Per
* | |-------------->| CPU #n | | APIC |<-- VCPU
* | Virtual | |---------| |-------| |
* | Machine | ^ \|/
* | |-------------->|---------|-----| |-------------|
* |-------------| | Virtual | | Registers |
* | | | | | | CPU #0 |---------->| |
* | | | | | |---------| | RAX,RIP,ETC |
* | | | | | | CR0,CR4,ETC |
* | | | | | | CPUID,ETC |
* | | | | | |-------------|
* | | | | |
* | | | | |
* | | | | |
* | | | | |
* |-------| | | | | | |-------------------------|
* | i8254 |<---| | | | | | |
* | PIT | | | | | | Memory Management |
* |-------| | | | |-------------------------->| Unit |
* | | | | | && |
* | | | | |--------------| | Shadow Page Table |
* |-------| | | | |->| Input/Output | | |
* | i8259 |<-----| | | APIC | |-------------------------|
* | PIC | \|/ |--------------|
* |-------| |---------|
* | IRQ |
* | Routing |
* | Table |
* |---------|
*
*
* Internal Code Layout and Design
* -------------------------------
*
* The KVM code can be broken down into the following broad sections:
*
* + Device driver entry points
* + Generic code and driver entry points
* + x86 and architecture specific code
* + Hardware emulation specific code
* + Host CPU specific code
*
* Host CPU Specific Code
*
* Both Intel and AMD provide a means for accelerating guest operation, VT-X
* (VMX) and SVM (AMD-V) respectively. However, the instructions, design, and
* means of interacting with each are different. To get around this there is a
* generic vector of operations which are implemented by both subsystems. The
* rest of the code base references these operations via the vector. As a part
* of attach(9E), the system dynamically determines whether the system
* should use the VMX or SVM operations.
*
* The operations vector is entitled kvm_x86_ops. It's functions are:
* TODO Functions and descriptions, though there may be too many
*
*
* Hardware Emulation Specific Code
*
* Various pieces of hardware are emulated by the kernel in the KVM module as
* described previously. These are accessed in several ways:
*
* + Userland performs ioctl(2)s to get and set state
* + Guests perform PIO to devices
* + Guests write to memory locations that correspond to devices
*
* To handle memory mapped devices in the guest there is an internal notion of
* an I/O device. There is an internal notion of an I/O bus. Devices can be
* registered onto the bus. Currently two buses exist. One for programmed I/O
* devices and another for memory mapped devices.
*
* Code related to IRQs is primairly contained within kvm_irq.c and
* kvm_irq_conn.c. To facilitate and provide a more generic IRQ system there are
* two useful sets of notifiers. The notifiers fire a callback when the
* specified event occurs. Currently there are two notifiers:
*
*
* + IRQ Mask Notifier: This fires its callback when an IRQ has been masked
* by an operation.
* + IRQ Ack Notifier: This fires its callback when an IRQ has been
* acknowledged.
*
* The hardware emulation code is broken down across the following files:
*
* + i8254 PIT implementation: kvm_i8254.c and kvm_i8254.h
* + i8259 PIC implementation: kvm_i8259.c
* + I/O APIC Implementation: kvm_ioapic.c and kvm_ioapic.h
* + Local APIC Implementation: kvm_lapic.c and kvm_lapic.h
* + Memory Management Unit: kvm_mmu.c, kvm_mmu.h, and kvm_paging_tmpl.h
*
* x86 and Architecture Specific Code
*
* The code specific to x86 that is not device specific is broken across two
* files. The first is kvm_x86.c. This contains most of the x86 specific
* logic, calls into the CPU specific vector of operations, and serves as a
* gateway to some device specific portions and memory management code.
*
* The other main piece of this is kvm_emulate.c. This file contains code
* that cannot be handled by the CPU specific instructions and instead need to
* be handled by kvm, for example an inb or outb instruction.
*
* Generic Code
*
* The code that is not specific to devices or to x86 specifically can be found
* in kvm.c. This includes code that interacts directly with different parts of
* the rest of the kernel; the scheduler, cross calls, etc.
*
* Device Driver Entry Points
*
* The KVM driver is a psuedo-device that presents as a character device. All of
* the necessary entry points and related pieces of infrastructure are all
* located in kvm.c. This includes all of the logic related to open(2),
* close(2), mmap(2), ioctl(2), and the other necessary driver entry points.
*
* Interactions between Userland and the Kernel
* --------------------------------------------
*
* -Opening and cloning / VCPUs
* -The mmap(2) related pieces.
* -The general ioctl->arch->x86_ops->vmx
*
* Timers and Cyclics
* ------------------
*
* -Timers mapping to cyclics
*
* Memory Management
* -----------------
*
* -Current memory model / assumptions (i.e. can't be paged)
* -Use of kpm
*/
#include <sys/types.h>
#include <sys/param.h>
#include <sys/errno.h>
#include <sys/uio.h>
#include <sys/buf.h>
#include <sys/modctl.h>
#include <sys/open.h>
#include <sys/kmem.h>
#include <sys/poll.h>
#include <sys/conf.h>
#include <sys/cmn_err.h>
#include <sys/stat.h>
#include <sys/ddi.h>
#include <sys/sunddi.h>
#include <sys/atomic.h>
#include <sys/spl.h>
#include <sys/cpuvar.h>
#include <sys/segments.h>
#include <sys/cred.h>
#include <sys/devops.h>
#include <sys/file.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/vm.h>
#include <sys/proc.h>
#include <vm/seg_kpm.h>
#include <sys/avl.h>
#include <sys/condvar_impl.h>
#include <sys/file.h>
#include <sys/vnode.h>
#include <sys/strsubr.h>
#include <sys/stream.h>
#include <sys/machparam.h>
#include <sys/xc_levels.h>
#include <asm/cpu.h>
#include <sys/id_space.h>
#include <sys/hma.h>
#include "kvm_bitops.h"
#include "kvm_vmx.h"
#include "msr-index.h"
#include "kvm_msr.h"
#include "kvm_host.h"
#include "kvm_lapic.h"
#include "processor-flags.h"
#include "hyperv.h"
#include "kvm_apicdef.h"
#include "kvm_iodev.h"
#include "kvm.h"
#include "kvm_x86impl.h"
#include "kvm_irq.h"
#include "kvm_ioapic.h"
#include "kvm_coalesced_mmio.h"
#include "kvm_i8254.h"
#include "kvm_mmu.h"
#include "kvm_cache_regs.h"
#undef DEBUG
/*
* The entire state of the kvm device.
*/
typedef struct {
struct kvm *kds_kvmp; /* pointer to underlying VM */
struct kvm_vcpu *kds_vcpu; /* pointer to VCPU */
} kvm_devstate_t;
/*
* Globals
*/
page_t *bad_page = NULL;
void *bad_page_kma = NULL;
pfn_t bad_pfn = PFN_INVALID;
/*
* Tunables
*/
static int kvm_hiwat = 0x1000000;
#define KVM_MINOR_BASE 0
#define KVM_MINOR_INSTS 1
/*
* Internal driver-wide values
*/
static void *kvm_state; /* DDI state */
static id_space_t *kvm_minors; /* minor number arena */
static dev_info_t *kvm_dip; /* global devinfo hanlde */
static hma_reg_t *kvm_hma_reg;
static int kvmid; /* monotonically increasing, unique per vm */
static int largepages_enabled = 1;
static uint_t kvm_usage_count;
static list_t vm_list;
static kmutex_t kvm_lock;
static int ignore_msrs = 0;
static unsigned long empty_zero_page[PAGESIZE / sizeof (unsigned long)];
int
kvm_xcall_func(kvm_xcall_t func, void *arg)
{
if (func != NULL)
(*func)(arg);
return (0);
}
void
kvm_xcall(processorid_t cpu, kvm_xcall_t func, void *arg)
{
cpuset_t set;
CPUSET_ZERO(set);
if (cpu == KVM_CPUALL) {
CPUSET_ALL(set);
} else {
CPUSET_ADD(set, cpu);
}
kpreempt_disable();
xc_sync((xc_arg_t)func, (xc_arg_t)arg, 0, CPUSET2BV(set),
(xc_func_t) kvm_xcall_func);
kpreempt_enable();
}
void
kvm_user_return_notifier_register(struct kvm_vcpu *vcpu,
struct kvm_user_return_notifier *urn)
{
vcpu->urn = urn;
}
void
kvm_user_return_notifier_unregister(struct kvm_vcpu *vcpu,
struct kvm_user_return_notifier *urn)
{
vcpu->urn = NULL;
}
void
kvm_fire_urn(struct kvm_vcpu *vcpu)
{
if (vcpu->urn)
vcpu->urn->on_user_return(vcpu, vcpu->urn);
}
void
kvm_ringbuf_record(kvm_ringbuf_t *ringbuf, uint32_t tag, uint64_t payload)
{
kvm_ringbuf_entry_t *ent = &ringbuf->kvmr_buf[ringbuf->kvmr_ent++ &
(KVM_RINGBUF_NENTRIES - 1)];
int id = curthread->t_cpu->cpu_id;
hrtime_t tsc = gethrtime_unscaled();
ent->kvmre_tag = tag;
ent->kvmre_cpuid = id;
ent->kvmre_thread = (uintptr_t)curthread;
ent->kvmre_tsc = tsc;
ent->kvmre_payload = payload;
ent = &ringbuf->kvmr_taglast[tag];
ent->kvmre_tag = tag;
ent->kvmre_cpuid = id;
ent->kvmre_thread = (uintptr_t)curthread;
ent->kvmre_tsc = tsc;
ent->kvmre_payload = payload;
ringbuf->kvmr_tagcount[tag]++;
}
/*
* Called when we've been asked to save our context. i.e. we're being swapped
* out.
*/
static void
kvm_ctx_save(void *arg)
{
struct kvm_vcpu *vcpu = arg;
kvm_ringbuf_record(&vcpu->kvcpu_ringbuf,
KVM_RINGBUF_TAG_CTXSAVE, vcpu->cpu);
kvm_arch_vcpu_put(vcpu);
kvm_fire_urn(vcpu);
}
/*
* Called when we're being asked to restore our context. i.e. we're returning
* from being swapped out.
*/
static void
kvm_ctx_restore(void *arg)
{
struct kvm_vcpu *vcpu = arg;
const int cpu = CPU->cpu_id;
kvm_ringbuf_record(&vcpu->kvcpu_ringbuf,
KVM_RINGBUF_TAG_CTXRESTORE, vcpu->cpu);
kvm_arch_vcpu_load(vcpu, cpu);
}
inline int
kvm_is_mmio_pfn(pfn_t pfn)
{
return (pfn == PFN_INVALID);
}
/*
* Switches to specified vcpu, until a matching vcpu_put()
*/
void
vcpu_load(struct kvm_vcpu *vcpu)
{
mutex_enter(&vcpu->mutex);
kpreempt_disable();
ctxop_attach(curthread, vcpu->ctxop);
kvm_arch_vcpu_load(vcpu, CPU->cpu_id);
kvm_ringbuf_record(&vcpu->kvcpu_ringbuf,
KVM_RINGBUF_TAG_VCPULOAD, vcpu->cpu);
kpreempt_enable();
}
struct kvm_vcpu *
kvm_get_vcpu(struct kvm *kvm, int i)
{
smp_rmb();
return (kvm->vcpus[i]);
}
void
vcpu_put(struct kvm_vcpu *vcpu)
{
int cpu;
kpreempt_disable();
cpu = vcpu->cpu;
kvm_arch_vcpu_put(vcpu);
kvm_fire_urn(vcpu);
ctxop_detach(curthread, vcpu->ctxop);
kvm_ringbuf_record(&vcpu->kvcpu_ringbuf, KVM_RINGBUF_TAG_VCPUPUT, cpu);
kpreempt_enable();
mutex_exit(&vcpu->mutex);
}
int
make_all_cpus_request(struct kvm *kvm, unsigned int req)
{
int i;
processorid_t me, cpu;
struct kvm_vcpu *vcpu;
mutex_enter(&kvm->requests_lock);
kpreempt_disable();
me = curthread->t_cpu->cpu_id;
for (i = 0; i < kvm->online_vcpus; i++) {
vcpu = kvm->vcpus[i];
if (!vcpu)
break;
if (test_and_set_bit(req, &vcpu->requests))
continue;
cpu = vcpu->cpu;
if (cpu != -1 && cpu != me)
poke_cpu(cpu);
}
kpreempt_enable();
mutex_exit(&kvm->requests_lock);
return (1);
}
void
kvm_flush_remote_tlbs(struct kvm *kvm)
{
if (make_all_cpus_request(kvm, KVM_REQ_TLB_FLUSH))
KVM_KSTAT_INC(kvm, kvmks_remote_tlb_flush);
}
void
kvm_reload_remote_mmus(struct kvm *kvm)
{
make_all_cpus_request(kvm, KVM_REQ_MMU_RELOAD);
}
static const struct ctxop_template kvm_ctxop_tpl = {
.ct_rev = CTXOP_TPL_REV,
.ct_save = kvm_ctx_save,
.ct_restore = kvm_ctx_restore
};
int
kvm_vcpu_init(struct kvm_vcpu *vcpu, struct kvm *kvm, unsigned id)
{
int r;
mutex_init(&vcpu->mutex, NULL, MUTEX_DRIVER, 0);
vcpu->cpu = -1;
vcpu->kvm = kvm;
vcpu->vcpu_id = id;
vcpu->run = ddi_umem_alloc(PAGESIZE * 2, DDI_UMEM_SLEEP, &vcpu->cookie);
r = kvm_arch_vcpu_init(vcpu);
if (r != 0) {
vcpu->run = NULL;
ddi_umem_free(vcpu->cookie);
return (r);
}
vcpu->ctxop = ctxop_allocate(&kvm_ctxop_tpl, vcpu);
return (0);
}
void
kvm_vcpu_uninit(struct kvm_vcpu *vcpu)
{
kvm_arch_vcpu_uninit(vcpu);
ddi_umem_free(vcpu->cookie);
ctxop_free(vcpu->ctxop);
}
/*
* Note if we want to implement the kvm mmu notifier components than the
* following two functions will need to be readdressed.
*/
static int kvm_init_mmu_notifier(struct kvm *kvm)
{
return (0);
}
static void
kvm_fini_mmu_notifier(struct kvm *kvm)
{
}
static void
kvm_destroy_vm(struct kvm *kvmp)
{
int ii;
if (kvmp == NULL)
return;
if (kvmp->kvm_kstat != NULL)
kstat_delete(kvmp->kvm_kstat);
kvm_arch_flush_shadow(kvmp); /* clean up shadow page tables */
kvm_arch_destroy_vm_comps(kvmp);
kvm_free_irq_routing(kvmp);
kvm_destroy_pic(kvmp);
kvm_ioapic_destroy(kvmp);
kvm_coalesced_mmio_free(kvmp);
list_remove(&vm_list, kvmp);
avl_destroy(&kvmp->kvm_avlmp);
mutex_destroy(&kvmp->kvm_avllock);
mutex_destroy(&kvmp->memslots_lock);
mutex_destroy(&kvmp->slots_lock);
mutex_destroy(&kvmp->irq_lock);
mutex_destroy(&kvmp->lock);
mutex_destroy(&kvmp->requests_lock);
mutex_destroy(&kvmp->mmu_lock);
mutex_destroy(&kvmp->buses_lock);
kvm_fini_mmu_notifier(kvmp);
for (ii = 0; ii < KVM_NR_BUSES; ii++)
kmem_free(kvmp->buses[ii], sizeof (struct kvm_io_bus));
rw_destroy(&kvmp->kvm_rwlock);
/*
* These lists are contained by the pic. However, the pic isn't
*/
list_destroy(&kvmp->irq_ack_notifier_list);
list_destroy(&kvmp->mask_notifier_list);
kvm_arch_destroy_vm(kvmp);
}
static struct kvm *
kvm_create_vm(void)
{
int rval = 0;
int i;
struct kvm *kvmp = kvm_arch_create_vm();
if (kvmp == NULL)
return (NULL);
list_create(&kvmp->mask_notifier_list,
sizeof (struct kvm_irq_mask_notifier),
offsetof(struct kvm_irq_mask_notifier, link));
list_create(&kvmp->irq_ack_notifier_list,
sizeof (struct kvm_irq_ack_notifier),
offsetof(struct kvm_irq_ack_notifier, link));
kvmp->memslots = kmem_zalloc(sizeof (struct kvm_memslots), KM_SLEEP);
rw_init(&kvmp->kvm_rwlock, NULL, RW_DRIVER, NULL);
for (i = 0; i < KVM_NR_BUSES; i++) {
kvmp->buses[i] =
kmem_zalloc(sizeof (struct kvm_io_bus), KM_SLEEP);
}
rval = kvm_init_mmu_notifier(kvmp);
if (rval != DDI_SUCCESS) {
rw_destroy(&kvmp->kvm_rwlock);
kvm_arch_destroy_vm(kvmp);
return (NULL);
}
mutex_init(&kvmp->mmu_lock, NULL, MUTEX_DRIVER, NULL);
mutex_init(&kvmp->requests_lock, NULL, MUTEX_DRIVER, NULL);
mutex_init(&kvmp->lock, NULL, MUTEX_DRIVER, NULL);
mutex_init(&kvmp->memslots_lock, NULL, MUTEX_DRIVER, NULL);
mutex_init(&kvmp->irq_lock, NULL, MUTEX_DRIVER, NULL);
mutex_init(&kvmp->slots_lock, NULL, MUTEX_DRIVER, NULL);
mutex_init(&kvmp->kvm_avllock, NULL, MUTEX_DRIVER, NULL);
mutex_init(&kvmp->buses_lock, NULL, MUTEX_DRIVER, NULL);
avl_create(&kvmp->kvm_avlmp, kvm_avlmmucmp, sizeof (kvm_mmu_page_t),
offsetof(kvm_mmu_page_t, kmp_avlnode));
mutex_enter(&kvm_lock);
kvmp->kvmid = kvmid++;
kvmp->users_count = 1;
list_insert_tail(&vm_list, kvmp);
mutex_exit(&kvm_lock);
if ((kvmp->kvm_kstat = kstat_create_zone("kvm", kvmp->kvmid, "vm",
"misc", KSTAT_TYPE_NAMED, sizeof (kvm_stats_t) /
sizeof (kstat_named_t), KSTAT_FLAG_VIRTUAL, GLOBAL_ZONEID)) ==
NULL) {
kvm_destroy_vm(kvmp);
return (NULL);
}
kvmp->kvm_kstat->ks_data = &kvmp->kvm_stats;
kvmp->kvm_kstat->ks_data_size +=
strlen(curproc->p_zone->zone_name) + 1;
KVM_KSTAT_INIT(kvmp, kvmks_pid, "pid");
kvmp->kvm_stats.kvmks_pid.value.ui64 = kvmp->kvm_pid = curproc->p_pid;
KVM_KSTAT_INIT(kvmp, kvmks_mmu_pte_write, "mmu-pte-write");
KVM_KSTAT_INIT(kvmp, kvmks_mmu_pte_updated, "mmu-pte-updated");
KVM_KSTAT_INIT(kvmp, kvmks_mmu_pte_zapped, "mmu-pte-zapped");
KVM_KSTAT_INIT(kvmp, kvmks_mmu_flooded, "mmu-flooded");
KVM_KSTAT_INIT(kvmp, kvmks_mmu_cache_miss, "mmu-cache-miss");
KVM_KSTAT_INIT(kvmp, kvmks_mmu_recycled, "mmu-recycled");
KVM_KSTAT_INIT(kvmp, kvmks_remote_tlb_flush, "remote-tlb-flush");
KVM_KSTAT_INIT(kvmp, kvmks_lpages, "lpages");
KVM_KSTAT_INIT(kvmp, kvmks_mmu_unsync_page, "mmu-unsync-page");
kstat_named_init(&(kvmp->kvm_stats.kvmks_zonename), "zonename",
KSTAT_DATA_STRING);
kstat_named_setstr(&(kvmp->kvm_stats.kvmks_zonename),
curproc->p_zone->zone_name);
kstat_install(kvmp->kvm_kstat);
kvm_coalesced_mmio_init(kvmp);
return (kvmp);
}
/*
* Free any memory in @free but not in @dont.
*/
static void
kvm_free_physmem_slot(struct kvm_memory_slot *free,
struct kvm_memory_slot *dont)
{
int i;
if (!dont || free->rmap != dont->rmap)
kmem_free(free->rmap, free->npages * sizeof (struct page *));
if ((!dont || free->dirty_bitmap != dont->dirty_bitmap) &&
free->dirty_bitmap)
kmem_free(free->dirty_bitmap, free->dirty_bitmap_sz);
for (i = 0; i < KVM_NR_PAGE_SIZES - 1; ++i) {
if ((!dont || free->lpage_info[i] != dont->lpage_info[i]) &&
free->lpage_info[i]) {
kmem_free(free->lpage_info[i], free->lpage_info_sz[i]);
free->lpage_info[i] = NULL;
}
}
free->npages = 0;
free->dirty_bitmap = NULL;
free->rmap = NULL;
}
void
kvm_free_physmem(struct kvm *kvm)
{
int ii;
struct kvm_memslots *slots = kvm->memslots;
for (ii = 0; ii < slots->nmemslots; ii++)
kvm_free_physmem_slot(&slots->memslots[ii], NULL);
kmem_free(kvm->memslots, sizeof (struct kvm_memslots));
}
void
kvm_get_kvm(struct kvm *kvm)
{
atomic_inc_32((volatile uint32_t *)&kvm->users_count);
}
unsigned long
kvm_dirty_bitmap_bytes(struct kvm_memory_slot *memslot)
{
return (BT_SIZEOFMAP(memslot->npages));
}
/*
* Allocate some memory and give it an address in the guest physical address
* space.
*
* Discontiguous memory is allowed, mostly for framebuffers.
*
* Must be called holding mmap_sem for write.
*/
int
__kvm_set_memory_region(struct kvm *kvmp,
struct kvm_userspace_memory_region *mem, int user_alloc)
{
int r, flush_shadow = 0;
gfn_t base_gfn;
unsigned long npages;
unsigned long i;
struct kvm_memory_slot *memslot;
struct kvm_memory_slot old, new;
struct kvm_memslots *slots, *old_memslots;
r = EINVAL;
/* General sanity checks */
if (mem->memory_size & (PAGESIZE - 1))
goto out;
if (mem->guest_phys_addr & (PAGESIZE - 1))
goto out;
if (user_alloc && (mem->userspace_addr & (PAGESIZE - 1)))
goto out;
if (mem->slot >= KVM_MEMORY_SLOTS + KVM_PRIVATE_MEM_SLOTS)
goto out;
if (mem->guest_phys_addr + mem->memory_size < mem->guest_phys_addr)
goto out;
memslot = &kvmp->memslots->memslots[mem->slot];
base_gfn = mem->guest_phys_addr >> PAGESHIFT;
npages = mem->memory_size >> PAGESHIFT;
if (!npages)
mem->flags &= ~KVM_MEM_LOG_DIRTY_PAGES;
new = old = *memslot;
new.base_gfn = base_gfn;
new.npages = npages;
new.flags = mem->flags;
/* Disallow changing a memory slot's size. */
r = EINVAL;
if (npages && old.npages && npages != old.npages)
goto out_free;
/* Check for overlaps */
r = EEXIST;
for (i = 0; i < KVM_MEMORY_SLOTS; ++i) {
struct kvm_memory_slot *s = &kvmp->memslots->memslots[i];
if (s == memslot || !s->npages)
continue;
if (!((base_gfn + npages <= s->base_gfn) ||
(base_gfn >= s->base_gfn + s->npages)))
goto out_free;
}
/* Free page dirty bitmap if unneeded */
if (!(new.flags & KVM_MEM_LOG_DIRTY_PAGES))
new.dirty_bitmap = NULL;
r = ENOMEM;
/* Allocate if a slot is being created */
if (npages && !new.rmap) {
new.rmap =
kmem_zalloc(npages * sizeof (struct page *), KM_SLEEP);
new.user_alloc = user_alloc;
new.userspace_addr = mem->userspace_addr;
}
if (!npages)
goto skip_lpage;
for (i = 0; i < KVM_NR_PAGE_SIZES - 1; ++i) {
unsigned long ugfn;
unsigned long j;
int lpages;
int level = i + 2;
/* Avoid unused variable warning if no large pages */
(void) level;
if (new.lpage_info[i])
continue;
lpages = 1 + (base_gfn + npages - 1) /
KVM_PAGES_PER_HPAGE(level);
lpages -= base_gfn / KVM_PAGES_PER_HPAGE(level);
new.lpage_info[i] =
kmem_zalloc(lpages * sizeof (*new.lpage_info[i]), KM_SLEEP);
new.lpage_info_sz[i] = lpages * sizeof (*new.lpage_info[i]);
if (base_gfn % KVM_PAGES_PER_HPAGE(level))
new.lpage_info[i][0].write_count = 1;
if ((base_gfn+npages) % KVM_PAGES_PER_HPAGE(level))
new.lpage_info[i][lpages - 1].write_count = 1;
ugfn = new.userspace_addr >> PAGESHIFT;
/*
* If the gfn and userspace address are not aligned wrt each
* other, or if explicitly asked to, disable large page
* support for this slot
*/
if ((base_gfn ^ ugfn) & (KVM_PAGES_PER_HPAGE(level) - 1) ||
!largepages_enabled)
for (j = 0; j < lpages; ++j)
new.lpage_info[i][j].write_count = 1;
}
skip_lpage:
/* Allocate page dirty bitmap if needed */
if ((new.flags & KVM_MEM_LOG_DIRTY_PAGES) && !new.dirty_bitmap) {
unsigned long dirty_bytes = kvm_dirty_bitmap_bytes(&new);
new.dirty_bitmap = kmem_zalloc(dirty_bytes, KM_SLEEP);
new.dirty_bitmap_sz = dirty_bytes;
/* destroy any largepage mappings for dirty tracking */
if (old.npages)
flush_shadow = 1;
}
if (!npages) {
r = ENOMEM;
slots = kmem_zalloc(sizeof (kvm_memslots_t), KM_SLEEP);
memcpy(slots, kvmp->memslots, sizeof (kvm_memslots_t));
if (mem->slot >= slots->nmemslots)
slots->nmemslots = mem->slot + 1;
slots->memslots[mem->slot].flags |= KVM_MEMSLOT_INVALID;
mutex_enter(&kvmp->memslots_lock);
old_memslots = kvmp->memslots;
kvmp->memslots = slots;
mutex_exit(&kvmp->memslots_lock);
/*
* From this point no new shadow pages pointing to a deleted
* memslot will be created.
*
* validation of sp->gfn happens in:
* - gfn_to_hva (kvm_read_guest, gfn_to_pfn)
* - kvm_is_visible_gfn (mmu_check_roots)
*/
kvm_arch_flush_shadow(kvmp);
kmem_free(old_memslots, sizeof (struct kvm_memslots));
}
r = kvm_arch_prepare_memory_region(kvmp, &new, old, mem, user_alloc);
if (r)
goto out_free;
r = ENOMEM;
slots = kmem_zalloc(sizeof (kvm_memslots_t), KM_SLEEP);
memcpy(slots, kvmp->memslots, sizeof (kvm_memslots_t));
if (mem->slot >= slots->nmemslots)
slots->nmemslots = mem->slot + 1;
/* actual memory is freed via old in kvm_free_physmem_slot below */
if (!npages) {
new.rmap = NULL;
new.dirty_bitmap = NULL;
for (i = 0; i < KVM_NR_PAGE_SIZES - 1; ++i)
new.lpage_info[i] = NULL;
}
slots->memslots[mem->slot] = new;
mutex_enter(&kvmp->memslots_lock);
old_memslots = kvmp->memslots;
kvmp->memslots = slots;
mutex_exit(&kvmp->memslots_lock);
kvm_arch_commit_memory_region(kvmp, mem, old, user_alloc);
mutex_enter(&kvmp->memslots_lock);
kvm_free_physmem_slot(&old, &new);
mutex_exit(&kvmp->memslots_lock);
kmem_free(old_memslots, sizeof (struct kvm_memslots));
if (flush_shadow)
kvm_arch_flush_shadow(kvmp);
return (DDI_SUCCESS);
out_free:
kvm_free_physmem_slot(&new, &old);
out:
return (r);