gc2.nim 25 KB

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