BlockAlloc.c 20.9 KB
Newer Older
1
2
/* -----------------------------------------------------------------------------
 *
3
 * (c) The GHC Team 1998-2008
4
 * 
5
6
7
8
9
 * The block allocator and free list manager.
 *
 * This is the architecture independent part of the block allocator.
 * It requires only the following support from the operating system: 
 *
Simon Marlow's avatar
Simon Marlow committed
10
 *    void *getMBlock(nat n);
11
 *
Simon Marlow's avatar
Simon Marlow committed
12
13
14
 * returns the address of an n*MBLOCK_SIZE region of memory, aligned on
 * an MBLOCK_SIZE boundary.  There are no other restrictions on the
 * addresses of memory returned by getMBlock().
15
16
17
 *
 * ---------------------------------------------------------------------------*/

18
#include "PosixSource.h"
19
#include "Rts.h"
Simon Marlow's avatar
Simon Marlow committed
20
21

#include "Storage.h"
22
23
24
#include "RtsUtils.h"
#include "BlockAlloc.h"

25
26
#include <string.h>

Simon Marlow's avatar
Simon Marlow committed
27
static void  initMBlock(void *mblock);
28

Simon Marlow's avatar
Simon Marlow committed
29
// The free_list is kept sorted by size, smallest first.
30
// In THREADED_RTS mode, the free list is protected by sm_mutex.
Simon Marlow's avatar
Simon Marlow committed
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

/* -----------------------------------------------------------------------------

  Implementation notes
  ~~~~~~~~~~~~~~~~~~~~

  Terminology:
    - bdescr = block descriptor
    - bgroup = block group (1 or more adjacent blocks)
    - mblock = mega block
    - mgroup = mega group (1 or more adjacent mblocks)

   Invariants on block descriptors
   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
   bd->start always points to the start of the block.

   bd->free is either:
      - zero for a non-group-head; bd->link points to the head
      - (-1) for the head of a free block group
      - or it points within the block

   bd->blocks is either:
      - zero for a non-group-head; bd->link points to the head
      - number of blocks in this group otherwise

   bd->link either points to a block descriptor or is NULL

   The following fields are not used by the allocator:
     bd->flags
     bd->gen_no
Simon Marlow's avatar
Simon Marlow committed
61
     bd->gen
62
     bd->dest
Simon Marlow's avatar
Simon Marlow committed
63
64
65
66
67
68
69
70
71

  Exceptions: we don't maintain invariants for all the blocks within a
  group on the free list, because it is expensive to modify every
  bdescr in a group when coalescing.  Just the head and last bdescrs
  will be correct for a group on the free list.


  Free lists
  ~~~~~~~~~~
72

Simon Marlow's avatar
Simon Marlow committed
73
  Preliminaries:
74
    - most allocations are for a small number of blocks
75
76
77
78
79
80
    - sometimes the OS gives us new memory backwards in the address
      space, sometimes forwards, so we should not be biased towards
      any particular layout in the address space
    - We want to avoid fragmentation
    - We want allocation and freeing to be O(1) or close.

Simon Marlow's avatar
Simon Marlow committed
81
  Coalescing trick: when a bgroup is freed (freeGroup()), we can check
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
  whether it can be coalesced with other free bgroups by checking the
  bdescrs for the blocks on either side of it.  This means that we can
  coalesce in O(1) time.  Every free bgroup must have its head and tail
  bdescrs initialised, the rest don't matter.

  We keep the free list in buckets, using a heap-sort strategy.
  Bucket N contains blocks with sizes 2^N - 2^(N+1)-1.  The list of
  blocks in each bucket is doubly-linked, so that if a block is
  coalesced we can easily remove it from its current free list.

  To allocate a new block of size S, grab a block from bucket
  log2ceiling(S) (i.e. log2() rounded up), in which all blocks are at
  least as big as S, and split it if necessary.  If there are no
  blocks in that bucket, look at bigger buckets until a block is found
  Allocation is therefore O(logN) time.

  To free a block:
    - coalesce it with neighbours.
    - remove coalesced neighbour(s) from free list(s)
    - add the new (coalesced) block to the front of the appropriate
      bucket, given by log2(S) where S is the size of the block.

  Free is O(1).

  We cannot play this coalescing trick with mblocks, because there is
  no requirement that the bdescrs in the second and subsequent mblock
  of an mgroup are initialised (the mgroup might be filled with a
  large array, overwriting the bdescrs for example).

  So there is a separate free list for megablocks, sorted in *address*
  order, so that we can coalesce.  Allocation in this list is best-fit
  by traversing the whole list: we don't expect this list to be long,
  and allocation/freeing of large blocks is rare; avoiding
  fragmentation is more important than performance here.
Simon Marlow's avatar
Simon Marlow committed
116
117
118
119
120
121
122
123

  freeGroup() might end up moving a block from free_list to
  free_mblock_list, if after coalescing we end up with a full mblock.

  checkFreeListSanity() checks all the invariants on the free lists.

  --------------------------------------------------------------------------- */

124
125
126
#define MAX_FREE_LIST 9

static bdescr *free_list[MAX_FREE_LIST];
Simon Marlow's avatar
Simon Marlow committed
127
128
static bdescr *free_mblock_list;

129
130
131
132
133
134
135
136
// free_list[i] contains blocks that are at least size 2^i, and at
// most size 2^(i+1) - 1.  
// 
// To find the free list in which to place a block, use log_2(size).
// To find a free block of the right size, use log_2_ceil(size).

lnat n_alloc_blocks;   // currently allocated blocks
lnat hw_alloc_blocks;  // high-water allocated blocks
137
138
139
140
141
142
143

/* -----------------------------------------------------------------------------
   Initialisation
   -------------------------------------------------------------------------- */

void initBlockAllocator(void)
{
144
145
146
147
    nat i;
    for (i=0; i < MAX_FREE_LIST; i++) {
        free_list[i] = NULL;
    }
Simon Marlow's avatar
Simon Marlow committed
148
    free_mblock_list = NULL;
149
150
    n_alloc_blocks = 0;
    hw_alloc_blocks = 0;
151
152
153
154
155
156
}

/* -----------------------------------------------------------------------------
   Allocation
   -------------------------------------------------------------------------- */

157
STATIC_INLINE void
simonmarhaskell@gmail.com's avatar
simonmarhaskell@gmail.com committed
158
initGroup(bdescr *head)
159
{
160
  bdescr *bd;
simonmarhaskell@gmail.com's avatar
simonmarhaskell@gmail.com committed
161
  nat i, n;
162

simonmarhaskell@gmail.com's avatar
simonmarhaskell@gmail.com committed
163
164
165
166
  n = head->blocks;
  head->free   = head->start;
  head->link   = NULL;
  for (i=1, bd = head+1; i < n; i++, bd++) {
167
168
169
      bd->free = 0;
      bd->blocks = 0;
      bd->link = head;
170
171
172
  }
}

173
174
175
176
177
// There are quicker non-loopy ways to do log_2, but we expect n to be
// usually small, and MAX_FREE_LIST is also small, so the loop version
// might well be the best choice here.
STATIC_INLINE nat
log_2_ceil(nat n)
178
{
179
180
181
182
183
    nat i, x;
    x = 1;
    for (i=0; i < MAX_FREE_LIST; i++) {
        if (x >= n) return i;
        x = x << 1;
Simon Marlow's avatar
Simon Marlow committed
184
    }
185
    return MAX_FREE_LIST;
Simon Marlow's avatar
Simon Marlow committed
186
}
187

188
189
STATIC_INLINE nat
log_2(nat n)
Simon Marlow's avatar
Simon Marlow committed
190
{
191
192
193
194
195
    nat i, x;
    x = n;
    for (i=0; i < MAX_FREE_LIST; i++) {
        x = x >> 1;
        if (x == 0) return i;
196
    }
197
    return MAX_FREE_LIST;
Simon Marlow's avatar
Simon Marlow committed
198
199
}

