avr-libc-dev
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[avr-libc-dev] Interrupt vector redirection scheme


From: Michael Schulze
Subject: [avr-libc-dev] Interrupt vector redirection scheme
Date: Fri, 31 Aug 2007 11:06:50 +0200
User-agent: Thunderbird 1.5.0.12 (X11/20070719)

Hi all,

I propose a new interrupt vector redirection scheme which can be integrated seamless into the avr-libc in my opinion without having side effects. It allows the redirection only of those interrupts changing over the runtime of the system. The usage of ISR and therewith the direct binding of an interrupt to a special function is always possible at the same time.

How does it is used?
For changable ISR's you use a macro called REDIR_ISR(vector) in order to define the necessary redirection stub and a memory variable for saving the address of the service routine, which have to be called, if the interrupt triggers. If you want to put a service routine, you use the macro redirectISR(vector, funct).

How does it works?
If the interrupt fires a jump to the redirection stub is done. The stub pushes the Z-pointer and loads the content of the associated memory variable into the Z-pointer following by a jump to a common redirection function. The function checks the value of the Z-pointer. If it is zero it pops old values to the Z-pointer and returns form interrupt. If the Z-pointer isn't zero it pushes a lot of registers, calls the function pointed by the Z-pointer and after coming back from it, pops the registers and return from interrupt.

Attached, you find an implementation for the at90can128 which shows the redirection scheme. I also tested it on the atmega128 successfully.
You can see that the standard way with ISR can coexist with REDIR_ISR.

I also made some measurement tests to check the size of the code in contrast to an redirection on C programming level. I used a test programm with fewer DEBUG outputs and therefore you shouldn't wonder that you get other sizes, if you compile the source.

Test environment:
        - binutils 2.17
        - avr-gcc 4.2.1
        - avr-libc 1.4.6
        - uC at90can128

count of Interrupts     Data    Text    Bss
0                       70      430     0

Redirection on C programming level
1                       70      530     2
2                       70      612     4
3                       70      694     6
4                       70      767     8

Redirection scheme with stubs
1                       70      534     2
2                       70      550     4
3                       70      566     6
4                       70      582     8

The stubs solution is smaller than the C version, if you need two redirections and so the break even is two redirections.

IMO it is an enhancement to the old proved scheme of ISR binding. REDIR_ISR can be used if someone needs the redirection functionality, but no-one have to pay for that, if it will not used.

How the maintainers see this? Is there a possibility of an integration of the redirection scheme in one of the next versions of avr-libc?


Michael
        

#define F_CPU 16000000

#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>

#include "redirvec.h"

#define DEBUG_INIT() do {                               \
        UBRR0H = (unsigned char) (51>>8);               \
        UBRR0L = (unsigned char) 51;                    \
        /* Enable UART receiver and transmitter */      \
        UCSR0B = ( ( 1 << RXEN0 ) | ( 1 << TXEN0 ) );   \
        /* Set frame format: 8N1 */                     \
        UCSR0C = (1<<UCSZ01)|(1<<UCSZ00);               \
        } while (0)

#define DEBUG(string) do {                              \
        volatile char* stri = string;                   \
        while( *stri ){                                 \
        /* Wait for empty transmit buffer */            \
        while ( !(UCSR0A & (1<<UDRE0)) );               \
        /* Start transmittion */                        \
                UDR0 = (unsigned char) *stri++;         \
        } } while (0)

void int_handler_example() {
  DEBUG("Timer1\n");
}

void int_handler_example2() {
  DEBUG("Timer1 resurrection\n");
}

// Binding the ISR directly to the interrupt vector
// Timer3 overflow interrupt service routine will and
// can never be changed
ISR(TIMER3_OVF_vect) {
        DEBUG("Timer3\n");
}

// Binding a redirection stub to the interrupt vector
// Timer1 overflow interrupt service routine can be
// changed at runtime
REDIR_ISR(TIMER1_OVF_vect)

