gc2.nim 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750
  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. # xxx deadcode, consider removing unless something could be reused.
  10. # Garbage Collector
  11. #
  12. # The basic algorithm is an incremental mark
  13. # and sweep GC to free cycles. It is hard realtime in that if you play
  14. # according to its rules, no deadline will ever be missed.
  15. # Since this kind of collector is very bad at recycling dead objects
  16. # early, Nim's codegen emits ``nimEscape`` calls at strategic
  17. # places. For this to work even 'unsureAsgnRef' needs to mark things
  18. # so that only return values need to be considered in ``nimEscape``.
  19. {.push profiler:off.}
  20. const
  21. CycleIncrease = 2 # is a multiplicative increase
  22. InitialCycleThreshold = 512*1024 # start collecting after 500KB
  23. ZctThreshold = 500 # we collect garbage if the ZCT's size
  24. # reaches this threshold
  25. # this seems to be a good value
  26. withRealTime = defined(useRealtimeGC)
  27. when withRealTime and not declared(getTicks):
  28. include "system/timers"
  29. when defined(memProfiler):
  30. proc nimProfile(requestedSize: int) {.benign.}
  31. when hasThreadSupport:
  32. include sharedlist
  33. type
  34. ObjectSpaceIter = object
  35. state: range[-1..0]
  36. iterToProc(allObjects, ptr ObjectSpaceIter, allObjectsAsProc)
  37. const
  38. escapedBit = 0b1000 # so that lowest 3 bits are not touched
  39. rcBlackOrig = 0b000
  40. rcWhiteOrig = 0b001
  41. rcGrey = 0b010 # traditional color for incremental mark&sweep
  42. rcUnused = 0b011
  43. colorMask = 0b011
  44. type
  45. WalkOp = enum
  46. waMarkGlobal, # part of the backup mark&sweep
  47. waMarkGrey,
  48. waZctDecRef,
  49. waDebug
  50. Phase {.pure.} = enum
  51. None, Marking, Sweeping
  52. Finalizer {.compilerproc.} = proc (self: pointer) {.nimcall, benign.}
  53. # A ref type can have a finalizer that is called before the object's
  54. # storage is freed.
  55. GcStat = object
  56. stackScans: int # number of performed stack scans (for statistics)
  57. completedCollections: int # number of performed full collections
  58. maxThreshold: int # max threshold that has been set
  59. maxStackSize: int # max stack size
  60. maxStackCells: int # max stack cells in ``decStack``
  61. cycleTableSize: int # max entries in cycle table
  62. maxPause: int64 # max measured GC pause in nanoseconds
  63. GcStack {.final, pure.} = object
  64. when nimCoroutines:
  65. prev: ptr GcStack
  66. next: ptr GcStack
  67. maxStackSize: int # Used to track statistics because we can not use
  68. # GcStat.maxStackSize when multiple stacks exist.
  69. bottom: pointer
  70. when withRealTime or nimCoroutines:
  71. pos: pointer # Used with `withRealTime` only for code clarity, see GC_Step().
  72. when withRealTime:
  73. bottomSaved: pointer
  74. GcHeap = object # this contains the zero count and
  75. # non-zero count table
  76. black, red: int # either 0 or 1.
  77. stack: GcStack
  78. when nimCoroutines:
  79. activeStack: ptr GcStack # current executing coroutine stack.
  80. phase: Phase
  81. cycleThreshold: int
  82. when useCellIds:
  83. idGenerator: int
  84. greyStack: CellSeq
  85. recGcLock: int # prevent recursion via finalizers; no thread lock
  86. when withRealTime:
  87. maxPause: Nanos # max allowed pause in nanoseconds; active if > 0
  88. region: MemRegion # garbage collected region
  89. stat: GcStat
  90. additionalRoots: CellSeq # explicit roots for GC_ref/unref
  91. spaceIter: ObjectSpaceIter
  92. pDumpHeapFile: pointer # File that is used for GC_dumpHeap
  93. when hasThreadSupport:
  94. toDispose: SharedList[pointer]
  95. gcThreadId: int
  96. var
  97. gch {.rtlThreadVar.}: GcHeap
  98. when not defined(useNimRtl):
  99. instantiateForRegion(gch.region)
  100. # Which color to use for new objects is tricky: When we're marking,
  101. # they have to be *white* so that everything is marked that is only
  102. # reachable from them. However, when we are sweeping, they have to
  103. # be black, so that we don't free them prematuredly. In order to save
  104. # a comparison gch.phase == Phase.Marking, we use the pseudo-color
  105. # 'red' for new objects.
  106. template allocColor(): untyped = gch.red
  107. template gcAssert(cond: bool, msg: string) =
  108. when defined(useGcAssert):
  109. if not cond:
  110. echo "[GCASSERT] ", msg
  111. GC_disable()
  112. writeStackTrace()
  113. rawQuit 1
  114. proc cellToUsr(cell: PCell): pointer {.inline.} =
  115. # convert object (=pointer to refcount) to pointer to userdata
  116. result = cast[pointer](cast[ByteAddress](cell)+%ByteAddress(sizeof(Cell)))
  117. proc usrToCell(usr: pointer): PCell {.inline.} =
  118. # convert pointer to userdata to object (=pointer to refcount)
  119. result = cast[PCell](cast[ByteAddress](usr)-%ByteAddress(sizeof(Cell)))
  120. proc extGetCellType(c: pointer): PNimType {.compilerproc.} =
  121. # used for code generation concerning debugging
  122. result = usrToCell(c).typ
  123. proc internRefcount(p: pointer): int {.exportc: "getRefcount".} =
  124. result = 0
  125. # this that has to equals zero, otherwise we have to round up UnitsPerPage:
  126. when BitsPerPage mod (sizeof(int)*8) != 0:
  127. {.error: "(BitsPerPage mod BitsPerUnit) should be zero!".}
  128. template color(c): untyped = c.refCount and colorMask
  129. template setColor(c, col) =
  130. c.refcount = c.refcount and not colorMask or col
  131. template markAsEscaped(c: PCell) =
  132. c.refcount = c.refcount or escapedBit
  133. template didEscape(c: PCell): bool =
  134. (c.refCount and escapedBit) != 0
  135. proc writeCell(file: File; msg: cstring, c: PCell) =
  136. var kind = -1
  137. if c.typ != nil: kind = ord(c.typ.kind)
  138. let col = if c.color == rcGrey: 'g'
  139. elif c.color == gch.black: 'b'
  140. else: 'w'
  141. when useCellIds:
  142. let id = c.id
  143. else:
  144. let id = c
  145. when defined(nimTypeNames):
  146. c_fprintf(file, "%s %p %d escaped=%ld color=%c of type %s\n",
  147. msg, id, kind, didEscape(c), col, c.typ.name)
  148. elif leakDetector:
  149. c_fprintf(file, "%s %p %d escaped=%ld color=%c from %s(%ld)\n",
  150. msg, id, kind, didEscape(c), col, c.filename, c.line)
  151. else:
  152. c_fprintf(file, "%s %p %d escaped=%ld color=%c\n",
  153. msg, id, kind, didEscape(c), col)
  154. proc writeCell(msg: cstring, c: PCell) =
  155. stdout.writeCell(msg, c)
  156. proc myastToStr[T](x: T): string {.magic: "AstToStr", noSideEffect.}
  157. template gcTrace(cell, state: untyped) =
  158. when traceGC: writeCell(myastToStr(state), cell)
  159. # forward declarations:
  160. proc collectCT(gch: var GcHeap) {.benign.}
  161. proc isOnStack(p: pointer): bool {.noinline, benign.}
  162. proc forAllChildren(cell: PCell, op: WalkOp) {.benign.}
  163. proc doOperation(p: pointer, op: WalkOp) {.benign.}
  164. proc forAllChildrenAux(dest: pointer, mt: PNimType, op: WalkOp) {.benign.}
  165. # we need the prototype here for debugging purposes
  166. proc nimGCref(p: pointer) {.compilerproc.} =
  167. let cell = usrToCell(p)
  168. markAsEscaped(cell)
  169. add(gch.additionalRoots, cell)
  170. proc nimGCunref(p: pointer) {.compilerproc.} =
  171. let cell = usrToCell(p)
  172. var L = gch.additionalRoots.len-1
  173. var i = L
  174. let d = gch.additionalRoots.d
  175. while i >= 0:
  176. if d[i] == cell:
  177. d[i] = d[L]
  178. dec gch.additionalRoots.len
  179. break
  180. dec(i)
  181. proc nimGCunrefNoCycle(p: pointer) {.compilerproc, inline.} =
  182. discard "can we do some freeing here?"
  183. proc nimGCunrefRC1(p: pointer) {.compilerproc, inline.} =
  184. discard "can we do some freeing here?"
  185. template markGrey(x: PCell) =
  186. if x.color != 1-gch.black and gch.phase == Phase.Marking:
  187. if not isAllocatedPtr(gch.region, x):
  188. c_fprintf(stdout, "[GC] markGrey proc: %p\n", x)
  189. #GC_dumpHeap()
  190. sysAssert(false, "wtf")
  191. x.setColor(rcGrey)
  192. add(gch.greyStack, x)
  193. proc asgnRef(dest: PPointer, src: pointer) {.compilerproc, inline.} =
  194. # the code generator calls this proc!
  195. gcAssert(not isOnStack(dest), "asgnRef")
  196. # BUGFIX: first incRef then decRef!
  197. if src != nil:
  198. let s = usrToCell(src)
  199. markAsEscaped(s)
  200. markGrey(s)
  201. dest[] = src
  202. proc asgnRefNoCycle(dest: PPointer, src: pointer) {.compilerproc, inline,
  203. deprecated: "old compiler compat".} = asgnRef(dest, src)
  204. proc unsureAsgnRef(dest: PPointer, src: pointer) {.compilerproc.} =
  205. # unsureAsgnRef marks 'src' as grey only if dest is not on the
  206. # stack. It is used by the code generator if it cannot decide whether a
  207. # reference is in the stack or not (this can happen for var parameters).
  208. if src != nil:
  209. let s = usrToCell(src)
  210. markAsEscaped(s)
  211. if not isOnStack(dest): markGrey(s)
  212. dest[] = src
  213. proc forAllSlotsAux(dest: pointer, n: ptr TNimNode, op: WalkOp) {.benign.} =
  214. var d = cast[ByteAddress](dest)
  215. case n.kind
  216. of nkSlot: forAllChildrenAux(cast[pointer](d +% n.offset), n.typ, op)
  217. of nkList:
  218. for i in 0..n.len-1:
  219. forAllSlotsAux(dest, n.sons[i], op)
  220. of nkCase:
  221. var m = selectBranch(dest, n)
  222. if m != nil: forAllSlotsAux(dest, m, op)
  223. of nkNone: sysAssert(false, "forAllSlotsAux")
  224. proc forAllChildrenAux(dest: pointer, mt: PNimType, op: WalkOp) =
  225. var d = cast[ByteAddress](dest)
  226. if dest == nil: return # nothing to do
  227. if ntfNoRefs notin mt.flags:
  228. case mt.kind
  229. of tyRef, tyString, tySequence: # leaf:
  230. doOperation(cast[PPointer](d)[], op)
  231. of tyObject, tyTuple:
  232. forAllSlotsAux(dest, mt.node, op)
  233. of tyArray, tyArrayConstr, tyOpenArray:
  234. for i in 0..(mt.size div mt.base.size)-1:
  235. forAllChildrenAux(cast[pointer](d +% i *% mt.base.size), mt.base, op)
  236. else: discard
  237. proc forAllChildren(cell: PCell, op: WalkOp) =
  238. gcAssert(cell != nil, "forAllChildren: 1")
  239. gcAssert(isAllocatedPtr(gch.region, cell), "forAllChildren: 2")
  240. gcAssert(cell.typ != nil, "forAllChildren: 3")
  241. gcAssert cell.typ.kind in {tyRef, tySequence, tyString}, "forAllChildren: 4"
  242. let marker = cell.typ.marker
  243. if marker != nil:
  244. marker(cellToUsr(cell), op.int)
  245. else:
  246. case cell.typ.kind
  247. of tyRef: # common case
  248. forAllChildrenAux(cellToUsr(cell), cell.typ.base, op)
  249. of tySequence:
  250. var d = cast[ByteAddress](cellToUsr(cell))
  251. var s = cast[PGenericSeq](d)
  252. if s != nil:
  253. for i in 0..s.len-1:
  254. forAllChildrenAux(cast[pointer](d +% align(GenericSeqSize, cell.typ.base.align) +% i *% cell.typ.base.size), 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(align(GenericSeqSize, typ.base.align), mulInt(len, typ.base.size))
  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, elemAlign = 1
  329. if ol.typ.kind != tyString:
  330. elemSize = ol.typ.base.size
  331. elemAlign = ol.typ.base.align
  332. incTypeSize ol.typ, newsize
  333. var oldsize = align(GenericSeqSize, elemAlign) + cast[PGenericSeq](old).len*elemSize
  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.}