200
STATIC_INLINE void
Simon Marlow's avatar
Simon Marlow committed
201
202
free_list_insert (bdescr *bd)
{
203
    nat ln;
Simon Marlow's avatar
Simon Marlow committed
204

205
206
207
208
    ASSERT(bd->blocks < BLOCKS_PER_MBLOCK);
    ln = log_2(bd->blocks);
    
    dbl_link_onto(bd, &free_list[ln]);
Simon Marlow's avatar
Simon Marlow committed
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
}


STATIC_INLINE bdescr *
tail_of (bdescr *bd)
{
    return bd + bd->blocks - 1;
}

// After splitting a group, the last block of each group must have a
// tail that points to the head block, to keep our invariants for
// coalescing. 
STATIC_INLINE void
setup_tail (bdescr *bd)
{
    bdescr *tail;
    tail = tail_of(bd);
    if (tail != bd) {
        tail->blocks = 0;
        tail->free = 0;
        tail->link = bd;
    }
}


// Take a free block group bd, and split off a group of size n from
// it.  Adjust the free list as necessary, and return the new group.
static bdescr *
237
split_free_block (bdescr *bd, nat n, nat ln)
Simon Marlow's avatar
Simon Marlow committed
238
239
240
241
{
    bdescr *fg; // free group

    ASSERT(bd->blocks > n);
242
    dbl_link_remove(bd, &free_list[ln]);
Simon Marlow's avatar
Simon Marlow committed
243
244
245
246
    fg = bd + bd->blocks - n; // take n blocks off the end
    fg->blocks = n;
    bd->blocks -= n;
    setup_tail(bd);
247
248
    ln = log_2(bd->blocks);
    dbl_link_onto(bd, &free_list[ln]);
Simon Marlow's avatar
Simon Marlow committed
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
    return fg;
}

static bdescr *
alloc_mega_group (nat mblocks)
{
    bdescr *best, *bd, *prev;
    nat n;

    n = MBLOCK_GROUP_BLOCKS(mblocks);

    best = NULL;
    prev = NULL;
    for (bd = free_mblock_list; bd != NULL; prev = bd, bd = bd->link)
    {
        if (bd->blocks == n) 
        {
            if (prev) {
                prev->link = bd->link;
            } else {
                free_mblock_list = bd->link;
            }
simonmarhaskell@gmail.com's avatar
simonmarhaskell@gmail.com committed
271
            initGroup(bd);
Simon Marlow's avatar
Simon Marlow committed
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
            return bd;
        }
        else if (bd->blocks > n)
        {
            if (!best || bd->blocks < best->blocks)
            {
                best = bd;
            }
        }
    }

    if (best)
    {
        // we take our chunk off the end here.
        nat best_mblocks  = BLOCKS_TO_MBLOCKS(best->blocks);
Simon Marlow's avatar
Simon Marlow committed
287
        bd = FIRST_BDESCR((StgWord8*)MBLOCK_ROUND_DOWN(best) + 
Simon Marlow's avatar
Simon Marlow committed
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
                          (best_mblocks-mblocks)*MBLOCK_SIZE);

        best->blocks = MBLOCK_GROUP_BLOCKS(best_mblocks - mblocks);
        initMBlock(MBLOCK_ROUND_DOWN(bd));
    }
    else
    {
        void *mblock = getMBlocks(mblocks);
        initMBlock(mblock);		// only need to init the 1st one
        bd = FIRST_BDESCR(mblock);
    }
    bd->blocks = MBLOCK_GROUP_BLOCKS(mblocks);
    return bd;
}

