-
-
Notifications
You must be signed in to change notification settings - Fork 605
/
mmu.cc
1923 lines (1722 loc) · 62.4 KB
/
mmu.cc
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
/*
* Copyright (C) 2013 Cloudius Systems, Ltd.
*
* This work is open source software, licensed under the terms of the
* BSD license as described in the LICENSE file in the top-level directory.
*/
#include <osv/mmu.hh>
#include <osv/mempool.hh>
#include "processor.hh"
#include <osv/debug.hh>
#include "exceptions.hh"
#include <boost/format.hpp>
#include <string.h>
#include <iterator>
#include "libc/signal.hh"
#include <osv/align.hh>
#include <osv/ilog2.hh>
#include <osv/prio.hh>
#include <safe-ptr.hh>
#include "fs/vfs/vfs.h"
#include <osv/error.h>
#include <osv/trace.hh>
#include <stack>
#include "java/jvm/jvm_balloon.hh"
#include <fs/fs.hh>
#include <osv/file.h>
#include "dump.hh"
#include <osv/rcu.hh>
#include <osv/rwlock.h>
#include <numeric>
extern void* elf_start;
extern size_t elf_size;
namespace {
typedef boost::format fmt;
}
extern const char text_start[], text_end[];
namespace mmu {
namespace bi = boost::intrusive;
class vma_compare {
public:
bool operator ()(const vma& a, const vma& b) const {
return a.addr() < b.addr();
}
};
typedef boost::intrusive::set<vma,
bi::compare<vma_compare>,
bi::member_hook<vma,
bi::set_member_hook<>,
&vma::_vma_list_hook>,
bi::optimize_size<true>
> vma_list_base;
struct vma_list_type : vma_list_base {
vma_list_type() {
// insert markers for the edges of allocatable area
// simplifies searches
insert(*new anon_vma(addr_range(0, 0), 0, 0));
uintptr_t e = 0x800000000000;
insert(*new anon_vma(addr_range(e, e), 0, 0));
}
};
__attribute__((init_priority((int)init_prio::vma_list)))
vma_list_type vma_list;
// protects vma list and page table modifications.
// anything that may add, remove, split vma, zaps pte or changes pte permission
// should hold the lock for write
rwlock_t vma_list_mutex;
// A mutex serializing modifications to the high part of the page table
// (linear map, etc.) which are not part of vma_list.
mutex page_table_high_mutex;
// 1's for the bits provided by the pte for this level
// 0's for the bits provided by the virtual address for this level
phys pte_level_mask(unsigned level)
{
auto shift = level * ilog2_roundup_constexpr(pte_per_page)
+ ilog2_roundup_constexpr(page_size);
return ~((phys(1) << shift) - 1);
}
void* phys_to_virt(phys pa)
{
// The ELF is mapped 1:1
void* phys_addr = reinterpret_cast<void*>(pa);
if ((phys_addr >= elf_start) && (phys_addr < elf_start + elf_size)) {
return phys_addr;
}
return phys_mem + pa;
}
phys virt_to_phys_pt(void* virt);
phys virt_to_phys(void *virt)
{
// The ELF is mapped 1:1
if ((virt >= elf_start) && (virt < elf_start + elf_size)) {
return reinterpret_cast<phys>(virt);
}
#if CONF_debug_memory
if (virt > debug_base) {
return virt_to_phys_pt(virt);
}
#endif
// For now, only allow non-mmaped areas. Later, we can either
// bounce such addresses, or lock them in memory and translate
assert(virt >= phys_mem);
return reinterpret_cast<uintptr_t>(virt) & (mem_area_size - 1);
}
template <int N, typename MakePTE>
phys allocate_intermediate_level(MakePTE make_pte)
{
phys pt_page = virt_to_phys(memory::alloc_page());
// since the pt is not yet mapped, we don't need to use hw_ptep
pt_element<N>* pt = phys_cast<pt_element<N>>(pt_page);
for (auto i = 0; i < pte_per_page; ++i) {
pt[i] = make_pte(i);
}
return pt_page;
}
template<int N>
void allocate_intermediate_level(hw_ptep<N> ptep, pt_element<N> org)
{
phys pt_page = allocate_intermediate_level<N>([org](int i) {
auto tmp = org;
phys addend = phys(i) << page_size_shift;
tmp.set_addr(tmp.addr() | addend, false);
return tmp;
});
ptep.write(make_intermediate_pte(ptep, pt_page));
}
template<int N>
void allocate_intermediate_level(hw_ptep<N> ptep)
{
phys pt_page = allocate_intermediate_level<N>([](int i) {
return make_empty_pte<N>();
});
if (!ptep.compare_exchange(make_empty_pte<N>(), make_intermediate_pte(ptep, pt_page))) {
memory::free_page(phys_to_virt(pt_page));
}
}
// only 4k can be cow for now
pt_element<0> pte_mark_cow(pt_element<0> pte, bool cow)
{
if (cow) {
pte.set_writable(false);
}
pte.set_sw_bit(pte_cow, cow);
return pte;
}
template<int N>
bool change_perm(hw_ptep<N> ptep, unsigned int perm)
{
static_assert(pt_level_traits<N>::leaf_capable::value, "non leaf pte");
pt_element<N> pte = ptep.read();
unsigned int old = (pte.valid() ? perm_read : 0) |
(pte.writable() ? perm_write : 0) |
(pte.executable() ? perm_exec : 0);
if (pte_is_cow(pte)) {
perm &= ~perm_write;
}
// Note: in x86, if the present bit (0x1) is off, not only read is
// disallowed, but also write and exec. So in mprotect, if any
// permission is requested, we must also grant read permission.
// Linux does this too.
pte.set_valid(true);
pte.set_writable(perm & perm_write);
pte.set_executable(perm & perm_exec);
pte.set_rsvd_bit(0, !perm);
ptep.write(pte);
return old & ~perm;
}
template<int N>
void split_large_page(hw_ptep<N> ptep)
{
}
template<>
void split_large_page(hw_ptep<1> ptep)
{
pt_element<1> pte_orig = ptep.read();
pte_orig.set_large(false);
allocate_intermediate_level(ptep, pte_orig);
}
struct page_allocator {
virtual bool map(uintptr_t offset, hw_ptep<0> ptep, pt_element<0> pte, bool write) = 0;
virtual bool map(uintptr_t offset, hw_ptep<1> ptep, pt_element<1> pte, bool write) = 0;
virtual bool unmap(void *addr, uintptr_t offset, hw_ptep<0> ptep) = 0;
virtual bool unmap(void *addr, uintptr_t offset, hw_ptep<1> ptep) = 0;
virtual ~page_allocator() {}
};
unsigned long all_vmas_size()
{
SCOPE_LOCK(vma_list_mutex.for_read());
return std::accumulate(vma_list.begin(), vma_list.end(), size_t(0), [](size_t s, vma& v) { return s + v.size(); });
}
void clamp(uintptr_t& vstart1, uintptr_t& vend1,
uintptr_t min, size_t max, size_t slop)
{
vstart1 &= ~(slop - 1);
vend1 |= (slop - 1);
vstart1 = std::max(vstart1, min);
vend1 = std::min(vend1, max);
}
constexpr unsigned pt_index(uintptr_t virt, unsigned level)
{
return pt_index(reinterpret_cast<void*>(virt), level);
}
unsigned nr_page_sizes = 2; // FIXME: detect 1GB pages
void set_nr_page_sizes(unsigned nr)
{
nr_page_sizes = nr;
}
enum class allocate_intermediate_opt : bool {no = true, yes = false};
enum class skip_empty_opt : bool {no = true, yes = false};
enum class descend_opt : bool {no = true, yes = false};
enum class once_opt : bool {no = true, yes = false};
enum class split_opt : bool {no = true, yes = false};
enum class account_opt: bool {no = true, yes = false};
// Parameter descriptions:
// Allocate - if "yes" page walker will allocate intermediate page if one is missing
// otherwise it will skip to next address.
// Skip - if "yes" page walker will not call leaf page handler on an empty pte.
// Descend - if "yes" page walker will descend one level if large page range is mapped
// by small pages, otherwise it will call huge_page() on intermediate small pte
// Once - if "yes" page walker will not loop over range of pages
// Split - If "yes" page walker will split huge pages to small pages while walking
template<allocate_intermediate_opt Allocate, skip_empty_opt Skip = skip_empty_opt::yes,
descend_opt Descend = descend_opt::yes, once_opt Once = once_opt::no, split_opt Split = split_opt::yes>
class page_table_operation {
protected:
template<typename T> bool opt2bool(T v) { return v == T::yes; }
public:
bool allocate_intermediate(void) { return opt2bool(Allocate); }
bool skip_empty(void) { return opt2bool(Skip); }
bool descend(void) { return opt2bool(Descend); }
bool once(void) { return opt2bool(Once); }
template<int N>
bool split_large(hw_ptep<N> ptep, int level) { return opt2bool(Split); }
unsigned nr_page_sizes(void) { return mmu::nr_page_sizes; }
template<int N>
pt_element<N> ptep_read(hw_ptep<N> ptep) { return ptep.read(); }
// page() function is called on leaf ptes. Each page table operation
// have to provide its own version.
template<int N>
bool page(hw_ptep<N> ptep, uintptr_t offset) { assert(0); }
// if huge page range is covered by smaller pages some page table operations
// may want to have special handling for level 1 non leaf pte. intermediate_page_pre()
// is called just before descending into the next level, while intermediate_page_post()
// is called just after.
void intermediate_page_pre(hw_ptep<1> ptep, uintptr_t offset) {}
void intermediate_page_post(hw_ptep<1> ptep, uintptr_t offset) {}
// Page walker calls page() when it a whole leaf page need to be handled, but if it
// has 2M pte and less then 2M of virt memory to operate upon and split is disabled
// sup_page is called instead. So if you are here it means that page walker encountered
// 2M pte and page table operation wants to do something special with sub-region of it
// since it disabled splitting.
void sub_page(hw_ptep<1> ptep, int level, uintptr_t offset) { return; }
};
template<typename PageOps, int N>
static inline typename std::enable_if<pt_level_traits<N>::large_capable::value>::type
sub_page(PageOps& pops, hw_ptep<N> ptep, int level, uintptr_t offset)
{
pops.sub_page(ptep, level, offset);
}
template<typename PageOps, int N>
static inline typename std::enable_if<!pt_level_traits<N>::large_capable::value>::type
sub_page(PageOps& pops, hw_ptep<N> ptep, int level, uintptr_t offset)
{
}
template<typename PageOps, int N>
static inline typename std::enable_if<pt_level_traits<N>::leaf_capable::value, bool>::type
page(PageOps& pops, hw_ptep<N> ptep, uintptr_t offset)
{
return pops.page(ptep, offset);
}
template<typename PageOps, int N>
static inline typename std::enable_if<!pt_level_traits<N>::leaf_capable::value, bool>::type
page(PageOps& pops, hw_ptep<N> ptep, uintptr_t offset)
{
assert(0);
return false;
}
template<typename PageOps, int N>
static inline typename std::enable_if<pt_level_traits<N>::large_capable::value>::type
intermediate_page_pre(PageOps& pops, hw_ptep<N> ptep, uintptr_t offset)
{
pops.intermediate_page_pre(ptep, offset);
}
template<typename PageOps, int N>
static inline typename std::enable_if<!pt_level_traits<N>::large_capable::value>::type
intermediate_page_pre(PageOps& pops, hw_ptep<N> ptep, uintptr_t offset)
{
}
template<typename PageOps, int N>
static inline typename std::enable_if<pt_level_traits<N>::large_capable::value>::type
intermediate_page_post(PageOps& pops, hw_ptep<N> ptep, uintptr_t offset)
{
pops.intermediate_page_post(ptep, offset);
}
template<typename PageOps, int N>
static inline typename std::enable_if<!pt_level_traits<N>::large_capable::value>::type
intermediate_page_post(PageOps& pops, hw_ptep<N> ptep, uintptr_t offset)
{
}
template<typename PageOp, int ParentLevel> class map_level;
template<typename PageOp>
void map_range(uintptr_t vma_start, uintptr_t vstart, size_t size, PageOp& page_mapper, size_t slop = page_size)
{
map_level<PageOp, 4> pt_mapper(vma_start, vstart, size, page_mapper, slop);
pt_mapper(hw_ptep<4>::force(mmu::get_root_pt(vstart)));
}
template<typename PageOp, int ParentLevel> class map_level {
private:
uintptr_t vma_start;
uintptr_t vcur;
uintptr_t vend;
size_t slop;
PageOp& page_mapper;
static constexpr int level = ParentLevel - 1;
friend void map_range<PageOp>(uintptr_t, uintptr_t, size_t, PageOp&, size_t);
friend class map_level<PageOp, ParentLevel + 1>;
map_level(uintptr_t vma_start, uintptr_t vcur, size_t size, PageOp& page_mapper, size_t slop) :
vma_start(vma_start), vcur(vcur), vend(vcur + size - 1), slop(slop), page_mapper(page_mapper) {}
pt_element<ParentLevel> read(const hw_ptep<ParentLevel>& ptep) const {
return page_mapper.ptep_read(ptep);
}
pt_element<level> read(const hw_ptep<level>& ptep) const {
return page_mapper.ptep_read(ptep);
}
hw_ptep<level> follow(hw_ptep<ParentLevel> ptep)
{
return hw_ptep<level>::force(phys_cast<pt_element<level>>(read(ptep).next_pt_addr()));
}
bool skip_pte(hw_ptep<level> ptep) {
return page_mapper.skip_empty() && read(ptep).empty();
}
bool descend(hw_ptep<level> ptep) {
return page_mapper.descend() && !read(ptep).empty() && !read(ptep).large();
}
template<int N>
typename std::enable_if<N == 0>::type
map_range(uintptr_t vcur, size_t size, PageOp& page_mapper, size_t slop,
hw_ptep<N> ptep, uintptr_t base_virt)
{
}
template<int N>
typename std::enable_if<N == level && N != 0>::type
map_range(uintptr_t vcur, size_t size, PageOp& page_mapper, size_t slop,
hw_ptep<N> ptep, uintptr_t base_virt)
{
map_level<PageOp, level> pt_mapper(vma_start, vcur, size, page_mapper, slop);
pt_mapper(ptep, base_virt);
}
void operator()(hw_ptep<ParentLevel> parent, uintptr_t base_virt = 0) {
if (!read(parent).valid()) {
if (!page_mapper.allocate_intermediate()) {
return;
}
allocate_intermediate_level(parent);
} else if (read(parent).large()) {
if (page_mapper.split_large(parent, ParentLevel)) {
// We're trying to change a small page out of a huge page (or
// in the future, potentially also 2 MB page out of a 1 GB),
// so we need to first split the large page into smaller pages.
// Our implementation ensures that it is ok to free pieces of a
// alloc_huge_page() with free_page(), so it is safe to do such a
// split.
split_large_page(parent);
} else {
// If page_mapper does not want to split, let it handle subpage by itself
sub_page(page_mapper, parent, ParentLevel, base_virt - vma_start);
return;
}
}
auto pt = follow(parent);
phys step = phys(1) << (page_size_shift + level * pte_per_page_shift);
auto idx = pt_index(vcur, level);
auto eidx = pt_index(vend, level);
base_virt += idx * step;
base_virt = (int64_t(base_virt) << 16) >> 16; // extend 47th bit
do {
auto ptep = pt.at(idx);
uintptr_t vstart1 = vcur, vend1 = vend;
clamp(vstart1, vend1, base_virt, base_virt + step - 1, slop);
if (unsigned(level) < page_mapper.nr_page_sizes() && vstart1 == base_virt && vend1 == base_virt + step - 1) {
uintptr_t offset = base_virt - vma_start;
if (level) {
if (!skip_pte(ptep)) {
if (descend(ptep) || !page(page_mapper, ptep, offset)) {
intermediate_page_pre(page_mapper, ptep, offset);
map_range(vstart1, vend1 - vstart1 + 1, page_mapper, slop, ptep, base_virt);
intermediate_page_post(page_mapper, ptep, offset);
}
}
} else {
if (!skip_pte(ptep)) {
page(page_mapper, ptep, offset);
}
}
} else {
map_range(vstart1, vend1 - vstart1 + 1, page_mapper, slop, ptep, base_virt);
}
base_virt += step;
++idx;
} while(!page_mapper.once() && idx <= eidx);
}
};
class linear_page_mapper :
public page_table_operation<allocate_intermediate_opt::yes, skip_empty_opt::no, descend_opt::no> {
phys start;
phys end;
mattr mem_attr;
public:
linear_page_mapper(phys start, size_t size, mattr mem_attr = mattr_default) :
start(start), end(start + size), mem_attr(mem_attr) {}
template<int N>
bool page(hw_ptep<N> ptep, uintptr_t offset) {
phys addr = start + offset;
assert(addr < end);
ptep.write(make_leaf_pte(ptep, addr, mmu::perm_rwx, mem_attr));
return true;
}
};
template<allocate_intermediate_opt Allocate, skip_empty_opt Skip = skip_empty_opt::yes,
account_opt Account = account_opt::no>
class vma_operation :
public page_table_operation<Allocate, Skip, descend_opt::yes, once_opt::no, split_opt::yes> {
public:
// returns true if tlb flush is needed after address range processing is completed.
bool tlb_flush_needed(void) { return false; }
// this function is called at the very end of operate_range(). vma_operation may do
// whatever cleanup is needed here.
void finalize(void) { return; }
ulong account_results(void) { return _total_operated; }
void account(size_t size) { if (this->opt2bool(Account)) _total_operated += size; }
private:
// We don't need locking because each walk will create its own instance, so
// while two instances can operate over the same linear address (therefore
// all the cmpxcghs), the same instance will go linearly over its duty.
ulong _total_operated = 0;
};
/*
* populate() populates the page table with the entries it is (assumed to be)
* missing to span the given virtual-memory address range, and then pre-fills
* (using the given fill function) these pages and sets their permissions to
* the given ones. This is part of the mmap implementation.
*/
template <account_opt T = account_opt::no>
class populate : public vma_operation<allocate_intermediate_opt::yes, skip_empty_opt::no, T> {
private:
page_allocator* _page_provider;
unsigned int _perm;
bool _write;
bool _map_dirty;
template<int N>
bool skip(pt_element<N> pte) {
if (pte.empty()) {
return false;
}
return !_write || pte.writable();
}
template<int N>
inline pt_element<N> dirty(pt_element<N> pte) {
pte.set_dirty(_map_dirty || _write);
return pte;
}
public:
populate(page_allocator* pops, unsigned int perm, bool write = false, bool map_dirty = true) :
_page_provider(pops), _perm(perm), _write(write), _map_dirty(map_dirty) { }
template<int N>
bool page(hw_ptep<N> ptep, uintptr_t offset) {
auto pte = ptep.read();
if (skip(pte)) {
return true;
}
pte = dirty(make_leaf_pte(ptep, 0, _perm));
try {
if (_page_provider->map(offset, ptep, pte, _write)) {
this->account(pt_level_traits<N>::size::value);
}
} catch(std::exception&) {
return false;
}
return true;
}
};
template <account_opt Account = account_opt::no>
class populate_small : public populate<Account> {
public:
populate_small(page_allocator* pops, unsigned int perm, bool write = false, bool map_dirty = true) :
populate<Account>(pops, perm, write, map_dirty) { }
template<int N>
bool page(hw_ptep<N> ptep, uintptr_t offset) {
assert(!pt_level_traits<N>::large_capable::value);
return populate<Account>::page(ptep, offset);
}
unsigned nr_page_sizes(void) { return 1; }
};
class splithugepages : public vma_operation<allocate_intermediate_opt::no, skip_empty_opt::yes, account_opt::no> {
public:
splithugepages() { }
template<int N>
bool page(hw_ptep<N> ptep, uintptr_t offset)
{
assert(!pt_level_traits<N>::large_capable::value);
return true;
}
unsigned nr_page_sizes(void) { return 1; }
};
struct tlb_gather {
static constexpr size_t max_pages = 20;
struct tlb_page {
void* addr;
size_t size;
};
size_t nr_pages = 0;
tlb_page pages[max_pages];
bool push(void* addr, size_t size) {
bool flushed = false;
if (nr_pages == max_pages) {
flush();
flushed = true;
}
pages[nr_pages++] = { addr, size };
return flushed;
}
bool flush() {
if (!nr_pages) {
return false;
}
mmu::flush_tlb_all();
for (auto i = 0u; i < nr_pages; ++i) {
auto&& tp = pages[i];
if (tp.size == page_size) {
memory::free_page(tp.addr);
} else {
memory::free_huge_page(tp.addr, tp.size);
}
}
nr_pages = 0;
return true;
}
};
/*
* Undo the operation of populate(), freeing memory allocated by populate()
* and marking the pages non-present.
*/
template <account_opt T = account_opt::no>
class unpopulate : public vma_operation<allocate_intermediate_opt::no, skip_empty_opt::yes, T> {
private:
tlb_gather _tlb_gather;
page_allocator* _pops;
bool do_flush = false;
public:
unpopulate(page_allocator* pops) : _pops(pops) {}
template<int N>
bool page(hw_ptep<N> ptep, uintptr_t offset) {
void* addr = phys_to_virt(ptep.read().addr());
size_t size = pt_level_traits<N>::size::value;
// Note: we free the page even if it is already marked "not present".
// evacuate() makes sure we are only called for allocated pages, and
// not-present may only mean mprotect(PROT_NONE).
if (_pops->unmap(addr, offset, ptep)) {
do_flush = !_tlb_gather.push(addr, size);
} else {
do_flush = true;
}
this->account(size);
return true;
}
void intermediate_page_post(hw_ptep<1> ptep, uintptr_t offset) {
osv::rcu_defer([](void *page) { memory::free_page(page); }, phys_to_virt(ptep.read().addr()));
ptep.write(make_empty_pte<1>());
}
bool tlb_flush_needed(void) {
return !_tlb_gather.flush() && do_flush;
}
void finalize(void) {}
};
class protection : public vma_operation<allocate_intermediate_opt::no, skip_empty_opt::yes> {
private:
unsigned int perm;
bool do_flush;
public:
protection(unsigned int perm) : perm(perm), do_flush(false) { }
template<int N>
bool page(hw_ptep<N> ptep, uintptr_t offset) {
do_flush |= change_perm(ptep, perm);
return true;
}
bool tlb_flush_needed(void) {return do_flush;}
};
template <typename T, account_opt Account = account_opt::no>
class dirty_cleaner : public vma_operation<allocate_intermediate_opt::no, skip_empty_opt::yes, Account> {
private:
bool do_flush;
T handler;
public:
dirty_cleaner(T handler) : do_flush(false), handler(handler) {}
template<int N>
bool page(hw_ptep<N> ptep, uintptr_t offset) {
pt_element<N> pte = ptep.read();
if (!pte.dirty()) {
return true;
}
do_flush |= true;
pte.set_dirty(false);
ptep.write(pte);
handler(ptep.read().addr(), offset, pt_level_traits<N>::size::value);
return true;
}
bool tlb_flush_needed(void) {return do_flush;}
void finalize() {
handler.finalize();
}
};
class dirty_page_sync {
friend dirty_cleaner<dirty_page_sync, account_opt::yes>;
friend file_vma;
private:
file *_file;
f_offset _offset;
uint64_t _size;
struct elm {
iovec iov;
off_t offset;
};
std::stack<elm> queue;
dirty_page_sync(file *file, f_offset offset, uint64_t size) : _file(file), _offset(offset), _size(size) {}
void operator()(phys addr, uintptr_t offset, size_t size) {
off_t off = _offset + offset;
size_t len = std::min(size, _size - off);
queue.push(elm{{phys_to_virt(addr), len}, off});
}
void finalize() {
while(!queue.empty()) {
elm w = queue.top();
uio data{&w.iov, 1, w.offset, ssize_t(w.iov.iov_len), UIO_WRITE};
int error = _file->write(&data, FOF_OFFSET);
if (error) {
throw make_error(error);
}
queue.pop();
}
}
};
class virt_to_phys_map :
public page_table_operation<allocate_intermediate_opt::no, skip_empty_opt::yes,
descend_opt::yes, once_opt::yes, split_opt::no> {
private:
uintptr_t v;
phys result;
static constexpr phys null = ~0ull;
virt_to_phys_map(uintptr_t v) : v(v), result(null) {}
phys addr(void) {
assert(result != null);
return result;
}
public:
friend phys virt_to_phys_pt(void* virt);
template<int N>
bool page(hw_ptep<N> ptep, uintptr_t offset) {
assert(result == null);
result = ptep.read().addr() | (v & ~pte_level_mask(N));
return true;
}
void sub_page(hw_ptep<1> ptep, int l, uintptr_t offset) {
assert(ptep.read().large());
page(ptep, offset);
}
};
class cleanup_intermediate_pages
: public page_table_operation<
allocate_intermediate_opt::no,
skip_empty_opt::yes,
descend_opt::yes,
once_opt::no,
split_opt::no> {
public:
template<int N>
bool page(hw_ptep<N> ptep, uintptr_t offset) {
if (!pt_level_traits<N>::large_capable::value) {
++live_ptes;
}
return true;
}
void intermediate_page_pre(hw_ptep<1> ptep, uintptr_t offset) {
live_ptes = 0;
}
void intermediate_page_post(hw_ptep<1> ptep, uintptr_t offset) {
if (!live_ptes) {
auto old = ptep.read();
auto v = phys_cast<u64*>(old.addr());
for (unsigned i = 0; i < 512; ++i) {
assert(v[i] == 0);
}
ptep.write(make_empty_pte<1>());
osv::rcu_defer([](void *page) { memory::free_page(page); }, phys_to_virt(old.addr()));
do_flush = true;
}
}
bool tlb_flush_needed() { return do_flush; }
void finalize() {}
ulong account_results(void) { return 0; }
private:
unsigned live_ptes;
bool do_flush = false;
};
class virt_to_pte_map_rcu :
public page_table_operation<allocate_intermediate_opt::no, skip_empty_opt::yes,
descend_opt::yes, once_opt::yes, split_opt::no> {
private:
virt_pte_visitor& _visitor;
virt_to_pte_map_rcu(virt_pte_visitor& visitor) : _visitor(visitor) {}
public:
friend void virt_visit_pte_rcu(uintptr_t, virt_pte_visitor&);
template<int N>
pt_element<N> ptep_read(hw_ptep<N> ptep) {
return ptep.ll_read();
}
template<int N>
bool page(hw_ptep<N> ptep, uintptr_t offset) {
auto pte = ptep_read(ptep);
_visitor.pte(pte);
assert(pt_level_traits<N>::large_capable::value == pte.large());
return true;
}
void sub_page(hw_ptep<1> ptep, int l, uintptr_t offset) {
page(ptep, offset);
}
};
template<typename T> ulong operate_range(T mapper, void *vma_start, void *start, size_t size)
{
start = align_down(start, page_size);
size = std::max(align_up(size, page_size), page_size);
uintptr_t virt = reinterpret_cast<uintptr_t>(start);
map_range(reinterpret_cast<uintptr_t>(vma_start), virt, size, mapper);
// TODO: consider if instead of requesting a full TLB flush, we should
// instead try to make more judicious use of INVLPG - e.g., in
// split_large_page() and other specific places where we modify specific
// page table entries.
if (mapper.tlb_flush_needed()) {
mmu::flush_tlb_all();
}
mapper.finalize();
return mapper.account_results();
}
template<typename T> ulong operate_range(T mapper, void *start, size_t size)
{
return operate_range(mapper, start, start, size);
}
phys virt_to_phys_pt(void* virt)
{
auto v = reinterpret_cast<uintptr_t>(virt);
auto vbase = align_down(v, page_size);
virt_to_phys_map v2p_mapper(v);
map_range(vbase, vbase, page_size, v2p_mapper);
return v2p_mapper.addr();
}
void virt_visit_pte_rcu(uintptr_t virt, virt_pte_visitor& visitor)
{
auto vbase = align_down(virt, page_size);
virt_to_pte_map_rcu v2pte_mapper(visitor);
WITH_LOCK(osv::rcu_read_lock) {
map_range(vbase, vbase, page_size, v2pte_mapper);
}
}
bool contains(uintptr_t start, uintptr_t end, vma& y)
{
return y.start() >= start && y.end() <= end;
}
// So that we don't need to create a vma (with size, permission and alot of
// other irrelevant data) just to find an address in the vma list, we have
// the following addr_compare, which compares exactly like vma_compare does,
// except that it takes a bare uintptr_t instead of a vma.
class addr_compare {
public:
bool operator()(const vma& x, uintptr_t y) const { return x.start() < y; }
bool operator()(uintptr_t x, const vma& y) const { return x < y.start(); }
};
// Find the single (if any) vma which contains the given address.
// The complexity is logarithmic in the number of vmas in vma_list.
static inline vma_list_type::iterator
find_intersecting_vma(uintptr_t addr) {
auto vma = vma_list.lower_bound(addr, addr_compare());
if (vma->start() == addr) {
return vma;
}
// Otherwise, vma->start() > addr, so we need to check the previous vma
--vma;
if (addr >= vma->start() && addr < vma->end()) {
return vma;
} else {
return vma_list.end();
}
}
// Find the list of vmas which intersect a given address range. Because the
// vmas are sorted in vma_list, the result is a consecutive slice of vma_list,
// [first, second), between the first returned iterator (inclusive), and the
// second returned iterator (not inclusive).
// The complexity is logarithmic in the number of vmas in vma_list.
static inline std::pair<vma_list_type::iterator, vma_list_type::iterator>
find_intersecting_vmas(const addr_range& r)
{
if (r.end() <= r.start()) { // empty range, so nothing matches
return {vma_list.end(), vma_list.end()};
}
auto start = vma_list.lower_bound(r.start(), addr_compare());
if (start->start() > r.start()) {
// The previous vma might also intersect with our range if it ends
// after our range's start.
auto prev = std::prev(start);
if (prev->end() > r.start()) {
start = prev;
}
}
// If the start vma is actually beyond the end of the search range,
// there is no intersection.
if (start->start() >= r.end()) {
return {vma_list.end(), vma_list.end()};
}
// end is the first vma starting >= r.end(), so any previous vma (after
// start) surely started < r.end() so is part of the intersection.
auto end = vma_list.lower_bound(r.end(), addr_compare());
return {start, end};
}
/**
* Change virtual memory range protection
*
* Change protection for a virtual memory range. Updates page tables and VMas
* for populated memory regions and just VMAs for unpopulated ranges.
*
* \return returns EACCESS/EPERM if requested permission cannot be granted
*/
static error protect(const void *addr, size_t size, unsigned int perm)
{
uintptr_t start = reinterpret_cast<uintptr_t>(addr);
uintptr_t end = start + size;
auto range = find_intersecting_vmas(addr_range(start, end));
for (auto i = range.first; i != range.second; ++i) {
if (i->perm() == perm)
continue;
int err = i->validate_perm(perm);
if (err != 0) {
return make_error(err);
}
i->split(end);
i->split(start);
if (contains(start, end, *i)) {
i->protect(perm);
i->operate_range(protection(perm));
}
}
return no_error();
}
uintptr_t find_hole(uintptr_t start, uintptr_t size)
{
bool small = size < huge_page_size;
uintptr_t good_enough = 0;
// FIXME: use lower_bound or something
auto p = vma_list.begin();
auto n = std::next(p);
while (n != vma_list.end()) {
if (start >= p->end() && start + size <= n->start()) {
return start;
}
if (p->end() >= start && n->start() - p->end() >= size) {
good_enough = p->end();
if (small) {
return good_enough;
}
if (n->start() - align_up(good_enough, huge_page_size) >= size) {
return align_up(good_enough, huge_page_size);
}
}
p = n;
++n;
}
if (good_enough) {
return good_enough;
}
throw make_error(ENOMEM);
}
ulong evacuate(uintptr_t start, uintptr_t end)
{
auto range = find_intersecting_vmas(addr_range(start, end));
ulong ret = 0;
for (auto i = range.first; i != range.second; ++i) {
i->split(end);
i->split(start);
if (contains(start, end, *i)) {
auto& dead = *i--;
auto size = dead.operate_range(unpopulate<account_opt::yes>(dead.page_ops()));
ret += size;
if (dead.has_flags(mmap_jvm_heap)) {
memory::stats::on_jvm_heap_free(size);
}
vma_list.erase(dead);
delete &dead;
}
}
return ret;
// FIXME: range also indicates where we can insert a new anon_vma, use it
}
static void unmap(const void* addr, size_t size)
{
size = align_up(size, mmu::page_size);
auto start = reinterpret_cast<uintptr_t>(addr);
evacuate(start, start+size);
}
static error sync(const void* addr, size_t length, int flags)
{
length = align_up(length, mmu::page_size);
auto start = reinterpret_cast<uintptr_t>(addr);
auto end = start+length;