summaryrefslogtreecommitdiff
path: root/sal/rtl/alloc_arena.cxx
blob: bdb7dcf24de88f7b4ae3b8660385131fe4a2aa9c (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#include "alloc_arena.hxx"

#include "alloc_impl.hxx"
#include <rtllifecycle.h>
#include <sal/macros.h>

#include <cassert>
#include <string.h>
#include <stdio.h>

/**
    @internal
*/
struct rtl_arena_list_st
{
    rtl_memory_lock_type m_lock;
    rtl_arena_type       m_arena_head;
};

static rtl_arena_list_st g_arena_list;

/**
    provided for arena_type allocations, and hash_table resizing.

    @internal
*/
static rtl_arena_type * gp_arena_arena = nullptr;

/**
    Low level virtual memory (pseudo) arena
    (platform dependent implementation)

    @internal
 */
static rtl_arena_type * gp_machdep_arena = nullptr;

rtl_arena_type * gp_default_arena = nullptr;

namespace
{

void * SAL_CALL rtl_machdep_alloc(
    rtl_arena_type * pArena,
    sal_Size *       pSize
);

void SAL_CALL rtl_machdep_free(
    rtl_arena_type * pArena,
    void *           pAddr,
    sal_Size         nSize
);

sal_Size rtl_machdep_pagesize();

int rtl_arena_segment_constructor(void * obj)
{
    rtl_arena_segment_type * segment = static_cast<rtl_arena_segment_type*>(obj);

    QUEUE_START_NAMED(segment, s);
    QUEUE_START_NAMED(segment, f);

    return 1;
}

void rtl_arena_segment_destructor(void * obj)
{
    rtl_arena_segment_type * segment = static_cast< rtl_arena_segment_type * >(
        obj);
    assert(QUEUE_STARTED_NAMED(segment, s));
    assert(QUEUE_STARTED_NAMED(segment, f));
    (void) segment; // avoid warnings
}

/**
    @precond  arena->m_lock acquired.
 */
bool rtl_arena_segment_populate(rtl_arena_type * arena)
{
    rtl_arena_segment_type *span;
    sal_Size                size = rtl_machdep_pagesize();

    span = static_cast< rtl_arena_segment_type * >(
        rtl_machdep_alloc(gp_machdep_arena, &size));
    if (span)
    {
        rtl_arena_segment_type *first, *last, *head;
        sal_Size                count = size / sizeof(rtl_arena_segment_type);

        /* insert onto reserve span list */
        QUEUE_INSERT_TAIL_NAMED(&(arena->m_segment_reserve_span_head), span, s);
        QUEUE_START_NAMED(span, f);
        span->m_addr = reinterpret_cast<sal_uIntPtr>(span);
        span->m_size = size;
        span->m_type = RTL_ARENA_SEGMENT_TYPE_SPAN;

        /* insert onto reserve list */
        head  = &(arena->m_segment_reserve_head);
        for (first = span + 1, last = span + count; first < last; ++first)
        {
            QUEUE_INSERT_TAIL_NAMED(head, first, s);
            QUEUE_START_NAMED(first, f);
            first->m_addr = 0;
            first->m_size = 0;
            first->m_type = 0;
        }
    }
    return (span != nullptr);
}

/**
    @precond  arena->m_lock acquired.
    @precond  (*ppSegment == 0)
*/
inline void rtl_arena_segment_get(
    rtl_arena_type * arena,
    rtl_arena_segment_type ** ppSegment
)
{
    rtl_arena_segment_type * head;

    assert(!*ppSegment);

    head = &(arena->m_segment_reserve_head);
    if (head->m_snext != head || rtl_arena_segment_populate (arena))
    {
        (*ppSegment) = head->m_snext;
        QUEUE_REMOVE_NAMED(*ppSegment, s);
    }
}

/**
    @precond  arena->m_lock acquired.
    @postcond (*ppSegment == 0)
 */
inline void rtl_arena_segment_put(
    rtl_arena_type * arena,
    rtl_arena_segment_type ** ppSegment
)
{
    rtl_arena_segment_type * head;

    assert(QUEUE_STARTED_NAMED(*ppSegment, s));
    assert(QUEUE_STARTED_NAMED(*ppSegment, f));

    (*ppSegment)->m_addr = 0;
    (*ppSegment)->m_size = 0;

    assert((*ppSegment)->m_type != RTL_ARENA_SEGMENT_TYPE_HEAD);
    (*ppSegment)->m_type = 0;

    /* keep as reserve */
    head = &(arena->m_segment_reserve_head);
    QUEUE_INSERT_HEAD_NAMED(head, (*ppSegment), s);

    /* clear */
    (*ppSegment) = nullptr;
}

/**
    @precond arena->m_lock acquired.
*/
inline void rtl_arena_freelist_insert (
    rtl_arena_type * arena,
    rtl_arena_segment_type * segment
)
{
    rtl_arena_segment_type * head;
    const auto bit = highbit(segment->m_size);
    assert(bit > 0);
    head = &(arena->m_freelist_head[bit - 1]);
    QUEUE_INSERT_TAIL_NAMED(head, segment, f);

    arena->m_freelist_bitmap |= head->m_size;
}

/**
    @precond arena->m_lock acquired.
*/
inline void rtl_arena_freelist_remove(
    rtl_arena_type * arena,
    rtl_arena_segment_type * segment
)
{
    if (segment->m_fnext->m_type == RTL_ARENA_SEGMENT_TYPE_HEAD &&
        segment->m_fprev->m_type == RTL_ARENA_SEGMENT_TYPE_HEAD)
    {
        rtl_arena_segment_type * head;

        head = segment->m_fprev;
        assert(arena->m_freelist_bitmap & head->m_size);
        arena->m_freelist_bitmap ^= head->m_size;
    }
    QUEUE_REMOVE_NAMED(segment, f);
}

#define RTL_ARENA_HASH_INDEX_IMPL(a, s, q, m) \
     ((((a) + ((a) >> (s)) + ((a) >> ((s) << 1))) >> (q)) & (m))

#define RTL_ARENA_HASH_INDEX(arena, addr) \
    RTL_ARENA_HASH_INDEX_IMPL((addr), (arena)->m_hash_shift, (arena)->m_quantum_shift, ((arena)->m_hash_size - 1))

/**
   @precond arena->m_lock released.
*/
void rtl_arena_hash_rescale(
    rtl_arena_type * arena,
    sal_Size new_size
)
{
    assert(new_size != 0);

    rtl_arena_segment_type ** new_table;
    sal_Size                  new_bytes;

    new_bytes = new_size * sizeof(rtl_arena_segment_type*);
    new_table = static_cast<rtl_arena_segment_type **>(rtl_arena_alloc (gp_arena_arena, &new_bytes));

    if (new_table)
    {
        rtl_arena_segment_type ** old_table;
        sal_Size                  old_size, i;

        memset (new_table, 0, new_bytes);

        RTL_MEMORY_LOCK_ACQUIRE(&(arena->m_lock));

        old_table = arena->m_hash_table;
        old_size  = arena->m_hash_size;

        arena->m_hash_table = new_table;
        arena->m_hash_size  = new_size;
        arena->m_hash_shift = highbit(arena->m_hash_size) - 1;

        for (i = 0; i < old_size; i++)
        {
            rtl_arena_segment_type * curr = old_table[i];
            while (curr)
            {
                rtl_arena_segment_type  * next = curr->m_fnext;
                rtl_arena_segment_type ** head;

                // coverity[negative_shift]
                head = &(arena->m_hash_table[RTL_ARENA_HASH_INDEX(arena, curr->m_addr)]);
                curr->m_fnext = (*head);
                (*head) = curr;

                curr = next;
            }
            old_table[i] = nullptr;
        }

        RTL_MEMORY_LOCK_RELEASE(&(arena->m_lock));

        if (old_table != arena->m_hash_table_0)
        {
            sal_Size old_bytes = old_size * sizeof(rtl_arena_segment_type*);
            rtl_arena_free (gp_arena_arena, old_table, old_bytes);
        }
    }
}

/**
    Insert arena hash, and update stats.
*/
inline void rtl_arena_hash_insert(
    rtl_arena_type * arena,
    rtl_arena_segment_type * segment
)
{
    rtl_arena_segment_type ** ppSegment;

    ppSegment = &(arena->m_hash_table[RTL_ARENA_HASH_INDEX(arena, segment->m_addr)]);

    segment->m_fnext = (*ppSegment);
    (*ppSegment) = segment;

    arena->m_stats.m_alloc     += 1;
    arena->m_stats.m_mem_alloc += segment->m_size;
}

/**
    Remove arena hash, and update stats.
*/
rtl_arena_segment_type * rtl_arena_hash_remove(
    rtl_arena_type * arena,
    sal_uIntPtr addr,
    sal_Size size
)
{
    rtl_arena_segment_type *segment, **segpp;
    sal_Size lookups = 0;

    segpp = &(arena->m_hash_table[RTL_ARENA_HASH_INDEX(arena, addr)]);
    while ((segment = *segpp))
    {
        if (segment->m_addr == addr)
        {
            *segpp = segment->m_fnext;
            segment->m_fnext = segment->m_fprev = segment;
            break;
        }

        /* update lookup miss stats */
        lookups += 1;
        segpp = &(segment->m_fnext);
    }

    assert(segment); // bad free
    if (segment)
    {
        assert(segment->m_size == size);
        (void) size; // avoid warnings

        arena->m_stats.m_free      += 1;
        arena->m_stats.m_mem_alloc -= segment->m_size;

        if (lookups > 1)
        {
            sal_Size nseg = (sal_Size)(arena->m_stats.m_alloc - arena->m_stats.m_free);
            if (nseg > 4 * arena->m_hash_size)
            {
                if (!(arena->m_flags & RTL_ARENA_FLAG_RESCALE))
                {
                    sal_Size ave = nseg >> arena->m_hash_shift;
                    assert(ave != 0);
                    sal_Size new_size = arena->m_hash_size << (highbit(ave) - 1);

                    arena->m_flags |= RTL_ARENA_FLAG_RESCALE;
                    RTL_MEMORY_LOCK_RELEASE(&(arena->m_lock));
                    rtl_arena_hash_rescale (arena, new_size);
                    RTL_MEMORY_LOCK_ACQUIRE(&(arena->m_lock));
                    arena->m_flags &= ~RTL_ARENA_FLAG_RESCALE;
                }
            }
        }
    }

    return segment;
}

/**
    allocate (and remove) segment from freelist

    @precond arena->m_lock acquired
    @precond (*ppSegment == 0)
*/
bool rtl_arena_segment_alloc(
    rtl_arena_type * arena,
    sal_Size size,
    rtl_arena_segment_type ** ppSegment
)
{
    int index = 0;

    assert(!*ppSegment);
    if (!RTL_MEMORY_ISP2(size))
    {
        unsigned int msb = highbit(size);
        if (RTL_ARENA_FREELIST_SIZE == msb)
        {
            /* highest possible freelist: fall back to first fit */
            rtl_arena_segment_type *head, *segment;

            head = &(arena->m_freelist_head[msb - 1]);
            for (segment = head->m_fnext; segment != head; segment = segment->m_fnext)
            {
                if (segment->m_size >= size)
                {
                    /* allocate first fit segment */
                    (*ppSegment) = segment;
                    break;
                }
            }
            goto dequeue_and_leave;
        }

        /* roundup to next power of 2 */
        size = (((sal_Size)1) << msb);
    }

    index = lowbit(RTL_MEMORY_P2ALIGN(arena->m_freelist_bitmap, size));
    if (index > 0)
    {
        /* instant fit: allocate first free segment */
        rtl_arena_segment_type *head;

        head = &(arena->m_freelist_head[index - 1]);
        (*ppSegment) = head->m_fnext;
        assert((*ppSegment) != head);
    }

dequeue_and_leave:
    if (*ppSegment)
    {
        /* remove from freelist */
        rtl_arena_freelist_remove (arena, (*ppSegment));
    }
    return (*ppSegment != nullptr);
}

/**
    import new (span) segment from source arena

    @precond arena->m_lock acquired
    @precond (*ppSegment == 0)
*/
int rtl_arena_segment_create(
    rtl_arena_type * arena,
    sal_Size size,
    rtl_arena_segment_type ** ppSegment
)
{
    assert(!*ppSegment);
    if (arena->m_source_alloc)
    {
        rtl_arena_segment_get (arena, ppSegment);
        if (*ppSegment)
        {
            rtl_arena_segment_type * span = nullptr;
            rtl_arena_segment_get (arena, &span);
            if (span)
            {
                /* import new span from source arena */
                RTL_MEMORY_LOCK_RELEASE(&(arena->m_lock));

                span->m_size = size;
                span->m_addr = reinterpret_cast<sal_uIntPtr>(
                    (arena->m_source_alloc)(
                        arena->m_source_arena, &(span->m_size)));

                RTL_MEMORY_LOCK_ACQUIRE(&(arena->m_lock));
                if (span->m_addr != 0)
                {
                    /* insert onto segment list, update stats */
                    span->m_type = RTL_ARENA_SEGMENT_TYPE_SPAN;
                    QUEUE_INSERT_HEAD_NAMED(&(arena->m_segment_head), span, s);
                    arena->m_stats.m_mem_total += span->m_size;

                    (*ppSegment)->m_addr = span->m_addr;
                    (*ppSegment)->m_size = span->m_size;
                    (*ppSegment)->m_type = RTL_ARENA_SEGMENT_TYPE_FREE;
                    QUEUE_INSERT_HEAD_NAMED(span, (*ppSegment), s);

                    /* report success */
                    return 1;
                }
                rtl_arena_segment_put (arena, &span);
            }
            rtl_arena_segment_put (arena, ppSegment);
        }
    }
    return 0;
}

/**
    mark as free and join with adjacent free segment(s)

    @precond arena->m_lock acquired
    @precond segment marked 'used'
*/
void rtl_arena_segment_coalesce(
    rtl_arena_type * arena,
    rtl_arena_segment_type * segment
)
{
    rtl_arena_segment_type *next, *prev;

    /* mark segment free */
    assert(segment->m_type == RTL_ARENA_SEGMENT_TYPE_USED);
    segment->m_type = RTL_ARENA_SEGMENT_TYPE_FREE;

    /* try to merge w/ next segment */
    next = segment->m_snext;
    if (next->m_type == RTL_ARENA_SEGMENT_TYPE_FREE)
    {
        assert(segment->m_addr + segment->m_size == next->m_addr);
        segment->m_size += next->m_size;

        /* remove from freelist */
        rtl_arena_freelist_remove (arena, next);

        /* remove from segment list */
        QUEUE_REMOVE_NAMED(next, s);

        /* release segment descriptor */
        rtl_arena_segment_put (arena, &next);
    }

    /* try to merge w/ prev segment */
    prev = segment->m_sprev;
    if (prev->m_type == RTL_ARENA_SEGMENT_TYPE_FREE)
    {
        assert(prev->m_addr + prev->m_size == segment->m_addr);
        segment->m_addr  = prev->m_addr;
        segment->m_size += prev->m_size;

        /* remove from freelist */
        rtl_arena_freelist_remove (arena, prev);

        /* remove from segment list */
        QUEUE_REMOVE_NAMED(prev, s);

        /* release segment descriptor */
        rtl_arena_segment_put (arena, &prev);
    }
}

void rtl_arena_constructor(void * obj)
{
    rtl_arena_type * arena = static_cast<rtl_arena_type*>(obj);
    rtl_arena_segment_type * head;
    size_t i;

    memset (arena, 0, sizeof(rtl_arena_type));

    QUEUE_START_NAMED(arena, arena_);

    RTL_MEMORY_LOCK_INIT(&(arena->m_lock));

    head = &(arena->m_segment_reserve_span_head);
    rtl_arena_segment_constructor (head);
    head->m_type = RTL_ARENA_SEGMENT_TYPE_HEAD;

    head = &(arena->m_segment_reserve_head);
    rtl_arena_segment_constructor (head);
    head->m_type = RTL_ARENA_SEGMENT_TYPE_HEAD;

    head = &(arena->m_segment_head);
    rtl_arena_segment_constructor (head);
    head->m_type = RTL_ARENA_SEGMENT_TYPE_HEAD;

    for (i = 0; i < RTL_ARENA_FREELIST_SIZE; i++)
    {
        head = &(arena->m_freelist_head[i]);
        rtl_arena_segment_constructor (head);

        head->m_size = (((sal_Size)1) << i);
        head->m_type = RTL_ARENA_SEGMENT_TYPE_HEAD;
    }

    arena->m_hash_table = arena->m_hash_table_0;
    arena->m_hash_size  = RTL_ARENA_HASH_SIZE;
    arena->m_hash_shift = highbit(arena->m_hash_size) - 1;
}

void rtl_arena_destructor(void * obj)
{
    rtl_arena_type * arena = static_cast<rtl_arena_type*>(obj);
    rtl_arena_segment_type * head;
    size_t i;

    assert(QUEUE_STARTED_NAMED(arena, arena_));

    RTL_MEMORY_LOCK_DESTROY(&(arena->m_lock));

    head = &(arena->m_segment_reserve_span_head);
    assert(head->m_type == RTL_ARENA_SEGMENT_TYPE_HEAD);
    rtl_arena_segment_destructor (head);

    head = &(arena->m_segment_reserve_head);
    assert(head->m_type == RTL_ARENA_SEGMENT_TYPE_HEAD);
    rtl_arena_segment_destructor (head);

    head = &(arena->m_segment_head);
    assert(head->m_type == RTL_ARENA_SEGMENT_TYPE_HEAD);
    rtl_arena_segment_destructor (head);

    for (i = 0; i < RTL_ARENA_FREELIST_SIZE; i++)
    {
        head = &(arena->m_freelist_head[i]);

        assert(head->m_size == (((sal_Size)1) << i));
        assert(head->m_type == RTL_ARENA_SEGMENT_TYPE_HEAD);

        rtl_arena_segment_destructor (head);
    }

    assert(arena->m_hash_table == arena->m_hash_table_0);
    assert(arena->m_hash_size  == RTL_ARENA_HASH_SIZE);
    assert(arena->m_hash_shift == highbit(arena->m_hash_size) - 1);
}

#if defined __GNUC__ && __GNUC__ >= 7
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wformat-truncation"
#endif
rtl_arena_type * rtl_arena_activate(
    rtl_arena_type * arena,
    const char *     name,
    sal_Size         quantum,
    sal_Size         quantum_cache_max,
    rtl_arena_type * source_arena,
    void * (SAL_CALL * source_alloc)(rtl_arena_type *, sal_Size *),
    void   (SAL_CALL * source_free) (rtl_arena_type *, void *, sal_Size)
)
{
    assert(arena);
    if (arena)
    {
        (void) snprintf (arena->m_name, sizeof(arena->m_name), "%s", name);

        if (!RTL_MEMORY_ISP2(quantum))
        {
            /* roundup to next power of 2 */
            quantum = (((sal_Size)1) << highbit(quantum));
        }
        quantum_cache_max = RTL_MEMORY_P2ROUNDUP(quantum_cache_max, quantum);

        arena->m_quantum = quantum;
        arena->m_quantum_shift = highbit(arena->m_quantum) - 1;
        arena->m_qcache_max = quantum_cache_max;

        arena->m_source_arena = source_arena;
        arena->m_source_alloc = source_alloc;
        arena->m_source_free  = source_free;

        if (arena->m_qcache_max > 0)
        {
            char namebuf[RTL_ARENA_NAME_LENGTH + 1];
            int  i, n = (arena->m_qcache_max >> arena->m_quantum_shift);

            sal_Size size = n * sizeof(rtl_cache_type*);
            arena->m_qcache_ptr = static_cast<rtl_cache_type**>(rtl_arena_alloc (gp_arena_arena, &size));
            if (!(arena->m_qcache_ptr))
            {
                /* out of memory */
                return nullptr;
            }
            for (i = 1; i <= n; i++)
            {
                size = i * arena->m_quantum;
                (void) snprintf (namebuf, sizeof(namebuf), "%s_%" SAL_PRIuUINTPTR, arena->m_name, size);
#if defined __GNUC__ && __GNUC__ >= 7
#pragma GCC diagnostic pop
#endif
                arena->m_qcache_ptr[i - 1] = rtl_cache_create(namebuf, size, 0, nullptr, nullptr, nullptr, nullptr, arena, RTL_CACHE_FLAG_QUANTUMCACHE);
            }
        }

        /* insert into arena list */
        RTL_MEMORY_LOCK_ACQUIRE(&(g_arena_list.m_lock));
        QUEUE_INSERT_TAIL_NAMED(&(g_arena_list.m_arena_head), arena, arena_);
        RTL_MEMORY_LOCK_RELEASE(&(g_arena_list.m_lock));
    }
    return arena;
}

void rtl_arena_deactivate(rtl_arena_type * arena)
{
    rtl_arena_segment_type * head, * segment;

    /* remove from arena list */
    RTL_MEMORY_LOCK_ACQUIRE(&(g_arena_list.m_lock));
    QUEUE_REMOVE_NAMED(arena, arena_);
    RTL_MEMORY_LOCK_RELEASE(&(g_arena_list.m_lock));

    /* cleanup quantum cache(s) */
    if (arena->m_qcache_max > 0 && arena->m_qcache_ptr)
    {
        int  i, n = (arena->m_qcache_max >> arena->m_quantum_shift);
        for (i = 1; i <= n; i++)
        {
            if (arena->m_qcache_ptr[i-1])
            {
                rtl_cache_destroy (arena->m_qcache_ptr[i-1]);
                arena->m_qcache_ptr[i-1] = nullptr;
            }
        }
        rtl_arena_free (
            gp_arena_arena,
            arena->m_qcache_ptr,
            n * sizeof(rtl_cache_type*));

        arena->m_qcache_ptr = nullptr;
    }

    /* check for leaked segments */
    if (arena->m_stats.m_alloc > arena->m_stats.m_free)
    {
        sal_Size i, n;

        /* cleanup still used segment(s) */
        for (i = 0, n = arena->m_hash_size; i < n; i++)
        {
            while ((segment = arena->m_hash_table[i]))
            {
                /* pop from hash table */
                arena->m_hash_table[i] = segment->m_fnext;
                segment->m_fnext = segment->m_fprev = segment;

                /* coalesce w/ adjacent free segment(s) */
                rtl_arena_segment_coalesce (arena, segment);

                /* insert onto freelist */
                rtl_arena_freelist_insert (arena, segment);
            }
        }
    }

    /* cleanup hash table */
    if (arena->m_hash_table != arena->m_hash_table_0)
    {
        rtl_arena_free(
            gp_arena_arena,
            arena->m_hash_table,
            arena->m_hash_size * sizeof(rtl_arena_segment_type*));

        arena->m_hash_table = arena->m_hash_table_0;
        arena->m_hash_size = RTL_ARENA_HASH_SIZE;
        arena->m_hash_shift = highbit(arena->m_hash_size) - 1;
    }

    /* cleanup segment list */
    head = &(arena->m_segment_head);
    for (segment = head->m_snext; segment != head; segment = head->m_snext)
    {
        if (segment->m_type == RTL_ARENA_SEGMENT_TYPE_FREE)
        {
            /* remove from freelist */
            rtl_arena_freelist_remove (arena, segment);
        }
        else
        {
            /* can have only free and span segments here */
            assert(segment->m_type == RTL_ARENA_SEGMENT_TYPE_SPAN);
        }

        /* remove from segment list */
        QUEUE_REMOVE_NAMED(segment, s);

        /* release segment descriptor */
        rtl_arena_segment_put (arena, &segment);
    }

    /* cleanup segment reserve list */
    head = &(arena->m_segment_reserve_head);
    for (segment = head->m_snext; segment != head; segment = head->m_snext)
    {
        /* remove from segment list */
        QUEUE_REMOVE_NAMED(segment, s);
    }

    /* cleanup segment reserve span(s) */
    head = &(arena->m_segment_reserve_span_head);
    for (segment = head->m_snext; segment != head; segment = head->m_snext)
    {
        /* can have only span segments here */
        assert(segment->m_type == RTL_ARENA_SEGMENT_TYPE_SPAN);

        /* remove from segment list */
        QUEUE_REMOVE_NAMED(segment, s);

        /* return span to g_machdep_arena */
        rtl_machdep_free (gp_machdep_arena, reinterpret_cast<void*>(segment->m_addr), segment->m_size);
    }
}

} // namespace

rtl_arena_type * SAL_CALL rtl_arena_create(
    const char *       name,
    sal_Size           quantum,
    sal_Size           quantum_cache_max,
    rtl_arena_type *   source_arena,
    void * (SAL_CALL * source_alloc)(rtl_arena_type *, sal_Size *),
    void   (SAL_CALL * source_free) (rtl_arena_type *, void *, sal_Size),
    SAL_UNUSED_PARAMETER int
) SAL_THROW_EXTERN_C()
{
    rtl_arena_type * result = nullptr;
    sal_Size         size   = sizeof(rtl_arena_type);

try_alloc:
    result = static_cast<rtl_arena_type*>(rtl_arena_alloc (gp_arena_arena, &size));
    if (result)
    {
        rtl_arena_type * arena = result;
        rtl_arena_constructor (arena);

        if (!source_arena)
        {
            assert(gp_default_arena);
            source_arena = gp_default_arena;
        }

        result = rtl_arena_activate (
            arena,
            name,
            quantum,
            quantum_cache_max,
            source_arena,
            source_alloc,
            source_free
        );

        if (!result)
        {
            rtl_arena_deactivate (arena);
            rtl_arena_destructor (arena);
            rtl_arena_free (gp_arena_arena, arena, size);
        }
    }
    else if (!gp_arena_arena)
    {
        ensureArenaSingleton();
        if (gp_arena_arena)
        {
            /* try again */
            goto try_alloc;
        }
    }
    return result;
}

void SAL_CALL rtl_arena_destroy(rtl_arena_type * arena) SAL_THROW_EXTERN_C()
{
    if (arena)
    {
        rtl_arena_deactivate (arena);
        rtl_arena_destructor (arena);
        rtl_arena_free (gp_arena_arena, arena, sizeof(rtl_arena_type));
    }
}

void * SAL_CALL rtl_arena_alloc(
    rtl_arena_type * arena,
    sal_Size *       pSize
) SAL_THROW_EXTERN_C()
{
    void * addr = nullptr;

    if (arena && pSize)
    {
        sal_Size size;

        size = RTL_MEMORY_ALIGN(*pSize, arena->m_quantum);
        if (size > arena->m_qcache_max)
        {
            /* allocate from segment list */
            rtl_arena_segment_type *segment = nullptr;

            RTL_MEMORY_LOCK_ACQUIRE(&(arena->m_lock));
            if (rtl_arena_segment_alloc (arena, size, &segment) ||
                rtl_arena_segment_create(arena, size, &segment)    )
            {
                /* shrink to fit */
                sal_Size oversize;

                /* mark segment used */
                assert(segment->m_type == RTL_ARENA_SEGMENT_TYPE_FREE);
                segment->m_type = RTL_ARENA_SEGMENT_TYPE_USED;

                /* resize */
                assert(segment->m_size >= size);
                oversize = segment->m_size - size;
                if (oversize >= arena->m_quantum && oversize >= arena->m_qcache_max)
                {
                    rtl_arena_segment_type * remainder = nullptr;
                    rtl_arena_segment_get (arena, &remainder);
                    if (remainder)
                    {
                        segment->m_size = size;

                        remainder->m_addr = segment->m_addr + segment->m_size;
                        remainder->m_size = oversize;
                        remainder->m_type = RTL_ARENA_SEGMENT_TYPE_FREE;
                        QUEUE_INSERT_HEAD_NAMED(segment, remainder, s);

                        rtl_arena_freelist_insert (arena, remainder);
                    }
                }

                rtl_arena_hash_insert (arena, segment);

                (*pSize) = segment->m_size;
                addr = reinterpret_cast<void*>(segment->m_addr);
            }
            RTL_MEMORY_LOCK_RELEASE(&(arena->m_lock));
        }
        else if (size > 0)
        {
            /* allocate from quantum cache(s) */
            int index = (size >> arena->m_quantum_shift) - 1;
            assert(arena->m_qcache_ptr[index]);

            addr = rtl_cache_alloc (arena->m_qcache_ptr[index]);
            if (addr)
                (*pSize) = size;
        }
    }
    return addr;
}

void SAL_CALL rtl_arena_free (
    rtl_arena_type * arena,
    void *           addr,
    sal_Size         size
) SAL_THROW_EXTERN_C()
{
    if (arena)
    {
        size = RTL_MEMORY_ALIGN(size, arena->m_quantum);
        if (size > arena->m_qcache_max)
        {
            /* free to segment list */
            rtl_arena_segment_type * segment;

            RTL_MEMORY_LOCK_ACQUIRE(&(arena->m_lock));

            segment = rtl_arena_hash_remove (arena, reinterpret_cast<sal_uIntPtr>(addr), size);
            if (segment)
            {
                rtl_arena_segment_type *next, *prev;

                /* coalesce w/ adjacent free segment(s) */
                rtl_arena_segment_coalesce (arena, segment);

                /* determine (new) next and prev segment */
                next = segment->m_snext;
                prev = segment->m_sprev;

                /* entire span free when prev is a span, and next is either a span or a list head */
                if (prev->m_type == RTL_ARENA_SEGMENT_TYPE_SPAN &&
                    ((next->m_type == RTL_ARENA_SEGMENT_TYPE_SPAN)  ||
                     (next->m_type == RTL_ARENA_SEGMENT_TYPE_HEAD)))
                {
                    assert(
                        prev->m_addr == segment->m_addr
                        && prev->m_size == segment->m_size);

                    if (arena->m_source_free)
                    {
                        addr = reinterpret_cast<void*>(prev->m_addr);
                        size = prev->m_size;

                        /* remove from segment list */
                        QUEUE_REMOVE_NAMED(segment, s);

                        /* release segment descriptor */
                        rtl_arena_segment_put (arena, &segment);

                        /* remove from segment list */
                        QUEUE_REMOVE_NAMED(prev, s);

                        /* release (span) segment descriptor */
                        rtl_arena_segment_put (arena, &prev);

                        /* update stats, return span to source arena */
                        arena->m_stats.m_mem_total -= size;
                        RTL_MEMORY_LOCK_RELEASE(&(arena->m_lock));

                        (arena->m_source_free)(arena->m_source_arena, addr, size);
                        return;
                    }
                }

                /* insert onto freelist */
                rtl_arena_freelist_insert (arena, segment);
            }

            RTL_MEMORY_LOCK_RELEASE(&(arena->m_lock));
        }
        else if (size > 0)
        {
            /* free to quantum cache(s) */
            int index = (size >> arena->m_quantum_shift) - 1;
            assert(arena->m_qcache_ptr[index]);

            rtl_cache_free (arena->m_qcache_ptr[index], addr);
        }
    }
}

#if defined(SAL_UNX)
#include <sys/mman.h>
#elif defined(SAL_W32)
#define MAP_FAILED nullptr
#endif /* SAL_UNX || SAL_W32 */

namespace
{

void * SAL_CALL rtl_machdep_alloc(
    rtl_arena_type * pArena,
    sal_Size *       pSize
)
{
    void *   addr;
    sal_Size size = (*pSize);

    assert(pArena == gp_machdep_arena);

#if defined(__sun) && defined(SPARC)
    /* see @ mmap(2) man pages */
    size += (pArena->m_quantum + pArena->m_quantum); /* "red-zone" pages */
    if (size > (4 << 20))
        size = RTL_MEMORY_P2ROUNDUP(size, (4 << 20));
    else if (size > (512 << 10))
        size = RTL_MEMORY_P2ROUNDUP(size, (512 << 10));
    else
        size = RTL_MEMORY_P2ROUNDUP(size, (64 << 10));
    size -= (pArena->m_quantum + pArena->m_quantum); /* "red-zone" pages */
#else
    /* default allocation granularity */
    if (pArena->m_quantum < (64 << 10))
    {
        size = RTL_MEMORY_P2ROUNDUP(size, (64 << 10));
    }
    else
    {
        size = RTL_MEMORY_P2ROUNDUP(size, pArena->m_quantum);
    }
#endif

#if defined(SAL_UNX)
    addr = mmap (nullptr, (size_t)size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0);
#elif defined(SAL_W32)
    addr = VirtualAlloc (nullptr, (SIZE_T)size, MEM_COMMIT, PAGE_READWRITE);
#endif /* (SAL_UNX || SAL_W32) */

    if (addr != MAP_FAILED)
    {
        pArena->m_stats.m_alloc += 1;
        pArena->m_stats.m_mem_total += size;
        pArena->m_stats.m_mem_alloc += size;

        (*pSize) = size;
        return addr;
    }
    return nullptr;
}

void SAL_CALL rtl_machdep_free(
    rtl_arena_type * pArena,
    void *           pAddr,
    sal_Size         nSize
)
{
    assert(pArena == gp_machdep_arena);

    pArena->m_stats.m_free += 1;
    pArena->m_stats.m_mem_total -= nSize;
    pArena->m_stats.m_mem_alloc -= nSize;

#if defined(SAL_UNX)
    (void) munmap(pAddr, nSize);
#elif defined(SAL_W32)
    (void) VirtualFree (pAddr, (SIZE_T)(0), MEM_RELEASE);
#endif /* (SAL_UNX || SAL_W32) */
}

sal_Size rtl_machdep_pagesize()
{
#if defined(SAL_UNX)
#if defined(FREEBSD) || defined(NETBSD) || defined(DRAGONFLY)
    return (sal_Size)getpagesize();
#else  /* POSIX */
    return (sal_Size)sysconf(_SC_PAGESIZE);
#endif /* xBSD || POSIX */
#elif defined(SAL_W32)
    SYSTEM_INFO info;
    GetSystemInfo (&info);
    return (sal_Size)info.dwPageSize;
#endif /* (SAL_UNX || SAL_W32) */
}

} //namespace

void rtl_arena_init()
{
    {
        /* list of arenas */
        RTL_MEMORY_LOCK_INIT(&(g_arena_list.m_lock));
        rtl_arena_constructor (&(g_arena_list.m_arena_head));
    }
    {
        /* machdep (pseudo) arena */
        static rtl_arena_type g_machdep_arena;

        assert(!gp_machdep_arena);
        rtl_arena_constructor (&g_machdep_arena);

        gp_machdep_arena = rtl_arena_activate (
            &g_machdep_arena,
            "rtl_machdep_arena",
            rtl_machdep_pagesize(),
            0,       /* no quantum caching */
            nullptr, nullptr, nullptr  /* no source */
        );
        assert(gp_machdep_arena);
    }
    {
        /* default arena */
        static rtl_arena_type g_default_arena;

        assert(!gp_default_arena);
        rtl_arena_constructor (&g_default_arena);

        gp_default_arena = rtl_arena_activate (
            &g_default_arena,
            "rtl_default_arena",
            rtl_machdep_pagesize(),
            0,                 /* no quantum caching */
            gp_machdep_arena,  /* source */
            rtl_machdep_alloc,
            rtl_machdep_free
        );
        assert(gp_default_arena);
    }
    {
        /* arena internal arena */
        static rtl_arena_type g_arena_arena;

        assert(!gp_arena_arena);
        rtl_arena_constructor (&g_arena_arena);

        gp_arena_arena = rtl_arena_activate(
            &g_arena_arena,
            "rtl_arena_internal_arena",
            64,                /* quantum */
            0,                 /* no quantum caching */
            gp_default_arena,  /* source */
            rtl_arena_alloc,
            rtl_arena_free
        );
        assert(gp_arena_arena);
    }
}

void rtl_arena_fini()
{
    if (gp_arena_arena)
    {
        rtl_arena_type * arena, * head;

        RTL_MEMORY_LOCK_ACQUIRE(&(g_arena_list.m_lock));
        head = &(g_arena_list.m_arena_head);

        for (arena = head->m_arena_next; arena != head; arena = arena->m_arena_next)
        {
            // noop
        }
        RTL_MEMORY_LOCK_RELEASE(&(g_arena_list.m_lock));
    }
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */