Home > Articles > Programming

Embedded Development: Handling Exceptions and Interrupts in eCos

The Embedded Configurable Operating System (eCos) gives professionals a low-cost, royalty-free embedded software development solution that works in highly constrained hardware environments, while scaling smoothly to larger products. In this book excerpt, you'll take a look at eCos exception handling, learning the two options and what features each holds. You will then turn to eCos split interrupt processing scheme using ISRs and DSRs and the eCos iterrupt handling process.
This chapter is from the book

In this chapter, we begin with a look at exceptions and how they are handled at the HAL and application layers within the eCos system. Next, we cover the eCos interrupt model, including interrupt configuration, handling, and control. The exception and interrupt information prepares us for managing software and hardware events that occur.

3.1 Exceptions

An exception is a synchronous event that occurs during the execution of a thread that disrupts the normal flow of instructions. If exceptions are not properly processed during program execution, severe consequences, such as system failures, can occur. Exception handling is extremely important, especially in embedded systems, to avoid these failures, and improves the robustness of the software. Properly implemented exception handling can also aid in software execution recovery so that an application can proceed with its task after an exception has occurred.

Examples of exceptions that can occur in a system include those raised by hardware (such as a memory access error) and those raised by software (such as a divide by zero error). After the exception causes an interruption, the processor will jump to a defined address (or exception vector) and begin to run the instructions at that location. The address that the processor jumps to contains the exception handling code to process the error. Different processor architectures might locate the exception handlers at various places and implement this jump process in a variety of methods.

The method for implementing exception handling can vary. eCos does not provide an implementation similar to the throw and catch facilities provided in C++. For an embedded system, the simplest and most flexible method for handling exceptions is to call a function. This function needs a context or an area to do its work, and is typically passed in information, such as the exception number and possibly some optional parameters, to process the exception. After returning from this exception handler function, the thread can continue its execution.

There are two main methods for exception handling in eCos. The first is a combination of HAL and Kernel Exception Handling. The HAL provides the general hardware-level exception processing and then passes control on to the application for any extended exception support needed. This is the default configuration method.

The second exception handling method is Application Exception Handling. This allows the application to take full control over any or all of the exceptions and attaches a vector service routine directly to the hardware. The exception handler routine needs to be written in assembly language when using this configuration method.

The configuration option names described are found in the graphical configuration tool. In parentheses are the CDL names for the given option. For example, using the graphical configuration tool you could look up the configuration option name HAL Exception Support, which is located in the configuration window. This configuration option has a CDL macro associated with it—in this case, CYGPKG_HAL_EXCEPTIONS—which is located in the Properties window of the graphical configuration tool. We cover the graphical configuration tool in Chapter 11, The eCos Toolset.

The configuration options that control the exception handling are the HAL Exception Support (CYGPKG_HAL_EXCEPTIONS) option, located under the Platform-Independent HAL Options (CYGPKG_HAL_COMMON) component, and the Exception Handling (CYGPKG_KERNEL_EXCEPTIONS) component under the eCos Kernel package. Each of these configuration components requires the other to be enabled. Enabling these options allows HAL and Kernel Exception Handling. If both of these configuration options are disabled, it is up to you to provide exception handlers for Application Exception Handling.

Figure 3.1 shows the exception handling execution flow for the two main configuration options. The gray boxes illustrate, using a system call exception as an example, the HAL and Kernel Exception Handling execution flow. The white boxes show the execution flow for Application Exception Handling using an alignment exception as an example. We look at the execution flow shown in Figure 3.1 later in this chapter.

Figure 01Figure 3.1 eCos exception handling execution flow.


As another option, all exception handling can be disabled in the system. If this configura-tion is selected and an exception occurs, the macro CYG_FAIL is called and an assertion is raised. If assertions are not enabled, the state of the processor is restored; however, the cause of the exception might still exist. This is not a very elegant method for exception handling and can lead to undefined system behavior when an exception occurs. However, if code space is extremely important, it might be necessary to eliminate any extended exception processing.

3.1.1 HAL and Kernel Exception Handling

