CNF.c 33.4 KB
Newer Older
gcampax's avatar
gcampax committed
1 2 3 4 5 6
/* -----------------------------------------------------------------------------
 *
 * (c) The GHC Team 1998-2014
 *
 * GC support for immutable non-GCed structures, also known as Compact
 * Normal Forms (CNF for short). This provides the RTS support for
7
 * the 'compact' package and the GHC.Compact module.
gcampax's avatar
gcampax committed
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
 *
 * ---------------------------------------------------------------------------*/

#define _GNU_SOURCE

#include "PosixSource.h"
#include "Rts.h"
#include "RtsUtils.h"

#include "Capability.h"
#include "GC.h"
#include "Storage.h"
#include "CNF.h"
#include "Hash.h"
#include "HeapAlloc.h"
#include "BlockAlloc.h"
24 25
#include "Trace.h"
#include "sm/ShouldCompact.h"
gcampax's avatar
gcampax committed
26

27 28
#include <string.h>

Ben Gamari's avatar
Ben Gamari committed
29
#if defined(HAVE_UNISTD_H)
gcampax's avatar
gcampax committed
30 31
#include <unistd.h>
#endif
Ben Gamari's avatar
Ben Gamari committed
32
#if defined(HAVE_LIMITS_H)
gcampax's avatar
gcampax committed
33 34 35
#include <limits.h>
#endif

36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
/*
  Note [Compact Normal Forms]
  ~~~~~~~~~~~~~~~~~~~~~~~~~~~

  A compact normal form (CNF) is a region of memory containing one or more
  Haskell data structures.  The goals are:

  * The CNF lives or dies as a single unit as far as the GC is concerned.  The
    GC does not traverse the data inside the CNF.

  * A CNF can be "serialized" (stored on disk or transmitted over a network).
    To "deserialize", all we need to do is adjust the addresses of the pointers
    within the CNF ("fixup"),  Deserializing can only be done in the context of
    the same Haskell binary that produced the CNF.

  Structure
  ~~~~~~~~~

54
  * In GHC.Compact we have
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
    data Compact a = Compact Compact# a

  * The Compact# primitive object is operated on by the primitives.

  * A single CNF looks like this:

  .---------,       .-------------------------------.        ,-------------
  | Compact |    ,--+-> StgCompactNFDataBlock       |   ,--->| StgCompac...
  +---------+    `--+--- self                       |   |    |   self
  |    .----+-.  ,--+--- owner                      |   |    |   wner
  +---------+ |  |  |    next ----------------------+---'    |   next -------->
  |    .    | |  |  |-------------------------------+        +-------------
  `----+----' `--+--+-> StgCompactNFData (Compact#) |        | more data...
       |            |    totalW                     |        |
       |            |    autoblockW                 |        |
       |            |    nursery                    |        |
       |            |    hash                       |        |
       |            |    last                       |        |
       |            |-------------------------------|        |
       `------------+--> data ...                   |        |
                    |                               |        |
                    |                               |        |
                    `-------------------------------'        `-------------

  * Each block in a CNF starts with a StgCompactNFDataBlock header

  * The blocks in a CNF are chained through the next field

  * Multiple CNFs are chained together using the bdescr->link and bdescr->u.prev
    fields of the bdescr.

  * The first block of a CNF (only) contains the StgCompactNFData (aka
    Compact#), right after the StgCompactNFDataBlock header.

  * The data inside a CNF block is ordinary closures

  * During compaction (with sharing enabled) the hash field points to
    a HashTable mapping heap addresses outside the compact to
    addresses within it.  If a GC strikes during compaction, this
    HashTable must be scanned by the GC.

  Invariants
  ~~~~~~~~~~

  (1) A CNF is self-contained.  The data within it does not have any external
      pointers.  EXCEPT: pointers to static constructors that are guaranteed to
      never refer (directly or indirectly) to CAFs are allowed, because the
      garbage collector does not have to track or follow these.

  (2) A CNF contains only immutable data: no THUNKS, FUNs, or mutable
      objects.  This helps maintain invariant (1).

  Details
  ~~~~~~~

  Blocks are appended to the chain automatically as needed, or manually with a
  compactResize() call, which also adjust the size of automatically appended
  blocks.

  Objects can be appended to the block currently marked to the nursery, or any
  of the later blocks if the nursery block is too full to fit the entire
  object. For each block in the chain (which can be multiple block allocator
  blocks), we use the bdescr of its beginning to store how full it is.
  After an object is appended, it is scavenged for any outgoing pointers,
  and all pointed to objects are appended, recursively, in a manner similar
  to copying GC (further discussion in the note [Appending to a Compact])

  We also flag each bdescr in each block allocator block of a compact
  (including those there were obtained as second or later from a single
  allocGroup(n) call) with the BF_COMPACT. This allows the GC to quickly
  realize that a given pointer is in a compact region, and trigger the
  CNF path.

  These two facts combined mean that in any compact block where some object
  begins bdescrs must be valid. For this simplicity this is achieved by
  restricting the maximum size of a compact block to 252 block allocator
  blocks (so that the total with the bdescr is one megablock).

  Compacts as a whole live in special list in each generation, where the
  list is held through the bd->link field of the bdescr of the StgCompactNFData
  closure (as for large objects). They live in a different list than large
  objects because the operation to free them is different (all blocks in
  a compact must be freed individually), and stats/sanity behavior are
  slightly different. This is also the reason that compact allocates memory
  using a special function instead of just calling allocate().

  Compacts are also suitable for network or disk serialization, and to
  that extent they support a pointer fixup operation, which adjusts pointers
  from a previous layout of the chain in memory to the new allocation.
  This works by constructing a temporary binary search table (in the C heap)
  of the old block addresses (which are known from the block header), and
  then searching for each pointer in the table, and adjusting it.
  It relies on ABI compatibility and static linking (or no ASLR) because it
  does not attempt to reconstruct info tables, and uses info tables to detect
  pointers. In practice this means only the exact same binary should be
  used.
*/
gcampax's avatar
gcampax committed
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