bdescr *
allocGroup (nat n)
{
    bdescr *bd, *rem;
307
    nat ln;
Simon Marlow's avatar
Simon Marlow committed
308
309
310
311
312

    if (n == 0) barf("allocGroup: requested zero blocks");
    
    if (n >= BLOCKS_PER_MBLOCK)
    {
313
314
315
316
317
318
319
320
321
322
        nat mblocks;

        mblocks = BLOCKS_TO_MBLOCKS(n);

        // n_alloc_blocks doesn't count the extra blocks we get in a
        // megablock group.
        n_alloc_blocks += mblocks * BLOCKS_PER_MBLOCK;
        if (n_alloc_blocks > hw_alloc_blocks) hw_alloc_blocks = n_alloc_blocks;

        bd = alloc_mega_group(mblocks);
Simon Marlow's avatar
Simon Marlow committed
323
        // only the bdescrs of the first MB are required to be initialised
simonmarhaskell@gmail.com's avatar
simonmarhaskell@gmail.com committed
324
        initGroup(bd);
325

Simon Marlow's avatar
Simon Marlow committed
326
327
328
329
        IF_DEBUG(sanity, checkFreeListSanity());
        return bd;
    }
    
330
331
332
    n_alloc_blocks += n;
    if (n_alloc_blocks > hw_alloc_blocks) hw_alloc_blocks = n_alloc_blocks;

333
334
    ln = log_2_ceil(n);

335
    while (ln < MAX_FREE_LIST && free_list[ln] == NULL) {
336
337
338
339
        ln++;
    }

    if (ln == MAX_FREE_LIST) {
340
341
342
343
344
345
346
347
#if 0
        if ((mblocks_allocated * MBLOCK_SIZE_W - n_alloc_blocks * BLOCK_SIZE_W) > (1024*1024)/sizeof(W_)) {
            debugBelch("Fragmentation, wanted %d blocks:", n);
            RtsFlags.DebugFlags.block_alloc = 1;
            checkFreeListSanity();
        }
#endif

348
349
        bd = alloc_mega_group(1);
        bd->blocks = n;
simonmarhaskell@gmail.com's avatar
simonmarhaskell@gmail.com committed
350
        initGroup(bd);		         // we know the group will fit
351
352
        rem = bd + n;
        rem->blocks = BLOCKS_PER_MBLOCK-n;
simonmarhaskell@gmail.com's avatar
simonmarhaskell@gmail.com committed
353
        initGroup(rem); // init the slop
354
355
356
357
        n_alloc_blocks += rem->blocks;
        freeGroup(rem);      	         // add the slop on to the free list
        IF_DEBUG(sanity, checkFreeListSanity());
        return bd;
Simon Marlow's avatar
Simon Marlow committed
358
359
    }

360
361
362
363
364
365
366
367
368
369
370
371
372
373
    bd = free_list[ln];

    if (bd->blocks == n)	        // exactly the right size!
    {
        dbl_link_remove(bd, &free_list[ln]);
    }
    else if (bd->blocks >  n)            // block too big...
    {                              
        bd = split_free_block(bd, n, ln);
    }
    else
    {
        barf("allocGroup: free list corrupted");
    }
simonmarhaskell@gmail.com's avatar
simonmarhaskell@gmail.com committed
374
    initGroup(bd);		// initialise it
Simon Marlow's avatar
Simon Marlow committed
375
    IF_DEBUG(sanity, checkFreeListSanity());
376
    ASSERT(bd->blocks == n);
Simon Marlow's avatar
Simon Marlow committed
377
    return bd;
378
379
}

380
381
382
383
384
385
386
387
388
389
bdescr *
allocGroup_lock(nat n)
{
    bdescr *bd;
    ACQUIRE_SM_LOCK;
    bd = allocGroup(n);
    RELEASE_SM_LOCK;
    return bd;
}

390
391
392
bdescr *
allocBlock(void)
{
Simon Marlow's avatar
Simon Marlow committed
393
    return allocGroup(1);
394
395
}

396
397
398
399
400
401
402
403
404
405
bdescr *
allocBlock_lock(void)
{
    bdescr *bd;
    ACQUIRE_SM_LOCK;
    bd = allocBlock();
    RELEASE_SM_LOCK;
    return bd;
}

