2.3. Interrupt Handling

Interrupt handling is made relatively simple by the header file <intrrpt.h> and associated library functions. This file declares the interrupt numbers, and provides a function to connect any interrupt to a user handler.

The run-time system contains a declaration of the interrupt vector, and provides the functions to connect a C function to an interrupt so that when the interrupt is raised, the C function is called. You should note that the stack used during an interrupt is not the main stack. The first interrupt switches from the main stack to the interrupt stack, and then any nested interrupts continue to use the interrupt stack. You should therefore ensure that the interrupt stack is big enough to accommodate interrupts nested up to the maximum depth your hardware is capable of.

The sizes of the main and interrupt stacks are set in the linker script file.

Where an interrupt handler accesses a data area shared between the handler and some base level code, then objects in the data area should be marked as volatile. This ensures that the compiler generates all the loads and all the stores and does not work on copies in registers.

This is the file hello7.cpp from the examples directory on the CD-ROM.

Example 2-3. How to Attach and Interrupt Handler


/////////////////////////////////////////////////////////////////
//
// Filename:
//
//   hello7.cpp
//
// Description:
//
//   Example of how to connect an interrupt to a handler.
//
// Revision:
//
//   $Id: gcc-erc32-gs.xml,v 1.8 2008/10/31 17:54:07 nettleto Exp $
//
/////////////////////////////////////////////////////////////////

#include <stdio.h>
#include <intrrpt.h>
#include <sys/kernel.h>

// Variable is shared, but is atomic, so no protection needed
static volatile int cnt;

void
timer_handler (int sig)
{
  printf ("Hello world %d\n", ++cnt);
  __xgc_restart_timer (10000);
}

int
main ()
{
  // Connect our interrupt handler to the interrupt.

  handler (INTALRM, timer_handler);

  // Request timer interrupt, 10000 microseconds from now

  __xgc_restart_timer (10000);

  // Wait until we've had 10 clock interrupts

  while (cnt < 10)
    ;
}