BIOS.Objects.Mod 69 KB

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