view MasterLoop.c @ 212:df00af7eb307

try 40 cores
author Nina Engelhardt <nengel@mailbox.tu-berlin.de>
date Fri, 09 Mar 2012 18:58:33 +0100
parents 20358f56e498
children
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"
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
92 int vpid,task;
94 //First animation of each MasterVP will in turn animate this part
95 // of setup code.. (VP creator sets up the stack as if this function
96 // was called normally, but actually get here by jmp)
97 //So, setup values about stack ptr, jmp pt and all that
98 //masterPr->nextInstrPt = &&masterLoopStartPt;
101 //Note, got rid of writing the stack and frame ptr up here, because
102 // only one
103 // core can ever animate a given MasterVP, so don't need to communicate
104 // new frame and stack ptr to the MasterVP storage before a second
105 // version of that MasterVP can get animated on a different core.
106 //Also got rid of the busy-wait.
109 //masterLoopStartPt:
110 while(1){
112 //============================= MEASUREMENT STUFF ========================
113 #ifdef MEAS__TIME_MASTER
114 //Total Master time includes one coreloop time -- just assume the core
115 // loop time is same for Master as for AppVPs, even though it may be
116 // smaller due to higher predictability of the fixed jmp.
117 saveLowTimeStampCountInto( masterPr->startMasterTSCLow );
118 #endif
120 //========================================================================
122 masterEnv = (MasterEnv*)_VMSMasterEnv;
124 //GCC may optimize so doesn't always re-define from frame-storage
125 masterPr = (VirtProcr*)volatileMasterPr; //just to make 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 #ifdef MEAS__PERF_COUNTERS
135 CounterHandler counterHandler = masterEnv->counterHandler;
136 #endif
137 //
138 //Poll each slot's Done flag
139 numSlotsFilled = 0;
140 for( slotIdx = 0; slotIdx < NUM_SCHED_SLOTS; slotIdx++)
141 {
142 currSlot = schedSlots[ slotIdx ];
144 if( currSlot->workIsDone )
145 {
146 currSlot->workIsDone = FALSE;
147 currSlot->needsProcrAssigned = TRUE;
149 //process requests from slave to master
150 //====================== MEASUREMENT STUFF ===================
151 #ifdef MEAS__TIME_PLUGIN
152 int32 startStamp1, endStamp1;
153 saveLowTimeStampCountInto( startStamp1 );
154 #endif
155 #ifdef MEAS__PERF_COUNTERS
156 /* Request Handler may call resume() on the VP, but we want to
157 * account the whole interval to the same task. Therefore, need
158 * to save task ID at the beginning.
159 *
160 * Using this value as "end of AppResponder Invocation Time"
161 * is possible if there is only one SchedSlot per core -
162 * invoking processor is last to be treated here! If more than
163 * one slot, MasterLoop processing time for all but the last VP
164 * would be erroneously counted as invocation time.
165 */
166 vpid = currSlot->procrAssignedToSlot->procrID;
167 task = currSlot->procrAssignedToSlot->numTimesScheduled;
168 uint64 cycles, instrs;
169 saveCyclesAndInstrs(thisCoresIdx,cycles, instrs);
170 (*counterHandler)(AppResponder_start,vpid,task,currSlot->procrAssignedToSlot,cycles,instrs);
171 #endif
172 //============================================================
173 (*requestHandler)( currSlot->procrAssignedToSlot, semanticEnv );
174 //====================== MEASUREMENT STUFF ===================
175 #ifdef MEAS__TIME_PLUGIN
176 saveLowTimeStampCountInto( endStamp1 );
177 addIntervalToHist( startStamp1, endStamp1,
178 _VMSMasterEnv->reqHdlrLowTimeHist );
179 addIntervalToHist( startStamp1, endStamp1,
180 _VMSMasterEnv->reqHdlrHighTimeHist );
181 #endif
182 #ifdef MEAS__PERF_COUNTERS
183 //use previous task ID here (may or may not be the same as current VP state)
184 uint64 cycles2,instrs2;
185 saveCyclesAndInstrs(thisCoresIdx,cycles2, instrs2);
186 (*counterHandler)(AppResponder_end,vpid,task,currSlot->procrAssignedToSlot,cycles2,instrs2);
187 (*counterHandler)(Timestamp_end,vpid,task,currSlot->procrAssignedToSlot,rdtsc(),0);
188 #endif
189 //============================================================
190 }
191 if( currSlot->needsProcrAssigned )
192 { //give slot a new virt procr
193 #ifdef MEAS__PERF_COUNTERS
194 //start assigner
195 /* Don't know who to account time to yet - goes to assigned VP
196 * after the call.
197 */
198 int empty = FALSE;
199 if(currSlot->procrAssignedToSlot == NULL){
200 empty= TRUE;
201 }
202 uint64 tmp_cycles;
203 uint64 tmp_instrs;
204 saveCyclesAndInstrs(thisCoresIdx,tmp_cycles,tmp_instrs);
205 uint64 tsc = rdtsc();
206 if(vpid > 0) {
207 (*counterHandler)(NextAssigner_start,vpid,task,currSlot->procrAssignedToSlot,tmp_cycles,tmp_instrs);
208 vpid = 0;
209 task = 0;
210 }
211 #endif
212 schedVirtPr =
213 (*slaveScheduler)( semanticEnv, thisCoresIdx, slotIdx );
215 if( schedVirtPr != NULL )
216 { currSlot->procrAssignedToSlot = schedVirtPr;
217 schedVirtPr->schedSlot = currSlot;
218 currSlot->needsProcrAssigned = FALSE;
219 numSlotsFilled += 1;
221 writeVMSQ( schedVirtPr, readyToAnimateQ );
223 #ifdef MEAS__PERF_COUNTERS
224 uint64 cycles;
225 uint64 instrs;
226 saveCyclesAndInstrs(thisCoresIdx,cycles,instrs);
228 if(empty){
229 (*counterHandler)(AssignerInvocation_start,schedVirtPr->procrID,schedVirtPr->numTimesScheduled,schedVirtPr,masterEnv->start_master_lock[thisCoresIdx][0],masterEnv->start_master_lock[thisCoresIdx][1]);
230 }
231 (*counterHandler)(Timestamp_start,schedVirtPr->procrID,schedVirtPr->numTimesScheduled,schedVirtPr,tsc,0);
232 (*counterHandler)(Assigner_start,schedVirtPr->procrID,schedVirtPr->numTimesScheduled,schedVirtPr,tmp_cycles,tmp_instrs);
233 (*counterHandler)(Assigner_end,schedVirtPr->procrID,schedVirtPr->numTimesScheduled,schedVirtPr,cycles,instrs);
234 #endif
235 }
236 }
238 }
241 #ifdef USE_WORK_STEALING
242 //If no slots filled, means no more work, look for work to steal.
243 if( numSlotsFilled == 0 )
244 { gateProtected_stealWorkInto( currSlot, readyToAnimateQ, masterPr );
245 }
246 #endif
249 #ifdef MEAS__TIME_MASTER
250 saveLowTimeStampCountInto( masterPr->endMasterTSCLow );
251 #endif
253 masterSwitchToCoreLoop(animatingPr);
254 flushRegisters();
255 }//MasterLoop
258 }
262 /*This has a race condition -- the coreloops are accessing their own queues
263 * at the same time that this work-stealer on a different core is trying to
264 */
265 void inline
266 stealWorkInto( SchedSlot *currSlot, VMSQueueStruc *readyToAnimateQ,
267 VirtProcr *masterPr )
268 {
269 VirtProcr *stolenPr;
270 int32 coreIdx, i;
271 VMSQueueStruc *currQ;
273 stolenPr = NULL;
274 coreIdx = masterPr->coreAnimatedBy;
275 for( i = 0; i < NUM_CORES -1; i++ )
276 {
277 if( coreIdx >= NUM_CORES -1 )
278 { coreIdx = 0;
279 }
280 else
281 { coreIdx++;
282 }
283 currQ = _VMSMasterEnv->readyToAnimateQs[coreIdx];
284 if( numInVMSQ( currQ ) > 0 )
285 { stolenPr = readVMSQ (currQ );
286 break;
287 }
288 }
290 if( stolenPr != NULL )
291 { currSlot->procrAssignedToSlot = stolenPr;
292 stolenPr->schedSlot = currSlot;
293 currSlot->needsProcrAssigned = FALSE;
295 writeVMSQ( stolenPr, readyToAnimateQ );
296 }
297 }
299 /*This algorithm makes the common case fast. Make the coreloop passive,
300 * and show its progress. Make the stealer control a gate that coreloop
301 * has to pass.
302 *To avoid interference, only one stealer at a time. Use a global
303 * stealer-lock.
304 *
305 *The pattern is based on a gate -- stealer shuts the gate, then monitors
306 * to be sure any already past make it all the way out, before starting.
307 *So, have a "progress" measure just before the gate, then have two after it,
308 * one is in a "waiting room" outside the gate, the other is at the exit.
309 *Then, the stealer first shuts the gate, then checks the progress measure
310 * outside it, then looks to see if the progress measure at the exit is the
311 * same. If yes, it knows the protected area is empty 'cause no other way
312 * to get in and the last to get in also exited.
313 *If the progress measure at the exit is not the same, then the stealer goes
314 * into a loop checking both the waiting-area and the exit progress-measures
315 * until one of them shows the same as the measure outside the gate. Might
316 * as well re-read the measure outside the gate each go around, just to be
317 * sure. It is guaranteed that one of the two will eventually match the one
318 * outside the gate.
319 *
320 *Here's an informal proof of correctness:
321 *The gate can be closed at any point, and have only four cases:
322 * 1) coreloop made it past the gate-closing but not yet past the exit
323 * 2) coreloop made it past the pre-gate progress update but not yet past
324 * the gate,
325 * 3) coreloop is right before the pre-gate update
326 * 4) coreloop is past the exit and far from the pre-gate update.
327 *
328 * Covering the cases in reverse order,
329 * 4) is not a problem -- stealer will read pre-gate progress, see that it
330 * matches exit progress, and the gate is closed, so stealer can proceed.
331 * 3) stealer will read pre-gate progress just after coreloop updates it..
332 * so stealer goes into a loop until the coreloop causes wait-progress
333 * to match pre-gate progress, so then stealer can proceed
334 * 2) same as 3..
335 * 1) stealer reads pre-gate progress, sees that it's different than exit,
336 * so goes into loop until exit matches pre-gate, now it knows coreloop
337 * is not in protected and cannot get back in, so can proceed.
338 *
339 *Implementation for the stealer:
340 *
341 *First, acquire the stealer lock -- only cores with no work to do will
342 * compete to steal, so not a big performance penalty having only one --
343 * will rarely have multiple stealers in a system with plenty of work -- and
344 * in a system with little work, it doesn't matter.
345 *
346 *Note, have single-reader, single-writer pattern for all variables used to
347 * communicate between stealer and victims
348 *
349 *So, scan the queues of the core loops, until find non-empty. Each core
350 * has its own list that it scans. The list goes in order from closest to
351 * furthest core, so it steals first from close cores. Later can add
352 * taking info from the app about overlapping footprints, and scan all the
353 * others then choose work with the most footprint overlap with the contents
354 * of this core's cache.
355 *
356 *Now, have a victim want to take work from. So, shut the gate in that
357 * coreloop, by setting the "gate closed" var on its stack to TRUE.
358 *Then, read the core's pre-gate progress and compare to the core's exit
359 * progress.
360 *If same, can proceed to take work from the coreloop's queue. When done,
361 * write FALSE to gate closed var.
362 *If different, then enter a loop that reads the pre-gate progress, then
363 * compares to exit progress then to wait progress. When one of two
364 * matches, proceed. Take work from the coreloop's queue. When done,
365 * write FALSE to the gate closed var.
366 *
367 */
368 void inline
369 gateProtected_stealWorkInto( SchedSlot *currSlot,
370 VMSQueueStruc *myReadyToAnimateQ,
371 VirtProcr *masterPr )
372 {
373 VirtProcr *stolenPr;
374 int32 coreIdx, i, haveAVictim, gotLock;
375 VMSQueueStruc *victimsQ;
377 volatile GateStruc *vicGate;
378 int32 coreMightBeInProtected;
382 //see if any other cores have work available to steal
383 haveAVictim = FALSE;
384 coreIdx = masterPr->coreAnimatedBy;
385 for( i = 0; i < NUM_CORES -1; i++ )
386 {
387 if( coreIdx >= NUM_CORES -1 )
388 { coreIdx = 0;
389 }
390 else
391 { coreIdx++;
392 }
393 victimsQ = _VMSMasterEnv->readyToAnimateQs[coreIdx];
394 if( numInVMSQ( victimsQ ) > 0 )
395 { haveAVictim = TRUE;
396 vicGate = _VMSMasterEnv->workStealingGates[ coreIdx ];
397 break;
398 }
399 }
400 if( !haveAVictim ) return; //no work to steal, exit
402 //have a victim core, now get the stealer-lock
403 gotLock =__sync_bool_compare_and_swap( &(_VMSMasterEnv->workStealingLock),
404 UNLOCKED, LOCKED );
405 if( !gotLock ) return; //go back to core loop, which will re-start master
408 //====== Start Gate-protection =======
409 vicGate->gateClosed = TRUE;
410 coreMightBeInProtected= vicGate->preGateProgress != vicGate->exitProgress;
411 while( coreMightBeInProtected )
412 { //wait until sure
413 if( vicGate->preGateProgress == vicGate->waitProgress )
414 coreMightBeInProtected = FALSE;
415 if( vicGate->preGateProgress == vicGate->exitProgress )
416 coreMightBeInProtected = FALSE;
417 }
419 stolenPr = readVMSQ ( victimsQ );
421 vicGate->gateClosed = FALSE;
422 //======= End Gate-protection =======
425 if( stolenPr != NULL ) //victim could have been in protected and taken
426 { currSlot->procrAssignedToSlot = stolenPr;
427 stolenPr->schedSlot = currSlot;
428 currSlot->needsProcrAssigned = FALSE;
430 writeVMSQ( stolenPr, myReadyToAnimateQ );
431 }
433 //unlock the work stealing lock
434 _VMSMasterEnv->workStealingLock = UNLOCKED;
435 }