int main() {
        register uint16_t i = 0x0400;
        DEBUG_INIT();
        DEBUG("Hallo World\n");

        DEBUG("plug in the ISR for timer 1\n");
        redirectISR(TIMER1_OVF_vect,&int_handler_example);
        
        DEBUG("initialize the the timer 1 and 3\n");
        TCCR1B = ((1<<CS12) | (1<<CS10));   // 1024 prescaler = 4s
        TIMSK1 = (1<<TOIE1); // enable overflow irq
        TCCR3B = ((1<<CS32) | (1<<CS30));   // 1024 prescaler = 4s
        TIMSK3 = (1<<TOIE3); // enable overflow irq

        DEBUG("allow interrupts globally\n");
        sei(); // enable global interrupts

        DEBUG("Wait some time before changing the ISR of timer 1\n");
        while ( i-- ){
            _delay_ms(20);
        }

        DEBUG("pluging in another ISR for timer 1\n");
        redirectISR(TIMER1_OVF_vect,&int_handler_example2);
        while(1);
}
# WinAVR Sample makefile written by Eric B. Weddington, Jrg Wunsch, et al.
# Released to the Public Domain
# Please read the make user manual!
#
# Additional material for this makefile was submitted by:
#  Tim Henigan
#  Peter Fleury
#  Reiner Patommel
#  Sander Pool
#  Frederik Rouleau
#  Markus Pfaff
#
# On command line:
#
# make all = Make software.
#
# make clean = Clean out built project files.
#
# make coff = Convert ELF to AVR COFF (for use with AVR Studio 3.x or VMLAB).
#
# make extcoff = Convert ELF to AVR Extended COFF (for use with AVR Studio
#                4.07 or greater).
#
# make program = Download the hex file to the device, using avrdude.  Please
#                customize the avrdude settings below first!
#
# make filename.s = Just compile filename.c into the assembler code only
#
# To rebuild project do "make clean" then "make all".
#

# MCU name
MCU = at90can128

# Output format. (can be srec, ihex, binary)
FORMAT = ihex

# Target file name (without extension).
TARGET = redir

# Optimization level, can be [0, 1, 2, 3, s]. 0 turns off optimization.
# (Note: 3 is not always the best optimization level. See avr-libc FAQ.)
OPT = s


# List C source files here. (C dependencies are automatically generated.)
SRC =  main.c 

# List Assembler source files here.
# Make them always end in a capital .S.  Files ending in a lowercase .s
# will not be considered source files but generated files (assembler
# output from the compiler), and will be deleted upon "make clean"!
# Even though the DOS/Win* filesystem matches both .s and .S the same,
# it will preserve the spelling of the filenames, and gcc itself does
# care about how the name is spelled on its command-line.
ASRC =  redirvec.S


# List any extra directories to look for include files here.
#     Each directory must be seperated by a space.
EXTRAINCDIRS =

# Optional compiler flags.
#  -g:        generate debugging information (for GDB, or for COFF conversion)
#  -O*:       optimization level
#  -f...:     tuning, see gcc manual and avr-libc documentation
#  -Wall...:  warning level
#  -Wa,...:   tell GCC to pass this to the assembler.
#    -ahlms:  create assembler listing

DEBUG_LEVEL=-g
WARNINGS=-Wall -Wextra -Wshadow -Wpointer-arith                         \
        -Wcast-align -Wsign-compare                                     \
        -Waggregate-return                                              \
        -Wunused

#       -fno-exceptions, as the avr-libs-faq suggests for c++
#       -fno-threadsafe-statics, local static objects can be used, as there 
#                                are no threads running
#       -fdata-sections -ffunction-sections, in order to remove dead code
CFLAGS = -D GCC_MEGA_AVR -I.    \
        $(DEBUG_LEVEL) -O$(OPT)                                         \
        -funsigned-char -funsigned-bitfields -fpack-struct -fshort-enums\
        $(WARNINGS)                                                     \
        -Wa,-adhlns=$(<:.c=.lst)                                        \
        $(patsubst %,-I%,$(EXTRAINCDIRS))                               \
#       -fno-exceptions                                                 \
#       -fno-threadsafe-statics                                         \
#       -fdata-sections -ffunction-sections



# Set a "language standard" compiler flag.
#   Unremark just one line below to set the language standard to use.
#   gnu99 = C99 + GNU extensions. See GCC manual for more information.
#CFLAGS += -std=c89
#CFLAGS += -std=gnu89
#CFLAGS += -std=c99
#CFLAGS += -std=gnu99


# Optional assembler flags.
#  -Wa,...:   tell GCC to pass this to the assembler.
#  -ahlms:    create listing
#  -gstabs:   have the assembler create line number information; note that
#             for use in COFF files, additional information about filenames
#             and function names needs to be present in the assembler source
#             files -- see avr-libc docs [FIXME: not yet described there]
ASFLAGS = -Wa,-adhlns=$(<:.S=.lst),-gstabs 

