gc2.nim 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746
  1. #
  2. #
  3. # Nim's Runtime Library
  4. # (c) Copyright 2017 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. # Garbage Collector
  10. #
  11. # The basic algorithm is an incremental mark
  12. # and sweep GC to free cycles. It is hard realtime in that if you play
  13. # according to its rules, no deadline will ever be missed.
  14. # Since this kind of collector is very bad at recycling dead objects
  15. # early, Nim's codegen emits ``nimEscape`` calls at strategic
  16. # places. For this to work even 'unsureAsgnRef' needs to mark things
  17. # so that only return values need to be considered in ``nimEscape``.
  18. {.push profiler:off.}
  19. const
  20. CycleIncrease = 2 # is a multiplicative increase
  21. InitialCycleThreshold = 512*1024 # start collecting after 500KB
  22. ZctThreshold = 500 # we collect garbage if the ZCT's size
  23. # reaches this threshold
  24. # this seems to be a good value
  25. withRealTime = defined(useRealtimeGC)
  26. when withRealTime and not declared(getTicks):
  27. include "system/timers"
  28. when defined(memProfiler):
  29. proc nimProfile(requestedSize: int) {.benign.}
  30. when hasThreadSupport:
  31. include sharedlist
  32. type
  33. ObjectSpaceIter = object
  34. state: range[-1..0]
  35. iterToProc(allObjects, ptr ObjectSpaceIter, allObjectsAsProc)
  36. const
  37. escapedBit = 0b1000 # so that lowest 3 bits are not touched
  38. rcBlackOrig = 0b000
  39. rcWhiteOrig = 0b001
  40. rcGrey = 0b010 # traditional color for incremental mark&sweep
  41. rcUnused = 0b011
  42. colorMask = 0b011
  43. type
  44. WalkOp = enum
  45. waMarkGlobal, # part of the backup mark&sweep
  46. waMarkGrey,
  47. waZctDecRef,
  48. waDebug
  49. Phase {.pure.} = enum
  50. None, Marking, Sweeping
  51. Finalizer {.compilerproc.} = proc (self: pointer) {.nimcall, benign.}
  52. # A ref type can have a finalizer that is called before the object's
  53. # storage is freed.
  54. GcStat = object
  55. stackScans: int # number of performed stack scans (for statistics)
  56. completedCollections: int # number of performed full collections
  57. maxThreshold: int # max threshold that has been set
  58. maxStackSize: int # max stack size
  59. maxStackCells: int # max stack cells in ``decStack``
  60. cycleTableSize: int # max entries in cycle table
  61. maxPause: int64 # max measured GC pause in nanoseconds
  62. GcStack {.final, pure.} = object
  63. when nimCoroutines:
  64. prev: ptr GcStack
  65. next: ptr GcStack
  66. maxStackSize: int # Used to track statistics because we can not use
  67. # GcStat.maxStackSize when multiple stacks exist.
  68. bottom: pointer
  69. when withRealTime or nimCoroutines:
  70. pos: pointer # Used with `withRealTime` only for code clarity, see GC_Step().
  71. when withRealTime:
  72. bottomSaved: pointer
  73. GcHeap = object # this contains the zero count and
  74. # non-zero count table
  75. black, red: int # either 0 or 1.
  76. stack: GcStack
  77. when nimCoroutines:
  78. activeStack: ptr GcStack # current executing coroutine stack.
  79. phase: Phase
  80. cycleThreshold: int
  81. when useCellIds:
  82. idGenerator: int
  83. greyStack: CellSeq
  84. recGcLock: int # prevent recursion via finalizers; no thread lock
  85. when withRealTime:
  86. maxPause: Nanos # max allowed pause in nanoseconds; active if > 0
  87. region: MemRegion # garbage collected region
  88. stat: GcStat
  89. additionalRoots: CellSeq # explicit roots for GC_ref/unref
  90. spaceIter: ObjectSpaceIter
  91. pDumpHeapFile: pointer # File that is used for GC_dumpHeap
  92. when hasThreadSupport:
  93. toDispose: SharedList[pointer]
  94. gcThreadId: int
  95. var
  96. gch {.rtlThreadVar.}: GcHeap
  97. when not defined(useNimRtl):
  98. instantiateForRegion(gch.region)
  99. # Which color to use for new objects is tricky: When we're marking,
  100. # they have to be *white* so that everything is marked that is only
  101. # reachable from them. However, when we are sweeping, they have to
  102. # be black, so that we don't free them prematuredly. In order to save
  103. # a comparison gch.phase == Phase.Marking, we use the pseudo-color
  104. # 'red' for new objects.
  105. template allocColor(): untyped = gch.red
  106. template gcAssert(cond: bool, msg: string) =
  107. when defined(useGcAssert):
  108. if not cond:
  109. echo "[GCASSERT] ", msg
  110. GC_disable()
  111. writeStackTrace()
  112. quit 1
  113. proc cellToUsr(cell: PCell): pointer {.inline.} =
  114. # convert object (=pointer to refcount) to pointer to userdata
  115. result = cast[pointer](cast[ByteAddress](cell)+%ByteAddress(sizeof(Cell)))
  116. proc usrToCell(usr: pointer): PCell {.inline.} =
  117. # convert pointer to userdata to object (=pointer to refcount)
  118. result = cast[PCell](cast[ByteAddress](usr)-%ByteAddress(sizeof(Cell)))
  119. proc extGetCellType(c: pointer): PNimType {.compilerproc.} =
  120. # used for code generation concerning debugging
  121. result = usrToCell(c).typ
  122. proc internRefcount(p: pointer): int {.exportc: "getRefcount".} =
  123. result = 0
  124. # this that has to equals zero, otherwise we have to round up UnitsPerPage:
  125. when BitsPerPage mod (sizeof(int)*8) != 0:
  126. {.error: "(BitsPerPage mod BitsPerUnit) should be zero!".}
  127. template color(c): untyped = c.refCount and colorMask
  128. template setColor(c, col) =
  129. c.refcount = c.refcount and not colorMask or col
  130. template markAsEscaped(c: PCell) =
  131. c.refcount = c.refcount or escapedBit
  132. template didEscape(c: PCell): bool =
  133. (c.refCount and escapedBit) != 0
  134. proc writeCell(file: File; msg: cstring, c: PCell) =
  135. var kind = -1
  136. if c.typ != nil: kind = ord(c.typ.kind)
  137. let col = if c.color == rcGrey: 'g'
  138. elif c.color == gch.black: 'b'
  139. else: 'w'
  140. when useCellIds:
  141. let id = c.id
  142. else:
  143. let id = c
  144. when defined(nimTypeNames):
  145. c_fprintf(file, "%s %p %d escaped=%ld color=%c of type %s\n",
  146. msg, id, kind, didEscape(c), col, c.typ.name)
  147. elif leakDetector:
  148. c_fprintf(file, "%s %p %d escaped=%ld color=%c from %s(%ld)\n",
  149. msg, id, kind, didEscape(c), col, c.filename, c.line)
  150. else:
  151. c_fprintf(file, "%s %p %d escaped=%ld color=%c\n",
  152. msg, id, kind, didEscape(c), col)
  153. proc writeCell(msg: cstring, c: PCell) =
  154. stdout.writeCell(msg, c)
  155. proc myastToStr[T](x: T): string {.magic: "AstToStr", noSideEffect.}
  156. template gcTrace(cell, state: untyped) =
  157. when traceGC: writeCell(myastToStr(state), cell)
  158. # forward declarations:
  159. proc collectCT(gch: var GcHeap) {.benign.}
  160. proc isOnStack(p: pointer): bool {.noinline, benign.}
  161. proc forAllChildren(cell: PCell, op: WalkOp) {.benign.}
  162. proc doOperation(p: pointer, op: WalkOp) {.benign.}
  163. proc forAllChildrenAux(dest: pointer, mt: PNimType, op: WalkOp) {.benign.}
  164. # we need the prototype here for debugging purposes
  165. proc nimGCref(p: pointer) {.compilerProc.} =
  166. let cell = usrToCell(p)
  167. markAsEscaped(cell)
  168. add(gch.additionalRoots, cell)
  169. proc nimGCunref(p: pointer) {.compilerProc.} =
  170. let cell = usrToCell(p)
  171. var L = gch.additionalRoots.len-1
  172. var i = L
  173. let d = gch.additionalRoots.d
  174. while i >= 0:
  175. if d[i] == cell:
  176. d[i] = d[L]
  177. dec gch.additionalRoots.len
  178. break
  179. dec(i)
  180. proc nimGCunrefNoCycle(p: pointer) {.compilerProc, inline.} =
  181. discard "can we do some freeing here?"
  182. proc nimGCunrefRC1(p: pointer) {.compilerProc, inline.} =
  183. discard "can we do some freeing here?"
  184. template markGrey(x: PCell) =
  185. if x.color != 1-gch.black and gch.phase == Phase.Marking:
  186. if not isAllocatedPtr(gch.region, x):
  187. c_fprintf(stdout, "[GC] markGrey proc: %p\n", x)
  188. #GC_dumpHeap()
  189. sysAssert(false, "wtf")
  190. x.setColor(rcGrey)
  191. add(gch.greyStack, x)
  192. proc asgnRef(dest: PPointer, src: pointer) {.compilerProc, inline.} =
  193. # the code generator calls this proc!
  194. gcAssert(not isOnStack(dest), "asgnRef")
  195. # BUGFIX: first incRef then decRef!
  196. if src != nil:
  197. let s = usrToCell(src)
  198. markAsEscaped(s)
  199. markGrey(s)
  200. dest[] = src
  201. proc asgnRefNoCycle(dest: PPointer, src: pointer) {.compilerproc, inline,
  202. deprecated: "old compiler compat".} = asgnRef(dest, src)
  203. proc unsureAsgnRef(dest: PPointer, src: pointer) {.compilerProc.} =
  204. # unsureAsgnRef marks 'src' as grey only if dest is not on the
  205. # stack. It is used by the code generator if it cannot decide wether a
  206. # reference is in the stack or not (this can happen for var parameters).
  207. if src != nil:
  208. let s = usrToCell(src)
  209. markAsEscaped(s)
  210. if not isOnStack(dest): markGrey(s)
  211. dest[] = src
  212. proc forAllSlotsAux(dest: pointer, n: ptr TNimNode, op: WalkOp) {.benign.} =
  213. var d = cast[ByteAddress](dest)
  214. case n.kind
  215. of nkSlot: forAllChildrenAux(cast[pointer](d +% n.offset), n.typ, op)
  216. of nkList:
  217. for i in 0..n.len-1:
  218. forAllSlotsAux(dest, n.sons[i], op)
  219. of nkCase:
  220. var m = selectBranch(dest, n)
  221. if m != nil: forAllSlotsAux(dest, m, op)
  222. of nkNone: sysAssert(false, "forAllSlotsAux")
  223. proc forAllChildrenAux(dest: pointer, mt: PNimType, op: WalkOp) =
  224. var d = cast[ByteAddress](dest)
  225. if dest == nil: return # nothing to do
  226. if ntfNoRefs notin mt.flags:
  227. case mt.kind
  228. of tyRef, tyString, tySequence: # leaf:
  229. doOperation(cast[PPointer](d)[], op)
  230. of tyObject, tyTuple:
  231. forAllSlotsAux(dest, mt.node, op)
  232. of tyArray, tyArrayConstr, tyOpenArray:
  233. for i in 0..(mt.size div mt.base.size)-1:
  234. forAllChildrenAux(cast[pointer](d +% i *% mt.base.size), mt.base, op)
  235. else: discard
  236. proc forAllChildren(cell: PCell, op: WalkOp) =
  237. gcAssert(cell != nil, "forAllChildren: 1")
  238. gcAssert(isAllocatedPtr(gch.region, cell), "forAllChildren: 2")
  239. gcAssert(cell.typ != nil, "forAllChildren: 3")
  240. gcAssert cell.typ.kind in {tyRef, tySequence, tyString}, "forAllChildren: 4"
  241. let marker = cell.typ.marker
  242. if marker != nil:
  243. marker(cellToUsr(cell), op.int)
  244. else:
  245. case cell.typ.kind
  246. of tyRef: # common case
  247. forAllChildrenAux(cellToUsr(cell), cell.typ.base, op)
  248. of tySequence:
  249. var d = cast[ByteAddress](cellToUsr(cell))
  250. var s = cast[PGenericSeq](d)
  251. if s != nil:
  252. for i in 0..s.len-1:
  253. forAllChildrenAux(cast[pointer](d +% i *% cell.typ.base.size +%
  254. GenericSeqSize), cell.typ.base, op)
  255. else: discard
  256. {.push stackTrace: off, profiler:off.}
  257. proc gcInvariant*() =
  258. sysAssert(allocInv(gch.region), "injected")
  259. when declared(markForDebug):
  260. markForDebug(gch)
  261. {.pop.}
  262. include gc_common
  263. proc initGC() =
  264. when not defined(useNimRtl):
  265. gch.red = (1-gch.black)
  266. gch.cycleThreshold = InitialCycleThreshold
  267. gch.stat.stackScans = 0
  268. gch.stat.completedCollections = 0
  269. gch.stat.maxThreshold = 0
  270. gch.stat.maxStackSize = 0
  271. gch.stat.maxStackCells = 0
  272. gch.stat.cycleTableSize = 0
  273. # init the rt
  274. init(gch.additionalRoots)
  275. init(gch.greyStack)
  276. when hasThreadSupport:
  277. init(gch.toDispose)
  278. gch.gcThreadId = atomicInc(gHeapidGenerator) - 1
  279. gcAssert(gch.gcThreadId >= 0, "invalid computed thread ID")
  280. proc rawNewObj(typ: PNimType, size: int, gch: var GcHeap): pointer =
  281. # generates a new object and sets its reference counter to 0
  282. sysAssert(allocInv(gch.region), "rawNewObj begin")
  283. gcAssert(typ.kind in {tyRef, tyString, tySequence}, "newObj: 1")
  284. collectCT(gch)
  285. var res = cast[PCell](rawAlloc(gch.region, size + sizeof(Cell)))
  286. gcAssert((cast[ByteAddress](res) and (MemAlign-1)) == 0, "newObj: 2")
  287. # now it is buffered in the ZCT
  288. res.typ = typ
  289. when leakDetector and not hasThreadSupport:
  290. if framePtr != nil and framePtr.prev != nil:
  291. res.filename = framePtr.prev.filename
  292. res.line = framePtr.prev.line
  293. # refcount is zero, color is black, but mark it to be in the ZCT
  294. res.refcount = allocColor()
  295. sysAssert(isAllocatedPtr(gch.region, res), "newObj: 3")
  296. when logGC: writeCell("new cell", res)
  297. gcTrace(res, csAllocated)
  298. when useCellIds:
  299. inc gch.idGenerator
  300. res.id = gch.idGenerator
  301. result = cellToUsr(res)
  302. sysAssert(allocInv(gch.region), "rawNewObj end")
  303. {.pop.}
  304. proc newObjNoInit(typ: PNimType, size: int): pointer {.compilerRtl.} =
  305. result = rawNewObj(typ, size, gch)
  306. when defined(memProfiler): nimProfile(size)
  307. proc newObj(typ: PNimType, size: int): pointer {.compilerRtl.} =
  308. result = rawNewObj(typ, size, gch)
  309. zeroMem(result, size)
  310. when defined(memProfiler): nimProfile(size)
  311. proc newSeq(typ: PNimType, len: int): pointer {.compilerRtl.} =
  312. # `newObj` already uses locks, so no need for them here.
  313. let size = addInt(mulInt(len, typ.base.size), GenericSeqSize)
  314. result = newObj(typ, size)
  315. cast[PGenericSeq](result).len = len
  316. cast[PGenericSeq](result).reserved = len
  317. when defined(memProfiler): nimProfile(size)
  318. proc newObjRC1(typ: PNimType, size: int): pointer {.compilerRtl.} =
  319. result = newObj(typ, size)
  320. proc newSeqRC1(typ: PNimType, len: int): pointer {.compilerRtl.} =
  321. result = newSeq(typ, len)
  322. proc growObj(old: pointer, newsize: int, gch: var GcHeap): pointer =
  323. collectCT(gch)
  324. var ol = usrToCell(old)
  325. sysAssert(ol.typ != nil, "growObj: 1")
  326. gcAssert(ol.typ.kind in {tyString, tySequence}, "growObj: 2")
  327. var res = cast[PCell](rawAlloc(gch.region, newsize + sizeof(Cell)))
  328. var elemSize = 1
  329. if ol.typ.kind != tyString: elemSize = ol.typ.base.size
  330. incTypeSize ol.typ, newsize
  331. var oldsize = cast[PGenericSeq](old).len*elemSize + GenericSeqSize
  332. copyMem(res, ol, oldsize + sizeof(Cell))
  333. zeroMem(cast[pointer](cast[ByteAddress](res)+% oldsize +% sizeof(Cell)),
  334. newsize-oldsize)
  335. sysAssert((cast[ByteAddress](res) and (MemAlign-1)) == 0, "growObj: 3")
  336. when false:
  337. # this is wrong since seqs can be shared via 'shallow':
  338. when reallyDealloc: rawDealloc(gch.region, ol)
  339. else:
  340. zeroMem(ol, sizeof(Cell))
  341. when useCellIds:
  342. inc gch.idGenerator
  343. res.id = gch.idGenerator
  344. result = cellToUsr(res)
  345. when defined(memProfiler): nimProfile(newsize-oldsize)
  346. proc growObj(old: pointer, newsize: int): pointer {.rtl.} =
  347. result = growObj(old, newsize, gch)
  348. {.push profiler:off.}
  349. template takeStartTime(workPackageSize) {.dirty.} =
  350. const workPackage = workPackageSize
  351. var debugticker = 1000
  352. when withRealTime:
  353. var steps = workPackage
  354. var t0: Ticks
  355. if gch.maxPause > 0: t0 = getticks()
  356. template takeTime {.dirty.} =
  357. when withRealTime: dec steps
  358. dec debugticker
  359. template checkTime {.dirty.} =
  360. if debugticker <= 0:
  361. #echo "in loop"
  362. debugticker = 1000
  363. when withRealTime:
  364. if steps == 0:
  365. steps = workPackage
  366. if gch.maxPause > 0:
  367. let duration = getticks() - t0
  368. # the GC's measuring is not accurate and needs some cleanup actions
  369. # (stack unmarking), so subtract some short amount of time in
  370. # order to miss deadlines less often:
  371. if duration >= gch.maxPause - 50_000:
  372. return false
  373. # ---------------- dump heap ----------------
  374. template dumpHeapFile(gch: var GcHeap): File =
  375. cast[File](gch.pDumpHeapFile)
  376. proc debugGraph(s: PCell) =
  377. c_fprintf(gch.dumpHeapFile, "child %p\n", s)
  378. proc dumpRoot(gch: var GcHeap; s: PCell) =
  379. if isAllocatedPtr(gch.region, s):
  380. c_fprintf(gch.dumpHeapFile, "global_root %p\n", s)
  381. else:
  382. c_fprintf(gch.dumpHeapFile, "global_root_invalid %p\n", s)
  383. proc GC_dumpHeap*(file: File) =
  384. ## Dumps the GCed heap's content to a file. Can be useful for
  385. ## debugging. Produces an undocumented text file format that
  386. ## can be translated into "dot" syntax via the "heapdump2dot" tool.
  387. gch.pDumpHeapFile = file
  388. var spaceIter: ObjectSpaceIter
  389. when false:
  390. var d = gch.decStack.d
  391. for i in 0 .. gch.decStack.len-1:
  392. if isAllocatedPtr(gch.region, d[i]):
  393. c_fprintf(file, "onstack %p\n", d[i])
  394. else:
  395. c_fprintf(file, "onstack_invalid %p\n", d[i])
  396. if gch.gcThreadId == 0:
  397. for i in 0 .. globalMarkersLen-1: globalMarkers[i]()
  398. for i in 0 .. threadLocalMarkersLen-1: threadLocalMarkers[i]()
  399. while true:
  400. let x = allObjectsAsProc(gch.region, addr spaceIter)
  401. if spaceIter.state < 0: break
  402. if isCell(x):
  403. # cast to PCell is correct here:
  404. var c = cast[PCell](x)
  405. writeCell(file, "cell ", c)
  406. forAllChildren(c, waDebug)
  407. c_fprintf(file, "end\n")
  408. gch.pDumpHeapFile = nil
  409. proc GC_dumpHeap() =
  410. var f: File
  411. if open(f, "heap.txt", fmWrite):
  412. GC_dumpHeap(f)
  413. f.close()
  414. else:
  415. c_fprintf(stdout, "cannot write heap.txt")
  416. # ---------------- cycle collector -------------------------------------------
  417. proc freeCyclicCell(gch: var GcHeap, c: PCell) =
  418. gcAssert(isAllocatedPtr(gch.region, c), "freeCyclicCell: freed pointer?")
  419. prepareDealloc(c)
  420. gcTrace(c, csCycFreed)
  421. when logGC: writeCell("cycle collector dealloc cell", c)
  422. when reallyDealloc:
  423. sysAssert(allocInv(gch.region), "free cyclic cell")
  424. rawDealloc(gch.region, c)
  425. else:
  426. gcAssert(c.typ != nil, "freeCyclicCell")
  427. zeroMem(c, sizeof(Cell))
  428. proc sweep(gch: var GcHeap): bool =
  429. takeStartTime(100)
  430. #echo "loop start"
  431. let white = 1-gch.black
  432. #c_fprintf(stdout, "black is %d\n", black)
  433. while true:
  434. let x = allObjectsAsProc(gch.region, addr gch.spaceIter)
  435. if gch.spaceIter.state < 0: break
  436. takeTime()
  437. if isCell(x):
  438. # cast to PCell is correct here:
  439. var c = cast[PCell](x)
  440. gcAssert c.color != rcGrey, "cell is still grey?"
  441. if c.color == white: freeCyclicCell(gch, c)
  442. # Since this is incremental, we MUST not set the object to 'white' here.
  443. # We could set all the remaining objects to white after the 'sweep'
  444. # completed but instead we flip the meaning of black/white to save one
  445. # traversal over the heap!
  446. checkTime()
  447. # prepare for next iteration:
  448. #echo "loop end"
  449. gch.spaceIter = ObjectSpaceIter()
  450. result = true
  451. proc markRoot(gch: var GcHeap, c: PCell) {.inline.} =
  452. if c.color == 1-gch.black:
  453. c.setColor(rcGrey)
  454. add(gch.greyStack, c)
  455. proc markIncremental(gch: var GcHeap): bool =
  456. var L = addr(gch.greyStack.len)
  457. takeStartTime(100)
  458. while L[] > 0:
  459. var c = gch.greyStack.d[0]
  460. if not isAllocatedPtr(gch.region, c):
  461. c_fprintf(stdout, "[GC] not allocated anymore: %p\n", c)
  462. #GC_dumpHeap()
  463. sysAssert(false, "wtf")
  464. #sysAssert(isAllocatedPtr(gch.region, c), "markIncremental: isAllocatedPtr")
  465. gch.greyStack.d[0] = gch.greyStack.d[L[] - 1]
  466. dec(L[])
  467. takeTime()
  468. if c.color == rcGrey:
  469. c.setColor(gch.black)
  470. forAllChildren(c, waMarkGrey)
  471. elif c.color == (1-gch.black):
  472. gcAssert false, "wtf why are there white objects in the greystack?"
  473. checkTime()
  474. gcAssert gch.greyStack.len == 0, "markIncremental: greystack not empty "
  475. result = true
  476. proc markGlobals(gch: var GcHeap) =
  477. if gch.gcThreadId == 0:
  478. for i in 0 .. globalMarkersLen-1: globalMarkers[i]()
  479. for i in 0 .. threadLocalMarkersLen-1: threadLocalMarkers[i]()
  480. proc doOperation(p: pointer, op: WalkOp) =
  481. if p == nil: return
  482. var c: PCell = usrToCell(p)
  483. gcAssert(c != nil, "doOperation: 1")
  484. # the 'case' should be faster than function pointers because of easy
  485. # prediction:
  486. case op
  487. of waZctDecRef:
  488. #if not isAllocatedPtr(gch.region, c):
  489. # c_fprintf(stdout, "[GC] decref bug: %p", c)
  490. gcAssert(isAllocatedPtr(gch.region, c), "decRef: waZctDecRef")
  491. discard "use me for nimEscape?"
  492. of waMarkGlobal:
  493. template handleRoot =
  494. if gch.dumpHeapFile.isNil:
  495. markRoot(gch, c)
  496. else:
  497. dumpRoot(gch, c)
  498. handleRoot()
  499. discard allocInv(gch.region)
  500. of waMarkGrey:
  501. when false:
  502. if not isAllocatedPtr(gch.region, c):
  503. c_fprintf(stdout, "[GC] not allocated anymore: MarkGrey %p\n", c)
  504. #GC_dumpHeap()
  505. sysAssert(false, "wtf")
  506. if c.color == 1-gch.black:
  507. c.setColor(rcGrey)
  508. add(gch.greyStack, c)
  509. of waDebug: debugGraph(c)
  510. proc nimGCvisit(d: pointer, op: int) {.compilerRtl.} =
  511. doOperation(d, WalkOp(op))
  512. proc gcMark(gch: var GcHeap, p: pointer) {.inline.} =
  513. # the addresses are not as cells on the stack, so turn them to cells:
  514. sysAssert(allocInv(gch.region), "gcMark begin")
  515. var cell = usrToCell(p)
  516. var c = cast[ByteAddress](cell)
  517. if c >% PageSize:
  518. # fast check: does it look like a cell?
  519. var objStart = cast[PCell](interiorAllocatedPtr(gch.region, cell))
  520. if objStart != nil:
  521. # mark the cell:
  522. markRoot(gch, objStart)
  523. sysAssert(allocInv(gch.region), "gcMark end")
  524. proc markStackAndRegisters(gch: var GcHeap) {.noinline, cdecl.} =
  525. forEachStackSlot(gch, gcMark)
  526. proc collectALittle(gch: var GcHeap): bool =
  527. case gch.phase
  528. of Phase.None:
  529. if getOccupiedMem(gch.region) >= gch.cycleThreshold:
  530. gch.phase = Phase.Marking
  531. markGlobals(gch)
  532. result = collectALittle(gch)
  533. #when false: c_fprintf(stdout, "collectALittle: introduced bug E %ld\n", gch.phase)
  534. #discard allocInv(gch.region)
  535. of Phase.Marking:
  536. when hasThreadSupport:
  537. for c in gch.toDispose:
  538. nimGCunref(c)
  539. prepareForInteriorPointerChecking(gch.region)
  540. markStackAndRegisters(gch)
  541. inc(gch.stat.stackScans)
  542. if markIncremental(gch):
  543. gch.phase = Phase.Sweeping
  544. gch.red = 1 - gch.red
  545. of Phase.Sweeping:
  546. gcAssert gch.greyStack.len == 0, "greystack not empty"
  547. when hasThreadSupport:
  548. for c in gch.toDispose:
  549. nimGCunref(c)
  550. if sweep(gch):
  551. gch.phase = Phase.None
  552. # flip black/white meanings:
  553. gch.black = 1 - gch.black
  554. gcAssert gch.red == 1 - gch.black, "red color is wrong"
  555. inc(gch.stat.completedCollections)
  556. result = true
  557. proc collectCTBody(gch: var GcHeap) =
  558. when withRealTime:
  559. let t0 = getticks()
  560. sysAssert(allocInv(gch.region), "collectCT: begin")
  561. when not nimCoroutines:
  562. gch.stat.maxStackSize = max(gch.stat.maxStackSize, stackSize())
  563. #gch.stat.maxStackCells = max(gch.stat.maxStackCells, gch.decStack.len)
  564. if collectALittle(gch):
  565. gch.cycleThreshold = max(InitialCycleThreshold, getOccupiedMem() *
  566. CycleIncrease)
  567. gch.stat.maxThreshold = max(gch.stat.maxThreshold, gch.cycleThreshold)
  568. sysAssert(allocInv(gch.region), "collectCT: end")
  569. when withRealTime:
  570. let duration = getticks() - t0
  571. gch.stat.maxPause = max(gch.stat.maxPause, duration)
  572. when defined(reportMissedDeadlines):
  573. if gch.maxPause > 0 and duration > gch.maxPause:
  574. c_fprintf(stdout, "[GC] missed deadline: %ld\n", duration)
  575. when nimCoroutines:
  576. proc currentStackSizes(): int =
  577. for stack in items(gch.stack):
  578. result = result + stack.stackSize()
  579. proc collectCT(gch: var GcHeap) =
  580. # stackMarkCosts prevents some pathological behaviour: Stack marking
  581. # becomes more expensive with large stacks and large stacks mean that
  582. # cells with RC=0 are more likely to be kept alive by the stack.
  583. when nimCoroutines:
  584. let stackMarkCosts = max(currentStackSizes() div (16*sizeof(int)), ZctThreshold)
  585. else:
  586. let stackMarkCosts = max(stackSize() div (16*sizeof(int)), ZctThreshold)
  587. if (gch.greyStack.len >= stackMarkCosts or (cycleGC and
  588. getOccupiedMem(gch.region)>=gch.cycleThreshold) or alwaysGC) and
  589. gch.recGcLock == 0:
  590. collectCTBody(gch)
  591. when withRealTime:
  592. proc toNano(x: int): Nanos {.inline.} =
  593. result = x * 1000
  594. proc GC_setMaxPause*(MaxPauseInUs: int) =
  595. gch.maxPause = MaxPauseInUs.toNano
  596. proc GC_step(gch: var GcHeap, us: int, strongAdvice: bool) =
  597. gch.maxPause = us.toNano
  598. #if (getOccupiedMem(gch.region)>=gch.cycleThreshold) or
  599. # alwaysGC or strongAdvice:
  600. collectCTBody(gch)
  601. proc GC_step*(us: int, strongAdvice = false, stackSize = -1) {.noinline.} =
  602. if stackSize >= 0:
  603. var stackTop {.volatile.}: pointer
  604. gch.getActiveStack().pos = addr(stackTop)
  605. for stack in gch.stack.items():
  606. stack.bottomSaved = stack.bottom
  607. when stackIncreases:
  608. stack.bottom = cast[pointer](
  609. cast[ByteAddress](stack.pos) - sizeof(pointer) * 6 - stackSize)
  610. else:
  611. stack.bottom = cast[pointer](
  612. cast[ByteAddress](stack.pos) + sizeof(pointer) * 6 + stackSize)
  613. GC_step(gch, us, strongAdvice)
  614. if stackSize >= 0:
  615. for stack in gch.stack.items():
  616. stack.bottom = stack.bottomSaved
  617. when not defined(useNimRtl):
  618. proc GC_disable() =
  619. inc(gch.recGcLock)
  620. proc GC_enable() =
  621. if gch.recGcLock > 0:
  622. dec(gch.recGcLock)
  623. proc GC_setStrategy(strategy: GC_Strategy) =
  624. discard
  625. proc GC_enableMarkAndSweep() = discard
  626. proc GC_disableMarkAndSweep() = discard
  627. proc GC_fullCollect() =
  628. var oldThreshold = gch.cycleThreshold
  629. gch.cycleThreshold = 0 # forces cycle collection
  630. collectCT(gch)
  631. gch.cycleThreshold = oldThreshold
  632. proc GC_getStatistics(): string =
  633. GC_disable()
  634. result = "[GC] total memory: " & $(getTotalMem()) & "\n" &
  635. "[GC] occupied memory: " & $(getOccupiedMem()) & "\n" &
  636. "[GC] stack scans: " & $gch.stat.stackScans & "\n" &
  637. "[GC] stack cells: " & $gch.stat.maxStackCells & "\n" &
  638. "[GC] completed collections: " & $gch.stat.completedCollections & "\n" &
  639. "[GC] max threshold: " & $gch.stat.maxThreshold & "\n" &
  640. "[GC] grey stack capacity: " & $gch.greyStack.cap & "\n" &
  641. "[GC] max cycle table size: " & $gch.stat.cycleTableSize & "\n" &
  642. "[GC] max pause time [ms]: " & $(gch.stat.maxPause div 1000_000) & "\n"
  643. when nimCoroutines:
  644. result.add "[GC] number of stacks: " & $gch.stack.len & "\n"
  645. for stack in items(gch.stack):
  646. result.add "[GC] stack " & stack.bottom.repr & "[GC] max stack size " & $stack.maxStackSize & "\n"
  647. else:
  648. result.add "[GC] max stack size: " & $gch.stat.maxStackSize & "\n"
  649. GC_enable()
  650. {.pop.}