typedef enum {
    ALLOCATE_APPEND,
    ALLOCATE_NEW,
    ALLOCATE_IMPORT_NEW,
    ALLOCATE_IMPORT_APPEND,
} AllocateOp;

static StgCompactNFDataBlock *
compactAllocateBlockInternal(Capability            *cap,
                             StgWord                aligned_size,
                             StgCompactNFDataBlock *first,
                             AllocateOp             operation)
{
    StgCompactNFDataBlock *self;
    bdescr *block, *head;
    uint32_t n_blocks;
    generation *g;

    n_blocks = aligned_size / BLOCK_SIZE;

    // Attempting to allocate an object larger than maxHeapSize
    // should definitely be disallowed.  (bug #1791)
    if ((RtsFlags.GcFlags.maxHeapSize > 0 &&
         n_blocks >= RtsFlags.GcFlags.maxHeapSize) ||
        n_blocks >= HS_INT32_MAX)   // avoid overflow when
                                    // calling allocGroup() below
    {
180 181
        reportHeapOverflow();
        // reportHeapOverflow() doesn't exit (see #2592), but we aren't
gcampax's avatar
gcampax committed
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
        // in a position to do a clean shutdown here: we
        // either have to allocate the memory or exit now.
        // Allocating the memory would be bad, because the user
        // has requested that we not exceed maxHeapSize, so we
        // just exit.
        stg_exit(EXIT_HEAPOVERFLOW);
    }

    // It is imperative that first is the first block in the compact
    // (or NULL if the compact does not exist yet)
    // because the evacuate code does not update the generation of
    // blocks other than the first (so we would get the statistics
    // wrong and crash in Sanity)
    if (first != NULL) {
        block = Bdescr((P_)first);
        g = block->gen;
    } else {
        g = g0;
    }

    ACQUIRE_SM_LOCK;
    block = allocGroup(n_blocks);
    switch (operation) {
    case ALLOCATE_NEW:
Ben Gamari's avatar
Ben Gamari committed
206 207
        ASSERT(first == NULL);
        ASSERT(g == g0);
gcampax's avatar
gcampax committed
208 209 210 211 212 213 214
        dbl_link_onto(block, &g0->compact_objects);
        g->n_compact_blocks += block->blocks;
        g->n_new_large_words += aligned_size / sizeof(StgWord);
        break;

    case ALLOCATE_IMPORT_NEW:
        dbl_link_onto(block, &g0->compact_blocks_in_import);
Ben Gamari's avatar
Ben Gamari committed
215
        FALLTHROUGH;
gcampax's avatar
gcampax committed
216
    case ALLOCATE_IMPORT_APPEND:
Ben Gamari's avatar
Ben Gamari committed
217 218
        ASSERT(first == NULL);
        ASSERT(g == g0);
gcampax's avatar
gcampax committed
219 220 221 222 223 224 225 226 227 228 229
        g->n_compact_blocks_in_import += block->blocks;
        g->n_new_large_words += aligned_size / sizeof(StgWord);
        break;

    case ALLOCATE_APPEND:
        g->n_compact_blocks += block->blocks;
        if (g == g0)
            g->n_new_large_words += aligned_size / sizeof(StgWord);
        break;

    default:
Ben Gamari's avatar
Ben Gamari committed
230
#if defined(DEBUG)
gcampax's avatar
gcampax committed
231
        ASSERT(!"code should not be reached");
232
#else
233
        RTS_UNREACHABLE;
gcampax's avatar
gcampax committed
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
#endif
    }
    RELEASE_SM_LOCK;

    cap->total_allocated += aligned_size / sizeof(StgWord);

    self = (StgCompactNFDataBlock*) block->start;
    self->self = self;
    self->next = NULL;

    head = block;
    initBdescr(head, g, g);
    head->flags = BF_COMPACT;
    for (block = head + 1, n_blocks --; n_blocks > 0; block++, n_blocks--) {
        block->link = head;
        block->blocks = 0;
        block->flags = BF_COMPACT;
    }

    return self;
}

static inline StgCompactNFDataBlock *
compactGetFirstBlock(StgCompactNFData *str)
{
    return (StgCompactNFDataBlock*) ((W_)str - sizeof(StgCompactNFDataBlock));
}

static inline StgCompactNFData *
firstBlockGetCompact(StgCompactNFDataBlock *block)
{
    return (StgCompactNFData*) ((W_)block + sizeof(StgCompactNFDataBlock));
}

268 269
void
compactFree(StgCompactNFData *str)
gcampax's avatar
gcampax committed
270
{
271
    StgCompactNFDataBlock *block, *next;
gcampax's avatar
gcampax committed
272 273
    bdescr *bd;

274 275
    block = compactGetFirstBlock(str);

gcampax's avatar
gcampax committed
276 277 278 279 280 281 282 283
    for ( ; block; block = next) {
        next = block->next;
        bd = Bdescr((StgPtr)block);
        ASSERT((bd->flags & BF_EVACUATED) == 0);
        freeGroup(bd);
    }
}

284
#if defined(DEBUG)
gcampax's avatar
gcampax committed
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
void
compactMarkKnown(StgCompactNFData *str)
{
    bdescr *bd;
    StgCompactNFDataBlock *block;

    block = compactGetFirstBlock(str);
    for ( ; block; block = block->next) {
        bd = Bdescr((StgPtr)block);
        bd->flags |= BF_KNOWN;
    }
}

StgWord
countCompactBlocks(bdescr *outer)
{
    StgCompactNFDataBlock *block;
    W_ count;

    count = 0;
    while (outer) {
        bdescr *inner;

        block = (StgCompactNFDataBlock*)(outer->start);
        do {
            inner = Bdescr((P_)block);
Ben Gamari's avatar
Ben Gamari committed
311
            ASSERT(inner->flags & BF_COMPACT);
gcampax's avatar
gcampax committed
312 313 314 315 316 317 318 319 320 321 322

            count += inner->blocks;
            block = block->next;
        } while(block);

        outer = outer->link;
    }

    return count;
}

