view MasterLoop.c @ 121:73acc2140742

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