# Optional linker flags.
#  -Wl,...:   tell GCC to pass this to linker.
#  -Map:      create map file
#  --cref:    add cross reference to  map file
# -static,--gc-sections in order to remove dead code
LDFLAGS = -Wl,-Map=$(TARGET).map,--cref

# Additional libraries

# Minimalistic printf version
#LDFLAGS += -Wl,-u,vfprintf -lprintf_min

# Floating point printf version (requires -lm below)
#LDFLAGS += -Wl,-u,vfprintf -lprintf_flt

# -lm = math library
#LDFLAGS += -lm

# Optional archiver flags
#   r: insert the object modules into the archive with replacement
#   c: create the archive. 
#   s: write/update an object-file index into the archive
ARFLAGS = rcs




# Programming support using avrdude. Settings and variables.

# Programming hardware: alf avr910 avrisp bascom bsd 
# dt006 pavr picoweb pony-stk200 sp12 stk200 stk500
#
# Type: avrdude -c ?
# to get a full listing.
#
AVRDUDE_PROGRAMMER = pcan

# programmer connected to Controller Area Network
AVRDUDE_PORT =  /dev/pcan24

AVRDUDE_WRITE_FLASH = -U flash:w:$(TARGET).hex

AVRDUDE_FLAGS = -p $(MCU) -P $(AVRDUDE_PORT) -c $(AVRDUDE_PROGRAMMER) -u -F -D

# Uncomment the following if you want avrdude's erase cycle counter.
# Note that this counter needs to be initialized first using -Yn,
# see avrdude manual.
#AVRDUDE_ERASE += -y

# Uncomment the following if you do /not/ wish a verification to be
# performed after programming the device.
AVRDUDE_FLAGS += -V

# Increase verbosity level.  Please use this when submitting bug
# reports about avrdude. See <http://savannah.nongnu.org/projects/avrdude> 
# to submit bug reports.
#AVRDUDE_FLAGS += -v -v




# ---------------------------------------------------------------------------

# Define directories, if needed.
DIRAVR =
DIRAVRBIN = 

# Define programs and commands.
SHELL = sh

CC = $(DIRAVRBIN)avr-gcc

OBJCOPY = $(DIRAVRBIN)avr-objcopy
OBJDUMP = $(DIRAVRBIN)avr-objdump
SIZE = $(DIRAVRBIN)avr-size
AVRNM = $(DIRAVRBIN)avr-nm
AVRAR = $(DIRAVRBIN)avr-ar

# Programming support using avrdude.
AVRDUDE = $(DIRAVRBIN)avrdude


REMOVE = rm -f
COPY = cp

HEXSIZE = $(SIZE) --target=$(FORMAT) $(TARGET).hex
ELFSIZE = $(SIZE) -A $(TARGET).elf



# Define Messages
# English
MSG_ERRORS_NONE = Errors: none
MSG_BEGIN = -------- begin --------
MSG_END = --------  end  --------
MSG_SIZE_BEFORE = Size before: 
MSG_SIZE_AFTER = Size after:
MSG_COFF = Converting to AVR COFF:
MSG_EXTENDED_COFF = Converting to AVR Extended COFF:
MSG_FLASH = Creating load file for Flash:
MSG_EEPROM = Creating load file for EEPROM:
MSG_EXTENDED_LISTING = Creating Extended Listing:
MSG_SYMBOL_TABLE = Creating Symbol Table:
MSG_LINKING = Linking:
MSG_COMPILING = Compiling:
MSG_ASSEMBLING = Assembling:
MSG_CLEANING = Cleaning project:
MSG_LIBRARY = Creating library:




# Define all object files.
OBJ = $(SRC:.c=.o) $(ASRC:.S=.o) 

# Define all listing files.
LST = $(ASRC:.S=.lst) $(SRC:.c=.lst)

# Combine all necessary flags and optional flags.
# Add target processor to flags.
ALL_CFLAGS = -mmcu=$(MCU) -I. $(CFLAGS)
ALL_ASFLAGS = -mmcu=$(MCU) -I. -x assembler-with-cpp $(ASFLAGS)



# Default target.
all: begin gccversion sizebefore $(TARGET).elf $(TARGET).hex $(TARGET).eep \
        $(TARGET).lss $(TARGET).sym sizeafter finished end