323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
// Like countCompactBlocks, but adjusts the size so each mblock is assumed to
// only contain BLOCKS_PER_MBLOCK blocks.  Used in memInventory().
StgWord
countAllocdCompactBlocks(bdescr *outer)
{
    StgCompactNFDataBlock *block;
    W_ count;

    count = 0;
    while (outer) {
        bdescr *inner;

        block = (StgCompactNFDataBlock*)(outer->start);
        do {
            inner = Bdescr((P_)block);
Ben Gamari's avatar
Ben Gamari committed
338
            ASSERT(inner->flags & BF_COMPACT);
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355

            count += inner->blocks;
            // See BlockAlloc.c:countAllocdBlocks()
            if (inner->blocks > BLOCKS_PER_MBLOCK) {
                count -= (MBLOCK_SIZE / BLOCK_SIZE - BLOCKS_PER_MBLOCK)
                    * (inner->blocks/(MBLOCK_SIZE/BLOCK_SIZE));
            }
            block = block->next;
        } while(block);

        outer = outer->link;
    }

    return count;
}
#endif

gcampax's avatar
gcampax committed
356 357 358 359 360 361 362 363
StgCompactNFData *
compactNew (Capability *cap, StgWord size)
{
    StgWord aligned_size;
    StgCompactNFDataBlock *block;
    StgCompactNFData *self;
    bdescr *bd;

364
    aligned_size = BLOCK_ROUND_UP(size + sizeof(StgCompactNFData)
gcampax's avatar
gcampax committed
365
                                  + sizeof(StgCompactNFDataBlock));
366 367 368

    // Don't allow sizes larger than a megablock, because we can't use the
    // memory after the first mblock for storing objects.
gcampax's avatar
gcampax committed
369 370 371 372 373 374 375
    if (aligned_size >= BLOCK_SIZE * BLOCKS_PER_MBLOCK)
        aligned_size = BLOCK_SIZE * BLOCKS_PER_MBLOCK;

    block = compactAllocateBlockInternal(cap, aligned_size, NULL,
                                         ALLOCATE_NEW);

    self = firstBlockGetCompact(block);
376
    SET_HDR((StgClosure*)self, &stg_COMPACT_NFDATA_CLEAN_info, CCS_SYSTEM);
gcampax's avatar
gcampax committed
377 378 379
    self->autoBlockW = aligned_size / sizeof(StgWord);
    self->nursery = block;
    self->last = block;
380
    self->hash = NULL;
gcampax's avatar
gcampax committed
381 382 383 384 385

    block->owner = self;

    bd = Bdescr((P_)block);
    bd->free = (StgPtr)((W_)self + sizeof(StgCompactNFData));
386 387
    self->hp = bd->free;
    self->hpLim = bd->start + bd->blocks * BLOCK_SIZE_W;
gcampax's avatar
gcampax committed
388 389 390

    self->totalW = bd->blocks * BLOCK_SIZE_W;

391 392
    debugTrace(DEBUG_compact, "compactNew: size %" FMT_Word, size);

gcampax's avatar
gcampax committed
393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409
    return self;
}

static StgCompactNFDataBlock *
compactAppendBlock (Capability       *cap,
                    StgCompactNFData *str,
                    StgWord           aligned_size)
{
    StgCompactNFDataBlock *block;
    bdescr *bd;

    block = compactAllocateBlockInternal(cap, aligned_size,
                                         compactGetFirstBlock(str),
                                         ALLOCATE_APPEND);
    block->owner = str;
    block->next = NULL;

Ben Gamari's avatar
Ben Gamari committed
410
    ASSERT(str->last->next == NULL);
gcampax's avatar
gcampax committed
411 412 413 414 415
    str->last->next = block;
    str->last = block;

    bd = Bdescr((P_)block);
    bd->free = (StgPtr)((W_)block + sizeof(StgCompactNFDataBlock));
Ben Gamari's avatar
Ben Gamari committed
416
    ASSERT(bd->free == (StgPtr)block + sizeofW(StgCompactNFDataBlock));
gcampax's avatar
gcampax committed
417 418 419 420 421 422 423 424 425 426 427 428

    str->totalW += bd->blocks * BLOCK_SIZE_W;

    return block;
}

void
compactResize (Capability *cap, StgCompactNFData *str, StgWord new_size)
{
    StgWord aligned_size;

    aligned_size = BLOCK_ROUND_UP(new_size + sizeof(StgCompactNFDataBlock));
429 430 431

    // Don't allow sizes larger than a megablock, because we can't use the
    // memory after the first mblock for storing objects.
gcampax's avatar
gcampax committed
432 433 434 435 436 437 438
    if (aligned_size >= BLOCK_SIZE * BLOCKS_PER_MBLOCK)
        aligned_size = BLOCK_SIZE * BLOCKS_PER_MBLOCK;

    str->autoBlockW = aligned_size / sizeof(StgWord);
    compactAppendBlock(cap, str, aligned_size);
}

439 440
STATIC_INLINE bool
has_room_for  (bdescr *bd, StgWord sizeW)
gcampax's avatar
gcampax committed
441
{
442 443
    return (bd->free < bd->start + BLOCK_SIZE_W * BLOCKS_PER_MBLOCK
            && bd->free + sizeW <= bd->start + BLOCK_SIZE_W * bd->blocks);
gcampax's avatar
gcampax committed
444 445
}

Ben Gamari's avatar
Ben Gamari committed
446
static bool
gcampax's avatar
gcampax committed
447 448 449 450 451 452 453 454 455 456 457
block_is_full (StgCompactNFDataBlock *block)
{
    bdescr *bd;

    // We consider a block full if we could not fit
    // an entire closure with 7 payload items
    // (this leaves a slop of 64 bytes at most, but
    // it avoids leaving a block almost empty to fit
    // a large byte array, while at the same time
    // it avoids trying to allocate a large closure
    // in a chain of almost empty blocks)
458 459 460

    bd = Bdescr((StgPtr)block);
    return (!has_room_for(bd,7));
gcampax's avatar
gcampax committed
461 462
}