It is important that an exception handler is installed for each exception supported by the processor. If a handler is not installed for a particular exception and it occurs during execution, the processor will jump to the exception address to begin execution only to find no code to execute. This can cause erratic behavior that can be very difficult to debug and might lead to system failures.

The eCos HAL uses a Vector Service Routine (VSR) table that is defined in each HAL package as hal_vsr_table. The VSR table is an array of pointers to the exception handler routines. The VSR table is the first place the processor looks to determine where to jump to execute the exception handler.1 The size and base address of the hal_vsr_table is architecture specific. For example, the PowerPC architecture has the option of locating the VSR table at either address 0x0000_0000 or 0xFFF0_0000, based on the configuration option settings of certain processor registers. The MIPS architecture specifies that the exception vector location be at address 0xBFC0_0000. Linker script files are used to define the location of the exception vector table. Linker script files are located under the arch subdirectory for a given HAL architecture and have a .ld extension.

The VSR table is located at a fixed memory location. This allows an application running from RAM, which is a typical debug configuration, to take control over certain exception service routines while keeping the ROM monitor in charge of debug exception handlers.

The eCos HAL ensures that a default exception VSR is installed during the HAL startup process for each exception supported by a given architecture. Installation of the default exception VSR takes place in the routine hal_mon_init. There is one default exception VSR defined in each HAL package. Different architectures have different names for the default exception VSR, as shown in Table 3.1.

The ARM architecture is not listed in Table 3.1 because it does not use the hal_vsr_table. Instead, the ARM architecture defines separate handler routines for each exception it supports. These routines can be found in the file vectors.S.

Table 3.1 Default Exception Vector Service Routines

Architecture

Default Exception Vector Service Routine Name

CalmRISC16a

__default_swi_vsr and __default_trq_vsr

Fujitsu FR-V

_exception

Hitachi H8/300

__default_trap_vsr

i386 (including Synth), PowerPC, SuperH

cyg_hal_default_exception_vsr

CalmRISC32, MIPS, MN10300

__default_exception_vsr

V8x

do_exception

SPARC, SPARClite

hal_default_exception_vsr


The job of the default exception VSR is to perform the common processing of all exceptions, which includes saving the processor's state, calling any kernel-level handler routine to perform additional processing, and restoring the state of the processor prior to returning to normal program execution.

After the HAL has completed the common exception processing, control is passed to the kernel level. The routine that is called to handle this HAL-to-kernel transition is cyg_hal_exception_handler. This routine is found in the file hal_misc.c under the HAL arch subdirectory. The cyg_hal_exception_handler routine has two different execution paths possible, based on configuration option settings. If we look at Figure 3.1, we can follow the execution path for a system call exception, shown in the gray boxes. At the kernel level, the two possible configuration options are labeled on the lines leading from the cyg_hal_exception_handler routine.

The first kernel-level configuration option we see in Figure 3.1 is Include GDB Stubs in HAL (CYGDBG_HAL_DEBUG_GDB_INCLUDE_STUBS), which is under the Source-Level Debug Support HAL (CYGPKG_HAL_DEBUG) common component. This option is typically used in a HAL package for a ROM monitor build to allow the debug stub code to process the exception. This exception processing occurs in the routine __handle_exception. The __handle_exception routine manages all debug exception processing such as breakpoints, single stepping, and debug packet protocol communication. Additional information about GDB and the GDB protocol can be found online at:

http://sources.redhat.com/gdb/onlinedocs/gdb_toc.html

The second kernel-level configuration option we see in Figure 3.1 is HAL Exception Support (CYGPKG_HAL_EXCEPTIONS), under the General Platform-Independent HAL common component. This HAL option requires the Kernel Exception Handling to be enabled in the eCos Kernel package. In this configuration, an application can install its own handler for exceptions to take care of any further processing, such as displaying or logging an error message.

Within the kernel Exception Handling (CYGPKG_KERNEL_EXCEPTIONS) option is the configuration suboption Use Global Exception Handlers (CYGSEM_KERNEL_EXCEPTIONS_ GLOBAL), which allows installation of handlers to be either global—one set of handlers for all exceptions in the entire system—or on a per-thread basis. The default configuration for this sub-option setting is to enable global exception handlers. In this configuration, the HAL exception handler calls the routine cyg_hal_deliver_exception, which is located in the file except.cxx under the kernel package subdirectory.

