Design Recipes for FPGAs Using Verilog and VHDL Peter Wilson Firstedition2007 Secondedition2016 ©2016ElsevierLtd. Previousedition:Copyright© 2007PeterR.Wilson PrintedandboundintheUnitedKingdom ISBN:978-0-08-097129-2 Preface to the Second Edition Theoriginalideabehindthefirsteditionofthisbookwastocollectsomeoftheuseful methodsfordesigningdigitalsystemsusingFPGAsthatIhadaccumulatedovertheyearsand hadbeenpassingontostudentsinourcoursesattheUniversityofSouthampton.Asaresult, theoriginalbookwaswrittenusingVHDL,asthiswasveryoftenthehardwaredescription languageofchoiceforuniversitystudentsandformanycourses(aswasthecaseat Southampton). Theinterveningtimehasseenthedevelopmentofotheroptions,suchasSystem-Cor System-Verilog(plusthecontinuingpopularityofVerilog).Oneofthecommonquestions tomewas“WhyistherenotaVerilogeditionofthisbook?”.Ihavethereforetakenthe opportunitywiththesecondeditiontointroduceVerilog,towidentheapplicabilityofthe booktoasmanydesignersaspossible. Thesecondeditionalsooffersthechancetocorrecterrorsandtakeonboardthenumerous reviewsoverthepastsevenyearssincethefirsteditionwaspublished.Forthesecomments andsuggestionsIammostgratefultothereadersofthebook.FPGAshavealsomovedonin leapsandboundssincethefirstedition,andthisalsogivesanopportunitytoupdatesomeof thetechnologicalbackgroundandcorrecterrorsinthefirstedition. Aboveallelse,thisbookwasnotandisnotintendedtobeatextbookfordigitalsystems design,butratherausefulhandbookfordesignerstodipinandusewhereveritcanhelp. IsincerelyhopeyoufindthisbookusefulandgoodluckwithyourFPGAdesigns! PeterWilson UniversityofBath Preface to the First Edition Thisbookisdesignedtobeadesktopreferenceforengineers,studentsandresearcherswho usefieldprogrammablegatearrays(FPGAs)astheirhardwareplatformofchoice.Thisbook hasbeenproducedinthespiritofthe“numericalrecipe”seriesofbooksforvarious programminglanguages–wheretheintentionisnottoteachthelanguageperse,butrather thephilosophyandtechniquesrequiredinmakingyourapplicationwork.Therationaleofthis bookissimilarinthattheintentionistoprovidethemethodsandunderstandingtoenablethe readertodeveloppractical,operationalVHDLthatwillruncorrectlyonFPGAs. Itisimportanttostressthatthisbookisnotdesignedasalanguagereferencemanualfor VHDL.ThereareplentyofthoseavailableandIhavereferencedthemthroughoutthetext. ThisbookisintendedasareferencefordesignwithVHDLandcanbeseenascomplementary toaconventionalVHDLtextbook. PART 1 Overview Thefirstpartofthebookprovidesastartingpointforengineerswhomayhavesomedigital experiencebutnotnecessarilywithFPGAsinparticular,orwitheitherofthelanguages featuredinthisbook(VHDLandVerilog).Whilethebookisnotintendedtoteacheither language,“primers”aregiveninbothasaidesdememoiretogetstarted.Anoverviewofthe maindesignapproachesandtoolflowsisalsoprovidedasastartingpoint. CHAPTER 1 Introduction 1.1 Overview Thebookisdividedintofivemainparts.Intheintroductorypartofthebook,primersare givenonFPGAs(field-programmablegatearrays),Verilogandthestandarddesignflow.In thesecondpartofthebook,aseriesofcomplexapplicationsthatencompassmanyofthekey designproblemsfacingdesignerstodayareworkedthroughfromstarttofinishinapractical way.Thiswillshowhowthedesignercaninterpretaspecification,developatop-downdesign methodologyandeventuallybuildindetaileddesignblocksperhapsdevelopedpreviouslyor byathirdparty.Inthethirdpartofthebook,importanttechniquesarediscussed,worked throughandexplainedfromanexampleperspectivesoyoucanseeexactlyhowtoimplement aparticularfunction.Thispartisreallyatoolboxofadvancedspecificfunctionsthatare commonlyrequiredinmoderndigitaldesign.Thefourthpartonadvancedtechniques discussestheimportantaspectofdesignoptimization,thatis,howcanImakemydesign faster,ormorecompact?Thefifthpartinvestigatesthedetailsoffundamentalissuesthatare implementedinVHDLandVerilog.ThisfinalpartisaimedatdesignerswithalimitedVHDL orVerilogcodingbackground,perhapsthoselookingforsimplerexamplestogetstarted,orto solveaparticulardetailedissue. 1.2 Verilog vs. VHDL Oneofthelongeststanding“arguments”betweenengineersindigitaldesignhasbeenthe issueofwhichisbest—VerilogorVHDL?Formanyyearsthiswaspartlyageographical divide,withNorthAmericaseemingtobemainlyusingVerilogandEuropegoingmorefor VHDL,althoughthiswasnotuniversalbyanymeans.Inmanycases,theEuropeanacademic communitywastrendingtowardVHDLwithitseasyapplicabilitytosystemleveldesign,and theperceptionthatVerilogwasreallymorea“lowlevel”designlanguage.Withtheadventof SystemVerilogandtheproliferationofdesigntools,theseboundariesandargumentshave largelysubsided,andmostengineersrealizethattheycanuseIPblocksfromeitherlanguage inmostofthedesigntools.Ofcourse,individualswillalwayshavetheirownpreferences; howeveritistruetosaythatnowitisgenuinelypossibletobelanguageagnosticanduse whicheverlanguageandtoolstheuserprefers.Moreoftenthannot,thechoicewilldependon 4 Chapter1 threemainfactors:(a)theexperienceoftheuser(forexample,theymayhaveabackgroundin aparticularlanguage);(b)thetoolsavailable(forexample,sometoolflowsmaysimplywork betterwithaparticularlanguage—SystemVerilogforinstancemaynotbesupportedbythe toolsavailable);and(c)corporatedecisions(wherethecompanyorinstitutionhasa preferenceforaspecificlanguage,andinturnthismaymeanthatlibrariesmustbeina specificformatandlanguage).Forresearchers,thereisaplethoraofinformationonalldesign languagesavailable,withmanyexampledesignspublishedontheweb,makingitrelatively simpletouseoneoranotherofthemainlanguages,andsometimesevenamixtureof languages(usingprecompiledlibraries,forexample).Ofcourse,thisisalsoavailableto employeesofcompaniesandfreematerialisnowwidelyavailablefromsourcessuchasOpen Cores(http://www.opencores.org),theFreeModelFoundry(http://www.freemodelfoundry. com/)andtheOpenHardwareRepositoryatCERN(http://www.ohwr.org/). 1.3 Why FPGAs? Therearenumerousoptionsfordesignersinselectingahardwareplatformforcustom electronicsdesigns,rangingfromembeddedprocessors,applicationspecificintegrated circuits(ASICs),programmablemicroprocessors(PICs),FPGAstoprogrammablelogic devices(PLDs).ThedecisiontochooseaspecifictechnologysuchasanFPGAshoulddepend primarilyonthedesignrequirementsratherthanapersonalpreferenceforonetechniqueover another.Forexample,ifthedesignrequiresaprogrammabledevicewithmanydesign changes,andalgorithmsusingcomplexoperationssuchasmultiplicationsandlooping,thenit maymakemoresensetouseadedicatedsignalprocessordevicesuchasaDSPthatcanbe programmedandreprogrammedeasilyusingCorsomeotherhighlevellanguage.Ifthespeed requirementsarenotparticularlystringentandacompactcheapplatformisrequired,thena generalpurposemicroprocessorsuchasaPIC,AVR,orMBEDwouldbeanidealchoice. Finally,ifthehardwarerequirementsrequireahigherlevelofperformance,sayuptoseveral hundredmegahertzoperation,thenanFPGAoffersasuitablelevelofperformance,whilestill retainingtheflexibilityandreusabilityofprogrammablelogic. Otherissuestoconsiderarethelevelofoptimizationinthehardwaredesignrequired.For example,asimplesoftwareprogramcanbewritteninCandthenamicroprocessor programmed,buttheperformancemaybelimitedbytheinabilityoftheprocessortooffer paralleloperationofkeyfunctions.ThiscanbeimplementedmuchmoredirectlyinanFPGA usingparallelismandpipeliningtoachievemuchgreaterthroughputthanwouldbepossible usingamicroprocessor.Ageneralruleofthumbwhenchoosingahardwareplatformisto identifyboththedesignrequirementsandthepossiblehardwareoptionsandthenselecta suitableplatformbasedonthoseconsiderations.Forexample,ifthedesignrequiresabasic clockspeedofupto1GHzthenanFPGAwouldbeasuitableplatform.Iftheclockspeed couldbe3-4MHz,thentheFPGAmaybeanexpensive(overkill)option.Ifthedesign Introduction 5 requiresaflexibleprocessoroption,althoughtheFPGAsavailabletodaysupportembedded processors,itprobablymakessensetouseaDSPormicroprocessor.Ifthedesignrequires dedicatedhardwarefunctionality,thenanFPGAistheroutetotake. Ifthedesignrequiresspecifichardwarefunctionssuchasmultiplicationandaddition,thena DSPmaywellbethebestroute,butifcustomhardwaredesignisrequired,thenanFPGA wouldbetheappropriatechoice.Ifthedesignrequiressmallsimplehardwareblocks,thena PLDorCPLDmaybethebestoption(compact,simpleprogrammablelogic);however,ifthe designhasmultiplefunctions,oracombinationofcomplexcontrollerandspecifichardware functions,thentheFPGAistheroutetotake.Examplesofthiskindofdecisioncanbe dependentonthecomplexityofthehardwareinvolved.Forexample,ahighperformance signalprocessorwithmultipleparalleltaskswillprobablyrequireanFPGAratherthanaPLD device,simplyduetothecomplexityofthehardwareinvolved.Anotherrelatedissueisthatof flexibilityandprogrammability.IfanFPGAisused,andtheresourcesarenotusedupona specificdevice(sayupto60%forexample),ifacommunicationsprotocolchanges,oris updated,thenthedevicemaywellhaveenoughheadroomtosupportadditionalfeatures,or updates,inthefuture. Finally,thecostofmanufacturewillbeimportantforproductsinthefield,aswellaswhere thedeviceisdeployed(intermsoftheoverallweight,powerrequirements,footprint,and volume).Also,theneedforupgradingfirmwaremaymandateanFPGAtoallowthistobe doneeasily.TheuseofanFPGAalsoallowsmuchhigherperformance,particularlyonhigh speedlinksormemory,enablingthedesigntobesomewhattolerantoffuturechanges. 1.4 Summary Usingthesimpleguidelinesandwiththeaidofsomeoftheexamplesinthisbook,an engineercanhopefullymakeanintelligentchoiceaboutthebestplatformtochoose,andalso whichhardwaredevicetoselectbasedontheseassumptions.AniceaspectofmostFPGA designsoftwarepackagesisthatmultipledesignplatformscanbeevaluatedforperformance andutilizationpriortomakingafinaldecisiononthehardwareofchoice.Thisbookwillshow howbothVHDLandVerilogcanbeusedtosolvetypicaldesignproblems,andhopefullywill helpdesignersgettheirowndesignscompletedfasterandmoreefficiently. CHAPTER 2 An FPGA Primer 2.1 Introduction ThissectionisanintroductiontotheFieldProgrammableGateArray(FPGA)platformfor thoseunfamiliarwiththetechnology.Itisusefulwhendesigninghardwaretounderstandthat thecontextthatthehardwaredescriptionlanguagemodels(VHDLorVerilog)isimportant andrelevanttotheultimatedesign. 2.2 FPGA Evolution Sincetheinceptionofdigitallogichardwareinthe1970s,therehasbeenaplethoraof individualsemiconductordigitaldevicesleadingtotheubiquitousTTLlogicseriesstillinuse today(74/54serieslogic),nowextendedtoCMOStechnology(HC,AC,FC,FCT,HCT,and soon).Whilethesehavebeenusedextensivelyinprintedcircuitboard(PCB)designandstill aretoday,therehasbeenaconsistenteffortoverthelast20yearstointroducegreater programmabilityintobasicdigitaldevices. Oneofthereasonsforthisneedisthedichotomyresultingfromthetwodifferingdesign approachesusedformanydigitalsystems.Onthehardwareside,thedriveisusuallytoward ultimateperformance,thatis,faster,smaller,lowerpower,andcheaper.Thisoftenleadsto customintegratedcircuitdesign(ApplicationSpecificIntegratedCircuitsorASICs)where eachchip(ASIC)hastobedesigned,laidout,fabricated,andpackagedindividually.Forlarge productionrunsthisisverycosteffective,butobviouslythisapproachishugelyexpensive (masksaloneforacurrentsiliconprocessmaycostover$500,000)andtimeconsuming(can takeuptoayearorevenmoreforlargeandcomplexdesigns). Fromasoftwareperspective,however,amorestandardapproachistouseastandard processorarchitecturesuchasIntelPentium,PowerPCorARM,anddevelopsoftware applicationsthatcanbedownloadedontosuchaplatformusingstandardsoftware developmenttoolsandcrosscompilers.Thistypeofapproachisobviouslyquickerto implementaninitialworkingplatform;however,usuallythereisasignificantoverheaddueto theneedforoperatingsystems,compilerinefficiencyandalsoaperformancereductiondueto theindirectrelationshipbetweenthehardwareandthesoftwareontheprocessor.Theother 8 Chapter2 issuefromahardwareperspectiveisoftenthecompromisenecessarywhenusingastandard platform,forexamplewillitbefastenough?Anotherkeyissuewhendesigninghardwareis havingaccesstothathardware.Inmanyprocessorplatforms,thedetailedhardwareisoften difficulttoaccessdirectlyorefficientlyenoughtomeettheperformanceneedsofthesystem, andwiththerigidarchitectureintermsofdatabusandaddressbuswidthsonstandard processors,veryoftenthereisnoscopeforgeneralpurposeIO(InputsandOutputs)whichare usefulfordigitaldesigners. Asaresult,programmabledeviceshavebeendevelopedasaformofintermediateapproach: hardwaredesignonahigh-performanceplatform,optimalresourceswithnooperatingsystem requiredandreconfigurableasthedevicescanbereprogrammed. 2.3 Programmable Logic Devices ThefirsttypeofdevicetobeprogrammablewastheProgrammableArrayLogic(PAL)witha typicallayoutasshowninFigure2.1.Thisconsistsofanarrayoflogicgatesthatcouldbe connectedusinganarrayofconnections.Thesedevicescouldsupportasmallnumberof flip-flops(usually<10)andwereabletoimplementsmallstatemachines.Thesedevicesstill haveauseforspecificfunctionsonasmallscale,butclearlywillbelimitedformorecomplex applications.Theyare,however,stillusefulforlow-costandcompactsolutionstoaspecific digitaldesignrequirement. ComplexProgrammableLogicDevices(CPLD)suchasshowninFigure2.2weredeveloped toaddressthelimitationsofsimplePALdevices.Thesedevicesusedthesamebasicprinciple asPALs,buthadaseriesofmacroblocks(eachroughlyequivalenttoaPAL)thatwere connectedusingroutingblocks.With,insomecases,manythousandsoflogicalelements,the CPLDcanbeextremelyusefulforimplementingaprogrammabledevicewithcustomlogic functionsandstatemachines.Insomeways,thelatestCPLDandearlyFPGAdevicesare almostindistinguishable,withonecrucialdifference.TheCPLDisafixedarrayoflogic,but theFPGAusescomplexlogicblocks(discussedinthenextsectionofthischapter).However, CPLDsarestillofarelativelysmallscale,andthemodernreconfigurabledeviceofchoicefor highperformanceistheFPGA. 2.4 Field Programmable Gate Arrays FieldProgrammableGateArrays(FPGAs)werethenextstepfromCPLDs.Insteadofafixed arrayofgates,theFPGAusestheconceptofaComplexLogicBlock(CLB).Thisis configurableandallowsnotonlyroutingonthedevice,butalsoeachlogicblockcanbe configuredoptimally.AtypicalCLBisshowninFigure2.3.Thisextremeflexibilityisvery efficientasthedevicedoesnotrelyonthefixedlogicalresources(asinthecaseofaCPLD),