lib:begin gccversion $(TARGET).a finished end

# Eye candy.
# AVR Studio 3.x does not check make's exit code but relies on
# the following magic strings to be generated by the compile job.
begin:
        @echo
        @echo $(MSG_BEGIN)

finished:
        @echo $(MSG_ERRORS_NONE)

end:
        @echo $(MSG_END)
        @echo


# Display size of file.
sizebefore:
        @if [ -f $(TARGET).elf ]; then echo; echo $(MSG_SIZE_BEFORE); 
$(ELFSIZE); echo; fi

sizeafter:
        @if [ -f $(TARGET).elf ]; then echo; echo $(MSG_SIZE_AFTER); 
$(ELFSIZE); echo; fi



# Display compiler version information.
gccversion : 
        @$(CC) --version




# Convert ELF to COFF for use in debugging / simulating in
# AVR Studio or VMLAB.
COFFCONVERT=$(OBJCOPY) --debugging \
        --change-section-address .data-0x800000 \
        --change-section-address .bss-0x800000 \
        --change-section-address .noinit-0x800000 \
        --change-section-address .eeprom-0x810000 


coff: $(TARGET).elf
        @echo
        @echo $(MSG_COFF) $(TARGET).cof
        $(COFFCONVERT) -O coff-avr $< $(TARGET).cof


extcoff: $(TARGET).elf
        @echo
        @echo $(MSG_EXTENDED_COFF) $(TARGET).cof
        $(COFFCONVERT) -O coff-ext-avr $< $(TARGET).cof




# Program the device.  
program: $(TARGET).hex $(TARGET).eep
        $(AVRDUDE) $(AVRDUDE_FLAGS) $(AVRDUDE_WRITE_FLASH) 
$(AVRDUDE_WRITE_EEPROM)




# Create final output files (.hex, .eep) from ELF output file.
%.hex: %.elf
        @echo
        @echo $(MSG_FLASH) $@
        $(OBJCOPY) -O $(FORMAT) -R .eeprom $< $@

%.eep: %.elf
        @echo
        @echo $(MSG_EEPROM) $@
        -$(OBJCOPY) -j .eeprom --set-section-flags=.eeprom="alloc,load" \
        --change-section-lma .eeprom=0 -O $(FORMAT) $< $@

# Create extended listing file from ELF output file.
%.lss: %.elf
        @echo
        @echo $(MSG_EXTENDED_LISTING) $@
        $(OBJDUMP) -h -S $< > $@

# Create a symbol table from ELF output file.
%.sym: %.elf
        @echo
        @echo $(MSG_SYMBOL_TABLE) $@
        $(AVRNM) -n $< > $@



# Link: create ELF output file from object files.
.SECONDARY : $(TARGET).elf
.PRECIOUS : $(OBJ)
%.elf: $(OBJ)
        @echo
        @echo $(MSG_LINKING) $@
        $(CC) $(ALL_CFLAGS) $(OBJ) --output $@ $(LDFLAGS)

# Link: create library output file from object files.
%.a: $(OBJ)
        @echo
        @echo $(MSG_LIBRARY) $@
        $(AVRAR) $(ARFLAGS) $@ $(OBJ) 

# Compile: create object files from C source files.
%.o : %.c
        @echo
        @echo $(MSG_COMPILING) $<
        $(CC) -c $(ALL_CFLAGS) $< -o $@


# Compile: create assembler files from C source files.
%.s : %.c
        $(CC) -S $(ALL_CFLAGS) $< -o $@


# Assemble: create object files from assembler source files.
%.o : %.S
        @echo
        @echo $(MSG_ASSEMBLING) $<
        $(CC) -c $(ALL_ASFLAGS) $< -o $@






# Target: clean project.
clean: begin clean_list finished end

clean_list :
        @echo
        @echo $(MSG_CLEANING)
        $(REMOVE) $(TARGET).hex
        $(REMOVE) $(TARGET).eep
        $(REMOVE) $(TARGET).obj
        $(REMOVE) $(TARGET).cof
        $(REMOVE) $(TARGET).elf
        $(REMOVE) $(TARGET).map
        $(REMOVE) $(TARGET).obj
        $(REMOVE) $(TARGET).a90
        $(REMOVE) $(TARGET).sym
        $(REMOVE) $(TARGET).lnk
        $(REMOVE) $(TARGET).lss
        $(REMOVE) $(TARGET).a
        $(REMOVE) $(OBJ)
        $(REMOVE) $(LST)
        $(REMOVE) $(SRC:.c=.s)
        $(REMOVE) $(SRC:.c=.d)


