BIOS.Objects.Mod 68 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862
  1. MODULE Objects; (** AUTHOR "pjm"; PURPOSE "Active object runtime support"; *)
  2. IMPORT SYSTEM, Trace, Machine, Heaps, Modules;
  3. CONST
  4. (** Process flags *)
  5. Restart* = 0; (* Restart/Destroy process on exception (hardcoded in compiler (OPC.CallRecBody / PCC.SysStart)) *)
  6. PleaseHalt* = 10; (* Process requested to Halt itself soon *)
  7. Unbreakable*= 11; (* FINALLY shall not catch HALT exception (PleaseHalt is also set) *)
  8. SelfTermination*=12; (* Indicates the process has requested to terminate ifself (PleaseHalt is also set) *)
  9. Preempted* = 27; (* Has been preempted. *)
  10. Resistant* = 28; (* Can only be destroyed by itself *)
  11. (** Process modes *)
  12. Unknown* = 0; Ready* = 1; Running* = 2; AwaitingLock* = 3;
  13. AwaitingCond* = 4; AwaitingEvent* = 5; Suspended* = 6; (* Suspened for compatibility with WinAos, not used for native A2 *)
  14. Terminated* = 7;
  15. (** Process priorities *)
  16. MinPriority = 0; (* only system idle processes run at this priority level *)
  17. Low* = 1; Normal* = 2; High* = 3; (* "user" priorities *)
  18. GCPriority* = 4; (* priority of garbage collector *)
  19. Realtime* = 5; (* reserved for interrupt handling and realtime apps, these processes are not allowed to allocate memory *)
  20. NumPriorities = Heaps.NumPriorities; (* number of priority levels *)
  21. (* Process termination halt codes *)
  22. halt* = 2222;
  23. haltUnbreakable* = 2223;
  24. MinIRQ = Machine.IRQ0;
  25. NumIRQ = Machine.MaxIRQ-MinIRQ+1;
  26. Stats* = FALSE; (* maintain statistical counters *)
  27. TraceVerbose = FALSE; (* write out verbose trace info *)
  28. StrongChecks = TRUE; (* strong sanity checks *)
  29. VeryConservative = FALSE; (* temp - be very conservative about stack-based pointers *)
  30. YieldTrick = FALSE; (* avoid yield when no ready process available *)
  31. HandlePriorityInv = TRUE; (* enables or disables priority inversion handling. Handling of priority inversion leads to a simplified locking, see Lock, Unlock and Await *)
  32. (* constant used in GC Process.FindPointers *)
  33. InitDiff = MAX(LONGINT);
  34. AddressSize = SIZEOF(ADDRESS);
  35. TYPE
  36. CpuCyclesArray* = ARRAY Machine.MaxCPU OF HUGEINT;
  37. EventHandler* = PROCEDURE {DELEGATE};
  38. Timer* = POINTER TO RECORD
  39. next, prev : Timer;
  40. trigger: LONGINT;
  41. handler: EventHandler
  42. END;
  43. ProtectedObject = POINTER TO RECORD END; (* protected object *)
  44. ProcessQueue = Heaps.ProcessQueue;
  45. Body = PROCEDURE (self: ProtectedObject);
  46. Condition = PROCEDURE (slink: ADDRESS): BOOLEAN;
  47. InterruptList = POINTER TO RECORD
  48. next: InterruptList;
  49. handler: EventHandler
  50. END;
  51. TYPE
  52. (** All exported fields and variables should be considered read-only. *)
  53. Process* = OBJECT (Heaps.ProcessLink)
  54. VAR
  55. rootedNext : Process; (** for rootedProcesses *)
  56. obj-: ProtectedObject; (** associated active object *)
  57. state-: Machine.State; (** processor state of suspended process *)
  58. sse: Machine.SSEState; (* fpu and sse state of preempted process (only valid if Preempted IN flag) *)
  59. sseAdr: ADDRESS;
  60. condition-: Condition; (** awaited process' condition *)
  61. condFP-: ADDRESS; (** awaited process' condition's context *)
  62. mode-: LONGINT; (** process state *) (* only changed inside Objects lock ??? *)
  63. procID-: LONGINT; (** processor ID where running *)
  64. waitingOn-: ProtectedObject; (** obj this process is waiting on (for lock or condition) *)
  65. id-: LONGINT; (** unique process ID for tracing *)
  66. flags*: SET; (** process flags *)
  67. priority-, staticPriority*: WORD; (** process dynamic priority (can change during priority inversion handling) and static priority *) (* exported for AosExceptions *)
  68. stack*: Machine.Stack; (** user-level stack of process *)
  69. restartPC-: ADDRESS; (** entry point of body, for SAFE exception recovery *)
  70. restartSP-: ADDRESS; (** stack level at start of body, for SAFE exception recovery *)
  71. exp*: Machine.ExceptionState;
  72. oldReturnPC: ADDRESS;
  73. cpuCycles, lastCpuCycles : CpuCyclesArray;
  74. prioRequests : ARRAY NumPriorities OF WORD; (* priorities of processes that wait for resources locked by this process, only the highest priority per resource is stored *)
  75. context: ANY;
  76. (* set priority of process: Machine.Objects lock is taken *)
  77. PROCEDURE SetPriority(p : WORD);
  78. BEGIN
  79. DEC(prioRequests[staticPriority]);
  80. staticPriority := p;
  81. INC(prioRequests[staticPriority]);
  82. priority := MaxPrio(prioRequests)
  83. END SetPriority;
  84. PROCEDURE FindRoots; (* override *)
  85. VAR pc, bp, curbp, sp: ADDRESS; d0, d1: SIZE; first : BOOLEAN;
  86. BEGIN
  87. IF traceProcess # NIL THEN traceProcess(SELF) END;
  88. (* stack garbage collection *)
  89. IF (priority >= Low) & (priority <= High) & (mode >= Ready) & (mode # Terminated) THEN
  90. (* only processes with priority < GCPriority are preempted during GC,
  91. only those are allowed to allocate memory and their stacks are inspected.
  92. Furthermore, the process must be in a valid state, e.g. terminated processes have a disposed stack. *)
  93. IF Heaps.GCType = Heaps.HeuristicStackInspectionGC THEN
  94. IF VeryConservative THEN
  95. Heaps.RegisterCandidates(stack.adr, stack.high-stack.adr)
  96. ELSE
  97. sp := state.SP; (* cf. Enter *)
  98. IF sp # 0 THEN
  99. IF Machine.ValidStack(stack, sp) THEN
  100. Heaps.RegisterCandidates(sp, stack.high - sp)
  101. END
  102. ELSE
  103. Trace.String("[Objects.FindRoots sp=0]")
  104. END
  105. END
  106. ELSIF Heaps.GCType = Heaps.MetaDataForStackGC THEN
  107. bp := state.BP; pc := state.PC; first := TRUE;
  108. IF pc # 0 THEN (* process is running already *)
  109. WHILE (bp # Heaps.NilVal) & (stack.adr <= bp) & (bp < stack.high) DO
  110. FindPointers(bp, pc, d0, d1);
  111. IF first THEN
  112. IF (d0 = 0) OR (d0 = 1) OR (d1 = 3) THEN
  113. (* situation where pc and bp are not synchronized: *)
  114. (* entry protocol of a procedure:
  115. PUSH EBP -- 1 byte instruction length, if pc points to this instruction at offset 0 from the codeoffset then bp still refers to caller frame -> critical
  116. MOV EBP, ESP -- 2 bytes instruction length, do. for offset 1 from the codeoffset
  117. (followed by initialization of local variables)
  118. exit protocol of a procedure:
  119. MOV ESP, EBP -- 2 bytes instruction length
  120. POP EBP -- 1 byte instruction length
  121. RET n -- 3 bytes instruction length, if pc points to this instruction at offset 3 from the last statement then bp already refers to caller's frame -> critical
  122. *)
  123. IF (d0 = 0) OR (d1 = 3) THEN
  124. SYSTEM.GET(state.SP, pc); (* matching pc is at position of stack pointer *)
  125. ELSE
  126. SYSTEM.GET(state.SP+AddressSize, pc); (* matching pc is at 4 bytes after stack pointer, pushed base pointer is at stack pointer position *)
  127. END;
  128. ELSE
  129. (* regular case: bp and pc were synchronized *)
  130. curbp := bp;
  131. SYSTEM.GET(curbp, bp);
  132. SYSTEM.GET(curbp+AddressSize, pc);
  133. END;
  134. first := FALSE;
  135. ELSE
  136. (* regular case: bp and pc were synchronized *)
  137. curbp := bp;
  138. SYSTEM.GET(curbp, bp);
  139. SYSTEM.GET(curbp+AddressSize, pc);
  140. END
  141. END
  142. END
  143. ELSE
  144. HALT(900) (* wrong GCType constant *)
  145. END
  146. END
  147. END FindRoots;
  148. PROCEDURE FindPointers(bp, pc : ADDRESS; VAR diff0, diff1: SIZE);
  149. (*VAR data: Modules.ProcTableEntry; startIndex, i: LONGINT; ptr : ADDRESS; success: BOOLEAN;
  150. BEGIN
  151. diff0 := InitDiff; diff1 := InitDiff;
  152. Modules.FindProc(pc, data, startIndex, success);
  153. IF success THEN
  154. diff0 := pc - data.pcFrom;
  155. diff1 := pc - data.pcStatementEnd;
  156. IF (data.noPtr > 0) & (pc >= data.pcStatementBegin) & (pc <= data.pcStatementEnd) THEN
  157. FOR i := 0 TO data.noPtr - 1 DO
  158. SYSTEM.GET(bp + Modules.ptrOffsets[startIndex + i], ptr);
  159. IF ptr # Heaps.NilVal THEN
  160. Heaps.Mark(SYSTEM.VAL(ANY, ptr))
  161. END
  162. END
  163. END
  164. END*)
  165. END FindPointers;
  166. END Process;
  167. TraceProcess* = PROCEDURE (p: Process);
  168. ExceptionHandler* = PROCEDURE(p: Process; VAR int: Machine.State; VAR exc: Machine.ExceptionState; VAR return: BOOLEAN);
  169. Idle = OBJECT
  170. BEGIN {ACTIVE, SAFE, PRIORITY(-1)} (* negative priority equivalent to MinPriority *)
  171. LOOP
  172. REPEAT
  173. IF ProcessorHLT # NIL THEN ProcessorHLT (* UP *)
  174. ELSE Machine.SpinHint (* MP *)
  175. END
  176. UNTIL maxReady >= lowestAllowedPriority;
  177. Yield
  178. END
  179. END Idle;
  180. Clock = OBJECT
  181. VAR h: Timer;
  182. BEGIN {ACTIVE, SAFE, PRIORITY(High)}
  183. LOOP
  184. Machine.Acquire(Machine.Objects);
  185. LOOP
  186. h := event.next;
  187. IF (h = event) OR (h.trigger - Machine.ticks > 0) THEN EXIT END;
  188. event.next := h.next; event.next.prev := event; (* unlink *)
  189. h.next := NIL; h.prev := NIL;
  190. Machine.Release(Machine.Objects);
  191. h.handler; (* assume handler will return promptly *)
  192. Machine.Acquire(Machine.Objects)
  193. END;
  194. ASSERT(timer = NIL); (* temp strong check *)
  195. timer := running[Machine.ID ()];
  196. timer.mode := AwaitingEvent;
  197. SwitchToNew
  198. END
  199. END Clock;
  200. ReadyProcesses = OBJECT(Heaps.RootObject)
  201. VAR q {UNTRACED}: ARRAY NumPriorities OF ProcessQueue;
  202. PROCEDURE &Init;
  203. VAR i: LONGINT;
  204. BEGIN
  205. FOR i := 0 TO NumPriorities - 1 DO
  206. q[i].head := NIL; q[i].tail := NIL
  207. END
  208. END Init;
  209. PROCEDURE FindRoots; (* override *)
  210. VAR i: LONGINT;
  211. BEGIN
  212. (* only mark queues of user processes since these will not change during GC *)
  213. FOR i := Low TO High DO
  214. Heaps.Mark(q[i].head);
  215. Heaps.Mark(q[i].tail)
  216. END
  217. END FindRoots;
  218. END ReadyProcesses;
  219. GCStatusExt = OBJECT(Heaps.GCStatus)
  220. VAR gcOngoing: BOOLEAN;
  221. PROCEDURE &Init;
  222. BEGIN
  223. gcOngoing := FALSE;
  224. END Init;
  225. (* called from Heaps.InvokeGC, i.e. this is a hidden upcall. However, it is necessary to take the Machine.Objects lock here since writing
  226. the set of variables here must not be interrupted, i.e. atomic writing of the set of variables is absolutely necessary. They system may hang
  227. if the lock is not taken. *)
  228. PROCEDURE SetgcOngoing(value: BOOLEAN);
  229. VAR p: Process;
  230. BEGIN
  231. IF value THEN
  232. Machine.Acquire(Machine.Objects);
  233. IF ~gcOngoing THEN
  234. gcOngoing := TRUE;
  235. lowestAllowedPriority := GCPriority;
  236. gcBarrier := Machine.allProcessors
  237. END;
  238. p := running[Machine.ID()];
  239. Enter(p);
  240. p.mode := Ready;
  241. SwitchToNew (* this method cannot schedule the running user process with priority Low, Normal or High since
  242. lowestAllowedPriority is set to GCPriority *)
  243. ELSE
  244. Machine.Acquire(Machine.Objects);
  245. gcOngoing := FALSE;
  246. lowestAllowedPriority := Low;
  247. Machine.Release(Machine.Objects)
  248. END;
  249. END SetgcOngoing;
  250. (* caller must hold Machine.Objects lock *)
  251. PROCEDURE GetgcOngoing(): BOOLEAN;
  252. BEGIN
  253. RETURN gcOngoing
  254. END GetgcOngoing;
  255. END GCStatusExt;
  256. GCActivity = OBJECT
  257. BEGIN {ACTIVE, SAFE, PRIORITY(GCPriority)}
  258. UpdateState;
  259. LOOP
  260. Machine.Acquire(Machine.Objects);
  261. ASSERT(gcProcess = NIL); (* temp strong check *)
  262. gcProcess := running[Machine.ID()];
  263. gcProcess.mode := AwaitingEvent;
  264. SwitchToNew; (* SwitchTo called by SwitchToNew will release the lock Machine.Objects *)
  265. (* process is scheduled -> gcProcess = NIL set by scheduler (Timeslice), perform garbage collection now *)
  266. Heaps.CollectGarbage(Modules.root);
  267. Machine.Acquire(Machine.Objects);
  268. IF finalizerProcess # NIL THEN
  269. (* it is safe to move finalizerProcess to the ready queue and set the variable to NIL
  270. since the process has been marked by the GC already - marking is finished here *)
  271. Enter(finalizerProcess);
  272. finalizerProcess := NIL
  273. END;
  274. Machine.Release(Machine.Objects);
  275. Heaps.gcStatus.SetgcOngoing(FALSE)
  276. END
  277. END GCActivity;
  278. FinalizerCaller = OBJECT (* separate active object that calls finalizers *)
  279. VAR n: Heaps.FinalizerNode;
  280. BEGIN {ACTIVE, SAFE, PRIORITY(High)}
  281. LOOP
  282. Machine.Acquire(Machine.Objects);
  283. ASSERT(finalizerProcess = NIL); (* temp strong check *)
  284. finalizerProcess := running[Machine.ID()];
  285. finalizerProcess.mode := AwaitingEvent;
  286. SwitchToNew; (* SwitchTo called by SwitchToNew will release the lock Machine.Objects *)
  287. (* process is scheduled -> finalizerProcess = NIL set by GCActivity, perform finalization now *)
  288. LOOP
  289. n := Heaps.GetFinalizer();
  290. IF n = NIL THEN EXIT END;
  291. IF n.collection # NIL THEN
  292. n.collection.RemoveAll(n.objStrong) (* remove it if it is not removed yet *)
  293. END;
  294. IF n.finalizer # NIL THEN
  295. n.finalizer(n.objStrong) (* may acquire locks *)
  296. END
  297. END;
  298. END
  299. END FinalizerCaller;
  300. Interrupter = OBJECT (ProtectedObject) (* to do: like Timer *)
  301. VAR interruptNumber: LONGINT;
  302. END Interrupter;
  303. VAR
  304. ready: ReadyProcesses; (* ready queue represented as an object that contains the queues *)
  305. maxReady: WORD; (* for all i : MinPriority <= maxReady < i < NumPriorities : Empty(ready.q[i]) *)
  306. lowestAllowedPriority: WORD; (* denotes the minimal user or realtime priority greater than the idle priority that can be
  307. scheduled depending on the GC status, minPriority = Low if GC is not running,
  308. minPrioriy = GCPriority otherwise *)
  309. running-{UNTRACED}: ARRAY Machine.MaxCPU OF Process; (** processes currently running, exported for Traps, not traced by the GC since it may change during collection *)
  310. nextProcessID: LONGINT;
  311. gcBarrier: SET; (* barrier that must be passed by all processors before actual collection starts *)
  312. gcActivity: GCActivity; (* active object for GC handling *)
  313. gcProcess: Process; (* suspended GC process, is NIL when collection has started, not equal NIL when no garbage collection is in process, same behaviour as for timer *)
  314. finalizerProcess: Process; (* finalizer process, regarded as part of GC *)
  315. interrupt: ARRAY NumIRQ OF RECORD
  316. root: InterruptList;
  317. process: Process
  318. END;
  319. processingIRQ: ARRAY NumIRQ OF BOOLEAN;
  320. rootedProcesses: ARRAY NumPriorities OF Process; (* list of potential processes that are not traced by GC when processing the ready queues, since GC only traces processes with
  321. priorities Low ... High in ready queues. The potentially not traced processes are rooted here and traced by the GC *)
  322. initObject: ProtectedObject; (* Active object for the init process *)
  323. event: Timer; (* list of events *)
  324. timer (*, realtimeTimer *): Process; (* suspended timer processes *)
  325. terminate: PROCEDURE;
  326. trap, trapReturn: ARRAY 2 OF PROCEDURE;
  327. ProcessorHLT*: PROCEDURE; (** installable procedure to halt the current processor while idle *)
  328. traceProcess*: TraceProcess; (** for debugging purposes (see Info.Active) *)
  329. entry: ADDRESS;
  330. init: Process;
  331. (* Performance monitoring *)
  332. idlecount*: ARRAY Machine.MaxCPU OF LONGINT; (** count of idle process timeslice interrupts *)
  333. idleCycles- : ARRAY Machine.MaxCPU OF HUGEINT; (** CPU cycles of idle threads *)
  334. perfTsc: ARRAY Machine.MaxCPU OF HUGEINT;
  335. (* Statistics *)
  336. Nlock-, Nunlock-, Nawait-, NawaitNoIF-, NawaitTrue-, Ncreate-, Nterminate-,
  337. Ncondition-, Ncondition1True-, Ncondition2-, Ncondition2True-,
  338. Ntimeslice-, NtimesliceTaken-, NtimesliceNothing-, NtimesliceIdle-,
  339. NtimesliceKernel-, NtimesliceV86-, NtimesliceCritical-,
  340. Npreempt-, NpreemptTaken-, NpreemptNothing-,
  341. NpreemptKernel-, NpreemptV86-, NpreemptCritical-,
  342. Nenter- : LONGINT;
  343. PROCEDURE GetMaxPrio(VAR queue: ProcessQueue; VAR new: Process);
  344. VAR
  345. t: Heaps.ProcessLink;
  346. maxPriority : WORD;
  347. BEGIN
  348. ASSERT(new = NIL);
  349. t := queue.head;
  350. maxPriority := MIN(WORD);
  351. WHILE (t # NIL) DO
  352. IF (t(Process).priority > maxPriority) THEN
  353. new := t(Process); maxPriority := t(Process).priority;
  354. END;
  355. t := t.next;
  356. END;
  357. IF new = NIL THEN (* zero elements in queue *)
  358. (* skip *)
  359. ELSE (* more than one element in queue *)
  360. IF new.next # NIL THEN new.next.prev := new.prev END;
  361. IF new.prev # NIL THEN new.prev.next := new.next END;
  362. IF queue.head = new THEN
  363. queue.head := new.next
  364. END;
  365. IF queue.tail = new THEN
  366. queue.tail := new.prev
  367. END;
  368. new.next := NIL; new.prev := NIL
  369. END;
  370. END GetMaxPrio;
  371. (* Get a process from a queue (NIL if none). Caller must hold lock for specific queue. *)
  372. PROCEDURE Get(VAR queue: ProcessQueue; VAR new: Process);
  373. VAR t: Heaps.ProcessLink;
  374. BEGIN
  375. t := queue.head;
  376. IF t = NIL THEN (* zero elements in queue *)
  377. (* skip *)
  378. ELSIF t = queue.tail THEN (* one element in queue *)
  379. queue.head := NIL; queue.tail := NIL (* {(t.next = NIL) & (t.prev = NIL)} *)
  380. ELSE (* more than one element in queue *)
  381. queue.head := t.next; t.next := NIL; queue.head.prev := NIL
  382. END;
  383. ASSERT((t = NIL) OR (t.next = NIL) & (t.prev = NIL)); (* temp strong check *)
  384. IF t = NIL THEN
  385. new := NIL
  386. ELSE
  387. ASSERT(t IS Process);
  388. new := t(Process)
  389. END;
  390. END Get;
  391. (* Put a process in a queue. Caller must hold lock for specific queue. *)
  392. (* If t was running, be careful to protect Put and the subsequent SwitchTo with the ready lock. *)
  393. PROCEDURE Put(VAR queue: ProcessQueue; t: Process);
  394. BEGIN (* {t # NIL & t.next = NIL} *)
  395. ASSERT((t.next = NIL) & (t.prev = NIL));
  396. IF queue.head = NIL THEN (* queue empty *)
  397. queue.head := t
  398. ELSE (* queue not empty *)
  399. queue.tail.next := t; t.prev := queue.tail
  400. END;
  401. queue.tail := t
  402. END Put;
  403. (* Select a process of at least the specified priority to run next on current processor (returns NIL if none). Caller must hold ready lock. *)
  404. PROCEDURE Select(VAR new: Process; priority: WORD);
  405. VAR thresholdPrio: WORD;
  406. BEGIN
  407. IF Heaps.gcStatus.GetgcOngoing() THEN
  408. thresholdPrio := GCPriority
  409. ELSE
  410. thresholdPrio := priority
  411. END;
  412. LOOP
  413. IF maxReady < thresholdPrio THEN
  414. IF priority < thresholdPrio THEN Get(ready.q[MinPriority], new) ELSE new := NIL END;
  415. EXIT
  416. END;
  417. Get(ready.q[maxReady], new);
  418. IF (new # NIL) OR (maxReady = MinPriority) THEN EXIT END;
  419. DEC(maxReady)
  420. END
  421. END Select;
  422. (* Enter a process in the ready queue. Caller must hold ready lock. *)
  423. (* If t was running, be careful to make Enter and the subsequent SwitchTo atomic, as the process could be grabbed by another process while it is still running. *)
  424. PROCEDURE Enter(t: Process);
  425. BEGIN
  426. IF Stats THEN Machine.AtomicInc(Nenter) END;
  427. t.mode := Ready;
  428. Put(ready.q[t.priority], t);
  429. IF t.priority > maxReady THEN
  430. maxReady := t.priority (* to do: re-establish global priority invariant *)
  431. END
  432. END Enter;
  433. (* Remove a process from a queue that contains it. Caller must hold lock for specific queue. *)
  434. (* Not intended for frequent use. *)
  435. PROCEDURE Remove(VAR queue: ProcessQueue; t: Process);
  436. BEGIN
  437. IF t.prev # NIL THEN t.prev.next := t.next END;
  438. IF t.next # NIL THEN t.next.prev := t.prev END;
  439. IF t = queue.head THEN queue.head := t.next END;
  440. IF t = queue.tail THEN queue.tail := t.prev END;
  441. ASSERT((queue.head = NIL) OR (queue.head.prev = NIL) & (queue.tail.next = NIL));
  442. t.prev := NIL;
  443. t.next := NIL
  444. END Remove;
  445. (* Switch to the specified process. Caller must hold ready lock. Return may be on different processor! *)
  446. PROCEDURE SwitchTo(VAR running: Process; new: Process); (* parameters used in SwitchToState, TerminateThis, New *)
  447. VAR id: LONGINT;
  448. BEGIN
  449. ASSERT(Machine.CS () MOD 4 = Machine.UserLevel); (* registers hold user state *)
  450. id := Machine.ID ();
  451. INC (running.cpuCycles[id], Machine.GetTimer () - perfTsc[id]);
  452. IF running.priority = MinPriority THEN (* Special treatment for idle threads *)
  453. INC (idleCycles[id], Machine.GetTimer () - perfTsc[id]);
  454. END;
  455. (* save current state *)
  456. running.state.PC := Machine.CurrentPC (); (* for GC *) (* ug *)
  457. running.state.SP := SYSTEM.GetStackPointer (); (* for GC *)
  458. running.state.BP := SYSTEM.GetFramePointer (); (* save state *)
  459. IF Machine.SSESupport THEN Machine.SSESaveMin(running.sseAdr)
  460. ELSE Machine.FPUSaveMin(running.sse)
  461. END;
  462. running := new; new.mode := Running;
  463. IF Preempted IN new.flags THEN
  464. ASSERT(new.state.CS MOD 4 = Machine.UserLevel); (* switching to user mode *)
  465. EXCL(new.flags, Preempted);
  466. perfTsc[id] := Machine.GetTimer ();
  467. SYSTEM.SetStackPointer (new.state.SP); (* for UpdateState - run on new stack (EBP on old) *)
  468. Machine.PushState(new.state);
  469. IF Machine.SSESupport THEN Machine.SSERestoreFull(new.sseAdr)
  470. ELSE Machine.FPURestoreFull(new.sse)
  471. END;
  472. Machine.Release(Machine.Objects);
  473. Machine.JumpState (* pops the state parameter from the stack and returns from interrupt *)
  474. ELSE
  475. IF Machine.SSESupport THEN Machine.SSERestoreMin(new.sseAdr)
  476. ELSE Machine.FPURestoreMin(new.sse)
  477. END;
  478. perfTsc[id] := Machine.GetTimer ();
  479. SYSTEM.SetStackPointer (new.state.SP); (* run on new stack *)
  480. SYSTEM.SetFramePointer (new.state.BP);
  481. Machine.Release(Machine.Objects);
  482. END;
  483. (*
  484. MOV ESP, EBP ; exit code generated by compiler
  485. POP EBP
  486. RET 8
  487. *)
  488. END SwitchTo;
  489. (* Select a new process to run and switch to it. Caller must hold ready lock. *)
  490. PROCEDURE SwitchToNew;
  491. VAR new: Process;
  492. BEGIN
  493. Select(new, MinPriority); (* will return at least an Idle process *)
  494. new.procID := Machine.ID ();
  495. SwitchTo(running[new.procID], new)
  496. END SwitchToNew;
  497. (** Relinquish control. *)
  498. PROCEDURE Yield*;
  499. VAR r, new: Process;
  500. BEGIN
  501. IF ~YieldTrick OR (maxReady >= lowestAllowedPriority) THEN
  502. r := SYSTEM.VAL (Process, Machine.GetProcessPtr ());
  503. Machine.Acquire(Machine.Objects);
  504. Select(new, r.priority);
  505. IF new # NIL THEN (* found another process *)
  506. Enter(r);
  507. new.procID := Machine.ID ();
  508. SwitchTo(running[new.procID], new)
  509. ELSE (* stay with same process *)
  510. Machine.Release(Machine.Objects)
  511. END
  512. END
  513. END Yield;
  514. PROCEDURE SwitchToState(new: Process; VAR state: Machine.State);
  515. BEGIN
  516. (* simulate return from SwitchTo - MOV ESP, EBP; POP EBP; RET 8 *)
  517. state.SP := new.state.BP+AddressSize*2; (* AddressSize*2 is effect of POP, RET *)
  518. SYSTEM.GET (new.state.BP, state.BP); (* effect of POP *)
  519. SYSTEM.GET (new.state.BP + AddressSize, state.PC); (* effect of RET *)
  520. END SwitchToState;
  521. (** Preempt the current process. *)
  522. PROCEDURE Timeslice*(VAR state: Machine.State);
  523. VAR id: LONGINT; new: Process;
  524. BEGIN
  525. (* handle a timer tick *)
  526. Machine.Acquire(Machine.Objects);
  527. IF Stats THEN Machine.AtomicInc(Ntimeslice) END;
  528. id := Machine.ID ();
  529. IF id = 0 THEN (* process 0 checks event queues *)
  530. IF event.next.trigger - Machine.ticks <= 0 THEN (* next normal event due *)
  531. IF event.next # event THEN (* not dummy event *)
  532. IF timer # NIL THEN
  533. ASSERT(timer.mode = AwaitingEvent);
  534. Enter(timer); timer := NIL
  535. END
  536. ELSE (* reset dummy event *)
  537. event.trigger := Machine.ticks + MAX(LONGINT) DIV 2 (* ignore overflow *)
  538. END
  539. END
  540. END;
  541. IF Heaps.gcStatus.GetgcOngoing() & (id IN gcBarrier) THEN
  542. EXCL(gcBarrier, id);
  543. IF gcBarrier = {} THEN
  544. ASSERT(gcProcess.mode = AwaitingEvent);
  545. Enter(gcProcess); gcProcess := NIL
  546. END
  547. END;
  548. (* pre-empt the current process *)
  549. IF Machine.PreemptCount(id) = 1 THEN (* check against 1, because we are holding one lock *)
  550. IF ~(Machine.VMBit IN state.FLAGS) THEN (* not V86 mode *)
  551. IF state.CS MOD 4 = Machine.UserLevel THEN (* not kernel mode (used during initialization or interrupts) *)
  552. IF running[id].priority # MinPriority THEN (* idle processes are not timesliced *)
  553. Select(new, running[id].priority);
  554. IF new # NIL THEN
  555. ASSERT(Machine.CS () MOD 4 = Machine.KernelLevel); (* otherwise we can not change state.SP *)
  556. INC (running[id].cpuCycles[id], Machine.GetTimer () - perfTsc[id]);
  557. IF Stats THEN Machine.AtomicInc(NtimesliceTaken) END;
  558. INCL(running[id].flags, Preempted);
  559. Machine.CopyState(state, running[id].state);
  560. IF Machine.SSESupport THEN Machine.SSESaveFull(running[id].sseAdr)
  561. ELSE Machine.FPUSaveFull(running[id].sse); (* to do: floating-point exception possible / Machine.SetupFPU *)
  562. END;
  563. Enter(running[id]);
  564. running[id] := new;
  565. new.mode := Running; new.procID := id;
  566. IF Preempted IN new.flags THEN
  567. EXCL(new.flags, Preempted);
  568. Machine.CopyState(new.state, state);
  569. IF Machine.SSESupport THEN Machine.SSERestoreFull(new.sseAdr)
  570. ELSE Machine.FPURestoreFull(new.sse)
  571. END
  572. ELSE
  573. SwitchToState(new, state);
  574. IF Machine.SSESupport THEN Machine.SSERestoreMin(new.sseAdr)
  575. ELSE Machine.FPURestoreMin(new.sse)
  576. END
  577. END;
  578. perfTsc[id] := Machine.GetTimer ()
  579. ELSE
  580. IF Stats THEN Machine.AtomicInc(NtimesliceNothing) END;
  581. END;
  582. (* Check if the process has the PleasHalt flag and handle it. *)
  583. IF PleaseHalt IN running[id].flags THEN
  584. (* Simulate procedure call: Increase stack & put return PC *)
  585. DEC(state.SP, AddressSize);
  586. SYSTEM.PUT (state.SP, state.PC); (* Here an stack overflow could happen! *)
  587. (* Set the right halt procedure *)
  588. IF (Unbreakable IN running[id].flags) THEN
  589. state.PC := SYSTEM.VAL (ADDRESS, trap[1]);
  590. ELSE
  591. state.PC := SYSTEM.VAL (ADDRESS, trap[0]);
  592. END;
  593. END;
  594. ELSE
  595. INC(idlecount[id]);
  596. IF Stats THEN Machine.AtomicInc(NtimesliceIdle) END;
  597. END
  598. ELSE
  599. (* can not interrupt kernel mode, because SwitchTo would not switch back to it *)
  600. IF Stats THEN Machine.AtomicInc(NtimesliceKernel) END (* kernel mode, e.g. during page fault or FieldIRQ *)
  601. END
  602. ELSE
  603. IF Stats THEN Machine.AtomicInc(NtimesliceV86) END (* V86 mode *)
  604. END
  605. ELSE
  606. IF Stats THEN Machine.AtomicInc(NtimesliceCritical) END (* not preemptable *)
  607. END;
  608. Machine.Release(Machine.Objects)
  609. END Timeslice;
  610. (** Return current process. (DEPRECATED, use ActiveObject) *)
  611. PROCEDURE CurrentProcess*( ): Process;
  612. BEGIN
  613. RETURN SYSTEM.VAL(Process, Machine.GetProcessPtr());
  614. END CurrentProcess;
  615. PROCEDURE CurrentContext*(): ANY;
  616. VAR p: Process;
  617. BEGIN
  618. p := CurrentProcess();
  619. IF p # NIL THEN RETURN p.context
  620. ELSE RETURN NIL
  621. END;
  622. END CurrentContext;
  623. PROCEDURE SetContext*(context: ANY);
  624. VAR p: Process;
  625. BEGIN
  626. p := CurrentProcess();
  627. IF p # NIL THEN p.context := context END;
  628. END SetContext;
  629. (* Return stack bottom of process. For compatibility WinAos/UnixAos/NativeAos *)
  630. PROCEDURE GetStackBottom*(p: Process): ADDRESS;
  631. BEGIN
  632. RETURN p.stack.high
  633. END GetStackBottom;
  634. (** Return the active object currently executing. *)
  635. PROCEDURE ActiveObject* (): ANY;
  636. VAR r: Process;
  637. BEGIN
  638. r := SYSTEM.VAL(Process, Machine.GetProcessPtr ());
  639. RETURN r.obj
  640. END ActiveObject;
  641. (** Return the ID of the active currently executing process. *)
  642. PROCEDURE GetProcessID* (): LONGINT;
  643. VAR r: Process;
  644. BEGIN
  645. r := SYSTEM.VAL (Process, Machine.GetProcessPtr ());
  646. RETURN r.id
  647. END GetProcessID;
  648. (** Set the current process' priority. *)
  649. PROCEDURE SetPriority*(priority: WORD);
  650. VAR id: LONGINT;
  651. BEGIN
  652. ASSERT((priority >= Low) & (priority <= Realtime)); (* priority in bounds *)
  653. IF HandlePriorityInv THEN
  654. Machine.Acquire(Machine.Objects);
  655. id := Machine.ID();
  656. running[id].SetPriority(priority);
  657. Machine.Release(Machine.Objects)
  658. ELSE
  659. id := Machine.AcquirePreemption ();
  660. running[id].priority := priority;
  661. Machine.ReleasePreemption
  662. (* to do: re-establish global priority invariant *)
  663. END
  664. END SetPriority;
  665. (** Return TRUE iff the specified protected object is locked exclusive to the current process. *)
  666. PROCEDURE LockedByCurrent*(obj: ANY): BOOLEAN;
  667. VAR hdr {UNTRACED}: Heaps.ProtRecBlock; id: LONGINT; res: BOOLEAN;
  668. BEGIN
  669. SYSTEM.GET(SYSTEM.VAL(ADDRESS, obj) + Heaps.HeapBlockOffset, hdr);
  670. ASSERT(hdr IS Heaps.ProtRecBlock);
  671. IF HandlePriorityInv THEN
  672. Machine.Acquire(Machine.Objects);
  673. id := Machine.ID();
  674. res := (hdr.lockedBy = running[id]);
  675. Machine.Release(Machine.Objects)
  676. ELSE
  677. id := Machine.AcquirePreemption ();
  678. Machine.AcquireObject(hdr.locked);
  679. res := (hdr.lockedBy = running[id]);
  680. Machine.ReleaseObject(hdr.locked);
  681. Machine.ReleasePreemption;
  682. END;
  683. RETURN res
  684. END LockedByCurrent;
  685. (** Return number of ready and running processes, excluding idle processes. *)
  686. PROCEDURE NumReady* (): LONGINT;
  687. VAR i, n: LONGINT; p: Heaps.ProcessLink;
  688. BEGIN
  689. n := 0;
  690. Machine.Acquire(Machine.Objects);
  691. FOR i := MinPriority+1 TO NumPriorities-1 DO
  692. p := ready.q[i].head; WHILE p # NIL DO INC(n); p := p.next END
  693. END;
  694. FOR i := 0 TO Machine.MaxCPU-1 DO
  695. IF (running[i] # NIL) & (running[i].priority > MinPriority) THEN INC(n) END
  696. END;
  697. Machine.Release(Machine.Objects);
  698. RETURN n
  699. END NumReady;
  700. (** Return number of CPU cycles consumed by the specified process for each processor. If all is TRUE,
  701. return the number of cycles since the process has been created. If FALSE, return the number of cycles
  702. consumed since the last time asked. *)
  703. PROCEDURE GetCpuCycles*(process : Process; VAR cpuCycles : CpuCyclesArray; all : BOOLEAN);
  704. VAR i : LONGINT;
  705. BEGIN
  706. ASSERT(process # NIL);
  707. FOR i := 0 TO Machine.MaxCPU-1 DO cpuCycles[i] := process.cpuCycles[i]; END;
  708. IF ~all THEN
  709. FOR i := 0 TO Machine.MaxCPU-1 DO
  710. cpuCycles[i] := cpuCycles[i] - process.lastCpuCycles[i];
  711. process.lastCpuCycles[i] := process.cpuCycles[i]; (* actually could have changed meanwhile *)
  712. END;
  713. END;
  714. END GetCpuCycles;
  715. PROCEDURE CurrentProcessTime*(): HUGEINT;
  716. VAR result: HUGEINT; process: Process; i: LONGINT;
  717. BEGIN
  718. process := CurrentProcess();
  719. FOR i := 0 TO Machine.MaxCPU-1 DO result := result + process.cpuCycles[i]; END;
  720. RETURN result;
  721. END CurrentProcessTime;
  722. PROCEDURE TimerFrequency*(): HUGEINT;
  723. BEGIN
  724. RETURN 1000000000;
  725. END TimerFrequency;
  726. (* Handle hardware interrupt and route it to an interrupt handler process. *)
  727. PROCEDURE FieldIRQ(VAR state: Machine.State);
  728. VAR t: Process; id: LONGINT; new: Process; preempt: BOOLEAN;
  729. BEGIN
  730. Machine.DisableIRQ(state.INT); (* do this before acknowledging irq *)
  731. IF StrongChecks THEN
  732. IF processingIRQ[state.INT-MinIRQ] THEN
  733. Trace.String("IRQ recursion "); Trace.Int(state.INT,1); Trace.Ln;
  734. RETURN
  735. ELSE
  736. processingIRQ[state.INT-MinIRQ] := TRUE;
  737. END;
  738. END;
  739. (* if the reenabling of interrupts cannot be circumvented, then it is REQUIRED to acknowledge interrupts
  740. BEFORE reenabling. Otherwise spurious IRQs cannot be identified as such.
  741. Please note that this particular problem with spurious IRQs cannot observed on many machines but IF it is observed
  742. then the machine will behave unexpected. Very hard to debug and trace!
  743. Machine.Ack(state.INT);
  744. Machine.Sti (); (* avoid Processors.StopAll deadlock when waiting for locks below (remove this) *)
  745. *)
  746. Machine.Acquire(Machine.Objects);
  747. t := interrupt[state.INT-MinIRQ].process;
  748. IF StrongChecks THEN ASSERT(t.mode = AwaitingEvent) END;
  749. id := Machine.ID ();
  750. preempt := (t.priority > maxReady) & (maxReady # MinPriority) & (t.priority > running[id].priority);
  751. Enter(t);
  752. IF preempt THEN
  753. IF Stats THEN Machine.AtomicInc(Npreempt) END;
  754. (* pre-empt the current process *)
  755. IF Machine.PreemptCount(id) = 1 THEN (* check against 1, because we are holding one lock *)
  756. IF ~(Machine.VMBit IN state.FLAGS) THEN (* not V86 mode *)
  757. IF state.CS MOD 4 = Machine.UserLevel THEN (* not kernel mode (used during initialization or interrupts) *)
  758. Select(new, running[id].priority + 1);
  759. IF new # NIL THEN
  760. ASSERT(Machine.CS () MOD 4 = Machine.KernelLevel); (* otherwise we can not change state.SP *)
  761. INC (running[id].cpuCycles[id], Machine.GetTimer () - perfTsc[id]);
  762. IF running[id].priority = MinPriority THEN (* Special treatment for idle threads *)
  763. INC (idleCycles[id], Machine.GetTimer () - perfTsc[id]);
  764. END;
  765. IF Stats THEN Machine.AtomicInc(NpreemptTaken) END;
  766. INCL(running[id].flags, Preempted);
  767. Machine.CopyState(state, running[id].state);
  768. IF Machine.SSESupport THEN Machine.SSESaveFull(running[id].sseAdr)
  769. ELSE Machine.FPUSaveFull(running[id].sse); (* to do: floating-point exception possible / Machine.SetupFPU *)
  770. END;
  771. Enter(running[id]);
  772. running[id] := new;
  773. new.mode := Running; new.procID := id;
  774. IF Preempted IN new.flags THEN
  775. EXCL(new.flags, Preempted);
  776. Machine.CopyState(new.state, state);
  777. IF Machine.SSESupport THEN Machine.SSERestoreFull(new.sseAdr)
  778. ELSE Machine.FPURestoreFull(new.sse)
  779. END
  780. ELSE
  781. SwitchToState(new, state);
  782. IF Machine.SSESupport THEN Machine.SSERestoreMin(new.sseAdr)
  783. ELSE Machine.FPURestoreMin(new.sse)
  784. END
  785. END;
  786. perfTsc[id] := Machine.GetTimer ()
  787. ELSE
  788. IF Stats THEN Machine.AtomicInc(NpreemptNothing) END
  789. END
  790. ELSE
  791. (* can not interrupt kernel mode, because SwitchTo would not switch back to it *)
  792. IF Stats THEN Machine.AtomicInc(NpreemptKernel) END (* kernel mode, e.g. during page fault or FieldIRQ *)
  793. END
  794. ELSE
  795. IF Stats THEN Machine.AtomicInc(NpreemptV86) END (* V86 mode *)
  796. END
  797. ELSE
  798. IF Stats THEN Machine.AtomicInc(NpreemptCritical) END (* not preemptable *)
  799. END
  800. END;
  801. Machine.Release(Machine.Objects)
  802. END FieldIRQ;
  803. (* Process scheduled to handle an interrupt. *)
  804. PROCEDURE InterruptProcess(self: ProtectedObject);
  805. VAR h: InterruptList; t: Process; int: LONGINT;
  806. BEGIN
  807. int := self(Interrupter).interruptNumber;
  808. t := interrupt[int-MinIRQ].process;
  809. LOOP
  810. h := interrupt[int-MinIRQ].root; (* concurrent updates allowed in InstallHandler and RemoveHandler *)
  811. WHILE h # NIL DO h.handler (); h := h.next END;
  812. Machine.Acquire(Machine.Objects);
  813. ASSERT(running[Machine.ID ()] = t); (* strong check *)
  814. t.mode := AwaitingEvent;
  815. processingIRQ[int-MinIRQ] := FALSE;
  816. Machine.EnableIRQ(int);
  817. SwitchToNew
  818. END
  819. END InterruptProcess;
  820. (** Install interrupt handler. *)
  821. PROCEDURE InstallHandler*(h: EventHandler; int: LONGINT);
  822. VAR t: Process; new: BOOLEAN; ih: Interrupter; n: InterruptList; i: LONGINT;
  823. BEGIN
  824. ASSERT((int >= MinIRQ) & (int-MinIRQ < NumIRQ)); (* range check *)
  825. IF interrupt[int-MinIRQ].process = NIL THEN (* first handler for this irq *)
  826. (* allocate process outside lock region, to avoid GC lock problems. *)
  827. (* hack: use type parameter to pass int index & set obj to h, for System.ShowProcesses *)
  828. NEW(ih); ih.interruptNumber := int;
  829. NewProcess(InterruptProcess, {Resistant}, ih, t);
  830. t.priority := High; (* second-level interrupt handling processes have high priority, handlers may allocate memory, use exclusive locks and awaits *)
  831. t.staticPriority := t.priority;
  832. FOR i := 0 TO LEN(t.prioRequests) - 1 DO t.prioRequests[i] := 0 END;
  833. INC(t.prioRequests[t.priority])
  834. END;
  835. NEW(n); n.handler := h;
  836. Machine.Acquire(Machine.Objects);
  837. IF interrupt[int-MinIRQ].process = NIL THEN (* still first handler for this irq *)
  838. t.id := nextProcessID; INC(nextProcessID);
  839. t.mode := AwaitingEvent;
  840. interrupt[int-MinIRQ].process := t;
  841. new := TRUE
  842. ELSE
  843. new := FALSE
  844. END;
  845. n.next := interrupt[int-MinIRQ].root; (* can be concurrent with loop in InterruptProcess *)
  846. interrupt[int-MinIRQ].root := n;
  847. Machine.Release(Machine.Objects);
  848. IF new THEN Machine.InstallHandler(FieldIRQ, int) END (* do outside lock region to avoid NEW/GC deadlock *)
  849. END InstallHandler;
  850. (** Remove interrupt handler. *)
  851. PROCEDURE RemoveHandler*(h: EventHandler; int: LONGINT);
  852. VAR p, c: InterruptList;
  853. BEGIN
  854. ASSERT((int >= MinIRQ) & (int-MinIRQ < NumIRQ)); (* range check *)
  855. Machine.Acquire(Machine.Objects);
  856. p := NIL; c := interrupt[int-MinIRQ].root;
  857. WHILE (c.handler # h) & (c # NIL) DO p := c; c := c.next END;
  858. IF c.handler = h THEN (* handler found *)
  859. IF p = NIL THEN
  860. interrupt[int-MinIRQ].root := c.next;
  861. (*
  862. IF c.inext = NIL THEN (* this was the last handler *)
  863. Machine.RemoveHandler(FieldIRQ, int)
  864. (* to do: synchronize with FieldIRQ and InterruptProcess *)
  865. END
  866. *)
  867. ELSE
  868. p.next := c.next
  869. END
  870. ELSE
  871. HALT(99); (* handler not found *)
  872. END;
  873. (* can not clear c.next field, because InterruptProcess may be traversing it. *)
  874. Machine.Release(Machine.Objects)
  875. END RemoveHandler;
  876. (* local procedure *)
  877. PROCEDURE SetTimeoutAbsOrRel(t: Timer; h: EventHandler; ms: LONGINT; isAbsolute: BOOLEAN);
  878. VAR e: Timer; trigger: LONGINT;
  879. BEGIN
  880. ASSERT(Machine.Second= 1000); (* assume milliseconds for now *)
  881. ASSERT((t # NIL) & (h # NIL));
  882. IF ms < 1 THEN ms := 1 END;
  883. Machine.Acquire(Machine.Objects);
  884. IF isAbsolute THEN trigger := ms ELSE trigger := Machine.ticks + ms (* ignore overflow *) END;
  885. IF t.next # NIL THEN (* cancel previous timeout *)
  886. t.next.prev := t.prev; t.prev.next := t.next
  887. END;
  888. t.trigger := trigger; t.handler := h;
  889. e := event.next; (* performance: linear search! *)
  890. WHILE (e # event) & (e.trigger - trigger <= 0) DO e := e.next END;
  891. t.prev := e.prev; e.prev := t; t.next := e; t.prev.next := t;
  892. Machine.Release(Machine.Objects)
  893. END SetTimeoutAbsOrRel;
  894. (** Set (or reset) an event handler object's timeout value. *)
  895. PROCEDURE SetTimeout*(t: Timer; h: EventHandler; ms: LONGINT);
  896. BEGIN
  897. SetTimeoutAbsOrRel(t, h, ms, FALSE)
  898. END SetTimeout;
  899. (** Set (or reset) an event handler object's timeout value. Here ms is absolute *)
  900. PROCEDURE SetTimeoutAt*(t: Timer; h: EventHandler; ms: LONGINT);
  901. BEGIN
  902. SetTimeoutAbsOrRel(t, h, ms, TRUE)
  903. END SetTimeoutAt;
  904. (** Cancel an event handler object's timeout, if any. It is possible that the timer has expired, but not yet been scheduled to run. *)
  905. PROCEDURE CancelTimeout*(t: Timer);
  906. BEGIN
  907. Machine.Acquire(Machine.Objects);
  908. ASSERT(t # event);
  909. IF t.next # NIL THEN
  910. t.next.prev := t.prev;
  911. IF t.prev #NIL THEN t.prev.next := t.next END;
  912. END;
  913. t.next := NIL; t.prev := NIL;
  914. Machine.Release(Machine.Objects)
  915. END CancelTimeout;
  916. (** Terminate the current process and switch to next process. *)
  917. PROCEDURE Terminate*; (* exported for Linker *)
  918. VAR id: LONGINT;
  919. BEGIN
  920. IF Stats THEN Machine.AtomicInc(Nterminate) END;
  921. Machine.Acquire(Machine.Objects);
  922. id := Machine.ID ();
  923. (*running[id].state.PC := CallerPC ();*) (* for tracing *)
  924. running[id].mode := Terminated; (* a process can also be "terminated" if the queue containing it is garbage collected *)
  925. SwitchToNew;
  926. HALT(2201) (* process resurrected *)
  927. END Terminate;
  928. PROCEDURE Halt;
  929. BEGIN
  930. HALT(halt); (* process halted *)
  931. END Halt;
  932. PROCEDURE HaltUnbreakable;
  933. BEGIN
  934. HALT(haltUnbreakable); (* process halted *)
  935. END HaltUnbreakable;
  936. (* Set the return PC which is saved in the process and set it to -1 *)
  937. PROCEDURE HaltAltPC(haltCode: WORD);
  938. VAR bp: ADDRESS; p: Process;
  939. BEGIN
  940. p := running[Machine.ID ()];
  941. ASSERT(p.oldReturnPC # -1);
  942. bp := SYSTEM.GetFramePointer ();
  943. SYSTEM.PUT (bp + AddressSize, p.oldReturnPC);
  944. CASE haltCode OF
  945. |halt: HALT(halt);
  946. |haltUnbreakable: HALT(haltUnbreakable);
  947. END;
  948. END HaltAltPC;
  949. PROCEDURE HaltReturn;
  950. VAR bp: ADDRESS;
  951. BEGIN
  952. bp := SYSTEM.GetFramePointer ();
  953. SYSTEM.GET (bp, bp); (* Get the dynamic link *)
  954. SYSTEM.SetFramePointer (bp); (* Undo the actual paf *)
  955. HaltAltPC(halt);
  956. END HaltReturn;
  957. PROCEDURE HaltUnbreakableReturn;
  958. VAR bp: ADDRESS;
  959. BEGIN
  960. bp := SYSTEM.GetFramePointer ();
  961. SYSTEM.GET (bp, bp); (* Get the dynamic link *)
  962. SYSTEM.SetFramePointer (bp); (* Undo the actual paf *)
  963. HaltAltPC(haltUnbreakable);
  964. END HaltUnbreakableReturn;
  965. PROCEDURE TerminateThis*(t: Process; unbreakable: BOOLEAN);
  966. VAR hdr {UNTRACED}: Heaps.ProtRecBlock; pc, fp : ADDRESS;
  967. (* terminates a process that is either in mode AwaitingLock or AwaitingCond *)
  968. PROCEDURE TerminateAwaiting(t: Process);
  969. VAR hdr {UNTRACED}: Heaps.ProtRecBlock;
  970. BEGIN
  971. SYSTEM.GET(SYSTEM.VAL(ADDRESS, t.waitingOn) + Heaps.HeapBlockOffset, hdr);
  972. ASSERT(hdr IS Heaps.ProtRecBlock);
  973. IF t.mode = AwaitingLock THEN
  974. fp := t.state.BP; (* SwitchTo PAF *)
  975. SYSTEM.GET (fp, fp); (* SwitchToNew PAF *)
  976. SYSTEM.GET (fp, fp); (* Lock PAF*)
  977. SYSTEM.GET (fp + AddressSize, pc); (* Get the return address*)
  978. IF ~Modules.IsExceptionHandled(pc, fp, FALSE) THEN
  979. Remove(hdr.awaitingLock, t);
  980. t.waitingOn := NIL; SYSTEM.GET (t.state.BP + AddressSize, t.oldReturnPC);
  981. IF unbreakable THEN
  982. SYSTEM.PUT (t.state.BP + AddressSize, SYSTEM.VAL (ADDRESS, trapReturn[1]))
  983. ELSE
  984. SYSTEM.PUT (t.state.BP + AddressSize, SYSTEM.VAL (ADDRESS, trapReturn[0]))
  985. END;
  986. Enter(t)
  987. ELSE
  988. Machine.Acquire (Machine.TraceOutput);
  989. Trace.String(" Not allowed to kill "); Trace.Int(t.id, 1); Trace.Char(" "); Trace.Int(t.mode, 1); Trace.Ln;
  990. Machine.Release (Machine.TraceOutput);
  991. END
  992. ELSIF t.mode = AwaitingCond THEN
  993. SYSTEM.GET (t.state.BP, fp);
  994. SYSTEM.GET (t.state.PC, pc);
  995. IF ~Modules.IsExceptionHandled(pc, fp, TRUE) THEN
  996. Remove(hdr.awaitingCond, t);
  997. t.waitingOn := NIL; SYSTEM.GET (t.state.BP + AddressSize, t.oldReturnPC);
  998. IF unbreakable THEN
  999. SYSTEM.PUT (t.state.BP + AddressSize, SYSTEM.VAL (ADDRESS, trapReturn[1]))
  1000. ELSE
  1001. SYSTEM.PUT (t.state.BP + AddressSize, SYSTEM.VAL (ADDRESS, trapReturn[0]))
  1002. END;
  1003. Enter(t)
  1004. ELSE
  1005. Machine.Acquire (Machine.TraceOutput);
  1006. Trace.String(" Not allowed to kill "); Trace.Int(t.id, 1); Trace.Char(" "); Trace.Int(t.mode, 1); Trace.Ln;
  1007. Machine.Release (Machine.TraceOutput);
  1008. END
  1009. END
  1010. END TerminateAwaiting;
  1011. BEGIN
  1012. IF PleaseHalt IN t.flags THEN
  1013. IF TraceVerbose THEN
  1014. Machine.Acquire (Machine.TraceOutput);
  1015. Trace.String("Process (ID="); Trace.Int(t.id, 0); Trace.StringLn (") is already halting!");
  1016. Machine.Release (Machine.TraceOutput);
  1017. END;
  1018. RETURN
  1019. ELSE
  1020. Machine.Acquire(Machine.Objects);
  1021. IF (t = running[Machine.ID ()]) THEN INCL(t.flags, SelfTermination); END;
  1022. IF TraceVerbose THEN
  1023. Machine.Acquire (Machine.TraceOutput);
  1024. Trace.String(" Kill "); Trace.Int(t.id, 1); Trace.Char(" "); Trace.Int(t.mode, 1); Trace.Ln;
  1025. Machine.Release (Machine.TraceOutput);
  1026. END;
  1027. CASE t.mode OF
  1028. |Running:
  1029. INCL(t.flags, PleaseHalt);
  1030. IF unbreakable THEN INCL(t.flags, Unbreakable) END
  1031. |Ready:
  1032. DEC(t.state.SP, AddressSize); SYSTEM.PUT (t.state.SP, t.state.PC);
  1033. IF unbreakable THEN t.state.PC := SYSTEM.VAL (ADDRESS, trap[1])
  1034. ELSE t.state.PC := SYSTEM.VAL (ADDRESS, trap[0]) END
  1035. |AwaitingLock, AwaitingCond:
  1036. IF HandlePriorityInv THEN
  1037. TerminateAwaiting(t)
  1038. ELSE
  1039. SYSTEM.GET(SYSTEM.VAL(ADDRESS, t.waitingOn) + Heaps.HeapBlockOffset, hdr);
  1040. ASSERT(hdr IS Heaps.ProtRecBlock);
  1041. IF ~hdr.locked THEN
  1042. Machine.AcquireObject(hdr.locked);
  1043. TerminateAwaiting(t);
  1044. Machine.ReleaseObject(hdr.locked)
  1045. END
  1046. END
  1047. | AwaitingEvent, Unknown, Terminated: (* skip *)
  1048. END;
  1049. Machine.Release(Machine.Objects)
  1050. END
  1051. END TerminateThis;
  1052. (* called by WMProcessInfo to obtain the current state of a running process *)
  1053. PROCEDURE UpdateProcessState*( p: Process );
  1054. BEGIN
  1055. (* update p.stat.{PC,BP,SP} *)
  1056. END UpdateProcessState;
  1057. (* Finalize a process. *)
  1058. PROCEDURE FinalizeProcess(t: ANY);
  1059. BEGIN
  1060. Machine.DisposeStack(t(Process).stack)
  1061. END FinalizeProcess;
  1062. (* Allocate a new process associated with "obj". Must be outside lock region, because of potential GC. *)
  1063. PROCEDURE NewProcess(body: Body; flags: SET; obj: ProtectedObject; VAR new: Process);
  1064. VAR t: Process; sp: ADDRESS; id: LONGINT; fn: Heaps.FinalizerNode;
  1065. BEGIN
  1066. NEW(t); NEW(fn); (* implicit call Heaps.NewRec *)
  1067. t.next := NIL; t.prev := NIL; t.rootedNext := NIL;
  1068. t.waitingOn := NIL; t.flags := flags;
  1069. t.obj := obj; t.mode := Unknown;
  1070. (* initialize the stack *)
  1071. Machine.NewStack(t.stack, t, sp);
  1072. IF VeryConservative THEN
  1073. Machine.Fill32(t.stack.adr, sp-t.stack.adr, LONGINT(0D0D0DEADH))
  1074. END;
  1075. SYSTEM.PUT (sp-1*AddressSize, obj); (* self parameter for body *)
  1076. SYSTEM.PUT (sp-2*AddressSize, terminate); (* return address for body *)
  1077. (* the following will be popped by SwitchTo exit code or Machine.JumpToUserLevel *)
  1078. SYSTEM.PUT (sp-3*AddressSize, body); (* return address for SwitchTo (body entry point) *)
  1079. SYSTEM.PUT (sp-4*AddressSize, NIL); (* end of dynamic link list (FP value at entry to body) *)
  1080. t.sseAdr := ADDRESSOF(t.sse) + ((-ADDRESSOF(t.sse)) MOD 16);
  1081. IF Machine.SSESupport THEN Machine.SSESaveMin(t.sseAdr)
  1082. ELSE Machine.FPUSaveMin(t.sse) (* inherit FPU state of caller *)
  1083. END;
  1084. t.state.BP := sp-4*AddressSize;
  1085. t.state.SP := t.state.BP;
  1086. t.state.PC := 0; (* indicating that process is not running yet *)
  1087. (* set up exception handling *)
  1088. IF Restart IN flags THEN (* restart object body *)
  1089. t.restartPC := SYSTEM.VAL (ADDRESS, body);
  1090. t.restartSP := sp-2*AddressSize (* 1 parameter and return address of body *)
  1091. ELSE (* terminate process *)
  1092. t.restartPC := SYSTEM.VAL (ADDRESS, terminate);
  1093. t.restartSP := sp
  1094. END;
  1095. fn.finalizer := FinalizeProcess;
  1096. Heaps.AddFinalizer(t, fn);
  1097. (* return *)
  1098. FOR id := 0 TO Machine.MaxCPU-1 DO t.cpuCycles[id] := 0 END;
  1099. new := t
  1100. END NewProcess;
  1101. (* Create the process associated with an active object (kernel call). *)
  1102. PROCEDURE CreateProcess*(body: Body; priority: WORD; flags: SET; obj: ProtectedObject);
  1103. VAR t: Process; type: ADDRESS; heapBlock {UNTRACED}: Heaps.HeapBlock; i: LONGINT;
  1104. BEGIN
  1105. IF Stats THEN Machine.AtomicInc(Ncreate) END;
  1106. SYSTEM.GET(SYSTEM.VAL(ADDRESS, obj) + Heaps.HeapBlockOffset, heapBlock);
  1107. ASSERT(heapBlock IS Heaps.ProtRecBlock); (* protected object *)
  1108. SYSTEM.GET (SYSTEM.VAL (ADDRESS, obj) + Heaps.TypeDescOffset, type); (* type tag *)
  1109. IF Restart IN flags THEN INCL(flags, Resistant) END; (* SAFE => Restart & Resistant *)
  1110. NewProcess(body, flags, obj, t);
  1111. Machine.Acquire(Machine.Objects);
  1112. t.id := nextProcessID; INC(nextProcessID);
  1113. IF ~Machine.WorkingOnKernelStack () THEN
  1114. t.context := CurrentContext();
  1115. END;
  1116. IF priority = 0 THEN (* no priority specified *)
  1117. t.priority := running[Machine.ID ()].priority (* inherit priority of creator *)
  1118. ELSIF priority > 0 THEN (* positive priority specified *)
  1119. t.priority := priority
  1120. ELSE (* negative priority specified (only for Idle process) *)
  1121. t.priority := MinPriority
  1122. END;
  1123. t.staticPriority := t.priority;
  1124. FOR i := 0 TO LEN(t.prioRequests) - 1 DO t.prioRequests[i] := 0 END;
  1125. INC(t.prioRequests[t.priority]);
  1126. CASE t.priority OF
  1127. MinPriority : t.rootedNext := rootedProcesses[t.priority]; rootedProcesses[t.priority] := t
  1128. | Low, Normal, High : (* do nothing, processes with this priority are traced by GC automatically *)
  1129. | GCPriority, Realtime : t.rootedNext := rootedProcesses[t.priority]; rootedProcesses[t.priority] := t
  1130. END;
  1131. Enter(t);
  1132. Machine.Release(Machine.Objects)
  1133. END CreateProcess;
  1134. (* Lock a protected object (kernel call) *)
  1135. (* There are two different procedures for locking a protected object in case of priority inversion handling enabled or disabled due to the different
  1136. locking strategy. *)
  1137. PROCEDURE Lock*(obj: ProtectedObject; exclusive: BOOLEAN);
  1138. BEGIN
  1139. IF HandlePriorityInv THEN
  1140. LockPriorityInv(obj, exclusive)
  1141. ELSE
  1142. LockNoPriorityInv(obj, exclusive)
  1143. END
  1144. END Lock;
  1145. (* Lock a protected object if priority inversion handling is disabled. Header locks, preemption and Machine.Objects locks are used. *)
  1146. PROCEDURE LockNoPriorityInv(obj: ProtectedObject; exclusive: BOOLEAN);
  1147. VAR hdr {UNTRACED}: Heaps.ProtRecBlock; r: Process; id: LONGINT;
  1148. BEGIN (* {called from user level} *)
  1149. IF Stats THEN Machine.AtomicInc(Nlock) END;
  1150. SYSTEM.GET(SYSTEM.VAL(ADDRESS, obj) + Heaps.HeapBlockOffset, hdr);
  1151. IF StrongChecks THEN
  1152. ASSERT(hdr IS Heaps.ProtRecBlock); (* protected object *)
  1153. ASSERT(exclusive) (* shared not implemented yet *)
  1154. END;
  1155. id := Machine.AcquirePreemption ();
  1156. Machine.AcquireObject(hdr.locked);
  1157. IF hdr.count = 0 THEN (* not locked *)
  1158. hdr.count := -1; hdr.lockedBy := SYSTEM.VAL (Process, Machine.GetProcessPtr ()); (* set exclusive lock *)
  1159. Machine.ReleaseObject(hdr.locked);
  1160. Machine.ReleasePreemption;
  1161. ELSE (* locked *)
  1162. r := SYSTEM.VAL (Process, Machine.GetProcessPtr ());
  1163. IF hdr.lockedBy = r THEN
  1164. Machine.ReleaseObject(hdr.locked);
  1165. Machine.ReleasePreemption;
  1166. ASSERT(hdr.lockedBy # r, 2203); (* nested locks not allowed *)
  1167. END;
  1168. ASSERT(r.waitingOn = NIL);
  1169. r.waitingOn := obj; r.mode := AwaitingLock;
  1170. Machine.Acquire(Machine.Objects);
  1171. Put(hdr.awaitingLock, r);
  1172. Machine.ReleaseObject(hdr.locked);
  1173. Machine.ReleasePreemption;
  1174. SwitchToNew
  1175. END
  1176. END LockNoPriorityInv;
  1177. (*
  1178. (* propagation of priorities - lock Machine.Objects is taken.
  1179. This is a procedure that calls itself recursively if a higher priority is propagated along a chain of resources and processes where each resource
  1180. is locked by a process that itself waits on a resource. The procedure can be rewritten into a non-recursive procedure if needed..
  1181. Remark: parameters of type Heaps.HeapBlock or extensions of it are not passed as parameters for clarity and safety reasons .
  1182. Instead, a ProtectedObject pointer is passed as the first parameter. *)
  1183. PROCEDURE PropagatePrio(obj: ProtectedObject; prevMaxWaitingPrio, waitingPrio: LONGINT);
  1184. VAR hdr {UNTRACED}: Heaps.ProtRecBlock; p: Process;
  1185. BEGIN
  1186. SYSTEM.GET(SYSTEM.VAL(ADDRESS, obj) + Heaps.HeapBlockOffset, hdr);
  1187. IF hdr.lockedBy # NIL THEN
  1188. p := hdr.lockedBy(Process);
  1189. DEC(p.prioRequests[prevMaxWaitingPrio]);
  1190. INC(p.prioRequests[waitingPrio]);
  1191. IF (p.waitingOn # NIL) & (waitingPrio > p.priority) THEN
  1192. obj := p.waitingOn;
  1193. SYSTEM.GET(SYSTEM.VAL(ADDRESS, obj) + Heaps.HeapBlockOffset, hdr);
  1194. prevMaxWaitingPrio := MaxPrio(hdr.waitingPriorities);
  1195. DEC(hdr.waitingPriorities[p.priority]);
  1196. INC(hdr.waitingPriorities[waitingPrio]);
  1197. IF waitingPrio > prevMaxWaitingPrio THEN PropagatePrio(obj, prevMaxWaitingPrio, waitingPrio) END
  1198. END;
  1199. IF waitingPrio > p.priority THEN
  1200. IF p.mode = Ready THEN Remove(ready.q[p.priority], p) END; (* remove p from the lower priority queue ... *)
  1201. p.priority := waitingPrio;
  1202. IF p.mode = Ready THEN Enter(p) END; (* ... and add it to the higher priority queue *)
  1203. END
  1204. END;
  1205. END PropagatePrio;
  1206. *)
  1207. (* propagation of priorities - lock Machine.Objects is taken.
  1208. This procedure is the iterative version of the above commented out recursive procedure.
  1209. Remark: hdr is an actually UNTRACED parameter. The GC, however, can handle this, see procedure Heaps.Mark, there is a check whether the
  1210. pointer to the header part is valid. In case of hdr, the pointer ot the header part is NIL. *)
  1211. PROCEDURE PropagatePrio(hdr: Heaps.ProtRecBlock; prevMaxWaitingPrio, waitingPrio: LONGINT);
  1212. VAR propagateFurther: BOOLEAN; p: Process; obj: ProtectedObject;
  1213. BEGIN
  1214. propagateFurther := TRUE;
  1215. WHILE propagateFurther & (waitingPrio > prevMaxWaitingPrio) DO
  1216. IF hdr.lockedBy # NIL THEN
  1217. p := hdr.lockedBy(Process);
  1218. DEC(p.prioRequests[prevMaxWaitingPrio]);
  1219. INC(p.prioRequests[waitingPrio]);
  1220. IF (p.waitingOn # NIL) & (waitingPrio > p.priority) THEN
  1221. obj := p.waitingOn;
  1222. SYSTEM.GET(SYSTEM.VAL(ADDRESS, obj) + Heaps.HeapBlockOffset, hdr);
  1223. prevMaxWaitingPrio := MaxPrio(hdr.waitingPriorities);
  1224. DEC(hdr.waitingPriorities[p.priority]);
  1225. INC(hdr.waitingPriorities[waitingPrio]);
  1226. ELSE (* p is not waiting for a resource or waitingPrio is less or equal to p's priority - priority propagation finishes *)
  1227. propagateFurther := FALSE
  1228. END;
  1229. IF waitingPrio > p.priority THEN (* independently of whether p is waiting on a resource or not the priority of p is changed if it is lower than waitingPrio *)
  1230. IF p.mode = Ready THEN Remove(ready.q[p.priority], p) END; (* remove p from the lower priority queue ... *)
  1231. p.priority := waitingPrio;
  1232. IF p.mode = Ready THEN Enter(p) END; (* ... and add it to the higher priority queue *)
  1233. END
  1234. ELSE (* current resource is not locked - priority propagation finishes *)
  1235. propagateFurther := FALSE
  1236. END
  1237. END
  1238. END PropagatePrio;
  1239. (* TO DO: adapt priority inversion algorithm such that priority of a process is not raised higher than High, it must not become Realtime, otherwise
  1240. GC may be corrupted *)
  1241. (* Lock a protected object if priority inversion handling is enabled. Machine.Objects lock is used. *)
  1242. PROCEDURE LockPriorityInv(obj: ProtectedObject; exclusive: BOOLEAN);
  1243. VAR hdr {UNTRACED}: Heaps.ProtRecBlock; r: Process;
  1244. maxWaitingPrio, prevMaxWaitingPrio: LONGINT;
  1245. BEGIN (* {called from user level} *)
  1246. IF Stats THEN Machine.AtomicInc(Nlock) END;
  1247. SYSTEM.GET(SYSTEM.VAL(ADDRESS, obj) + Heaps.HeapBlockOffset, hdr);
  1248. IF StrongChecks THEN
  1249. ASSERT(hdr IS Heaps.ProtRecBlock); (* protected object *)
  1250. ASSERT(exclusive) (* shared not implemented yet *)
  1251. END;
  1252. Machine.Acquire(Machine.Objects);
  1253. r := SYSTEM.VAL(Process, Machine.GetProcessPtr());
  1254. IF hdr.count = 0 THEN (* not locked *)
  1255. hdr.count := -1; hdr.lockedBy := r; (* set exclusive lock *)
  1256. maxWaitingPrio := MaxPrio(hdr.waitingPriorities);
  1257. INC(r.prioRequests[maxWaitingPrio]);
  1258. r.priority := MaxPrio(r.prioRequests);
  1259. Machine.Release(Machine.Objects);
  1260. ELSE (* locked (to do: on multiprocessors, perhaps spin here for a while, if lockedBy.mode = running) *)
  1261. IF hdr.lockedBy = r THEN
  1262. Machine.Release(Machine.Objects);
  1263. ASSERT(hdr.lockedBy # r, 2203); (* nested locks not allowed *)
  1264. END;
  1265. IF r.waitingOn # NIL THEN
  1266. Machine.Acquire(Machine.TraceOutput);
  1267. Trace.String("Objects: LockPriorityInv - hdr.count # NIL, but r.waitingOn # NIL");
  1268. Machine.Release(Machine.TraceOutput)
  1269. END;
  1270. ASSERT(r.waitingOn = NIL);
  1271. r.waitingOn := obj; r.mode := AwaitingLock;
  1272. prevMaxWaitingPrio := MaxPrio(hdr.waitingPriorities);
  1273. INC(hdr.waitingPriorities[r.priority]);
  1274. IF r.priority > prevMaxWaitingPrio THEN PropagatePrio(hdr, prevMaxWaitingPrio, r.priority) END;
  1275. Put(hdr.awaitingLock, r);
  1276. SwitchToNew
  1277. END
  1278. END LockPriorityInv;
  1279. (* Find the first true condition from the queue and remove it. Assume the object is currently locked. *)
  1280. PROCEDURE FindCondition(VAR q: ProcessQueue): Process;
  1281. VAR first, cand: Process;
  1282. BEGIN
  1283. IF Stats THEN Machine.AtomicInc(Ncondition) END;
  1284. Get(q, first);
  1285. IF first.condition(first.condFP) THEN
  1286. IF Stats THEN Machine.AtomicInc(Ncondition1True) END;
  1287. RETURN first
  1288. END;
  1289. Put(q, first);
  1290. WHILE q.head # first DO
  1291. IF Stats THEN Machine.AtomicInc(Ncondition2) END;
  1292. Get(q, cand);
  1293. IF cand.condition(cand.condFP) THEN
  1294. IF Stats THEN Machine.AtomicInc(Ncondition2True) END;
  1295. RETURN cand
  1296. END;
  1297. Put(q, cand)
  1298. END;
  1299. RETURN NIL
  1300. END FindCondition;
  1301. (* Find highest priority in array of priority counts *)
  1302. PROCEDURE MaxPrio(CONST priorityCounts: ARRAY OF WORD): WORD;
  1303. VAR i: WORD;
  1304. BEGIN
  1305. i := LEN(priorityCounts) - 1;
  1306. WHILE (i >= 0) & (priorityCounts[i] = 0) DO DEC(i) END;
  1307. IF priorityCounts[i] = 0 THEN
  1308. Machine.Acquire(Machine.TraceOutput);
  1309. Trace.StringLn("Objects: MaxPrio - SEVERE ERROR: priorityCounts contains all zeros");
  1310. Machine.Release(Machine.TraceOutput);
  1311. END;
  1312. RETURN i
  1313. END MaxPrio;
  1314. (* Unlock a protected object (kernel call). *)
  1315. (* There are two different procedures for locking a protected object in case of priority inverison handling enabled or disabled due to the different
  1316. locking strategy. *)
  1317. PROCEDURE Unlock*(obj: ProtectedObject; dummy: BOOLEAN);
  1318. BEGIN
  1319. IF HandlePriorityInv THEN
  1320. UnlockPriorityInv(obj)
  1321. ELSE
  1322. UnlockNoPriorityInv(obj)
  1323. END
  1324. END Unlock;
  1325. (* transfer the lock from a resource to another process.
  1326. Remark: hdr is an actually UNTRACED parameter. The GC, however, can handle this, see procedure Heaps.Mark, there is a check whether the
  1327. pointer to the header part is valid. In case of hdr, the pointer ot the header part is NIL. *)
  1328. PROCEDURE TransferLock(hdr: Heaps.ProtRecBlock; p: Process);
  1329. VAR maxWaitingPrio: WORD;
  1330. BEGIN
  1331. p.waitingOn := NIL; hdr.lockedBy := p;
  1332. IF HandlePriorityInv THEN
  1333. DEC(hdr.waitingPriorities[p.priority]);
  1334. maxWaitingPrio := MaxPrio(hdr.waitingPriorities);
  1335. INC(p.prioRequests[maxWaitingPrio]);
  1336. p.priority := MaxPrio(p.prioRequests)
  1337. END
  1338. END TransferLock;
  1339. (* Unlock a protected object if priority inversion handling is disabled. Header locks, preemption and Machine.Objects locks are used. *)
  1340. PROCEDURE UnlockNoPriorityInv(obj: ProtectedObject);
  1341. VAR hdr {UNTRACED}: Heaps.ProtRecBlock; t, c, r: Process; id: LONGINT;
  1342. BEGIN
  1343. IF Stats THEN Machine.AtomicInc(Nunlock) END;
  1344. SYSTEM.GET(SYSTEM.VAL(ADDRESS, obj) + Heaps.HeapBlockOffset, hdr);
  1345. IF StrongChecks THEN
  1346. ASSERT(hdr IS Heaps.ProtRecBlock) (* protected object *)
  1347. END;
  1348. ASSERT(hdr.count = -1); (* exclusive locked *)
  1349. IF hdr.awaitingCond.head # NIL THEN (* evaluate the waiting conditions *)
  1350. (* we are holding the lock, so the queue can not change (to do: except in TerminateThis) *)
  1351. c := FindCondition(hdr.awaitingCond) (* interrupts should be on during this call *)
  1352. ELSE
  1353. c := NIL
  1354. END;
  1355. id := Machine.AcquirePreemption ();
  1356. Machine.AcquireObject(hdr.locked);
  1357. r := running[Machine.ID ()];
  1358. IF hdr.lockedBy # r THEN
  1359. Machine.ReleaseObject(hdr.locked);
  1360. Machine.ReleasePreemption;
  1361. ASSERT(hdr.lockedBy = r)
  1362. END;
  1363. IF c = NIL THEN (* no true condition found, check the lock queue *)
  1364. Get(hdr.awaitingLock, t);
  1365. IF t # NIL THEN
  1366. IF StrongChecks THEN
  1367. ASSERT((t.mode = AwaitingLock) & (t.waitingOn = obj))
  1368. END;
  1369. TransferLock(hdr, t)
  1370. ELSE
  1371. hdr.lockedBy := NIL; hdr.count := 0
  1372. END
  1373. ELSE (* true condition found, transfer the lock *)
  1374. TransferLock(hdr, c);
  1375. t := NIL
  1376. END;
  1377. Machine.ReleaseObject(hdr.locked);
  1378. IF (c # NIL) OR (t # NIL) THEN
  1379. Machine.Acquire(Machine.Objects);
  1380. IF c # NIL THEN Enter(c) END;
  1381. IF t # NIL THEN Enter(t) END;
  1382. Machine.Release(Machine.Objects);
  1383. END;
  1384. Machine.ReleasePreemption;
  1385. END UnlockNoPriorityInv;
  1386. (* Unlock a protected object in case priority inversion handling is enabled. Machine.Objects lock is used. *)
  1387. PROCEDURE UnlockPriorityInv(obj: ProtectedObject);
  1388. VAR hdr {UNTRACED}: Heaps.ProtRecBlock; t, c, r: Process; maxWaitingPrio: WORD;
  1389. BEGIN
  1390. IF Stats THEN Machine.AtomicInc(Nunlock) END;
  1391. SYSTEM.GET(SYSTEM.VAL(ADDRESS, obj) + Heaps.HeapBlockOffset, hdr);
  1392. IF StrongChecks THEN
  1393. ASSERT(hdr IS Heaps.ProtRecBlock) (* protected object *)
  1394. END;
  1395. ASSERT(hdr.count = -1); (* exclusive locked *)
  1396. IF hdr.awaitingCond.head # NIL THEN (* evaluate the waiting conditions *)
  1397. (* we are holding the lock, so the queue can not change (to do: except in TerminateThis) *)
  1398. c := FindCondition(hdr.awaitingCond) (* interrupts should be on during this call *)
  1399. ELSE
  1400. c := NIL
  1401. END;
  1402. Machine.Acquire(Machine.Objects);
  1403. r := running[Machine.ID ()];
  1404. IF hdr.lockedBy # r THEN
  1405. Machine.Release(Machine.Objects);
  1406. ASSERT(hdr.lockedBy = r)
  1407. END;
  1408. maxWaitingPrio := MaxPrio(hdr.waitingPriorities);
  1409. DEC(r.prioRequests[maxWaitingPrio]);
  1410. r.priority := MaxPrio(r.prioRequests);
  1411. IF c = NIL THEN (* no true condition found, check the lock queue *)
  1412. GetMaxPrio(hdr.awaitingLock, t);
  1413. IF t = NIL THEN
  1414. hdr.lockedBy := NIL; hdr.count := 0
  1415. ELSE
  1416. IF StrongChecks THEN ASSERT((t.mode = AwaitingLock) & (t.waitingOn = obj)) END;
  1417. TransferLock(hdr, t)
  1418. END
  1419. ELSE (* true condition found, transfer the lock *)
  1420. TransferLock(hdr, c);
  1421. t := NIL
  1422. END;
  1423. IF (c # NIL) OR (t # NIL) THEN
  1424. IF c # NIL THEN Enter(c) END;
  1425. IF t # NIL THEN Enter(t) END;
  1426. END;
  1427. Machine.Release(Machine.Objects);
  1428. END UnlockPriorityInv;
  1429. (* Await a condition (kernel call). *)
  1430. (* There are two different procedures for locking a protected object in case of priority inverison handling enabled or disabled due to the different
  1431. locking strategies, i.e. there are no header locks in case of priority inversion handling. *)
  1432. PROCEDURE Await*(cond: Condition; slink: ADDRESS; obj: ProtectedObject; flags: SET);
  1433. BEGIN
  1434. IF HandlePriorityInv THEN
  1435. AwaitPriorityInv(cond, slink, obj, flags)
  1436. ELSE
  1437. AwaitNoPriorityInv(cond, slink, obj, flags)
  1438. END
  1439. END Await;
  1440. (* Await a condition if priority inversion handling is disabled. Header locks, preemption and Machine.Objects locks are used. *)
  1441. PROCEDURE AwaitNoPriorityInv(cond: Condition; slink: ADDRESS; obj: ProtectedObject; flags: SET);
  1442. VAR hdr {UNTRACED}: Heaps.ProtRecBlock; r, c, t: Process; id: LONGINT;
  1443. BEGIN
  1444. IF Stats THEN Machine.AtomicInc(Nawait) END;
  1445. IF 1 IN flags THEN (* compiler did not generate IF *)
  1446. IF Stats THEN Machine.AtomicInc(NawaitNoIF) END;
  1447. IF cond(slink) THEN
  1448. IF Stats THEN Machine.AtomicInc(NawaitTrue) END;
  1449. RETURN (* condition already true *)
  1450. END
  1451. END;
  1452. SYSTEM.GET(SYSTEM.VAL(ADDRESS, obj) + Heaps.HeapBlockOffset, hdr);
  1453. IF StrongChecks THEN
  1454. ASSERT(hdr IS Heaps.ProtRecBlock) (* protected object *)
  1455. END;
  1456. id := Machine.AcquirePreemption ();
  1457. Machine.AcquireObject(hdr.locked); (* must acquire object lock before other locks *)
  1458. r := running[id];
  1459. IF hdr.lockedBy = r THEN (* current process holds exclusive lock *)
  1460. IF StrongChecks THEN ASSERT(hdr.count = -1) END; (* exclusive locked *)
  1461. IF hdr.awaitingCond.head # NIL THEN (* evaluate the waiting conditions *)
  1462. (* we are holding the lock, so the queue can not change (to do: except in TerminateThis) *)
  1463. c := FindCondition(hdr.awaitingCond) (* interrupts should be on during this call *)
  1464. ELSE
  1465. c := NIL
  1466. END;
  1467. IF c = NIL THEN
  1468. Get(hdr.awaitingLock, t);
  1469. IF t = NIL THEN (* none waiting - remove lock *)
  1470. hdr.count := 0; hdr.lockedBy := NIL;
  1471. ELSE (* transfer lock to first waiting process *)
  1472. IF StrongChecks THEN ASSERT(t.mode = AwaitingLock) END;
  1473. TransferLock(hdr, t)
  1474. END;
  1475. ELSE
  1476. TransferLock(hdr, c);
  1477. t := NIL
  1478. END;
  1479. ELSE (* no lock, or some other process may hold the lock, but that's the user's indaba (may be monotonic condition) *)
  1480. Machine.ReleaseObject(hdr.locked);
  1481. Machine.ReleasePreemption;
  1482. HALT(2204) (* await must be exclusive region *)
  1483. END;
  1484. Machine.Acquire(Machine.Objects); (* Put and SwitchTo must be protected *)
  1485. IF c # NIL THEN Enter(c) END;
  1486. IF t # NIL THEN Enter(t) END;
  1487. IF StrongChecks THEN ASSERT(r.waitingOn = NIL) END;
  1488. r.condition := cond; r.condFP := slink;
  1489. r.waitingOn := obj; r.mode := AwaitingCond;
  1490. Put(hdr.awaitingCond, r);
  1491. Machine.ReleaseObject(hdr.locked);
  1492. Machine.ReleasePreemption;
  1493. (* reschedule *)
  1494. SwitchToNew;
  1495. IF StrongChecks THEN
  1496. ASSERT(cond(slink));
  1497. ASSERT(hdr.lockedBy = r) (* lock held again *)
  1498. END
  1499. END AwaitNoPriorityInv;
  1500. (* Await a condition in case priority inversion handling is enabled. Machine.Objects lock is used. *)
  1501. PROCEDURE AwaitPriorityInv(cond: Condition; slink: ADDRESS; obj: ProtectedObject; flags: SET);
  1502. VAR hdr {UNTRACED}: Heaps.ProtRecBlock; r, c, t: Process; id, maxWaitingPrio, prevMaxWaitingPrio: WORD;
  1503. BEGIN
  1504. IF Stats THEN Machine.AtomicInc(Nawait) END;
  1505. IF 1 IN flags THEN (* compiler did not generate IF *)
  1506. IF Stats THEN Machine.AtomicInc(NawaitNoIF) END;
  1507. IF cond(slink) THEN
  1508. IF Stats THEN Machine.AtomicInc(NawaitTrue) END;
  1509. RETURN (* condition already true *)
  1510. END
  1511. END;
  1512. SYSTEM.GET(SYSTEM.VAL(ADDRESS, obj) + Heaps.HeapBlockOffset, hdr);
  1513. IF StrongChecks THEN
  1514. ASSERT(hdr IS Heaps.ProtRecBlock) (* protected object *)
  1515. END;
  1516. Machine.Acquire(Machine.Objects);
  1517. id := Machine.ID();
  1518. r := running[id];
  1519. IF hdr.lockedBy = r THEN (* current process holds exclusive lock *)
  1520. IF StrongChecks THEN ASSERT(hdr.count = -1) END; (* exclusive locked *)
  1521. maxWaitingPrio := MaxPrio(hdr.waitingPriorities);
  1522. DEC(r.prioRequests[maxWaitingPrio]);
  1523. r.priority := MaxPrio(r.prioRequests);
  1524. IF hdr.awaitingCond.head # NIL THEN (* evaluate the waiting conditions *)
  1525. (* we are holding the lock, so the queue can not change (to do: except in TerminateThis) *)
  1526. c := FindCondition(hdr.awaitingCond) (* interrupts should be on during this call *)
  1527. ELSE
  1528. c := NIL
  1529. END;
  1530. IF c = NIL THEN
  1531. GetMaxPrio(hdr.awaitingLock, t);
  1532. IF t = NIL THEN (* none waiting - remove lock *)
  1533. hdr.count := 0; hdr.lockedBy := NIL;
  1534. ELSE (* transfer lock to first waiting process *)
  1535. IF StrongChecks THEN ASSERT(t.mode = AwaitingLock) END;
  1536. TransferLock(hdr, t);
  1537. END;
  1538. ELSE (* true condition found, transfer the lock *)
  1539. TransferLock(hdr, c);
  1540. t := NIL;
  1541. END;
  1542. ELSE (* no lock, or some other process may hold the lock, but that's the user's indaba (may be monotonic condition) *)
  1543. Machine.Release(Machine.Objects);
  1544. HALT(2204) (* await must be exclusive region *)
  1545. END;
  1546. IF c # NIL THEN Enter(c) END;
  1547. IF t # NIL THEN Enter(t) END;
  1548. IF StrongChecks THEN ASSERT(r.waitingOn = NIL) END;
  1549. r.condition := cond; r.condFP := slink;
  1550. r.waitingOn := obj; r.mode := AwaitingCond;
  1551. IF hdr.lockedBy # NIL THEN
  1552. prevMaxWaitingPrio := MaxPrio(hdr.waitingPriorities);
  1553. INC(hdr.waitingPriorities[r.priority]);
  1554. IF r.priority > prevMaxWaitingPrio THEN PropagatePrio(hdr, prevMaxWaitingPrio, r.priority) END;
  1555. ELSE (* it may happen that hdr is not locked - in that case no priority propagation takes place *)
  1556. INC(hdr.waitingPriorities[r.priority])
  1557. END;
  1558. Put(hdr.awaitingCond, r);
  1559. (* reschedule *)
  1560. SwitchToNew;
  1561. IF StrongChecks THEN
  1562. ASSERT(cond(slink));
  1563. ASSERT(hdr.lockedBy = r) (* lock held again *)
  1564. END
  1565. END AwaitPriorityInv;
  1566. (** Update the state snapshot of the current process for GC. (for Processors) *)
  1567. PROCEDURE UpdateState;
  1568. VAR t: Process;
  1569. BEGIN (* interrupts off *)
  1570. Machine.Acquire(Machine.Objects);
  1571. t := running[Machine.ID ()];
  1572. IF t # NIL THEN
  1573. t.state.PC := Machine.CurrentPC(); (* ug: required information for GC with meta data for stack inspection *)
  1574. t.state.SP := SYSTEM.GetStackPointer(); (* ug: not necessarily needed for GC *)
  1575. t.state.BP := SYSTEM.GetFramePointer(); (* ug: necessary information for GC with meta data for stack inspection *)
  1576. END;
  1577. Machine.Release(Machine.Objects)
  1578. END UpdateState;
  1579. (** Start executing user processes. Every processor calls this during initialization. *)
  1580. PROCEDURE Start*;
  1581. VAR id: LONGINT; idle: Idle; new: Process;
  1582. BEGIN (* running at kernel level (not preemptable) *)
  1583. id := Machine.ID (); (* preemption not enabled yet, because we are running at kernel level *)
  1584. NEW(idle); (* create process with MinPriority *)
  1585. Machine.Acquire(Machine.Objects);
  1586. Get(ready.q[MinPriority], new); (* can not use Select here, as it might return a preempted process *)
  1587. ASSERT(~(Preempted IN new.flags)); (* will at least get the Idle process just created *)
  1588. Machine.Release(Machine.Objects);
  1589. running[id] := new; (* schedule new process *)
  1590. new.mode := Running; new.procID := id;
  1591. IF Machine.SSESupport THEN Machine.SSERestoreMin(new.sseAdr)
  1592. ELSE Machine.FPURestoreMin(new.sse)
  1593. END;
  1594. Machine.JumpToUserLevel(new.state.BP)
  1595. END Start;
  1596. (* Initialize module. *)
  1597. PROCEDURE Init; (* can not use NEW *)
  1598. VAR
  1599. i: LONGINT;
  1600. BEGIN
  1601. ProcessorHLT := NIL;
  1602. maxReady := High; (* scan all queues at start *)
  1603. lowestAllowedPriority := Low; (* normal case, will be set to GCPriority if GC is running *)
  1604. gcBarrier := {};
  1605. FOR i := 0 TO Machine.MaxCPU - 1 DO running[i] := NIL END;
  1606. FOR i := 0 TO NumPriorities - 1 DO rootedProcesses[i] := NIL END;
  1607. FOR i := 0 TO NumIRQ-1 DO processingIRQ[i] := FALSE END;
  1608. nextProcessID := 0; Machine.ticks := 0;
  1609. traceProcess := NIL;
  1610. terminate := Terminate;
  1611. trap[0] := Halt;
  1612. trap[1] := HaltUnbreakable;
  1613. trapReturn[0] := HaltReturn;
  1614. trapReturn[1] := HaltUnbreakableReturn;
  1615. END Init;
  1616. PROCEDURE InitEventHandling;
  1617. VAR i: LONGINT; clock: Clock; (* realtimeClock: RealtimeClock; *)
  1618. BEGIN
  1619. FOR i := 0 TO NumIRQ-1 DO
  1620. interrupt[i].root := NIL; interrupt[i].process := NIL
  1621. END;
  1622. (* create normal event list *)
  1623. NEW(event); event.next := event; event.prev := event;
  1624. event.trigger := Machine.ticks + MAX(LONGINT) DIV 2;
  1625. (* create normal timer processes *)
  1626. timer := NIL; NEW(clock);
  1627. END InitEventHandling;
  1628. PROCEDURE InitGCHandling;
  1629. VAR finalizerCaller: FinalizerCaller;
  1630. BEGIN
  1631. gcProcess := NIL; NEW(gcActivity);
  1632. finalizerProcess := NIL; NEW(finalizerCaller);
  1633. END InitGCHandling;
  1634. PROCEDURE InitStats;
  1635. BEGIN
  1636. Nlock := 0; Nunlock := 0; Nawait := 0; NawaitNoIF := 0; NawaitTrue := 0;
  1637. Ncreate := 0; Nterminate := 0; Ncondition := 0; Ncondition1True := 0;
  1638. Ncondition2 := 0; Ncondition2True := 0;
  1639. Ntimeslice := 0; NtimesliceTaken := 0; NtimesliceNothing := 0;
  1640. NtimesliceIdle := 0; NtimesliceKernel := 0; NtimesliceV86 := 0; NtimesliceCritical := 0;
  1641. Npreempt := 0; NpreemptTaken := 0; NpreemptNothing := 0;
  1642. NpreemptKernel := 0; NpreemptV86 := 0; NpreemptCritical := 0;
  1643. Nenter := 0;
  1644. END InitStats;
  1645. PROCEDURE GCStatusFactory(): Heaps.GCStatus;
  1646. VAR gcStatusExt : GCStatusExt;
  1647. BEGIN
  1648. ASSERT(Heaps.gcStatus = NIL);
  1649. NEW(gcStatusExt);
  1650. RETURN gcStatusExt
  1651. END GCStatusFactory;
  1652. PROCEDURE InitPrioRequest;
  1653. VAR
  1654. i: SIZE;
  1655. BEGIN
  1656. FOR i := 0 TO LEN(init.prioRequests) - 1 DO init.prioRequests[i] := 0 END;
  1657. END InitPrioRequest;
  1658. VAR
  1659. (* for compatibility and later extension *)
  1660. TraceProcessHook*: PROCEDURE (prcoess: Process; pc, bp: ADDRESS; stacklow, stackhigh: ADDRESS);
  1661. BEGIN
  1662. TraceProcessHook := NIL;
  1663. IF Stats THEN InitStats; END;
  1664. Init;
  1665. (* initialize memory management *)
  1666. Machine.UpdateState; (* for gc *)
  1667. Heaps.CollectGarbage(Modules.root); (* still in single-processor mode *)
  1668. (* now NEW can be used *)
  1669. NEW(ready); (* create the ready queues *)
  1670. Machine.InitInterrupts;
  1671. Machine.Start; (* initialize interrupts *)
  1672. InitEventHandling;
  1673. InitGCHandling;
  1674. Heaps.gcStatus := GCStatusFactory();
  1675. (* create a process for rest of init code, which runs at user level *)
  1676. entry := SYSTEM.GetFramePointer ();
  1677. SYSTEM.GET (entry+AddressSize, entry); (* return address into linker-generated call table *)
  1678. NEW(initObject);
  1679. NewProcess(SYSTEM.VAL (Body, entry), {Resistant}, initObject, init); (* create init process *)
  1680. init.priority := High;
  1681. init.staticPriority := init.priority;
  1682. (* initialize prioRequests for init process *)
  1683. InitPrioRequest;
  1684. INC(init.prioRequests[init.priority]);
  1685. Machine.Acquire(Machine.Objects);
  1686. init.id := -1; Enter(init); init := NIL;
  1687. Machine.Release(Machine.Objects);
  1688. Start (* start it *)
  1689. (* linker call table will end with a call to Terminate. So after executing all module bodies,
  1690. the init process will terminate and other processes created during init will continue running. *)
  1691. END Objects.
  1692. (*
  1693. 24.03.1998 pjm Started
  1694. 06.05.1998 pjm CreateProcess init process, page fault handler
  1695. 06.08.1998 pjm Moved exception interrupt handling here for current process
  1696. 17.08.1998 pjm FindRoots method
  1697. 02.10.1998 pjm Idle process
  1698. 06.11.1998 pjm snapshot
  1699. 25.03.1999 pjm Scope removed
  1700. 28.05.1999 pjm EventHandler object
  1701. 01.06.1999 pjm Fixed InterruptProcess lock error
  1702. 16.06.1999 pjm Flat IRQ priority model to avoid GC deadlock
  1703. 23.06.1999 pjm Flat IRQ priority experiment failed, rather do STI in FieldIRQ to avoid GC deadlock
  1704. 29.06.1999 pjm Timeout in EventHandler object
  1705. 13.01.2000 pjm Overed (Interrupt Objects, Event Handlers, Process ID, Process state, Process mode, Process stack, Await)
  1706. 17.10.2000 pjm Priorities
  1707. 22.10.2003 mib SSE2 extension
  1708. 24.10.2003 phk Priority inversion / cycle counters
  1709. 19.06.2007 ug Garbage Collector using meta data for stack inspection
  1710. *)
  1711. (*
  1712. Location Stack
  1713. Lock Current process
  1714. SwitchTo.A Current process
  1715. SwitchTo.B
  1716. *)