xref: /freebsd/contrib/lua/src/lgc.c (revision c66ec88fed842fbaad62c30d510644ceb7bd2d71)
1 /*
2 ** $Id: lgc.c $
3 ** Garbage Collector
4 ** See Copyright Notice in lua.h
5 */
6 
7 #define lgc_c
8 #define LUA_CORE
9 
10 #include "lprefix.h"
11 
12 #include <stdio.h>
13 #include <string.h>
14 
15 
16 #include "lua.h"
17 
18 #include "ldebug.h"
19 #include "ldo.h"
20 #include "lfunc.h"
21 #include "lgc.h"
22 #include "lmem.h"
23 #include "lobject.h"
24 #include "lstate.h"
25 #include "lstring.h"
26 #include "ltable.h"
27 #include "ltm.h"
28 
29 
30 /*
31 ** Maximum number of elements to sweep in each single step.
32 ** (Large enough to dissipate fixed overheads but small enough
33 ** to allow small steps for the collector.)
34 */
35 #define GCSWEEPMAX	100
36 
37 /*
38 ** Maximum number of finalizers to call in each single step.
39 */
40 #define GCFINMAX	10
41 
42 
43 /*
44 ** Cost of calling one finalizer.
45 */
46 #define GCFINALIZECOST	50
47 
48 
49 /*
50 ** The equivalent, in bytes, of one unit of "work" (visiting a slot,
51 ** sweeping an object, etc.)
52 */
53 #define WORK2MEM	sizeof(TValue)
54 
55 
56 /*
57 ** macro to adjust 'pause': 'pause' is actually used like
58 ** 'pause / PAUSEADJ' (value chosen by tests)
59 */
60 #define PAUSEADJ		100
61 
62 
63 /* mask with all color bits */
64 #define maskcolors	(bitmask(BLACKBIT) | WHITEBITS)
65 
66 /* mask with all GC bits */
67 #define maskgcbits      (maskcolors | AGEBITS)
68 
69 
70 /* macro to erase all color bits then set only the current white bit */
71 #define makewhite(g,x)	\
72   (x->marked = cast_byte((x->marked & ~maskcolors) | luaC_white(g)))
73 
74 /* make an object gray (neither white nor black) */
75 #define set2gray(x)	resetbits(x->marked, maskcolors)
76 
77 
78 /* make an object black (coming from any color) */
79 #define set2black(x)  \
80   (x->marked = cast_byte((x->marked & ~WHITEBITS) | bitmask(BLACKBIT)))
81 
82 
83 #define valiswhite(x)   (iscollectable(x) && iswhite(gcvalue(x)))
84 
85 #define keyiswhite(n)   (keyiscollectable(n) && iswhite(gckey(n)))
86 
87 
88 /*
89 ** Protected access to objects in values
90 */
91 #define gcvalueN(o)     (iscollectable(o) ? gcvalue(o) : NULL)
92 
93 
94 #define markvalue(g,o) { checkliveness(g->mainthread,o); \
95   if (valiswhite(o)) reallymarkobject(g,gcvalue(o)); }
96 
97 #define markkey(g, n)	{ if keyiswhite(n) reallymarkobject(g,gckey(n)); }
98 
99 #define markobject(g,t)	{ if (iswhite(t)) reallymarkobject(g, obj2gco(t)); }
100 
101 /*
102 ** mark an object that can be NULL (either because it is really optional,
103 ** or it was stripped as debug info, or inside an uncompleted structure)
104 */
105 #define markobjectN(g,t)	{ if (t) markobject(g,t); }
106 
107 static void reallymarkobject (global_State *g, GCObject *o);
108 static lu_mem atomic (lua_State *L);
109 static void entersweep (lua_State *L);
110 
111 
112 /*
113 ** {======================================================
114 ** Generic functions
115 ** =======================================================
116 */
117 
118 
119 /*
120 ** one after last element in a hash array
121 */
122 #define gnodelast(h)	gnode(h, cast_sizet(sizenode(h)))
123 
124 
125 static GCObject **getgclist (GCObject *o) {
126   switch (o->tt) {
127     case LUA_VTABLE: return &gco2t(o)->gclist;
128     case LUA_VLCL: return &gco2lcl(o)->gclist;
129     case LUA_VCCL: return &gco2ccl(o)->gclist;
130     case LUA_VTHREAD: return &gco2th(o)->gclist;
131     case LUA_VPROTO: return &gco2p(o)->gclist;
132     case LUA_VUSERDATA: {
133       Udata *u = gco2u(o);
134       lua_assert(u->nuvalue > 0);
135       return &u->gclist;
136     }
137     default: lua_assert(0); return 0;
138   }
139 }
140 
141 
142 /*
143 ** Link a collectable object 'o' with a known type into the list 'p'.
144 ** (Must be a macro to access the 'gclist' field in different types.)
145 */
146 #define linkgclist(o,p)	linkgclist_(obj2gco(o), &(o)->gclist, &(p))
147 
148 static void linkgclist_ (GCObject *o, GCObject **pnext, GCObject **list) {
149   lua_assert(!isgray(o));  /* cannot be in a gray list */
150   *pnext = *list;
151   *list = o;
152   set2gray(o);  /* now it is */
153 }
154 
155 
156 /*
157 ** Link a generic collectable object 'o' into the list 'p'.
158 */
159 #define linkobjgclist(o,p) linkgclist_(obj2gco(o), getgclist(o), &(p))
160 
161 
162 
163 /*
164 ** Clear keys for empty entries in tables. If entry is empty, mark its
165 ** entry as dead. This allows the collection of the key, but keeps its
166 ** entry in the table: its removal could break a chain and could break
167 ** a table traversal.  Other places never manipulate dead keys, because
168 ** its associated empty value is enough to signal that the entry is
169 ** logically empty.
170 */
171 static void clearkey (Node *n) {
172   lua_assert(isempty(gval(n)));
173   if (keyiscollectable(n))
174     setdeadkey(n);  /* unused key; remove it */
175 }
176 
177 
178 /*
179 ** tells whether a key or value can be cleared from a weak
180 ** table. Non-collectable objects are never removed from weak
181 ** tables. Strings behave as 'values', so are never removed too. for
182 ** other objects: if really collected, cannot keep them; for objects
183 ** being finalized, keep them in keys, but not in values
184 */
185 static int iscleared (global_State *g, const GCObject *o) {
186   if (o == NULL) return 0;  /* non-collectable value */
187   else if (novariant(o->tt) == LUA_TSTRING) {
188     markobject(g, o);  /* strings are 'values', so are never weak */
189     return 0;
190   }
191   else return iswhite(o);
192 }
193 
194 
195 /*
196 ** Barrier that moves collector forward, that is, marks the white object
197 ** 'v' being pointed by the black object 'o'.  In the generational
198 ** mode, 'v' must also become old, if 'o' is old; however, it cannot
199 ** be changed directly to OLD, because it may still point to non-old
200 ** objects. So, it is marked as OLD0. In the next cycle it will become
201 ** OLD1, and in the next it will finally become OLD (regular old). By
202 ** then, any object it points to will also be old.  If called in the
203 ** incremental sweep phase, it clears the black object to white (sweep
204 ** it) to avoid other barrier calls for this same object. (That cannot
205 ** be done is generational mode, as its sweep does not distinguish
206 ** whites from deads.)
207 */
208 void luaC_barrier_ (lua_State *L, GCObject *o, GCObject *v) {
209   global_State *g = G(L);
210   lua_assert(isblack(o) && iswhite(v) && !isdead(g, v) && !isdead(g, o));
211   if (keepinvariant(g)) {  /* must keep invariant? */
212     reallymarkobject(g, v);  /* restore invariant */
213     if (isold(o)) {
214       lua_assert(!isold(v));  /* white object could not be old */
215       setage(v, G_OLD0);  /* restore generational invariant */
216     }
217   }
218   else {  /* sweep phase */
219     lua_assert(issweepphase(g));
220     if (g->gckind == KGC_INC)  /* incremental mode? */
221       makewhite(g, o);  /* mark 'o' as white to avoid other barriers */
222   }
223 }
224 
225 
226 /*
227 ** barrier that moves collector backward, that is, mark the black object
228 ** pointing to a white object as gray again.
229 */
230 void luaC_barrierback_ (lua_State *L, GCObject *o) {
231   global_State *g = G(L);
232   lua_assert(isblack(o) && !isdead(g, o));
233   lua_assert((g->gckind == KGC_GEN) == (isold(o) && getage(o) != G_TOUCHED1));
234   if (getage(o) == G_TOUCHED2)  /* already in gray list? */
235     set2gray(o);  /* make it gray to become touched1 */
236   else  /* link it in 'grayagain' and paint it gray */
237     linkobjgclist(o, g->grayagain);
238   if (isold(o))  /* generational mode? */
239     setage(o, G_TOUCHED1);  /* touched in current cycle */
240 }
241 
242 
243 void luaC_fix (lua_State *L, GCObject *o) {
244   global_State *g = G(L);
245   lua_assert(g->allgc == o);  /* object must be 1st in 'allgc' list! */
246   set2gray(o);  /* they will be gray forever */
247   setage(o, G_OLD);  /* and old forever */
248   g->allgc = o->next;  /* remove object from 'allgc' list */
249   o->next = g->fixedgc;  /* link it to 'fixedgc' list */
250   g->fixedgc = o;
251 }
252 
253 
254 /*
255 ** create a new collectable object (with given type and size) and link
256 ** it to 'allgc' list.
257 */
258 GCObject *luaC_newobj (lua_State *L, int tt, size_t sz) {
259   global_State *g = G(L);
260   GCObject *o = cast(GCObject *, luaM_newobject(L, novariant(tt), sz));
261   o->marked = luaC_white(g);
262   o->tt = tt;
263   o->next = g->allgc;
264   g->allgc = o;
265   return o;
266 }
267 
268 /* }====================================================== */
269 
270 
271 
272 /*
273 ** {======================================================
274 ** Mark functions
275 ** =======================================================
276 */
277 
278 
279 /*
280 ** Mark an object.  Userdata with no user values, strings, and closed
281 ** upvalues are visited and turned black here.  Open upvalues are
282 ** already indirectly linked through their respective threads in the
283 ** 'twups' list, so they don't go to the gray list; nevertheless, they
284 ** are kept gray to avoid barriers, as their values will be revisited
285 ** by the thread or by 'remarkupvals'.  Other objects are added to the
286 ** gray list to be visited (and turned black) later.  Both userdata and
287 ** upvalues can call this function recursively, but this recursion goes
288 ** for at most two levels: An upvalue cannot refer to another upvalue
289 ** (only closures can), and a userdata's metatable must be a table.
290 */
291 static void reallymarkobject (global_State *g, GCObject *o) {
292   switch (o->tt) {
293     case LUA_VSHRSTR:
294     case LUA_VLNGSTR: {
295       set2black(o);  /* nothing to visit */
296       break;
297     }
298     case LUA_VUPVAL: {
299       UpVal *uv = gco2upv(o);
300       if (upisopen(uv))
301         set2gray(uv);  /* open upvalues are kept gray */
302       else
303         set2black(uv);  /* closed upvalues are visited here */
304       markvalue(g, uv->v);  /* mark its content */
305       break;
306     }
307     case LUA_VUSERDATA: {
308       Udata *u = gco2u(o);
309       if (u->nuvalue == 0) {  /* no user values? */
310         markobjectN(g, u->metatable);  /* mark its metatable */
311         set2black(u);  /* nothing else to mark */
312         break;
313       }
314       /* else... */
315     }  /* FALLTHROUGH */
316     case LUA_VLCL: case LUA_VCCL: case LUA_VTABLE:
317     case LUA_VTHREAD: case LUA_VPROTO: {
318       linkobjgclist(o, g->gray);  /* to be visited later */
319       break;
320     }
321     default: lua_assert(0); break;
322   }
323 }
324 
325 
326 /*
327 ** mark metamethods for basic types
328 */
329 static void markmt (global_State *g) {
330   int i;
331   for (i=0; i < LUA_NUMTAGS; i++)
332     markobjectN(g, g->mt[i]);
333 }
334 
335 
336 /*
337 ** mark all objects in list of being-finalized
338 */
339 static lu_mem markbeingfnz (global_State *g) {
340   GCObject *o;
341   lu_mem count = 0;
342   for (o = g->tobefnz; o != NULL; o = o->next) {
343     count++;
344     markobject(g, o);
345   }
346   return count;
347 }
348 
349 
350 /*
351 ** For each non-marked thread, simulates a barrier between each open
352 ** upvalue and its value. (If the thread is collected, the value will be
353 ** assigned to the upvalue, but then it can be too late for the barrier
354 ** to act. The "barrier" does not need to check colors: A non-marked
355 ** thread must be young; upvalues cannot be older than their threads; so
356 ** any visited upvalue must be young too.) Also removes the thread from
357 ** the list, as it was already visited. Removes also threads with no
358 ** upvalues, as they have nothing to be checked. (If the thread gets an
359 ** upvalue later, it will be linked in the list again.)
360 */
361 static int remarkupvals (global_State *g) {
362   lua_State *thread;
363   lua_State **p = &g->twups;
364   int work = 0;  /* estimate of how much work was done here */
365   while ((thread = *p) != NULL) {
366     work++;
367     if (!iswhite(thread) && thread->openupval != NULL)
368       p = &thread->twups;  /* keep marked thread with upvalues in the list */
369     else {  /* thread is not marked or without upvalues */
370       UpVal *uv;
371       lua_assert(!isold(thread) || thread->openupval == NULL);
372       *p = thread->twups;  /* remove thread from the list */
373       thread->twups = thread;  /* mark that it is out of list */
374       for (uv = thread->openupval; uv != NULL; uv = uv->u.open.next) {
375         lua_assert(getage(uv) <= getage(thread));
376         work++;
377         if (!iswhite(uv)) {  /* upvalue already visited? */
378           lua_assert(upisopen(uv) && isgray(uv));
379           markvalue(g, uv->v);  /* mark its value */
380         }
381       }
382     }
383   }
384   return work;
385 }
386 
387 
388 static void cleargraylists (global_State *g) {
389   g->gray = g->grayagain = NULL;
390   g->weak = g->allweak = g->ephemeron = NULL;
391 }
392 
393 
394 /*
395 ** mark root set and reset all gray lists, to start a new collection
396 */
397 static void restartcollection (global_State *g) {
398   cleargraylists(g);
399   markobject(g, g->mainthread);
400   markvalue(g, &g->l_registry);
401   markmt(g);
402   markbeingfnz(g);  /* mark any finalizing object left from previous cycle */
403 }
404 
405 /* }====================================================== */
406 
407 
408 /*
409 ** {======================================================
410 ** Traverse functions
411 ** =======================================================
412 */
413 
414 
415 /*
416 ** Check whether object 'o' should be kept in the 'grayagain' list for
417 ** post-processing by 'correctgraylist'. (It could put all old objects
418 ** in the list and leave all the work to 'correctgraylist', but it is
419 ** more efficient to avoid adding elements that will be removed.) Only
420 ** TOUCHED1 objects need to be in the list. TOUCHED2 doesn't need to go
421 ** back to a gray list, but then it must become OLD. (That is what
422 ** 'correctgraylist' does when it finds a TOUCHED2 object.)
423 */
424 static void genlink (global_State *g, GCObject *o) {
425   lua_assert(isblack(o));
426   if (getage(o) == G_TOUCHED1) {  /* touched in this cycle? */
427     linkobjgclist(o, g->grayagain);  /* link it back in 'grayagain' */
428   }  /* everything else do not need to be linked back */
429   else if (getage(o) == G_TOUCHED2)
430     changeage(o, G_TOUCHED2, G_OLD);  /* advance age */
431 }
432 
433 
434 /*
435 ** Traverse a table with weak values and link it to proper list. During
436 ** propagate phase, keep it in 'grayagain' list, to be revisited in the
437 ** atomic phase. In the atomic phase, if table has any white value,
438 ** put it in 'weak' list, to be cleared.
439 */
440 static void traverseweakvalue (global_State *g, Table *h) {
441   Node *n, *limit = gnodelast(h);
442   /* if there is array part, assume it may have white values (it is not
443      worth traversing it now just to check) */
444   int hasclears = (h->alimit > 0);
445   for (n = gnode(h, 0); n < limit; n++) {  /* traverse hash part */
446     if (isempty(gval(n)))  /* entry is empty? */
447       clearkey(n);  /* clear its key */
448     else {
449       lua_assert(!keyisnil(n));
450       markkey(g, n);
451       if (!hasclears && iscleared(g, gcvalueN(gval(n))))  /* a white value? */
452         hasclears = 1;  /* table will have to be cleared */
453     }
454   }
455   if (g->gcstate == GCSatomic && hasclears)
456     linkgclist(h, g->weak);  /* has to be cleared later */
457   else
458     linkgclist(h, g->grayagain);  /* must retraverse it in atomic phase */
459 }
460 
461 
462 /*
463 ** Traverse an ephemeron table and link it to proper list. Returns true
464 ** iff any object was marked during this traversal (which implies that
465 ** convergence has to continue). During propagation phase, keep table
466 ** in 'grayagain' list, to be visited again in the atomic phase. In
467 ** the atomic phase, if table has any white->white entry, it has to
468 ** be revisited during ephemeron convergence (as that key may turn
469 ** black). Otherwise, if it has any white key, table has to be cleared
470 ** (in the atomic phase). In generational mode, some tables
471 ** must be kept in some gray list for post-processing; this is done
472 ** by 'genlink'.
473 */
474 static int traverseephemeron (global_State *g, Table *h, int inv) {
475   int marked = 0;  /* true if an object is marked in this traversal */
476   int hasclears = 0;  /* true if table has white keys */
477   int hasww = 0;  /* true if table has entry "white-key -> white-value" */
478   unsigned int i;
479   unsigned int asize = luaH_realasize(h);
480   unsigned int nsize = sizenode(h);
481   /* traverse array part */
482   for (i = 0; i < asize; i++) {
483     if (valiswhite(&h->array[i])) {
484       marked = 1;
485       reallymarkobject(g, gcvalue(&h->array[i]));
486     }
487   }
488   /* traverse hash part; if 'inv', traverse descending
489      (see 'convergeephemerons') */
490   for (i = 0; i < nsize; i++) {
491     Node *n = inv ? gnode(h, nsize - 1 - i) : gnode(h, i);
492     if (isempty(gval(n)))  /* entry is empty? */
493       clearkey(n);  /* clear its key */
494     else if (iscleared(g, gckeyN(n))) {  /* key is not marked (yet)? */
495       hasclears = 1;  /* table must be cleared */
496       if (valiswhite(gval(n)))  /* value not marked yet? */
497         hasww = 1;  /* white-white entry */
498     }
499     else if (valiswhite(gval(n))) {  /* value not marked yet? */
500       marked = 1;
501       reallymarkobject(g, gcvalue(gval(n)));  /* mark it now */
502     }
503   }
504   /* link table into proper list */
505   if (g->gcstate == GCSpropagate)
506     linkgclist(h, g->grayagain);  /* must retraverse it in atomic phase */
507   else if (hasww)  /* table has white->white entries? */
508     linkgclist(h, g->ephemeron);  /* have to propagate again */
509   else if (hasclears)  /* table has white keys? */
510     linkgclist(h, g->allweak);  /* may have to clean white keys */
511   else
512     genlink(g, obj2gco(h));  /* check whether collector still needs to see it */
513   return marked;
514 }
515 
516 
517 static void traversestrongtable (global_State *g, Table *h) {
518   Node *n, *limit = gnodelast(h);
519   unsigned int i;
520   unsigned int asize = luaH_realasize(h);
521   for (i = 0; i < asize; i++)  /* traverse array part */
522     markvalue(g, &h->array[i]);
523   for (n = gnode(h, 0); n < limit; n++) {  /* traverse hash part */
524     if (isempty(gval(n)))  /* entry is empty? */
525       clearkey(n);  /* clear its key */
526     else {
527       lua_assert(!keyisnil(n));
528       markkey(g, n);
529       markvalue(g, gval(n));
530     }
531   }
532   genlink(g, obj2gco(h));
533 }
534 
535 
536 static lu_mem traversetable (global_State *g, Table *h) {
537   const char *weakkey, *weakvalue;
538   const TValue *mode = gfasttm(g, h->metatable, TM_MODE);
539   markobjectN(g, h->metatable);
540   if (mode && ttisstring(mode) &&  /* is there a weak mode? */
541       (cast_void(weakkey = strchr(svalue(mode), 'k')),
542        cast_void(weakvalue = strchr(svalue(mode), 'v')),
543        (weakkey || weakvalue))) {  /* is really weak? */
544     if (!weakkey)  /* strong keys? */
545       traverseweakvalue(g, h);
546     else if (!weakvalue)  /* strong values? */
547       traverseephemeron(g, h, 0);
548     else  /* all weak */
549       linkgclist(h, g->allweak);  /* nothing to traverse now */
550   }
551   else  /* not weak */
552     traversestrongtable(g, h);
553   return 1 + h->alimit + 2 * allocsizenode(h);
554 }
555 
556 
557 static int traverseudata (global_State *g, Udata *u) {
558   int i;
559   markobjectN(g, u->metatable);  /* mark its metatable */
560   for (i = 0; i < u->nuvalue; i++)
561     markvalue(g, &u->uv[i].uv);
562   genlink(g, obj2gco(u));
563   return 1 + u->nuvalue;
564 }
565 
566 
567 /*
568 ** Traverse a prototype. (While a prototype is being build, its
569 ** arrays can be larger than needed; the extra slots are filled with
570 ** NULL, so the use of 'markobjectN')
571 */
572 static int traverseproto (global_State *g, Proto *f) {
573   int i;
574   markobjectN(g, f->source);
575   for (i = 0; i < f->sizek; i++)  /* mark literals */
576     markvalue(g, &f->k[i]);
577   for (i = 0; i < f->sizeupvalues; i++)  /* mark upvalue names */
578     markobjectN(g, f->upvalues[i].name);
579   for (i = 0; i < f->sizep; i++)  /* mark nested protos */
580     markobjectN(g, f->p[i]);
581   for (i = 0; i < f->sizelocvars; i++)  /* mark local-variable names */
582     markobjectN(g, f->locvars[i].varname);
583   return 1 + f->sizek + f->sizeupvalues + f->sizep + f->sizelocvars;
584 }
585 
586 
587 static int traverseCclosure (global_State *g, CClosure *cl) {
588   int i;
589   for (i = 0; i < cl->nupvalues; i++)  /* mark its upvalues */
590     markvalue(g, &cl->upvalue[i]);
591   return 1 + cl->nupvalues;
592 }
593 
594 /*
595 ** Traverse a Lua closure, marking its prototype and its upvalues.
596 ** (Both can be NULL while closure is being created.)
597 */
598 static int traverseLclosure (global_State *g, LClosure *cl) {
599   int i;
600   markobjectN(g, cl->p);  /* mark its prototype */
601   for (i = 0; i < cl->nupvalues; i++) {  /* visit its upvalues */
602     UpVal *uv = cl->upvals[i];
603     markobjectN(g, uv);  /* mark upvalue */
604   }
605   return 1 + cl->nupvalues;
606 }
607 
608 
609 /*
610 ** Traverse a thread, marking the elements in the stack up to its top
611 ** and cleaning the rest of the stack in the final traversal. That
612 ** ensures that the entire stack have valid (non-dead) objects.
613 ** Threads have no barriers. In gen. mode, old threads must be visited
614 ** at every cycle, because they might point to young objects.  In inc.
615 ** mode, the thread can still be modified before the end of the cycle,
616 ** and therefore it must be visited again in the atomic phase. To ensure
617 ** these visits, threads must return to a gray list if they are not new
618 ** (which can only happen in generational mode) or if the traverse is in
619 ** the propagate phase (which can only happen in incremental mode).
620 */
621 static int traversethread (global_State *g, lua_State *th) {
622   UpVal *uv;
623   StkId o = th->stack;
624   if (isold(th) || g->gcstate == GCSpropagate)
625     linkgclist(th, g->grayagain);  /* insert into 'grayagain' list */
626   if (o == NULL)
627     return 1;  /* stack not completely built yet */
628   lua_assert(g->gcstate == GCSatomic ||
629              th->openupval == NULL || isintwups(th));
630   for (; o < th->top; o++)  /* mark live elements in the stack */
631     markvalue(g, s2v(o));
632   for (uv = th->openupval; uv != NULL; uv = uv->u.open.next)
633     markobject(g, uv);  /* open upvalues cannot be collected */
634   if (g->gcstate == GCSatomic) {  /* final traversal? */
635     for (; o < th->stack_last + EXTRA_STACK; o++)
636       setnilvalue(s2v(o));  /* clear dead stack slice */
637     /* 'remarkupvals' may have removed thread from 'twups' list */
638     if (!isintwups(th) && th->openupval != NULL) {
639       th->twups = g->twups;  /* link it back to the list */
640       g->twups = th;
641     }
642   }
643   else if (!g->gcemergency)
644     luaD_shrinkstack(th); /* do not change stack in emergency cycle */
645   return 1 + stacksize(th);
646 }
647 
648 
649 /*
650 ** traverse one gray object, turning it to black.
651 */
652 static lu_mem propagatemark (global_State *g) {
653   GCObject *o = g->gray;
654   nw2black(o);
655   g->gray = *getgclist(o);  /* remove from 'gray' list */
656   switch (o->tt) {
657     case LUA_VTABLE: return traversetable(g, gco2t(o));
658     case LUA_VUSERDATA: return traverseudata(g, gco2u(o));
659     case LUA_VLCL: return traverseLclosure(g, gco2lcl(o));
660     case LUA_VCCL: return traverseCclosure(g, gco2ccl(o));
661     case LUA_VPROTO: return traverseproto(g, gco2p(o));
662     case LUA_VTHREAD: return traversethread(g, gco2th(o));
663     default: lua_assert(0); return 0;
664   }
665 }
666 
667 
668 static lu_mem propagateall (global_State *g) {
669   lu_mem tot = 0;
670   while (g->gray)
671     tot += propagatemark(g);
672   return tot;
673 }
674 
675 
676 /*
677 ** Traverse all ephemeron tables propagating marks from keys to values.
678 ** Repeat until it converges, that is, nothing new is marked. 'dir'
679 ** inverts the direction of the traversals, trying to speed up
680 ** convergence on chains in the same table.
681 **
682 */
683 static void convergeephemerons (global_State *g) {
684   int changed;
685   int dir = 0;
686   do {
687     GCObject *w;
688     GCObject *next = g->ephemeron;  /* get ephemeron list */
689     g->ephemeron = NULL;  /* tables may return to this list when traversed */
690     changed = 0;
691     while ((w = next) != NULL) {  /* for each ephemeron table */
692       Table *h = gco2t(w);
693       next = h->gclist;  /* list is rebuilt during loop */
694       nw2black(h);  /* out of the list (for now) */
695       if (traverseephemeron(g, h, dir)) {  /* marked some value? */
696         propagateall(g);  /* propagate changes */
697         changed = 1;  /* will have to revisit all ephemeron tables */
698       }
699     }
700     dir = !dir;  /* invert direction next time */
701   } while (changed);  /* repeat until no more changes */
702 }
703 
704 /* }====================================================== */
705 
706 
707 /*
708 ** {======================================================
709 ** Sweep Functions
710 ** =======================================================
711 */
712 
713 
714 /*
715 ** clear entries with unmarked keys from all weaktables in list 'l'
716 */
717 static void clearbykeys (global_State *g, GCObject *l) {
718   for (; l; l = gco2t(l)->gclist) {
719     Table *h = gco2t(l);
720     Node *limit = gnodelast(h);
721     Node *n;
722     for (n = gnode(h, 0); n < limit; n++) {
723       if (iscleared(g, gckeyN(n)))  /* unmarked key? */
724         setempty(gval(n));  /* remove entry */
725       if (isempty(gval(n)))  /* is entry empty? */
726         clearkey(n);  /* clear its key */
727     }
728   }
729 }
730 
731 
732 /*
733 ** clear entries with unmarked values from all weaktables in list 'l' up
734 ** to element 'f'
735 */
736 static void clearbyvalues (global_State *g, GCObject *l, GCObject *f) {
737   for (; l != f; l = gco2t(l)->gclist) {
738     Table *h = gco2t(l);
739     Node *n, *limit = gnodelast(h);
740     unsigned int i;
741     unsigned int asize = luaH_realasize(h);
742     for (i = 0; i < asize; i++) {
743       TValue *o = &h->array[i];
744       if (iscleared(g, gcvalueN(o)))  /* value was collected? */
745         setempty(o);  /* remove entry */
746     }
747     for (n = gnode(h, 0); n < limit; n++) {
748       if (iscleared(g, gcvalueN(gval(n))))  /* unmarked value? */
749         setempty(gval(n));  /* remove entry */
750       if (isempty(gval(n)))  /* is entry empty? */
751         clearkey(n);  /* clear its key */
752     }
753   }
754 }
755 
756 
757 static void freeupval (lua_State *L, UpVal *uv) {
758   if (upisopen(uv))
759     luaF_unlinkupval(uv);
760   luaM_free(L, uv);
761 }
762 
763 
764 static void freeobj (lua_State *L, GCObject *o) {
765   switch (o->tt) {
766     case LUA_VPROTO:
767       luaF_freeproto(L, gco2p(o));
768       break;
769     case LUA_VUPVAL:
770       freeupval(L, gco2upv(o));
771       break;
772     case LUA_VLCL: {
773       LClosure *cl = gco2lcl(o);
774       luaM_freemem(L, cl, sizeLclosure(cl->nupvalues));
775       break;
776     }
777     case LUA_VCCL: {
778       CClosure *cl = gco2ccl(o);
779       luaM_freemem(L, cl, sizeCclosure(cl->nupvalues));
780       break;
781     }
782     case LUA_VTABLE:
783       luaH_free(L, gco2t(o));
784       break;
785     case LUA_VTHREAD:
786       luaE_freethread(L, gco2th(o));
787       break;
788     case LUA_VUSERDATA: {
789       Udata *u = gco2u(o);
790       luaM_freemem(L, o, sizeudata(u->nuvalue, u->len));
791       break;
792     }
793     case LUA_VSHRSTR: {
794       TString *ts = gco2ts(o);
795       luaS_remove(L, ts);  /* remove it from hash table */
796       luaM_freemem(L, ts, sizelstring(ts->shrlen));
797       break;
798     }
799     case LUA_VLNGSTR: {
800       TString *ts = gco2ts(o);
801       luaM_freemem(L, ts, sizelstring(ts->u.lnglen));
802       break;
803     }
804     default: lua_assert(0);
805   }
806 }
807 
808 
809 /*
810 ** sweep at most 'countin' elements from a list of GCObjects erasing dead
811 ** objects, where a dead object is one marked with the old (non current)
812 ** white; change all non-dead objects back to white, preparing for next
813 ** collection cycle. Return where to continue the traversal or NULL if
814 ** list is finished. ('*countout' gets the number of elements traversed.)
815 */
816 static GCObject **sweeplist (lua_State *L, GCObject **p, int countin,
817                              int *countout) {
818   global_State *g = G(L);
819   int ow = otherwhite(g);
820   int i;
821   int white = luaC_white(g);  /* current white */
822   for (i = 0; *p != NULL && i < countin; i++) {
823     GCObject *curr = *p;
824     int marked = curr->marked;
825     if (isdeadm(ow, marked)) {  /* is 'curr' dead? */
826       *p = curr->next;  /* remove 'curr' from list */
827       freeobj(L, curr);  /* erase 'curr' */
828     }
829     else {  /* change mark to 'white' */
830       curr->marked = cast_byte((marked & ~maskgcbits) | white);
831       p = &curr->next;  /* go to next element */
832     }
833   }
834   if (countout)
835     *countout = i;  /* number of elements traversed */
836   return (*p == NULL) ? NULL : p;
837 }
838 
839 
840 /*
841 ** sweep a list until a live object (or end of list)
842 */
843 static GCObject **sweeptolive (lua_State *L, GCObject **p) {
844   GCObject **old = p;
845   do {
846     p = sweeplist(L, p, 1, NULL);
847   } while (p == old);
848   return p;
849 }
850 
851 /* }====================================================== */
852 
853 
854 /*
855 ** {======================================================
856 ** Finalization
857 ** =======================================================
858 */
859 
860 /*
861 ** If possible, shrink string table.
862 */
863 static void checkSizes (lua_State *L, global_State *g) {
864   if (!g->gcemergency) {
865     if (g->strt.nuse < g->strt.size / 4) {  /* string table too big? */
866       l_mem olddebt = g->GCdebt;
867       luaS_resize(L, g->strt.size / 2);
868       g->GCestimate += g->GCdebt - olddebt;  /* correct estimate */
869     }
870   }
871 }
872 
873 
874 /*
875 ** Get the next udata to be finalized from the 'tobefnz' list, and
876 ** link it back into the 'allgc' list.
877 */
878 static GCObject *udata2finalize (global_State *g) {
879   GCObject *o = g->tobefnz;  /* get first element */
880   lua_assert(tofinalize(o));
881   g->tobefnz = o->next;  /* remove it from 'tobefnz' list */
882   o->next = g->allgc;  /* return it to 'allgc' list */
883   g->allgc = o;
884   resetbit(o->marked, FINALIZEDBIT);  /* object is "normal" again */
885   if (issweepphase(g))
886     makewhite(g, o);  /* "sweep" object */
887   else if (getage(o) == G_OLD1)
888     g->firstold1 = o;  /* it is the first OLD1 object in the list */
889   return o;
890 }
891 
892 
893 static void dothecall (lua_State *L, void *ud) {
894   UNUSED(ud);
895   luaD_callnoyield(L, L->top - 2, 0);
896 }
897 
898 
899 static void GCTM (lua_State *L) {
900   global_State *g = G(L);
901   const TValue *tm;
902   TValue v;
903   lua_assert(!g->gcemergency);
904   setgcovalue(L, &v, udata2finalize(g));
905   tm = luaT_gettmbyobj(L, &v, TM_GC);
906   if (!notm(tm)) {  /* is there a finalizer? */
907     int status;
908     lu_byte oldah = L->allowhook;
909     int running  = g->gcrunning;
910     L->allowhook = 0;  /* stop debug hooks during GC metamethod */
911     g->gcrunning = 0;  /* avoid GC steps */
912     setobj2s(L, L->top++, tm);  /* push finalizer... */
913     setobj2s(L, L->top++, &v);  /* ... and its argument */
914     L->ci->callstatus |= CIST_FIN;  /* will run a finalizer */
915     status = luaD_pcall(L, dothecall, NULL, savestack(L, L->top - 2), 0);
916     L->ci->callstatus &= ~CIST_FIN;  /* not running a finalizer anymore */
917     L->allowhook = oldah;  /* restore hooks */
918     g->gcrunning = running;  /* restore state */
919     if (unlikely(status != LUA_OK)) {  /* error while running __gc? */
920       luaE_warnerror(L, "__gc metamethod");
921       L->top--;  /* pops error object */
922     }
923   }
924 }
925 
926 
927 /*
928 ** Call a few finalizers
929 */
930 static int runafewfinalizers (lua_State *L, int n) {
931   global_State *g = G(L);
932   int i;
933   for (i = 0; i < n && g->tobefnz; i++)
934     GCTM(L);  /* call one finalizer */
935   return i;
936 }
937 
938 
939 /*
940 ** call all pending finalizers
941 */
942 static void callallpendingfinalizers (lua_State *L) {
943   global_State *g = G(L);
944   while (g->tobefnz)
945     GCTM(L);
946 }
947 
948 
949 /*
950 ** find last 'next' field in list 'p' list (to add elements in its end)
951 */
952 static GCObject **findlast (GCObject **p) {
953   while (*p != NULL)
954     p = &(*p)->next;
955   return p;
956 }
957 
958 
959 /*
960 ** Move all unreachable objects (or 'all' objects) that need
961 ** finalization from list 'finobj' to list 'tobefnz' (to be finalized).
962 ** (Note that objects after 'finobjold1' cannot be white, so they
963 ** don't need to be traversed. In incremental mode, 'finobjold1' is NULL,
964 ** so the whole list is traversed.)
965 */
966 static void separatetobefnz (global_State *g, int all) {
967   GCObject *curr;
968   GCObject **p = &g->finobj;
969   GCObject **lastnext = findlast(&g->tobefnz);
970   while ((curr = *p) != g->finobjold1) {  /* traverse all finalizable objects */
971     lua_assert(tofinalize(curr));
972     if (!(iswhite(curr) || all))  /* not being collected? */
973       p = &curr->next;  /* don't bother with it */
974     else {
975       if (curr == g->finobjsur)  /* removing 'finobjsur'? */
976         g->finobjsur = curr->next;  /* correct it */
977       *p = curr->next;  /* remove 'curr' from 'finobj' list */
978       curr->next = *lastnext;  /* link at the end of 'tobefnz' list */
979       *lastnext = curr;
980       lastnext = &curr->next;
981     }
982   }
983 }
984 
985 
986 /*
987 ** If pointer 'p' points to 'o', move it to the next element.
988 */
989 static void checkpointer (GCObject **p, GCObject *o) {
990   if (o == *p)
991     *p = o->next;
992 }
993 
994 
995 /*
996 ** Correct pointers to objects inside 'allgc' list when
997 ** object 'o' is being removed from the list.
998 */
999 static void correctpointers (global_State *g, GCObject *o) {
1000   checkpointer(&g->survival, o);
1001   checkpointer(&g->old1, o);
1002   checkpointer(&g->reallyold, o);
1003   checkpointer(&g->firstold1, o);
1004 }
1005 
1006 
1007 /*
1008 ** if object 'o' has a finalizer, remove it from 'allgc' list (must
1009 ** search the list to find it) and link it in 'finobj' list.
1010 */
1011 void luaC_checkfinalizer (lua_State *L, GCObject *o, Table *mt) {
1012   global_State *g = G(L);
1013   if (tofinalize(o) ||                 /* obj. is already marked... */
1014       gfasttm(g, mt, TM_GC) == NULL)   /* or has no finalizer? */
1015     return;  /* nothing to be done */
1016   else {  /* move 'o' to 'finobj' list */
1017     GCObject **p;
1018     if (issweepphase(g)) {
1019       makewhite(g, o);  /* "sweep" object 'o' */
1020       if (g->sweepgc == &o->next)  /* should not remove 'sweepgc' object */
1021         g->sweepgc = sweeptolive(L, g->sweepgc);  /* change 'sweepgc' */
1022     }
1023     else
1024       correctpointers(g, o);
1025     /* search for pointer pointing to 'o' */
1026     for (p = &g->allgc; *p != o; p = &(*p)->next) { /* empty */ }
1027     *p = o->next;  /* remove 'o' from 'allgc' list */
1028     o->next = g->finobj;  /* link it in 'finobj' list */
1029     g->finobj = o;
1030     l_setbit(o->marked, FINALIZEDBIT);  /* mark it as such */
1031   }
1032 }
1033 
1034 /* }====================================================== */
1035 
1036 
1037 /*
1038 ** {======================================================
1039 ** Generational Collector
1040 ** =======================================================
1041 */
1042 
1043 static void setpause (global_State *g);
1044 
1045 
1046 /*
1047 ** Sweep a list of objects to enter generational mode.  Deletes dead
1048 ** objects and turns the non dead to old. All non-dead threads---which
1049 ** are now old---must be in a gray list. Everything else is not in a
1050 ** gray list. Open upvalues are also kept gray.
1051 */
1052 static void sweep2old (lua_State *L, GCObject **p) {
1053   GCObject *curr;
1054   global_State *g = G(L);
1055   while ((curr = *p) != NULL) {
1056     if (iswhite(curr)) {  /* is 'curr' dead? */
1057       lua_assert(isdead(g, curr));
1058       *p = curr->next;  /* remove 'curr' from list */
1059       freeobj(L, curr);  /* erase 'curr' */
1060     }
1061     else {  /* all surviving objects become old */
1062       setage(curr, G_OLD);
1063       if (curr->tt == LUA_VTHREAD) {  /* threads must be watched */
1064         lua_State *th = gco2th(curr);
1065         linkgclist(th, g->grayagain);  /* insert into 'grayagain' list */
1066       }
1067       else if (curr->tt == LUA_VUPVAL && upisopen(gco2upv(curr)))
1068         set2gray(curr);  /* open upvalues are always gray */
1069       else  /* everything else is black */
1070         nw2black(curr);
1071       p = &curr->next;  /* go to next element */
1072     }
1073   }
1074 }
1075 
1076 
1077 /*
1078 ** Sweep for generational mode. Delete dead objects. (Because the
1079 ** collection is not incremental, there are no "new white" objects
1080 ** during the sweep. So, any white object must be dead.) For
1081 ** non-dead objects, advance their ages and clear the color of
1082 ** new objects. (Old objects keep their colors.)
1083 ** The ages of G_TOUCHED1 and G_TOUCHED2 objects cannot be advanced
1084 ** here, because these old-generation objects are usually not swept
1085 ** here.  They will all be advanced in 'correctgraylist'. That function
1086 ** will also remove objects turned white here from any gray list.
1087 */
1088 static GCObject **sweepgen (lua_State *L, global_State *g, GCObject **p,
1089                             GCObject *limit, GCObject **pfirstold1) {
1090   static const lu_byte nextage[] = {
1091     G_SURVIVAL,  /* from G_NEW */
1092     G_OLD1,      /* from G_SURVIVAL */
1093     G_OLD1,      /* from G_OLD0 */
1094     G_OLD,       /* from G_OLD1 */
1095     G_OLD,       /* from G_OLD (do not change) */
1096     G_TOUCHED1,  /* from G_TOUCHED1 (do not change) */
1097     G_TOUCHED2   /* from G_TOUCHED2 (do not change) */
1098   };
1099   int white = luaC_white(g);
1100   GCObject *curr;
1101   while ((curr = *p) != limit) {
1102     if (iswhite(curr)) {  /* is 'curr' dead? */
1103       lua_assert(!isold(curr) && isdead(g, curr));
1104       *p = curr->next;  /* remove 'curr' from list */
1105       freeobj(L, curr);  /* erase 'curr' */
1106     }
1107     else {  /* correct mark and age */
1108       if (getage(curr) == G_NEW) {  /* new objects go back to white */
1109         int marked = curr->marked & ~maskgcbits;  /* erase GC bits */
1110         curr->marked = cast_byte(marked | G_SURVIVAL | white);
1111       }
1112       else {  /* all other objects will be old, and so keep their color */
1113         setage(curr, nextage[getage(curr)]);
1114         if (getage(curr) == G_OLD1 && *pfirstold1 == NULL)
1115           *pfirstold1 = curr;  /* first OLD1 object in the list */
1116       }
1117       p = &curr->next;  /* go to next element */
1118     }
1119   }
1120   return p;
1121 }
1122 
1123 
1124 /*
1125 ** Traverse a list making all its elements white and clearing their
1126 ** age. In incremental mode, all objects are 'new' all the time,
1127 ** except for fixed strings (which are always old).
1128 */
1129 static void whitelist (global_State *g, GCObject *p) {
1130   int white = luaC_white(g);
1131   for (; p != NULL; p = p->next)
1132     p->marked = cast_byte((p->marked & ~maskgcbits) | white);
1133 }
1134 
1135 
1136 /*
1137 ** Correct a list of gray objects. Return pointer to where rest of the
1138 ** list should be linked.
1139 ** Because this correction is done after sweeping, young objects might
1140 ** be turned white and still be in the list. They are only removed.
1141 ** 'TOUCHED1' objects are advanced to 'TOUCHED2' and remain on the list;
1142 ** Non-white threads also remain on the list; 'TOUCHED2' objects become
1143 ** regular old; they and anything else are removed from the list.
1144 */
1145 static GCObject **correctgraylist (GCObject **p) {
1146   GCObject *curr;
1147   while ((curr = *p) != NULL) {
1148     GCObject **next = getgclist(curr);
1149     if (iswhite(curr))
1150       goto remove;  /* remove all white objects */
1151     else if (getage(curr) == G_TOUCHED1) {  /* touched in this cycle? */
1152       lua_assert(isgray(curr));
1153       nw2black(curr);  /* make it black, for next barrier */
1154       changeage(curr, G_TOUCHED1, G_TOUCHED2);
1155       goto remain;  /* keep it in the list and go to next element */
1156     }
1157     else if (curr->tt == LUA_VTHREAD) {
1158       lua_assert(isgray(curr));
1159       goto remain;  /* keep non-white threads on the list */
1160     }
1161     else {  /* everything else is removed */
1162       lua_assert(isold(curr));  /* young objects should be white here */
1163       if (getage(curr) == G_TOUCHED2)  /* advance from TOUCHED2... */
1164         changeage(curr, G_TOUCHED2, G_OLD);  /* ... to OLD */
1165       nw2black(curr);  /* make object black (to be removed) */
1166       goto remove;
1167     }
1168     remove: *p = *next; continue;
1169     remain: p = next; continue;
1170   }
1171   return p;
1172 }
1173 
1174 
1175 /*
1176 ** Correct all gray lists, coalescing them into 'grayagain'.
1177 */
1178 static void correctgraylists (global_State *g) {
1179   GCObject **list = correctgraylist(&g->grayagain);
1180   *list = g->weak; g->weak = NULL;
1181   list = correctgraylist(list);
1182   *list = g->allweak; g->allweak = NULL;
1183   list = correctgraylist(list);
1184   *list = g->ephemeron; g->ephemeron = NULL;
1185   correctgraylist(list);
1186 }
1187 
1188 
1189 /*
1190 ** Mark black 'OLD1' objects when starting a new young collection.
1191 ** Gray objects are already in some gray list, and so will be visited
1192 ** in the atomic step.
1193 */
1194 static void markold (global_State *g, GCObject *from, GCObject *to) {
1195   GCObject *p;
1196   for (p = from; p != to; p = p->next) {
1197     if (getage(p) == G_OLD1) {
1198       lua_assert(!iswhite(p));
1199       changeage(p, G_OLD1, G_OLD);  /* now they are old */
1200       if (isblack(p))
1201         reallymarkobject(g, p);
1202     }
1203   }
1204 }
1205 
1206 
1207 /*
1208 ** Finish a young-generation collection.
1209 */
1210 static void finishgencycle (lua_State *L, global_State *g) {
1211   correctgraylists(g);
1212   checkSizes(L, g);
1213   g->gcstate = GCSpropagate;  /* skip restart */
1214   if (!g->gcemergency)
1215     callallpendingfinalizers(L);
1216 }
1217 
1218 
1219 /*
1220 ** Does a young collection. First, mark 'OLD1' objects. Then does the
1221 ** atomic step. Then, sweep all lists and advance pointers. Finally,
1222 ** finish the collection.
1223 */
1224 static void youngcollection (lua_State *L, global_State *g) {
1225   GCObject **psurvival;  /* to point to first non-dead survival object */
1226   GCObject *dummy;  /* dummy out parameter to 'sweepgen' */
1227   lua_assert(g->gcstate == GCSpropagate);
1228   if (g->firstold1) {  /* are there regular OLD1 objects? */
1229     markold(g, g->firstold1, g->reallyold);  /* mark them */
1230     g->firstold1 = NULL;  /* no more OLD1 objects (for now) */
1231   }
1232   markold(g, g->finobj, g->finobjrold);
1233   markold(g, g->tobefnz, NULL);
1234   atomic(L);
1235 
1236   /* sweep nursery and get a pointer to its last live element */
1237   g->gcstate = GCSswpallgc;
1238   psurvival = sweepgen(L, g, &g->allgc, g->survival, &g->firstold1);
1239   /* sweep 'survival' */
1240   sweepgen(L, g, psurvival, g->old1, &g->firstold1);
1241   g->reallyold = g->old1;
1242   g->old1 = *psurvival;  /* 'survival' survivals are old now */
1243   g->survival = g->allgc;  /* all news are survivals */
1244 
1245   /* repeat for 'finobj' lists */
1246   dummy = NULL;  /* no 'firstold1' optimization for 'finobj' lists */
1247   psurvival = sweepgen(L, g, &g->finobj, g->finobjsur, &dummy);
1248   /* sweep 'survival' */
1249   sweepgen(L, g, psurvival, g->finobjold1, &dummy);
1250   g->finobjrold = g->finobjold1;
1251   g->finobjold1 = *psurvival;  /* 'survival' survivals are old now */
1252   g->finobjsur = g->finobj;  /* all news are survivals */
1253 
1254   sweepgen(L, g, &g->tobefnz, NULL, &dummy);
1255   finishgencycle(L, g);
1256 }
1257 
1258 
1259 /*
1260 ** Clears all gray lists, sweeps objects, and prepare sublists to enter
1261 ** generational mode. The sweeps remove dead objects and turn all
1262 ** surviving objects to old. Threads go back to 'grayagain'; everything
1263 ** else is turned black (not in any gray list).
1264 */
1265 static void atomic2gen (lua_State *L, global_State *g) {
1266   cleargraylists(g);
1267   /* sweep all elements making them old */
1268   g->gcstate = GCSswpallgc;
1269   sweep2old(L, &g->allgc);
1270   /* everything alive now is old */
1271   g->reallyold = g->old1 = g->survival = g->allgc;
1272   g->firstold1 = NULL;  /* there are no OLD1 objects anywhere */
1273 
1274   /* repeat for 'finobj' lists */
1275   sweep2old(L, &g->finobj);
1276   g->finobjrold = g->finobjold1 = g->finobjsur = g->finobj;
1277 
1278   sweep2old(L, &g->tobefnz);
1279 
1280   g->gckind = KGC_GEN;
1281   g->lastatomic = 0;
1282   g->GCestimate = gettotalbytes(g);  /* base for memory control */
1283   finishgencycle(L, g);
1284 }
1285 
1286 
1287 /*
1288 ** Enter generational mode. Must go until the end of an atomic cycle
1289 ** to ensure that all objects are correctly marked and weak tables
1290 ** are cleared. Then, turn all objects into old and finishes the
1291 ** collection.
1292 */
1293 static lu_mem entergen (lua_State *L, global_State *g) {
1294   lu_mem numobjs;
1295   luaC_runtilstate(L, bitmask(GCSpause));  /* prepare to start a new cycle */
1296   luaC_runtilstate(L, bitmask(GCSpropagate));  /* start new cycle */
1297   numobjs = atomic(L);  /* propagates all and then do the atomic stuff */
1298   atomic2gen(L, g);
1299   return numobjs;
1300 }
1301 
1302 
1303 /*
1304 ** Enter incremental mode. Turn all objects white, make all
1305 ** intermediate lists point to NULL (to avoid invalid pointers),
1306 ** and go to the pause state.
1307 */
1308 static void enterinc (global_State *g) {
1309   whitelist(g, g->allgc);
1310   g->reallyold = g->old1 = g->survival = NULL;
1311   whitelist(g, g->finobj);
1312   whitelist(g, g->tobefnz);
1313   g->finobjrold = g->finobjold1 = g->finobjsur = NULL;
1314   g->gcstate = GCSpause;
1315   g->gckind = KGC_INC;
1316   g->lastatomic = 0;
1317 }
1318 
1319 
1320 /*
1321 ** Change collector mode to 'newmode'.
1322 */
1323 void luaC_changemode (lua_State *L, int newmode) {
1324   global_State *g = G(L);
1325   if (newmode != g->gckind) {
1326     if (newmode == KGC_GEN)  /* entering generational mode? */
1327       entergen(L, g);
1328     else
1329       enterinc(g);  /* entering incremental mode */
1330   }
1331   g->lastatomic = 0;
1332 }
1333 
1334 
1335 /*
1336 ** Does a full collection in generational mode.
1337 */
1338 static lu_mem fullgen (lua_State *L, global_State *g) {
1339   enterinc(g);
1340   return entergen(L, g);
1341 }
1342 
1343 
1344 /*
1345 ** Set debt for the next minor collection, which will happen when
1346 ** memory grows 'genminormul'%.
1347 */
1348 static void setminordebt (global_State *g) {
1349   luaE_setdebt(g, -(cast(l_mem, (gettotalbytes(g) / 100)) * g->genminormul));
1350 }
1351 
1352 
1353 /*
1354 ** Does a major collection after last collection was a "bad collection".
1355 **
1356 ** When the program is building a big structure, it allocates lots of
1357 ** memory but generates very little garbage. In those scenarios,
1358 ** the generational mode just wastes time doing small collections, and
1359 ** major collections are frequently what we call a "bad collection", a
1360 ** collection that frees too few objects. To avoid the cost of switching
1361 ** between generational mode and the incremental mode needed for full
1362 ** (major) collections, the collector tries to stay in incremental mode
1363 ** after a bad collection, and to switch back to generational mode only
1364 ** after a "good" collection (one that traverses less than 9/8 objects
1365 ** of the previous one).
1366 ** The collector must choose whether to stay in incremental mode or to
1367 ** switch back to generational mode before sweeping. At this point, it
1368 ** does not know the real memory in use, so it cannot use memory to
1369 ** decide whether to return to generational mode. Instead, it uses the
1370 ** number of objects traversed (returned by 'atomic') as a proxy. The
1371 ** field 'g->lastatomic' keeps this count from the last collection.
1372 ** ('g->lastatomic != 0' also means that the last collection was bad.)
1373 */
1374 static void stepgenfull (lua_State *L, global_State *g) {
1375   lu_mem newatomic;  /* count of traversed objects */
1376   lu_mem lastatomic = g->lastatomic;  /* count from last collection */
1377   if (g->gckind == KGC_GEN)  /* still in generational mode? */
1378     enterinc(g);  /* enter incremental mode */
1379   luaC_runtilstate(L, bitmask(GCSpropagate));  /* start new cycle */
1380   newatomic = atomic(L);  /* mark everybody */
1381   if (newatomic < lastatomic + (lastatomic >> 3)) {  /* good collection? */
1382     atomic2gen(L, g);  /* return to generational mode */
1383     setminordebt(g);
1384   }
1385   else {  /* another bad collection; stay in incremental mode */
1386     g->GCestimate = gettotalbytes(g);  /* first estimate */;
1387     entersweep(L);
1388     luaC_runtilstate(L, bitmask(GCSpause));  /* finish collection */
1389     setpause(g);
1390     g->lastatomic = newatomic;
1391   }
1392 }
1393 
1394 
1395 /*
1396 ** Does a generational "step".
1397 ** Usually, this means doing a minor collection and setting the debt to
1398 ** make another collection when memory grows 'genminormul'% larger.
1399 **
1400 ** However, there are exceptions.  If memory grows 'genmajormul'%
1401 ** larger than it was at the end of the last major collection (kept
1402 ** in 'g->GCestimate'), the function does a major collection. At the
1403 ** end, it checks whether the major collection was able to free a
1404 ** decent amount of memory (at least half the growth in memory since
1405 ** previous major collection). If so, the collector keeps its state,
1406 ** and the next collection will probably be minor again. Otherwise,
1407 ** we have what we call a "bad collection". In that case, set the field
1408 ** 'g->lastatomic' to signal that fact, so that the next collection will
1409 ** go to 'stepgenfull'.
1410 **
1411 ** 'GCdebt <= 0' means an explicit call to GC step with "size" zero;
1412 ** in that case, do a minor collection.
1413 */
1414 static void genstep (lua_State *L, global_State *g) {
1415   if (g->lastatomic != 0)  /* last collection was a bad one? */
1416     stepgenfull(L, g);  /* do a full step */
1417   else {
1418     lu_mem majorbase = g->GCestimate;  /* memory after last major collection */
1419     lu_mem majorinc = (majorbase / 100) * getgcparam(g->genmajormul);
1420     if (g->GCdebt > 0 && gettotalbytes(g) > majorbase + majorinc) {
1421       lu_mem numobjs = fullgen(L, g);  /* do a major collection */
1422       if (gettotalbytes(g) < majorbase + (majorinc / 2)) {
1423         /* collected at least half of memory growth since last major
1424            collection; keep doing minor collections */
1425         setminordebt(g);
1426       }
1427       else {  /* bad collection */
1428         g->lastatomic = numobjs;  /* signal that last collection was bad */
1429         setpause(g);  /* do a long wait for next (major) collection */
1430       }
1431     }
1432     else {  /* regular case; do a minor collection */
1433       youngcollection(L, g);
1434       setminordebt(g);
1435       g->GCestimate = majorbase;  /* preserve base value */
1436     }
1437   }
1438   lua_assert(isdecGCmodegen(g));
1439 }
1440 
1441 /* }====================================================== */
1442 
1443 
1444 /*
1445 ** {======================================================
1446 ** GC control
1447 ** =======================================================
1448 */
1449 
1450 
1451 /*
1452 ** Set the "time" to wait before starting a new GC cycle; cycle will
1453 ** start when memory use hits the threshold of ('estimate' * pause /
1454 ** PAUSEADJ). (Division by 'estimate' should be OK: it cannot be zero,
1455 ** because Lua cannot even start with less than PAUSEADJ bytes).
1456 */
1457 static void setpause (global_State *g) {
1458   l_mem threshold, debt;
1459   int pause = getgcparam(g->gcpause);
1460   l_mem estimate = g->GCestimate / PAUSEADJ;  /* adjust 'estimate' */
1461   lua_assert(estimate > 0);
1462   threshold = (pause < MAX_LMEM / estimate)  /* overflow? */
1463             ? estimate * pause  /* no overflow */
1464             : MAX_LMEM;  /* overflow; truncate to maximum */
1465   debt = gettotalbytes(g) - threshold;
1466   if (debt > 0) debt = 0;
1467   luaE_setdebt(g, debt);
1468 }
1469 
1470 
1471 /*
1472 ** Enter first sweep phase.
1473 ** The call to 'sweeptolive' makes the pointer point to an object
1474 ** inside the list (instead of to the header), so that the real sweep do
1475 ** not need to skip objects created between "now" and the start of the
1476 ** real sweep.
1477 */
1478 static void entersweep (lua_State *L) {
1479   global_State *g = G(L);
1480   g->gcstate = GCSswpallgc;
1481   lua_assert(g->sweepgc == NULL);
1482   g->sweepgc = sweeptolive(L, &g->allgc);
1483 }
1484 
1485 
1486 /*
1487 ** Delete all objects in list 'p' until (but not including) object
1488 ** 'limit'.
1489 */
1490 static void deletelist (lua_State *L, GCObject *p, GCObject *limit) {
1491   while (p != limit) {
1492     GCObject *next = p->next;
1493     freeobj(L, p);
1494     p = next;
1495   }
1496 }
1497 
1498 
1499 /*
1500 ** Call all finalizers of the objects in the given Lua state, and
1501 ** then free all objects, except for the main thread.
1502 */
1503 void luaC_freeallobjects (lua_State *L) {
1504   global_State *g = G(L);
1505   luaC_changemode(L, KGC_INC);
1506   separatetobefnz(g, 1);  /* separate all objects with finalizers */
1507   lua_assert(g->finobj == NULL);
1508   callallpendingfinalizers(L);
1509   deletelist(L, g->allgc, obj2gco(g->mainthread));
1510   deletelist(L, g->finobj, NULL);
1511   deletelist(L, g->fixedgc, NULL);  /* collect fixed objects */
1512   lua_assert(g->strt.nuse == 0);
1513 }
1514 
1515 
1516 static lu_mem atomic (lua_State *L) {
1517   global_State *g = G(L);
1518   lu_mem work = 0;
1519   GCObject *origweak, *origall;
1520   GCObject *grayagain = g->grayagain;  /* save original list */
1521   g->grayagain = NULL;
1522   lua_assert(g->ephemeron == NULL && g->weak == NULL);
1523   lua_assert(!iswhite(g->mainthread));
1524   g->gcstate = GCSatomic;
1525   markobject(g, L);  /* mark running thread */
1526   /* registry and global metatables may be changed by API */
1527   markvalue(g, &g->l_registry);
1528   markmt(g);  /* mark global metatables */
1529   work += propagateall(g);  /* empties 'gray' list */
1530   /* remark occasional upvalues of (maybe) dead threads */
1531   work += remarkupvals(g);
1532   work += propagateall(g);  /* propagate changes */
1533   g->gray = grayagain;
1534   work += propagateall(g);  /* traverse 'grayagain' list */
1535   convergeephemerons(g);
1536   /* at this point, all strongly accessible objects are marked. */
1537   /* Clear values from weak tables, before checking finalizers */
1538   clearbyvalues(g, g->weak, NULL);
1539   clearbyvalues(g, g->allweak, NULL);
1540   origweak = g->weak; origall = g->allweak;
1541   separatetobefnz(g, 0);  /* separate objects to be finalized */
1542   work += markbeingfnz(g);  /* mark objects that will be finalized */
1543   work += propagateall(g);  /* remark, to propagate 'resurrection' */
1544   convergeephemerons(g);
1545   /* at this point, all resurrected objects are marked. */
1546   /* remove dead objects from weak tables */
1547   clearbykeys(g, g->ephemeron);  /* clear keys from all ephemeron tables */
1548   clearbykeys(g, g->allweak);  /* clear keys from all 'allweak' tables */
1549   /* clear values from resurrected weak tables */
1550   clearbyvalues(g, g->weak, origweak);
1551   clearbyvalues(g, g->allweak, origall);
1552   luaS_clearcache(g);
1553   g->currentwhite = cast_byte(otherwhite(g));  /* flip current white */
1554   lua_assert(g->gray == NULL);
1555   return work;  /* estimate of slots marked by 'atomic' */
1556 }
1557 
1558 
1559 static int sweepstep (lua_State *L, global_State *g,
1560                       int nextstate, GCObject **nextlist) {
1561   if (g->sweepgc) {
1562     l_mem olddebt = g->GCdebt;
1563     int count;
1564     g->sweepgc = sweeplist(L, g->sweepgc, GCSWEEPMAX, &count);
1565     g->GCestimate += g->GCdebt - olddebt;  /* update estimate */
1566     return count;
1567   }
1568   else {  /* enter next state */
1569     g->gcstate = nextstate;
1570     g->sweepgc = nextlist;
1571     return 0;  /* no work done */
1572   }
1573 }
1574 
1575 
1576 static lu_mem singlestep (lua_State *L) {
1577   global_State *g = G(L);
1578   switch (g->gcstate) {
1579     case GCSpause: {
1580       restartcollection(g);
1581       g->gcstate = GCSpropagate;
1582       return 1;
1583     }
1584     case GCSpropagate: {
1585       if (g->gray == NULL) {  /* no more gray objects? */
1586         g->gcstate = GCSenteratomic;  /* finish propagate phase */
1587         return 0;
1588       }
1589       else
1590         return propagatemark(g);  /* traverse one gray object */
1591     }
1592     case GCSenteratomic: {
1593       lu_mem work = atomic(L);  /* work is what was traversed by 'atomic' */
1594       entersweep(L);
1595       g->GCestimate = gettotalbytes(g);  /* first estimate */;
1596       return work;
1597     }
1598     case GCSswpallgc: {  /* sweep "regular" objects */
1599       return sweepstep(L, g, GCSswpfinobj, &g->finobj);
1600     }
1601     case GCSswpfinobj: {  /* sweep objects with finalizers */
1602       return sweepstep(L, g, GCSswptobefnz, &g->tobefnz);
1603     }
1604     case GCSswptobefnz: {  /* sweep objects to be finalized */
1605       return sweepstep(L, g, GCSswpend, NULL);
1606     }
1607     case GCSswpend: {  /* finish sweeps */
1608       checkSizes(L, g);
1609       g->gcstate = GCScallfin;
1610       return 0;
1611     }
1612     case GCScallfin: {  /* call remaining finalizers */
1613       if (g->tobefnz && !g->gcemergency) {
1614         int n = runafewfinalizers(L, GCFINMAX);
1615         return n * GCFINALIZECOST;
1616       }
1617       else {  /* emergency mode or no more finalizers */
1618         g->gcstate = GCSpause;  /* finish collection */
1619         return 0;
1620       }
1621     }
1622     default: lua_assert(0); return 0;
1623   }
1624 }
1625 
1626 
1627 /*
1628 ** advances the garbage collector until it reaches a state allowed
1629 ** by 'statemask'
1630 */
1631 void luaC_runtilstate (lua_State *L, int statesmask) {
1632   global_State *g = G(L);
1633   while (!testbit(statesmask, g->gcstate))
1634     singlestep(L);
1635 }
1636 
1637 
1638 /*
1639 ** Performs a basic incremental step. The debt and step size are
1640 ** converted from bytes to "units of work"; then the function loops
1641 ** running single steps until adding that many units of work or
1642 ** finishing a cycle (pause state). Finally, it sets the debt that
1643 ** controls when next step will be performed.
1644 */
1645 static void incstep (lua_State *L, global_State *g) {
1646   int stepmul = (getgcparam(g->gcstepmul) | 1);  /* avoid division by 0 */
1647   l_mem debt = (g->GCdebt / WORK2MEM) * stepmul;
1648   l_mem stepsize = (g->gcstepsize <= log2maxs(l_mem))
1649                  ? ((cast(l_mem, 1) << g->gcstepsize) / WORK2MEM) * stepmul
1650                  : MAX_LMEM;  /* overflow; keep maximum value */
1651   do {  /* repeat until pause or enough "credit" (negative debt) */
1652     lu_mem work = singlestep(L);  /* perform one single step */
1653     debt -= work;
1654   } while (debt > -stepsize && g->gcstate != GCSpause);
1655   if (g->gcstate == GCSpause)
1656     setpause(g);  /* pause until next cycle */
1657   else {
1658     debt = (debt / stepmul) * WORK2MEM;  /* convert 'work units' to bytes */
1659     luaE_setdebt(g, debt);
1660   }
1661 }
1662 
1663 /*
1664 ** performs a basic GC step if collector is running
1665 */
1666 void luaC_step (lua_State *L) {
1667   global_State *g = G(L);
1668   lua_assert(!g->gcemergency);
1669   if (g->gcrunning) {  /* running? */
1670     if(isdecGCmodegen(g))
1671       genstep(L, g);
1672     else
1673       incstep(L, g);
1674   }
1675 }
1676 
1677 
1678 /*
1679 ** Perform a full collection in incremental mode.
1680 ** Before running the collection, check 'keepinvariant'; if it is true,
1681 ** there may be some objects marked as black, so the collector has
1682 ** to sweep all objects to turn them back to white (as white has not
1683 ** changed, nothing will be collected).
1684 */
1685 static void fullinc (lua_State *L, global_State *g) {
1686   if (keepinvariant(g))  /* black objects? */
1687     entersweep(L); /* sweep everything to turn them back to white */
1688   /* finish any pending sweep phase to start a new cycle */
1689   luaC_runtilstate(L, bitmask(GCSpause));
1690   luaC_runtilstate(L, bitmask(GCScallfin));  /* run up to finalizers */
1691   /* estimate must be correct after a full GC cycle */
1692   lua_assert(g->GCestimate == gettotalbytes(g));
1693   luaC_runtilstate(L, bitmask(GCSpause));  /* finish collection */
1694   setpause(g);
1695 }
1696 
1697 
1698 /*
1699 ** Performs a full GC cycle; if 'isemergency', set a flag to avoid
1700 ** some operations which could change the interpreter state in some
1701 ** unexpected ways (running finalizers and shrinking some structures).
1702 */
1703 void luaC_fullgc (lua_State *L, int isemergency) {
1704   global_State *g = G(L);
1705   lua_assert(!g->gcemergency);
1706   g->gcemergency = isemergency;  /* set flag */
1707   if (g->gckind == KGC_INC)
1708     fullinc(L, g);
1709   else
1710     fullgen(L, g);
1711   g->gcemergency = 0;
1712 }
1713 
1714 /* }====================================================== */
1715 
1716 
1717