8d679d440cf5bcc1bff39277b1a9a2e7ae8d6493
[cacao.git] / src / mm / boehm-gc / reclaim.c
1 /* 
2  * Copyright 1988, 1989 Hans-J. Boehm, Alan J. Demers
3  * Copyright (c) 1991-1996 by Xerox Corporation.  All rights reserved.
4  * Copyright (c) 1996-1999 by Silicon Graphics.  All rights reserved.
5  * Copyright (c) 1999-2004 Hewlett-Packard Development Company, L.P.
6  *
7  * THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY EXPRESSED
8  * OR IMPLIED.  ANY USE IS AT YOUR OWN RISK.
9  *
10  * Permission is hereby granted to use or copy this program
11  * for any purpose,  provided the above notices are retained on all copies.
12  * Permission to modify the code and to distribute modified code is granted,
13  * provided the above notices are retained, and a notice that the code was
14  * modified is included with the above copyright notice.
15  */
16
17 #include "config.h"
18
19 #include <stdio.h>
20 #include "private/gc_priv.h"
21
22 signed_word GC_bytes_found = 0;
23                         /* Number of bytes of memory reclaimed     */
24                         /* minus the number of bytes originally    */
25                         /* on free lists which we had to drop.     */
26
27 #if defined(PARALLEL_MARK) || defined(THREAD_LOCAL_ALLOC)
28   word GC_fl_builder_count = 0;
29         /* Number of threads currently building free lists without      */
30         /* holding GC lock.  It is not safe to collect if this is       */
31         /* nonzero.                                                     */
32 #endif /* PARALLEL_MARK */
33
34 /* We defer printing of leaked objects until we're done with the GC     */
35 /* cycle, since the routine for printing objects needs to run outside   */
36 /* the collector, e.g. without the allocation lock.                     */
37 #define MAX_LEAKED 40
38 ptr_t GC_leaked[MAX_LEAKED];
39 unsigned GC_n_leaked = 0;
40
41 GC_bool GC_have_errors = FALSE;
42
43 void GC_add_leaked(ptr_t leaked)
44 {
45     if (GC_n_leaked < MAX_LEAKED) {
46       GC_have_errors = TRUE;
47       GC_leaked[GC_n_leaked++] = leaked;
48       /* Make sure it's not reclaimed this cycle */
49         GC_set_mark_bit(leaked);
50     }
51 }
52
53 static GC_bool printing_errors = FALSE;
54 /* Print all objects on the list after printing any smashed objs.       */
55 /* Clear both lists.                                                    */
56 void GC_print_all_errors ()
57 {
58     unsigned i;
59
60     LOCK();
61     if (printing_errors) {
62         UNLOCK();
63         return;
64     }
65     printing_errors = TRUE;
66     UNLOCK();
67     if (GC_debugging_started) GC_print_all_smashed();
68     for (i = 0; i < GC_n_leaked; ++i) {
69         ptr_t p = GC_leaked[i];
70         if (HDR(p) -> hb_obj_kind == PTRFREE) {
71             GC_err_printf("Leaked atomic object at ");
72         } else {
73             GC_err_printf("Leaked composite object at ");
74         }
75         GC_print_heap_obj(p);
76         GC_err_printf("\n");
77         GC_free(p);
78         GC_leaked[i] = 0;
79     }
80     GC_n_leaked = 0;
81     printing_errors = FALSE;
82 }
83
84
85 /*
86  * reclaim phase
87  *
88  */
89
90
91 /*
92  * Test whether a block is completely empty, i.e. contains no marked
93  * objects.  This does not require the block to be in physical
94  * memory.
95  */
96  
97 GC_bool GC_block_empty(hdr *hhdr)
98 {
99     return (hhdr -> hb_n_marks == 0);
100 }
101
102 GC_bool GC_block_nearly_full(hdr *hhdr)
103 {
104     return (hhdr -> hb_n_marks > 7 * HBLK_OBJS(hhdr -> hb_sz)/8);
105 }
106
107 /* FIXME: This should perhaps again be specialized for USE_MARK_BYTES   */
108 /* and USE_MARK_BITS cases.                                             */
109
110 /*
111  * Restore unmarked small objects in h of size sz to the object
112  * free list.  Returns the new list.
113  * Clears unmarked objects.  Sz is in bytes.
114  */
115 /*ARGSUSED*/
116 ptr_t GC_reclaim_clear(struct hblk *hbp, hdr *hhdr, size_t sz,
117                        ptr_t list, signed_word *count)
118 {
119     word bit_no = 0;
120     word *p, *q, *plim;
121     signed_word n_bytes_found = 0;
122     
123     GC_ASSERT(hhdr == GC_find_header((ptr_t)hbp));
124     GC_ASSERT(sz == hhdr -> hb_sz);
125     GC_ASSERT((sz & (BYTES_PER_WORD-1)) == 0);
126     p = (word *)(hbp->hb_body);
127     plim = (word *)(hbp->hb_body + HBLKSIZE - sz);
128
129     /* go through all words in block */
130         while( p <= plim )  {
131             if( mark_bit_from_hdr(hhdr, bit_no) ) {
132                 p = (word *)((ptr_t)p + sz);
133             } else {
134                 n_bytes_found += sz;
135                 /* object is available - put on list */
136                     obj_link(p) = list;
137                     list = ((ptr_t)p);
138                 /* Clear object, advance p to next object in the process */
139                     q = (word *)((ptr_t)p + sz);
140 #                   ifdef USE_MARK_BYTES
141                       GC_ASSERT(!(sz & 1)
142                                 && !((word)p & (2 * sizeof(word) - 1)));
143                       p[1] = 0;
144                       p += 2;
145                       while (p < q) {
146                         CLEAR_DOUBLE(p);
147                         p += 2;
148                       }
149 #                   else
150                       p++; /* Skip link field */
151                       while (p < q) {
152                         *p++ = 0;
153                       }
154 #                   endif
155             }
156             bit_no += MARK_BIT_OFFSET(sz);
157         }
158     *count += n_bytes_found;
159     return(list);
160 }
161
162 /* The same thing, but don't clear objects: */
163 /*ARGSUSED*/
164 ptr_t GC_reclaim_uninit(struct hblk *hbp, hdr *hhdr, size_t sz,
165                         ptr_t list, signed_word *count)
166 {
167     word bit_no = 0;
168     word *p, *plim;
169     signed_word n_bytes_found = 0;
170     
171     GC_ASSERT(sz == hhdr -> hb_sz);
172     p = (word *)(hbp->hb_body);
173     plim = (word *)((ptr_t)hbp + HBLKSIZE - sz);
174
175     /* go through all words in block */
176         while( p <= plim )  {
177             if( !mark_bit_from_hdr(hhdr, bit_no) ) {
178                 n_bytes_found += sz;
179                 /* object is available - put on list */
180                     obj_link(p) = list;
181                     list = ((ptr_t)p);
182             }
183             p = (word *)((ptr_t)p + sz);
184             bit_no += MARK_BIT_OFFSET(sz);
185         }
186     *count += n_bytes_found;
187     return(list);
188 }
189
190 /* Don't really reclaim objects, just check for unmarked ones: */
191 /*ARGSUSED*/
192 void GC_reclaim_check(struct hblk *hbp, hdr *hhdr, word sz)
193 {
194     word bit_no = 0;
195     ptr_t p, plim;
196     
197     GC_ASSERT(sz == hhdr -> hb_sz);
198     p = hbp->hb_body;
199     plim = p + HBLKSIZE - sz;
200
201     /* go through all words in block */
202         while( p <= plim )  {
203             if( !mark_bit_from_hdr(hhdr, bit_no) ) {
204                 GC_add_leaked(p);
205             }
206             p += sz;
207             bit_no += MARK_BIT_OFFSET(sz);
208         }
209 }
210
211
212 /*
213  * Generic procedure to rebuild a free list in hbp.
214  * Also called directly from GC_malloc_many.
215  * Sz is now in bytes.
216  */
217 ptr_t GC_reclaim_generic(struct hblk * hbp, hdr *hhdr, size_t sz,
218                          GC_bool init, ptr_t list, signed_word *count)
219 {
220     ptr_t result = list;
221
222     GC_ASSERT(GC_find_header((ptr_t)hbp) == hhdr);
223     GC_remove_protection(hbp, 1, (hhdr)->hb_descr == 0 /* Pointer-free? */);
224     if (init) {
225       result = GC_reclaim_clear(hbp, hhdr, sz, list, count);
226     } else {
227       GC_ASSERT((hhdr)->hb_descr == 0 /* Pointer-free block */);
228       result = GC_reclaim_uninit(hbp, hhdr, sz, list, count);
229     } 
230     if (IS_UNCOLLECTABLE(hhdr -> hb_obj_kind)) GC_set_hdr_marks(hhdr);
231     return result;
232 }
233
234 /*
235  * Restore unmarked small objects in the block pointed to by hbp
236  * to the appropriate object free list.
237  * If entirely empty blocks are to be completely deallocated, then
238  * caller should perform that check.
239  */
240 void GC_reclaim_small_nonempty_block(struct hblk *hbp,
241                                      int report_if_found, signed_word *count)
242 {
243     hdr *hhdr = HDR(hbp);
244     size_t sz = hhdr -> hb_sz;
245     int kind = hhdr -> hb_obj_kind;
246     struct obj_kind * ok = &GC_obj_kinds[kind];
247     void **flh = &(ok -> ok_freelist[BYTES_TO_GRANULES(sz)]);
248     
249     hhdr -> hb_last_reclaimed = (unsigned short) GC_gc_no;
250
251     if (report_if_found) {
252         GC_reclaim_check(hbp, hhdr, sz);
253     } else {
254         *flh = GC_reclaim_generic(hbp, hhdr, sz,
255                                   (ok -> ok_init || GC_debugging_started),
256                                   *flh, &GC_bytes_found);
257     }
258 }
259
260 /*
261  * Restore an unmarked large object or an entirely empty blocks of small objects
262  * to the heap block free list.
263  * Otherwise enqueue the block for later processing
264  * by GC_reclaim_small_nonempty_block.
265  * If report_if_found is TRUE, then process any block immediately, and
266  * simply report free objects; do not actually reclaim them.
267  */
268 void GC_reclaim_block(struct hblk *hbp, word report_if_found)
269 {
270     hdr * hhdr = HDR(hbp);
271     size_t sz = hhdr -> hb_sz;  /* size of objects in current block     */
272     struct obj_kind * ok = &GC_obj_kinds[hhdr -> hb_obj_kind];
273     struct hblk ** rlh;
274
275     if( sz > MAXOBJBYTES ) {  /* 1 big object */
276         if( !mark_bit_from_hdr(hhdr, 0) ) {
277             if (report_if_found) {
278               GC_add_leaked((ptr_t)hbp);
279             } else {
280               size_t blocks = OBJ_SZ_TO_BLOCKS(sz);
281               if (blocks > 1) {
282                 GC_large_allocd_bytes -= blocks * HBLKSIZE;
283               }
284               GC_bytes_found += sz;
285               GC_freehblk(hbp);
286             }
287         } else {
288             if (hhdr -> hb_descr != 0) {
289               GC_composite_in_use += sz;
290             } else {
291               GC_atomic_in_use += sz;
292             }
293         }
294     } else {
295         GC_bool empty = GC_block_empty(hhdr);
296 #       ifdef PARALLEL_MARK
297           /* Count can be low or one too high because we sometimes      */
298           /* have to ignore decrements.  Objects can also potentially   */
299           /* be repeatedly marked by each marker.                       */
300           /* Here we assume two markers, but this is extremely          */
301           /* unlikely to fail spuriously with more.  And if it does, it */
302           /* should be looked at.                                       */
303           GC_ASSERT(hhdr -> hb_n_marks <= 2 * (HBLKSIZE/sz + 1) + 16);
304 #       else
305           GC_ASSERT(sz * hhdr -> hb_n_marks <= HBLKSIZE);
306 #       endif
307         if (hhdr -> hb_descr != 0) {
308           GC_composite_in_use += sz * hhdr -> hb_n_marks;
309         } else {
310           GC_atomic_in_use += sz * hhdr -> hb_n_marks;
311         }
312         if (report_if_found) {
313           GC_reclaim_small_nonempty_block(hbp, (int)report_if_found,
314                                           &GC_bytes_found);
315         } else if (empty) {
316           GC_bytes_found += HBLKSIZE;
317           GC_freehblk(hbp);
318         } else if (TRUE != GC_block_nearly_full(hhdr)){
319           /* group of smaller objects, enqueue the real work */
320           rlh = &(ok -> ok_reclaim_list[BYTES_TO_GRANULES(sz)]);
321           hhdr -> hb_next = *rlh;
322           *rlh = hbp;
323         } /* else not worth salvaging. */
324         /* We used to do the nearly_full check later, but we    */
325         /* already have the right cache context here.  Also     */
326         /* doing it here avoids some silly lock contention in   */
327         /* GC_malloc_many.                                      */
328     }
329 }
330
331 #if !defined(NO_DEBUGGING)
332 /* Routines to gather and print heap block info         */
333 /* intended for debugging.  Otherwise should be called  */
334 /* with lock.                                           */
335
336 struct Print_stats
337 {
338         size_t number_of_blocks;
339         size_t total_bytes;
340 };
341
342 #ifdef USE_MARK_BYTES
343
344 /* Return the number of set mark bits in the given header       */
345 int GC_n_set_marks(hdr *hhdr)
346 {
347     int result = 0;
348     int i;
349     size_t sz = hhdr -> hb_sz;
350     int offset = MARK_BIT_OFFSET(sz);
351     int limit = FINAL_MARK_BIT(sz);
352
353     for (i = 0; i < limit; i += offset) {
354         result += hhdr -> hb_marks[i];
355     }
356     GC_ASSERT(hhdr -> hb_marks[limit]);
357     return(result);
358 }
359
360 #else
361
362 /* Number of set bits in a word.  Not performance critical.     */
363 static int set_bits(word n)
364 {
365     word m = n;
366     int result = 0;
367     
368     while (m > 0) {
369         if (m & 1) result++;
370         m >>= 1;
371     }
372     return(result);
373 }
374
375 /* Return the number of set mark bits in the given header       */
376 int GC_n_set_marks(hdr *hhdr)
377 {
378     int result = 0;
379     int i;
380     int n_mark_words;
381 #   ifdef MARK_BIT_PER_OBJ
382       int n_objs = HBLK_OBJS(hhdr -> hb_sz);
383     
384       if (0 == n_objs) n_objs = 1;
385       n_mark_words = divWORDSZ(n_objs + WORDSZ - 1);
386 #   else /* MARK_BIT_PER_GRANULE */
387       n_mark_words = MARK_BITS_SZ;
388 #   endif
389     for (i = 0; i < n_mark_words - 1; i++) {
390         result += set_bits(hhdr -> hb_marks[i]);
391     }
392 #   ifdef MARK_BIT_PER_OBJ
393       result += set_bits((hhdr -> hb_marks[n_mark_words - 1])
394                          << (n_mark_words * WORDSZ - n_objs));
395 #   else
396       result += set_bits(hhdr -> hb_marks[n_mark_words - 1]);
397 #   endif
398     return(result - 1);
399 }
400
401 #endif /* !USE_MARK_BYTES  */
402
403 /*ARGSUSED*/
404 void GC_print_block_descr(struct hblk *h, word /* struct PrintStats */ raw_ps)
405 {
406     hdr * hhdr = HDR(h);
407     size_t bytes = hhdr -> hb_sz;
408     struct Print_stats *ps;
409     unsigned n_marks = GC_n_set_marks(hhdr);
410     
411     if (hhdr -> hb_n_marks != n_marks) {
412       GC_printf("(%u:%u,%u!=%u)", hhdr -> hb_obj_kind,
413                                   bytes,
414                                   hhdr -> hb_n_marks, n_marks);
415     } else {
416       GC_printf("(%u:%u,%u)", hhdr -> hb_obj_kind,
417                               bytes, n_marks);
418     }
419     bytes += HBLKSIZE-1;
420     bytes &= ~(HBLKSIZE-1);
421
422     ps = (struct Print_stats *)raw_ps;
423     ps->total_bytes += bytes;
424     ps->number_of_blocks++;
425 }
426
427 void GC_print_block_list()
428 {
429     struct Print_stats pstats;
430
431     GC_printf("(kind(0=ptrfree,1=normal,2=unc.):size_in_bytes, #_marks_set)\n");
432     pstats.number_of_blocks = 0;
433     pstats.total_bytes = 0;
434     GC_apply_to_all_blocks(GC_print_block_descr, (word)&pstats);
435     GC_printf("\nblocks = %lu, bytes = %lu\n",
436               (unsigned long)pstats.number_of_blocks,
437               (unsigned long)pstats.total_bytes);
438 }
439
440 /* Currently for debugger use only: */
441 void GC_print_free_list(int kind, size_t sz_in_granules)
442 {
443     struct obj_kind * ok = &GC_obj_kinds[kind];
444     ptr_t flh = ok -> ok_freelist[sz_in_granules];
445     struct hblk *lastBlock = 0;
446     int n = 0;
447
448     while (flh){
449         struct hblk *block = HBLKPTR(flh);
450         if (block != lastBlock){
451             GC_printf("\nIn heap block at 0x%x:\n\t", block);
452             lastBlock = block;
453         }
454         GC_printf("%d: 0x%x;", ++n, flh);
455         flh = obj_link(flh);
456     }
457 }
458
459 #endif /* NO_DEBUGGING */
460
461 /*
462  * Clear all obj_link pointers in the list of free objects *flp.
463  * Clear *flp.
464  * This must be done before dropping a list of free gcj-style objects,
465  * since may otherwise end up with dangling "descriptor" pointers.
466  * It may help for other pointer-containing objects.
467  */
468 void GC_clear_fl_links(void **flp)
469 {
470     void *next = *flp;
471
472     while (0 != next) {
473        *flp = 0;
474        flp = &(obj_link(next));
475        next = *flp;
476     }
477 }
478
479 /*
480  * Perform GC_reclaim_block on the entire heap, after first clearing
481  * small object free lists (if we are not just looking for leaks).
482  */
483 void GC_start_reclaim(GC_bool report_if_found)
484 {
485     unsigned kind;
486     
487 #   if defined(PARALLEL_MARK) || defined(THREAD_LOCAL_ALLOC)
488       GC_ASSERT(0 == GC_fl_builder_count);
489 #   endif
490     /* Reset in use counters.  GC_reclaim_block recomputes them. */
491       GC_composite_in_use = 0;
492       GC_atomic_in_use = 0;
493     /* Clear reclaim- and free-lists */
494       for (kind = 0; kind < GC_n_kinds; kind++) {
495         void **fop;
496         void **lim;
497         struct hblk ** rlp;
498         struct hblk ** rlim;
499         struct hblk ** rlist = GC_obj_kinds[kind].ok_reclaim_list;
500         GC_bool should_clobber = (GC_obj_kinds[kind].ok_descriptor != 0);
501         
502         if (rlist == 0) continue;       /* This kind not used.  */
503         if (!report_if_found) {
504             lim = &(GC_obj_kinds[kind].ok_freelist[MAXOBJGRANULES+1]);
505             for( fop = GC_obj_kinds[kind].ok_freelist; fop < lim; fop++ ) {
506               if (*fop != 0) {
507                 if (should_clobber) {
508                   GC_clear_fl_links(fop);
509                 } else {
510                   *fop = 0;
511                 }
512               }
513             }
514         } /* otherwise free list objects are marked,    */
515           /* and its safe to leave them                 */
516         rlim = rlist + MAXOBJGRANULES+1;
517         for( rlp = rlist; rlp < rlim; rlp++ ) {
518             *rlp = 0;
519         }
520       }
521     
522
523   /* Go through all heap blocks (in hblklist) and reclaim unmarked objects */
524   /* or enqueue the block for later processing.                            */
525     GC_apply_to_all_blocks(GC_reclaim_block, (word)report_if_found);
526
527 # ifdef EAGER_SWEEP
528     /* This is a very stupid thing to do.  We make it possible anyway,  */
529     /* so that you can convince yourself that it really is very stupid. */
530     GC_reclaim_all((GC_stop_func)0, FALSE);
531 # endif
532 # if defined(PARALLEL_MARK) || defined(THREAD_LOCAL_ALLOC)
533     GC_ASSERT(0 == GC_fl_builder_count);
534 # endif
535     
536 }
537
538 /*
539  * Sweep blocks of the indicated object size and kind until either the
540  * appropriate free list is nonempty, or there are no more blocks to
541  * sweep.
542  */
543 void GC_continue_reclaim(size_t sz /* granules */, int kind)
544 {
545     hdr * hhdr;
546     struct hblk * hbp;
547     struct obj_kind * ok = &(GC_obj_kinds[kind]);
548     struct hblk ** rlh = ok -> ok_reclaim_list;
549     void **flh = &(ok -> ok_freelist[sz]);
550     
551     if (rlh == 0) return;       /* No blocks of this kind.      */
552     rlh += sz;
553     while ((hbp = *rlh) != 0) {
554         hhdr = HDR(hbp);
555         *rlh = hhdr -> hb_next;
556         GC_reclaim_small_nonempty_block(hbp, FALSE, &GC_bytes_found);
557         if (*flh != 0) break;
558     }
559 }
560
561 /*
562  * Reclaim all small blocks waiting to be reclaimed.
563  * Abort and return FALSE when/if (*stop_func)() returns TRUE.
564  * If this returns TRUE, then it's safe to restart the world
565  * with incorrectly cleared mark bits.
566  * If ignore_old is TRUE, then reclaim only blocks that have been 
567  * recently reclaimed, and discard the rest.
568  * Stop_func may be 0.
569  */
570 GC_bool GC_reclaim_all(GC_stop_func stop_func, GC_bool ignore_old)
571 {
572     word sz;
573     unsigned kind;
574     hdr * hhdr;
575     struct hblk * hbp;
576     struct obj_kind * ok;
577     struct hblk ** rlp;
578     struct hblk ** rlh;
579     CLOCK_TYPE start_time;
580     CLOCK_TYPE done_time;
581         
582     if (GC_print_stats == VERBOSE)
583         GET_TIME(start_time);
584     
585     for (kind = 0; kind < GC_n_kinds; kind++) {
586         ok = &(GC_obj_kinds[kind]);
587         rlp = ok -> ok_reclaim_list;
588         if (rlp == 0) continue;
589         for (sz = 1; sz <= MAXOBJGRANULES; sz++) {
590             rlh = rlp + sz;
591             while ((hbp = *rlh) != 0) {
592                 if (stop_func != (GC_stop_func)0 && (*stop_func)()) {
593                     return(FALSE);
594                 }
595                 hhdr = HDR(hbp);
596                 *rlh = hhdr -> hb_next;
597                 if (!ignore_old || hhdr -> hb_last_reclaimed == GC_gc_no - 1) {
598                     /* It's likely we'll need it this time, too */
599                     /* It's been touched recently, so this      */
600                     /* shouldn't trigger paging.                */
601                     GC_reclaim_small_nonempty_block(hbp, FALSE, &GC_bytes_found);
602                 }
603             }
604         }
605     }
606     if (GC_print_stats == VERBOSE) {
607         GET_TIME(done_time);
608         GC_log_printf("Disposing of reclaim lists took %lu msecs\n",
609                   MS_TIME_DIFF(done_time,start_time));
610     }
611     return(TRUE);
612 }