Detecting the current executing context

dreamsters wrote on Wednesday, March 29, 2017:

Hi

I run FreeRTOS on an STM32 and inorder to detect if the current executing function is running in an interrupt or non-interrupt context. The following will do the job for me.

boolean bCalledFromInterrupt(void) {
    if ( (SCB->ICSR & SCB_ICSR_VECTACTIVE_Msk) != 0) {
    	return TRUE;
    }
    else {
    	return FALSE;
    }
}

But is still cant distinguish between interrupts that may call FromISR functions and others that dont. I can ofcourse implement a lookuptable, but then I also have to maintain that.

I have looked at vPortValidateInterruptPriority in port.c which does detect the interesting case, but does not allow me to use the functionallity as it uses assert.

How about adding something like this to FreeRTOS that allows the caller to detect the current executing context.

typedef enum {
   UTIL_RTOS_NO_CALLS 			= 0U,
   UTIL_RTOS_TASK_CALLS 		= 1U,
   UTIL_RTOS_ISR_CALLS			= 2U,
} teRTOSCallType;


teRTOSCallType teGetRTOSAPIType(void) {
	teRTOSCallType ret_val = UTIL_RTOS_NO_CALLS;
	BaseType_t scheduler_state = xTaskGetSchedulerState();

	if (scheduler_state == taskSCHEDULER_NOT_STARTED) {
		// Already set to no_calls
	}
	else {
		boolean from_interrupt 	= bCalledFromInterrupt();

		if (from_interrupt == FALSE) {
			ret_val = UTIL_RTOS_TASK_CALLS;
		}
		else {
			boolean safe_isr = bMayCallRTOSISR();
			if (safe_isr == TRUE) {
				ret_val =  UTIL_RTOS_ISR_CALLS;
			}
			else {
				// Already set to no_calls
			}
		}
	}
	return ret_val;
}

where the bMayCallRTOSISR call will use the same statevariables and logic as vPortValidateInterruptPriority.

Best regads
Martin

rtel wrote on Wednesday, March 29, 2017:

I run FreeRTOS on an STM32 and inorder to detect if the current
executing function is running in an interrupt or non-interrupt context.
The following will do the job for me.

boolean bCalledFromInterrupt(void) {
if ( (SCB->ICSR & SCB_ICSR_VECTACTIVE_Msk) != 0) {
return TRUE;
}
else {
return FALSE;
}
}

See the function xPortIsInsideInterrupt() in
FreeRTOS/Source/portable/GCC/ARM_CM4F/portmacro.h. Maybe we could
update that function to return the priority of the currently executing
interrupt rather than just pdTRUE.

dreamsters wrote on Thursday, March 30, 2017:

Wouldnt we also need a way to compare that to the to the ucMaxSysCallPriority and adjust for the interrupt priority depending of the port?

richard_damon wrote on Thursday, March 30, 2017:

Since an ISR for an interrupt above ucMaxSysCallPriority isn’t allowed to call ANY FreeRTOS API routine, there isn’t really a need to determine which one they can call, since it is neither.

I can understand somewhat the desire for such a function, if you are writing an API for something, so you don’t need to replicate non-ISR and FromISR API points, but I have seen that this is more often an indication that too much is being done in the interrupt.