Mercurial > cgi-bin > hgwebdir.cgi > VMS > VMS_Implementations > VMS_impls > VMS__MC_shared_impl
view MasterLoop.c @ 134:a9b72021f053
Distributed memory management w/o free requests working
| author | Merten Sach <msach@mailbox.tu-berlin.de> |
|---|---|
| date | Fri, 16 Sep 2011 16:19:24 +0200 |
| parents | dbfc8382d546 |
| children | 0b49fd35afc1 |
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 "scheduling.h"
15 #include "inter_VMS_request_handlers.h"
17 //===========================================================================
18 void inline
19 stealWorkInto( SchedSlot *currSlot, VMSQueueStruc *readyToAnimateQ,
20 VirtProcr *masterPr);
22 void inline
23 handleInterMasterReq( InterMasterReqst *currReq, void *_semEnv,
24 VirtProcr *masterPr);
26 void inline
27 handleInterVMSCoreReq( InterVMSCoreReqst *currReq, VirtProcr *masterPr);
29 //===========================================================================
33 /*This code is animated by the virtual Master processor.
34 *
35 *Polls each sched slot exactly once, hands any requests made by a newly
36 * done slave to the "request handler" plug-in function
37 *
38 *Any slots that need a virt procr assigned are given to the "schedule"
39 * plug-in function, which tries to assign a virt procr (slave) to it.
40 *
41 *When all slots needing a processor have been given to the schedule plug-in,
42 * a fraction of the procrs successfully scheduled are put into the
43 * work queue, then a continuation of this function is put in, then the rest
44 * of the virt procrs that were successfully scheduled.
45 *
46 *The first thing the continuation does is busy-wait until the previous
47 * animation completes. This is because an (unlikely) continuation may
48 * sneak through queue before previous continuation is done putting second
49 * part of scheduled slaves in, which is the only race condition.
50 *
51 */
53 /*May 29, 2010 -- birth a Master during init so that first core loop to
54 * start running gets it and does all the stuff for a newly born --
55 * from then on, will be doing continuation, but do suspension self
56 * directly at end of master loop
57 *So VMS__init just births the master virtual processor same way it births
58 * all the others -- then does any extra setup needed and puts it into the
59 * work queue.
60 *However means have to make masterEnv a global static volatile.
61 *
62 *
63 *Aug 18, 2010 -- Going to a separate MasterVP for each core, to see if this
64 * avoids the suspected bug in the system stack that causes bizarre faults
65 * at random places in the system code.
66 *
67 *So, this function is coupled to each of the MasterVPs, -- meaning this
68 * function can't rely on a particular stack and frame -- each MasterVP that
69 * animates this function has a different stack.
70 *
71 *At this point, the masterLoop does not write itself into the queue anymore,
72 * instead, the coreLoop acquires the masterLock when it has nothing to
73 * animate, and then animates its own masterLoop. However, still try to put
74 * several AppVPs into the queue to amortize the startup cost of switching
75 * to the MasterVP. Note, don't have to worry about latency of requests much
76 * because most requests generate work for same core -- only latency issue
77 * is case when other cores starved and one core's requests generate work
78 * for them -- so keep max in queue to 3 or 4..
79 */
80 void masterLoop( void *initData, VirtProcr *animatingPr )
81 {
82 int32 slotIdx, numSlotsFilled;
83 VirtProcr *schedVirtPr;
84 SchedSlot *currSlot, **schedSlots;
85 MasterEnv *masterEnv;
86 VMSQueueStruc *readyToAnimateQ;
88 SlaveScheduler slaveScheduler;
89 RequestHandler requestHandler;
90 void *semanticEnv;
92 int32 thisCoresIdx;
93 VirtProcr *masterPr;
94 volatile VirtProcr *volatileMasterPr;
96 volatileMasterPr = animatingPr;
97 masterPr = (VirtProcr*)volatileMasterPr; //used to force re-define after jmp
98 masterEnv = (MasterEnv*)_VMSMasterEnv;
100 //First animation of each MasterVP will in turn animate this part
101 // of setup code.. (VP creator sets up the stack as if this function
102 // was called normally, but actually get here by jmp)
104 //Sept 2011
105 //Old code jumped directly to this point, but doesn't work on x64
106 // So, just make this an endless loop, and do assembly function at end
107 // that saves its own return addr, then jumps to core_loop.
108 while(1)
109 {
110 //============================= MEASUREMENT STUFF ========================
111 #ifdef MEAS__TIME_MASTER
112 //Total Master time includes one coreloop time -- just assume the core
113 // loop time is same for Master as is for AppVPs, even though it may be
114 // smaller due to higher predictability of the fixed jmp.
115 saveLowTimeStampCountInto( masterPr->startMasterTSCLow );
116 #endif
117 //========================================================================
119 //GCC may optimize so doesn't always re-define from frame-storage
120 thisCoresIdx = masterPr->coreAnimatedBy;
121 masterEnv->currentMasterProcrID = thisCoresIdx;
122 readyToAnimateQ = masterEnv->readyToAnimateQs[thisCoresIdx];
123 schedSlots = masterEnv->allSchedSlots[thisCoresIdx];
125 requestHandler = masterEnv->requestHandler;
126 slaveScheduler = masterEnv->slaveScheduler;
127 semanticEnv = masterEnv->semanticEnv;
129 //First, check for requests from other MasterVPs, and handle them
130 InterMasterReqst* currReq = masterEnv->interMasterRequestsFor[thisCoresIdx];
131 while(currReq)
132 {
133 handleInterMasterReq( currReq, semanticEnv, masterPr );
134 currReq = currReq->nextReqst;
135 }
137 //Now, take care of the SlaveVPs
138 //Go through the slots -- if Slave there newly suspended, handle its request
139 // then, either way, ask assigner to fill each slot
140 numSlotsFilled = 0;
141 for( slotIdx = 0; slotIdx < NUM_SCHED_SLOTS; slotIdx++)
142 {
143 currSlot = schedSlots[ slotIdx ];
145 if( currSlot->workIsDone )
146 {
147 currSlot->workIsDone = FALSE;
148 currSlot->needsProcrAssigned = TRUE;
150 //process requests from slave to master
151 //====================== MEASUREMENT STUFF ===================
152 #ifdef MEAS__TIME_PLUGIN
153 int32 startStamp1, endStamp1;
154 saveLowTimeStampCountInto( startStamp1 );
155 #endif
156 //============================================================
157 (*requestHandler)( currSlot->procrAssignedToSlot, semanticEnv );
158 //====================== MEASUREMENT STUFF ===================
159 #ifdef MEAS__TIME_PLUGIN
160 saveLowTimeStampCountInto( endStamp1 );
161 addIntervalToHist( startStamp1, endStamp1,
162 _VMSMasterEnv->reqHdlrLowTimeHist );
163 addIntervalToHist( startStamp1, endStamp1,
164 _VMSMasterEnv->reqHdlrHighTimeHist );
165 #endif
166 //============================================================
167 }
168 if( currSlot->needsProcrAssigned )
169 { //give slot a new virt procr
170 schedVirtPr =
171 (*slaveScheduler)( semanticEnv, thisCoresIdx );
173 if( schedVirtPr != NULL )
174 { currSlot->procrAssignedToSlot = schedVirtPr;
175 schedVirtPr->schedSlot = currSlot;
176 schedVirtPr->coreAnimatedBy = thisCoresIdx;
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 }
