12 SOPC NiosII Exception Interrupt - iet.unipi.it · The VIC core is SOPC Builder-ready and...

44
SISTEMI EMBEDDED (Software) Exceptions and (Hardware) Interrupts Federico Baronti Last version: 20160410

Transcript of 12 SOPC NiosII Exception Interrupt - iet.unipi.it · The VIC core is SOPC Builder-ready and...

SISTEMIEMBEDDED

(Software)Exceptionsand(Hardware)Interrupts

FedericoBaronti Lastversion:20160410

ExceptionsandInterrupts

• Exception:atransferofcontrolawayfromaprogram’snormalflowofexecution,causedbyanevent,eitherinternalorexternaltotheprocessor,whichrequiresimmediateattention

• Interrupt:anexceptioncausedbyanexplicitrequestsignalfromanexternaldevice(hardware/interruptexception)

Exceptiontypes(1)

• Resetexception:occurswhentheNios IIprocessorisreset.Controlistransferredtotheresetaddress specifiedwhengeneratingtheNios IIprocessorcore

• Breakexception:occurswhentheJTAGdebugmodulerequestscontrol.Controlistransferredtothebreakaddress specifiedwhengeneratingtheNios IIprocessorcore

Exceptiontypes(2)

• Instruction-relatedexception:occurswhenoneofseveralinternalconditionsoccurs.Controlistransferredtothegeneralexceptionaddress specifiedwhengeneratingtheNios IIprocessorcore(Softwareexception)

• Interruptexception:occurswhenaperipheraldevicesignalsaconditionrequiringservice.Controlistransferredtothegeneralexceptionaddress (ortoaspecificaddressincaseofvectoredinterrupthandling)

Breakexceptions• Ahardwarebreakisatransferofcontrolawayfromaprogram’snormalflowofexecutionforthepurposeofdebugging

• SoftwaredebuggingtoolscantakecontroloftheNios IIprocessorviatheJTAGdebugmoduletoimplementdebuganddiagnosticfeatures,suchasbreakpointsandwatchpoints

• Theprocessorentersthebreakprocessingstateunderoneofthefollowingconditions:– Theprocessorexecutesthebreakinstruction(softwarebreak)

– TheJTAGdebugmoduleassertsahardwarebreak

Instruction-relatedexceptions

• OccurduringexecutionofNios IIinstructions– Trapinstruction:software-invokedexception.Usefulto“call”OSserviceswithoutknowingtheroutinerun-timeaddresses

– BreakInstruction– Illegalinstruction– Unimplementedinstruction– Divisionerror– …

Interruptexceptions

• Aperipheraldevicecanrequestaninterruptbyassertinganinterruptrequest(IRQ)signal.IRQsinteractwiththeNios IIprocessorthroughaninterruptcontroller

• TheNios IIprocessorcanbeconfiguredwithoneofthefollowinginterruptcontrolleroptions:– Theinternalinterruptcontroller– Theexternalinterruptcontrollerinterface

ExampleofaNios IISystem

ExternalInterruptController

NiosIIProcessorCoreArchitecture

Resetsignals

Somedefinitions• Exception(interrupt) latency: thetimeelapsedbetweentheeventthatcausestheexception(assertionofaninterruptrequest) andtheexecutionofthefirstinstructionatthehandleraddress

• Exception(interrupt) responsetime:thetimeelapsedbetweentheeventthatcausestheexception(assertionofaninterruptrequest) andtheexecutionofnon-overheadexceptioncode,whichisspecifictotheexceptiontype(device)– Mayincludethetimeneededtosavegeneralpurposeregistersandtodeterminethecauseoftheexception(forNONVECTOREDinterrupts)

Internalinterruptcontroller

• Non-vectoredexceptioncontrollertohandleallexceptiontypes

• Eachexception,includinghardwareinterrupts(IRQ31-0),causestheprocessortotransferexecutiontothesamegeneralexceptionaddress

• Anexceptionhandleratthisaddressdeterminesthecauseoftheexceptionanddispatchesanappropriateexceptionroutine

Externalinterruptcontrollerinterface(1)

• ExternalInterruptController(EIC)canbeusedtoshortenexceptionresponsetime