406
/* -----------------------------------------------------------------------------
Simon Marlow's avatar
Simon Marlow committed
407
   De-Allocation
408
409
   -------------------------------------------------------------------------- */

Simon Marlow's avatar
Simon Marlow committed
410
411
412
413
414
415
416
417
STATIC_INLINE bdescr *
coalesce_mblocks (bdescr *p)
{
    bdescr *q;

    q = p->link;
    if (q != NULL && 
        MBLOCK_ROUND_DOWN(q) == 
Simon Marlow's avatar
Simon Marlow committed
418
419
        (StgWord8*)MBLOCK_ROUND_DOWN(p) + 
        BLOCKS_TO_MBLOCKS(p->blocks) * MBLOCK_SIZE) {
Simon Marlow's avatar
Simon Marlow committed
420
421
422
423
424
        // can coalesce
        p->blocks  = MBLOCK_GROUP_BLOCKS(BLOCKS_TO_MBLOCKS(p->blocks) +
                                         BLOCKS_TO_MBLOCKS(q->blocks));
        p->link = q->link;
        return p;
425
    }
Simon Marlow's avatar
Simon Marlow committed
426
    return q;
427
428
}

Simon Marlow's avatar
Simon Marlow committed
429
430
static void
free_mega_group (bdescr *mg)
431
{
Simon Marlow's avatar
Simon Marlow committed
432
433
434
435
436
437
438
439
440
441
    bdescr *bd, *prev;

    // Find the right place in the free list.  free_mblock_list is
    // sorted by *address*, not by size as the free_list is.
    prev = NULL;
    bd = free_mblock_list;
    while (bd && bd->start < mg->start) {
        prev = bd;
        bd = bd->link;
    }
442

Simon Marlow's avatar
Simon Marlow committed
443
444
    // coalesce backwards
    if (prev)
445
    {
Simon Marlow's avatar
Simon Marlow committed
446
447
448
        mg->link = prev->link;
        prev->link = mg;
        mg = coalesce_mblocks(prev);
449
    }
Simon Marlow's avatar
Simon Marlow committed
450
451
452
453
454
455
456
457
458
459
460
    else
    {
        mg->link = free_mblock_list;
        free_mblock_list = mg;
    }
    // coalesce forwards
    coalesce_mblocks(mg);

    IF_DEBUG(sanity, checkFreeListSanity());
}    

461
462
463
464

void
freeGroup(bdescr *p)
{
465
  nat ln;
466

Simon Marlow's avatar
Simon Marlow committed
467
468
  // Todo: not true in multithreaded GC
  // ASSERT_SM_LOCK();
469

Simon Marlow's avatar
Simon Marlow committed
470
  ASSERT(p->free != (P_)-1);
471
472

  p->free = (void *)-1;  /* indicates that this block is free */
Simon Marlow's avatar
Simon Marlow committed
473
  p->gen = NULL;
474
  p->gen_no = 0;
475
476
477
  /* fill the block group with garbage if sanity checking is on */
  IF_DEBUG(sanity,memset(p->start, 0xaa, p->blocks * BLOCK_SIZE));

Simon Marlow's avatar
Simon Marlow committed
478
479
480
481
  if (p->blocks == 0) barf("freeGroup: block size is zero");

  if (p->blocks >= BLOCKS_PER_MBLOCK)
  {
482
483
484
      nat mblocks;

      mblocks = BLOCKS_TO_MBLOCKS(p->blocks);
Simon Marlow's avatar
Simon Marlow committed
485
      // If this is an mgroup, make sure it has the right number of blocks
486
487
488
489
      ASSERT(p->blocks == MBLOCK_GROUP_BLOCKS(mblocks));

      n_alloc_blocks -= mblocks * BLOCKS_PER_MBLOCK;

Simon Marlow's avatar
Simon Marlow committed
490
491
      free_mega_group(p);
      return;
492
493
  }

494
495
496
  ASSERT(n_alloc_blocks >= p->blocks);
  n_alloc_blocks -= p->blocks;

Simon Marlow's avatar
Simon Marlow committed
497
498
499
500
501
502
503
  // coalesce forwards
  {
      bdescr *next;
      next = p + p->blocks;
      if (next <= LAST_BDESCR(MBLOCK_ROUND_DOWN(p)) && next->free == (P_)-1)
      {
          p->blocks += next->blocks;
504
505
          ln = log_2(next->blocks);
          dbl_link_remove(next, &free_list[ln]);
Simon Marlow's avatar
Simon Marlow committed
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
          if (p->blocks == BLOCKS_PER_MBLOCK)
          {
              free_mega_group(p);
              return;
          }
          setup_tail(p);
      }
  }

  // coalesce backwards
  if (p != FIRST_BDESCR(MBLOCK_ROUND_DOWN(p)))
  {
      bdescr *prev;
      prev = p - 1;
      if (prev->blocks == 0) prev = prev->link; // find the head

      if (prev->free == (P_)-1)
      {
524
525
          ln = log_2(prev->blocks);
          dbl_link_remove(prev, &free_list[ln]);
Simon Marlow's avatar
Simon Marlow committed
526
527
528
529
530
531
532
533
534
535
          prev->blocks += p->blocks;
          if (prev->blocks >= BLOCKS_PER_MBLOCK)
          {
              free_mega_group(prev);
              return;
          }
          p = prev;
      }
  }
      
536
537
  setup_tail(p);
  free_list_insert(p);
538
539
540
541

  IF_DEBUG(sanity, checkFreeListSanity());
}

