1
/*
2
 * $Id$
3
 *
4
 * Copyright (C) 2003-2009 JNode.org
5
 *
6
 * This library is free software; you can redistribute it and/or modify it
7
 * under the terms of the GNU Lesser General Public License as published
8
 * by the Free Software Foundation; either version 2.1 of the License, or
9
 * (at your option) any later version.
10
 *
11
 * This library is distributed in the hope that it will be useful, but 
12
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
13
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public 
14
 * License for more details.
15
 *
16
 * You should have received a copy of the GNU Lesser General Public License
17
 * along with this library; If not, write to the Free Software Foundation, Inc., 
18
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19
 */
20
21
package org.jnode.vm.memmgr.generational;
22
23
import org.jnode.annotation.Inline;
24
import org.jnode.annotation.MagicPermission;
25
import org.jnode.vm.ObjectVisitor;
26
import org.jnode.vm.VmMagic;
27
import org.jnode.vm.classmgr.ObjectFlags;
28
import org.jnode.vm.classmgr.ObjectLayout;
29
import org.jnode.vm.classmgr.VmClassType;
30
import org.jnode.vm.classmgr.VmNormalClass;
31
import org.jnode.vm.classmgr.VmType;
32
import org.jnode.vm.memmgr.HeapHelper;
33
import org.vmmagic.pragma.UninterruptiblePragma;
34
import org.vmmagic.unboxed.Address;
35
import org.vmmagic.unboxed.Extent;
36
import org.vmmagic.unboxed.ObjectReference;
37
import org.vmmagic.unboxed.Offset;
38
import org.vmmagic.unboxed.Word;
39
40
/**
41
 * @author epr
42
 */