463 464 465 466
void *
allocateForCompact (Capability *cap,
                    StgCompactNFData *str,
                    StgWord sizeW)
gcampax's avatar
gcampax committed
467
{
468
    StgPtr to;
gcampax's avatar
gcampax committed
469
    StgWord next_size;
470 471 472 473 474 475 476
    StgCompactNFDataBlock *block;
    bdescr *bd;

    ASSERT(str->nursery != NULL);
    ASSERT(str->hp > Bdescr((P_)str->nursery)->start);
    ASSERT(str->hp <= Bdescr((P_)str->nursery)->start +
           Bdescr((P_)str->nursery)->blocks * BLOCK_SIZE_W);
gcampax's avatar
gcampax committed
477 478

 retry:
479 480 481 482 483 484 485 486
    if (str->hp + sizeW < str->hpLim) {
        to = str->hp;
        str->hp += sizeW;
        return to;
    }

    bd = Bdescr((P_)str->nursery);
    bd->free = str->hp;
gcampax's avatar
gcampax committed
487

488 489 490
    // We know it doesn't fit in the nursery
    // if it is a large object, allocate a new block
    if (sizeW > LARGE_OBJECT_THRESHOLD/sizeof(W_)) {
491
        next_size = BLOCK_ROUND_UP(sizeW*sizeof(W_) + sizeof(StgCompactNFDataBlock));
492 493 494 495 496 497 498 499 500 501
        block = compactAppendBlock(cap, str, next_size);
        bd = Bdescr((P_)block);
        to = bd->free;
        bd->free += sizeW;
        return to;
    }

    // move the nursery past full blocks
    if (block_is_full (str->nursery)) {
        do {
gcampax's avatar
gcampax committed
502
            str->nursery = str->nursery->next;
503
        } while (str->nursery && block_is_full(str->nursery));
gcampax's avatar
gcampax committed
504

505 506 507 508 509 510 511 512 513
        if (str->nursery == NULL) {
            str->nursery = compactAppendBlock(cap, str,
                                              str->autoBlockW * sizeof(W_));
        }
        bd = Bdescr((P_)str->nursery);
        str->hp = bd->free;
        str->hpLim = bd->start + bd->blocks * BLOCK_SIZE_W;
        goto retry;
    }
gcampax's avatar
gcampax committed
514

515 516 517 518 519 520 521
    // try subsequent blocks
    for (block = str->nursery->next; block != NULL; block = block->next) {
        bd = Bdescr((P_)block);
        if (has_room_for(bd,sizeW)) {
            to = bd->free;
            bd->free += sizeW;
            return to;
gcampax's avatar
gcampax committed
522 523 524
        }
    }

525
    // If all else fails, allocate a new block of the right size.
526
    next_size = stg_max(str->autoBlockW * sizeof(StgWord),
527 528
                    BLOCK_ROUND_UP(sizeW * sizeof(StgWord)
                                   + sizeof(StgCompactNFDataBlock)));
gcampax's avatar
gcampax committed
529 530

    block = compactAppendBlock(cap, str, next_size);
531 532 533 534
    bd = Bdescr((P_)block);
    to = bd->free;
    bd->free += sizeW;
    return to;
gcampax's avatar
gcampax committed
535 536 537
}


538 539 540 541 542 543
void
insertCompactHash (Capability *cap,
                   StgCompactNFData *str,
                   StgClosure *p, StgClosure *to)
{
    insertHashTable(str->hash, (StgWord)p, (const void*)to);
Ben Gamari's avatar
Ben Gamari committed
544 545 546
    const StgInfoTable **strinfo = &str->header.info;
    if (*strinfo == &stg_COMPACT_NFDATA_CLEAN_info) {
        *strinfo = &stg_COMPACT_NFDATA_DIRTY_info;
547
        recordClosureMutated(cap, (StgClosure*)str);
gcampax's avatar
gcampax committed
548 549 550
    }
}

551 552 553

StgWord
compactContains (StgCompactNFData *str, StgPtr what)
gcampax's avatar
gcampax committed
554 555 556
{
    bdescr *bd;

557 558 559 560
    // This check is the reason why this needs to be
    // implemented in C instead of (possibly faster) Cmm
    if (!HEAP_ALLOCED (what))
        return 0;
gcampax's avatar
gcampax committed
561

562 563 564
    // Note that we don't care about tags, they are eaten
    // away by the Bdescr operation anyway
    bd = Bdescr((P_)what);
gcampax's avatar
gcampax committed
565
    return (bd->flags & BF_COMPACT) != 0 &&
566
        (str == NULL || objectGetCompact((StgClosure*)what) == str);
gcampax's avatar
gcampax committed
567 568
}

569 570 571 572
StgCompactNFDataBlock *
compactAllocateBlock(Capability            *cap,
                     StgWord                size,
                     StgCompactNFDataBlock *previous)
