summaryrefslogtreecommitdiffstats
path: root/src/lib/kStuff/kHlp/Bare/kHlpBareHeap.c
blob: d5e44b4e77a3b1df54ac0a45a5b22c5f741087eb (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
/* $Id: kHlpBareHeap.c 29 2009-07-01 20:30:29Z bird $ */
/** @file
 * kHlpBare - Heap.
 */

/*
 * Copyright (c) 2006-2007 Knut St. Osmundsen <bird-kStuff-spamix@anduin.net>
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * 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 AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 */

#define KHLPHEAP_STRICT

/*******************************************************************************
*   Header Files                                                               *
*******************************************************************************/
#include <k/kHlpAlloc.h>
#include <k/kHlpString.h>
#include <k/kHlpAssert.h>

#if K_OS == K_OS_OS2
# define INCL_BASE
# define INCL_ERRORS
# include <os2.h>

#elif  K_OS == K_OS_WINDOWS
# include <Windows.h>

#else
# include <k/kHlpAlloc.h>
#endif


/*******************************************************************************
*   Structures and Typedefs                                                    *
*******************************************************************************/
/**
 * A heap block.
 */
typedef struct KHLPHEAPBLOCK
{
    /** Next block in the global list. */
    struct KHLPHEAPBLOCK   *pNext;
    /** Previous block in the global list. */
    struct KHLPHEAPBLOCK   *pPrev;
    /** The size of this block including this header. */
    KSIZE                   cb;
    /** The flags. */
    KSIZE                   fFlags;
} KHLPHEAPBLOCK, *PKHLPHEAPBLOCK;

/** Indicates whether the block is free (set) or allocated (clear). */
#define KHLPHEAPBLOCK_FLAG_FREE     ((KSIZE)1)
/** Valid flag mask. */
#define KHLPHEAPBLOCK_FLAG_MASK     ((KSIZE)1)

/** Checks if the block is freed. */
#define KHLPHEAPBLOCK_IS_FREE(pB)       ( (pB)->fFlags & KHLPHEAPBLOCK_FLAG_FREE )
/** Check if the block is allocated. */
#define KHLPHEAPBLOCK_IS_ALLOCATED(pB)  !KHLPHEAPBLOCK_IS_FREE(pB)
/** Checks if the two blocks are adjacent.
 * Assumes pB1 < pB2. */
#define KHLPHEAPBLOCK_IS_ADJACENT(pB1, pB2) \
    ( ((KUPTR)(pB1) + (pB1)->cb) == (KUPTR)(pB2) )

/** The block alignment. */
#define KHLPHEAPBLOCK_ALIGNMENT     sizeof(KHLPHEAPBLOCK)

/** @def KHLPHEAP_ASSERT
 * Heap assertion. */
/** @def KHLPHEAP_ASSERT_BLOCK
 * Assert that a heap block is valid. */
/** @def KHLPHEAP_ASSERT_FREE
 * Assert that a heap free block is valid. */
#ifdef KHLPHEAP_STRICT
# define KHLPHEAP_ASSERT(expr)      kHlpAssert(expr)

# define KHLPHEAP_ASSERT_BLOCK(pHeap, pBlock) \
    do { \
        KHLPHEAP_ASSERT(!((pBlock)->fFlags & ~KHLPHEAPBLOCK_FLAG_MASK)); \
        KHLPHEAP_ASSERT(!((pBlock)->cb & (KHLPHEAPBLOCK_ALIGNMENT - 1))); \
        KHLPHEAP_ASSERT((KUPTR)(pBlock)->pPrev < (KUPTR)(pBlock)); \
        KHLPHEAP_ASSERT((KUPTR)(pBlock)->pNext > (KUPTR)(pBlock) || !(pBlock)->pNext); \
    } while (0)

# define KHLPHEAP_ASSERT_FREE(pHeap, pFree) \
    do { \
        KHLPHEAP_ASSERT_BLOCK(pHeap, &(pFree)->Core); \
        KHLPHEAP_ASSERT((KUPTR)(pFree)->pPrev < (KUPTR)(pFree)); \
        KHLPHEAP_ASSERT((KUPTR)(pFree)->pNext > (KUPTR)(pFree) || !(pFree)->pNext); \
    } while (0)

#else
# define KHLPHEAP_ASSERT(expr)          do { } while (0)
# define KHLPHEAP_ASSERT_BLOCK(pH, pB)  do { } while (0)
# define KHLPHEAP_ASSERT_FREE(pH, pF)   do { } while (0)
#endif


/**
 * A free heap block.
 */
typedef struct KHLPHEAPFREE
{
    /** The core bit which we have in common with used blocks. */
    KHLPHEAPBLOCK           Core;
    /** The next free block. */
    struct KHLPHEAPFREE    *pNext;
    /** The previous free block. */
    struct KHLPHEAPFREE    *pPrev;
} KHLPHEAPFREE, *PKHLPHEAPFREE;


/**
 * A heap segment.
 */
typedef struct KHLPHEAPSEG
{
    /** The base address of the segment. */
    void                   *pvBase;
    /** The length of the segment (in bytes). */
    KSIZE                   cb;
} KHLPHEAPSEG, *PKHLPHEAPSEG;

/**
 * Bundle of heap segments.
 */
typedef struct KHLPHEAPSEGS
{
    /** Pointer to the next segment bundle. */
    struct KHLPHEAPSEGS    *pNext;
    /** The number of segments used. */
    KU32                    cSegs;
    /** Array of chunks. */
    KHLPHEAPSEG             aSegs[64];
} KHLPHEAPSEGS, *PKHLPHEAPSEGS;


/**
 * Heap anchor block.
 */
typedef struct KHLPHEAPANCHOR
{
    /** Head of the block list. */
    PKHLPHEAPBLOCK          pHead;
    /** Tail of the block list. */
    PKHLPHEAPBLOCK          pTail;
    /** Head of the free list. */
    PKHLPHEAPFREE           pFreeHead;
    /** Head segment bundle.
     * The order of this list is important, but a bit peculiar.
     * Logically, SegsHead::pNext is the tail pointer. */
    KHLPHEAPSEGS            SegsHead;
} KHLPHEAPANCHOR, *PKHLPHEAPANCHOR;



/*******************************************************************************
*   Global Variables                                                           *
*******************************************************************************/
/** The heap anchor block. */
static KHLPHEAPANCHOR       g_Heap;


/*******************************************************************************
*   Internal Functions                                                         *
*******************************************************************************/
static int      khlpHeapInit(PKHLPHEAPANCHOR pHeap);
static void     khlpHeapDelete(PKHLPHEAPANCHOR pHeap);
static void *   khlpHeapAlloc(PKHLPHEAPANCHOR pHeap, KSIZE cb);
static void     khlpHeapFree(PKHLPHEAPANCHOR pHeap, void *pv);
static KSIZE    khlpHeapBlockSize(PKHLPHEAPANCHOR pHeap, void *pv);
static void     khlpHeapDonate(PKHLPHEAPANCHOR pHeap, void *pv, KSIZE cb);
static int      khlpHeapSegAlloc(PKHLPHEAPSEG pSeg, KSIZE cb);
static void     khlpHeapSegFree(PKHLPHEAPSEG pSeg);


/**
 * Initializes the kLdr heap.
 *
 * @returns 0 on success, non-zero OS specific status code on failure.
 */
KHLP_DECL(int) kHlpHeapInit(void)
{
    return khlpHeapInit(&g_Heap);
}


/**
 * Terminates the kLdr heap.
 */
KHLP_DECL(void) kHlpHeapTerm(void)
{
    khlpHeapDelete(&g_Heap);
}


KHLP_DECL(void *) kHlpAlloc(KSIZE cb)
{
    return khlpHeapAlloc(&g_Heap, cb);
}


KHLP_DECL(void *) kHlpAllocZ(KSIZE cb)
{
    void *pv = khlpHeapAlloc(&g_Heap, cb);
    if (pv)
        kHlpMemSet(pv, 0, cb);
    return pv;
}


KHLP_DECL(void *) kHlpDup(const void *pv, KSIZE cb)
{
    void *pvNew = khlpHeapAlloc(&g_Heap, cb);
    if (pvNew)
        kHlpMemCopy(pvNew, pv, cb);
    return pvNew;
}


KHLP_DECL(char *) kHlpStrDup(const char *psz)
{
    return (char *)kHlpDup(psz, kHlpStrLen(psz) + 1);
}


KHLP_DECL(void *) kHlpRealloc(void *pv, KSIZE cb)
{
    void *pvNew;
    if (!cb)
    {
        kHlpFree(pv);
        pvNew = NULL;
    }
    else if (!pv)
        pvNew = khlpHeapAlloc(&g_Heap, cb);
    else
    {
        KSIZE cbToCopy = khlpHeapBlockSize(&g_Heap, pv);
        pvNew = khlpHeapAlloc(&g_Heap, cb);
        if (pvNew)
        {
            kHlpMemCopy(pvNew, pv, cb);
            kHlpFree(pv);
        }
    }
    return pvNew;
}


KHLP_DECL(void) kHlpFree(void *pv)
{
    khlpHeapFree(&g_Heap, pv);
}


/**
 * Donates memory to the heap.
 *
 * @param   pv      The address of the memory.
 * @param   cb      The amount of memory.
 */
KHLP_DECL(void) kHlpHeapDonate(void *pv, KSIZE cb)
{
    khlpHeapDonate(&g_Heap, pv, cb);
}



/**
 * Initializes the heap anchor.
 *
 * @returns 0 on success, non-zero on failure.
 * @param   pHeap   The heap anchor to be initialized.
 */
static int khlpHeapInit(PKHLPHEAPANCHOR pHeap)
{
    pHeap->pHead = NULL;
    pHeap->pTail = NULL;
    pHeap->pFreeHead = NULL;
    pHeap->SegsHead.pNext = NULL;
    pHeap->SegsHead.cSegs = 0;
    return 0;
}


/**
 * Deletes a heap.
 * This will free all resources (memory) associated with the heap.
 *
 * @param   pHeap   The heap to be deleted.
 */
static void khlpHeapDelete(PKHLPHEAPANCHOR pHeap)
{
    /*
     * Free the segments, LIFO order.
     * The head element is the last to be free, while the
     * head.pNext is really the tail pointer - neat or what?
     */
    while (     pHeap->SegsHead.cSegs
           ||   pHeap->SegsHead.pNext)
    {
        /* find the tail. */
        KU32            iSeg;
        PKHLPHEAPSEGS   pSegs = pHeap->SegsHead.pNext;
        if (!pSegs)
            pSegs = &pHeap->SegsHead;
        else
        {
            pHeap->SegsHead.pNext = pSegs->pNext;
            pSegs->pNext = NULL;
        }

        /* free the segments */
        iSeg = pSegs->cSegs;
        while (iSeg-- > 0)
            khlpHeapSegFree(&pSegs->aSegs[iSeg]);
        pSegs->cSegs = 0;
    }

    /* Zap the anchor. */
    pHeap->pHead = NULL;
    pHeap->pTail = NULL;
    pHeap->pFreeHead = NULL;
    pHeap->SegsHead.pNext = NULL;
    pHeap->SegsHead.cSegs = 0;
}


/**
 * Internal heap block allocator.
 */
static void *   kldrHeapAllocSub(PKHLPHEAPANCHOR pHeap, KSIZE cb)
{
    /*
     * Find a fitting free block.
     */
    const KSIZE     cbReq = K_ALIGN_Z(cb + sizeof(KHLPHEAPBLOCK), KHLPHEAPBLOCK_ALIGNMENT);
    PKHLPHEAPFREE   pCur = pHeap->pFreeHead;
    while (pCur)
    {
        if (pCur->Core.cb >= cbReq)
        {
            if (pCur->Core.cb != cbReq)
            {
                /* check and see if there is a better match close by. */
                PKHLPHEAPFREE pCur2 = pCur->pNext;
                unsigned i = 16;
                while (i-- > 0 && pCur2)
                {
                    if (pCur2->Core.cb >= cbReq)
                    {
                        if (pCur2->Core.cb == cbReq)
                        {
                            pCur = pCur2;
                            break;
                        }
                        if (pCur2->Core.cb < pCur->Core.cb)
                            pCur = pCur2;
                    }

                    /* next */
                    KHLPHEAP_ASSERT_FREE(pHeap, pCur2);
                    pCur2 = pCur2->pNext;
                }
            }
            break;
        }

        /* next */
        KHLPHEAP_ASSERT_FREE(pHeap, pCur);
        pCur = pCur->pNext;
    }
    if (!pCur)
        return NULL;
    KHLPHEAP_ASSERT_FREE(pHeap, pCur);

    /*
     * Do we need to split out a block?
     */
    if (pCur->Core.cb - cbReq >= KHLPHEAPBLOCK_ALIGNMENT * 2)
    {
        PKHLPHEAPBLOCK pNew;

        pCur->Core.cb -= cbReq;

        pNew = (PKHLPHEAPBLOCK)((KUPTR)pCur + pCur->Core.cb);
        pNew->fFlags = 0;
        pNew->cb = cbReq;
        pNew->pNext = pCur->Core.pNext;
        if (pNew->pNext)
            pNew->pNext->pPrev = pNew;
        else
            pHeap->pTail = pNew;
        pNew->pPrev = &pCur->Core;
        pCur->Core.pNext = pNew;

        KHLPHEAP_ASSERT_FREE(pHeap, pCur);
        KHLPHEAP_ASSERT_BLOCK(pHeap, pNew);
        return pNew + 1;
    }

    /*
     * No, just unlink it from the free list and return.
     */
    if (pCur->pNext)
        pCur->pNext->pPrev = pCur->pPrev;
    if (pCur->pPrev)
        pCur->pPrev->pNext = pCur->pNext;
    else
        pHeap->pFreeHead = pCur->pNext;
    pCur->Core.fFlags &= ~KHLPHEAPBLOCK_FLAG_FREE;

    KHLPHEAP_ASSERT_BLOCK(pHeap, &pCur->Core);
    return &pCur->Core + 1;
}


/**
 * Allocate a heap block.
 *
 * @returns Pointer to the allocated heap block on success. On failure NULL is returned.
 * @param   pHeap   The heap.
 * @param   cb      The requested heap block size.
 */
static void *   khlpHeapAlloc(PKHLPHEAPANCHOR pHeap, KSIZE cb)
{
    void *pv;

    /* adjust the requested block size. */
    cb = K_ALIGN_Z(cb, KHLPHEAPBLOCK_ALIGNMENT);
    if (!cb)
        cb = KHLPHEAPBLOCK_ALIGNMENT;

    /* try allocate the block. */
    pv = kldrHeapAllocSub(pHeap, cb);
    if (!pv)
    {
        /*
         * Failed, add another segment and try again.
         */
        KHLPHEAPSEG Seg;
        if (khlpHeapSegAlloc(&Seg, cb + sizeof(KHLPHEAPSEGS) + sizeof(KHLPHEAPBLOCK) * 16))
            return NULL;

        /* donate before insterting the segment, this makes sure we got heap to expand the segment list. */
        khlpHeapDonate(pHeap, Seg.pvBase, Seg.cb);

        /* insert the segment. */
        if (pHeap->SegsHead.cSegs < sizeof(pHeap->SegsHead.aSegs) / sizeof(pHeap->SegsHead.aSegs[0]))
            pHeap->SegsHead.aSegs[pHeap->SegsHead.cSegs++] = Seg;
        else if (   pHeap->SegsHead.pNext
                 && pHeap->SegsHead.pNext->cSegs < sizeof(pHeap->SegsHead.aSegs) / sizeof(pHeap->SegsHead.aSegs[0]))
            pHeap->SegsHead.pNext->aSegs[pHeap->SegsHead.pNext->cSegs++] = Seg;
        else
        {
            PKHLPHEAPSEGS pSegs = (PKHLPHEAPSEGS)kldrHeapAllocSub(pHeap, sizeof(*pSegs));
            KHLPHEAP_ASSERT(pSegs);
            pSegs->pNext = pHeap->SegsHead.pNext;
            pHeap->SegsHead.pNext = pSegs;
            pSegs->aSegs[0] = Seg;
            pSegs->cSegs = 1;
        }

        /* retry (should succeed) */
        pv = kldrHeapAllocSub(pHeap, cb);
        KHLPHEAP_ASSERT(pv);
    }

    return pv;
}


/**
 * Frees a heap block.
 *
 * @param   pHeap   The heap.
 * @param   pv      The pointer returned by khlpHeapAlloc().
 */
static void     khlpHeapFree(PKHLPHEAPANCHOR pHeap, void *pv)
{
    PKHLPHEAPFREE pFree, pLeft, pRight;

    /* ignore NULL pointers. */
    if (!pv)
        return;

    pFree = (PKHLPHEAPFREE)((PKHLPHEAPBLOCK)pv - 1);
    KHLPHEAP_ASSERT_BLOCK(pHeap, &pFree->Core);
    KHLPHEAP_ASSERT(KHLPHEAPBLOCK_IS_ALLOCATED(&pFree->Core));

    /*
     * Merge or link with left node?
     */
    pLeft = (PKHLPHEAPFREE)pFree->Core.pPrev;
    if (    pLeft
        &&  KHLPHEAPBLOCK_IS_FREE(&pLeft->Core)
        &&  KHLPHEAPBLOCK_IS_ADJACENT(&pLeft->Core, &pFree->Core)
       )
    {
        /* merge left */
        pLeft->Core.pNext = pFree->Core.pNext;
        if (pFree->Core.pNext)
            pFree->Core.pNext->pPrev = &pLeft->Core;
        else
            pHeap->pTail = &pLeft->Core;

        pLeft->Core.cb += pFree->Core.cb;
        pFree->Core.fFlags = ~0;
        pFree = pLeft;
    }
    else
    {
        /* link left */
        while (pLeft && !KHLPHEAPBLOCK_IS_FREE(&pLeft->Core))
            pLeft = (PKHLPHEAPFREE)pLeft->Core.pPrev;
        if (pLeft)
        {
            pFree->pPrev = pLeft;
            pFree->pNext = pLeft->pNext;
            if (pLeft->pNext)
                pLeft->pNext->pPrev = pFree;
            pLeft->pNext  = pFree;
        }
        else
        {
            pFree->pPrev = NULL;
            pFree->pNext = pHeap->pFreeHead;
            if (pHeap->pFreeHead)
                pHeap->pFreeHead->pPrev = pFree;
            pHeap->pFreeHead = pFree;
        }
        pFree->Core.fFlags |= KHLPHEAPBLOCK_FLAG_FREE;
    }
    KHLPHEAP_ASSERT_FREE(pHeap, pFree);

    /*
     * Merge right?
     */
    pRight = (PKHLPHEAPFREE)pFree->Core.pNext;
    if (    pRight
        &&  KHLPHEAPBLOCK_IS_FREE(&pRight->Core)
        &&  KHLPHEAPBLOCK_IS_ADJACENT(&pFree->Core, pRight)
       )
    {
        /* unlink pRight from the global list. */
        pFree->Core.pNext = pRight->Core.pNext;
        if (pRight->Core.pNext)
            pRight->Core.pNext->pPrev = &pFree->Core;
        else
            pHeap->pTail = &pFree->Core;

        /* unlink pRight from the free list. */
        pFree->pNext = pRight->pNext;
        if (pRight->pNext)
            pRight->pNext->pPrev = pFree;

        /* update size and invalidate pRight. */
        pFree->Core.cb += pRight->Core.cb;
        pRight->Core.fFlags = ~0;
    }
}


/**
 * Calcs the size of a heap block.
 *
 * @returns The block size (in bytes).
 * @param   pHeap       The heap.
 * @param   pv          Pointer to an in-use heap block.
 */
static KSIZE khlpHeapBlockSize(PKHLPHEAPANCHOR pHeap, void *pv)
{
    PKHLPHEAPBLOCK pBlock  = (PKHLPHEAPBLOCK)pv - 1;
    KHLPHEAP_ASSERT_BLOCK(pHeap, pBlock);
    KHLPHEAP_ASSERT(KHLPHEAPBLOCK_IS_ALLOCATED(pBlock));
    return (KU8 *)pBlock->pNext - (KU8 *)pv;
}


/**
 * Donates memory to the heap.
 *
 * The donated memory is returned to the donator when the heap is deleted.
 *
 * @param pHeap The heap
 * @param pv    The pointer to the donated memory.
 * @param cb    Size of the donated memory.
 */
static void     khlpHeapDonate(PKHLPHEAPANCHOR pHeap, void *pv, KSIZE cb)
{
    PKHLPHEAPBLOCK pBlock;

    /*
     * Don't bother with small donations.
     */
    if (cb < KHLPHEAPBLOCK_ALIGNMENT * 4)
        return;

    /*
     * Align the donation on a heap block boundrary.
     */
    if ((KUPTR)pv & (KHLPHEAPBLOCK_ALIGNMENT - 1))
    {
        cb -= (KUPTR)pv & 31;
        pv = K_ALIGN_P(pv, KHLPHEAPBLOCK_ALIGNMENT);
    }
    cb &= ~(KSIZE)(KHLPHEAPBLOCK_ALIGNMENT - 1);

    /*
     * Create an allocated block, link it and free it.
     */
    pBlock = (PKHLPHEAPBLOCK)pv;
    pBlock->pNext = NULL;
    pBlock->pPrev = NULL;
    pBlock->cb = cb;
    pBlock->fFlags = 0;

    /* insert */
    if ((KUPTR)pBlock < (KUPTR)pHeap->pHead)
    {
        /* head */
        pBlock->pNext = pHeap->pHead;
        pHeap->pHead->pPrev = pBlock;
        pHeap->pHead = pBlock;
    }
    else if ((KUPTR)pBlock > (KUPTR)pHeap->pTail)
    {
        if (pHeap->pTail)
        {
            /* tail */
            pBlock->pPrev = pHeap->pTail;
            pHeap->pTail->pNext = pBlock;
            pHeap->pTail = pBlock;
        }
        else
        {
            /* first */
            pHeap->pHead = pBlock;
            pHeap->pTail = pBlock;
        }
    }
    else
    {
        /* in list (unlikely) */
        PKHLPHEAPBLOCK pPrev = pHeap->pHead;
        PKHLPHEAPBLOCK pCur = pPrev->pNext;
        for (;;)
        {
            KHLPHEAP_ASSERT_BLOCK(pHeap, pCur);
            if ((KUPTR)pCur > (KUPTR)pBlock)
                break;
            pPrev = pCur;
            pCur = pCur->pNext;
        }

        pBlock->pNext = pCur;
        pBlock->pPrev = pPrev;
        pPrev->pNext = pBlock;
        pCur->pPrev = pBlock;
    }
    KHLPHEAP_ASSERT_BLOCK(pHeap, pBlock);

    /* free it */
    khlpHeapFree(pHeap, pBlock + 1);
}



/**
 * Allocates a new segment.
 *
 * @returns 0 on success, non-zero OS status code on failure.
 * @param   pSeg    Where to put the info about the allocated segment.
 * @param   cbMin   The minimum segment size.
 */
static int khlpHeapSegAlloc(PKHLPHEAPSEG pSeg, KSIZE cbMin)
{
#if K_OS == K_OS_OS2
    APIRET rc;

    pSeg->cb = (cbMin + 0xffff) & ~(KSIZE)0xffff;
    pSeg->pvBase = NULL;
    rc = DosAllocMem(&pSeg->pvBase, pSeg->cb, PAG_COMMIT | PAG_READ | PAG_WRITE | OBJ_ANY);
    if (rc == ERROR_INVALID_PARAMETER)
        rc = DosAllocMem(&pSeg->pvBase, pSeg->cb, PAG_COMMIT | PAG_READ | PAG_WRITE);
    if (rc)
    {
        pSeg->pvBase = NULL;
        pSeg->cb = 0;
        return rc;
    }

#elif  K_OS == K_OS_WINDOWS
    pSeg->cb = (cbMin + 0xffff) & ~(KSIZE)0xffff;
    pSeg->pvBase = VirtualAlloc(NULL, pSeg->cb, MEM_COMMIT, PAGE_READWRITE);
    if (!pSeg->pvBase)
    {
        pSeg->cb = 0;
        return GetLastError();
    }

#else
    int rc;

    pSeg->cb = (cbMin + 0xffff) & ~(KSIZE)0xffff;
    pSeg->pvBase = NULL;
    rc = kHlpPageAlloc(&pSeg->pvBase, pSeg->cb, KPROT_READWRITE, K_FALSE);
    if (rc)
    {
        pSeg->pvBase = NULL;
        pSeg->cb = 0;
        return rc;
    }

#endif

    return 0;
}


/**
 * Frees a segment.
 *
 * @param   pSeg    The segment to be freed.
 */
static void khlpHeapSegFree(PKHLPHEAPSEG pSeg)
{
#if K_OS == K_OS_OS2
    APIRET rc = DosFreeMem(pSeg->pvBase);
    KHLPHEAP_ASSERT(!rc); (void)rc;

#elif  K_OS == K_OS_WINDOWS
    BOOL fRc = VirtualFree(pSeg->pvBase, 0 /*pSeg->cb*/, MEM_RELEASE);
    KHLPHEAP_ASSERT(fRc); (void)fRc;

#else
    int rc = kHlpPageFree(pSeg->pvBase, pSeg->cb);
    KHLPHEAP_ASSERT(!rc); (void)rc;

#endif
}