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