gcampax's avatar
gcampax committed
573
{
574 575 576
    StgWord aligned_size;
    StgCompactNFDataBlock *block;
    bdescr *bd;
gcampax's avatar
gcampax committed
577

578
    aligned_size = BLOCK_ROUND_UP(size);
gcampax's avatar
gcampax committed
579

580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596
    // We do not link the new object into the generation ever
    // - we cannot let the GC know about this object until we're done
    // importing it and we have fixed up all info tables and stuff
    //
    // but we do update n_compact_blocks, otherwise memInventory()
    // in Sanity will think we have a memory leak, because it compares
    // the blocks he knows about with the blocks obtained by the
    // block allocator
    // (if by chance a memory leak does happen due to a bug somewhere
    // else, memInventory will also report that all compact blocks
    // associated with this compact are leaked - but they are not really,
    // we have a pointer to them and we're not losing track of it, it's
    // just we can't use the GC until we're done with the import)
    //
    // (That btw means that the high level import code must be careful
    // not to lose the pointer, so don't use the primops directly
    // unless you know what you're doing!)
gcampax's avatar
gcampax committed
597

598 599 600 601
    // Other trickery: we pass NULL as first, which means our blocks
    // are always in generation 0
    // This is correct because the GC has never seen the blocks so
    // it had no chance of promoting them
gcampax's avatar
gcampax committed
602

603 604 605 606
    block = compactAllocateBlockInternal(cap, aligned_size, NULL,
                                         previous != NULL ? ALLOCATE_IMPORT_APPEND : ALLOCATE_IMPORT_NEW);
    if (previous != NULL)
        previous->next = block;
gcampax's avatar
gcampax committed
607

608 609
    bd = Bdescr((P_)block);
    bd->free = (P_)((W_)bd->start + size);
gcampax's avatar
gcampax committed
610

611
    return block;
gcampax's avatar
gcampax committed
612 613
}

614 615 616 617 618 619 620
//
// shouldCompact(c,p): returns:
//    SHOULDCOMPACT_IN_CNF if the object is in c
//    SHOULDCOMPACT_STATIC if the object is static
//    SHOULDCOMPACT_NOTIN_CNF if the object is dynamic and not in c
//
StgWord shouldCompact (StgCompactNFData *str, StgClosure *p)
gcampax's avatar
gcampax committed
621
{
622
    bdescr *bd;
gcampax's avatar
gcampax committed
623

624 625
    if (!HEAP_ALLOCED(p))
        return SHOULDCOMPACT_STATIC;  // we have to copy static closures too
gcampax's avatar
gcampax committed
626

627 628 629
    bd = Bdescr((P_)p);
    if (bd->flags & BF_PINNED) {
        return SHOULDCOMPACT_PINNED;
gcampax's avatar
gcampax committed
630
    }
631 632 633 634
    if ((bd->flags & BF_COMPACT) && objectGetCompact(p) == str) {
        return SHOULDCOMPACT_IN_CNF;
    } else {
        return SHOULDCOMPACT_NOTIN_CNF;
gcampax's avatar
gcampax committed
635 636 637
    }
}

638 639 640 641
/* -----------------------------------------------------------------------------
   Sanity-checking a compact
   -------------------------------------------------------------------------- */

Ben Gamari's avatar
Ben Gamari committed
642
#if defined(DEBUG)
643 644
STATIC_INLINE void
check_object_in_compact (StgCompactNFData *str, StgClosure *p)
gcampax's avatar
gcampax committed
645
{
646
    bdescr *bd;
gcampax's avatar
gcampax committed
647

648 649 650 651 652
    // Only certain static closures are allowed to be referenced from
    // a compact, but let's be generous here and assume that all
    // static closures are OK.
    if (!HEAP_ALLOCED(p))
        return;
gcampax's avatar
gcampax committed
653

654 655
    bd = Bdescr((P_)p);
    ASSERT((bd->flags & BF_COMPACT) != 0 && objectGetCompact(p) == str);
gcampax's avatar
gcampax committed
656 657
}

658
static void
gcampax's avatar
gcampax committed
659 660 661 662 663 664 665 666
verify_mut_arr_ptrs (StgCompactNFData *str,
                     StgMutArrPtrs    *a)
{
    StgPtr p, q;

    p = (StgPtr)&a->payload[0];
    q = (StgPtr)&a->payload[a->ptrs];
    for (; p < q; p++) {
667
        check_object_in_compact(str, UNTAG_CLOSURE(*(StgClosure**)p));
gcampax's avatar
gcampax committed
668 669
    }

670
    return;
gcampax's avatar
gcampax committed
671 672
}

673
static void
gcampax's avatar
gcampax committed
674 675 676 677 678 679 680 681 682 683 684 685
verify_consistency_block (StgCompactNFData *str, StgCompactNFDataBlock *block)
{
    bdescr *bd;
    StgPtr p;
    const StgInfoTable *info;
    StgClosure *q;

    p = (P_)firstBlockGetCompact(block);
    bd = Bdescr((P_)block);
    while (p < bd->free) {
        q = (StgClosure*)p;

686
        ASSERT(LOOKS_LIKE_CLOSURE_PTR(q));
gcampax's avatar
gcampax committed
687 688 689 690

        info = get_itbl(q);
        switch (info->type) {
        case CONSTR_1_0:
691
            check_object_in_compact(str, UNTAG_CLOSURE(q->payload[0]));
Ben Gamari's avatar
Ben Gamari committed
692
            FALLTHROUGH;
gcampax's avatar
gcampax committed
693 694 695 696 697
        case CONSTR_0_1:
            p += sizeofW(StgClosure) + 1;
            break;

        case CONSTR_2_0:
698
            check_object_in_compact(str, UNTAG_CLOSURE(q->payload[1]));
Ben Gamari's avatar
Ben Gamari committed
699
            FALLTHROUGH;
gcampax's avatar
gcampax committed
700
        case CONSTR_1_1:
701
            check_object_in_compact(str, UNTAG_CLOSURE(q->payload[0]));
Ben Gamari's avatar
Ben Gamari committed
702
            FALLTHROUGH;
gcampax's avatar
gcampax committed
703 704 705 706 707 708
        case CONSTR_0_2:
            p += sizeofW(StgClosure) + 2;
            break;

        case CONSTR:
        case PRIM:
Simon Marlow's avatar
Simon Marlow committed
709
        case CONSTR_NOCAF:
gcampax's avatar
gcampax committed
710 711 712
        {
            uint32_t i;

713 714 715
            for (i = 0; i < info->layout.payload.ptrs; i++) {
                check_object_in_compact(str, UNTAG_CLOSURE(q->payload[i]));
            }
gcampax's avatar
gcampax committed
716 717 718 719 720 721 722 723 724
            p += sizeofW(StgClosure) + info->layout.payload.ptrs +
                info->layout.payload.nptrs;
            break;
        }

        case ARR_WORDS:
            p += arr_words_sizeW((StgArrBytes*)p);
            break;

725 726
        case MUT_ARR_PTRS_FROZEN_CLEAN:
        case MUT_ARR_PTRS_FROZEN_DIRTY:
727
            verify_mut_arr_ptrs(str, (StgMutArrPtrs*)p);
gcampax's avatar
gcampax committed
728 729 730
            p += mut_arr_ptrs_sizeW((StgMutArrPtrs*)p);
            break;

731 732
        case SMALL_MUT_ARR_PTRS_FROZEN_CLEAN:
        case SMALL_MUT_ARR_PTRS_FROZEN_DIRTY:
gcampax's avatar
gcampax committed
733 734 735 736 737
        {
            uint32_t i;
            StgSmallMutArrPtrs *arr = (StgSmallMutArrPtrs*)p;

            for (i = 0; i < arr->ptrs; i++)
738
                check_object_in_compact(str, UNTAG_CLOSURE(arr->payload[i]));
gcampax's avatar
gcampax committed
739 740 741 742 743 744 745 746 747 748

            p += sizeofW(StgSmallMutArrPtrs) + arr->ptrs;
            break;
        }

        case COMPACT_NFDATA:
            p += sizeofW(StgCompactNFData);
            break;

        default:
749
            barf("verify_consistency_block");
gcampax's avatar
gcampax committed
750 751 752
        }
    }

753
    return;
gcampax's avatar
gcampax committed
754 755
}

