view MasterLoop.c @ 127:24466227d8bb

bugs fixed, code is now compiling
author Merten Sach <msach@mailbox.tu-berlin.de>
date Wed, 07 Sep 2011 17:45:05 +0200
parents d4c881c7f03a
children dbfc8382d546
line source
1 /*
2 * Copyright 2010 OpenSourceStewardshipFoundation
3 *
4 * Licensed under BSD
5 */
9 #include <stdio.h>
10 #include <stddef.h>
12 #include "VMS.h"
13 #include "ProcrContext.h"
14 #include "inter_VMS_request_handlers.h"
16 //===========================================================================
17 void inline
18 stealWorkInto( SchedSlot *currSlot, VMSQueueStruc *readyToAnimateQ,
19 VirtProcr *masterPr);
21 void inline
22 handleInterMasterReq( InterMasterReqst *currReq, void *_semEnv,
23 VirtProcr *masterPr);
25 void inline
26 handleInterVMSCoreReq( InterVMSCoreReqst *currReq, VirtProcr *masterPr);
28 //===========================================================================
32 /*This code is animated by the virtual Master processor.
33 *
34 *Polls each sched slot exactly once, hands any requests made by a newly
35 * done slave to the "request handler" plug-in function
36 *
37 *Any slots that need a virt procr assigned are given to the "schedule"
38 * plug-in function, which tries to assign a virt procr (slave) to it.
39 *
40 *When all slots needing a processor have been given to the schedule plug-in,
41 * a fraction of the procrs successfully scheduled are put into the
42 * work queue, then a continuation of this function is put in, then the rest
43 * of the virt procrs that were successfully scheduled.
44 *
45 *The first thing the continuation does is busy-wait until the previous
46 * animation completes. This is because an (unlikely) continuation may
47 * sneak through queue before previous continuation is done putting second
48 * part of scheduled slaves in, which is the only race condition.
49 *
50 */
52 /*May 29, 2010 -- birth a Master during init so that first core loop to
53 * start running gets it and does all the stuff for a newly born --
54 * from then on, will be doing continuation, but do suspension self
55 * directly at end of master loop
56 *So VMS__init just births the master virtual processor same way it births
57 * all the others -- then does any extra setup needed and puts it into the
58 * work queue.
59 *However means have to make masterEnv a global static volatile.
60 *
61 *
62 *Aug 18, 2010 -- Going to a separate MasterVP for each core, to see if this
63 * avoids the suspected bug in the system stack that causes bizarre faults
64 * at random places in the system code.
65 *
66 *So, this function is coupled to each of the MasterVPs, -- meaning this
67 * function can't rely on a particular stack and frame -- each MasterVP that
68 * animates this function has a different stack.
69 *
70 *At this point, the masterLoop does not write itself into the queue anymore,
71 * instead, the coreLoop acquires the masterLock when it has nothing to
72 * animate, and then animates its own masterLoop. However, still try to put
73 * several AppVPs into the queue to amortize the startup cost of switching
74 * to the MasterVP. Note, don't have to worry about latency of requests much
75 * because most requests generate work for same core -- only latency issue
76 * is case when other cores starved and one core's requests generate work
77 * for them -- so keep max in queue to 3 or 4..
78 */
79 void masterLoop( void *initData, VirtProcr *animatingPr )
80 {
81 int32 slotIdx, numSlotsFilled;
82 VirtProcr *schedVirtPr;
83 SchedSlot *currSlot, **schedSlots;
84 MasterEnv *masterEnv;
85 VMSQueueStruc *readyToAnimateQ;
87 SlaveScheduler slaveScheduler;
88 RequestHandler requestHandler;
89 void *semanticEnv;
91 int32 thisCoresIdx;
92 VirtProcr *masterPr;
93 volatile VirtProcr *volatileMasterPr;
95 volatileMasterPr = animatingPr;
96 masterPr = (VirtProcr*)volatileMasterPr; //used to force re-define after jmp
98 //First animation of each MasterVP will in turn animate this part
99 // of setup code.. (VP creator sets up the stack as if this function
100 // was called normally, but actually get here by jmp)
102 //Sept 2011
103 //Old code jumped directly to this point, but doesn't work on x64
104 // So, just make this an endless loop, and do assembly function at end
105 // that saves its own return addr, then jumps to core_loop.
106 while(1)
107 {
109 //============================= MEASUREMENT STUFF ========================
110 #ifdef MEAS__TIME_MASTER
111 //Total Master time includes one coreloop time -- just assume the core
112 // loop time is same for Master as is for AppVPs, even though it may be
113 // smaller due to higher predictability of the fixed jmp.
114 saveLowTimeStampCountInto( masterPr->startMasterTSCLow );
115 #endif
116 //========================================================================
118 masterEnv = (MasterEnv*)_VMSMasterEnv;
120 //GCC may optimize so doesn't always re-define from frame-storage
121 masterPr = (VirtProcr*)volatileMasterPr; //on stack, reload after jmp
122 thisCoresIdx = masterPr->coreAnimatedBy;
123 readyToAnimateQ = masterEnv->readyToAnimateQs[thisCoresIdx];
124 schedSlots = masterEnv->allSchedSlots[thisCoresIdx];
126 requestHandler = masterEnv->requestHandler;
127 slaveScheduler = masterEnv->slaveScheduler;
128 semanticEnv = masterEnv->semanticEnv;
130 //First, check for requests from other MasterVPs, and handle them
131 InterMasterReqst* currReq = masterEnv->interMasterRequestsFor[thisCoresIdx];
132 while(currReq)
133 {
134 handleInterMasterReq( currReq, semanticEnv, masterPr );
135 currReq = currReq->nextReqst;
136 }
138 //Now, take care of the SlaveVPs
139 //Go through the slots -- if Slave there newly suspended, handle its request
140 // then, either way, ask assigner to fill each slot
141 numSlotsFilled = 0;
142 for( slotIdx = 0; slotIdx < NUM_SCHED_SLOTS; slotIdx++)
143 {
144 currSlot = schedSlots[ slotIdx ];
146 if( currSlot->workIsDone )
147 {
148 currSlot->workIsDone = FALSE;
149 currSlot->needsProcrAssigned = TRUE;
151 //process requests from slave to master
152 //====================== MEASUREMENT STUFF ===================
153 #ifdef MEAS__TIME_PLUGIN
154 int32 startStamp1, endStamp1;
155 saveLowTimeStampCountInto( startStamp1 );
156 #endif
157 //============================================================
158 (*requestHandler)( currSlot->procrAssignedToSlot, semanticEnv );
159 //====================== MEASUREMENT STUFF ===================
160 #ifdef MEAS__TIME_PLUGIN
161 saveLowTimeStampCountInto( endStamp1 );
162 addIntervalToHist( startStamp1, endStamp1,
163 _VMSMasterEnv->reqHdlrLowTimeHist );
164 addIntervalToHist( startStamp1, endStamp1,
165 _VMSMasterEnv->reqHdlrHighTimeHist );
166 #endif
167 //============================================================
168 }
169 if( currSlot->needsProcrAssigned )
170 { //give slot a new virt procr
171 schedVirtPr =
172 (*slaveScheduler)( semanticEnv, thisCoresIdx );
174 if( schedVirtPr != NULL )
175 { currSlot->procrAssignedToSlot = schedVirtPr;
176 schedVirtPr->schedSlot = currSlot;
177 currSlot->needsProcrAssigned = FALSE;
178 numSlotsFilled += 1;
180 writeVMSQ( schedVirtPr, readyToAnimateQ );
181 }
182 }
183 }
186 #ifdef USE_WORK_STEALING
187 //If no slots filled, means no more work, look for work to steal.
188 if( numSlotsFilled == 0 )
189 { gateProtected_stealWorkInto( currSlot, readyToAnimateQ, masterPr );
190 }
191 #endif
194 #ifdef MEAS__TIME_MASTER
195 saveLowTimeStampCountInto( masterPr->endMasterTSCLow );
196 #endif
198 masterSwitchToCoreLoop(animatingPr);
199 flushRegisters();
200 }//while(1) MasterLoop
201 }
203 /*This is for inter-master communication. Either the master itself or
204 * the plugin sends one of these requests. Some are handled here, by the
205 * master_loop, others are handed off to the plugin.
206 */
207 void inline
208 handleInterMasterReq( InterMasterReqst *currReq, void *_semEnv,
209 VirtProcr *masterPr )
210 {
212 switch( currReq->reqType )
213 {
214 case destVMSCore:
215 handleInterVMSCoreReq( (InterVMSCoreReqst *)currReq, masterPr);
216 break;
217 case destPlugin:
218 _VMSMasterEnv->interPluginReqHdlr( ((InterPluginReqst *)currReq)->pluginReq,
219 _semEnv );
220 break;
221 default:
222 break;
223 }
224 }
226 void inline
227 handleInterVMSCoreReq( InterVMSCoreReqst *currReq, VirtProcr *masterPr )
228 {
229 switch( currReq->reqType )
230 {
231 case transfer_free_ptr: handleTransferFree( currReq, masterPr );
232 break;
233 default:
234 break;
235 }
236 }
238 /*Work Stealing Alg -- racy one
239 *This algorithm has a race condition -- the coreloops are accessing their
240 * own queues at the same time that this work-stealer on a different core
241 * is trying to.
242 *The second stealing alg, below, protects against this.
243 */
244 void inline
245 stealWorkInto( SchedSlot *currSlot, VMSQueueStruc *readyToAnimateQ,
246 VirtProcr *masterPr )
247 {
248 VirtProcr *stolenPr;
249 int32 coreIdx, i;
250 VMSQueueStruc *currQ;
252 stolenPr = NULL;
253 coreIdx = masterPr->coreAnimatedBy;
254 for( i = 0; i < NUM_CORES -1; i++ )
255 {
256 if( coreIdx >= NUM_CORES -1 )
257 { coreIdx = 0;
258 }
259 else
260 { coreIdx++;
261 }
262 currQ = _VMSMasterEnv->readyToAnimateQs[coreIdx];
263 if( numInVMSQ( currQ ) > 0 )
264 { stolenPr = readVMSQ (currQ );
265 break;
266 }
267 }
269 if( stolenPr != NULL )
270 { currSlot->procrAssignedToSlot = stolenPr;
271 stolenPr->schedSlot = currSlot;
272 currSlot->needsProcrAssigned = FALSE;
274 writeVMSQ( stolenPr, readyToAnimateQ );
275 }
276 }
278 /*Work Stealing alg -- protected one
279 *This algorithm makes the common case fast. Make the coreloop passive,
280 * and show its progress. Make the stealer control a gate that coreloop
281 * has to pass.
282 *To avoid interference, only one stealer at a time. Use a global
283 * stealer-lock.
284 *
285 *The pattern is based on a gate -- stealer shuts the gate, then monitors
286 * to be sure any already past make it all the way out, before starting.
287 *So, have a "progress" measure just before the gate, then have two after it,
288 * one is in a "waiting room" outside the gate, the other is at the exit.
289 *Then, the stealer first shuts the gate, then checks the progress measure
290 * outside it, then looks to see if the progress measure at the exit is the
291 * same. If yes, it knows the protected area is empty 'cause no other way
292 * to get in and the last to get in also exited.
293 *If the progress measure at the exit is not the same, then the stealer goes
294 * into a loop checking both the waiting-area and the exit progress-measures
295 * until one of them shows the same as the measure outside the gate. Might
296 * as well re-read the measure outside the gate each go around, just to be
297 * sure. It is guaranteed that one of the two will eventually match the one
298 * outside the gate.
299 *
300 *Here's an informal proof of correctness:
301 *The gate can be closed at any point, and have only four cases:
302 * 1) coreloop made it past the gate-closing but not yet past the exit
303 * 2) coreloop made it past the pre-gate progress update but not yet past
304 * the gate,
305 * 3) coreloop is right before the pre-gate update
306 * 4) coreloop is past the exit and far from the pre-gate update.
307 *
308 * Covering the cases in reverse order,
309 * 4) is not a problem -- stealer will read pre-gate progress, see that it
310 * matches exit progress, and the gate is closed, so stealer can proceed.
311 * 3) stealer will read pre-gate progress just after coreloop updates it..
312 * so stealer goes into a loop until the coreloop causes wait-progress
313 * to match pre-gate progress, so then stealer can proceed
314 * 2) same as 3..
315 * 1) stealer reads pre-gate progress, sees that it's different than exit,
316 * so goes into loop until exit matches pre-gate, now it knows coreloop
317 * is not in protected and cannot get back in, so can proceed.
318 *
319 *Implementation for the stealer:
320 *
321 *First, acquire the stealer lock -- only cores with no work to do will
322 * compete to steal, so not a big performance penalty having only one --
323 * will rarely have multiple stealers in a system with plenty of work -- and
324 * in a system with little work, it doesn't matter.
325 *
326 *Note, have single-reader, single-writer pattern for all variables used to
327 * communicate between stealer and victims
328 *
329 *So, scan the queues of the core loops, until find non-empty. Each core
330 * has its own list that it scans. The list goes in order from closest to
331 * furthest core, so it steals first from close cores. Later can add
332 * taking info from the app about overlapping footprints, and scan all the
333 * others then choose work with the most footprint overlap with the contents
334 * of this core's cache.
335 *
336 *Now, have a victim want to take work from. So, shut the gate in that
337 * coreloop, by setting the "gate closed" var on its stack to TRUE.
338 *Then, read the core's pre-gate progress and compare to the core's exit
339 * progress.
340 *If same, can proceed to take work from the coreloop's queue. When done,
341 * write FALSE to gate closed var.
342 *If different, then enter a loop that reads the pre-gate progress, then
343 * compares to exit progress then to wait progress. When one of two
344 * matches, proceed. Take work from the coreloop's queue. When done,
345 * write FALSE to the gate closed var.
346 *
347 */
348 void inline
349 gateProtected_stealWorkInto( SchedSlot *currSlot,
350 VMSQueueStruc *myReadyToAnimateQ,
351 VirtProcr *masterPr )
352 {
353 VirtProcr *stolenPr;
354 int32 coreIdx, i, haveAVictim, gotLock;
355 VMSQueueStruc *victimsQ;
357 volatile GateStruc *vicGate;
358 int32 coreMightBeInProtected;
362 //see if any other cores have work available to steal
363 haveAVictim = FALSE;
364 coreIdx = masterPr->coreAnimatedBy;
365 for( i = 0; i < NUM_CORES -1; i++ )
366 {
367 if( coreIdx >= NUM_CORES -1 )
368 { coreIdx = 0;
369 }
370 else
371 { coreIdx++;
372 }
373 victimsQ = _VMSMasterEnv->readyToAnimateQs[coreIdx];
374 if( numInVMSQ( victimsQ ) > 0 )
375 { haveAVictim = TRUE;
376 vicGate = _VMSMasterEnv->workStealingGates[ coreIdx ];
377 break;
378 }
379 }
380 if( !haveAVictim ) return; //no work to steal, exit
382 //have a victim core, now get the stealer-lock
383 gotLock =__sync_bool_compare_and_swap( &(_VMSMasterEnv->workStealingLock),
384 UNLOCKED, LOCKED );
385 if( !gotLock ) return; //go back to core loop, which will re-start master
388 //====== Start Gate-protection =======
389 vicGate->gateClosed = TRUE;
390 coreMightBeInProtected= vicGate->preGateProgress != vicGate->exitProgress;
391 while( coreMightBeInProtected )
392 { //wait until sure
393 if( vicGate->preGateProgress == vicGate->waitProgress )
394 coreMightBeInProtected = FALSE;
395 if( vicGate->preGateProgress == vicGate->exitProgress )
396 coreMightBeInProtected = FALSE;
397 }
399 stolenPr = readVMSQ ( victimsQ );
401 vicGate->gateClosed = FALSE;
402 //======= End Gate-protection =======
405 if( stolenPr != NULL ) //victim could have been in protected and took it
406 { currSlot->procrAssignedToSlot = stolenPr;
407 stolenPr->schedSlot = currSlot;
408 currSlot->needsProcrAssigned = FALSE;
410 writeVMSQ( stolenPr, myReadyToAnimateQ );
411 }
413 //unlock the work stealing lock
414 _VMSMasterEnv->workStealingLock = UNLOCKED;
415 }