542
543
544
545
546
547
548
549
void
freeGroup_lock(bdescr *p)
{
    ACQUIRE_SM_LOCK;
    freeGroup(p);
    RELEASE_SM_LOCK;
}

550
551
552
553
554
555
556
557
558
559
560
void
freeChain(bdescr *bd)
{
  bdescr *next_bd;
  while (bd != NULL) {
    next_bd = bd->link;
    freeGroup(bd);
    bd = next_bd;
  }
}

561
562
563
564
565
566
567
568
void
freeChain_lock(bdescr *bd)
{
    ACQUIRE_SM_LOCK;
    freeChain(bd);
    RELEASE_SM_LOCK;
}

569
570
571
// splitBlockGroup(bd,B) splits bd in two.  Afterward, bd will have B
// blocks, and a new block descriptor pointing to the remainder is
// returned.
572
573
574
575
576
577
578
579
580
581
bdescr *
splitBlockGroup (bdescr *bd, nat blocks)
{
    bdescr *new_bd;

    if (bd->blocks <= blocks) {
        barf("splitLargeBlock: too small");
    }

    if (bd->blocks > BLOCKS_PER_MBLOCK) {
582
        nat low_mblocks, high_mblocks;
583
584
585
586
        void *new_mblock;
        if ((blocks - BLOCKS_PER_MBLOCK) % (MBLOCK_SIZE / BLOCK_SIZE) != 0) {
            barf("splitLargeBlock: not a multiple of a megablock");
        }
587
588
589
590
        low_mblocks = 1 + (blocks - BLOCKS_PER_MBLOCK) / (MBLOCK_SIZE / BLOCK_SIZE);
        high_mblocks = (bd->blocks - blocks) / (MBLOCK_SIZE / BLOCK_SIZE);

        new_mblock = (void *) ((P_)MBLOCK_ROUND_DOWN(bd) + low_mblocks * MBLOCK_SIZE_W);
591
592
        initMBlock(new_mblock);
        new_bd = FIRST_BDESCR(new_mblock);
593
594
595
596
        new_bd->blocks = MBLOCK_GROUP_BLOCKS(high_mblocks);

        ASSERT(blocks + new_bd->blocks == 
               bd->blocks + BLOCKS_PER_MBLOCK - MBLOCK_SIZE/BLOCK_SIZE);
597
598
599
600
601
602
603
604
605
606
607
608
609
610
    }
    else
    {
        // NB. we're not updating all the bdescrs in the split groups to
        // point to the new heads, so this can only be used for large
        // objects which do not start in the non-head block.
        new_bd = bd + blocks;
        new_bd->blocks = bd->blocks - blocks;
    }
    bd->blocks = blocks;

    return new_bd;
}