• EICcanmonitorandprioritizeIRQsignalsanddeterminewhichinterrupttopresenttotheNios IIprocessor.AnEICcanbesoftware-configurable

• WhenanIRQisasserted,theEICprovidesthefollowingdatatotheNios IIprocessor:– Therequestedhandleraddress(RHA)– TheRequested InterruptLevel(RIL);theinterruptistakenonlywhentheRILisgreaterthantheILfield(6-bit)inthestatusregister

– TheRequestedRegister Set(RRS)– Requested NonMaskable Interrupt(RNMI)mode

Externalinterruptcontrollerinterface(2)• Requestedregistersetisoneoftheimplementedshadowregistersets– Thiswaythecontextswitchoverheadiseliminated(usefulforhigh-criticalinterrupts)

– Lesscriticalinterruptscansharethesameshadowregisterset• Noproblemifinterruptpre-emptioncannotoccuramongtheseinterrupts– Sameprioritylevelornestedinterruptsaredisabled

• OtherwisetheISRmustsaveitsregistersetonentryandrestoreitonexit

Externalinterruptcontrollerinterface(3)

• TheNios IIprocessorEICinterfaceconnectstoasingleEIC,butanEICcansupportadaisy-chainedconfiguration

• MultipleEICscanmonitorandprioritizeinterrupts• TheEICdirectlyconnectedtotheprocessorpresentstheprocessorwiththehighest-priorityinterruptfromallEICsinthedaisychain

• AnEICcomponentcansupportanarbitrarylevelofdaisy-chaining,potentiallyallowingtheNios IIprocessortohandleanarbitrarynumberofprioritizedinterrupts

Externalinterruptcontrollerinterface (4)

June 2011 Altera Corporation Embedded Peripherals IP User Guide

31. Vectored Interrupt Controller Core

Core OverviewThe vectored interrupt controller (VIC) core serves the following main purposes:

■ Provides an interface to the interrupts in your system

■ Reduces interrupt overhead

■ Manages large numbers of interrupts

The VIC offers high-performance, low-latency interrupt handling. The VIC prioritizes interrupts in hardware and outputs information about the highest-priority pending interrupt. When external interrupts occur in a system containing a VIC, the VIC determines the highest priority interrupt, determines the source that is requesting service, computes the requested handler address (RHA), and provides information, including the RHA, to the processor.

The VIC core contains the following interfaces:

■ Up to 32 interrupt input ports per VIC core

■ One Avalon® Memory-Mapped (Avalon-MM) slave interface to access the internal control status registers (CSR)

■ One Avalon Streaming (Avalon-ST) interface output interface to pass information about the selected interrupt

■ One optional Avalon-ST interface input interface to receive the Avalon-ST output in systems with daisy-chained VICs

Figure 31–1 outlines the basic layout of a system containing two VIC components.

To use the VIC, the processor in your system needs to have a matching Avalon-ST interface to accept the interrupt information, such as the Nios® II processor's external interrupt controller interface.

Figure 31–1. Sample System Layout

Avalon-MM Interconnect Fabric

VIC

CPU

IRQ

Core

Avalon-ST..

....

IRQ

VIC

IRQ

Core ......

IRQ

Avalon-ST

Core Core

31–2 Chapter 31: Vectored Interrupt Controller CoreFunctional Description

Embedded Peripherals IP User Guide June 2011 Altera Corporation

The characteristics of each interrupt port are configured via the Avalon-MM slave interface. When you need more than 32 interrupt ports, you can daisy chain multiple VICs together.

The VIC core provides the following features:

■ Separate programmable requested interrupt level (RIL) for each interrupt

■ Separate programmable requested register set (RRS) for each interrupt, to tell the interrupt handler which processor register set to use

■ Separate programmable requested non-maskable interrupt (RNMI) flag for each interrupt, to control whether each interrupt is maskable or non-maskable

■ Software-controlled priority arbitration scheme

The VIC core is SOPC Builder-ready and integrates easily into any SOPC Builder-generated system. For the Nios II processor, Altera provides Hardware Abstraction Layer (HAL) driver routines for the VIC core. Refer to “Altera HAL Software Programming Model” on page 31–10 for HAL support details.