756
static void
gcampax's avatar
gcampax committed
757 758 759 760 761 762
verify_consistency_loop (StgCompactNFData *str)
{
    StgCompactNFDataBlock *block;

    block = compactGetFirstBlock(str);
    do {
763
        verify_consistency_block(str, block);
gcampax's avatar
gcampax committed
764 765 766 767
        block = block->next;
    } while (block && block->owner);
}

768
void verifyCompact (StgCompactNFData *str USED_IF_DEBUG)
gcampax's avatar
gcampax committed
769
{
770
    IF_DEBUG(sanity, verify_consistency_loop(str));
gcampax's avatar
gcampax committed
771
}
772
#endif // DEBUG
gcampax's avatar
gcampax committed
773

774 775 776
/* -----------------------------------------------------------------------------
   Fixing up pointers
   -------------------------------------------------------------------------- */
gcampax's avatar
gcampax committed
777

Ben Gamari's avatar
Ben Gamari committed
778
STATIC_INLINE bool
gcampax's avatar
gcampax committed
779 780 781 782 783 784 785 786
any_needs_fixup(StgCompactNFDataBlock *block)
{
    // ->next pointers are always valid, even if some blocks were
    // not allocated where we want them, because compactAllocateAt()
    // will take care to adjust them

    do {
        if (block->self != block)
Ben Gamari's avatar
Ben Gamari committed
787
            return true;
gcampax's avatar
gcampax committed
788 789 790
        block = block->next;
    } while (block && block->owner);

Ben Gamari's avatar
Ben Gamari committed
791
    return false;
gcampax's avatar
gcampax committed
792 793
}

Ben Gamari's avatar
Ben Gamari committed
794
#if defined(DEBUG)
gcampax's avatar
gcampax committed
795 796 797 798 799 800 801 802 803
static void
spew_failing_pointer(StgWord *fixup_table, uint32_t count, StgWord address)
{
    uint32_t i;
    StgWord key, value;
    StgCompactNFDataBlock *block;
    bdescr *bd;
    StgWord size;

804
    debugBelch("Failed to adjust 0x%" FMT_HexWord ". Block dump follows...\n",
gcampax's avatar
gcampax committed
805 806 807 808 809 810 811 812 813 814
               address);

    for (i  = 0; i < count; i++) {
        key = fixup_table [2 * i];
        value = fixup_table [2 * i + 1];

        block = (StgCompactNFDataBlock*)value;
        bd = Bdescr((P_)block);
        size = (W_)bd->free - (W_)bd->start;

815 816 817
        debugBelch("%" FMT_Word32 ": was 0x%" FMT_HexWord "-0x%" FMT_HexWord
                   ", now 0x%" FMT_HexWord "-0x%" FMT_HexWord "\n", i, key,
                   key+size, value, value+size);
gcampax's avatar
gcampax committed
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
    }
}
#endif

STATIC_INLINE StgCompactNFDataBlock *
find_pointer(StgWord *fixup_table, uint32_t count, StgClosure *q)
{
    StgWord address = (W_)q;
    uint32_t a, b, c;
    StgWord key, value;
    bdescr *bd;

    a = 0;
    b = count;
    while (a < b-1) {
        c = (a+b)/2;

        key = fixup_table[c * 2];
        value = fixup_table[c * 2 + 1];

        if (key > address)
            b = c;
        else
            a = c;
    }

    // three cases here: 0, 1 or 2 blocks to check
    for ( ; a < b; a++) {
        key = fixup_table[a * 2];
        value = fixup_table[a * 2 + 1];

        if (key > address)
            goto fail;

        bd = Bdescr((P_)value);

        if (key + bd->blocks * BLOCK_SIZE <= address)
            goto fail;

        return (StgCompactNFDataBlock*)value;
    }

 fail:
    // We should never get here

Ben Gamari's avatar
Ben Gamari committed
863
#if defined(DEBUG)
gcampax's avatar
gcampax committed
864 865 866 867 868
    spew_failing_pointer(fixup_table, count, address);
#endif
    return NULL;
}

