view VMS.c @ 24:2b161e1a50ee

1st working version -- as far as can tell due to SEH bugs
author Me
date Wed, 07 Jul 2010 13:15:54 -0700
parents 1dbc7f6e3e67
children c556193f7211
line source
1 /*
2 * Copyright 2010 OpenSourceCodeStewardshipFoundation
3 *
4 * Licensed under BSD
5 */
7 #include <stdio.h>
8 #include <stdlib.h>
9 #include <malloc.h>
11 #include "VMS.h"
12 #include "Queue_impl/BlockingQueue.h"
15 //===========================================================================
16 void
17 shutdownFn( void *dummy, VirtProcr *dummy2 );
19 void
20 create_sched_slots( MasterEnv *masterEnv );
22 //===========================================================================
24 /*Setup has two phases:
25 * 1) Semantic layer first calls init_VMS, which creates masterEnv, and puts
26 * the master virt procr into the work-queue, ready for first "call"
27 * 2) Semantic layer then does its own init, which creates the seed virt
28 * procr inside the semantic layer, ready to schedule it when
29 * asked by the first run of the masterLoop.
30 *
31 *This part is bit weird because VMS really wants to be "always there", and
32 * have applications attach and detach.. for now, this VMS is part of
33 * the app, so the VMS system starts up as part of running the app.
34 *
35 *The semantic layer is isolated from the VMS internals by making the
36 * semantic layer do setup to a state that it's ready with its
37 * initial virt procrs, ready to schedule them to slots when the masterLoop
38 * asks. Without this pattern, the semantic layer's setup would
39 * have to modify slots directly to assign the initial virt-procrs, and put
40 * them into the workQ itself, breaking the isolation completely.
41 *
42 *
43 *The semantic layer creates the initial virt procr(s), and adds its
44 * own environment to masterEnv, and fills in the pointers to
45 * the requestHandler and slaveScheduler plug-in functions
46 */
48 /*This allocates VMS data structures, populates the master VMSProc,
49 * and master environment, and returns the master environment to the semantic
50 * layer.
51 */
52 void
53 VMS__init()
54 { MasterEnv *masterEnv;
55 CASQueueStruc *workQ;
57 //Make the central work-queue
58 _VMSWorkQ = makeCASQ();
59 workQ = _VMSWorkQ;
61 _VMSMasterEnv = malloc( sizeof(MasterEnv) );
62 masterEnv = _VMSMasterEnv;
64 //create the master virtual processor
65 masterEnv->masterVirtPr = VMS__create_procr( &masterLoop, masterEnv );
67 create_sched_slots( masterEnv );
69 //Set slot 0 to be the master virt procr & set flags just in case
70 masterEnv->schedSlots[0]->needsProcrAssigned = FALSE; //says don't touch
71 masterEnv->schedSlots[0]->workIsDone = FALSE; //says don't touch
72 masterEnv->schedSlots[0]->procrAssignedToSlot = masterEnv->masterVirtPr;
73 masterEnv->masterVirtPr->schedSlot = masterEnv->schedSlots[0];
74 masterEnv->stillRunning = FALSE;
76 //First core loop to start up gets this, which will schedule seed Pr
77 //TODO: debug: check address of masterVirtPr
78 writeCASQ( masterEnv->masterVirtPr, workQ );
80 numProcrsCreated = 1;
82 //========================================================================
83 // Create the Threads
84 int coreIdx;
86 //Make params given to the win threads that animate the core loops
87 for( coreIdx=0; coreIdx < NUM_CORES; coreIdx++ )
88 { coreLoopThdParams[coreIdx] = malloc( sizeof(ThdParams) );
89 coreLoopThdParams[coreIdx]->coreNum = coreIdx;
91 //make the core loop threads, born in suspended state
92 coreLoopThdHandles[ coreIdx ] =
93 CreateThread ( NULL, // Security attributes
94 0, // Stack size
95 coreLoop,
96 coreLoopThdParams[coreIdx],
97 CREATE_SUSPENDED,
98 &(coreLoopThdIds[coreIdx])
99 );
100 }
102 }
105 void
106 create_sched_slots( MasterEnv *masterEnv )
107 { SchedSlot **schedSlots, **filledSlots;
108 int i;
110 schedSlots = malloc( NUM_SCHED_SLOTS * sizeof(SchedSlot *) );
111 filledSlots = malloc( NUM_SCHED_SLOTS * sizeof(SchedSlot *) );
112 masterEnv->schedSlots = schedSlots;
113 masterEnv->filledSlots = filledSlots;
115 for( i = 0; i < NUM_SCHED_SLOTS; i++ )
116 {
117 schedSlots[i] = malloc( sizeof(SchedSlot) );
119 //Set state to mean "handling requests done, slot needs filling"
120 schedSlots[i]->workIsDone = FALSE;
121 schedSlots[i]->needsProcrAssigned = TRUE;
122 }
123 }
126 /*Semantic layer calls this when it want the system to start running..
127 *
128 *This starts the core loops running then waits for them to exit.
129 */
130 void
131 VMS__start_the_work_then_wait_until_done()
132 { int coreIdx;
133 //Start the core loops running
134 //===========================================================================
135 LARGE_INTEGER stPerfCount, endPerfCount, countFreq;
136 unsigned long long count = 0, freq = 0;
137 double runTime;
139 QueryPerformanceCounter( &stPerfCount );
141 //start them running
142 for( coreIdx=0; coreIdx < NUM_CORES; coreIdx++ )
143 { //Create the threads
144 ResumeThread( coreLoopThdHandles[coreIdx] ); //starts thread
145 }
147 //wait for all to complete
148 for( coreIdx=0; coreIdx < NUM_CORES; coreIdx++ )
149 {
150 WaitForSingleObject(coreLoopThdHandles[coreIdx], INFINITE);
151 }
153 //NOTE: do not clean up VMS env here -- semantic layer has to have
154 // a chance to clean up its environment first, then do a call to free
155 // the Master env and rest of VMS locations
157 QueryPerformanceCounter( &endPerfCount );
158 count = endPerfCount.QuadPart - stPerfCount.QuadPart;
160 QueryPerformanceFrequency( &countFreq );
161 freq = countFreq.QuadPart;
162 runTime = (double)count / (double)freq;
164 printf("\n Time startup to shutdown: %f\n", runTime);
165 fflush( stdin );
166 }
170 /*Create stack, then create __cdecl structure on it and put initialData and
171 * pointer to the new structure instance into the parameter positions on
172 * the stack
173 *Then put function pointer into nextInstrPt -- the stack is setup in std
174 * call structure, so jumping to function ptr is same as a GCC generated
175 * function call
176 *No need to save registers on old stack frame, because there's no old
177 * animator state to return to --
178 *
179 */
180 VirtProcr *
181 VMS__create_procr( VirtProcrFnPtr fnPtr, void *initialData )
182 { VirtProcr *newPr;
183 char *stackLocs, *stackPtr;
185 newPr = malloc( sizeof(VirtProcr) );
186 newPr->procrID = numProcrsCreated++;
187 newPr->nextInstrPt = fnPtr;
188 newPr->initialData = initialData;
190 //fnPtr takes two params -- void *initData & void *animProcr
191 //alloc stack locations, make stackPtr be the highest addr minus room
192 // for 2 params + return addr. Return addr (NULL) is in loc pointed to
193 // by stackPtr, initData at stackPtr + 4 bytes, animatingPr just above
194 stackLocs = malloc( VIRT_PROCR_STACK_SIZE );
195 newPr->startOfStack = stackLocs;
196 stackPtr = ( (char *)stackLocs + VIRT_PROCR_STACK_SIZE - 0x10 );
197 //setup __cdecl on stack -- coreloop will switch to stackPtr before jmp
198 *( (int *)stackPtr + 2 ) = (int) newPr; //rightmost param -- 32bit pointer
199 *( (int *)stackPtr + 1 ) = (int) initialData; //next param to left
200 newPr->stackPtr = stackPtr; //core loop will switch to this, then
201 newPr->framePtr = stackPtr; //suspend loop will save new stack & frame ptr
203 return newPr;
204 }
207 /*there is a label inside this function -- save the addr of this label in
208 * the callingPr struc, as the pick-up point from which to start the next
209 * work-unit for that procr. If turns out have to save registers, then
210 * save them in the procr struc too. Then do assembly jump to the CoreLoop's
211 * "done with work-unit" label. The procr struc is in the request in the
212 * slave that animated the just-ended work-unit, so all the state is saved
213 * there, and will get passed along, inside the request handler, to the
214 * next work-unit for that procr.
215 */
216 void
217 VMS__suspend_procr( VirtProcr *callingPr )
218 { void *jmpPt, *stackPtrAddr, *framePtrAddr, *coreLoopStackPtr;
219 void *coreLoopFramePtr;
221 //The request to master will cause this suspended virt procr to get
222 // scheduled again at some future point -- to resume, core loop jumps
223 // to the resume point (below), which causes restore of saved regs and
224 // "return" from this call.
225 callingPr->nextInstrPt = &&ResumePt;
227 //return ownership of the virt procr and sched slot to Master virt pr
228 callingPr->schedSlot->workIsDone = TRUE;
229 // coreIdx = callingPr->coreAnimatedBy;
231 stackPtrAddr = &(callingPr->stackPtr);
232 framePtrAddr = &(callingPr->framePtr);
234 jmpPt = callingPr->coreLoopStartPt;
235 coreLoopFramePtr = callingPr->coreLoopFramePtr;//need this only
236 coreLoopStackPtr = callingPr->coreLoopStackPtr;//shouldn't need -- safety
238 //Save the virt procr's stack and frame ptrs, restore coreloop's frame
239 // ptr, then jump back to "start" of core loop
240 //Note, GCC compiles to assembly that saves esp and ebp in the stack
241 // frame -- so have to explicitly do assembly that saves to memory
242 asm volatile("movl %0, %%eax; \
243 movl %%esp, (%%eax); \
244 movl %1, %%eax; \
245 movl %%ebp, (%%eax); \
246 movl %2, %%eax; \
247 movl %3, %%esp; \
248 movl %4, %%ebp; \
249 jmp %%eax " \
250 /* outputs */ : "=g" (stackPtrAddr), "=g" (framePtrAddr) \
251 /* inputs */ : "g" (jmpPt), "g"(coreLoopStackPtr), "g"(coreLoopFramePtr)\
252 /* clobber */ : "memory", "%eax", "%ebx", "%ecx", "%edx", "%edi","%esi" \
253 ); //list everything as clobbered to force GCC to save all
254 // live vars that are in regs on stack before this
255 // assembly, so that stack pointer is correct, before jmp
257 ResumePt:
258 return;
259 }
263 /*This is equivalent to "jump back to core loop" -- it's mainly only used
264 * just after adding dissipate request to a processor -- so the semantic
265 * layer is the only place it will be seen and/or used.
266 *
267 *It does almost the same thing as suspend, except don't need to save the
268 * stack nor set the nextInstrPt
269 *
270 *As of June 30, 2010 just implementing as a call to suspend -- just sugar
271 */
272 void
273 VMS__return_from_fn( VirtProcr *animatingPr )
274 {
275 VMS__suspend_procr( animatingPr );
276 }
279 /*Not sure yet the form going to put "dissipate" in, so this is the third
280 * possibility -- the semantic layer can just make a macro that looks like
281 * a call to its name, then expands to a call to this.
282 *
283 *As of June 30, 2010 this looks like the top choice..
284 *
285 *This adds a request to dissipate, then suspends the processor so that the
286 * request handler will receive the request. The request handler is what
287 * does the work of freeing memory and removing the processor from the
288 * semantic environment's data structures.
289 *The request handler also is what figures out when to shutdown the VMS
290 * system -- which causes all the core loop threads to die, and returns from
291 * the call that started up VMS to perform the work.
292 *
293 *This form is a bit misleading to understand if one is trying to figure out
294 * how VMS works -- it looks like a normal function call, but inside it
295 * sends a request to the request handler and suspends the processor, which
296 * jumps out of the VMS__dissipate_procr function, and out of all nestings
297 * above it, transferring the work of dissipating to the request handler,
298 * which then does the actual work -- causing the processor that animated
299 * the call of this function to disappear and the "hanging" state of this
300 * function to just poof into thin air -- the virtual processor's trace
301 * never returns from this call, but instead the virtual processor's trace
302 * gets suspended in this call and all the virt processor's state disap-
303 * pears -- making that suspend the last thing in the virt procr's trace.
304 */
305 void
306 VMS__dissipate_procr( VirtProcr *procrToDissipate )
307 { VMSReqst *req;
309 req = malloc( sizeof(VMSReqst) );
310 // req->virtProcrFrom = callingPr;
311 req->reqType = dissipate;
312 req->nextReqst = procrToDissipate->requests;
313 procrToDissipate->requests = req;
315 VMS__suspend_procr( procrToDissipate );
316 }
319 /*This inserts the semantic-layer's request data into standard VMS carrier
320 */
321 inline void
322 VMS__add_sem_request( void *semReqData, VirtProcr *callingPr )
323 { VMSReqst *req;
325 req = malloc( sizeof(VMSReqst) );
326 // req->virtProcrFrom = callingPr;
327 req->reqType = semantic;
328 req->semReqData = semReqData;
329 req->nextReqst = callingPr->requests;
330 callingPr->requests = req;
331 }
335 //TODO: add a semantic-layer supplied "freer" for the semantic-data portion
336 // of a request -- IE call with both a virt procr and a fn-ptr to request
337 // freer (or maybe put request freer as a field in virt procr?)
338 void
339 VMS__remove_and_free_top_request( VirtProcr *procrWithReq )
340 { VMSReqst *req;
342 req = procrWithReq->requests;
343 procrWithReq->requests = procrWithReq->requests->nextReqst;
344 free( req );
345 }
348 //TODO: add a semantic-layer supplied "freer" for the semantic-data portion
349 // of a request -- IE call with both a virt procr and a fn-ptr to request
350 // freer (also maybe put sem request freer as a field in virt procr?)
351 void
352 VMS__free_request( VMSReqst *req )
353 {
354 free( req );
355 }
357 VMSReqst *
358 VMS__take_top_request_from( VirtProcr *procrWithReq )
359 { VMSReqst *req;
361 req = procrWithReq->requests;
362 if( req == NULL ) return req;
364 procrWithReq->requests = procrWithReq->requests->nextReqst;
365 return req;
366 }
368 inline int
369 VMS__isSemanticReqst( VMSReqst *req )
370 {
371 return ( req->reqType == semantic );
372 }
375 inline void *
376 VMS__take_sem_reqst_from( VMSReqst *req )
377 {
378 return req->semReqData;
379 }
381 inline int
382 VMS__isDissipateReqst( VMSReqst *req )
383 {
384 return ( req->reqType == dissipate );
385 }
387 inline int
388 VMS__isCreateReqst( VMSReqst *req )
389 {
390 return ( req->reqType == regCreated );
391 }
393 void
394 VMS__send_register_new_procr_request(VirtProcr *newPr, VirtProcr *reqstingPr)
395 { VMSReqst *req;
397 req = malloc( sizeof(VMSReqst) );
398 req->reqType = regCreated;
399 req->semReqData = newPr;
400 req->nextReqst = reqstingPr->requests;
401 reqstingPr->requests = req;
403 VMS__suspend_procr( reqstingPr );
404 }
407 /*The semantic layer figures out when the work is done ( perhaps by a call
408 * in the application to "work all done", or perhaps all the virtual
409 * processors have dissipated.. a.s.o. )
410 *
411 *The semantic layer is responsible for making sure all work has fully
412 * completed before using this to shutdown the VMS system.
413 *
414 *After the semantic layer has determined it wants to shut down, the
415 * next time the Master Loop calls the scheduler plug-in, the scheduler
416 * then calls this function and returns the virtual processor it gets back.
417 *
418 *When the shut-down processor runs, it first frees all locations malloc'd to
419 * the VMS system (that wasn't
420 * specified as return-locations). Then it creates one core-loop shut-down
421 * processor for each core loop and puts them all into the workQ. When a
422 * core loop animates a core loop shut-down processor, it causes exit-thread
423 * to run, and when all core loop threads have exited, then the "wait for
424 * work to finish" in the main thread is woken, and the function-call that
425 * started all the work returns.
426 *
427 *The function animated by this processor performs the shut-down work.
428 */
429 VirtProcr *
430 VMS__create_the_shutdown_procr()
431 {
432 return VMS__create_procr( &shutdownFn, NULL );
433 }
436 /*This must be called by the request handler plugin -- it cannot be called
437 * from the semantic library "dissipate processor" function -- instead, the
438 * semantic layer has to generate a request for the plug-in to call this
439 * function.
440 *The reason is that this frees the virtual processor's stack -- which is
441 * still in use inside semantic library calls!
442 *
443 *This frees or recycles all the state owned by and comprising the VMS
444 * portion of the animating virtual procr. The request handler must first
445 * free any semantic data created for the processor that didn't use the
446 * VMS_malloc mechanism. Then it calls this, which first asks the malloc
447 * system to disown any state that did use VMS_malloc, and then frees the
448 * statck and the processor-struct itself.
449 *If the dissipated processor is the sole (remaining) owner of VMS__malloc'd
450 * state, then that state gets freed (or sent to recycling) as a side-effect
451 * of dis-owning it.
452 */
453 void
454 VMS__free_procr_locs( VirtProcr *animatingPr )
455 {
456 //dis-own all locations owned by this processor, causing to be freed
457 // any locations that it is (was) sole owner of
458 //TODO: implement VMS__malloc system, including "give up ownership"
460 //The dissipate request might still be attached, so remove and free it
461 VMS__remove_and_free_top_request( animatingPr );
462 free( animatingPr->startOfStack );
464 //NOTE: initialData was given to the processor, so should either have
465 // been alloc'd with VMS__malloc, or freed by the level above animPr.
466 //So, all that's left to free here is the stack and the VirtProcr struc
467 // itself
468 free( animatingPr->startOfStack );
469 free( animatingPr );
470 }
474 /*This is the function run by the special "shut-down" processor
475 *
476 *The _VMSMasterEnv is needed by this shut down function, so the "wait"
477 * function run in the main loop has to free it, and the thread-related
478 * locations (coreLoopThdParams a.s.o.).
479 *However, the semantic environment and all data malloc'd to VMS can be
480 * freed here.
481 *
482 *NOTE: the semantic plug-in is expected to use VMS__malloc to get all the
483 * locations it needs -- they will be automatically freed by the standard
484 * "free all owned locations"
485 *
486 *Free any locations malloc'd to the VMS system (that weren't
487 * specified as return-locations).
488 *Then create one core-loop shut-down processor for each core loop and puts
489 * them all into the workQ.
490 */
491 void
492 shutdownFn( void *dummy, VirtProcr *animatingPr )
493 { int coreIdx;
494 VirtProcr *shutDownPr;
495 CASQueueStruc *workQ = _VMSWorkQ;
497 //free all the locations owned within the VMS system
498 //TODO: write VMS__malloc and free.. -- take the DKU malloc as starting pt
500 //make the core loop shut-down processors and put them into the workQ
501 for( coreIdx=0; coreIdx < NUM_CORES; coreIdx++ )
502 {
503 shutDownPr = VMS__create_procr( NULL, NULL );
504 shutDownPr->nextInstrPt = _VMSMasterEnv->coreLoopShutDownPt;
505 writeCASQ( shutDownPr, workQ );
506 }
508 //This is an issue: the animating processor of this function may not
509 // get its request handled before all the cores have shutdown.
510 //TODO: after all the threads stop, clean out the MasterEnv, the
511 // SemanticEnv, and the workQ before returning.
512 VMS__dissipate_procr( animatingPr ); //will never come back from this
513 }
516 /*This has to free anything allocated during VMS_init, and any other alloc'd
517 * locations that might be left over.
518 */
519 void
520 VMS__shutdown()
521 { int i;
523 free( _VMSWorkQ );
524 free( _VMSMasterEnv->filledSlots );
525 for( i = 0; i < NUM_SCHED_SLOTS; i++ )
526 {
527 free( _VMSMasterEnv->schedSlots[i] );
528 }
530 free( _VMSMasterEnv->schedSlots);
531 VMS__free_procr_locs( _VMSMasterEnv->masterVirtPr );
533 free( _VMSMasterEnv );
534 }
537 //===========================================================================
539 inline TSCount getTSCount()
540 { unsigned int low, high;
541 TSCount out;
543 saveTimeStampCountInto( low, high );
544 out = high;
545 out = (out << 32) + low;
546 return out;
547 }