Functional DescriptionFigure 31–2 shows a high-level block diagram of the VIC core.

External InterfacesThe following sections describe the external interfaces for the VIC core.

clkclk is a system clock interface. This interface connects to your system’s main clock source. The interface’s signals are clk and reset_n.

Figure 31–2. VIC Block Diagram

Control Status Registers

csr_access(Avalon-MM slavefrom processor)

InterruptRequest

Blockinterrupt_controller_in

(optional Avalon-STVIC daisy chain input)

VectorGeneration

Block

PriorityProcessing

Block

interrupt_controller_out(Avalon-ST to processor orto interrupt_controller_in

of another VIC)

clk(clock)

irq_input(external interrupt input)

Nios IIregisters(1)• General-purposeregisters(r0-r31)

Nios IIregisters(2)• Controlregisters accessibleonlybythespecialinstructions rdctl and

wrctl thatareonlyavailableinsupervisormode

Statusregister(1)

Statusregister(2)

Other relevant controlregisters(1)

• Theestatus register holdsasavedcopyofthestatusregisterduringnonbreak exceptionprocessing

• Thebstatus registerholdsasavedcopyofthestatusregisterduringbreakexceptionprocessing

• Theienable register controlsthehandlingofinternalhardwareinterrupts

• Theipending register indicatesthevalueoftheinterruptsignalsdrivenintotheprocessor

Other relevant controlregisters(2)

• Whentheextraexceptioninformationoptionisenabled,theNios IIprocessorprovidesinformationusefultosystemsoftwareforexceptionprocessingintheexception andbadaddr registerswhenanexceptionoccurs

Maskinganddisablinginterrupts

statusregister

withInternalInterruptController

Exceptionprocessingflow(1)

• Inresponsetoanexception,theNios IIprocessordoesthefollowingactions:– Savethestatus registerintotheestatus register– ClearPIEbitinthestatus register– SavePC(returnaddress)toea register– Transferexecutiontothe:• generalexceptionhandler (w/InternalInterruptController)• specificexceptionhandler (w/ExternalInterruptController)

Exceptionprocessingflow(2)• Thegeneralexceptionhandler isaroutinethatdeterminesthecauseofeachexception andthendispatchesanexceptionroutinetorespondtothespecificexception(softwareorhardware)

• Thegeneralexceptionhandler isfoundatthegeneralexceptionaddress– Atruntimethisaddressisfixed,andsoftwarecannotmodifyit

– ProgrammersdonotdirectlyaccessexceptionvectorsandcanwriteprogramswithoutawarenessofthisaddressthankstoHAL

Determiningtheexceptioncause

• Instruction-related(software)exception– cause filedoftheexception register(ifpresent)storestheinfoonwhatinstructionhascausedtheexception

– Ifnon-present,thehandlermustretrievetheinstructionthathascausedtheexception

/*Withaninternalinterruptcontroller,checkforinterruptexceptions.Withanexternalinterrupt*controller,ipending isalways0,andthischeckcanbeomitted.*/if(estatus.PIE ==1andipending !=0) handlehardwareinterruptelse{

/*Decodeexceptionfrominstruction*/decodeinstructionat [ea]-4if(instructionistrap)handletrapexceptionelseif(instructionisloadorstore)handlemisaligneddataaddressexceptionelseif(instructionisbranch,bret,callr,eret,jmp,orret)

handlemisaligneddestinationaddressexceptionelseif(instructionisunimplemented)handleunimplementedinstructionexceptionelseif(instructionisillegal)handleillegalinstructionexceptionelseif(instructionisdivide){

if(denominator==0)handledivisionerrorexceptionelseif(instructionissigneddivideandnumerator==0x80000000

anddenominator==0xffffffff)handledivisionerrorexception

}/*Notanyknown exception*/elsehandleunknown exception}

PseudoCcodefordispatichingsoftwareexceptions(w/oexcepetion register)andhardwareinterrupts

Interrupt Latency &ResponseTime

t

SWw/int disorhigherpriorityint beingexecuted

event

SWforspecificeventhandling

SWoverhead

SWoverhead

LATENCY

RESPONSETIME

GENERALHANDLEREXECUTION