Ben Gamari's avatar
Ben Gamari committed
869
static bool
gcampax's avatar
gcampax committed
870 871 872 873 874 875
fixup_one_pointer(StgWord *fixup_table, uint32_t count, StgClosure **p)
{
    StgWord tag;
    StgClosure *q;
    StgCompactNFDataBlock *block;

876

gcampax's avatar
gcampax committed
877 878 879 880
    q = *p;
    tag = GET_CLOSURE_TAG(q);
    q = UNTAG_CLOSURE(q);

881 882 883 884 885 886
    // We can encounter a pointer outside the compact if it points to
    // a static constructor that does not (directly or indirectly)
    // reach any CAFs. (see Note [Compact Normal Forms])
    if (!HEAP_ALLOCED(q))
        return true;

gcampax's avatar
gcampax committed
887 888
    block = find_pointer(fixup_table, count, q);
    if (block == NULL)
Ben Gamari's avatar
Ben Gamari committed
889
        return false;
gcampax's avatar
gcampax committed
890
    if (block == block->self)
Ben Gamari's avatar
Ben Gamari committed
891
        return true;
gcampax's avatar
gcampax committed
892 893 894 895

    q = (StgClosure*)((W_)q - (W_)block->self + (W_)block);
    *p = TAG_CLOSURE(tag, q);

Ben Gamari's avatar
Ben Gamari committed
896
    return true;
gcampax's avatar
gcampax committed
897 898
}

Ben Gamari's avatar
Ben Gamari committed
899
static bool
gcampax's avatar
gcampax committed
900 901 902 903 904 905 906 907 908 909
fixup_mut_arr_ptrs (StgWord          *fixup_table,
                    uint32_t               count,
                    StgMutArrPtrs    *a)
{
    StgPtr p, q;

    p = (StgPtr)&a->payload[0];
    q = (StgPtr)&a->payload[a->ptrs];
    for (; p < q; p++) {
        if (!fixup_one_pointer(fixup_table, count, (StgClosure**)p))
Ben Gamari's avatar
Ben Gamari committed
910
            return false;
gcampax's avatar
gcampax committed
911 912
    }

Ben Gamari's avatar
Ben Gamari committed
913
    return true;
gcampax's avatar
gcampax committed
914 915
}

Ben Gamari's avatar
Ben Gamari committed
916
static bool
gcampax's avatar
gcampax committed
917 918 919 920 921 922 923 924 925
fixup_block(StgCompactNFDataBlock *block, StgWord *fixup_table, uint32_t count)
{
    const StgInfoTable *info;
    bdescr *bd;
    StgPtr p;

    bd = Bdescr((P_)block);
    p = bd->start + sizeofW(StgCompactNFDataBlock);
    while (p < bd->free) {
Ben Gamari's avatar
Ben Gamari committed
926
        ASSERT(LOOKS_LIKE_CLOSURE_PTR(p));
gcampax's avatar
gcampax committed
927 928 929 930 931 932
        info = get_itbl((StgClosure*)p);

        switch (info->type) {
        case CONSTR_1_0:
            if (!fixup_one_pointer(fixup_table, count,
                                   &((StgClosure*)p)->payload[0]))
Ben Gamari's avatar
Ben Gamari committed
933
                return false;
Ben Gamari's avatar
Ben Gamari committed
934
            FALLTHROUGH;
gcampax's avatar
gcampax committed
935 936 937 938 939 940 941
        case CONSTR_0_1:
            p += sizeofW(StgClosure) + 1;
            break;

        case CONSTR_2_0:
            if (!fixup_one_pointer(fixup_table, count,
                                   &((StgClosure*)p)->payload[1]))
Ben Gamari's avatar
Ben Gamari committed
942
                return false;
Ben Gamari's avatar
Ben Gamari committed
943
            FALLTHROUGH;
gcampax's avatar
gcampax committed
944 945 946
        case CONSTR_1_1:
            if (!fixup_one_pointer(fixup_table, count,
                                   &((StgClosure*)p)->payload[0]))
Ben Gamari's avatar
Ben Gamari committed
947
                return false;
Ben Gamari's avatar
Ben Gamari committed
948
            FALLTHROUGH;
gcampax's avatar
gcampax committed
949 950 951 952 953 954
        case CONSTR_0_2:
            p += sizeofW(StgClosure) + 2;
            break;

        case CONSTR:
        case PRIM:
Simon Marlow's avatar
Simon Marlow committed
955
        case CONSTR_NOCAF:
gcampax's avatar
gcampax committed
956 957 958 959 960 961
        {
            StgPtr end;

            end = (P_)((StgClosure *)p)->payload + info->layout.payload.ptrs;
            for (p = (P_)((StgClosure *)p)->payload; p < end; p++) {
                if (!fixup_one_pointer(fixup_table, count, (StgClosure **)p))
Ben Gamari's avatar
Ben Gamari committed
962
                    return false;
gcampax's avatar
gcampax committed
963 964 965 966 967 968 969 970 971
            }
            p += info->layout.payload.nptrs;
            break;
        }

        case ARR_WORDS:
            p += arr_words_sizeW((StgArrBytes*)p);
            break;

972 973
        case MUT_ARR_PTRS_FROZEN_CLEAN:
        case MUT_ARR_PTRS_FROZEN_DIRTY:
gcampax's avatar
gcampax committed
974 975 976 977
            fixup_mut_arr_ptrs(fixup_table, count, (StgMutArrPtrs*)p);
            p += mut_arr_ptrs_sizeW((StgMutArrPtrs*)p);
            break;

978 979
        case SMALL_MUT_ARR_PTRS_FROZEN_CLEAN:
        case SMALL_MUT_ARR_PTRS_FROZEN_DIRTY:
gcampax's avatar
gcampax committed
980 981 982 983 984 985 986
        {
            uint32_t i;
            StgSmallMutArrPtrs *arr = (StgSmallMutArrPtrs*)p;

            for (i = 0; i < arr->ptrs; i++) {
                if (!fixup_one_pointer(fixup_table, count,
                                       &arr->payload[i]))
Ben Gamari's avatar
Ben Gamari committed
987
                    return false;
gcampax's avatar
gcampax committed
988 989 990 991 992 993 994 995 996 997 998 999 1000 1001
            }

            p += sizeofW(StgSmallMutArrPtrs) + arr->ptrs;
            break;
        }

        case COMPACT_NFDATA:
            if (p == (bd->start + sizeofW(StgCompactNFDataBlock))) {
                // Ignore the COMPACT_NFDATA header
                // (it will be fixed up later)
                p += sizeofW(StgCompactNFData);
                break;
            }

Ben Gamari's avatar
Ben Gamari committed
1002
            FALLTHROUGH;
gcampax's avatar
gcampax committed
1003 1004 1005 1006

        default:
            debugBelch("Invalid non-NFData closure (type %d) in Compact\n",
                       info->type);
Ben Gamari's avatar
Ben Gamari committed
1007
            return false;
gcampax's avatar
gcampax committed
1008 1009 1010
        }
    }

Ben Gamari's avatar
Ben Gamari committed
1011
    return true;
gcampax's avatar
gcampax committed
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
}

