2
0

Objects.Mod 68 KB

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