eventisacknowledged

HWhandling

• Savecontext

• Determineexceptioncause

• Restorecontext

• eret

Hardwareinterruptsprocessingfloww/EIC

• Softwareexceptionsarehandledasw/IIC• WhentheEICinterfacepresentsaninterrupttotheNios IIprocessor,theprocessorusesseveralcriteriatodeterminewhetherornottotaketheinterrupt:– Nonmaskable interrupts:theprocessortakesanyNMIaslongasitisnotprocessingapreviousNMI

– Maskable interrupts:theprocessortakesamaskableinterruptifmaskable interruptsareenabled(PIE=1)andiftherequestedinterruptlevelishigherthanthatoftheinterruptcurrentlybeingprocessed(ifany)• However,ifshadowregistersetsareimplemented,theprocessortakestheinterruptonlyiftheinterruptrequestsaregistersetdifferentfromthecurrentregisterset,oriftheregistersetinterruptenableflag(status.RSIE)isset

Nestedexceptions(1)

• Nestedexceptionscanoccurunderthefollowingcircumstances:– Anexceptionhandlerenablesmaskable interrupts– AnEICispresentand• anNMIoccursor• theprocessorisconfiguredtokeepmaskable interruptsenabledwhentakinganinterrupt

– Anexceptionhandlertriggersaninstruction-relatedexception

Nestedexceptions(2)• Bydefault,Nios IIprocessordisablesmaskableinterruptswhenittakesaninterruptrequest

• Toenablenestedinterrupts,theISRitselfmustre-enableinterruptsaftertheinterruptistaken

• Alternatively,totakefulladvantageofnestedinterruptswithshadowregistersets,systemsoftwarecansettheconfig.ANI flagintheconfigcontrolregister.Whenconfig.ANI=1,theNios IIprocessorkeepsmaskable interruptsenabledafterittakesaninterrupt

InterruptServiceRoutine(ISR)

• TheHALprovidesanenhancedapplicationprogramminginterface (API)forwriting,registeringandmanagingISRs– ThisAPIiscompatiblewithbothinternalandexternalhardwareinterruptcontrollers

• ForbackcompatibilityAlteraalsosupportsalegacy hardwareinterruptAPI– ThisAPIsupportsonlytheIIC– AcustomdriverwrittenpriortoNios IIversion9.1usesthelegacyAPI

HALAPI• BothinterruptAPIsincludethefollowingtypesofroutines:– RoutinestobecalledbyadevicedrivertoregisteranISR– RoutinestobecalledbyanISRtomanageitsenvironment– RoutinestobecalledbyBSPorapplicationcodetocontrolISRbehavior

• BothinterruptAPIssupportthefollowingtypesofBSPs:– HALBSPwithoutanRTOS– HAL-basedRTOSBSP,suchasaMicroC/OS-IIBSP

• WhenanEICispresent,thecontroller’sdriverprovidesfunctionstobecalledbytheHAL

HALAPIselection• WhentheSBTcreatesaBSP,itdetermineswhethertheBSPmustimplementthelegacyinterruptAPI– EachdriverthatsupportstheenhancedAPIpublishesthiscapabilitytotheSBTthroughits<drivername>_sw.tcl file

• TheBSPimplementstheenhancedAPIifalldriverssupportit;otherwiseitusesthelegacyAPI– AlteradriverswrittenfortheenhancedAPI,alsosupportthelegacyone

– DeviceswhoseinterruptsarenotconnectedtotheNios IIprocessorareignored

ExampleDE2BasicComputer• system.h

/** System configuration*/#define ALT_DEVICE_FAMILY "CYCLONEII"#define ALT_IRQ_BASE NULL#define ALT_LEGACY_INTERRUPT_API_PRESENT#define ALT_LOG_PORT "/dev/null"#define ALT_LOG_PORT_BASE 0x0#define ALT_LOG_PORT_DEV null#define ALT_LOG_PORT_TYPE ""#define ALT_NUM_EXTERNAL_INTERRUPT_CONTROLLERS 0#define ALT_NUM_INTERNAL_INTERRUPT_CONTROLLERS 1#define ALT_NUM_INTERRUPT_CONTROLLERS 1