static int
cmp_fixup_table_item (const void *e1, const void *e2)
{
    const StgWord *w1 = e1;
    const StgWord *w2 = e2;

    return *w1 - *w2;
}

static StgWord *
build_fixup_table (StgCompactNFDataBlock *block, uint32_t *pcount)
{
    uint32_t count;
    StgCompactNFDataBlock *tmp;
    StgWord *table;

    count = 0;
    tmp = block;
    do {
        count++;
        tmp = tmp->next;
    } while(tmp && tmp->owner);

    table = stgMallocBytes(sizeof(StgWord) * 2 * count, "build_fixup_table");

    count = 0;
    do {
        table[count * 2] = (W_)block->self;
        table[count * 2 + 1] = (W_)block;
        count++;
        block = block->next;
    } while(block && block->owner);

    qsort(table, count, sizeof(StgWord) * 2, cmp_fixup_table_item);

    *pcount = count;
    return table;
}

Ben Gamari's avatar
Ben Gamari committed
1053
static bool
gcampax's avatar
gcampax committed
1054 1055 1056
fixup_loop(StgCompactNFDataBlock *block, StgClosure **proot)
{
    StgWord *table;
Ben Gamari's avatar
Ben Gamari committed
1057
    bool ok;
gcampax's avatar
gcampax committed
1058 1059 1060 1061 1062 1063
    uint32_t count;

    table = build_fixup_table (block, &count);

    do {
        if (!fixup_block(block, table, count)) {
Ben Gamari's avatar
Ben Gamari committed
1064
            ok = false;
gcampax's avatar
gcampax committed
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
            goto out;
        }

        block = block->next;
    } while(block && block->owner);

    ok = fixup_one_pointer(table, count, proot);

 out:
    stgFree(table);
    return ok;
}

static void
fixup_early(StgCompactNFData *str, StgCompactNFDataBlock *block)
{
    StgCompactNFDataBlock *last;

    do {
        last = block;
        block = block->next;
    } while(block);

    str->last = last;
}

static void
fixup_late(StgCompactNFData *str, StgCompactNFDataBlock *block)
{
    StgCompactNFDataBlock *nursery;
    bdescr *bd;
    StgWord totalW;

    nursery = block;
    totalW = 0;
    do {
        block->self = block;

        bd = Bdescr((P_)block);
        totalW += bd->blocks * BLOCK_SIZE_W;

        if (block->owner != NULL) {
            if (bd->free != bd->start)
                nursery = block;
            block->owner = str;
        }

        block = block->next;
    } while(block);

    str->nursery = nursery;
1116 1117 1118 1119
    bd = Bdescr((P_)nursery);
    str->hp = bd->free;
    str->hpLim = bd->start + bd->blocks * BLOCK_SIZE_W;

gcampax's avatar
gcampax committed
1120 1121 1122 1123 1124 1125 1126
    str->totalW = totalW;
}

static StgClosure *
maybe_fixup_internal_pointers (StgCompactNFDataBlock *block,
                               StgClosure            *root)
{
Ben Gamari's avatar
Ben Gamari committed
1127
    bool ok;
gcampax's avatar
gcampax committed
1128 1129 1130 1131 1132 1133
    StgClosure **proot;

    // Check for fast path
    if (!any_needs_fixup(block))
        return root;

1134
    IF_DEBUG(compact, debugBelch("Compact imported at the wrong address, "
1135
                            "will fix up internal pointers\n"));
gcampax's avatar
gcampax committed
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 1167 1168 1169 1170 1171

    // I am PROOT!
    proot = &root;

    ok = fixup_loop(block, proot);
    if (!ok)
        *proot = NULL;

    return *proot;
}

StgPtr
compactFixupPointers(StgCompactNFData *str,
                     StgClosure       *root)
{
    StgCompactNFDataBlock *block;
    bdescr *bd;
    StgWord total_blocks;

    block = compactGetFirstBlock(str);

    fixup_early(str, block);

    root = maybe_fixup_internal_pointers(block, root);

    // Do the late fixup even if we did not fixup all
    // internal pointers, we need that for GC and Sanity
    fixup_late(str, block);

    // Now we're ready to let the GC, Sanity, the profiler
    // etc. know about this object
    bd = Bdescr((P_)block);

    total_blocks = str->totalW / BLOCK_SIZE_W;

    ACQUIRE_SM_LOCK;
Ben Gamari's avatar
Ben Gamari committed
1172 1173
    ASSERT(bd->gen == g0);
    ASSERT(g0->n_compact_blocks_in_import >= total_blocks);
gcampax's avatar
gcampax committed
1174 1175 1176 1177 1178 1179
    g0->n_compact_blocks_in_import -= total_blocks;
    g0->n_compact_blocks += total_blocks;
    dbl_link_remove(bd, &g0->compact_blocks_in_import);
    dbl_link_onto(bd, &g0->compact_objects);
    RELEASE_SM_LOCK;

Ben Gamari's avatar
Ben Gamari committed
1180
#if defined(DEBUG)
gcampax's avatar
gcampax committed
1181 1182 1183 1184 1185 1186
    if (root)
        verify_consistency_loop(str);
#endif

    return (StgPtr)root;
}