//
// Copyright (c) Microsoft Corporation.  All rights reserved.
//
//
// Use of this source code is subject to the terms of the Microsoft end-user
// license agreement (EULA) under which you licensed this SOFTWARE PRODUCT.
// If you did not accept the terms of the EULA, you are not authorized to use
// this source code. For a copy of the EULA, please see the LICENSE.RTF on your
// install media.
//
/*++
THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
PARTICULAR PURPOSE.

Module Name:  mdprof.c

Abstract:
 This file implements the platform specific profiler support

Functions:


Notes:

--*/
#include <windows.h>
#include <nkintr.h>
#include <s2440.h>

// local data
volatile unsigned int ReschedCount;
volatile unsigned int ReschedCountMax;
BOOL bProfileEnabled=FALSE;             // platform profiler enabled flag

// external data
extern int (*PProfileInterrupt)(void);  // pointer to profiler ISR
extern DWORD dwReschedIncrement;

// external routines
extern void ProfilerHit(DWORD);				// exported by the kernel
extern DWORD GetEPC ();						// exported by the kernel
extern DWORD SetSysTimerInterval(DWORD);	// supplied by the OAL


int ProfileInterrupt(void)
{
	int nInt = SYSINTR_RESCHED;
	
	if (bProfileEnabled) {
		// every ReschedCountMax'th tick is a real reschedule
		ReschedCount++;
		ProfilerHit(GetEPC());
		if (ReschedCount >= ReschedCountMax) {
			// return SYSINTR_RESCHED and reset our tick counter
			ReschedCount = 0;
		} else {
			// not a reschedule interrupt
			nInt = SYSINTR_NOP;
		}
	}
	
	return nInt;
}

// When profiling is turned on, we halve the interrupt period so that
// we can use one interrupt for the profile and one for the timing
void OEMProfileTimerEnable(DWORD dwUSec)
{
    DWORD dwProfileIncrement;
	
    // calculate the number of ticks taking place in the profiling ISR before we call the
    // "real" ISR to update the millisecond count.
    dwProfileIncrement = (RESCHED_INCREMENT * dwUSec) / 1000;
    if(dwProfileIncrement != 0) {
		ReschedCountMax = RESCHED_INCREMENT / dwProfileIncrement;
		if(ReschedCountMax > 0) {
			ReschedCountMax -= 1;
		}
    } else {
		dwProfileIncrement = dwReschedIncrement;
		ReschedCountMax = 0;
    }
	
    DEBUGMSG(TRUE, (_T("OEMProfileTimerEnable: usec %u, profinc %u, max %u\r\n"), dwUSec, dwProfileIncrement, ReschedCountMax));
    ReschedCount = 0;
    dwReschedIncrement = dwProfileIncrement;
    PProfileInterrupt = ProfileInterrupt;
    SetSysTimerInterval(dwProfileIncrement);
    bProfileEnabled = TRUE;
}


void OEMProfileTimerDisable(void)
{
	bProfileEnabled=FALSE;
	PProfileInterrupt = NULL;
	dwReschedIncrement = RESCHED_INCREMENT;
	ReschedCountMax = 0;
	SetSysTimerInterval(dwReschedIncrement) ;
}

/* EOF mdprof.c */