Item List 3.1

Syntax:

void
cyg_exception_set_handler(
 cyg_code_t exception_number,
 cyg_exception_handler_t *new_handler,
 cyg_addrword_t new_data,
 cyg_exception_handler_t **old_handler,
 void **old_data
);

Context:2

Thread

Parameters:

exception_number—HAL architecture-specific exception definition number. Each HAL defines, in the file hal_intr.h, all exceptions supported starting from 0. new_handler—address of application exception handler routine to be called after HAL has completed its exception processing. new_data—data to be passed into exception handler. old_handler—address of previously installed exception handler, or NULL if this is the first handler installed for the exception. old_data—data of previously installed exception handler, or NULL if this is the first handler installed for the exception.

Description:

Replace the current exception handler either globally or on a per thread basis, depending on the kernel exception handling configuration.

Syntax:

void
cyg_exception_clear_handler(
 cyg_code_t exception_number,
); 

Context:

Thread

Parameters:

exception_number—HAL architecture-specific exception definition number. Each HAL defines, in the file hal_intr.h, all exceptions supported starting from 0. Description: Restores the default handler.

Syntax:

void
cyg_exception_call_handler(
 cyg_handle_t thread,
 cyg_code_t exception_number,
 cyg_addrword_t exception_info
 ); 

Context:

Thread

Parameters:

thread—current handle for the executing thread allowing the thread to call the global or thread exception handler. exception_number—HAL architecture-specific exception definition number. Each HAL defines, in the file hal_intr.h, all exceptions supported starting from 0. exception_info—this parameter is the third parameter passed into the exception handler routine.

Description:

Invokes the installed exception handler for the given exception number. The return value is void for this function.


To control the exception service routines from the application, the eCos kernel defines functions within its API. Item List 3.1 shows the details of these functions.

  1  #include <cyg/kernel/kapi.h>
  2  #include <cyg/infra/diag.h>
  3  #include <cyg/hal/hal_intr.h>
  4
  5  //
  6  // New System Call exception handler.
  7  //
  8  void system_call_exception_handler(
  9     cyg_addrword_t data,
10      cyg_code_t number,
11      cyg_addrword_t info)
12  { 
13    diag_printf( "ERROR: System Call Exception\n" );
14  } 
15
16
17  // 
18  // Main starting point for the application.
19  // 
20  void cyg_user_start(
21         void)
22  { 
23    cyg_exception_handler_t *old_handler;
24    cyg_addrword_t old_data;
25
26    //
27    // Install the exception handler for error output.
28    //
29    cyg_exception_set_handler(
30       CYGNUM_HAL_VECTOR_SYSTEM_CALL,
31       &system_call_exception_handler,
32       0,
33       &old_handler,
34       &old_data);
35  }

Code Listing 3.1 Example using the eCos kernel API for installing an exception handler within an application.

In Code Listing 3.1, we see an example of an application setting up the routine system_call_exception_handler, shown on line 8, for the PowerPC system call exception, CYGNUM_HAL_VECTOR_SYSTEM_CALL. CYGNUM_HAL_VECTOR_SYSTEM_CALL is defined in the PowerPC HAL package in the file hal_intr.h, which is included on line 3.

In this example, the exception handler simply writes out a message to the diagnostic port when this particular exception occurs, as shown on line 13. The function used is diag_printf, which is defined in the file diag.h included on line 2. When the call is made to install the handler, line 29, it can apply to either the thread or globally, depending on the con-figuration of the Use Global Exception Handlers (CYGSEM_KERNEL_EXCEPTIONS_GLOBAL) exception handling configuration suboption.

The cyg_user_start function, on line 20, is the main application entry point. The kernel startup process describing the cyg_user_start function is detailed in Chapter 5. To use the kernel API, the application must include the file kapi.h. The parameters passed into system_call_exception_handler, lines 9, 10, and 11, are:

datathe parameter setup in the cyg_exception_set_handlercall (0 in this example). It is often useful to use this parameter to pass a pointer to a structure for the exception handler routine to have information needed.

numberthe exception number that occurred.

infothe processor-specific saved machine state. Currently, a pointer to the HAL_SavedRegisters structure is passed in this parameter. If this structure is modified, the saved state of the processor is altered. This allows the exception handler to correct the condition in order to allow the processor to continue. See the HAL macro definitions in Chapter 2 for an explanation of this architecture-specific structure.

If we look at Figure 3.1, the gray boxes illustrate the execution flow after setting up the exception handler in Code Listing 3.1.

The final routine that is called from the HAL is restore_state, as shown in Figure 3.1. This routine restores the processor registers to the state they were in prior to entering the default exception VSR. The state of the processor is contained in the HAL_SavedRegisters structure, which is passed in as a pointer. After restore_state returns, the processor can continue with its normal execution of the program.

3.1.2 Application Exception Handling

eCos provides a means for an application to completely take over all or some of the exception handling. This eliminates the HAL and kernel processing and allows the processor to vector directly to an application's VSR when an exception occurs. The application exception handler is then responsible for saving and restoring the processor's state, the same functionality provided by the HAL default exception VSR. It is also important to note that the VSR must be written in assembly language.

As we see in Figure 3.1, the white boxes illustrate how the application can take over exception handling. After the alignment exception occurs the VSR installed by the application is called to handle the exception condition. After the VSR completes, the handler must restore the processor's state so that the program can continue running.

The HAL defines macros to give the application access to the VSR table directly. These macros are described in Item List 3.2.

Item List 3.2 HAL Exception Vector Service Routine Macros

Syntax:

HAL_VSR_GET(
 _vector_,
 _pvsr_
 ) 

Parameters:

_vector_—exception vector to retrieve from the VSR table. Each HAL defines, in the file hal_intr.h, all exceptions supported starting from 0. This value is used to determine the index into the VSR table.

_pvsr_—returned address of the VSR from the table.

Description:

Get the current VSR set in the hal_vsr_table and return it in the location pointed to by _pvsr_.

Syntax:

HAL_VSR_SET(
 vector_,
 vsr_,
 poldvsr_
 ) 

Parameters:

_vector_—exception vector to set in the VSR table. Each HAL defines, in the file hal_intr.h, all exceptions supported starting from 0. This value is used to determine the index into the VSR table.

vsr_—new vector service routine address to set in the VSR table.

poldvsr_—returned address of the previously installed VSR.

Description:

Replace the routine in the hal_vsr_table with the new vector service routine.


When installing a vector service routine, it is not necessary to call the HAL set and get macros directly. The eCos kernel API defines functions for the application to use instead. Item List 3.3 shows the kernel API functions for accessing the VSR table. These functions call the respective get and set HAL macros defined in Item List 3.3. For example, cyg_interrupt_get_vsr calls the HAL macro HAL_VSR_GET.

Item List 3.3 Kernel Exception Vector Service Routine API Functions

Syntax:

void
cyg_interrupt_get_vsr(
 cyg_vector_t vector,
 cyg_VSR_t **vsr
 );

Context:

Any

Parameters:

vector—exception vector to retrieve from the VSR table. Each HAL defines, in the file hal_intr.h, all exceptions supported starting from 0. This value is used to determine the index into the VSR table. vsr—returned pointer to vector service routine currently set in the VSR table.

Description:

Return the pointer for the given exception vector from the VSR table.

Syntax:

void
cyg_interrupt_set_vsr(
 cyg_vector_t vector,
 cyg_VSR_t *vsr
 );

Context:

Any

Parameters:

vector—exception vector to set in the VSR table. Each HAL defines, in the file hal_intr.h, all exceptions supported starting from 0. This value is used to determine the index into the VSR table. vsr—address of the vector service routine to be set in the VSR table.

Description:

Set the vector service routine directly into the VSR table. This vector service routine must be written in assembly and handle all exception processing, such as saving and restoring the processor state information.


InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020