611
612
613
static void
initMBlock(void *mblock)
{
Simon Marlow's avatar
Simon Marlow committed
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
    bdescr *bd;
    StgWord8 *block;

    /* the first few Bdescr's in a block are unused, so we don't want to
     * put them all on the free list.
     */
    block = FIRST_BLOCK(mblock);
    bd    = FIRST_BDESCR(mblock);
    
    /* Initialise the start field of each block descriptor
     */
    for (; block <= (StgWord8*)LAST_BLOCK(mblock); bd += 1, 
             block += BLOCK_SIZE) {
        bd->start = (void*)block;
    }
629
630
}

Simon Marlow's avatar
Simon Marlow committed
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
/* -----------------------------------------------------------------------------
   Stats / metrics
   -------------------------------------------------------------------------- */

nat
countBlocks(bdescr *bd)
{
    nat n;
    for (n=0; bd != NULL; bd=bd->link) {
	n += bd->blocks;
    }
    return n;
}

// (*1) Just like countBlocks, except that we adjust the count for a
// megablock group so that it doesn't include the extra few blocks
// that would be taken up by block descriptors in the second and
// subsequent megablock.  This is so we can tally the count with the
// number of blocks allocated in the system, for memInventory().
nat
countAllocdBlocks(bdescr *bd)
{
    nat n;
    for (n=0; bd != NULL; bd=bd->link) {
	n += bd->blocks;
	// hack for megablock groups: see (*1) above
	if (bd->blocks > BLOCKS_PER_MBLOCK) {
	    n -= (MBLOCK_SIZE / BLOCK_SIZE - BLOCKS_PER_MBLOCK)
		* (bd->blocks/(MBLOCK_SIZE/BLOCK_SIZE));
	}
    }
    return n;
}

665
666
667
668
669
/* -----------------------------------------------------------------------------
   Debugging
   -------------------------------------------------------------------------- */

#ifdef DEBUG
670
static void
Simon Marlow's avatar
Simon Marlow committed
671
check_tail (bdescr *bd)
672
{
Simon Marlow's avatar
Simon Marlow committed
673
    bdescr *tail = tail_of(bd);
674

Simon Marlow's avatar
Simon Marlow committed
675
676
677
678
679
    if (tail != bd)
    {
        ASSERT(tail->blocks == 0);
        ASSERT(tail->free == 0);
        ASSERT(tail->link == bd);
680
681
682
    }
}

