navienginebsp/ne1_tb/specific/power.cpp
changeset 0 5de814552237
equal deleted inserted replaced
-1:000000000000 0:5de814552237
       
     1 /*
       
     2 * Copyright (c) 2008-2010 Nokia Corporation and/or its subsidiary(-ies).
       
     3 * All rights reserved.
       
     4 * This component and the accompanying materials are made available
       
     5 * under the terms of "Eclipse Public License v1.0"
       
     6 * which accompanies this distribution, and is available
       
     7 * at the URL "http://www.eclipse.org/legal/epl-v10.html".
       
     8 *
       
     9 * Initial Contributors:
       
    10 * Nokia Corporation - initial contribution.
       
    11 *
       
    12 * Contributors:
       
    13 *
       
    14 * Description:  
       
    15 * ne1_tb\specific\power.cpp*
       
    16 */
       
    17 
       
    18 
       
    19 
       
    20 #include "ne1_tb_power.h"
       
    21 
       
    22 DNE1_TBPowerController* TNE1_TBPowerController::iPowerController = NULL;
       
    23 
       
    24 #ifdef __SMP__
       
    25 #ifndef __NO_IDLE_HANDLER_PIL__
       
    26 DNE1_SMPIdleHandler* TNE1_TBPowerController::iIdleHandler = NULL;
       
    27 #endif
       
    28 const TUint32 DNE1_TBPowerController::KCyclesPerTick 	= 66666;
       
    29 const TInt DNE1_TBPowerController::KMaxSleepTicks 	= TInt(0xffffff00u/DNE1_TBPowerController::KCyclesPerTick)-1;
       
    30 const TUint32 DNE1_TBPowerController::KWakeUpBeforeTick = 24000;
       
    31 const TUint32 DNE1_TBPowerController::KTooCloseToTick	= 6666;
       
    32 const TUint32 DNE1_TBPowerController::KMinTimeToTick	= 2000;
       
    33 const TInt DNE1_TBPowerController::KMinIdleTicks		= 2;
       
    34 #if defined(SIMULATE_RETIREMENT) && !defined(__NO_IDLE_HANDLER_PIL__)
       
    35 volatile TUint32 DNE1_SMPIdleHandler::iRetiredCores = 0;
       
    36 #endif
       
    37 #endif // __SMP__
       
    38 
       
    39 inline TUint32 abs_u32diff(TUint32 aA, TUint32 aB) 
       
    40     {
       
    41     return (aA > aB) ? aA - aB : aB - aA; 
       
    42     }
       
    43 
       
    44 
       
    45 //-/-/-/-/-/-/-/-/-/ class DNE1_SMPIdleHandler /-/-/-/-/-/-/-/-/-/
       
    46 
       
    47 #if defined(__SMP__) && !defined(__NO_IDLE_HANDLER_PIL__)
       
    48 
       
    49 DNE1_SMPIdleHandler::DNE1_SMPIdleHandler(DNE1_TBPowerController* aController)
       
    50     :DSMPIdleHandler(),iController(aController)
       
    51     {
       
    52     }
       
    53 
       
    54 TInt DNE1_SMPIdleHandler::Initialise()
       
    55     {
       
    56     TInt r = KErrNone;
       
    57     DSMPIdleHandler::Initialise(KHwBaseGlobalIntDist,KHwBaseIntIf);
       
    58 #ifdef SIMULATE_RETIREMENT
       
    59     // create as many antiIdle threads as there are cored
       
    60     TInt nc = NKern::NumberOfCpus();
       
    61     iIdleStealers = new TDfcQue*[nc];
       
    62     __PM_ASSERT_ALWAYS(iIdleStealers);
       
    63     iIdleStealDfcs = new TDfc*[nc];
       
    64     __PM_ASSERT_ALWAYS(iIdleStealDfcs);
       
    65     for (TInt i = 0; i < nc; i++)
       
    66         {
       
    67         TName name = _L("IDLESTEALER");
       
    68         name.AppendNum(i);
       
    69         r = Kern::DfcQCreate(iIdleStealers[i],1,&name);
       
    70         __PM_ASSERT_ALWAYS(KErrNone==r);
       
    71         iIdleStealDfcs[i] = new TDfc(IdleSteal,(TAny*) i,iIdleStealers[i],0);
       
    72         __PM_ASSERT_ALWAYS(iIdleStealDfcs[i]);
       
    73         NKern::ThreadSetCpuAffinity((NThread*)iIdleStealers[i]->iThread,i);
       
    74         }
       
    75     TName name = _L("RETIREENAGE");
       
    76     r = Kern::DfcQCreate(iRetireEngageQue,27,&name);
       
    77 #endif
       
    78     return r;
       
    79     }
       
    80 
       
    81 TBool DNE1_SMPIdleHandler::DoEnterIdle(TInt aCpuMask, TInt aStage, volatile TAny* /*aU*/)
       
    82     {
       
    83     if (aStage & SCpuIdleHandler::EPostamble)
       
    84         {
       
    85         iController->IdleTickSuppresionRestore();
       
    86         return EFalse;
       
    87         }
       
    88 #ifdef SIMULATE_RETIREMENT
       
    89     // are we retiring? 
       
    90     if (iRetiredCores&aCpuMask) 
       
    91         {
       
    92         // this should be safe as no cores can be using sync points yet 
       
    93         // as DoEnterIdle is called before all cores are in idle
       
    94         // and the last core has not arrived yet
       
    95         // theorically would not return from here 
       
    96         // DoRetireCore would call TIdleSupport::MarkCoreRetired as last 
       
    97         // thing once core is guaranteed not to enter idle handler again 
       
    98         // until it is enaged once more
       
    99         DoRetireCore(__e32_find_ms1_32(aCpuMask),0); 
       
   100         return EFalse;
       
   101         }
       
   102 #endif
       
   103     return ETrue;
       
   104     }
       
   105 
       
   106 
       
   107 TBool DNE1_SMPIdleHandler::GetLowPowerMode(TInt aIdleTime, TInt &aLowPowerMode)
       
   108     {
       
   109     
       
   110     aLowPowerMode = 0;
       
   111     if (aIdleTime < DNE1_TBPowerController::KMinIdleTicks) return EFalse;
       
   112     iController->IdleTickSuppresionEntry(DNE1_TBPowerController::KWakeUpBeforeTick,aIdleTime);  
       
   113     return ETrue;
       
   114     }
       
   115 
       
   116 TBool DNE1_SMPIdleHandler::EnterLowPowerMode(TInt aMode, TInt aCpuMask, TBool aLastCpu)
       
   117     {
       
   118     TIdleSupport::DoWFI();	// maybe we will wake up, or maybe another CPU will wake us up
       
   119     return ETrue;
       
   120     }
       
   121 
       
   122 
       
   123 #ifdef SIMULATE_RETIREMENT
       
   124 
       
   125 void DNE1_SMPIdleHandler::IdleSteal(TAny* aPtr)
       
   126     {
       
   127     TInt cpu = (TInt) aPtr;
       
   128     PMBTRACE4(KRetireCore,KRetireCoreEntry,cpu);
       
   129     TUint32 cpuMask = 0x1 << cpu;
       
   130 
       
   131     while (cpuMask&iRetiredCores);
       
   132     PMBTRACE4(KRetireCore,KRetireCoreeXit,cpu);
       
   133     }
       
   134 
       
   135 void DNE1_SMPIdleHandler::DoRetireCore(TInt aCpu, TLinAddr /*aReturnPoint*/)
       
   136     {
       
   137     iIdleStealDfcs[aCpu]->RawAdd();
       
   138     TIdleSupport::MarkCoreRetired(0x1<<aCpu);
       
   139     }
       
   140 
       
   141 #endif
       
   142 #endif
       
   143 
       
   144 
       
   145 //-/-/-/-/-/-/-/-/-/ class DNE1_TBPowerController /-/-/-/-/-/-/-/-/-/
       
   146 
       
   147 DNE1_TBPowerController::DNE1_TBPowerController()
       
   148 #if defined(__SMP__) && !defined(__NO_IDLE_HANDLER_PIL__)
       
   149     :iIdleHandler(this)
       
   150 #endif
       
   151     {
       
   152     Register();			// register Power Controller with Power Manager
       
   153 	TNE1_TBPowerController::RegisterPowerController(this);
       
   154 	
       
   155 #if defined(__SMP__) && !defined(__NO_IDLE_HANDLER_PIL__)
       
   156     //	Register idle handler
       
   157     if ((AsspRegister::Read32(KHwRoGpio_Port_Value) & (0x1<<27)))
       
   158         {
       
   159         __PM_ASSERT_ALWAYS(KErrNone==iIdleHandler.Initialise());
       
   160         }
       
   161     else 
       
   162         {
       
   163         // press and hold User Switch 0 / INT0 (SW3) on boot
       
   164         // to disable idle tick suppression
       
   165         Kern::Printf("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
       
   166         Kern::Printf("!!!!!!!!!!!! NOT DOING ITS !!!!!!!!!!!");
       
   167         Kern::Printf("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
       
   168         }
       
   169 #endif
       
   170 	}
       
   171 
       
   172 void DNE1_TBPowerController::CpuIdle()
       
   173 	{
       
   174 	Arch::TheAsic()->Idle();
       
   175 #ifndef __SMP__
       
   176     iIdleCount++;
       
   177 #endif
       
   178 	}
       
   179 
       
   180 void DNE1_TBPowerController::EnableWakeupEvents()
       
   181 	{
       
   182 	//
       
   183 	// TO DO: (mandatory)
       
   184 	//
       
   185 	// Enable tracking of wake-up events directly in hardware. If the hardware is controlled by a Driver
       
   186 	// or Extension, may need to disable interrupts and preemption around the code that accesses the hardware
       
   187 	// and set up a flag which the Driver/Extension code need to read before modifying the state of that piece
       
   188 	// of hardware. Note in that case the Driver/Extension may need to link to this Library.
       
   189 	//
       
   190 
       
   191 	//
       
   192 	// EXAMPLE ONLY
       
   193 	// In this example we simply assume that the driver will call the Power Controller every time a 
       
   194 	// wakeup event occurr. It is up to the Power Controller to know if it is tracking them or not.
       
   195 	// We also assume that if a wakeup event occurrs when the CPU is in Standby, this will automatically
       
   196 	// bring it back from that state.
       
   197 	iWakeupEventsOn = ETrue;	// start tracking wakeup events
       
   198 	}
       
   199 
       
   200 void DNE1_TBPowerController::DisableWakeupEvents()
       
   201 	{
       
   202 	//
       
   203 	// TO DO: (mandatory)
       
   204 	//
       
   205 	// Disable tracking of wake-up events directly in hardware or if the hardware is controlled by a Driver or
       
   206 	// Extension need to set up a flag which the Driver/Extension reads whenever the event occurs, in order to
       
   207 	// find out if it needs to deliver notification to the Power Controller
       
   208 	//
       
   209 	iWakeupEventsOn = EFalse;	// stop tracking wakeup events
       
   210 	}
       
   211 
       
   212 void DNE1_TBPowerController::AbsoluteTimerExpired()
       
   213 	{
       
   214 	if (iTargetState == EPwStandby && iWakeupEventsOn)
       
   215 		{
       
   216 		iWakeupEventsOn = EFalse;		// one occurred, no longer track wakeup events
       
   217 		WakeupEvent();
       
   218 		}
       
   219 	}
       
   220 
       
   221 void DNE1_TBPowerController::PowerDown(TTimeK aWakeupST)	
       
   222 	{
       
   223 	if (iTargetState == EPwStandby)
       
   224 		{
       
   225 		//
       
   226 		// TO DO: (mandatory)
       
   227 		//
       
   228 		// Converts between the Wakeup time in System Time units as passed in to this function and a Wakeup
       
   229 		// time in RTC units. The following code is given as an example how to convert between System time units
       
   230 		// RTC time units on a system with a 32 bit RTC timer and which is incremented on a second interval:
       
   231 		//
       
   232 		// TUint32 wakeupRTC;
       
   233 		if (aWakeupST)
       
   234 			{
       
   235 			TUint32 nowRTC = TNaviEngine::RtcData();
       
   236 			TTimeK nowST = Kern::SystemTime();
       
   237 			__KTRACE_OPT(KPOWER,Kern::Printf("system time: now = 0x%lx(us) wakeup = 0x%lx(us)", nowST, aWakeupST));
       
   238 			if (aWakeupST < nowST)
       
   239 				return;
       
   240 			Int64 deltaSecs = (aWakeupST - nowST) / 1000000;
       
   241 			if (deltaSecs <= 0)
       
   242 				return;
       
   243 			if (deltaSecs + (Int64)nowRTC > (Int64)(KMaxTInt - 2))
       
   244 				{
       
   245 				//wakeupRTC = (KMaxTInt - 2); // RTC can't wrap around during standby
       
   246 				__KTRACE_OPT(KPOWER,Kern::Printf("RTC: now = %d(s) wakeup = %d(s)", nowRTC, KMaxTInt - 2));
       
   247 				}
       
   248 			else
       
   249 				{
       
   250 				//wakeupRTC = nowRTC + deltaSecs;
       
   251 				__KTRACE_OPT(KPOWER,Kern::Printf("RTC: now = %d(s) wakeup = %d(s)", nowRTC, nowRTC + deltaSecs));
       
   252 				}
       
   253 			}
       
   254 //		else
       
   255 //			wakeupRTC = 0;
       
   256 		//
       
   257 		// TO DO: (optional)
       
   258 		//
       
   259 		// It then uses the calculated value to program the RTC to wakeup the System at the Wakeup
       
   260 		// time ans sets the CPU and remaining hardware to go to the correponding low power mode. When the 
       
   261 		// state of the Core and Core Peripherals is not preserved in this mode the following is usually 
       
   262 		// required:
       
   263 		//	- save current Core state (current Mode, banked registers for each Mode and Stack Pointer for 
       
   264 		//	  both current and User Modes
       
   265 		//	- save MMU state: Control Register, TTB and Domain Access Control
       
   266 		//	- Flush Dta Cache and drain Write Buffer
       
   267 		//	- save Core Peripherals state: Interrupt Controller, Pin Function, Bus State and Clock settings
       
   268 		// SDRAM should be put in self refresh mode. Peripheral devices involved in detection of Wakeup events
       
   269 		// should be left powered.
       
   270 		// The Tick timer should be disabled and the current count of this and other System timers shall be
       
   271 		// saved.
       
   272 		// On wakeing up the state should be restored from the save state as above. SDRAM shall be brought back
       
   273 		// under CPU control, The Tick count shall be restored and timers re-enabled.
       
   274 
       
   275 		// We assume that if a wakeup event occurrs when the CPU is in Standby, this will automatically
       
   276 		// bring it back from that state. Therefore we stop tracking wakeup events as the Power Manager will
       
   277 		// complete any pending notifications anyway. When the driver delivers its notification, we just ignore
       
   278 		// it.
       
   279 		iWakeupEventsOn = EFalse;		// tracking of wakeup events is now done in hardware
       
   280 		}
       
   281 	else
       
   282 		{
       
   283 		Kern::Restart(0x80000000);
       
   284 		}
       
   285 	}
       
   286 
       
   287 void DNE1_TBPowerController::IdleTickSuppresionRestore()
       
   288     {
       
   289 #ifdef __SMP__	
       
   290     // only one CPU can enter this function
       
   291     NETimer& NET = NETimer::Timer(0);
       
   292     TUint32 timerWrapped = NET.iGTInterrupt&KNETimerGTIInt_TCI;
       
   293     __e32_io_completion_barrier();
       
   294     TUint32  timeIn = NET.iTimerCount;
       
   295     TUint32 timeSlept = timeIn;
       
   296 
       
   297     __PM_ASSERT_DEBUG(NET.iTimerReset == iNextInterrupt);
       
   298     
       
   299     if (timerWrapped) 
       
   300         {
       
   301         // We woke up due to a the main timer. If this is case unless we clear the interrupt
       
   302         // this result in an extra tick being advanced. We are reprogramming the ISR for a latter
       
   303         // activation aligned with the correct phase. For timer based wakeups we wake up a bit early
       
   304         // early enough to allow the time needed to repogram the timer for the next edge
       
   305         timeSlept+=((iNextInterrupt+KCyclesPerTick)-iOriginalTimerExpire);  // timer wrapped if interrupt is pending
       
   306         ClearTimerInterrupt();
       
   307         }
       
   308 	else if	(timeIn >= iOriginalTimerExpire)
       
   309 		{
       
   310 		//We woke up after one or more ticks
       
   311 		timeSlept+=(KCyclesPerTick-iOriginalTimerExpire);		
       
   312 		}
       
   313 		
       
   314     TUint32 ticksSlept = timeSlept/KCyclesPerTick;
       
   315     TUint32 timeToNextInterruptDelta = (ticksSlept+1)*KCyclesPerTick-timeSlept;
       
   316 	
       
   317 	if	(timerWrapped==0 && timeIn<iOriginalTimerExpire)
       
   318 		{
       
   319 		//We woke up before first tick expired
       
   320 		ticksSlept=0;
       
   321 		timeToNextInterruptDelta=iOriginalTimerExpire-timeIn;
       
   322 		}
       
   323 	
       
   324 	
       
   325     if (timeToNextInterruptDelta < KMinTimeToTick) 
       
   326         {        
       
   327         // This should not happen on normal timer expiries as we should be be programmed to wake 
       
   328         // well before the next timer expiry which therefore means that ie we need to make sure that
       
   329         // wake up times are always larger than this KMinTimeToTick
       
   330 		// However a WakeupEvent could have resulted in us waking close potential tick		
       
   331         // skip a tick
       
   332         ticksSlept++;
       
   333         timeToNextInterruptDelta +=KCyclesPerTick;
       
   334         }
       
   335     TUint32 timeToNextInterrupt = timeIn+timeToNextInterruptDelta;
       
   336 
       
   337 //while(timeToNextInterrupt==KWakeUpBeforeTick);
       
   338 
       
   339 
       
   340     NET.iTimerReset = timeToNextInterrupt;
       
   341 	__e32_io_completion_barrier();
       
   342     NTimerQ::Advance(ticksSlept);
       
   343     // restart stopped timers used in NKern::Timestamp, in hardware that will be used for
       
   344     // product timers of this type would stop when entering low power mode
       
   345     NETimer& T1 = NETimer::Timer(1);
       
   346 	NETimer& T2 = NETimer::Timer(2);
       
   347 
       
   348     TUint32 t2 = T2.iTimerCount;
       
   349     TUint32 t1 = T1.iTimerCount;
       
   350 
       
   351     // because timers at started one after the other
       
   352     // there a certain amount of error accumulated in the diffence between them
       
   353     // we need to take into account this error level when restarting them
       
   354     // so that we can ensure the error does not grow
       
   355 	// note sleep time cannot exceed 0xffffff00
       
   356     TUint32 error = (t1-t2)&0xff;
       
   357     TUint32 remainder = 0xffffff00-t1;
       
   358     if (remainder > timeSlept) t1+=timeSlept;
       
   359     else t1 = timeSlept - remainder;
       
   360     T1.iTimerCount = t1;
       
   361     T2.iTimerCount += timeSlept + error;
       
   362 	__e32_io_completion_barrier();
       
   363 	T1.iTimerCtrl |=  KNETimerCtrl_CAE;	// start   timer 1 first
       
   364 	__e32_io_completion_barrier();
       
   365     T2.iTimerCtrl |=  KNETimerCtrl_CAE;	// start   timer 2
       
   366 	__e32_io_completion_barrier();
       
   367 
       
   368 #ifndef __NO_IDLE_HANDLER_PIL__
       
   369     PMBTRACE8(KIdleTickSupression,KTimeSleptTimeNextInt,timeSlept,timeToNextInterrupt);
       
   370     PMBTRACE8(KIdleTickSupression,KTIcksSlept,ticksSlept,timeToNextInterruptDelta);
       
   371     PMBTRACE8(KMisc,0x20,timeIn,timerWrapped);
       
   372 #endif
       
   373 #endif	
       
   374     }
       
   375 
       
   376 void DNE1_TBPowerController::IdleTickSuppresionEntry(TUint32 aWakeDelay, TInt aNextTimer)
       
   377     {
       
   378 #ifdef __SMP__		
       
   379 	NETimer& NET = NETimer::Timer(0);
       
   380     	
       
   381     TUint32 cyclesInTick = NET.iTimerCount;
       
   382 	TUint32 cyclesFullTick= NET.iTimerReset;
       
   383 	__e32_io_completion_barrier();
       
   384      
       
   385     if (abs_u32diff(cyclesFullTick,cyclesInTick) < KTooCloseToTick || (NET.iGTInterrupt&KNETimerGTIInt_TCI)) 
       
   386 		return; // to close to edge of tick so we skip this one or even past it
       
   387 		
       
   388     if (aNextTimer > KMaxSleepTicks) aNextTimer = KMaxSleepTicks;
       
   389     iNextInterrupt = (aNextTimer)*KCyclesPerTick;//max time we can sleep	for
       
   390 	if	(iNextInterrupt > (KMaxTUint32-cyclesFullTick))
       
   391 		return;
       
   392 	// We need to wakeup just before the next timer expire is due	
       
   393 	iOriginalTimerExpire=cyclesFullTick;//this is where the current tick would have expired
       
   394 	iNextInterrupt+=(cyclesFullTick -aWakeDelay);//adjust next interrupt time from where we are now
       
   395     
       
   396     NET.iTimerReset = iNextInterrupt;
       
   397     __e32_io_completion_barrier();	
       
   398     NET.iGTInterrupt = KNETimerGTIInt_All;	// clear any pending interrupts
       
   399 	__e32_io_completion_barrier();
       
   400 #ifndef __NO_IDLE_HANDLER_PIL__
       
   401     PMBTRACE8(KIdleTickSupression,KCyclesInTickCyclesFullTick,cyclesInTick,cyclesFullTick);
       
   402     PMBTRACE4(KIdleTickSupression,KNextInterrupt,iNextInterrupt);
       
   403 #endif    
       
   404 //TO DO: Review method of setting iPostambleReuired flag
       
   405 	SCpuIdleHandler* pS = NKern::CpuIdleHandler();
       
   406 	pS->iPostambleRequired = ETrue;
       
   407     // stop timers used in NKern::Timestamp, in hardware that will be used for
       
   408     // product timers of this type would stop when entering low power mode
       
   409     NETimer& T1 = NETimer::Timer(1);
       
   410 	NETimer& T2 = NETimer::Timer(2);
       
   411     T2.iTimerCtrl &= ~ KNETimerCtrl_CAE;	// clear timer CAE to hold timer value
       
   412 	__e32_io_completion_barrier();
       
   413 	T1.iTimerCtrl &= ~ KNETimerCtrl_CAE; // stop timer 1 last (lets error increase
       
   414 	__e32_io_completion_barrier();       // but this should be ok as it shouldn't exceed 0xff
       
   415     iIdleCount++;
       
   416 #endif	
       
   417     }
       
   418 
       
   419 //-/-/-/-/-/-/-/-/-/ class TNE1_TBPowerController /-/-/-/-/-/-/-/-/-/
       
   420 
       
   421 
       
   422 EXPORT_C void TNE1_TBPowerController::WakeupEvent()
       
   423 	{
       
   424 	if(!iPowerController)
       
   425 		__PM_PANIC("Power Controller not present");
       
   426 	else if(iPowerController->iWakeupEventsOn)
       
   427 		{
       
   428 		iPowerController->iWakeupEventsOn=EFalse;		// one occurred, no longer track wakeup events
       
   429 		iPowerController->WakeupEvent();
       
   430 		}
       
   431 	}
       
   432 
       
   433 // NOTE: these are just enabler functions to simulate core retirement
       
   434 //       they would not stand to any scrutiny as the basis for a proper solution
       
   435 //       they are just here to allow to test the idle handler for robustness against retirement
       
   436 //       whilst we wait for a kernel solution
       
   437 // @pre thread context, interrupt on, kernel unlocked, no fast mutex held
       
   438 EXPORT_C void TNE1_TBPowerController::RetireCore(TInt aCpu,TRetireEngageCb& aCb)
       
   439     {
       
   440 #if defined(__SMP__) && !defined(__NO_IDLE_HANDLER_PIL__) && defined(SIMULATE_RETIREMENT)
       
   441     SRetireCall* call = new SRetireCall(aCpu,aCb);
       
   442     if (call && aCpu < NKern::NumberOfCpus()) 
       
   443         {
       
   444         call->Call();
       
   445         }
       
   446     else
       
   447         {
       
   448         
       
   449         if (!call) aCb.iResult = KErrNoMemory;
       
   450         else 
       
   451             {
       
   452             aCb.iResult = KErrArgument;
       
   453             delete call;
       
   454             }
       
   455         aCb.iDfc.Enque();
       
   456         }
       
   457 #endif    
       
   458     }
       
   459 
       
   460 // can be called from any core to engage any other core but caller must be outside idle thread
       
   461 // @pre thread context interrupt on no fast mutex held
       
   462 EXPORT_C void TNE1_TBPowerController::EngageCore(TInt aCpu, TRetireEngageCb& aCb)
       
   463     {
       
   464 #if defined(__SMP__) && !defined(__NO_IDLE_HANDLER_PIL__) && defined(SIMULATE_RETIREMENT)
       
   465     SEngageCall* call = new SEngageCall(aCpu,aCb);
       
   466     if (call && aCpu < NKern::NumberOfCpus()) 
       
   467         {
       
   468         call->Call();
       
   469         }
       
   470     else
       
   471         {
       
   472         if (!call) aCb.iResult = KErrNoMemory;
       
   473         else
       
   474             {
       
   475             aCb.iResult = KErrArgument;
       
   476             delete call;
       
   477             }
       
   478         aCb.iDfc.Enque();
       
   479         }
       
   480 #endif
       
   481     }
       
   482 
       
   483 
       
   484 /**
       
   485    Idle count is incremented everytime ITS takes place
       
   486    @return idle count
       
   487 */ 
       
   488 EXPORT_C TUint TNE1_TBPowerController::IdleCount()
       
   489     {
       
   490     return iPowerController->iIdleCount;
       
   491     }
       
   492 
       
   493 
       
   494 //-/-/-/-/-/-/-/-/-/ class SRetireCall /-/-/-/-/-/-/-/-/-/
       
   495 
       
   496 SRetireCall::SRetireCall(TInt aCpu,TRetireEngageCb& aCb)
       
   497 #if defined(__SMP__) && !defined(__NO_IDLE_HANDLER_PIL__) && defined(SIMULATE_RETIREMENT)
       
   498     :iTimer(RetireCoreDfcFn,(TAny*)this,
       
   499             TNE1_TBPowerController::iIdleHandler->iRetireEngageQue,0),
       
   500      iCpu(aCpu),iCb(aCb),iAllCpusMask(TIdleSupport::AllCpusMask())
       
   501 #endif
       
   502     {};
       
   503 
       
   504 #if defined(__SMP__) && !defined(__NO_IDLE_HANDLER_PIL__) && defined(SIMULATE_RETIREMENT)
       
   505 void SRetireCall::RetireCoreDfcFn(TAny* aParam)
       
   506     {
       
   507     
       
   508     SRetireCall* pC = (SRetireCall*) aParam;
       
   509     
       
   510     TUint32 cMask = 0x1<<pC->iCpu;
       
   511     TUint32 toBeRetired = DNE1_SMPIdleHandler::iRetiredCores|cMask;
       
   512     PMBTRACE4(KRetireCore,0x10,toBeRetired);
       
   513     if (toBeRetired==pC->iAllCpusMask || (DNE1_SMPIdleHandler::iRetiredCores&cMask) )
       
   514         {
       
   515         //Make sure we don't retire all cores! at least one should run. Core might also already be retired
       
   516         pC->iCb.iResult = KErrArgument;
       
   517         pC->iCb.iDfc.Enque();
       
   518         delete pC;
       
   519         return;
       
   520         }
       
   521     //Ensure that timer interrupt only hits a cpu that is still active
       
   522     // this won't be need when core retiring support is complete in the kernel
       
   523     // as it will migrate all interrupts to remaining enaged cores
       
   524     // also just for added realism make sure this thread can only run in cores that are still enaged
       
   525     TUint32 enaged = (~toBeRetired)&pC->iAllCpusMask;
       
   526     TInt targetCpu =  __e32_find_ls1_32(enaged);
       
   527     TUint32 targetCpuMask = 0x1<<targetCpu;
       
   528     PMBTRACE4(KRetireCore,0x11,targetCpu);
       
   529     targetCpuMask <<= ((KIntIdOstMatchMsTimer %4)<<3);
       
   530     TUint32 clear = ~(0xff << ((KHwBaseGlobalIntDist%4)<<3));
       
   531     GicDistributor* GIC = (GicDistributor*) KHwBaseGlobalIntDist;
       
   532     GIC->iTarget[KIntIdOstMatchMsTimer>>2]&=clear;
       
   533     __e32_io_completion_barrier();
       
   534     GIC->iTarget[KIntIdOstMatchMsTimer>>2]|=targetCpuMask;
       
   535     __e32_io_completion_barrier();
       
   536     NKern::ThreadSetCpuAffinity(NKern::CurrentThread(),targetCpu);
       
   537     TNE1_TBPowerController::iIdleHandler->ResetSyncPoints(); 
       
   538     DNE1_SMPIdleHandler::iRetiredCores=toBeRetired;
       
   539     PMBTRACE4(KRetireCore,0x12,DNE1_SMPIdleHandler::iRetiredCores);//,DNE1_TBPowerController::iEngagingCores);
       
   540     // queue callback
       
   541     pC->iCb.iResult = KErrNone;
       
   542     pC->iCb.iDfc.Enque();
       
   543     delete pC;
       
   544     }
       
   545 #endif
       
   546 
       
   547 //-/-/-/-/-/-/-/-/-/ class SEngageCall /-/-/-/-/-/-/-/-/-/
       
   548 
       
   549 SEngageCall::SEngageCall(TInt aCpu,TRetireEngageCb& aCb)
       
   550 #if defined(__SMP__) && !defined(__NO_IDLE_HANDLER_PIL__) && defined(SIMULATE_RETIREMENT)
       
   551     :iDfc(EngageCoreDfcFn,(TAny*)this,
       
   552           TNE1_TBPowerController::iIdleHandler->iRetireEngageQue,0),iCpu(aCpu),iCb(aCb)
       
   553 #endif
       
   554     {};
       
   555 
       
   556 #if defined(__SMP__) && !defined(__NO_IDLE_HANDLER_PIL__) && defined(SIMULATE_RETIREMENT)
       
   557 void SEngageCall::EngageCoreDfcFn(TAny* aParam)
       
   558     {
       
   559     SEngageCall* pC = (SEngageCall*) aParam;
       
   560     TUint32 cMask = 0x1<<pC->iCpu;
       
   561     PMBTRACE4(KEngageCore,0x10,cMask);
       
   562     if ((~DNE1_SMPIdleHandler::iRetiredCores)&cMask )
       
   563         {
       
   564         //core is already engaged
       
   565         pC->iCb.iResult = KErrArgument;
       
   566         pC->iCb.iDfc.Enque();
       
   567         delete pC;
       
   568         return;
       
   569         }
       
   570 
       
   571     TNE1_TBPowerController::iIdleHandler->ResetSyncPoints();  
       
   572     TIdleSupport::MarkCoreEngaged(cMask);
       
   573     DNE1_SMPIdleHandler::iRetiredCores&=~cMask;                // This will free calling CPU
       
   574     PMBTRACE4(KEngageCore,0x11,DNE1_SMPIdleHandler::iRetiredCores);
       
   575     pC->iCb.iResult = KErrNone;
       
   576     pC->iCb.iDfc.Enque();
       
   577     delete pC;
       
   578     }
       
   579 #endif
       
   580 
       
   581 
       
   582 
       
   583 TInt BinaryPowerInit();		// the Symbian example Battery Monitor and Power HAL handling
       
   584 
       
   585 GLDEF_C TInt KernelModuleEntry(TInt aReason)
       
   586 	{
       
   587 	if(aReason==KModuleEntryReasonVariantInit0)
       
   588 		{
       
   589 		//
       
   590 		//
       
   591 		//
       
   592 		__KTRACE_OPT(KPOWER, Kern::Printf("Starting NE1_TBVariant Resource controller"));
       
   593 		return KErrNone;
       
   594 		}
       
   595 	else if(aReason==KModuleEntryReasonExtensionInit0)
       
   596 		{
       
   597 		__KTRACE_OPT(KPOWER, Kern::Printf("Starting NE1_TBVariant power controller"));
       
   598 		//
       
   599 		// TO DO: (optional)
       
   600 		//
       
   601 		// Start the Kernel-side Battery Monitor and hook a Power HAL handling function.
       
   602 		// Symbian provides example code for both of the above in \e32\include\driver\binpower.h
       
   603 		// You may want to write your own versions.
       
   604 		// The call below starts the example Battery Monitor and hooks the example Power HAL handling function
       
   605 		// At the end we return an error to make sure that the entry point is not called again with
       
   606 		// KModuleEntryReasonExtensionInit1 (which would call the constructor of TheResourceManager again)
       
   607 		//
       
   608 		TInt r = BinaryPowerInit();
       
   609 		if (r!= KErrNone)
       
   610 			__PM_PANIC("Can't initialise Binary Power model");
       
   611 		DNE1_TBPowerController* c = new DNE1_TBPowerController();
       
   612 		if(c)
       
   613 			return KErrGeneral;
       
   614 		else
       
   615 			__PM_PANIC("Can't create Power Controller");
       
   616 		}
       
   617 	else if(aReason==KModuleEntryReasonExtensionInit1)
       
   618 		{
       
   619         // doesn't get called
       
   620 		}
       
   621 	return KErrArgument;
       
   622 	}
       
   623