# Automatically generate C source code dependencies. 
# (Code originally taken from the GNU make user manual and modified 
# (See README.txt Credits).)
#
# Note that this will work with sh (bash) and sed that is shipped with WinAVR
# (see the SHELL variable defined above).
# This may not work with other shells or other seds.
#
%.d: %.c
        set -e; $(CC) -MM $(ALL_CFLAGS) $< \
        | sed 's,\(.*\)\.o[ :]*,\1.o \1.d : ,g' > $@; \
        [ -s $@ ] || rm -f $@


# Remove the '-' if you want to see the dependency files generated.
-include $(SRC:.c=.d)



# Listing of phony targets.
.PHONY : all begin finish end sizebefore sizeafter gccversion coff extcoff \
        clean clean_list program

#ifndef REDIRVEC_H_
#define REDIRVEC_H_

#include <avr/io.h>

// defining of redirection memory variable and 
// the redirection stub for the certain vector
#define REDIR_ISR(vector)       __REDIR_ISR(vector)
#define __REDIR_ISR(vector)                             \
        uint16_t vector ## _REDIR=0;                    \
        void vector (void) __attribute__ ((naked));     \
        void vector (void) {                            \
                asm volatile (                          \
                        "push r31               \n"     \
                        "push r30               \n"     \
                        "lds r30, %0            \n"     \
                        "lds r31, %0+1          \n"     \
                        "jmp redir_func         \n"     \
                        :                               \
                        :"m" (vector ## _REDIR)         \
                        );                              \
                }


// macro for setting the redirection function 
// for a specific vector
#define redirectISR(vector,func)        __redirectISR(vector,func)
#define __redirectISR(vector,func)                      \
do {                                                    \
        extern uint16_t vector ## _REDIR;               \
        uint8_t tmp=SREG;                               \
        cli();                                          \
        vector ## _REDIR=(uint16_t)func;                \
        SREG=tmp;                                       \
} while(0)

#endif
#include <avr/io.h>

; global redirection routine
; saves registers as needed and redirect to the
; address specified in redirection memory variable
.global redir_func
.func redir_func
redir_func:
        sbiw ZL, 0                      ; test for zero
        breq redir_func_restore         ; skip, if zero                         

                                        ; save used registers. Saves all 
                                        ; call-used registers. Called routines
                                        ; SHOULD do this by default. But 
                                        ; ignored for the sake of clarity and 
                                        ; in case of naked routines 
        push r1                         ; save zero register
        eor r1, r1                      ; clear zero register, as assumed to
                                        ; always be zero
        push r0                         ; save temporary register
                                        ; long names (__zero_reg__) 
                                        ; first avaiable in macros.inc
        in r0, _SFR_IO_ADDR(SREG)       ; load status. SREG is a SFR macro
        push r0                         ; save loaded status. Assumes irqs are 
                                        ; disabled
        push r18                        ; save other call-used registers
        push r19                        ;
        push r20                        ;
        push r21                        ;
        push r22                        ;
        push r23                        ;
        push r24                        ;
        push r25                        ;
        push XL                         ;
        push XH                         ;
                                
        
        icall                           ; jump to address pointed by Z pointer

                                        ; back from routine.
                                        ; restore used registers
        pop XH                          ; restore call-used registers
        pop XL                          ;
        pop r25                         ;
        pop r24                         ;
        pop r23                         ;
        pop r22                         ;
        pop r21                         ;
        pop r20                         ;
        pop r19                         ;
        pop r18                         ;
        pop r0                          ; restore status register into temporary
        out _SFR_IO_ADDR(SREG), r0      ; load status register
        pop r0                          ; restore temporary register     
        pop r1                          ; restore zero register  
redir_func_restore:
        pop ZL                          ; restore lower Z pointer        
        pop ZH                          ; restore higher Z pointer       
        reti                            ; return from redirection and so return
                                        ; from interrupt
.endfunc                                ; end of redirection routine    

.end            

Attachment: smime.p7s
Description: S/MIME Cryptographic Signature


reply via email to

[Prev in Thread] Current Thread [Next in Thread]