This repository has been archived by the owner on Mar 15, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 76
/
usermodepageallocator.c
2295 lines (2229 loc) · 79 KB
/
usermodepageallocator.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
/* A very fast user mode page allocator implementation enabling all sorts of
useful speed improvements for common malloc operations. (C) 2010 Niall Douglas.
Boost Software License - Version 1.0 - August 17th, 2003
Permission is hereby granted, free of charge, to any person or organization
obtaining a copy of the software and accompanying documentation covered by
this license (the "Software") to use, reproduce, display, distribute,
execute, and transmit the Software, and to prepare derivative works of the
Software, and to permit third-parties to whom the Software is furnished to
do so, all subject to the following:
The copyright notices in the Software and this entire statement, including
the above license grant, this restriction and the following disclaimer,
must be included in all copies of the Software, in whole or in part, and
all derivative works of the Software, unless such copies or derivative
works are solely in the form of machine-executable object code generated by
a source language processor.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#ifdef ENABLE_USERMODEPAGEALLOCATOR
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable: 4101) /* unreferenced local variable */
#pragma warning(disable: 4189) /* local variable is initialized but not referenced */
#endif
/* This is how many free pages relative to used pages to keep around before
returning them to the system. It gets ignored if system free memory is
perceived to be tight. */
/*#define USERMODEPAGEALLOCATOR_FREEPAGECACHESIZE(usedpages, freepages) (usedpages)*/
#define USERMODEPAGEALLOCATOR_FREEPAGECACHESIZE(usedpages, freepages) ((size_t)-1)
/* This is how many subsequent free operations must happen since a page was
freed before it will be eligible to be returned to the system. It helps prevent
large amounts of memory getting repeatedly freed and reallocated. It gets ignored
if system free memory is perceived to be tight. */
#define USERMODEPAGEALLOCATOR_FREEPAGECACHEAGE(usedpages, freepages) 256
/* This is how many pages to immediately preload the free page cache with on
process startup. If you set it too high relative to the remaining system free
memory, it will get given back fairly rapidly. */
/*#define USERMODEPAGEALLOCATOR_FREEPAGECACHEPRELOAD(systemmemorypressure) ((512*1024*1024/4096))*/
#define USERMODEPAGEALLOCATOR_FREEPAGECACHEPRELOAD(systemmemorypressure) 0
/* This defines how frequently the system free memory state should be
checked, and it must be a power of two. */
#define USERMODEPAGEALLOCATOR_SYSTEMFREEMEMORYCHECKRATE 64
/* This turns on the storage of free page metadata directly in the page tables which
will halve the page table memory requirements. As on x86/x64 page frames start from
one going upwards sequentially and will never use the top bit, this ought to always
be safe. */
#if (defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__))) || (defined(_MSC_VER) && (defined(_M_IX86) || defined(_M_X64)))
/*#define USERMODEPAGEALLOCATOR_USECOMPACTFREEPAGEINDICATOR*/
#endif
/* This puts the user mode page allocator into debug config which means that as
much buffering and caching is disabled as possible in order to best test the code. */
#ifdef DEBUG
#define USERMODEPAGEALLOCATOR_DEBUGCONFIG
#endif
/*
#if (defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__)))
#define PREFETCHCACHELINE(addr, rw, locality) __builtin_prefetch((const void *)(addr), (rw), (locality))
#define STRUCTUREALIGNMENT(alignment) __attribute__ ((aligned(alignment)))
#elif (defined(_MSC_VER) && (defined(_M_IX86) || defined(_M_X64)))
#define PREFETCHCACHELINE(addr, rw, locality) _mm_prefetch((const char *)(addr), (locality))
#define STRUCTUREALIGNMENT(alignment) __declspec(align(alignment))
#endif
*/
#ifndef PREFETCHCACHELINE
#define PREFETCHCACHELINE(addr, rw, locality)
#endif
#ifndef STRUCTUREALIGNMENT
#define STRUCTUREALIGNMENT(alignment)
#endif
#ifdef USERMODEPAGEALLOCATOR_DEBUGCONFIG
#undef USERMODEPAGEALLOCATOR_FREEPAGECACHESIZE
#define USERMODEPAGEALLOCATOR_FREEPAGECACHESIZE(usedpages, freepages) ((usedpages)/16)
#undef USERMODEPAGEALLOCATOR_FREEPAGECACHEAGE
#define USERMODEPAGEALLOCATOR_FREEPAGECACHEAGE(usedpages, freepages) 0
#undef USERMODEPAGEALLOCATOR_SYSTEMFREEMEMORYCHECKRATE
#define USERMODEPAGEALLOCATOR_SYSTEMFREEMEMORYCHECKRATE 1
#endif
#include "nedtries/nedtrie.h"
extern int OSHavePhysicalPageSupport(void);
extern void *userpage_malloc(size_t toallocate, unsigned flags);
extern int userpage_free(void *mem, size_t size);
extern void *userpage_realloc(void *mem, size_t oldsize, size_t newsize, int flags, unsigned flags2);
#if defined(WIN32) && defined(USERMODEPAGEALLOCATOR_DLL_EXPORTS)
extern void DebugPrint(const char *fmt, ...) THROWSPEC;
#else
#define DebugPrint printf
#endif
#ifndef PAGE_SIZE
#define PAGE_SIZE 4096
#endif
#ifndef USERPAGE_TOPDOWN
#define USERPAGE_TOPDOWN (M2_CUSTOM_FLAGS_BEGIN<<0)
#define USERPAGE_NOCOMMIT (M2_CUSTOM_FLAGS_BEGIN<<1)
#endif
#define REGION_ENTRY(type) NEDTRIE_ENTRY(type)
#define REGION_HEAD(name, type) NEDTRIE_HEAD(name, type)
#define REGION_INIT(treevar) NEDTRIE_INIT(treevar)
#define REGION_EMPTY(treevar) NEDTRIE_EMPTY(treevar)
#define REGION_GENERATE(proto, treetype, nodetype, link, cmpfunct) NEDTRIE_GENERATE(proto, treetype, nodetype, link, cmpfunct, NEDTRIE_NOBBLEZEROS(treetype))
#define REGION_INSERT(treetype, treevar, node) NEDTRIE_INSERT(treetype, treevar, node)
#define REGION_REMOVE(treetype, treevar, node) NEDTRIE_REMOVE(treetype, treevar, node)
#define REGION_FIND(treetype, treevar, node) NEDTRIE_FIND(treetype, treevar, node)
#define REGION_EXACTFIND(treetype, treevar, node) NEDTRIE_EXACTFIND(treetype, treevar, node)
#define REGION_CFIND(treetype, treevar, node, rounds) NEDTRIE_CFIND(treetype, treevar, node, rounds)
#define REGION_MAX(treetype, treevar) NEDTRIE_MAX(treetype, treevar)
#define REGION_MIN(treetype, treevar) NEDTRIE_MIN(treetype, treevar)
#define REGION_NEXT(treetype, treevar, node) NEDTRIE_NEXT(treetype, treevar, node)
#define REGION_PREV(treetype, treevar, node) NEDTRIE_PREV(treetype, treevar, node)
#define REGION_FOREACH(var, treetype, treevar) NEDTRIE_FOREACH(var, treetype, treevar)
#define REGION_HASNODEHEADER(treevar, node, link) NEDTRIE_HASNODEHEADER(treevar, node, link)
typedef struct RegionStorage_s RegionStorage_t;
typedef struct region_node_s region_node_t;
struct region_node_s {
RegionStorage_t *owner;
region_node_t *prev, *next; /* Always keep owner, prev at top */
REGION_ENTRY(region_node_s) linkA; /* by start addr */
REGION_ENTRY(region_node_s) linkL; /* by length */
void *start, *end;
};
typedef struct regionA_tree_s regionA_tree_t;
REGION_HEAD(regionA_tree_s, region_node_s);
typedef struct regionL_tree_s regionL_tree_t;
REGION_HEAD(regionL_tree_s, region_node_s);
size_t regionkeyA(const region_node_t *RESTRICT r)
{
return (size_t) r->start;
}
size_t regionkeyL(const region_node_t *RESTRICT r)
{
return (size_t) r->end - (size_t) r->start;
}
REGION_GENERATE(static, regionA_tree_s, region_node_s, linkA, regionkeyA);
REGION_GENERATE(static, regionL_tree_s, region_node_s, linkL, regionkeyL);
typedef struct MemorySource_t MemorySource;
static struct MemorySource_t
{
regionA_tree_t regiontreeA; /* The list of allocated regions, keyed by start addr */
regionL_tree_t regiontreeL; /* The list of free regions, keyed by length */
region_node_t *firstregion; /* The first region by order of addition */
region_node_t *lastregion; /* The last region by order of addition */
} lower, upper;
typedef struct OSAddressSpaceReservationData_t
{
void *addr;
void *data[2];
} OSAddressSpaceReservationData;
#ifndef WIN32
typedef size_t PageFrameType;
/* This function determines whether the host OS allows user mode physical memory
page mapping. */
static int OSDeterminePhysicalPageSupport(void) { return 0; }
/* This function returns a simple true or false if the host OS allows user mode
physical page mapping */
int OSHavePhysicalPageSupport(void) { return 0; }
/* This function determines whether the host OS is currently short of memory.
The value is LINEAR between 0.0 (no pressure) and 1.0 (terrible pressure). */
static double OSSystemMemoryPressure(void) { return 0; }
/* This function could ask the host OS for address space, or on embedded systems
it could simply parcel out space via moving a pointer. The second two void *
are some arbitrary extra data to be later passed to OSReleaseAddrSpace(). */
static OSAddressSpaceReservationData OSReserveAddrSpace(size_t space) { OSAddressSpaceReservationData asrd={0}; return asrd; }
/* This function returns address space previously allocated using
OSReserveAddrSpace(). It is guaranteed to exactly match what was previously
returned by that function. */
static int OSReleaseAddrSpace(OSAddressSpaceReservationData *data, size_t space) { return 0; }
/* This function obtains physical memory pages, either by asking the host OS
or on embedded systems by simply pulling them from a free page ring list. */
static size_t OSObtainMemoryPages(PageFrameType *buffer, size_t number, OSAddressSpaceReservationData *data) { return 0; }
/* This function returns previously obtained physical memory pages. */
static size_t OSReleaseMemoryPages(PageFrameType *buffer, size_t number, OSAddressSpaceReservationData *data) { return 0; }
/* This function causes the specified set of physical memory pages to be
mapped at the specified address. On an embedded system this would simply
modify the MMU and flush the appropriate TLB entries.
*/
static size_t OSRemapMemoryPagesOntoAddr(void *addr, size_t entries, PageFrameType *pageframes, OSAddressSpaceReservationData *data) { return 0; }
/* This function causes the specified set of physical memory pages to be
mapped at the specified set of addresses. On an embedded system this would
simply modify the MMU and flush the appropriate TLB entries. It works like this:
for(size_t n=0; n<entries; n++, addrs++, pageframes++) {
if(*pageframe)
Map(*addr, *pageframe);
else
Unmap(*addr);
}
*/
static size_t OSRemapMemoryPagesOntoAddrs(void **addrs, size_t entries, PageFrameType *pageframes, OSAddressSpaceReservationData *data) { return 0; }
#else
static enum {
DISABLEEVERYTHING=1,
NOPHYSICALPAGESUPPORT=2,
HAVEPHYSICALPAGESUPPORT=4
} PhysicalPageSupport;
#ifdef ENABLE_PHYSICALPAGEEMULATION
/* Windows has the curious problem of using 4Kb pages but requiring those pages
to be mapped at 64Kb aligned address. By far the easiest solution is to pretend
that we actually have 64Kb pages. */
#undef PAGE_SIZE
#define PAGE_SIZE 65536
typedef struct PageFrameType_t
{
ULONG_PTR pages[16];
} PageFrameType;
#else
typedef ULONG_PTR PageFrameType;
#endif
/* Returns 1 for bad compile, 2 for no support on this machine/user,
4 for supported */
#pragma comment(lib, "advapi32.lib")
static int OSDeterminePhysicalPageSupport(void)
{
if(!PhysicalPageSupport)
{ /* Quick test */
PageFrameType pageframe;
size_t no=sizeof(PageFrameType)/sizeof(ULONG_PTR);
SYSTEM_INFO si={0};
{
HANDLE token;
if(OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &token))
{
TOKEN_PRIVILEGES privs={1};
if(LookupPrivilegeValue(NULL, SE_LOCK_MEMORY_NAME, &privs.Privileges[0].Luid))
{
privs.Privileges[0].Attributes=SE_PRIVILEGE_ENABLED;
if(!AdjustTokenPrivileges(token, FALSE, &privs, 0, NULL, NULL) || GetLastError()!=S_OK)
{
}
}
CloseHandle(token);
}
}
if(AllocateUserPhysicalPages((HANDLE)(size_t)-1, (PULONG_PTR) &no, (PULONG_PTR) &pageframe))
{
FreeUserPhysicalPages((HANDLE)(size_t)-1, (PULONG_PTR) &no, (PULONG_PTR) &pageframe);
PhysicalPageSupport=HAVEPHYSICALPAGESUPPORT;
CreateEvent(NULL, FALSE, FALSE, __T("UserModePageAllocatorEnabled"));
}
else
{
PhysicalPageSupport=NOPHYSICALPAGESUPPORT;
/*fprintf(stderr, "User Mode Page Allocator: Failed to allocate physical memory pages (does the user running this process have the right to lock pages in memory?). User Mode Page Allocator will not be used.\n");*/
OutputDebugStringA("User Mode Page Allocator: Failed to allocate physical memory pages (does the user running this process have the right to lock pages in memory?). User Mode Page Allocator will not be used.\n");
CreateEvent(NULL, FALSE, FALSE, __T("UserModePageAllocatorDisabled"));
}
GetSystemInfo(&si);
#ifdef ENABLE_PHYSICALPAGEEMULATION
if(si.dwAllocationGranularity!=PAGE_SIZE)
{
assert(si.dwAllocationGranularity==PAGE_SIZE);
fprintf(stderr, "User Mode Page Allocator: Allocation granularity is %u not %u. Please recompile with corrected PAGE_SIZE\n", si.dwAllocationGranularity, PAGE_SIZE);
PhysicalPageSupport=DISABLEEVERYTHING;
}
if(si.dwAllocationGranularity/si.dwPageSize!=sizeof(PageFrameType)/sizeof(ULONG_PTR))
{
assert(si.dwAllocationGranularity/si.dwPageSize==sizeof(PageFrameType)/sizeof(ULONG_PTR));
fprintf(stderr, "User Mode Page Allocator: Pages per PageFrameType is %u not %u. Please recompile with corrected PageFrameType definition\n", si.dwAllocationGranularity/si.dwPageSize, sizeof(PageFrameType)/sizeof(ULONG_PTR));
PhysicalPageSupport=DISABLEEVERYTHING;
}
#else
if(si.dwPageSize!=PAGE_SIZE)
{
assert(si.dwPageSize==PAGE_SIZE);
fprintf(stderr, "User Mode Page Allocator: Page size is %u not %u. Please recompile with corrected PAGE_SIZE\n", si.dwPageSize, PAGE_SIZE);
PhysicalPageSupport=DISABLEEVERYTHING;
}
#endif
}
return PhysicalPageSupport;
}
int OSHavePhysicalPageSupport(void)
{
if(!PhysicalPageSupport) OSDeterminePhysicalPageSupport();
return HAVEPHYSICALPAGESUPPORT==PhysicalPageSupport;
}
static double OSSystemMemoryPressure(void)
{
MEMORYSTATUSEX ms={sizeof(MEMORYSTATUSEX)};
if(!GlobalMemoryStatusEx(&ms))
return 0;
return ms.dwMemoryLoad/100.0;
}
static OSAddressSpaceReservationData OSReserveAddrSpace(size_t space)
{
OSAddressSpaceReservationData ret={0};
if(!PhysicalPageSupport) OSDeterminePhysicalPageSupport();
if(DISABLEEVERYTHING==PhysicalPageSupport) return ret;
if(HAVEPHYSICALPAGESUPPORT==PhysicalPageSupport)
{
ret.addr=VirtualAlloc(NULL, space, MEM_RESERVE|MEM_PHYSICAL, PAGE_READWRITE);
}
#ifdef ENABLE_PHYSICALPAGEEMULATION
if(!ret.addr)
{
HANDLE fmh;
fmh = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE|SEC_RESERVE,
#if defined(_M_IA64) || defined(_M_X64) || defined(WIN64)
(DWORD)(space>>32),
#else
0,
#endif
(DWORD)(space&((DWORD)-1)), NULL);
if(fmh)
{ /* This is breathtakingly inefficient, but win32 leaves us no choice :(
At least this function is called very infrequently. */
while((ret.addr=VirtualAlloc(NULL, space, MEM_RESERVE, PAGE_READWRITE)))
{
void *RESTRICT seg;
VirtualFree(ret.addr, 0, MEM_RELEASE);
for(seg=ret.addr; seg<(void*)((size_t) ret.addr + space); seg=(void *)((size_t) seg + Win32granularity))
{
if(!VirtualAlloc(seg, Win32granularity, MEM_RESERVE, PAGE_READWRITE))
break;
}
if(seg==(void*)((size_t) ret.addr + space))
break;
else
{
for(; seg>=ret.addr; seg=(void *)((size_t) seg - Win32granularity))
VirtualFree(seg, 0, MEM_RELEASE);
}
}
if(!ret.addr)
CloseHandle(fmh);
else
{
ret.data[0]=(void *) fmh;
ret.data[1]=(void *)(size_t) 1;
}
}
}
#endif
return ret;
}
static int OSReleaseAddrSpace(OSAddressSpaceReservationData *RESTRICT data, size_t space)
{
if(!data->data[0])
return VirtualFree(data->addr, 0, MEM_RELEASE);
#ifdef ENABLE_PHYSICALPAGEEMULATION
else
{
void *seg;
CloseHandle((HANDLE)data->data[0]);
for(seg=data->addr; seg<(void*)((size_t) data->addr + space); seg=(void *)((size_t) seg + Win32granularity))
VirtualFree(seg, 0, MEM_RELEASE);
return 1;
}
#endif
return 0;
}
static size_t OSObtainMemoryPages(PageFrameType *RESTRICT buffer, size_t number, OSAddressSpaceReservationData *RESTRICT data)
{
if(!data->data[0])
{
#ifdef ENABLE_PHYSICALPAGEEMULATION
number*=sizeof(PageFrameType)/sizeof(ULONG_PTR);
#endif
#if 1
if(!AllocateUserPhysicalPages((HANDLE)(size_t)-1, (PULONG_PTR) &number, (PULONG_PTR) buffer))
{
if(number)
FreeUserPhysicalPages((HANDLE)(size_t)-1, (PULONG_PTR) &number, (PULONG_PTR) buffer);
return 0;
}
#else
{
size_t n;
PageFrameType *RESTRICT bptr;
for(n=0, bptr=buffer; n<number; n++, bptr++)
{
size_t no=1;
if(!AllocateUserPhysicalPages((HANDLE)(size_t)-1, (PULONG_PTR) &no, (PULONG_PTR) bptr))
{
for(bptr--; bptr>=buffer; bptr--)
{
no=1;
FreeUserPhysicalPages((HANDLE)(size_t)-1, (PULONG_PTR) &no, (PULONG_PTR) bptr);
}
return 0;
}
}
}
#endif
#ifdef ENABLE_PHYSICALPAGEEMULATION
number/=sizeof(PageFrameType)/sizeof(ULONG_PTR);
#endif
return number;
}
#ifdef ENABLE_PHYSICALPAGEEMULATION
else
{
size_t n;
ULONG_PTR *RESTRICT pf=(ULONG_PTR *RESTRICT) &data->data[1];
for(n=0; n<number*(sizeof(PageFrameType)/sizeof(ULONG_PTR)); n++)
((ULONG_PTR *) buffer)[n]=(*pf)++;
return number;
}
#endif
return 0;
}
static size_t OSReleaseMemoryPages(PageFrameType *RESTRICT buffer, size_t number, OSAddressSpaceReservationData *RESTRICT data)
{
if(!data->data[0])
{
#ifdef ENABLE_PHYSICALPAGEEMULATION
number*=sizeof(PageFrameType)/sizeof(ULONG_PTR);
#endif
#if 1
if(!FreeUserPhysicalPages((HANDLE)(size_t)-1, (PULONG_PTR) &number, (PULONG_PTR) buffer)) return 0;
#else
{
size_t n;
PageFrameType *RESTRICT bptr;
for(n=0, bptr=buffer; n<number; n++, bptr++)
{
size_t no=1;
if(!FreeUserPhysicalPages((HANDLE)(size_t)-1, (PULONG_PTR) &no, (PULONG_PTR) bptr))
{
assert(0);
}
}
}
#endif
#ifdef ENABLE_PHYSICALPAGEEMULATION
number/=sizeof(PageFrameType)/sizeof(ULONG_PTR);
#endif
#ifdef DEBUG
/*for(n=0; n<number*(sizeof(PageFrameType)/sizeof(ULONG_PTR)); n++)
((ULONG_PTR *) buffer)[n]=0;*/
#endif
return number;
}
/* Always fail if we are emulating physical pages */
return 0;
}
static
__declspec(noinline)
size_t OSRemapMemoryPagesOntoAddr(void *addr, size_t entries, PageFrameType *RESTRICT pageframes, OSAddressSpaceReservationData *RESTRICT data)
{
if(!data->data[0])
{
BOOL ret;
#ifdef ENABLE_PHYSICALPAGEEMULATION
entries*=sizeof(PageFrameType)/sizeof(ULONG_PTR);
#endif
#if 1
ret=MapUserPhysicalPages(addr, entries, (PULONG_PTR) pageframes);
if(!ret)
{
assert(ret);
}
return ret;
#else
{
size_t n;
PageFrameType *RESTRICT bptr;
for(n=0, bptr=pageframes; n<entries; n++, bptr++, addr=(void *)((size_t) addr + PAGE_SIZE))
{
ret=MapUserPhysicalPages(addr, 1, pageframes ? bptr : NULL);
if(!ret)
{
assert(ret);
return 0;
}
}
return 1;
}
#endif
}
#ifdef ENABLE_PHYSICALPAGEEMULATION
else
{
size_t n, ret=1;
PageFrameType *RESTRICT pfa, *RESTRICT pf;
for(n=0; n<entries; n++, addr=(void *)((size_t) addr + PAGE_SIZE), pageframes++)
{
if(*pageframe)
{
size_t filemappingoffset=PAGE_SIZE*((*pageframe)-1);
/* Change reservation for next segment */
if(!VirtualFree(addr, 0, MEM_RELEASE)) ret=0;
if(!MapViewOfFileEx((HANDLE) data.data[0], FILE_MAP_ALL_ACCESS,
#if defined(_M_IA64) || defined(_M_X64) || defined(WIN64)
(DWORD)(filemappingoffset>>32),
#else
0,
#endif
(DWORD)(filemappingoffset & (DWORD)-1), PAGE_SIZE, addr)) ret=0;
}
else
{
if(!UnmapViewOfFile(addr)) ret=0;
/* Rereserve */
if(!VirtualAlloc(addr, PAGE_SIZE, MEM_RESERVE, PAGE_READWRITE)) ret=0;
}
}
return ret;
}
#endif
return 0;
}
static
__declspec(noinline)
size_t OSRemapMemoryPagesOntoAddrs(void *RESTRICT *addrs, size_t entries, PageFrameType *RESTRICT pageframes, OSAddressSpaceReservationData *RESTRICT data)
{
#ifdef DEBUG
size_t n;
void *RESTRICT *addr;
PageFrameType *RESTRICT pf;
assert(entries);
for(addr=addrs, pf=pageframes, n=0; n<entries; n++, addr++, pf++)
{
assert(*addr);
/*DebugPrint("Mapping page frame %p to %p\n", *pf, *addr);*/
}
#endif
if(!data->data[0])
{
BOOL ret;
#ifdef ENABLE_PHYSICALPAGEEMULATION
entries*=sizeof(PageFrameType)/sizeof(ULONG_PTR);
#endif
#if 1
ret=MapUserPhysicalPagesScatter(addrs, entries, (PULONG_PTR) pageframes);
if(!ret)
{
assert(ret);
}
#else
{
size_t n;
void **aptr;
PageFrameType *RESTRICT bptr;
for(n=0, aptr=addrs, bptr=pageframes; n<entries; n++, aptr++, bptr++)
{
ret=MapUserPhysicalPages(*aptr, 1, *bptr ? bptr : NULL);
if(!ret)
{
assert(ret);
return 0;
}
}
return 1;
}
#endif
return ret;
}
#ifdef ENABLE_PHYSICALPAGEEMULATION
else
{
size_t n, ret=1;
PageFrameType *RESTRICT pfa, *RESTRICT pf;
for(n=0; n<entries; n++, addrs++, pageframes++)
{
if(*pageframe)
{
size_t filemappingoffset=PAGE_SIZE*((*pageframe)-1);
/* Change reservation for next segment */
if(!VirtualFree(*addrs, 0, MEM_RELEASE)) ret=0;
if(!MapViewOfFileEx((HANDLE) data.data[0], FILE_MAP_ALL_ACCESS,
#if defined(_M_IA64) || defined(_M_X64) || defined(WIN64)
(DWORD)(filemappingoffset>>32),
#else
0,
#endif
(DWORD)(filemappingoffset & (DWORD)-1), PAGE_SIZE, *addrs)) ret=0;
}
else
{
if(!UnmapViewOfFile(*addrs)) ret=0;
/* Rereserve */
if(!VirtualAlloc(*addrs, PAGE_SIZE, MEM_RESERVE, PAGE_READWRITE)) ret=0;
}
}
return ret;
}
#endif
return 0;
}
#endif
/* Maps an address reservation */
typedef struct FreePageNodeStorage_s FreePageNodeStorage_t;
typedef struct FreePageNode_t FreePageNode;
struct FreePageNode_t
{
FreePageNodeStorage_t *owner;
FreePageNode *older, *newer; /* Always keep owner + older at top */
void *freepage;
PageFrameType pageframe;
size_t dirty: 1;
size_t age :(8*sizeof(size_t)-1);
};
static FreePageNode *AllocateFPN(void);
static void FreeFPN(FreePageNode *node);
typedef struct AddressSpaceReservation_s AddressSpaceReservation_t;
#ifdef USERMODEPAGEALLOCATOR_USECOMPACTFREEPAGEINDICATOR
typedef union PageMapping_t PageMapping;
union PageMapping_t
#else
typedef struct PageMapping_t PageMapping;
struct PageMapping_t
#endif
{
PageFrameType pageframe; /* Actually the pageframe shifted left by one and the bottom bit always set */
FreePageNode *freepagenode;
};
static struct AddressSpaceReservation_s
{
OSAddressSpaceReservationData OSreservedata;
AddressSpaceReservation_t *RESTRICT next;
void *front, *frontptr; /* Grows upward */
void *back, *backptr; /* Grows downward */
size_t opcount;
FreePageNode *oldestclean, *newestclean;
FreePageNode *oldestdirty, *newestdirty;
FreePageNode *nodestore;
size_t freepages;
size_t usedpages; /* Doesn't include pages used to store this structure */
PageMapping pagemapping[1]; /* Includes this structure */
} *RESTRICT addressspacereservation;
#ifdef USERMODEPAGEALLOCATOR_USECOMPACTFREEPAGEINDICATOR
#define ISPAGEFREE(pagemapping) (!((size_t)((pagemapping).pageframe) & 1))
#define PAGEFRAME(pagemapping) (ISPAGEFREE(pagemapping) ? ((pagemapping).freepagenode)->pageframe : (PageFrameType)((size_t)((pagemapping).pageframe)>>1))
#define SETPAGEFRAME(pagemapping, pf) ((pagemapping).pageframe=!(pf) ? 0 : (PageFrameType)(((size_t)(pf)<<1)|1))
#define SETPAGEFREE(pagemapping, fpn) ((fpn)->pageframe=(PageFrameType)((size_t)((pagemapping).pageframe)>>1), (pagemapping).freepagenode=(fpn))
#define SETPAGEUSED(pagemapping, pf) (SETPAGEFRAME((pagemapping), (pf))
#else
#define ISPAGEFREE(pagemapping) (((pagemapping).freepagenode))
#define PAGEFRAME(pagemapping) ((pagemapping).pageframe)
#define SETPAGEFRAME(pagemapping, pf) ((pagemapping).pageframe=(pf))
#define SETPAGEFREE(pagemapping, fpn) ((fpn)->pageframe=((pagemapping).pageframe), (pagemapping).freepagenode=(fpn))
#define SETPAGEUSED(pagemapping, pf) (SETPAGEFRAME((pagemapping), (pf)), (pagemapping).freepagenode=0)
#endif
static void ValidateFreePageLists(AddressSpaceReservation_t *RESTRICT addr)
{
#ifndef NDEBUG
#if 1
FreePageNode *RESTRICT fpn;
size_t count=0;
PageMapping *RESTRICT pf;
size_t n, freepagepfidx;
for(fpn=addr->oldestclean; fpn; fpn=fpn->newer)
{
freepagepfidx=((size_t)fpn->freepage-(size_t)addr)/PAGE_SIZE;
assert(ISPAGEFREE(addr->pagemapping[freepagepfidx]));
assert(addr->pagemapping[freepagepfidx].freepagenode==fpn);
assert((!fpn->older && addr->oldestclean==fpn) || fpn->older->newer==fpn);
assert((!fpn->newer && addr->newestclean==fpn) || fpn->newer->older==fpn);
assert(fpn->age<=addr->opcount);
assert(!fpn->dirty);
count++;
}
for(fpn=addr->oldestdirty; fpn; fpn=fpn->newer)
{
freepagepfidx=((size_t)fpn->freepage-(size_t)addr)/PAGE_SIZE;
assert(ISPAGEFREE(addr->pagemapping[freepagepfidx]));
assert(addr->pagemapping[freepagepfidx].freepagenode==fpn);
assert((!fpn->older && addr->oldestdirty==fpn) || fpn->older->newer==fpn);
assert((!fpn->newer && addr->newestdirty==fpn) || fpn->newer->older==fpn);
assert(fpn->age<=addr->opcount);
assert(fpn->dirty);
count++;
}
assert(count==addr->freepages);
#if 0
count=0;
for(pf=addr->pagemapping, n=0; n<((size_t) addr->frontptr + 16*PAGE_SIZE - (size_t) addr); pf++, n+=PAGE_SIZE)
{
if(pf->pageframe && ISPAGEFREE(*pf))
{
fpn=pf->freepagenode;
freepagepfidx=((size_t)fpn->freepage-(size_t)addr)/PAGE_SIZE;
assert(addr->pagemapping+freepagepfidx==pf);
assert((size_t)fpn->freepage-(size_t)addr==n);
assert((!fpn->older && addr->oldestdirty==fpn) || fpn->older->newer==fpn);
assert((!fpn->newer && addr->newestdirty==fpn) || fpn->newer->older==fpn);
assert(fpn->age<=addr->opcount);
count++;
}
}
n=((size_t) addr->backptr - 16*PAGE_SIZE - (size_t) addr);
for(pf=addr->pagemapping+n/PAGE_SIZE; n<((size_t) addr->back - (size_t) addr); pf++, n+=PAGE_SIZE)
{
if(pf->pageframe && ISPAGEFREE(*pf))
{
fpn=pf->freepagenode;
freepagepfidx=((size_t)fpn->freepage-(size_t)addr)/PAGE_SIZE;
assert(addr->pagemapping+freepagepfidx==pf);
assert((size_t)fpn->freepage-(size_t)addr==n);
assert((!fpn->older && addr->oldestdirty==fpn) || fpn->older->newer==fpn);
assert((!fpn->newer && addr->newestdirty==fpn) || fpn->newer->older==fpn);
assert(fpn->age<=addr->opcount);
count++;
}
}
assert(count==addr->freepages);
#endif
#endif
#endif
}
static void ValidatePageMappings(AddressSpaceReservation_t *RESTRICT addr)
{
#ifndef NDEBUG
#if 0
#ifdef _MSC_VER
PageMapping *RESTRICT pf;
size_t n;
for(pf=addr->pagemapping, n=0; n<((size_t) addr->frontptr + 16*PAGE_SIZE - (size_t) addr); pf++, n+=PAGE_SIZE)
{
volatile size_t *RESTRICT pageaddr=(size_t *RESTRICT)((size_t) addr + n + 0x300/* For some odd reason Windows maps 0x2F0 extra bytes */);
int faulted=0;
PageFrameType t=pf->pageframe ? PAGEFRAME(*pf) : 0;
if(pf->pageframe && n)
{ /* Verify that this is indeed a valid page frame */
assert(OSRemapMemoryPagesOntoAddr((void *)((size_t) addr + n), 1, NULL, &addr->OSreservedata));
assert(OSRemapMemoryPagesOntoAddr((void *)((size_t) addr + n), 1, &t, &addr->OSreservedata));
}
#if 0
#if 1
{
char buffer[8];
faulted=!ReadProcessMemory((HANDLE)(size_t)-1, (void *) pageaddr, buffer, 1, NULL);
}
#else
__try
{
*pageaddr;
}
__except(1)
{
faulted=1;
}
#endif
assert(faulted==!t);
#endif
}
#endif
#endif
#endif
}
static AddressSpaceReservation_t *ReserveSpace(size_t space)
{
const size_t RESERVEALWAYSLEAVEFREE=64*1024*1024; /* Windows goes seriously screwy if you take away all address space */
OSAddressSpaceReservationData addrR={0};
AddressSpaceReservation_t *RESTRICT addr=0;
size_t pagemappingsize, n, pagesallocated;
PageFrameType pagebuffer[256];
if(space<(size_t)1<<30 /* 1Gb */)
{
space=(size_t)1<<30;
if(8==sizeof(size_t)) space<<=2; /* Go for 4Gb chunks on 64 bit */
}
while(space>=RESERVEALWAYSLEAVEFREE && !(addrR=OSReserveAddrSpace(space)).addr)
space>>=1;
if(space<RESERVEALWAYSLEAVEFREE)
return 0;
pagemappingsize=sizeof(AddressSpaceReservation_t)+sizeof(PageMapping)*((space/PAGE_SIZE)-2);
pagemappingsize=(pagemappingsize+PAGE_SIZE-1) &~(PAGE_SIZE-1);
pagemappingsize/=PAGE_SIZE;
/* We now need pagemappingsize number of pages in order to store the mapping tables, but
because this could be as much as 4Mb of stuff we'll need to do it in chunks to avoid
breaking the stack. */
for(n=0; n<pagemappingsize; n+=pagesallocated)
{
size_t torequest=sizeof(pagebuffer)/sizeof(PageFrameType);
void *mapaddr=(void *)((size_t) addrR.addr + n*PAGE_SIZE);
if(torequest>pagemappingsize-n) torequest=pagemappingsize-n;
if(!(pagesallocated=OSObtainMemoryPages(pagebuffer, torequest, &addrR)))
goto badexit;
if(!OSRemapMemoryPagesOntoAddr(mapaddr, pagesallocated, pagebuffer, &addrR))
goto badexit;
if(!n)
{ /* This is the first run, so install AddressSpaceReservation */
addr=(AddressSpaceReservation_t *RESTRICT) addrR.addr;
addr->OSreservedata=addrR;
addr->front=addr->frontptr=(void *)((size_t)addr+pagemappingsize*PAGE_SIZE);
addr->back=addr->backptr=(void *)((size_t)addr+space);
}
/* Add these new pages to the page mappings. Because we are premapping in new pages,
we are guaranteed to have memory already there ready for us. */
for(torequest=0; torequest<pagesallocated; torequest++)
SETPAGEFRAME(addr->pagemapping[n+torequest], pagebuffer[torequest]);
}
ValidatePageMappings(addr);
#ifdef DEBUG
DebugPrint("*** Reserved address space from %p to %p (%luMb)\n", addr, addr->back, (unsigned long)((size_t)addr->back - (size_t) addr)/1024/1024);
#endif
return addr;
badexit:
/* Firstly throw away any just allocated pages */
if(pagesallocated)
OSReleaseMemoryPages(pagebuffer, pagesallocated, &addrR);
if(addr)
{ /* Now throw away any previously stored */
size_t m, o, torequest;
for(m=0; m<n; m+=torequest)
{
torequest=sizeof(pagebuffer)/sizeof(PageFrameType);;
if(torequest<m-n) torequest=m-n;
for(o=m; o<m+torequest; o++)
pagebuffer[o]=PAGEFRAME(addr->pagemapping[o]);
OSReleaseMemoryPages(pagebuffer, torequest, &addrR);
}
}
OSReleaseAddrSpace(&addrR, space);
return 0;
}
static int CheckFreeAddressSpaces(AddressSpaceReservation_t *RESTRICT *RESTRICT _addr)
{
AddressSpaceReservation_t *RESTRICT addr=*_addr;
if(!addr->next || CheckFreeAddressSpaces(&addr->next))
{
assert(!addr->next);
if(0==addr->usedpages)
{
size_t size=(size_t)addr->back-(size_t)addr;
assert(addr->frontptr==addr->front);
assert(addr->backptr==addr->back);
if(OSReleaseAddrSpace(&addr->OSreservedata, size))
{
*_addr=0;
return 1;
}
}
}
return 0;
}
#ifdef USERMODEPAGEALLOCATOR_DEBUGCONFIG
#define REMAPMEMORYPAGESBLOCKSIZE 16
#else
#define REMAPMEMORYPAGESBLOCKSIZE 1024
#endif
typedef struct STRUCTUREALIGNMENT(16) RemapMemoryPagesBlock_t
{
void *addrs[REMAPMEMORYPAGESBLOCKSIZE];
PageFrameType pageframes[REMAPMEMORYPAGESBLOCKSIZE];
size_t idx;
} RemapMemoryPagesBlock;
static size_t FillWithFreePages(AddressSpaceReservation_t *RESTRICT addr, RemapMemoryPagesBlock *RESTRICT memtodecommit, RemapMemoryPagesBlock *RESTRICT memtocommit, void *freespaceaddr, PageMapping *RESTRICT start, PageMapping *RESTRICT end, int needclean)
{
size_t n, pages=end-start;
PageMapping *RESTRICT pf=start;
for(n=0; n<pages && addr->freepages; n++, pf++, freespaceaddr=(void *)((size_t) freespaceaddr + PAGE_SIZE))
{
FreePageNode *RESTRICT fpn=0, *RESTRICT *RESTRICT fpnaddr=0, *RESTRICT *RESTRICT fpnnaddr=0;
PageFrameType freepageframe;
size_t freepagepfidx;
assert(!pf->pageframe);
if(needclean && addr->oldestclean)
{
assert(!addr->oldestclean->older);
fpn=addr->oldestclean;
fpnaddr=&addr->oldestclean;
fpnnaddr=&addr->newestclean;
}
else if(addr->oldestdirty)
{
assert(!addr->oldestdirty->older);
fpn=addr->oldestdirty;
fpnaddr=&addr->oldestdirty;
fpnnaddr=&addr->newestdirty;
}
else if(!needclean && addr->oldestclean)
{
assert(!addr->oldestclean->older);
fpn=addr->oldestclean;
fpnaddr=&addr->oldestclean;
fpnnaddr=&addr->newestclean;
}
/* Add to the list of pages to demap */
memtodecommit->addrs[memtodecommit->idx]=fpn->freepage;
/*memtodecommit->pageframes[memtodecommit->idx]=0;*/
memtodecommit->idx++;
/* Add to the list of pages to remap */
freepagepfidx=((size_t)fpn->freepage-(size_t)addr)/PAGE_SIZE;
freepageframe=fpn->pageframe;
SETPAGEUSED(addr->pagemapping[freepagepfidx], 0);
memtocommit->addrs[memtocommit->idx]=freespaceaddr;
SETPAGEUSED(*pf, freepageframe);
memtocommit->pageframes[memtocommit->idx]=freepageframe;
memtocommit->idx++;
/* Remove from free page lists */
assert(!fpn->older);
*fpnaddr=fpn->newer;
if(*fpnaddr)
(*fpnaddr)->older=0;
else
*fpnnaddr=0;
addr->freepages--;
addr->usedpages++;
#if MMAP_CLEARS
if(needclean && fpn->dirty)
memset(fpn->freepage, 0, PAGE_SIZE);
#endif
FreeFPN(fpn);
ValidateFreePageLists(addr);
if(REMAPMEMORYPAGESBLOCKSIZE==memtocommit->idx)
{
if(memtodecommit->idx) OSRemapMemoryPagesOntoAddrs(memtodecommit->addrs, memtodecommit->idx, NULL, &addr->OSreservedata);
OSRemapMemoryPagesOntoAddrs(memtocommit->addrs, memtocommit->idx, memtocommit->pageframes, &addr->OSreservedata);
memtodecommit->idx=memtocommit->idx=0;
ValidatePageMappings(addr);
}
}
/* Allocate more pages if needed */
#ifdef DEBUG
if(pages-n>0) DebugPrint("Requesting %lu new pages from kernel\n", (unsigned long) pages-n);
#endif
while(pages-n>0)
{
size_t newpagesnow=pages-n, newpagesobtained, m;
if(newpagesnow>REMAPMEMORYPAGESBLOCKSIZE-memtocommit->idx) newpagesnow=REMAPMEMORYPAGESBLOCKSIZE-memtocommit->idx;
newpagesobtained=OSObtainMemoryPages(&memtocommit->pageframes[memtocommit->idx], newpagesnow, &addr->OSreservedata);
if(newpagesnow!=newpagesobtained)
{
if(newpagesobtained) OSReleaseMemoryPages(&memtocommit->pageframes[memtocommit->idx], newpagesobtained, &addr->OSreservedata);
return n;
}
for(m=memtocommit->idx; m<memtocommit->idx+newpagesobtained; m++, pf++, freespaceaddr=(void *)((size_t) freespaceaddr + PAGE_SIZE))
{
memtocommit->addrs[m]=freespaceaddr;
SETPAGEUSED(*pf, memtocommit->pageframes[m]);
}
memtocommit->idx+=newpagesobtained;
n+=newpagesobtained;
addr->usedpages+=newpagesobtained;
if(REMAPMEMORYPAGESBLOCKSIZE==memtocommit->idx)
{
if(memtodecommit->idx) OSRemapMemoryPagesOntoAddrs(memtodecommit->addrs, memtodecommit->idx, NULL, &addr->OSreservedata);
OSRemapMemoryPagesOntoAddrs(memtocommit->addrs, memtocommit->idx, memtocommit->pageframes, &addr->OSreservedata);
memtodecommit->idx=memtocommit->idx=0;
ValidatePageMappings(addr);
}
}
return n;
}
static int DetachFreePage(AddressSpaceReservation_t *RESTRICT addr, FreePageNode *RESTRICT fpn)
{
int wipeall=0;
FreePageNode *RESTRICT *RESTRICT prevnextaddr=0, *RESTRICT *RESTRICT nextprevaddr=0;
if(fpn->older)
{
assert(fpn->older->newer==fpn);
prevnextaddr=&fpn->older->newer;
}
else if(addr->oldestdirty==fpn)
{
assert(!fpn->older);
prevnextaddr=&addr->oldestdirty;
wipeall=1;
}
else if(addr->oldestclean==fpn)