43
@MagicPermission
44
public final class VmDefaultHeap extends VmAbstractHeap implements ObjectFlags {
45
46
    /**
47
     * Offset within this heap of the next free memory block
48
     */
49
    private Address nextFreePtr;
50
51
    /**
52
     * The allocation bitmap as object, so we won't throw it away in a GC cycle
53
     */
54
    private Object allocationBitmap;
55
56
    /**
57
     * The total size of free space
58
     */
59
    private Extent freeSize;
60
61
    /**
62
     * Offset (in bytes) from the start of an object to the size of an object
63
     */
64
    private Offset sizeOffset;
65
66
    /**
67
     * Offset (in bytes) from the start of an object to the size of an object
68
     */
69
    private static Offset objectSizeOffset;
70
71
    /**
72
     * The next heap (linked list)
73
     */
74
    private VmDefaultHeap next;
75
76
    /**
77
     * Initialize this instance
78
     * 
79
     * @param heapMgr
80
     */
81
82
    public VmDefaultHeap(HeapHelper heapHelper) {
83
        super(heapHelper);
84
    }
85
86
    public static void initializeSizeOffset(int slotSize) {
87
        objectSizeOffset = Offset.fromIntSignExtend(-((ObjectLayout.HEADER_SLOTS + 1) * slotSize));
88
    }
89
90
    public static long getObjectSize(Object object) {
91
        return ObjectReference.fromObject(object).toAddress().add(objectSizeOffset).loadInt();
92
    }
93
94
    /**
95
     * Setup the heap object according to the given start-address of the heap.
96
     * 
97
     * @param start
98
     * @param heapClass
99
     * @param slotSize
100
     * @return the heap
101
     */
102
    public static VmDefaultHeap setupHeap(HeapHelper helper, Address start,
103
            VmNormalClass<VmDefaultHeap> heapClass, int slotSize) {
104
        //Unsafe.debug("Begin: setupHead");
105
        final int headerSize = ObjectLayout.objectAlign((ObjectLayout.HEADER_SLOTS + 3) * slotSize);
106
        final Offset vmtOffset = Offset.fromIntSignExtend(ObjectLayout.TIB_SLOT * slotSize);
107
        final Offset sizeOffset = Offset
108
                .fromIntSignExtend(-((ObjectLayout.HEADER_SLOTS + 1) * slotSize));
109
        final Offset flagsOffset = Offset.fromIntSignExtend(ObjectLayout.FLAGS_SLOT * slotSize);
110
        final Offset ageOffset = Offset.fromIntSignExtend(ObjectLayout.COLLECTION_AGE_SLOT
111
                * slotSize);
112
        final Offset nbRefOffset = Offset.fromIntSignExtend(ObjectLayout.NB_REFS_SLOT * slotSize);
113
114
        // Setup a heap object, so the heap can initialize itself.
115
        final Address heapPtr = start.add(headerSize);
116
        final Word heapObjSize = Word.fromIntZeroExtend(ObjectLayout.objectAlign(heapClass
117
                .getObjectSize()));
118
        final Word flags = Word.fromIntZeroExtend(ObjectFlags.GC_DEFAULT_COLOR);
119
        heapPtr.store(heapObjSize, sizeOffset);
120
        heapPtr.store(flags, flagsOffset);
121
        heapPtr.store(ObjectFlags.OLD_OBJECT, ageOffset);
122
        heapPtr.store(1, nbRefOffset);
123
        heapPtr.store(ObjectReference.fromObject(heapClass.getTIB()), vmtOffset);
124
        helper.clear(heapPtr, heapObjSize.toInt());
125
126
        VmDefaultHeap heap = (VmDefaultHeap) heapPtr.toObjectReference().toObject();
127
        heap.helper = helper;
128
        //Unsafe.debug("End: setupHead");
129
        return heap;
130
    }
131
132
    /**
133
     * Append a new heap to the end of the linked list of heaps.
134
     * 
135
     * @param newHeap
136
     */
137
    public final void append(VmDefaultHeap newHeap) {
138
        VmDefaultHeap heap = this;
139
        while (heap.next != null) {
140
            heap = heap.next;
141
        }
142
        heap.next = newHeap;
143
    }
144
145
    /**
146
     * Gets the next heap in the linked list of heaps.
147
     * 
148
     * @return Next heap
149
     */
150
    @Inline
151
    public final VmDefaultHeap getNext() {
152
        return next;
153
    }
154
155
    /**
156
     * Initialize this heap
157
     * 
158
     * @param start
159
     *            Start address of this heap
160
     * @param end
161
     *            End address of this heap (first address after this heap)
162
     * @param slotSize
163
     */
164
    @Override
165
    public void initialize(Address start, Address end, int slotSize) {
166
167
        // Set my variables
168
        this.start = start;
169
        this.end = end;
170
        initializeAbstract(slotSize);
171
        this.sizeOffset = Offset.fromIntSignExtend(-((ObjectLayout.HEADER_SLOTS + 1) * slotSize));
172
        this.headerSize = ObjectLayout.objectAlign(this.headerSize + slotSize);
173
        final int size = getSize();
174
175
        final Address myAddr = ObjectReference.fromObject(this).toAddress();
176
        final Word mySize = myAddr.loadWord(sizeOffset);
177
        Address firstObject;
178
        if (inHeap(myAddr)) {
179
            firstObject = myAddr.add(mySize).add(headerSize);
180
        } else {
181
            firstObject = start.add(headerSize);
182
        }
183
184
        // Initialize an allocation bitmap
185
        final int allocationBits = size / ObjectLayout.OBJECT_ALIGN;
186
        final int allocationBitmapSize = ObjectLayout.objectAlign((allocationBits + 7) / 8);
187
        this.allocationBitmapPtr = firstObject;
188
        final Address bitmapPtr = this.allocationBitmapPtr;
189
        // Make the bitmap an object, so it is easy to manipulate.
190
        bitmapPtr.store(Word.fromIntZeroExtend(allocationBitmapSize), sizeOffset);
191
        bitmapPtr.store(Word.fromIntZeroExtend(GC_DEFAULT_COLOR), flagsOffset);
192
        bitmapPtr.store(Word.fromIntZeroExtend(OLD_OBJECT), ageOffset);
193
        bitmapPtr.store(Word.fromIntZeroExtend(1), nbRefOffset);
194
        bitmapPtr.store(ObjectReference.fromObject(VmType.getObjectClass().getTIB()), tibOffset);
195
        firstObject = firstObject.add(allocationBitmapSize + headerSize);
196
        helper.clear(allocationBitmapPtr, allocationBitmapSize);
197
        this.allocationBitmap = allocationBitmapPtr.toObjectReference().toObject();
198
199
        // Mark this heap in the allocation bitmap
200
        setAllocationBit(this, true);
201
        // Mark the allocation bitmap in the allocation bitmap
202
        setAllocationBit(allocationBitmap, true);
203
204
        // Initialize the remaining space as free object.
205
        final Word remainingSize = end.toWord().sub(firstObject.toWord());
206
        final Address ptr = firstObject;
207
        ptr.store(remainingSize, sizeOffset);
208
        ptr.store(ObjectReference.fromObject(FREE), tibOffset);
209
        this.nextFreePtr = ptr;
210
        this.freeSize = remainingSize.toExtent();
211
    }
212
213
    /**
214
     * Allocate a new instance for the given class. Not that this method cannot
215
     * be synchronized, since the synchronization is handled in VmHeap.
216
     * 
217
     * @param vmClass
218
     * @param alignedSize
219
     * @return Object Null if no space is left.
220
     */
221
    public Object alloc(VmClassType<?> vmClass, int alignedSize) {
222
223
        if (nextFreePtr.EQ(Address.zero())) { /* This heap is full */
224
            return null;
225
        }
226
227
        final Offset tibOffset = this.tibOffset;
228
        final Word headerSize = Word.fromIntZeroExtend(this.headerSize);
229
        final Offset flagsOffset = this.flagsOffset;
230
        final Offset sizeOffset = this.sizeOffset;
231
        final Offset ageOffset = this.ageOffset;
232
        final Offset nbRefOffset = this.nbRefOffset;
233
234
        Word alignedSizeW = Word.fromIntZeroExtend(alignedSize);
235
        final Word totalSize = alignedSizeW.add(headerSize);
236
        final Object tib = vmClass.getTIB();
237
        if (tib == null) {
238
            throw new IllegalArgumentException("vmClass.TIB is null");
239
        }
240
        // final int size = getSize();
241
        Address objectPtr = Address.zero();
242
        lock();
243
        try {
244
            // Search for the first free block that is large enough
245
            // Screen.debug("a");
246
            while (objectPtr == null) {
247
                final Address ptr = nextFreePtr;
248
                final Word objSize = ptr.loadWord(sizeOffset);
249
                final Object objVmt = ptr.loadObjectReference(tibOffset);
250
                final Address nextPtr = ptr.add(objSize.add(headerSize));
251
                if ((objVmt == FREE) && alignedSizeW.LE(objSize)) {
252
                    objectPtr = ptr;
253
                } else {
254
                    if (!inHeap(nextPtr)) {
255
                        // No large enough free space has been found
256
                        // A collect may recover smaller free spaces in this
257
                        // heap, but we leave that to a GC iteration.
258
                        nextFreePtr = Address.zero();
259
                        // Screen.debug("B");
260
                        return null;
261
                    } else {
262
                        this.nextFreePtr = nextPtr;
263
                    }
264
                }
265
            }
266
            // Screen.debug("A");
267
268
            final Word curFreeSize = objectPtr.loadWord(sizeOffset);
269
            if (curFreeSize.GT(totalSize)) {
270
                // Block is larger then we need, split it up.
271
                final Word newFreeSize = curFreeSize.sub(totalSize);
272
                /*
273
                 * if (newFreeSize <= headerSize) {
274
                 * Unsafe.debug("Block splitup failed");
275
                 * Unsafe.debug("\ncurFreeSize "); Unsafe.debug(curFreeSize);
276
                 * Unsafe.debug("\ntotalSize   "); Unsafe.debug(totalSize);
277
                 * Unsafe.debug("\nnewFreeSize "); Unsafe.debug(newFreeSize);
278
                 * Unsafe.debug("\nheaderSize  "); Unsafe.debug(headerSize);
279
                 * throw new Error("Block splitup failed"); }
280
                 */
281
                final Address newFreePtr = objectPtr.add(totalSize);
282
                // Set the header for the remaining free block
283
                newFreePtr.store(newFreeSize, sizeOffset);
284
                newFreePtr.store(0, flagsOffset);
285
                newFreePtr.store(OLD_OBJECT, ageOffset);
286
                newFreePtr.store(0, nbRefOffset);
287
                newFreePtr.store(ObjectReference.fromObject(FREE), tibOffset);
288
                // Set the next free offset
289
                nextFreePtr = newFreePtr;
290
            } else {
291
                // The block is not large enough to split up, make the
292
                // new object the size of the free block.
293
                alignedSizeW = curFreeSize;
294
            }
295
296
            // Create the object header
297
            objectPtr.store(alignedSizeW, sizeOffset);
298
            objectPtr.store(0, flagsOffset);
299
            objectPtr.store(0, ageOffset);
300
            objectPtr.store(0, nbRefOffset);
301
            objectPtr.store(ObjectReference.fromObject(tib), tibOffset);
302
            // Mark the object in the allocation bitmap
303
            setAllocationBit(objectPtr, true);
304
305
            // Fix the freeSize
306
            freeSize = freeSize.sub(alignedSizeW);
307
        } finally {
308
            unlock();
309
        }
310
311
        // Clear the contents of the object.
312
        helper.clear(objectPtr, alignedSize);
313
314
        return objectPtr.toObjectReference().toObject();
315
    }
316
317
    /**
318
     * Mark the given object as free space.
319
     * 
320
     * @param object
321
     */
322
    @Inline
323
    public final void free(Object object) {
324
        final Address ptr = ObjectReference.fromObject(object).toAddress();
325
        final Word objSize = ptr.loadWord(sizeOffset);
326
        ptr.store(ObjectReference.fromObject(FREE), tibOffset);
327
        setAllocationBit(object, false);
328
        freeSize = freeSize.add(objSize);
329
    }
330
331
    /**
332
     * @return The free size
333
     * @see VmAbstractHeap#getFreeSize()
334
     */
335
    public Extent getFreeSize() {
336
        return freeSize;
337
    }
338
339
    /**
340
     * Join all adjacent free spaces.
341
     * 
342
     * @throws UninterruptiblePragma
343
     */
344
    protected final void defragment() throws UninterruptiblePragma {
345
        final Word size = Word.fromIntZeroExtend(getSize());
346
        final Word headerSize = Word.fromIntZeroExtend(this.headerSize);
347
        Word offset = headerSize;
348
        final Offset sizeOffset = this.sizeOffset;
349
        final Offset tibOffset = this.tibOffset;
350
351
        lock();
352
        try {
353
            Address firstFreePtr = Address.zero();
354
            while (offset.LT(size)) {
355
                final Address ptr = start.add(offset);
356
                final Word objSize = ptr.loadWord(sizeOffset);
357
                final Word nextOffset = offset.add(objSize).add(headerSize);
358
                final Object vmt = ptr.loadObjectReference(tibOffset);
359
                if ((firstFreePtr == null) && (vmt == FREE)) {
360
                    firstFreePtr = ptr;
361
                }
362
                if ((vmt == FREE) && (nextOffset.LT(size))) {
363
                    final Object nextVmt;
364
                    final Address nextObjectPtr = start.add(nextOffset);
365
                    nextVmt = nextObjectPtr.loadObjectReference(tibOffset);
366
                    if (nextVmt == FREE) {
367
                        // Combine two free spaces
368
                        Word nextObjSize = nextObjectPtr.loadWord(sizeOffset);
369
                        Word newObjSize = objSize.add(headerSize).add(nextObjSize);
370
                        ptr.store(newObjSize, sizeOffset);
371
                        // Do not increment offset here, because there may be
372
                        // another next free object, which we will combine
373
                        // in the next loop.
374
                    } else {
375
                        offset = nextOffset;
376
                    }
377
                } else {
378
                    offset = nextOffset;
379
                }
380
            }
381
            // Set the address of the next free block, to the first free block
382
            this.nextFreePtr = firstFreePtr;
383
        } finally {
384
            unlock();
385
        }
386
    }
387
388
    /**
389
     * Let all objects in this heap make a visit to the given visitor.
390
     * 
391
     * @param visitor
392
     * @param locking
393
     *            If true, use lock/unlock while proceeding to the next object.
394
     */
395
    @Override
396
    public final void walk(ObjectVisitor visitor, boolean locking, Word flagsMask, Word flagsValue) {
397
        // Go through the heap and call visit on each object
398
        final Word headerSize = Word.fromIntZeroExtend(this.headerSize);
399
        final Offset sizeOffset = this.sizeOffset;
400
        final Offset tibOffset = this.tibOffset;
401
        final Object FREE = this.FREE;
402
        Word offset = headerSize;
403
        final Word size = Word.fromIntZeroExtend(getSize());
404
405
        if (locking) {
406
            while (offset.LT(size)) {
407
                final Object tib;
408
                final Object object;
409
                final Word objSize;
410
                final Word flags;
411
412
                lock();
413
                try {
414
                    final Address ptr = start.add(offset);
415
                    object = ptr.toObjectReference().toObject();
416
                    tib = ptr.loadObjectReference(tibOffset);
417
                    objSize = ptr.loadWord(sizeOffset);
418
                    flags = (flagsMask.isZero()) ? Word.zero() : VmMagic.getObjectFlags(object)
419
                            .and(flagsMask);
420
                } finally {
421
                    unlock();
422
                }
423
                if (tib != FREE) {
424
                    if (flags.EQ(flagsValue)) {
425
                        if (!visitor.visit(object)) {
426
                            // Stop
427
                            return;
428
                        }
429
                    }
430
                }
431
                offset = offset.add(objSize).add(headerSize);
432
            }
433
        } else {
434
            while (offset.LT(size)) {
435
                final Address ptr = start.add(offset);
436
                final Object object = ptr.toObjectReference().toObject();
437
                final Object tib = ptr.loadObjectReference(tibOffset);
438
                final Word objSize = ptr.loadWord(sizeOffset);
439
                final Word flags = flagsMask.isZero() ? Word.zero() : VmMagic
440
                        .getObjectFlags(object).and(flagsMask);
441
                if (tib != FREE) {
442
                    if (flags.EQ(flagsValue)) {
443
                        if (!visitor.visit(object)) {
444
                            // Stop
445
                            return;
446
                        }
447
                    }
448
                }
449
                offset = offset.add(objSize).add(headerSize);
450
            }
451
        }
452
    }
453
}