683
684
685
void
checkFreeListSanity(void)
{
Simon Marlow's avatar
Simon Marlow committed
686
    bdescr *bd, *prev;
687
    nat ln, min;
688

Simon Marlow's avatar
Simon Marlow committed
689

690
691
692
    min = 1;
    for (ln = 0; ln < MAX_FREE_LIST; ln++) {
        IF_DEBUG(block_alloc, debugBelch("free block list [%d]:\n", ln));
Simon Marlow's avatar
Simon Marlow committed
693

694
695
696
697
698
699
700
701
702
703
        prev = NULL;
        for (bd = free_list[ln]; bd != NULL; prev = bd, bd = bd->link)
        {
            IF_DEBUG(block_alloc,
                     debugBelch("group at %p, length %ld blocks\n", 
                                bd->start, (long)bd->blocks));
            ASSERT(bd->free == (P_)-1);
            ASSERT(bd->blocks > 0 && bd->blocks < BLOCKS_PER_MBLOCK);
            ASSERT(bd->blocks >= min && bd->blocks <= (min*2 - 1));
            ASSERT(bd->link != bd); // catch easy loops
Simon Marlow's avatar
Simon Marlow committed
704

705
            check_tail(bd);
Simon Marlow's avatar
Simon Marlow committed
706

707
708
709
710
            if (prev)
                ASSERT(bd->u.back == prev);
            else 
                ASSERT(bd->u.back == NULL);
Simon Marlow's avatar
Simon Marlow committed
711
712

            {
713
714
715
716
717
718
                bdescr *next;
                next = bd + bd->blocks;
                if (next <= LAST_BDESCR(MBLOCK_ROUND_DOWN(bd)))
                {
                    ASSERT(next->free != (P_)-1);
                }
Simon Marlow's avatar
Simon Marlow committed
719
720
            }
        }
721
        min = min << 1;
Simon Marlow's avatar
Simon Marlow committed
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
    }

    prev = NULL;
    for (bd = free_mblock_list; bd != NULL; prev = bd, bd = bd->link)
    {
        IF_DEBUG(block_alloc,
                 debugBelch("mega group at %p, length %ld blocks\n", 
                            bd->start, (long)bd->blocks));

        ASSERT(bd->link != bd); // catch easy loops

        if (bd->link != NULL)
        {
            // make sure the list is sorted
            ASSERT(bd->start < bd->link->start);
        }

        ASSERT(bd->blocks >= BLOCKS_PER_MBLOCK);
        ASSERT(MBLOCK_GROUP_BLOCKS(BLOCKS_TO_MBLOCKS(bd->blocks))
               == bd->blocks);

        // make sure we're fully coalesced
        if (bd->link != NULL)
        {
            ASSERT (MBLOCK_ROUND_DOWN(bd->link) != 
Simon Marlow's avatar
Simon Marlow committed
747
                    (StgWord8*)MBLOCK_ROUND_DOWN(bd) + 
Simon Marlow's avatar
Simon Marlow committed
748
749
                    BLOCKS_TO_MBLOCKS(bd->blocks) * MBLOCK_SIZE);
        }
750
751
    }
}
752
753
754
755
756
757

nat /* BLOCKS */
countFreeList(void)
{
  bdescr *bd;
  lnat total_blocks = 0;
758
  nat ln;
759

760
761
762
763
  for (ln=0; ln < MAX_FREE_LIST; ln++) {
      for (bd = free_list[ln]; bd != NULL; bd = bd->link) {
          total_blocks += bd->blocks;
      }
Simon Marlow's avatar
Simon Marlow committed
764
765
766
767
768
769
770
  }
  for (bd = free_mblock_list; bd != NULL; bd = bd->link) {
      total_blocks += BLOCKS_PER_MBLOCK * BLOCKS_TO_MBLOCKS(bd->blocks);
      // The caller of this function, memInventory(), expects to match
      // the total number of blocks in the system against mblocks *
      // BLOCKS_PER_MBLOCK, so we must subtract the space for the
      // block descriptors from *every* mblock.
771
772
773
  }
  return total_blocks;
}
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796

void
markBlocks (bdescr *bd)
{
    for (; bd != NULL; bd = bd->link) {
        bd->flags |= BF_KNOWN;
    }
}

void
reportUnmarkedBlocks (void)
{
    void *mblock;
    bdescr *bd;

    debugBelch("Unreachable blocks:\n");
    for (mblock = getFirstMBlock(); mblock != NULL;
         mblock = getNextMBlock(mblock)) {
        for (bd = FIRST_BDESCR(mblock); bd <= LAST_BDESCR(mblock); ) {
            if (!(bd->flags & BF_KNOWN) && bd->free != (P_)-1) {
                debugBelch("  %p\n",bd);
            }
            if (bd->blocks >= BLOCKS_PER_MBLOCK) {
Simon Marlow's avatar
Simon Marlow committed
797
798
                mblock = (StgWord8*)mblock +
                    (BLOCKS_TO_MBLOCKS(bd->blocks) - 1) * MBLOCK_SIZE;
799
800
801
802
803
804
805
806
                break;
            } else {
                bd += bd->blocks;
            }
        }
    }
}

807
#endif