forked from qemu/qemu
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvirtio-llfree-balloon.c
1474 lines (1248 loc) · 47 KB
/
virtio-llfree-balloon.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
#include "qemu/osdep.h"
#include "qemu/iov.h"
#include "qemu/module.h"
#include "qemu/queue.h"
#include "qemu/timer.h"
#include "qemu/madvise.h"
#include "qemu/error-report.h"
#include "hw/virtio/virtio.h"
#include "hw/virtio/virtio-bus.h"
#include "hw/qdev-properties.h"
#include "hw/boards.h"
#include "hw/virtio/virtio-llfree-balloon.h"
#include "llfree_platform.h"
#include "subprojects/llfree-c/llc/src/utils.h"
#include "sysemu/llfree-balloon.h"
#include "sysemu/kvm.h"
#include "exec/address-spaces.h"
#include "qapi/error.h"
#include "tests/unit/iothread.h"
#include "trace.h"
#include "standard-headers/linux/virtio_llfree_balloon.h"
#include "standard-headers/linux/virtio_ids.h"
#include "llfree.h"
#include "llfree_zone.h"
#include "llfree_states.h"
#include <stdbool.h>
#include <stdint.h>
#include <linux/kvm.h>
// For Testing
// #define CONFIG_SIMULATE_BROKEN_VFIO 1
// #define CONFIG_DEBUG 1
#define LL_PAGE_SHIFT 12
#define LL_PAGE_SIZE (1 << LL_PAGE_SHIFT)
#define LL_HUGE_ORDER 9
#define LL_HUGE_COUNT (1 << LL_HUGE_ORDER)
#define LL_HUGE_SHIFT (LL_PAGE_SHIFT + LL_HUGE_ORDER)
#define LL_HUGE_SIZE (1 << LL_HUGE_SHIFT)
#define LL_RETRY_INTERVAL (5 * NANOSECONDS_PER_SECOND)
#define LL_PAGECACHE_RETRIES 1
#define LL_NUM_STATIC_QUEUES 2
/*-----------------------------------------------------------------------------------------------
| Shared Structs and Enums
-------------------------------------------------------------------------------------------------*/
typedef enum ll_notification {
PAGECACHE_DROPPED,
} ll_notification_t;
typedef struct ll_install_info {
uint32_t node;
uint32_t zone;
uint64_t frame;
} ll_install_info_t;
/// Static Memory Zone Preference Definitions.
/// We exclude ZONE_DMA as it is already quite small.
static const ll_zone_type_t zone_priority[] = {
LL_ZONE_NORMAL,
LL_ZONE_MOVABLE,
LL_ZONE_DMA32,
};
#define ZONE_PRIORITY_LEN (sizeof(zone_priority) / sizeof(*zone_priority))
/*-----------------------------------------------------------------------------------------------
| Helper Functions
-------------------------------------------------------------------------------------------------*/
static ram_addr_t get_current_ram_size(void)
{
MachineState *machine = MACHINE(qdev_get_machine());
if (machine->device_memory) {
return machine->ram_size + machine->device_memory->dimm_size;
} else {
return machine->ram_size;
}
}
static uint32_t get_num_vcpus(void)
{
MachineState *machine = MACHINE(qdev_get_machine());
return machine->smp.cpus;
}
typedef int (*aggregate_fn)(void *ctx, uint64_t frame, size_t len);
typedef struct aggerage {
aggregate_fn fn;
void *ctx;
uint64_t frame;
size_t len;
} aggregate_t;
static aggregate_t aggregate_start(aggregate_fn fn, void *ctx)
{
return (aggregate_t){
.fn = fn,
.ctx = ctx,
.frame = 0,
.len = 0,
};
}
static int aggregate_next(aggregate_t *self, uint64_t frame, size_t len)
{
g_assert(len > 0);
// first range
if (self->len == 0) {
self->frame = frame;
self->len = len;
return 0;
}
// extend right
if (self->frame + self->len == frame) {
self->len += len;
return 0;
}
// extend left
if (frame + len == self->frame) {
self->frame = frame;
self->len += len;
return 0;
}
// not extendable
int ret = (self->fn)(self->ctx, self->frame, self->len);
self->frame = frame;
self->len = len;
return ret;
}
static int aggregate_finish(aggregate_t *self)
{
if (self->len > 0)
return (self->fn)(self->ctx, self->frame, self->len);
return 0;
}
/*-----------------------------------------------------------------------------------------------
| RamDiscardManager Functions, Part 1
| Bitmap Manipulation and explicit VFIO Notifications
| Implementation is largely taken directly from virtio-mem
-------------------------------------------------------------------------------------------------*/
/*
* Adjust the memory section to cover the intersection with the given range.
*
* Returns false if the intersection is empty, otherwise returns true.
*/
static bool intersect_memory_section(MemoryRegionSection *s, uint64_t offset,
uint64_t size)
{
uint64_t start = MAX(s->offset_within_region, offset);
uint64_t end =
MIN(s->offset_within_region + int128_get64(s->size), offset + size);
if (end <= start) {
return false;
}
s->offset_within_address_space += start - s->offset_within_region;
s->offset_within_region = start;
s->size = int128_make64(end - start);
return true;
}
static void notify_discard(VirtIOLLFreeBalloon *dev, uint64_t offset,
uint64_t size)
{
RamDiscardListener *rdl;
#ifdef CONFIG_SIMULATE_BROKEN_VFIO
return;
#endif
if (QLIST_EMPTY(&dev->rdl_list)) {
return;
}
bool found_intersection = false;
QLIST_FOREACH(rdl, &dev->rdl_list, next)
{
MemoryRegionSection tmp = *rdl->section;
if (!intersect_memory_section(&tmp, offset, size)) {
continue;
}
found_intersection = true;
rdl->notify_discard(rdl, &tmp);
}
// we always expect to find at least one match, as we are inflating
// RAM memory
g_assert(found_intersection == true);
}
static int notify_populate(VirtIOLLFreeBalloon *dev, uint64_t offset,
uint64_t size)
{
RamDiscardListener *rdl, *rdl2;
int ret = 0;
#ifdef CONFIG_SIMULATE_BROKEN_VFIO
return 0;
#endif
if (QLIST_EMPTY(&dev->rdl_list)) {
return 0;
}
bool found_intersection = false;
QLIST_FOREACH(rdl, &dev->rdl_list, next)
{
MemoryRegionSection tmp = *rdl->section;
if (!intersect_memory_section(&tmp, offset, size)) {
continue;
}
found_intersection = true;
ret = rdl->notify_populate(rdl, &tmp);
if (ret) {
break;
}
}
// we always expect to find at least one match, as we are inflating
// RAM memory
g_assert(found_intersection == true);
if (ret) {
/* Notify all already-notified listeners. */
QLIST_FOREACH(rdl2, &dev->rdl_list, next)
{
MemoryRegionSection tmp = *rdl2->section;
if (rdl2 == rdl) {
break;
}
if (!intersect_memory_section(&tmp, offset, size)) {
continue;
}
rdl2->notify_discard(rdl2, &tmp);
}
}
return ret;
}
/*-----------------------------------------------------------------------------------------------
| LLFree-Balloon Inflation Operation Functions
-------------------------------------------------------------------------------------------------*/
static void unmap_range(VirtIOLLFreeBalloon *dev, hwaddr gpa, size_t size)
{
g_assert(gpa > 0 && gpa > 0 && size % LL_HUGE_SIZE == 0);
MemoryRegionSection section =
memory_region_find(get_system_memory(), gpa, size);
// we registered as RamDiscardManager for the RAM memory region
// every section here should be part of this region and therefore we should
// see that the RamDiscardManager field has been set by us
g_assert(section.mr != NULL);
if (!memory_region_is_ram(section.mr) || memory_region_is_rom(section.mr) ||
memory_region_is_romd(section.mr)) {
g_assert(!"unmap: invalid section");
}
void *addr =
memory_region_get_ram_ptr(section.mr) + section.offset_within_region;
ram_addr_t rb_offset;
RAMBlock *rb = qemu_ram_block_from_host(addr, false, &rb_offset);
int ret = ram_block_discard_range(rb, rb_offset, size);
if (ret < 0)
g_assert(!"unmap: discard failed");
notify_discard(dev, section.offset_within_region, size);
memory_region_unref(section.mr);
}
struct ag_dev_zone {
VirtIOLLFreeBalloon *dev;
ll_zone_t *zone;
};
static int reclaim_mapped_range_cb(void *ctx, uint64_t frame, size_t len)
{
struct ag_dev_zone *data = ctx;
ll_reclaim_states_t *states = ll_zone_states(data->zone);
// Check if range is valid
for (size_t i = 0; i < len; i += LL_HUGE_COUNT) {
if (ll_reclaim_states_is_hard(states, frame + i)) {
error_report("range already reclaimed %lx-%lx", frame, frame + len);
return -1;
}
if (ll_reclaim_states_is_soft(states, frame + i)) {
error_report("range already unmapped %lx-%lx", frame, frame + len);
return -1;
}
}
hwaddr addr = (ll_zone_start_frame(data->zone) + frame) * LL_PAGE_SIZE;
unmap_range(data->dev, addr, len * LL_PAGE_SIZE);
for (size_t i = 0; i < len; i += LL_HUGE_COUNT) {
if (!ll_frame_states_hard_reclaim(states, frame + i, false)) {
error_report("invalid frame state");
return -1;
}
}
return 0;
}
static int32_t hard_reclaim_node(VirtIOLLFreeBalloon *dev, size_t node,
size_t target)
{
g_assert(target > 0);
size_t reclaimed = 0;
for (size_t i = 0; i < ZONE_PRIORITY_LEN; i++) {
ll_zone_type_t zone_type = zone_priority[i];
ll_zone_t *zone = ll_nodes_get_zone(dev->nodes, node, zone_type);
if (zone == NULL)
continue;
ll_zone_lock(zone);
ll_reclaim_states_t *states = ll_zone_states(zone);
struct ag_dev_zone data = {.dev = dev, .zone = zone};
aggregate_t ag = aggregate_start(reclaim_mapped_range_cb, &data);
for (; reclaimed < target; reclaimed++) {
llfree_result_t res = ll_zone_reclaim(zone, true);
if (llfree_is_ok(res)) {
if (res.reclaimed) {
// already unmapped
if (!ll_frame_states_hard_reclaim(states, res.frame, true))
error_report("invalid frame state");
} else {
// we have to unmap it
aggregate_next(&ag, res.frame, LL_HUGE_COUNT);
}
} else {
if (res.error != LLFREE_ERR_MEMORY)
error_report("failed llfree reclaim");
break;
}
}
aggregate_finish(&ag);
ll_zone_unlock(zone);
if (reclaimed >= target) {
break;
}
}
info_report("reclaimed %zu", reclaimed);
return reclaimed;
}
static int soft_reclaim_cb(void *ctx, uint64_t frame, size_t len)
{
struct ag_dev_zone *data = ctx;
ll_reclaim_states_t *states = ll_zone_states(data->zone);
// Check if range is valid
for (size_t i = 0; i < len; i += LL_HUGE_COUNT) {
if (ll_reclaim_states_is_soft(states, frame + i)) {
error_report("range already unmapped %lx-%lx", frame, frame + len);
return -1;
}
}
hwaddr addr = (ll_zone_start_frame(data->zone) + frame) * LL_PAGE_SIZE;
unmap_range(data->dev, addr, len * LL_PAGE_SIZE);
for (size_t i = 0; i < len; i += LL_HUGE_COUNT) {
if (!ll_frame_states_soft_reclaim(states, frame + i)) {
error_report("invalid frame state");
return -1;
}
}
return 0;
}
static int32_t ll_auto_soft_reclaim(VirtIOLLFreeBalloon *dev)
{
size_t unmapped_huge = 0;
for (size_t node = 0; node < ll_nodes_len(dev->nodes); node++) {
for (size_t i = 0; i < ZONE_PRIORITY_LEN; i++) {
ll_zone_type_t zid = zone_priority[i];
ll_zone_t *zone = ll_nodes_get_zone(dev->nodes, node, zid);
if (zone == NULL)
continue;
// allocate a chunk of frames, inflate them, and repeat until nomem
while (true) {
ll_zone_lock(zone);
// aggregate syscalls
struct ag_dev_zone data = {.dev = dev, .zone = zone};
aggregate_t ag = aggregate_start(soft_reclaim_cb, &data);
// find inflatable frames
bool nomem = false;
for (size_t i = 0; i < LLFREE_TREE_CHILDREN; i++) {
llfree_result_t res = ll_zone_reclaim(zone, false);
if (!llfree_is_ok(res)) {
if (res.error != LLFREE_ERR_MEMORY)
error_report("llfree unmap failed");
nomem = true;
break;
}
aggregate_next(&ag, res.frame, LL_HUGE_COUNT);
unmapped_huge += 1;
}
aggregate_finish(&ag);
ll_zone_unlock(zone);
if (nomem) {
break; // we were unable to allocate enough frames
}
// let others run
sched_yield();
}
}
}
if (unmapped_huge > 0) {
info_report("Auto unmap: %zu huge pages", unmapped_huge);
}
return unmapped_huge;
}
/*-----------------------------------------------------------------------------------------------
| LLFree-Balloon Deflation Operation Functions
-------------------------------------------------------------------------------------------------*/
static void map_range(VirtIOLLFreeBalloon *dev, hwaddr gpa, uint64_t size)
{
// find QEMUs matching memory section
MemoryRegionSection section =
memory_region_find(get_system_memory(), gpa, size);
// we registered as RamDiscardManager for the RAM memory region
// every section here should be part of this region and therefore we should
// see that the RamDiscardManager field has been set by us
if (section.mr == NULL)
g_assert(!"map: invalid section");
if (!memory_region_is_ram(section.mr) || memory_region_is_rom(section.mr) ||
memory_region_is_romd(section.mr))
g_assert(!"map: invalid section");
// Allocating host physical memory, in case of VFIO
// additionally create IOMMU mapping
void *addr =
memory_region_get_ram_ptr(section.mr) + section.offset_within_region;
void *host_addr = (void *)((uintptr_t)addr & ~(size - 1));
if (virtio_has_feature(dev->host_features, LL_BALLOON_F_VFIO)) {
notify_populate(dev, section.offset_within_region, size);
}
int ret = qemu_madvise(host_addr, size, MADV_POPULATE_WRITE);
if (ret != 0)
error_report("madvise failed with %d", ret);
memory_region_unref(section.mr);
}
static int32_t return_node(VirtIOLLFreeBalloon *dev, size_t node, size_t target)
{
g_assert(target > 0);
size_t returned = 0;
for (size_t i = ZONE_PRIORITY_LEN; i > 0; i--) {
ll_zone_t *zone =
ll_nodes_get_zone(dev->nodes, node, zone_priority[i - 1]);
if (zone == NULL)
continue;
ll_reclaim_states_t *states = ll_zone_states(zone);
g_assert(states != NULL);
ll_zone_lock(zone);
for (; returned < target; returned++) {
llfree_result_t res = ll_frame_states_return_next(states);
if (!llfree_is_ok(res))
break;
res = ll_zone_return(zone, res.frame);
if (!llfree_is_ok(res)) {
error_report("failed llfree return %u", res.error);
break;
}
}
ll_zone_unlock(zone);
if (returned >= target) {
break;
}
}
info_report("returned %zu", returned);
g_assert(returned == target);
return returned;
}
/*-----------------------------------------------------------------------------------------------
| LLFree-Balloon Classic Memory Ballooning Functions + Guest Pagecache Shrinking
-------------------------------------------------------------------------------------------------*/
static bool ll_try_shrink_pagecache(VirtIOLLFreeBalloon *dev,
uint32_t diff_huge_pages)
{
VirtIODevice *vdev = VIRTIO_DEVICE(dev);
uint32_t file_pages = 0;
for (size_t node = 0; node < ll_nodes_len(dev->nodes); node++) {
for (ll_zone_type_t zid = 0; zid < LL_ZONE_LEN; zid++) {
ll_zone_t *zone = ll_nodes_get_zone(dev->nodes, node, zid);
if (zone != NULL)
file_pages += ll_zone_file_pages(zone);
}
}
if (dev->shrink_pagecache == 0 &&
dev->pagecache_retries < LL_PAGECACHE_RETRIES && file_pages > 0) {
size_t target = MIN(diff_huge_pages * LL_HUGE_COUNT, file_pages);
dev->shrink_pagecache = target;
dev->pagecache_retries += 1;
virtio_notify_config(vdev);
return true;
}
return false;
}
static void ll_balloon_update_size(VirtIOLLFreeBalloon *dev,
bool shrink_pagecache)
{
// how much memory should be reclaimed, or given back if negative
int64_t diff_huge_pages =
qatomic_read(&dev->target_huge) - qatomic_read(&dev->actual_huge);
if (diff_huge_pages == 0)
return;
info_report("update balloon size %ld->%ld: %ld",
qatomic_read(&dev->actual_huge),
qatomic_read(&dev->target_huge), diff_huge_pages);
g_assert(dev->nodes != NULL);
if (diff_huge_pages > 0) {
// shrink VM
for (size_t node = 0;
node < ll_nodes_len(dev->nodes) && diff_huge_pages > 0; node++) {
size_t reclaimed = hard_reclaim_node(dev, node, diff_huge_pages);
qatomic_add(&dev->actual_huge, reclaimed);
diff_huge_pages -= reclaimed;
}
} else {
// grow VM
for (size_t node = 0;
node < ll_nodes_len(dev->nodes) && diff_huge_pages < 0; node++) {
size_t returned = return_node(dev, node, -diff_huge_pages);
qatomic_sub(&dev->actual_huge, returned);
diff_huge_pages += returned;
}
}
info_report("llfree_balloon_end %lu ns",
qemu_clock_get_ns(QEMU_CLOCK_REALTIME));
// decide whether to shrink the guests page cache
diff_huge_pages =
qatomic_read(&dev->target_huge) - qatomic_read(&dev->actual_huge);
if (diff_huge_pages > 0 && shrink_pagecache &&
virtio_has_feature(dev->host_features, LL_BALLOON_F_SHRINK_PAGECACHE)) {
if (ll_try_shrink_pagecache(dev, diff_huge_pages)) {
// Retry inflation later
timer_mod(dev->retry_llfree_timer,
qemu_clock_get_ns(QEMU_CLOCK_HOST) + LL_RETRY_INTERVAL);
}
}
}
static void ll_balloon_update_size_cb(void *opaque)
{
VirtIOLLFreeBalloon *dev = opaque;
ll_balloon_update_size(dev, true);
}
// target is rounded down to next aligned huge page
static void ll_balloon_resize(void *opaque, ram_addr_t target)
{
VirtIOLLFreeBalloon *dev = VIRTIO_LLFREE_BALLOON(opaque);
ram_addr_t vm_ram_size = get_current_ram_size();
if (target & (LL_HUGE_SIZE - 1)) {
warn_report("Target is not huge page (2MiB) aligned, will be rounded "
"down to next alignment\n");
}
if (target > vm_ram_size)
target = vm_ram_size;
qatomic_set_u64(&dev->target_huge, (vm_ram_size - target) >> LL_HUGE_SHIFT);
// we reset the retry counter on a new target value
dev->pagecache_retries = 0;
info_report("llfree_balloon_start %lu ns",
qemu_clock_get_ns(QEMU_CLOCK_REALTIME));
ll_balloon_update_size(dev, true);
}
/*-----------------------------------------------------------------------------------------------
| (Automatic) Scheduling Functions
-------------------------------------------------------------------------------------------------*/
static void ll_schedule_auto_reclaim(VirtIOLLFreeBalloon *dev)
{
timer_mod(dev->auto_mode_timer,
qemu_clock_get_ns(QEMU_CLOCK_HOST) + LL_RETRY_INTERVAL);
}
static void ll_balloon_auto_reclaim(void *opaque)
{
VirtIOLLFreeBalloon *dev = opaque;
ll_auto_soft_reclaim(dev);
// and repeat with configured time interval
ll_schedule_auto_reclaim(dev);
}
/*-----------------------------------------------------------------------------------------------
| VirtQueue Handler Functions
-------------------------------------------------------------------------------------------------*/
// scheduled in main event loop
static void handle_llfree_zone_info(VirtIODevice *vdev, VirtQueue *vq)
{
VirtIOLLFreeBalloon *dev = VIRTIO_LLFREE_BALLOON(vdev);
VirtQueueElement *elem = virtqueue_pop(vq, sizeof(VirtQueueElement));
if (!elem) {
warn_report("%s: No element in queue (null pointer)", __func__);
return;
}
void *buffer = g_malloc(ll_zone_buffer_size());
iov_to_buf(elem->out_sg, elem->out_num, 0, buffer, ll_zone_buffer_size());
ll_nodes_add_zone(dev->nodes, buffer);
virtqueue_push(vq, elem, 0);
virtio_notify(vdev, vq);
g_free(elem);
return;
}
struct install_range_ctx {
VirtIOLLFreeBalloon *dev;
ll_zone_t *zone;
};
static int install_range_cb(void *ctx, uint64_t frame, size_t len)
{
struct install_range_ctx *data = ctx;
g_assert(frame % LL_HUGE_COUNT == 0);
g_assert(frame < ll_zone_frames(data->zone));
hwaddr gpa_addr = (ll_zone_start_frame(data->zone) + frame) * LL_PAGE_SIZE;
map_range(data->dev, gpa_addr, len * LL_PAGE_SIZE);
// Update llfree state
for (size_t i = 0; i < len; i += LL_HUGE_COUNT) {
llfree_result_t res = ll_zone_install(data->zone, frame + i);
if (!llfree_is_ok(res)) {
error_report("Failed install %ld", frame + i);
return -1;
}
}
return 0;
}
// Handle request from guest to populate the given memory range
static void handle_install_request(VirtIODevice *vdev, VirtQueue *vq)
{
VirtIOLLFreeBalloon *dev = VIRTIO_LLFREE_BALLOON(vdev);
VirtQueueElement *elem = virtqueue_pop(vq, sizeof(VirtQueueElement));
if (!elem)
return;
ll_install_info_t info;
iov_to_buf(elem->out_sg, elem->out_num, 0, &info,
sizeof(ll_install_info_t));
// calculate corresponding huge frame
uint64_t huge_frame = align_down(info.frame, LL_HUGE_COUNT);
ll_zone_t *zone = ll_nodes_get_zone(dev->nodes, info.node, info.zone);
ll_zone_lock(zone);
// already populated
if (!ll_zone_is_evicted(zone, huge_frame)) {
// check host state
g_assert(
ll_reclaim_states_is_installed(ll_zone_states(zone), huge_frame));
goto finish;
}
// check host state
g_assert(ll_reclaim_states_is_soft(ll_zone_states(zone), huge_frame));
struct install_range_ctx ctx = {.zone = zone, .dev = dev};
#if 0
// deflate whole tree
aggregate_t ag = aggregate_start(install_range_cb, &ctx);
uint64_t tree_offset = align_down(huge_frame, LLFREE_TREE_SIZE);
for (size_t child = 0; child < LLFREE_TREE_CHILDREN; child++) {
uint64_t frame = tree_offset + child * LLFREE_CHILD_SIZE;
if (ll_frame_states_install(ll_zone_states(zone), frame)) {
aggregate_next(&ag, frame, LL_HUGE_COUNT);
}
}
aggregate_finish(&ag);
#else
g_assert(ll_frame_states_install(ll_zone_states(zone), huge_frame));
install_range_cb(&ctx, huge_frame, LL_HUGE_COUNT);
#endif
finish:
ll_zone_unlock(zone);
virtqueue_push(vq, elem, 0);
virtio_notify(vdev, vq);
g_free(elem);
}
// scheduled in main event loop
static void handle_update_request(VirtIODevice *vdev, VirtQueue *vq)
{
VirtIOLLFreeBalloon *dev = VIRTIO_LLFREE_BALLOON(vdev);
VirtQueueElement *elem = virtqueue_pop(vq, sizeof(VirtQueueElement));
if (!elem) {
warn_report("No element in llfree_request_vq (null pointer) \n");
return;
}
ll_notification_t guest_req;
iov_to_buf(elem->out_sg, elem->out_num, 0, &guest_req,
sizeof(ll_notification_t));
virtqueue_push(vq, elem, 0);
virtio_notify(vdev, vq);
g_free(elem);
switch (guest_req) {
case PAGECACHE_DROPPED:
ll_balloon_update_size(dev, false);
break;
default:
break;
}
}
/*-----------------------------------------------------------------------------------------------
| RamDiscardManager Functions, Part 2
| Implementation is largely taken directly from virtio-mem
-------------------------------------------------------------------------------------------------*/
typedef int (*ll_wrapper_cb)(MemoryRegionSection *s, void *opaque);
struct ll_wrapper_data {
size_t start_frame;
MemoryRegionSection *section;
ll_wrapper_cb cb;
void *opaque;
};
static int ll_section_wrapper(void *ctx, uint64_t frame, size_t len)
{
struct ll_wrapper_data *data = ctx;
MemoryRegionSection tmp = *data->section;
hwaddr offset = (data->start_frame + frame) * LL_PAGE_SIZE;
size_t size = len * LL_PAGE_SIZE;
if (intersect_memory_section(&tmp, offset, size)) {
int ret = (data->cb)(&tmp, data->opaque);
if (ret < 0)
error_report("rdl notify failed %lx-%lx", offset, offset + size);
return ret;
}
return 0;
}
static int ll_for_each_section(const VirtIOLLFreeBalloon *dev,
MemoryRegionSection *s, ll_wrapper_cb cb,
void *opaque, bool installed)
{
if (ll_nodes_len(dev->nodes) == 0) {
// Not initialized: just map all!
struct ll_wrapper_data ctx = {
.start_frame = s->offset_within_address_space / LL_PAGE_SIZE,
.section = s,
.cb = cb,
.opaque = opaque,
};
return ll_section_wrapper(&ctx, 0, int128_get64(s->size));
}
for (size_t node = 0; node < ll_nodes_len(dev->nodes); node++) {
for (ll_zone_type_t zid = 0; zid < LL_ZONE_LEN; zid++) {
ll_zone_t *zone = ll_nodes_get_zone(dev->nodes, node, zid);
if (zone == NULL)
continue;
ll_zone_lock(zone);
struct ll_wrapper_data ctx = {
.start_frame = ll_zone_start_frame(zone),
.section = s,
.cb = cb,
.opaque = opaque,
};
aggregate_t ag = aggregate_start(ll_section_wrapper, &ctx);
for (size_t f = 0; f < ll_zone_frames(zone); f += LL_HUGE_COUNT) {
if (ll_reclaim_states_is_installed(ll_zone_states(zone), f) ==
installed) {
int ret = aggregate_next(&ag, f, LL_HUGE_COUNT);
if (ret < 0) {
ll_zone_unlock(zone);
return ret;
}
}
}
int ret = aggregate_finish(&ag);
ll_zone_unlock(zone);
return ret;
}
}
return 0;
}
static uint64_t ll_rdm_get_min_granularity(const RamDiscardManager *rdm,
const MemoryRegion *mr)
{
return LL_HUGE_SIZE;
}
static bool ll_rdm_is_populated(const RamDiscardManager *rdm,
const MemoryRegionSection *s)
{
VirtIOLLFreeBalloon *dev = VIRTIO_LLFREE_BALLOON(rdm);
uint64_t start = s->offset_within_region / LL_PAGE_SIZE;
uint64_t end = DIV_ROUND_UP(s->offset_within_region + int128_get64(s->size),
LL_PAGE_SIZE);
uint64_t len = end - start;
for (size_t node = 0; node < ll_nodes_len(dev->nodes); node++) {
for (ll_zone_type_t zid = 0; zid < LL_ZONE_LEN; zid++) {
ll_zone_t *zone = ll_nodes_get_zone(dev->nodes, node, zid);
if (zone == NULL)
continue;
if (ll_zone_start_frame(zone) <= start &&
len <= ll_zone_frames(zone)) {
ll_reclaim_states_t *states = ll_zone_states(zone);
for (size_t i = 0; i < len; i++)
if (!ll_reclaim_states_is_installed(states, start + i))
return false;
return true;
}
}
}
error_report("Zone not found for region %lu", start);
return false;
}
static int ll_rdm_replay_populated(const RamDiscardManager *rdm,
MemoryRegionSection *section,
ReplayRamPopulate replay_fn, void *opaque)
{
VirtIOLLFreeBalloon *dev = VIRTIO_LLFREE_BALLOON(rdm);
return ll_for_each_section(dev, section, replay_fn, opaque, true);
}
struct replay_discard_data {
ReplayRamDiscard replay_fn;
void *opaque;
};
static int ll_replay_discard_cb(MemoryRegionSection *section, void *opaque)
{
struct replay_discard_data *data = opaque;
(data->replay_fn)(section, data->opaque);
return 0;
}
static void ll_rdm_replay_discarded(const RamDiscardManager *rdm,
MemoryRegionSection *section,
ReplayRamDiscard replay_fn, void *opaque)
{
VirtIOLLFreeBalloon *dev = VIRTIO_LLFREE_BALLOON(rdm);
struct replay_discard_data data = {.replay_fn = replay_fn,
.opaque = opaque};
ll_for_each_section(dev, section, ll_replay_discard_cb, &data, false);
}
struct ll_notify_populate_data {
NotifyRamPopulate cb;
RamDiscardListener *rdl;
};
static int ll_notify_populate_cb(MemoryRegionSection *s, void *opaque)
{
struct ll_notify_populate_data *data = opaque;
int ret = (data->cb)(data->rdl, s);
if (ret < 0)
error_report("rdl notify failed %lx-%lx",
s->offset_within_address_space,
s->offset_within_address_space + int128_get64(s->size));
return ret;
}
static void ll_rdm_register_listener(RamDiscardManager *rdm,
RamDiscardListener *rdl,
MemoryRegionSection *s)
{
VirtIOLLFreeBalloon *dev = VIRTIO_LLFREE_BALLOON(rdm);
rdl->section = memory_region_section_new_copy(s);
QLIST_INSERT_HEAD(&dev->rdl_list, rdl, next);
struct ll_notify_populate_data data = {
.cb = rdl->notify_populate,
.rdl = rdl,
};
int ret = ll_for_each_section(dev, rdl->section, ll_notify_populate_cb,
&data, true);
if (ret < 0) {
error_report("%s: Replaying non inflated ranges failed: %s", __func__,
strerror(-ret));
}
virtio_add_feature((uint64_t *)&dev->host_features, LL_BALLOON_F_VFIO);
}
struct ll_notify_discard_data {
NotifyRamDiscard cb;
RamDiscardListener *rdl;
};
static int ll_notify_discard_cb(MemoryRegionSection *s, void *opaque)
{
struct ll_notify_discard_data *data = opaque;
(data->cb)(data->rdl, s);
return 0;
}
static void ll_rdm_unregister_listener(RamDiscardManager *rdm,
RamDiscardListener *rdl)
{
VirtIOLLFreeBalloon *dev = VIRTIO_LLFREE_BALLOON(rdm);
if (rdl->double_discard_supported) {
rdl->notify_discard(rdl, rdl->section);
} else {
struct ll_notify_discard_data data = {
.cb = rdl->notify_discard,
.rdl = rdl,
};
ll_for_each_section(dev, rdl->section, ll_notify_discard_cb, &data,
true);
}
memory_region_section_free_copy(rdl->section);
rdl->section = NULL;
QLIST_REMOVE(rdl, next);
if (QLIST_EMPTY(&dev->rdl_list))
virtio_clear_feature((uint64_t *)&dev->host_features,
LL_BALLOON_F_VFIO);
}
/*-----------------------------------------------------------------------------------------------
| Functions for managing iothread pool backend for multi-threaded auto-deflate
| taken from virtio-blk.c, slightly modified
-------------------------------------------------------------------------------------------------*/
static void balloon_ioeventfd_attach(VirtIOLLFreeBalloon *dev)
{
VirtIODevice *vdev = VIRTIO_DEVICE(dev);
for (uint16_t i = 0; i < dev->num_queues; i++) {
VirtQueue *vq = virtio_get_queue(vdev, i);
virtio_queue_aio_attach_host_notifier(vq, dev->vq_aio_context[i]);
}
}
/* Context: BQL held */