Objects.Mod 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842
  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. i: LONGINT;
  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 : LONGINT;
  354. BEGIN
  355. ASSERT(new = NIL);
  356. t := queue.head;
  357. maxPriority := MIN(LONGINT);
  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: LONGINT);
  412. VAR thresholdPrio: LONGINT;
  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 := Machine.CurrentSP (); (* for GC *)
  465. running.state.BP := Machine.CurrentBP (); (* 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. Machine.SetSP (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. Machine.SetSP (new.state.SP); (* run on new stack *)
  487. Machine.SetBP (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. (* Return stack bottom of process. For compatibility WinAos/UnixAos/NativeAos *)
  623. PROCEDURE GetStackBottom*(p: Process): ADDRESS;
  624. BEGIN
  625. RETURN p.stack.high
  626. END GetStackBottom;
  627. (** Return the active object currently executing. *)
  628. PROCEDURE ActiveObject* (): ANY;
  629. VAR r: Process;
  630. BEGIN
  631. r := SYSTEM.VAL(Process, Machine.GetProcessPtr ());
  632. RETURN r.obj
  633. END ActiveObject;
  634. (** Return the ID of the active currently executing process. *)
  635. PROCEDURE GetProcessID* (): LONGINT;
  636. VAR r: Process;
  637. BEGIN
  638. r := SYSTEM.VAL (Process, Machine.GetProcessPtr ());
  639. RETURN r.id
  640. END GetProcessID;
  641. (** Set the current process' priority. *)
  642. PROCEDURE SetPriority*(priority: LONGINT);
  643. VAR id: LONGINT;
  644. BEGIN
  645. ASSERT((priority >= Low) & (priority <= Realtime)); (* priority in bounds *)
  646. IF HandlePriorityInv THEN
  647. Machine.Acquire(Machine.Objects);
  648. id := Machine.ID();
  649. running[id].SetPriority(priority);
  650. Machine.Release(Machine.Objects)
  651. ELSE
  652. id := Machine.AcquirePreemption ();
  653. running[id].priority := priority;
  654. Machine.ReleasePreemption
  655. (* to do: re-establish global priority invariant *)
  656. END
  657. END SetPriority;
  658. (** Return TRUE iff the specified protected object is locked exclusive to the current process. *)
  659. PROCEDURE LockedByCurrent*(obj: ANY): BOOLEAN;
  660. VAR hdr {UNTRACED}: Heaps.ProtRecBlock; id: LONGINT; res: BOOLEAN;
  661. BEGIN
  662. SYSTEM.GET(SYSTEM.VAL(ADDRESS, obj) + Heaps.HeapBlockOffset, hdr);
  663. ASSERT(hdr IS Heaps.ProtRecBlock);
  664. IF HandlePriorityInv THEN
  665. Machine.Acquire(Machine.Objects);
  666. id := Machine.ID();
  667. res := (hdr.lockedBy = running[id]);
  668. Machine.Release(Machine.Objects)
  669. ELSE
  670. id := Machine.AcquirePreemption ();
  671. Machine.AcquireObject(hdr.locked);
  672. res := (hdr.lockedBy = running[id]);
  673. Machine.ReleaseObject(hdr.locked);
  674. Machine.ReleasePreemption;
  675. END;
  676. RETURN res
  677. END LockedByCurrent;
  678. (** Return number of ready and running processes, excluding idle processes. *)
  679. PROCEDURE NumReady* (): LONGINT;
  680. VAR i, n: LONGINT; p: Heaps.ProcessLink;
  681. BEGIN
  682. n := 0;
  683. Machine.Acquire(Machine.Objects);
  684. FOR i := MinPriority+1 TO NumPriorities-1 DO
  685. p := ready.q[i].head; WHILE p # NIL DO INC(n); p := p.next END
  686. END;
  687. FOR i := 0 TO Machine.MaxCPU-1 DO
  688. IF (running[i] # NIL) & (running[i].priority > MinPriority) THEN INC(n) END
  689. END;
  690. Machine.Release(Machine.Objects);
  691. RETURN n
  692. END NumReady;
  693. (** Return number of CPU cycles consumed by the specified process for each processor. If all is TRUE,
  694. return the number of cycles since the process has been created. If FALSE, return the number of cycles
  695. consumed since the last time asked. *)
  696. PROCEDURE GetCpuCycles*(process : Process; VAR cpuCycles : CpuCyclesArray; all : BOOLEAN);
  697. VAR i : LONGINT;
  698. BEGIN
  699. ASSERT(process # NIL);
  700. FOR i := 0 TO Machine.MaxCPU-1 DO cpuCycles[i] := process.cpuCycles[i]; END;
  701. IF ~all THEN
  702. FOR i := 0 TO Machine.MaxCPU-1 DO
  703. cpuCycles[i] := cpuCycles[i] - process.lastCpuCycles[i];
  704. process.lastCpuCycles[i] := process.cpuCycles[i]; (* actually could have changed meanwhile *)
  705. END;
  706. END;
  707. END GetCpuCycles;
  708. PROCEDURE CurrentProcessTime*(): HUGEINT;
  709. VAR result: HUGEINT; process: Process;
  710. BEGIN
  711. process := CurrentProcess();
  712. FOR i := 0 TO Machine.MaxCPU-1 DO result := result + process.cpuCycles[i]; END;
  713. RETURN result;
  714. END CurrentProcessTime;
  715. PROCEDURE TimerFrequency*(): HUGEINT;
  716. BEGIN
  717. RETURN 1000000000;
  718. END TimerFrequency;
  719. (* Handle hardware interrupt and route it to an interrupt handler process. *)
  720. PROCEDURE FieldIRQ(VAR state: Machine.State);
  721. VAR t: Process; id: LONGINT; new: Process; preempt: BOOLEAN;
  722. BEGIN
  723. Machine.DisableIRQ(state.INT); (* do this before acknowledging irq *)
  724. IF StrongChecks THEN
  725. IF processingIRQ[state.INT-MinIRQ] THEN
  726. Trace.String("IRQ recursion "); Trace.Int(state.INT,1); Trace.Ln;
  727. RETURN
  728. ELSE
  729. processingIRQ[state.INT-MinIRQ] := TRUE;
  730. END;
  731. END;
  732. (* if the reenabling of interrupts cannot be circumvented, then it is REQUIRED to acknowledge interrupts
  733. BEFORE reenabling. Otherwise spurious IRQs cannot be identified as such.
  734. Please note that this particular problem with spurious IRQs cannot observed on many machines but IF it is observed
  735. then the machine will behave unexpected. Very hard to debug and trace!
  736. Machine.Ack(state.INT);
  737. Machine.Sti (); (* avoid Processors.StopAll deadlock when waiting for locks below (remove this) *)
  738. *)
  739. Machine.Acquire(Machine.Objects);
  740. t := interrupt[state.INT-MinIRQ].process;
  741. IF StrongChecks THEN ASSERT(t.mode = AwaitingEvent) END;
  742. id := Machine.ID ();
  743. preempt := (t.priority > maxReady) & (maxReady # MinPriority) & (t.priority > running[id].priority);
  744. Enter(t);
  745. IF preempt THEN
  746. IF Stats THEN Machine.AtomicInc(Npreempt) END;
  747. (* pre-empt the current process *)
  748. IF Machine.PreemptCount(id) = 1 THEN (* check against 1, because we are holding one lock *)
  749. IF ~(Machine.VMBit IN state.FLAGS) THEN (* not V86 mode *)
  750. IF state.CS MOD 4 = Machine.UserLevel THEN (* not kernel mode (used during initialization or interrupts) *)
  751. Select(new, running[id].priority + 1);
  752. IF new # NIL THEN
  753. ASSERT(Machine.CS () MOD 4 = Machine.KernelLevel); (* otherwise we can not change state.SP *)
  754. INC (running[id].cpuCycles[id], Machine.GetTimer () - perfTsc[id]);
  755. IF running[id].priority = MinPriority THEN (* Special treatment for idle threads *)
  756. INC (idleCycles[id], Machine.GetTimer () - perfTsc[id]);
  757. END;
  758. IF Stats THEN Machine.AtomicInc(NpreemptTaken) END;
  759. INCL(running[id].flags, Preempted);
  760. Machine.CopyState(state, running[id].state);
  761. IF Machine.SSESupport THEN Machine.SSESaveFull(running[id].sseAdr)
  762. ELSE Machine.FPUSaveFull(running[id].sse); (* to do: floating-point exception possible / Machine.SetupFPU *)
  763. END;
  764. Enter(running[id]);
  765. running[id] := new;
  766. new.mode := Running; new.procID := id;
  767. IF Preempted IN new.flags THEN
  768. EXCL(new.flags, Preempted);
  769. Machine.CopyState(new.state, state);
  770. IF Machine.SSESupport THEN Machine.SSERestoreFull(new.sseAdr)
  771. ELSE Machine.FPURestoreFull(new.sse)
  772. END
  773. ELSE
  774. SwitchToState(new, state);
  775. IF Machine.SSESupport THEN Machine.SSERestoreMin(new.sseAdr)
  776. ELSE Machine.FPURestoreMin(new.sse)
  777. END
  778. END;
  779. perfTsc[id] := Machine.GetTimer ()
  780. ELSE
  781. IF Stats THEN Machine.AtomicInc(NpreemptNothing) END
  782. END
  783. ELSE
  784. (* can not interrupt kernel mode, because SwitchTo would not switch back to it *)
  785. IF Stats THEN Machine.AtomicInc(NpreemptKernel) END (* kernel mode, e.g. during page fault or FieldIRQ *)
  786. END
  787. ELSE
  788. IF Stats THEN Machine.AtomicInc(NpreemptV86) END (* V86 mode *)
  789. END
  790. ELSE
  791. IF Stats THEN Machine.AtomicInc(NpreemptCritical) END (* not preemptable *)
  792. END
  793. END;
  794. Machine.Release(Machine.Objects)
  795. END FieldIRQ;
  796. (* Process scheduled to handle an interrupt. *)
  797. PROCEDURE InterruptProcess(self: ProtectedObject);
  798. VAR h: InterruptList; t: Process; int: LONGINT;
  799. BEGIN
  800. int := self(Interrupter).interruptNumber;
  801. t := interrupt[int-MinIRQ].process;
  802. LOOP
  803. h := interrupt[int-MinIRQ].root; (* concurrent updates allowed in InstallHandler and RemoveHandler *)
  804. WHILE h # NIL DO h.handler (); h := h.next END;
  805. Machine.Acquire(Machine.Objects);
  806. ASSERT(running[Machine.ID ()] = t); (* strong check *)
  807. t.mode := AwaitingEvent;
  808. processingIRQ[int-MinIRQ] := FALSE;
  809. Machine.EnableIRQ(int);
  810. SwitchToNew
  811. END
  812. END InterruptProcess;
  813. (** Install interrupt handler. *)
  814. PROCEDURE InstallHandler*(h: EventHandler; int: LONGINT);
  815. VAR t: Process; new: BOOLEAN; ih: Interrupter; n: InterruptList; i: LONGINT;
  816. BEGIN
  817. ASSERT((int >= MinIRQ) & (int-MinIRQ < NumIRQ)); (* range check *)
  818. IF interrupt[int-MinIRQ].process = NIL THEN (* first handler for this irq *)
  819. (* allocate process outside lock region, to avoid GC lock problems. *)
  820. (* hack: use type parameter to pass int index & set obj to h, for System.ShowProcesses *)
  821. NEW(ih); ih.interruptNumber := int;
  822. NewProcess(InterruptProcess, {Resistant}, ih, t);
  823. t.priority := High; (* second-level interrupt handling processes have high priority, handlers may allocate memory, use exclusive locks and awaits *)
  824. t.staticPriority := t.priority;
  825. FOR i := 0 TO LEN(t.prioRequests) - 1 DO t.prioRequests[i] := 0 END;
  826. INC(t.prioRequests[t.priority])
  827. END;
  828. NEW(n); n.handler := h;
  829. Machine.Acquire(Machine.Objects);
  830. IF interrupt[int-MinIRQ].process = NIL THEN (* still first handler for this irq *)
  831. t.id := nextProcessID; INC(nextProcessID);
  832. t.mode := AwaitingEvent;
  833. interrupt[int-MinIRQ].process := t;
  834. new := TRUE
  835. ELSE
  836. new := FALSE
  837. END;
  838. n.next := interrupt[int-MinIRQ].root; (* can be concurrent with loop in InterruptProcess *)
  839. interrupt[int-MinIRQ].root := n;
  840. Machine.Release(Machine.Objects);
  841. IF new THEN Machine.InstallHandler(FieldIRQ, int) END (* do outside lock region to avoid NEW/GC deadlock *)
  842. END InstallHandler;
  843. (** Remove interrupt handler. *)
  844. PROCEDURE RemoveHandler*(h: EventHandler; int: LONGINT);
  845. VAR p, c: InterruptList;
  846. BEGIN
  847. ASSERT((int >= MinIRQ) & (int-MinIRQ < NumIRQ)); (* range check *)
  848. Machine.Acquire(Machine.Objects);
  849. p := NIL; c := interrupt[int-MinIRQ].root;
  850. WHILE (c.handler # h) & (c # NIL) DO p := c; c := c.next END;
  851. IF c.handler = h THEN (* handler found *)
  852. IF p = NIL THEN
  853. interrupt[int-MinIRQ].root := c.next;
  854. (*
  855. IF c.inext = NIL THEN (* this was the last handler *)
  856. Machine.RemoveHandler(FieldIRQ, int)
  857. (* to do: synchronize with FieldIRQ and InterruptProcess *)
  858. END
  859. *)
  860. ELSE
  861. p.next := c.next
  862. END
  863. ELSE
  864. HALT(99); (* handler not found *)
  865. END;
  866. (* can not clear c.next field, because InterruptProcess may be traversing it. *)
  867. Machine.Release(Machine.Objects)
  868. END RemoveHandler;
  869. (* local procedure *)
  870. PROCEDURE SetTimeoutAbsOrRel(t: Timer; h: EventHandler; ms: LONGINT; isAbsolute: BOOLEAN);
  871. VAR e: Timer; trigger: LONGINT;
  872. BEGIN
  873. ASSERT(Machine.Second= 1000); (* assume milliseconds for now *)
  874. ASSERT((t # NIL) & (h # NIL));
  875. IF ms < 1 THEN ms := 1 END;
  876. Machine.Acquire(Machine.Objects);
  877. IF isAbsolute THEN trigger := ms ELSE trigger := Machine.ticks + ms (* ignore overflow *) END;
  878. IF t.next # NIL THEN (* cancel previous timeout *)
  879. t.next.prev := t.prev; t.prev.next := t.next
  880. END;
  881. t.trigger := trigger; t.handler := h;
  882. e := event.next; (* performance: linear search! *)
  883. WHILE (e # event) & (e.trigger - trigger <= 0) DO e := e.next END;
  884. t.prev := e.prev; e.prev := t; t.next := e; t.prev.next := t;
  885. Machine.Release(Machine.Objects)
  886. END SetTimeoutAbsOrRel;
  887. (** Set (or reset) an event handler object's timeout value. *)
  888. PROCEDURE SetTimeout*(t: Timer; h: EventHandler; ms: LONGINT);
  889. BEGIN
  890. SetTimeoutAbsOrRel(t, h, ms, FALSE)
  891. END SetTimeout;
  892. (** Set (or reset) an event handler object's timeout value. Here ms is absolute *)
  893. PROCEDURE SetTimeoutAt*(t: Timer; h: EventHandler; ms: LONGINT);
  894. BEGIN
  895. SetTimeoutAbsOrRel(t, h, ms, TRUE)
  896. END SetTimeoutAt;
  897. (** Cancel an event handler object's timeout, if any. It is possible that the timer has expired, but not yet been scheduled to run. *)
  898. PROCEDURE CancelTimeout*(t: Timer);
  899. BEGIN
  900. Machine.Acquire(Machine.Objects);
  901. ASSERT(t # event);
  902. IF t.next # NIL THEN
  903. t.next.prev := t.prev; t.prev.next := t.next;
  904. t.next := NIL; t.prev := NIL
  905. END;
  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. (* Finalize a process. *)
  1045. PROCEDURE FinalizeProcess(t: ANY);
  1046. BEGIN
  1047. Machine.DisposeStack(t(Process).stack)
  1048. END FinalizeProcess;
  1049. (* Allocate a new process associated with "obj". Must be outside lock region, because of potential GC. *)
  1050. PROCEDURE NewProcess(body: Body; flags: SET; obj: ProtectedObject; VAR new: Process);
  1051. VAR t: Process; sp: ADDRESS; id: LONGINT; fn: Heaps.FinalizerNode;
  1052. BEGIN
  1053. NEW(t); NEW(fn); (* implicit call Heaps.NewRec *)
  1054. t.next := NIL; t.prev := NIL; t.rootedNext := NIL;
  1055. t.waitingOn := NIL; t.flags := flags;
  1056. t.obj := obj; t.mode := Unknown;
  1057. (* initialize the stack *)
  1058. Machine.NewStack(t.stack, t, sp);
  1059. IF VeryConservative THEN
  1060. Machine.Fill32(t.stack.adr, sp-t.stack.adr, LONGINT(0D0D0DEADH))
  1061. END;
  1062. SYSTEM.PUT (sp-1*AddressSize, obj); (* self parameter for body *)
  1063. SYSTEM.PUT (sp-2*AddressSize, terminate); (* return address for body *)
  1064. (* the following will be popped by SwitchTo exit code or Machine.JumpToUserLevel *)
  1065. SYSTEM.PUT (sp-3*AddressSize, body); (* return address for SwitchTo (body entry point) *)
  1066. SYSTEM.PUT (sp-4*AddressSize, NIL); (* end of dynamic link list (FP value at entry to body) *)
  1067. t.sseAdr := ADDRESSOF(t.sse) + ((-ADDRESSOF(t.sse)) MOD 16);
  1068. IF Machine.SSESupport THEN Machine.SSESaveMin(t.sseAdr)
  1069. ELSE Machine.FPUSaveMin(t.sse) (* inherit FPU state of caller *)
  1070. END;
  1071. t.state.BP := sp-4*AddressSize;
  1072. t.state.SP := t.state.BP;
  1073. t.state.PC := 0; (* indicating that process is not running yet *)
  1074. (* set up exception handling *)
  1075. IF Restart IN flags THEN (* restart object body *)
  1076. t.restartPC := SYSTEM.VAL (ADDRESS, body);
  1077. t.restartSP := sp-2*AddressSize (* 1 parameter and return address of body *)
  1078. ELSE (* terminate process *)
  1079. t.restartPC := SYSTEM.VAL (ADDRESS, terminate);
  1080. t.restartSP := sp
  1081. END;
  1082. fn.finalizer := FinalizeProcess;
  1083. Heaps.AddFinalizer(t, fn);
  1084. (* return *)
  1085. FOR id := 0 TO Machine.MaxCPU-1 DO t.cpuCycles[id] := 0 END;
  1086. new := t
  1087. END NewProcess;
  1088. (* Create the process associated with an active object (kernel call). *)
  1089. PROCEDURE CreateProcess*(body: Body; priority: LONGINT; flags: SET; obj: ProtectedObject);
  1090. VAR t: Process; type: ADDRESS; heapBlock {UNTRACED}: Heaps.HeapBlock; i: LONGINT;
  1091. BEGIN
  1092. IF Stats THEN Machine.AtomicInc(Ncreate) END;
  1093. SYSTEM.GET(SYSTEM.VAL(ADDRESS, obj) + Heaps.HeapBlockOffset, heapBlock);
  1094. ASSERT(heapBlock IS Heaps.ProtRecBlock); (* protected object *)
  1095. SYSTEM.GET (SYSTEM.VAL (ADDRESS, obj) + Heaps.TypeDescOffset, type); (* type tag *)
  1096. IF Restart IN flags THEN INCL(flags, Resistant) END; (* SAFE => Restart & Resistant *)
  1097. NewProcess(body, flags, obj, t);
  1098. Machine.Acquire(Machine.Objects);
  1099. t.id := nextProcessID; INC(nextProcessID);
  1100. IF priority = 0 THEN (* no priority specified *)
  1101. t.priority := running[Machine.ID ()].priority (* inherit priority of creator *)
  1102. ELSIF priority > 0 THEN (* positive priority specified *)
  1103. t.priority := priority
  1104. ELSE (* negative priority specified (only for Idle process) *)
  1105. t.priority := MinPriority
  1106. END;
  1107. t.staticPriority := t.priority;
  1108. FOR i := 0 TO LEN(t.prioRequests) - 1 DO t.prioRequests[i] := 0 END;
  1109. INC(t.prioRequests[t.priority]);
  1110. CASE t.priority OF
  1111. MinPriority : t.rootedNext := rootedProcesses[t.priority]; rootedProcesses[t.priority] := t
  1112. | Low, Normal, High : (* do nothing, processes with this priority are traced by GC automatically *)
  1113. | GCPriority, Realtime : t.rootedNext := rootedProcesses[t.priority]; rootedProcesses[t.priority] := t
  1114. END;
  1115. Enter(t);
  1116. Machine.Release(Machine.Objects)
  1117. END CreateProcess;
  1118. (* Lock a protected object (kernel call) *)
  1119. (* There are two different procedures for locking a protected object in case of priority inversion handling enabled or disabled due to the different
  1120. locking strategy. *)
  1121. PROCEDURE Lock*(obj: ProtectedObject; exclusive: BOOLEAN);
  1122. BEGIN
  1123. IF HandlePriorityInv THEN
  1124. LockPriorityInv(obj, exclusive)
  1125. ELSE
  1126. LockNoPriorityInv(obj, exclusive)
  1127. END
  1128. END Lock;
  1129. (* Lock a protected object if priority inversion handling is disabled. Header locks, preemption and Machine.Objects locks are used. *)
  1130. PROCEDURE LockNoPriorityInv(obj: ProtectedObject; exclusive: BOOLEAN);
  1131. VAR hdr {UNTRACED}: Heaps.ProtRecBlock; r: Process; id: LONGINT;
  1132. BEGIN (* {called from user level} *)
  1133. IF Stats THEN Machine.AtomicInc(Nlock) END;
  1134. SYSTEM.GET(SYSTEM.VAL(ADDRESS, obj) + Heaps.HeapBlockOffset, hdr);
  1135. IF StrongChecks THEN
  1136. ASSERT(hdr IS Heaps.ProtRecBlock); (* protected object *)
  1137. ASSERT(exclusive) (* shared not implemented yet *)
  1138. END;
  1139. id := Machine.AcquirePreemption ();
  1140. Machine.AcquireObject(hdr.locked);
  1141. IF hdr.count = 0 THEN (* not locked *)
  1142. hdr.count := -1; hdr.lockedBy := SYSTEM.VAL (Process, Machine.GetProcessPtr ()); (* set exclusive lock *)
  1143. Machine.ReleaseObject(hdr.locked);
  1144. Machine.ReleasePreemption;
  1145. ELSE (* locked *)
  1146. r := SYSTEM.VAL (Process, Machine.GetProcessPtr ());
  1147. IF hdr.lockedBy = r THEN
  1148. Machine.ReleaseObject(hdr.locked);
  1149. Machine.ReleasePreemption;
  1150. ASSERT(hdr.lockedBy # r, 2203); (* nested locks not allowed *)
  1151. END;
  1152. ASSERT(r.waitingOn = NIL);
  1153. r.waitingOn := obj; r.mode := AwaitingLock;
  1154. Machine.Acquire(Machine.Objects);
  1155. Put(hdr.awaitingLock, r);
  1156. Machine.ReleaseObject(hdr.locked);
  1157. Machine.ReleasePreemption;
  1158. SwitchToNew
  1159. END
  1160. END LockNoPriorityInv;
  1161. (*
  1162. (* propagation of priorities - lock Machine.Objects is taken.
  1163. This is a procedure that calls itself recursively if a higher priority is propagated along a chain of resources and processes where each resource
  1164. is locked by a process that itself waits on a resource. The procedure can be rewritten into a non-recursive procedure if needed..
  1165. Remark: parameters of type Heaps.HeapBlock or extensions of it are not passed as parameters for clarity and safety reasons .
  1166. Instead, a ProtectedObject pointer is passed as the first parameter. *)
  1167. PROCEDURE PropagatePrio(obj: ProtectedObject; prevMaxWaitingPrio, waitingPrio: LONGINT);
  1168. VAR hdr {UNTRACED}: Heaps.ProtRecBlock; p: Process;
  1169. BEGIN
  1170. SYSTEM.GET(SYSTEM.VAL(ADDRESS, obj) + Heaps.HeapBlockOffset, hdr);
  1171. IF hdr.lockedBy # NIL THEN
  1172. p := hdr.lockedBy(Process);
  1173. DEC(p.prioRequests[prevMaxWaitingPrio]);
  1174. INC(p.prioRequests[waitingPrio]);
  1175. IF (p.waitingOn # NIL) & (waitingPrio > p.priority) THEN
  1176. obj := p.waitingOn;
  1177. SYSTEM.GET(SYSTEM.VAL(ADDRESS, obj) + Heaps.HeapBlockOffset, hdr);
  1178. prevMaxWaitingPrio := MaxPrio(hdr.waitingPriorities);
  1179. DEC(hdr.waitingPriorities[p.priority]);
  1180. INC(hdr.waitingPriorities[waitingPrio]);
  1181. IF waitingPrio > prevMaxWaitingPrio THEN PropagatePrio(obj, prevMaxWaitingPrio, waitingPrio) END
  1182. END;
  1183. IF waitingPrio > p.priority THEN
  1184. IF p.mode = Ready THEN Remove(ready.q[p.priority], p) END; (* remove p from the lower priority queue ... *)
  1185. p.priority := waitingPrio;
  1186. IF p.mode = Ready THEN Enter(p) END; (* ... and add it to the higher priority queue *)
  1187. END
  1188. END;
  1189. END PropagatePrio;
  1190. *)
  1191. (* propagation of priorities - lock Machine.Objects is taken.
  1192. This procedure is the iterative version of the above commented out recursive procedure.
  1193. Remark: hdr is an actually UNTRACED parameter. The GC, however, can handle this, see procedure Heaps.Mark, there is a check whether the
  1194. pointer to the header part is valid. In case of hdr, the pointer ot the header part is NIL. *)
  1195. PROCEDURE PropagatePrio(hdr: Heaps.ProtRecBlock; prevMaxWaitingPrio, waitingPrio: LONGINT);
  1196. VAR propagateFurther: BOOLEAN; p: Process; obj: ProtectedObject;
  1197. BEGIN
  1198. propagateFurther := TRUE;
  1199. WHILE propagateFurther & (waitingPrio > prevMaxWaitingPrio) DO
  1200. IF hdr.lockedBy # NIL THEN
  1201. p := hdr.lockedBy(Process);
  1202. DEC(p.prioRequests[prevMaxWaitingPrio]);
  1203. INC(p.prioRequests[waitingPrio]);
  1204. IF (p.waitingOn # NIL) & (waitingPrio > p.priority) THEN
  1205. obj := p.waitingOn;
  1206. SYSTEM.GET(SYSTEM.VAL(ADDRESS, obj) + Heaps.HeapBlockOffset, hdr);
  1207. prevMaxWaitingPrio := MaxPrio(hdr.waitingPriorities);
  1208. DEC(hdr.waitingPriorities[p.priority]);
  1209. INC(hdr.waitingPriorities[waitingPrio]);
  1210. ELSE (* p is not waiting for a resource or waitingPrio is less or equal to p's priority - priority propagation finishes *)
  1211. propagateFurther := FALSE
  1212. END;
  1213. 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 *)
  1214. IF p.mode = Ready THEN Remove(ready.q[p.priority], p) END; (* remove p from the lower priority queue ... *)
  1215. p.priority := waitingPrio;
  1216. IF p.mode = Ready THEN Enter(p) END; (* ... and add it to the higher priority queue *)
  1217. END
  1218. ELSE (* current resource is not locked - priority propagation finishes *)
  1219. propagateFurther := FALSE
  1220. END
  1221. END
  1222. END PropagatePrio;
  1223. (* TO DO: adapt priority inversion algorithm such that priority of a process is not raised higher than High, it must not become Realtime, otherwise
  1224. GC may be corrupted *)
  1225. (* Lock a protected object if priority inversion handling is enabled. Machine.Objects lock is used. *)
  1226. PROCEDURE LockPriorityInv(obj: ProtectedObject; exclusive: BOOLEAN);
  1227. VAR hdr {UNTRACED}: Heaps.ProtRecBlock; r: Process;
  1228. maxWaitingPrio, prevMaxWaitingPrio: LONGINT;
  1229. BEGIN (* {called from user level} *)
  1230. IF Stats THEN Machine.AtomicInc(Nlock) END;
  1231. SYSTEM.GET(SYSTEM.VAL(ADDRESS, obj) + Heaps.HeapBlockOffset, hdr);
  1232. IF StrongChecks THEN
  1233. ASSERT(hdr IS Heaps.ProtRecBlock); (* protected object *)
  1234. ASSERT(exclusive) (* shared not implemented yet *)
  1235. END;
  1236. Machine.Acquire(Machine.Objects);
  1237. r := SYSTEM.VAL(Process, Machine.GetProcessPtr());
  1238. IF hdr.count = 0 THEN (* not locked *)
  1239. hdr.count := -1; hdr.lockedBy := r; (* set exclusive lock *)
  1240. maxWaitingPrio := MaxPrio(hdr.waitingPriorities);
  1241. INC(r.prioRequests[maxWaitingPrio]);
  1242. r.priority := MaxPrio(r.prioRequests);
  1243. Machine.Release(Machine.Objects);
  1244. ELSE (* locked (to do: on multiprocessors, perhaps spin here for a while, if lockedBy.mode = running) *)
  1245. IF hdr.lockedBy = r THEN
  1246. Machine.Release(Machine.Objects);
  1247. ASSERT(hdr.lockedBy # r, 2203); (* nested locks not allowed *)
  1248. END;
  1249. IF r.waitingOn # NIL THEN
  1250. Machine.Acquire(Machine.TraceOutput);
  1251. Trace.String("Objects: LockPriorityInv - hdr.count # NIL, but r.waitingOn # NIL");
  1252. Machine.Release(Machine.TraceOutput)
  1253. END;
  1254. ASSERT(r.waitingOn = NIL);
  1255. r.waitingOn := obj; r.mode := AwaitingLock;
  1256. prevMaxWaitingPrio := MaxPrio(hdr.waitingPriorities);
  1257. INC(hdr.waitingPriorities[r.priority]);
  1258. IF r.priority > prevMaxWaitingPrio THEN PropagatePrio(hdr, prevMaxWaitingPrio, r.priority) END;
  1259. Put(hdr.awaitingLock, r);
  1260. SwitchToNew
  1261. END
  1262. END LockPriorityInv;
  1263. (* Find the first true condition from the queue and remove it. Assume the object is currently locked. *)
  1264. PROCEDURE FindCondition(VAR q: ProcessQueue): Process;
  1265. VAR first, cand: Process;
  1266. BEGIN
  1267. IF Stats THEN Machine.AtomicInc(Ncondition) END;
  1268. Get(q, first);
  1269. IF first.condition(first.condFP) THEN
  1270. IF Stats THEN Machine.AtomicInc(Ncondition1True) END;
  1271. RETURN first
  1272. END;
  1273. Put(q, first);
  1274. WHILE q.head # first DO
  1275. IF Stats THEN Machine.AtomicInc(Ncondition2) END;
  1276. Get(q, cand);
  1277. IF cand.condition(cand.condFP) THEN
  1278. IF Stats THEN Machine.AtomicInc(Ncondition2True) END;
  1279. RETURN cand
  1280. END;
  1281. Put(q, cand)
  1282. END;
  1283. RETURN NIL
  1284. END FindCondition;
  1285. (* Find highest priority in array of priority counts *)
  1286. PROCEDURE MaxPrio(CONST priorityCounts: ARRAY OF LONGINT): LONGINT;
  1287. VAR i: LONGINT;
  1288. BEGIN
  1289. i := LEN(priorityCounts) - 1;
  1290. WHILE (i >= 0) & (priorityCounts[i] = 0) DO DEC(i) END;
  1291. IF priorityCounts[i] = 0 THEN
  1292. Machine.Acquire(Machine.TraceOutput);
  1293. Trace.StringLn("Objects: MaxPrio - SEVERE ERROR: priorityCounts contains all zeros");
  1294. Machine.Release(Machine.TraceOutput);
  1295. END;
  1296. RETURN i
  1297. END MaxPrio;
  1298. (* Unlock a protected object (kernel call). *)
  1299. (* There are two different procedures for locking a protected object in case of priority inverison handling enabled or disabled due to the different
  1300. locking strategy. *)
  1301. PROCEDURE Unlock*(obj: ProtectedObject; dummy: BOOLEAN);
  1302. BEGIN
  1303. IF HandlePriorityInv THEN
  1304. UnlockPriorityInv(obj)
  1305. ELSE
  1306. UnlockNoPriorityInv(obj)
  1307. END
  1308. END Unlock;
  1309. (* transfer the lock from a resource to another process.
  1310. Remark: hdr is an actually UNTRACED parameter. The GC, however, can handle this, see procedure Heaps.Mark, there is a check whether the
  1311. pointer to the header part is valid. In case of hdr, the pointer ot the header part is NIL. *)
  1312. PROCEDURE TransferLock(hdr: Heaps.ProtRecBlock; p: Process);
  1313. VAR maxWaitingPrio: LONGINT;
  1314. BEGIN
  1315. p.waitingOn := NIL; hdr.lockedBy := p;
  1316. IF HandlePriorityInv THEN
  1317. DEC(hdr.waitingPriorities[p.priority]);
  1318. maxWaitingPrio := MaxPrio(hdr.waitingPriorities);
  1319. INC(p.prioRequests[maxWaitingPrio]);
  1320. p.priority := MaxPrio(p.prioRequests)
  1321. END
  1322. END TransferLock;
  1323. (* Unlock a protected object if priority inversion handling is disabled. Header locks, preemption and Machine.Objects locks are used. *)
  1324. PROCEDURE UnlockNoPriorityInv(obj: ProtectedObject);
  1325. VAR hdr {UNTRACED}: Heaps.ProtRecBlock; t, c, r: Process; id: LONGINT;
  1326. BEGIN
  1327. IF Stats THEN Machine.AtomicInc(Nunlock) END;
  1328. SYSTEM.GET(SYSTEM.VAL(ADDRESS, obj) + Heaps.HeapBlockOffset, hdr);
  1329. IF StrongChecks THEN
  1330. ASSERT(hdr IS Heaps.ProtRecBlock) (* protected object *)
  1331. END;
  1332. ASSERT(hdr.count = -1); (* exclusive locked *)
  1333. IF hdr.awaitingCond.head # NIL THEN (* evaluate the waiting conditions *)
  1334. (* we are holding the lock, so the queue can not change (to do: except in TerminateThis) *)
  1335. c := FindCondition(hdr.awaitingCond) (* interrupts should be on during this call *)
  1336. ELSE
  1337. c := NIL
  1338. END;
  1339. id := Machine.AcquirePreemption ();
  1340. Machine.AcquireObject(hdr.locked);
  1341. r := running[Machine.ID ()];
  1342. IF hdr.lockedBy # r THEN
  1343. Machine.ReleaseObject(hdr.locked);
  1344. Machine.ReleasePreemption;
  1345. ASSERT(hdr.lockedBy = r)
  1346. END;
  1347. IF c = NIL THEN (* no true condition found, check the lock queue *)
  1348. Get(hdr.awaitingLock, t);
  1349. IF t # NIL THEN
  1350. IF StrongChecks THEN
  1351. ASSERT((t.mode = AwaitingLock) & (t.waitingOn = obj))
  1352. END;
  1353. TransferLock(hdr, t)
  1354. ELSE
  1355. hdr.lockedBy := NIL; hdr.count := 0
  1356. END
  1357. ELSE (* true condition found, transfer the lock *)
  1358. TransferLock(hdr, c);
  1359. t := NIL
  1360. END;
  1361. Machine.ReleaseObject(hdr.locked);
  1362. IF (c # NIL) OR (t # NIL) THEN
  1363. Machine.Acquire(Machine.Objects);
  1364. IF c # NIL THEN Enter(c) END;
  1365. IF t # NIL THEN Enter(t) END;
  1366. Machine.Release(Machine.Objects);
  1367. END;
  1368. Machine.ReleasePreemption;
  1369. END UnlockNoPriorityInv;
  1370. (* Unlock a protected object in case priority inversion handling is enabled. Machine.Objects lock is used. *)
  1371. PROCEDURE UnlockPriorityInv(obj: ProtectedObject);
  1372. VAR hdr {UNTRACED}: Heaps.ProtRecBlock; t, c, r: Process; maxWaitingPrio: LONGINT;
  1373. BEGIN
  1374. IF Stats THEN Machine.AtomicInc(Nunlock) END;
  1375. SYSTEM.GET(SYSTEM.VAL(ADDRESS, obj) + Heaps.HeapBlockOffset, hdr);
  1376. IF StrongChecks THEN
  1377. ASSERT(hdr IS Heaps.ProtRecBlock) (* protected object *)
  1378. END;
  1379. ASSERT(hdr.count = -1); (* exclusive locked *)
  1380. IF hdr.awaitingCond.head # NIL THEN (* evaluate the waiting conditions *)
  1381. (* we are holding the lock, so the queue can not change (to do: except in TerminateThis) *)
  1382. c := FindCondition(hdr.awaitingCond) (* interrupts should be on during this call *)
  1383. ELSE
  1384. c := NIL
  1385. END;
  1386. Machine.Acquire(Machine.Objects);
  1387. r := running[Machine.ID ()];
  1388. IF hdr.lockedBy # r THEN
  1389. Machine.Release(Machine.Objects);
  1390. ASSERT(hdr.lockedBy = r)
  1391. END;
  1392. maxWaitingPrio := MaxPrio(hdr.waitingPriorities);
  1393. DEC(r.prioRequests[maxWaitingPrio]);
  1394. r.priority := MaxPrio(r.prioRequests);
  1395. IF c = NIL THEN (* no true condition found, check the lock queue *)
  1396. GetMaxPrio(hdr.awaitingLock, t);
  1397. IF t = NIL THEN
  1398. hdr.lockedBy := NIL; hdr.count := 0
  1399. ELSE
  1400. IF StrongChecks THEN ASSERT((t.mode = AwaitingLock) & (t.waitingOn = obj)) END;
  1401. TransferLock(hdr, t)
  1402. END
  1403. ELSE (* true condition found, transfer the lock *)
  1404. TransferLock(hdr, c);
  1405. t := NIL
  1406. END;
  1407. IF (c # NIL) OR (t # NIL) THEN
  1408. IF c # NIL THEN Enter(c) END;
  1409. IF t # NIL THEN Enter(t) END;
  1410. END;
  1411. Machine.Release(Machine.Objects);
  1412. END UnlockPriorityInv;
  1413. (* Await a condition (kernel call). *)
  1414. (* There are two different procedures for locking a protected object in case of priority inverison handling enabled or disabled due to the different
  1415. locking strategies, i.e. there are no header locks in case of priority inversion handling. *)
  1416. PROCEDURE Await*(cond: Condition; slink: ADDRESS; obj: ProtectedObject; flags: SET);
  1417. BEGIN
  1418. IF HandlePriorityInv THEN
  1419. AwaitPriorityInv(cond, slink, obj, flags)
  1420. ELSE
  1421. AwaitNoPriorityInv(cond, slink, obj, flags)
  1422. END
  1423. END Await;
  1424. (* Await a condition if priority inversion handling is disabled. Header locks, preemption and Machine.Objects locks are used. *)
  1425. PROCEDURE AwaitNoPriorityInv(cond: Condition; slink: ADDRESS; obj: ProtectedObject; flags: SET);
  1426. VAR hdr {UNTRACED}: Heaps.ProtRecBlock; r, c, t: Process; id: LONGINT;
  1427. BEGIN
  1428. IF Stats THEN Machine.AtomicInc(Nawait) END;
  1429. IF 1 IN flags THEN (* compiler did not generate IF *)
  1430. IF Stats THEN Machine.AtomicInc(NawaitNoIF) END;
  1431. IF cond(slink) THEN
  1432. IF Stats THEN Machine.AtomicInc(NawaitTrue) END;
  1433. RETURN (* condition already true *)
  1434. END
  1435. END;
  1436. SYSTEM.GET(SYSTEM.VAL(ADDRESS, obj) + Heaps.HeapBlockOffset, hdr);
  1437. IF StrongChecks THEN
  1438. ASSERT(hdr IS Heaps.ProtRecBlock) (* protected object *)
  1439. END;
  1440. id := Machine.AcquirePreemption ();
  1441. Machine.AcquireObject(hdr.locked); (* must acquire object lock before other locks *)
  1442. r := running[id];
  1443. IF hdr.lockedBy = r THEN (* current process holds exclusive lock *)
  1444. IF StrongChecks THEN ASSERT(hdr.count = -1) END; (* exclusive locked *)
  1445. IF hdr.awaitingCond.head # NIL THEN (* evaluate the waiting conditions *)
  1446. (* we are holding the lock, so the queue can not change (to do: except in TerminateThis) *)
  1447. c := FindCondition(hdr.awaitingCond) (* interrupts should be on during this call *)
  1448. ELSE
  1449. c := NIL
  1450. END;
  1451. IF c = NIL THEN
  1452. Get(hdr.awaitingLock, t);
  1453. IF t = NIL THEN (* none waiting - remove lock *)
  1454. hdr.count := 0; hdr.lockedBy := NIL;
  1455. ELSE (* transfer lock to first waiting process *)
  1456. IF StrongChecks THEN ASSERT(t.mode = AwaitingLock) END;
  1457. TransferLock(hdr, t)
  1458. END;
  1459. ELSE
  1460. TransferLock(hdr, c);
  1461. t := NIL
  1462. END;
  1463. ELSE (* no lock, or some other process may hold the lock, but that's the user's indaba (may be monotonic condition) *)
  1464. Machine.ReleaseObject(hdr.locked);
  1465. Machine.ReleasePreemption;
  1466. HALT(2204) (* await must be exclusive region *)
  1467. END;
  1468. Machine.Acquire(Machine.Objects); (* Put and SwitchTo must be protected *)
  1469. IF c # NIL THEN Enter(c) END;
  1470. IF t # NIL THEN Enter(t) END;
  1471. IF StrongChecks THEN ASSERT(r.waitingOn = NIL) END;
  1472. r.condition := cond; r.condFP := slink;
  1473. r.waitingOn := obj; r.mode := AwaitingCond;
  1474. Put(hdr.awaitingCond, r);
  1475. Machine.ReleaseObject(hdr.locked);
  1476. Machine.ReleasePreemption;
  1477. (* reschedule *)
  1478. SwitchToNew;
  1479. IF StrongChecks THEN
  1480. ASSERT(cond(slink));
  1481. ASSERT(hdr.lockedBy = r) (* lock held again *)
  1482. END
  1483. END AwaitNoPriorityInv;
  1484. (* Await a condition in case priority inversion handling is enabled. Machine.Objects lock is used. *)
  1485. PROCEDURE AwaitPriorityInv(cond: Condition; slink: ADDRESS; obj: ProtectedObject; flags: SET);
  1486. VAR hdr {UNTRACED}: Heaps.ProtRecBlock; r, c, t: Process; id, maxWaitingPrio, prevMaxWaitingPrio: LONGINT;
  1487. BEGIN
  1488. IF Stats THEN Machine.AtomicInc(Nawait) END;
  1489. IF 1 IN flags THEN (* compiler did not generate IF *)
  1490. IF Stats THEN Machine.AtomicInc(NawaitNoIF) END;
  1491. IF cond(slink) THEN
  1492. IF Stats THEN Machine.AtomicInc(NawaitTrue) END;
  1493. RETURN (* condition already true *)
  1494. END
  1495. END;
  1496. SYSTEM.GET(SYSTEM.VAL(ADDRESS, obj) + Heaps.HeapBlockOffset, hdr);
  1497. IF StrongChecks THEN
  1498. ASSERT(hdr IS Heaps.ProtRecBlock) (* protected object *)
  1499. END;
  1500. Machine.Acquire(Machine.Objects);
  1501. id := Machine.ID();
  1502. r := running[id];
  1503. IF hdr.lockedBy = r THEN (* current process holds exclusive lock *)
  1504. IF StrongChecks THEN ASSERT(hdr.count = -1) END; (* exclusive locked *)
  1505. maxWaitingPrio := MaxPrio(hdr.waitingPriorities);
  1506. DEC(r.prioRequests[maxWaitingPrio]);
  1507. r.priority := MaxPrio(r.prioRequests);
  1508. IF hdr.awaitingCond.head # NIL THEN (* evaluate the waiting conditions *)
  1509. (* we are holding the lock, so the queue can not change (to do: except in TerminateThis) *)
  1510. c := FindCondition(hdr.awaitingCond) (* interrupts should be on during this call *)
  1511. ELSE
  1512. c := NIL
  1513. END;
  1514. IF c = NIL THEN
  1515. GetMaxPrio(hdr.awaitingLock, t);
  1516. IF t = NIL THEN (* none waiting - remove lock *)
  1517. hdr.count := 0; hdr.lockedBy := NIL;
  1518. ELSE (* transfer lock to first waiting process *)
  1519. IF StrongChecks THEN ASSERT(t.mode = AwaitingLock) END;
  1520. TransferLock(hdr, t);
  1521. END;
  1522. ELSE (* true condition found, transfer the lock *)
  1523. TransferLock(hdr, c);
  1524. t := NIL;
  1525. END;
  1526. ELSE (* no lock, or some other process may hold the lock, but that's the user's indaba (may be monotonic condition) *)
  1527. Machine.Release(Machine.Objects);
  1528. HALT(2204) (* await must be exclusive region *)
  1529. END;
  1530. IF c # NIL THEN Enter(c) END;
  1531. IF t # NIL THEN Enter(t) END;
  1532. IF StrongChecks THEN ASSERT(r.waitingOn = NIL) END;
  1533. r.condition := cond; r.condFP := slink;
  1534. r.waitingOn := obj; r.mode := AwaitingCond;
  1535. IF hdr.lockedBy # NIL THEN
  1536. prevMaxWaitingPrio := MaxPrio(hdr.waitingPriorities);
  1537. INC(hdr.waitingPriorities[r.priority]);
  1538. IF r.priority > prevMaxWaitingPrio THEN PropagatePrio(hdr, prevMaxWaitingPrio, r.priority) END;
  1539. ELSE (* it may happen that hdr is not locked - in that case no priority propagation takes place *)
  1540. INC(hdr.waitingPriorities[r.priority])
  1541. END;
  1542. Put(hdr.awaitingCond, r);
  1543. (* reschedule *)
  1544. SwitchToNew;
  1545. IF StrongChecks THEN
  1546. ASSERT(cond(slink));
  1547. ASSERT(hdr.lockedBy = r) (* lock held again *)
  1548. END
  1549. END AwaitPriorityInv;
  1550. (** Update the state snapshot of the current process for GC. (for Processors) *)
  1551. PROCEDURE UpdateState;
  1552. VAR t: Process;
  1553. BEGIN (* interrupts off *)
  1554. Machine.Acquire(Machine.Objects);
  1555. t := running[Machine.ID ()];
  1556. IF t # NIL THEN
  1557. t.state.PC := Machine.CurrentPC(); (* ug: required information for GC with meta data for stack inspection *)
  1558. t.state.SP := Machine.CurrentSP(); (* ug: not necessarily needed for GC *)
  1559. t.state.BP := Machine.CurrentBP(); (* ug: necessary information for GC with meta data for stack inspection *)
  1560. END;
  1561. Machine.Release(Machine.Objects)
  1562. END UpdateState;
  1563. (** Start executing user processes. Every processor calls this during initialization. *)
  1564. PROCEDURE Start*;
  1565. VAR id: LONGINT; idle: Idle; new: Process;
  1566. BEGIN (* running at kernel level (not preemptable) *)
  1567. id := Machine.ID (); (* preemption not enabled yet, because we are running at kernel level *)
  1568. NEW(idle); (* create process with MinPriority *)
  1569. Machine.Acquire(Machine.Objects);
  1570. Get(ready.q[MinPriority], new); (* can not use Select here, as it might return a preempted process *)
  1571. ASSERT(~(Preempted IN new.flags)); (* will at least get the Idle process just created *)
  1572. Machine.Release(Machine.Objects);
  1573. running[id] := new; (* schedule new process *)
  1574. new.mode := Running; new.procID := id;
  1575. IF Machine.SSESupport THEN Machine.SSERestoreMin(new.sseAdr)
  1576. ELSE Machine.FPURestoreMin(new.sse)
  1577. END;
  1578. Machine.JumpToUserLevel(new.state.BP)
  1579. END Start;
  1580. (* Initialize module. *)
  1581. PROCEDURE Init; (* can not use NEW *)
  1582. VAR
  1583. lock: PROCEDURE (obj: ProtectedObject; exclusive: BOOLEAN);
  1584. unlock: PROCEDURE (obj: ProtectedObject; dummy: BOOLEAN);
  1585. await: PROCEDURE (cond: Condition; slink: ADDRESS; obj: ProtectedObject; flags: SET);
  1586. create: PROCEDURE (body: Body; priority: LONGINT; flags: SET; obj: ProtectedObject);
  1587. i: LONGINT;
  1588. BEGIN
  1589. ProcessorHLT := NIL;
  1590. maxReady := High; (* scan all queues at start *)
  1591. lowestAllowedPriority := Low; (* normal case, will be set to GCPriority if GC is running *)
  1592. gcBarrier := {};
  1593. FOR i := 0 TO Machine.MaxCPU - 1 DO running[i] := NIL END;
  1594. FOR i := 0 TO NumPriorities - 1 DO rootedProcesses[i] := NIL END;
  1595. FOR i := 0 TO NumIRQ-1 DO processingIRQ[i] := FALSE END;
  1596. nextProcessID := 0; Machine.ticks := 0;
  1597. traceProcess := NIL;
  1598. lock := Lock; unlock := Unlock; await := Await; create := CreateProcess;
  1599. Modules.kernelProc[3] := SYSTEM.VAL (ADDRESS, create); (* 250 *)
  1600. Modules.kernelProc[4] := SYSTEM.VAL (ADDRESS, await); (* 249 *)
  1601. Modules.kernelProc[6] := SYSTEM.VAL (ADDRESS, lock); (* 247 *)
  1602. Modules.kernelProc[7] := SYSTEM.VAL (ADDRESS, unlock); (* 246 *)
  1603. terminate := Terminate;
  1604. trap[0] := Halt;
  1605. trap[1] := HaltUnbreakable;
  1606. trapReturn[0] := HaltReturn;
  1607. trapReturn[1] := HaltUnbreakableReturn;
  1608. END Init;
  1609. PROCEDURE InitEventHandling;
  1610. VAR i: LONGINT; clock: Clock; (* realtimeClock: RealtimeClock; *)
  1611. BEGIN
  1612. FOR i := 0 TO NumIRQ-1 DO
  1613. interrupt[i].root := NIL; interrupt[i].process := NIL
  1614. END;
  1615. (* create normal event list *)
  1616. NEW(event); event.next := event; event.prev := event;
  1617. event.trigger := Machine.ticks + MAX(LONGINT) DIV 2;
  1618. (* create normal timer processes *)
  1619. timer := NIL; NEW(clock);
  1620. END InitEventHandling;
  1621. PROCEDURE InitGCHandling;
  1622. VAR finalizerCaller: FinalizerCaller;
  1623. BEGIN
  1624. gcProcess := NIL; NEW(gcActivity);
  1625. finalizerProcess := NIL; NEW(finalizerCaller);
  1626. END InitGCHandling;
  1627. PROCEDURE InitStats;
  1628. BEGIN
  1629. Nlock := 0; Nunlock := 0; Nawait := 0; NawaitNoIF := 0; NawaitTrue := 0;
  1630. Ncreate := 0; Nterminate := 0; Ncondition := 0; Ncondition1True := 0;
  1631. Ncondition2 := 0; Ncondition2True := 0;
  1632. Ntimeslice := 0; NtimesliceTaken := 0; NtimesliceNothing := 0;
  1633. NtimesliceIdle := 0; NtimesliceKernel := 0; NtimesliceV86 := 0; NtimesliceCritical := 0;
  1634. Npreempt := 0; NpreemptTaken := 0; NpreemptNothing := 0;
  1635. NpreemptKernel := 0; NpreemptV86 := 0; NpreemptCritical := 0;
  1636. Nenter := 0;
  1637. END InitStats;
  1638. PROCEDURE GCStatusFactory(): Heaps.GCStatus;
  1639. VAR gcStatusExt : GCStatusExt;
  1640. BEGIN
  1641. ASSERT(Heaps.gcStatus = NIL);
  1642. NEW(gcStatusExt);
  1643. RETURN gcStatusExt
  1644. END GCStatusFactory;
  1645. BEGIN
  1646. IF Stats THEN InitStats; END;
  1647. Init;
  1648. (* initialize memory management *)
  1649. Machine.UpdateState; (* for gc *)
  1650. Heaps.CollectGarbage(Modules.root); (* still in single-processor mode *)
  1651. (* now NEW can be used *)
  1652. NEW(ready); (* create the ready queues *)
  1653. Machine.InitInterrupts;
  1654. Machine.Start; (* initialize interrupts *)
  1655. InitEventHandling;
  1656. InitGCHandling;
  1657. Heaps.gcStatus := GCStatusFactory();
  1658. (* create a process for rest of init code, which runs at user level *)
  1659. entry := Machine.CurrentBP ();
  1660. SYSTEM.GET (entry+AddressSize, entry); (* return address into linker-generated call table *)
  1661. NEW(initObject);
  1662. NewProcess(SYSTEM.VAL (Body, entry), {Resistant}, initObject, init); (* create init process *)
  1663. init.priority := High;
  1664. init.staticPriority := init.priority;
  1665. (* initialize prioRequests for init process *)
  1666. FOR i := 0 TO LEN(init.prioRequests) - 1 DO init.prioRequests[i] := 0 END;
  1667. INC(init.prioRequests[init.priority]);
  1668. Machine.Acquire(Machine.Objects);
  1669. init.id := -1; Enter(init); init := NIL;
  1670. Machine.Release(Machine.Objects);
  1671. Start (* start it *)
  1672. (* linker call table will end with a call to Terminate. So after executing all module bodies,
  1673. the init process will terminate and other processes created during init will continue running. *)
  1674. END Objects.
  1675. (*
  1676. 24.03.1998 pjm Started
  1677. 06.05.1998 pjm CreateProcess init process, page fault handler
  1678. 06.08.1998 pjm Moved exception interrupt handling here for current process
  1679. 17.08.1998 pjm FindRoots method
  1680. 02.10.1998 pjm Idle process
  1681. 06.11.1998 pjm snapshot
  1682. 25.03.1999 pjm Scope removed
  1683. 28.05.1999 pjm EventHandler object
  1684. 01.06.1999 pjm Fixed InterruptProcess lock error
  1685. 16.06.1999 pjm Flat IRQ priority model to avoid GC deadlock
  1686. 23.06.1999 pjm Flat IRQ priority experiment failed, rather do STI in FieldIRQ to avoid GC deadlock
  1687. 29.06.1999 pjm Timeout in EventHandler object
  1688. 13.01.2000 pjm Overed (Interrupt Objects, Event Handlers, Process ID, Process state, Process mode, Process stack, Await)
  1689. 17.10.2000 pjm Priorities
  1690. 22.10.2003 mib SSE2 extension
  1691. 24.10.2003 phk Priority inversion / cycle counters
  1692. 19.06.2007 ug Garbage Collector using meta data for stack inspection
  1693. *)
  1694. (*
  1695. Location Stack
  1696. Lock Current process
  1697. SwitchTo.A Current process
  1698. SwitchTo.B
  1699. *)