avalon_parallel_port_driverandup_avalon_rs232_driverdonotsupportenhancedAPI

Enhanced HALInterruptAPI

• UsingtheenhancedHALAPItoimplementISRsrequiresperformingthefollowingsteps:– WritetheISRthathandleshardwareinterruptsforaspecificdevice– EnsurethatthemainprogramregisterstheISRwiththeHALbycalling

thealt_ic_isr_register()function(thisfunctionalsoenablesthehardwareinterrupts)

Legacy HALInterruptAPI• alt_irq_register()• alt_irq_disable()• alt_irq_enable()• alt_irq_disable_all()• alt_irq_enable_all()• alt_irq_interruptible()• alt_irq_non_interruptible()• alt_irq_enabled()

• UsingthelegacyHALAPItoimplementISRsrequiresperformingthefollowingsteps:– WritetheISRthathandleshardwareinterruptsforaspecificdevice– EnsurethatthemainprogramregisterstheISRwiththeHALbycallingthe

alt_irq_register()function– alt_irq_register()enablesalsohardwareinterruptsbycalling

alt_irq_enable_all()

HALexceptionhandlingw/IICGeneralexceptionfunnel

Softwareexceptionfunnel

Hardwareexceptionfunnel

Harwdareinterruptfunnel

IntheHALfunnel,hardwareinterrupt0hasthehighestpriority,and31thelowestpriority

AftertheISRi execution,ipending register isscannedagainfrom0,sothathigher-priorityinterruptsarealwaysprocessedbeforelower-priorityinterrupts

ISRcodemustcleartheassociatedperipheral’sinterruptcondition

CallISRi

• Interrupttabledefinition(LegacyHALInterruptAPI)struct {void(*handler)(void*,alt_u32);void*context;}alt_irq[32];

• CallISRialt_irq[i].handler(alt_irq[i].context,i);

WhenwritinganISR...• Keepitassimpleaspossible.Deferintensivelytaskstothe

applicationcode.• ISRsruninarestrictedenvironment.Alargenumberofthe

HALAPIcallsarenotavailablefromISRs– Forexample,accessestotheHALfilesystemarenotpermitted

• Asageneralrule,neverincludefunctioncallsthatcanblockforanyreason(suchaswaitingforahardwareinterrupt)– AvoidusingtheCstandardlibraryI/OAPI,becausecallingthese

functionscanresultindeadlockwithinthesystem,thatis,thesystemcanbecomepermanentlyblockedintheISR

– Donotcallprintf()fromwithinanISRunlessyouarecertainthatstdout ismappedtoanon-interrupt-baseddevicedriver

– Otherwise,printf()candeadlockthesystem,waitingforahardwareinterruptthatneveroccursbecauseinterruptsaredisabled

Puttingintopractice (1)

• Writeaprogramthatreadsthepushbuttonactivityexplotingtherelatedhardwareinterruptandturnson/offsomeLEDs

• #include<sys/alt_irq.h>touseInterruptHALAPI• ISRprototype

– staticvoidpushbutton_ISR(void*context,unsignedlongid);

Puttingintopractice (2)• MakeGREENledsblinkusingtheIntervalTimerandthesys_clkHAL w/2speriod– Mapsys_clkHAL totheInterval_timerperipheralusingtheBSPeditor

– Defineavariableofalt_alarm type(youneedtoinclude"sys/alt_alarm.h " headerfile)

– Startthealarmusingthealt_alarm_start()functionpassingasparameterthepointertothecallbackfunctionthatmakestheledsblink• Prototypeofthecallbackfunction:alt_u32my_alarm_callback(void*context)

• Thereturnvalueisthetimethatwillpassbeforethenextalarmevent

– HandletheGREEN_LEDSParallelPortusingtherelatedHAL;see"altera_up_avalon_parallel_port.h " headerforhowtouseit

References

• Altera,“Nios IIProcessorReferenceHandbook,”n2cpu_nii5v1.pdf– 2.ProcessorArchitecture– 3.ProgrammingModel/ExceptionProcessing

• Altera,“Nios IISoftwareDeveloper’sHandbook,”n2sw_nii5v2.pdf– 8.ExceptionHandling– 14.HALAPIReference