gc2.nim 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747
  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 whether 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 +% align(GenericSeqSize, cell.typ.base.align) +% i *% cell.typ.base.size), cell.typ.base, op)
  254. else: discard
  255. {.push stackTrace: off, profiler:off.}
  256. proc gcInvariant*() =
  257. sysAssert(allocInv(gch.region), "injected")
  258. when declared(markForDebug):
  259. markForDebug(gch)
  260. {.pop.}
  261. include gc_common
  262. proc initGC() =
  263. when not defined(useNimRtl):
  264. gch.red = (1-gch.black)
  265. gch.cycleThreshold = InitialCycleThreshold
  266. gch.stat.stackScans = 0
  267. gch.stat.completedCollections = 0
  268. gch.stat.maxThreshold = 0
  269. gch.stat.maxStackSize = 0
  270. gch.stat.maxStackCells = 0
  271. gch.stat.cycleTableSize = 0
  272. # init the rt
  273. init(gch.additionalRoots)
  274. init(gch.greyStack)
  275. when hasThreadSupport:
  276. init(gch.toDispose)
  277. gch.gcThreadId = atomicInc(gHeapidGenerator) - 1
  278. gcAssert(gch.gcThreadId >= 0, "invalid computed thread ID")
  279. proc rawNewObj(typ: PNimType, size: int, gch: var GcHeap): pointer =
  280. # generates a new object and sets its reference counter to 0
  281. sysAssert(allocInv(gch.region), "rawNewObj begin")
  282. gcAssert(typ.kind in {tyRef, tyString, tySequence}, "newObj: 1")
  283. collectCT(gch)
  284. var res = cast[PCell](rawAlloc(gch.region, size + sizeof(Cell)))
  285. gcAssert((cast[ByteAddress](res) and (MemAlign-1)) == 0, "newObj: 2")
  286. # now it is buffered in the ZCT
  287. res.typ = typ
  288. when leakDetector and not hasThreadSupport:
  289. if framePtr != nil and framePtr.prev != nil:
  290. res.filename = framePtr.prev.filename
  291. res.line = framePtr.prev.line
  292. # refcount is zero, color is black, but mark it to be in the ZCT
  293. res.refcount = allocColor()
  294. sysAssert(isAllocatedPtr(gch.region, res), "newObj: 3")
  295. when logGC: writeCell("new cell", res)
  296. gcTrace(res, csAllocated)
  297. when useCellIds:
  298. inc gch.idGenerator
  299. res.id = gch.idGenerator
  300. result = cellToUsr(res)
  301. sysAssert(allocInv(gch.region), "rawNewObj end")
  302. {.pop.}
  303. proc newObjNoInit(typ: PNimType, size: int): pointer {.compilerRtl.} =
  304. result = rawNewObj(typ, size, gch)
  305. when defined(memProfiler): nimProfile(size)
  306. proc newObj(typ: PNimType, size: int): pointer {.compilerRtl.} =
  307. result = rawNewObj(typ, size, gch)
  308. zeroMem(result, size)
  309. when defined(memProfiler): nimProfile(size)
  310. proc newSeq(typ: PNimType, len: int): pointer {.compilerRtl.} =
  311. # `newObj` already uses locks, so no need for them here.
  312. let size = addInt(align(GenericSeqSize, typ.base.align), mulInt(len, typ.base.size))
  313. result = newObj(typ, size)
  314. cast[PGenericSeq](result).len = len
  315. cast[PGenericSeq](result).reserved = len
  316. when defined(memProfiler): nimProfile(size)
  317. proc newObjRC1(typ: PNimType, size: int): pointer {.compilerRtl.} =
  318. result = newObj(typ, size)
  319. proc newSeqRC1(typ: PNimType, len: int): pointer {.compilerRtl.} =
  320. result = newSeq(typ, len)
  321. proc growObj(old: pointer, newsize: int, gch: var GcHeap): pointer =
  322. collectCT(gch)
  323. var ol = usrToCell(old)
  324. sysAssert(ol.typ != nil, "growObj: 1")
  325. gcAssert(ol.typ.kind in {tyString, tySequence}, "growObj: 2")
  326. var res = cast[PCell](rawAlloc(gch.region, newsize + sizeof(Cell)))
  327. var elemSize, elemAlign = 1
  328. if ol.typ.kind != tyString:
  329. elemSize = ol.typ.base.size
  330. elemAlign = ol.typ.base.align
  331. incTypeSize ol.typ, newsize
  332. var oldsize = align(GenericSeqSize, elemAlign) + cast[PGenericSeq](old).len*elemSize
  333. copyMem(res, ol, oldsize + sizeof(Cell))
  334. zeroMem(cast[pointer](cast[ByteAddress](res)+% oldsize +% sizeof(Cell)),
  335. newsize-oldsize)
  336. sysAssert((cast[ByteAddress](res) and (MemAlign-1)) == 0, "growObj: 3")
  337. when false:
  338. # this is wrong since seqs can be shared via 'shallow':
  339. when reallyDealloc: rawDealloc(gch.region, ol)
  340. else:
  341. zeroMem(ol, sizeof(Cell))
  342. when useCellIds:
  343. inc gch.idGenerator
  344. res.id = gch.idGenerator
  345. result = cellToUsr(res)
  346. when defined(memProfiler): nimProfile(newsize-oldsize)
  347. proc growObj(old: pointer, newsize: int): pointer {.rtl.} =
  348. result = growObj(old, newsize, gch)
  349. {.push profiler:off.}
  350. template takeStartTime(workPackageSize) {.dirty.} =
  351. const workPackage = workPackageSize
  352. var debugticker = 1000
  353. when withRealTime:
  354. var steps = workPackage
  355. var t0: Ticks
  356. if gch.maxPause > 0: t0 = getticks()
  357. template takeTime {.dirty.} =
  358. when withRealTime: dec steps
  359. dec debugticker
  360. template checkTime {.dirty.} =
  361. if debugticker <= 0:
  362. #echo "in loop"
  363. debugticker = 1000
  364. when withRealTime:
  365. if steps == 0:
  366. steps = workPackage
  367. if gch.maxPause > 0:
  368. let duration = getticks() - t0
  369. # the GC's measuring is not accurate and needs some cleanup actions
  370. # (stack unmarking), so subtract some short amount of time in
  371. # order to miss deadlines less often:
  372. if duration >= gch.maxPause - 50_000:
  373. return false
  374. # ---------------- dump heap ----------------
  375. template dumpHeapFile(gch: var GcHeap): File =
  376. cast[File](gch.pDumpHeapFile)
  377. proc debugGraph(s: PCell) =
  378. c_fprintf(gch.dumpHeapFile, "child %p\n", s)
  379. proc dumpRoot(gch: var GcHeap; s: PCell) =
  380. if isAllocatedPtr(gch.region, s):
  381. c_fprintf(gch.dumpHeapFile, "global_root %p\n", s)
  382. else:
  383. c_fprintf(gch.dumpHeapFile, "global_root_invalid %p\n", s)
  384. proc GC_dumpHeap*(file: File) =
  385. ## Dumps the GCed heap's content to a file. Can be useful for
  386. ## debugging. Produces an undocumented text file format that
  387. ## can be translated into "dot" syntax via the "heapdump2dot" tool.
  388. gch.pDumpHeapFile = file
  389. var spaceIter: ObjectSpaceIter
  390. when false:
  391. var d = gch.decStack.d
  392. for i in 0 .. gch.decStack.len-1:
  393. if isAllocatedPtr(gch.region, d[i]):
  394. c_fprintf(file, "onstack %p\n", d[i])
  395. else:
  396. c_fprintf(file, "onstack_invalid %p\n", d[i])
  397. if gch.gcThreadId == 0:
  398. for i in 0 .. globalMarkersLen-1: globalMarkers[i]()
  399. for i in 0 .. threadLocalMarkersLen-1: threadLocalMarkers[i]()
  400. while true:
  401. let x = allObjectsAsProc(gch.region, addr spaceIter)
  402. if spaceIter.state < 0: break
  403. if isCell(x):
  404. # cast to PCell is correct here:
  405. var c = cast[PCell](x)
  406. writeCell(file, "cell ", c)
  407. forAllChildren(c, waDebug)
  408. c_fprintf(file, "end\n")
  409. gch.pDumpHeapFile = nil
  410. proc GC_dumpHeap() =
  411. var f: File
  412. if open(f, "heap.txt", fmWrite):
  413. GC_dumpHeap(f)
  414. f.close()
  415. else:
  416. c_fprintf(stdout, "cannot write heap.txt")
  417. # ---------------- cycle collector -------------------------------------------
  418. proc freeCyclicCell(gch: var GcHeap, c: PCell) =
  419. gcAssert(isAllocatedPtr(gch.region, c), "freeCyclicCell: freed pointer?")
  420. prepareDealloc(c)
  421. gcTrace(c, csCycFreed)
  422. when logGC: writeCell("cycle collector dealloc cell", c)
  423. when reallyDealloc:
  424. sysAssert(allocInv(gch.region), "free cyclic cell")
  425. rawDealloc(gch.region, c)
  426. else:
  427. gcAssert(c.typ != nil, "freeCyclicCell")
  428. zeroMem(c, sizeof(Cell))
  429. proc sweep(gch: var GcHeap): bool =
  430. takeStartTime(100)
  431. #echo "loop start"
  432. let white = 1-gch.black
  433. #c_fprintf(stdout, "black is %d\n", black)
  434. while true:
  435. let x = allObjectsAsProc(gch.region, addr gch.spaceIter)
  436. if gch.spaceIter.state < 0: break
  437. takeTime()
  438. if isCell(x):
  439. # cast to PCell is correct here:
  440. var c = cast[PCell](x)
  441. gcAssert c.color != rcGrey, "cell is still grey?"
  442. if c.color == white: freeCyclicCell(gch, c)
  443. # Since this is incremental, we MUST not set the object to 'white' here.
  444. # We could set all the remaining objects to white after the 'sweep'
  445. # completed but instead we flip the meaning of black/white to save one
  446. # traversal over the heap!
  447. checkTime()
  448. # prepare for next iteration:
  449. #echo "loop end"
  450. gch.spaceIter = ObjectSpaceIter()
  451. result = true
  452. proc markRoot(gch: var GcHeap, c: PCell) {.inline.} =
  453. if c.color == 1-gch.black:
  454. c.setColor(rcGrey)
  455. add(gch.greyStack, c)
  456. proc markIncremental(gch: var GcHeap): bool =
  457. var L = addr(gch.greyStack.len)
  458. takeStartTime(100)
  459. while L[] > 0:
  460. var c = gch.greyStack.d[0]
  461. if not isAllocatedPtr(gch.region, c):
  462. c_fprintf(stdout, "[GC] not allocated anymore: %p\n", c)
  463. #GC_dumpHeap()
  464. sysAssert(false, "wtf")
  465. #sysAssert(isAllocatedPtr(gch.region, c), "markIncremental: isAllocatedPtr")
  466. gch.greyStack.d[0] = gch.greyStack.d[L[] - 1]
  467. dec(L[])
  468. takeTime()
  469. if c.color == rcGrey:
  470. c.setColor(gch.black)
  471. forAllChildren(c, waMarkGrey)
  472. elif c.color == (1-gch.black):
  473. gcAssert false, "wtf why are there white objects in the greystack?"
  474. checkTime()
  475. gcAssert gch.greyStack.len == 0, "markIncremental: greystack not empty "
  476. result = true
  477. proc markGlobals(gch: var GcHeap) =
  478. if gch.gcThreadId == 0:
  479. for i in 0 .. globalMarkersLen-1: globalMarkers[i]()
  480. for i in 0 .. threadLocalMarkersLen-1: threadLocalMarkers[i]()
  481. proc doOperation(p: pointer, op: WalkOp) =
  482. if p == nil: return
  483. var c: PCell = usrToCell(p)
  484. gcAssert(c != nil, "doOperation: 1")
  485. # the 'case' should be faster than function pointers because of easy
  486. # prediction:
  487. case op
  488. of waZctDecRef:
  489. #if not isAllocatedPtr(gch.region, c):
  490. # c_fprintf(stdout, "[GC] decref bug: %p", c)
  491. gcAssert(isAllocatedPtr(gch.region, c), "decRef: waZctDecRef")
  492. discard "use me for nimEscape?"
  493. of waMarkGlobal:
  494. template handleRoot =
  495. if gch.dumpHeapFile.isNil:
  496. markRoot(gch, c)
  497. else:
  498. dumpRoot(gch, c)
  499. handleRoot()
  500. discard allocInv(gch.region)
  501. of waMarkGrey:
  502. when false:
  503. if not isAllocatedPtr(gch.region, c):
  504. c_fprintf(stdout, "[GC] not allocated anymore: MarkGrey %p\n", c)
  505. #GC_dumpHeap()
  506. sysAssert(false, "wtf")
  507. if c.color == 1-gch.black:
  508. c.setColor(rcGrey)
  509. add(gch.greyStack, c)
  510. of waDebug: debugGraph(c)
  511. proc nimGCvisit(d: pointer, op: int) {.compilerRtl.} =
  512. doOperation(d, WalkOp(op))
  513. proc gcMark(gch: var GcHeap, p: pointer) {.inline.} =
  514. # the addresses are not as cells on the stack, so turn them to cells:
  515. sysAssert(allocInv(gch.region), "gcMark begin")
  516. var cell = usrToCell(p)
  517. var c = cast[ByteAddress](cell)
  518. if c >% PageSize:
  519. # fast check: does it look like a cell?
  520. var objStart = cast[PCell](interiorAllocatedPtr(gch.region, cell))
  521. if objStart != nil:
  522. # mark the cell:
  523. markRoot(gch, objStart)
  524. sysAssert(allocInv(gch.region), "gcMark end")
  525. proc markStackAndRegisters(gch: var GcHeap) {.noinline, cdecl.} =
  526. forEachStackSlot(gch, gcMark)
  527. proc collectALittle(gch: var GcHeap): bool =
  528. case gch.phase
  529. of Phase.None:
  530. if getOccupiedMem(gch.region) >= gch.cycleThreshold:
  531. gch.phase = Phase.Marking
  532. markGlobals(gch)
  533. result = collectALittle(gch)
  534. #when false: c_fprintf(stdout, "collectALittle: introduced bug E %ld\n", gch.phase)
  535. #discard allocInv(gch.region)
  536. of Phase.Marking:
  537. when hasThreadSupport:
  538. for c in gch.toDispose:
  539. nimGCunref(c)
  540. prepareForInteriorPointerChecking(gch.region)
  541. markStackAndRegisters(gch)
  542. inc(gch.stat.stackScans)
  543. if markIncremental(gch):
  544. gch.phase = Phase.Sweeping
  545. gch.red = 1 - gch.red
  546. of Phase.Sweeping:
  547. gcAssert gch.greyStack.len == 0, "greystack not empty"
  548. when hasThreadSupport:
  549. for c in gch.toDispose:
  550. nimGCunref(c)
  551. if sweep(gch):
  552. gch.phase = Phase.None
  553. # flip black/white meanings:
  554. gch.black = 1 - gch.black
  555. gcAssert gch.red == 1 - gch.black, "red color is wrong"
  556. inc(gch.stat.completedCollections)
  557. result = true
  558. proc collectCTBody(gch: var GcHeap) =
  559. when withRealTime:
  560. let t0 = getticks()
  561. sysAssert(allocInv(gch.region), "collectCT: begin")
  562. when not nimCoroutines:
  563. gch.stat.maxStackSize = max(gch.stat.maxStackSize, stackSize())
  564. #gch.stat.maxStackCells = max(gch.stat.maxStackCells, gch.decStack.len)
  565. if collectALittle(gch):
  566. gch.cycleThreshold = max(InitialCycleThreshold, getOccupiedMem() *
  567. CycleIncrease)
  568. gch.stat.maxThreshold = max(gch.stat.maxThreshold, gch.cycleThreshold)
  569. sysAssert(allocInv(gch.region), "collectCT: end")
  570. when withRealTime:
  571. let duration = getticks() - t0
  572. gch.stat.maxPause = max(gch.stat.maxPause, duration)
  573. when defined(reportMissedDeadlines):
  574. if gch.maxPause > 0 and duration > gch.maxPause:
  575. c_fprintf(stdout, "[GC] missed deadline: %ld\n", duration)
  576. when nimCoroutines:
  577. proc currentStackSizes(): int =
  578. for stack in items(gch.stack):
  579. result = result + stack.stackSize()
  580. proc collectCT(gch: var GcHeap) =
  581. # stackMarkCosts prevents some pathological behaviour: Stack marking
  582. # becomes more expensive with large stacks and large stacks mean that
  583. # cells with RC=0 are more likely to be kept alive by the stack.
  584. when nimCoroutines:
  585. let stackMarkCosts = max(currentStackSizes() div (16*sizeof(int)), ZctThreshold)
  586. else:
  587. let stackMarkCosts = max(stackSize() div (16*sizeof(int)), ZctThreshold)
  588. if (gch.greyStack.len >= stackMarkCosts or (cycleGC and
  589. getOccupiedMem(gch.region)>=gch.cycleThreshold) or alwaysGC) and
  590. gch.recGcLock == 0:
  591. collectCTBody(gch)
  592. when withRealTime:
  593. proc toNano(x: int): Nanos {.inline.} =
  594. result = x * 1000
  595. proc GC_setMaxPause*(MaxPauseInUs: int) =
  596. gch.maxPause = MaxPauseInUs.toNano
  597. proc GC_step(gch: var GcHeap, us: int, strongAdvice: bool) =
  598. gch.maxPause = us.toNano
  599. #if (getOccupiedMem(gch.region)>=gch.cycleThreshold) or
  600. # alwaysGC or strongAdvice:
  601. collectCTBody(gch)
  602. proc GC_step*(us: int, strongAdvice = false, stackSize = -1) {.noinline.} =
  603. if stackSize >= 0:
  604. var stackTop {.volatile.}: pointer
  605. gch.getActiveStack().pos = addr(stackTop)
  606. for stack in gch.stack.items():
  607. stack.bottomSaved = stack.bottom
  608. when stackIncreases:
  609. stack.bottom = cast[pointer](
  610. cast[ByteAddress](stack.pos) - sizeof(pointer) * 6 - stackSize)
  611. else:
  612. stack.bottom = cast[pointer](
  613. cast[ByteAddress](stack.pos) + sizeof(pointer) * 6 + stackSize)
  614. GC_step(gch, us, strongAdvice)
  615. if stackSize >= 0:
  616. for stack in gch.stack.items():
  617. stack.bottom = stack.bottomSaved
  618. when not defined(useNimRtl):
  619. proc GC_disable() =
  620. inc(gch.recGcLock)
  621. proc GC_enable() =
  622. if gch.recGcLock > 0:
  623. dec(gch.recGcLock)
  624. proc GC_setStrategy(strategy: GC_Strategy) =
  625. discard
  626. proc GC_enableMarkAndSweep() = discard
  627. proc GC_disableMarkAndSweep() = discard
  628. proc GC_fullCollect() =
  629. var oldThreshold = gch.cycleThreshold
  630. gch.cycleThreshold = 0 # forces cycle collection
  631. collectCT(gch)
  632. gch.cycleThreshold = oldThreshold
  633. proc GC_getStatistics(): string =
  634. GC_disable()
  635. result = "[GC] total memory: " & $(getTotalMem()) & "\n" &
  636. "[GC] occupied memory: " & $(getOccupiedMem()) & "\n" &
  637. "[GC] stack scans: " & $gch.stat.stackScans & "\n" &
  638. "[GC] stack cells: " & $gch.stat.maxStackCells & "\n" &
  639. "[GC] completed collections: " & $gch.stat.completedCollections & "\n" &
  640. "[GC] max threshold: " & $gch.stat.maxThreshold & "\n" &
  641. "[GC] grey stack capacity: " & $gch.greyStack.cap & "\n" &
  642. "[GC] max cycle table size: " & $gch.stat.cycleTableSize & "\n" &
  643. "[GC] max pause time [ms]: " & $(gch.stat.maxPause div 1000_000) & "\n"
  644. when nimCoroutines:
  645. result.add "[GC] number of stacks: " & $gch.stack.len & "\n"
  646. for stack in items(gch.stack):
  647. result.add "[GC] stack " & stack.bottom.repr & "[GC] max stack size " & $stack.maxStackSize & "\n"
  648. else:
  649. result.add "[GC] max stack size: " & $gch.stat.maxStackSize & "\n"
  650. GC_enable()
  651. {.pop.}