README.adoc 661 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310
  1. = Linux Kernel Module Cheat
  2. :description: The perfect emulation setup to study and develop the <<linux-kernel>> v5.2.1, kernel modules, <<qemu-buildroot-setup,QEMU>>, <<gem5-buildroot-setup,gem5>> and x86_64, ARMv7 and ARMv8 <<userland-assembly,userland>> and <<baremetal-setup,baremetal>> assembly, <<c,ANSI C>>, <<cpp,C++>> and <<posix,POSIX>>. <<gdb>> and <<kgdb>> just work. Powered by <<about-the-qemu-buildroot-setup,Buildroot>> and <<about-the-baremetal-setup,crosstool-NG>>. Highly automated. Thoroughly documented. Automated <<test-this-repo,tests>>. "Tested" in an Ubuntu 18.04 host.
  3. :idprefix:
  4. :idseparator: -
  5. :nofooter:
  6. :sectanchors:
  7. :sectlinks:
  8. :sectnumlevels: 6
  9. :sectnums:
  10. :toc-title:
  11. :toc: macro
  12. :toclevels: 6
  13. https://zenodo.org/badge/latestdoi/64534859[image:https://zenodo.org/badge/64534859.svg[]]
  14. {description}
  15. TL;DR: xref:qemu-buildroot-setup-getting-started[xrefstyle=full]
  16. The source code for this page is located at: https://github.com/cirosantilli/linux-kernel-module-cheat[]. Due to https://github.com/isaacs/github/issues/1610[a GitHub limitation], this README is too long and not fully rendered on github.com. Either use: link:README.adoc[], https://cirosantilli.com/linux-kernel-module-cheat or <<build-the-documentation,build the docs yourself>>.
  17. toc::[]
  18. == Getting started
  19. Each child section describes a possible different setup for this repo.
  20. If you don't know which one to go for, start with <<qemu-buildroot-setup-getting-started>>.
  21. Design goals of this project are documented at: xref:design-goals[xrefstyle=full].
  22. === QEMU Buildroot setup
  23. ==== QEMU Buildroot setup getting started
  24. This setup has been mostly tested on Ubuntu. For other host operating systems see: xref:supported-hosts[xrefstyle=full]. For greater stability, consider using the <<release-procedure,latest release>> instead of master: https://github.com/cirosantilli/linux-kernel-module-cheat/releases
  25. Reserve 12Gb of disk and run:
  26. ....
  27. git clone https://github.com/cirosantilli/linux-kernel-module-cheat
  28. cd linux-kernel-module-cheat
  29. ./build --download-dependencies qemu-buildroot
  30. ./run
  31. ....
  32. You don't need to clone recursively even though we have `.git` submodules: `download-dependencies` fetches just the submodules that you need for this build to save time.
  33. If something goes wrong, see: xref:common-build-issues[xrefstyle=full] and use our issue tracker: https://github.com/cirosantilli/linux-kernel-module-cheat/issues
  34. The initial build will take a while (30 minutes to 2 hours) to clone and build, see <<benchmark-builds>> for more details.
  35. If you don't want to wait, you could also try the following faster but much more limited methods:
  36. * <<prebuilt>>
  37. * <<host>>
  38. but you will soon find that they are simply not enough if you anywhere near serious about systems programming.
  39. After `./run`, QEMU opens up leaving you in the <<lkmc_home,`/lkmc/` directory>>, and you can start playing with the kernel modules inside the simulated system:
  40. ....
  41. insmod hello.ko
  42. insmod hello2.ko
  43. rmmod hello
  44. rmmod hello2
  45. ....
  46. This should print to the screen:
  47. ....
  48. hello init
  49. hello2 init
  50. hello cleanup
  51. hello2 cleanup
  52. ....
  53. which are `printk` messages from `init` and `cleanup` methods of those modules.
  54. Sources:
  55. * link:kernel_modules/hello.c[]
  56. * link:kernel_modules/hello2.c[]
  57. Quit QEMU with:
  58. ....
  59. Ctrl-A X
  60. ....
  61. See also: xref:quit-qemu-from-text-mode[xrefstyle=full].
  62. All available modules can be found in the link:kernel_modules[] directory.
  63. It is super easy to build for different <<cpu-architecture,CPU architectures>>, just use the `--arch` option:
  64. ....
  65. ./build --arch aarch64 --download-dependencies qemu-buildroot
  66. ./run --arch aarch64
  67. ....
  68. To avoid typing `--arch aarch64` many times, you can set the default arch as explained at: xref:default-command-line-arguments[xrefstyle=full]
  69. I now urge you to read the following sections which contain widely applicable information:
  70. * <<run-command-after-boot>>
  71. * <<clean-the-build>>
  72. * <<build-the-documentation>>
  73. * Linux kernel
  74. ** <<printk>>
  75. ** <<kernel-command-line-parameters>>
  76. Once you use <<gdb>> and <<tmux>>, your terminal will look a bit like this:
  77. ....
  78. [ 1.451857] input: AT Translated Set 2 keyboard as /devices/platform/i8042/s1│loading @0xffffffffc0000000: ../kernel_modules-1.0//timer.ko
  79. [ 1.454310] ledtrig-cpu: registered to indicate activity on CPUs │(gdb) b lkmc_timer_callback
  80. [ 1.455621] usbcore: registered new interface driver usbhid │Breakpoint 1 at 0xffffffffc0000000: file /home/ciro/bak/git/linux-kernel-module
  81. [ 1.455811] usbhid: USB HID core driver │-cheat/out/x86_64/buildroot/build/kernel_modules-1.0/./timer.c, line 28.
  82. [ 1.462044] NET: Registered protocol family 10 │(gdb) c
  83. [ 1.467911] Segment Routing with IPv6 │Continuing.
  84. [ 1.468407] sit: IPv6, IPv4 and MPLS over IPv4 tunneling driver │
  85. [ 1.470859] NET: Registered protocol family 17 │Breakpoint 1, lkmc_timer_callback (data=0xffffffffc0002000 <mytimer>)
  86. [ 1.472017] 9pnet: Installing 9P2000 support │ at /linux-kernel-module-cheat//out/x86_64/buildroot/build/
  87. [ 1.475461] sched_clock: Marking stable (1473574872, 0)->(1554017593, -80442)│kernel_modules-1.0/./timer.c:28
  88. [ 1.479419] ALSA device list: │28 {
  89. [ 1.479567] No soundcards found. │(gdb) c
  90. [ 1.619187] ata2.00: ATAPI: QEMU DVD-ROM, 2.5+, max UDMA/100 │Continuing.
  91. [ 1.622954] ata2.00: configured for MWDMA2 │
  92. [ 1.644048] scsi 1:0:0:0: CD-ROM QEMU QEMU DVD-ROM 2.5+ P5│Breakpoint 1, lkmc_timer_callback (data=0xffffffffc0002000 <mytimer>)
  93. [ 1.741966] tsc: Refined TSC clocksource calibration: 2904.010 MHz │ at /linux-kernel-module-cheat//out/x86_64/buildroot/build/
  94. [ 1.742796] clocksource: tsc: mask: 0xffffffffffffffff max_cycles: 0x29dc0f4s│kernel_modules-1.0/./timer.c:28
  95. [ 1.743648] clocksource: Switched to clocksource tsc │28 {
  96. [ 2.072945] input: ImExPS/2 Generic Explorer Mouse as /devices/platform/i8043│(gdb) bt
  97. [ 2.078641] EXT4-fs (vda): couldn't mount as ext3 due to feature incompatibis│#0 lkmc_timer_callback (data=0xffffffffc0002000 <mytimer>)
  98. [ 2.080350] EXT4-fs (vda): mounting ext2 file system using the ext4 subsystem│ at /linux-kernel-module-cheat//out/x86_64/buildroot/build/
  99. [ 2.088978] EXT4-fs (vda): mounted filesystem without journal. Opts: (null) │kernel_modules-1.0/./timer.c:28
  100. [ 2.089872] VFS: Mounted root (ext2 filesystem) readonly on device 254:0. │#1 0xffffffff810ab494 in call_timer_fn (timer=0xffffffffc0002000 <mytimer>,
  101. [ 2.097168] devtmpfs: mounted │ fn=0xffffffffc0000000 <lkmc_timer_callback>) at kernel/time/timer.c:1326
  102. [ 2.126472] Freeing unused kernel memory: 1264K │#2 0xffffffff810ab71f in expire_timers (head=<optimized out>,
  103. [ 2.126706] Write protecting the kernel read-only data: 16384k │ base=<optimized out>) at kernel/time/timer.c:1363
  104. [ 2.129388] Freeing unused kernel memory: 2024K │#3 __run_timers (base=<optimized out>) at kernel/time/timer.c:1666
  105. [ 2.139370] Freeing unused kernel memory: 1284K │#4 run_timer_softirq (h=<optimized out>) at kernel/time/timer.c:1692
  106. [ 2.246231] EXT4-fs (vda): warning: mounting unchecked fs, running e2fsck isd│#5 0xffffffff81a000cc in __do_softirq () at kernel/softirq.c:285
  107. [ 2.259574] EXT4-fs (vda): re-mounted. Opts: block_validity,barrier,user_xatr│#6 0xffffffff810577cc in invoke_softirq () at kernel/softirq.c:365
  108. hello S98 │#7 irq_exit () at kernel/softirq.c:405
  109. │#8 0xffffffff818021ba in exiting_irq () at ./arch/x86/include/asm/apic.h:541
  110. Apr 15 23:59:23 login[49]: root login on 'console' │#9 smp_apic_timer_interrupt (regs=<optimized out>)
  111. hello /root/.profile │ at arch/x86/kernel/apic/apic.c:1052
  112. # insmod /timer.ko │#10 0xffffffff8180190f in apic_timer_interrupt ()
  113. [ 6.791945] timer: loading out-of-tree module taints kernel. │ at arch/x86/entry/entry_64.S:857
  114. # [ 7.821621] 4294894248 │#11 0xffffffff82003df8 in init_thread_union ()
  115. [ 8.851385] 4294894504 │#12 0x0000000000000000 in ?? ()
  116. │(gdb)
  117. ....
  118. ==== How to hack stuff
  119. Besides a seamless <<qemu-buildroot-setup-getting-started,initial build>>, this project also aims to make it effortless to modify and rebuild several major components of the system, to serve as an awesome development setup.
  120. ===== Your first Linux kernel hack
  121. Let's hack up the <<linux-kernel-entry-point, Linux kernel entry point>>, which is an easy place to start.
  122. Open the file:
  123. ....
  124. vim submodules/linux/init/main.c
  125. ....
  126. and find the `start_kernel` function, then add there a:
  127. ....
  128. pr_info("I'VE HACKED THE LINUX KERNEL!!!");
  129. ....
  130. Then rebuild the Linux kernel, quit QEMU and reboot the modified kernel:
  131. ....
  132. ./build-linux
  133. ./run
  134. ....
  135. and, surely enough, your message has appeared at the beginning of the boot:
  136. ....
  137. <6>[ 0.000000] I'VE HACKED THE LINUX KERNEL!!!
  138. ....
  139. So you are now officially a Linux kernel hacker, way to go!
  140. We could have used just link:build[] to rebuild the kernel as in the <<qemu-buildroot-setup-getting-started,initial build>> instead of link:build-linux[], but building just the required individual components is preferred during development:
  141. * saves a few seconds from parsing Make scripts and reading timestamps
  142. * makes it easier to understand what is being done in more detail
  143. * allows passing more specific options to customize the build
  144. The link:build[] script is just a lightweight wrapper that calls the smaller build scripts, and you can see what `./build` does with:
  145. ....
  146. ./build --dry-run
  147. ....
  148. When you reach difficulties, QEMU makes it possible to easily GDB step debug the Linux kernel source code, see: xref:gdb[xrefstyle=full].
  149. ===== Your first kernel module hack
  150. Edit link:kernel_modules/hello.c[] to contain:
  151. ....
  152. pr_info("hello init hacked\n");
  153. ....
  154. and rebuild with:
  155. ....
  156. ./build-modules
  157. ....
  158. Now there are two ways to test it out: the fast way, and the safe way.
  159. The fast way is, without quitting or rebooting QEMU, just directly re-insert the module with:
  160. ....
  161. insmod /mnt/9p/out_rootfs_overlay/lkmc/hello.ko
  162. ....
  163. and the new `pr_info` message should now show on the terminal at the end of the boot.
  164. This works because we have a <<9p>> mount there setup by default, which mounts the host directory that contains the build outputs on the guest:
  165. ....
  166. ls "$(./getvar out_rootfs_overlay_dir)"
  167. ....
  168. The fast method is slightly risky because your previously insmodded buggy kernel module attempt might have corrupted the kernel memory, which could affect future runs.
  169. Such failures are however unlikely, and you should be fine if you don't see anything weird happening.
  170. The safe way, is to fist <<rebuild-buildroot-while-running,quit QEMU>>, rebuild the modules, put them in the root filesystem, and then reboot:
  171. ....
  172. ./build-modules
  173. ./build-buildroot
  174. ./run --eval-after 'insmod hello.ko'
  175. ....
  176. `./build-buildroot` is required after `./build-modules` because it re-generates the root filesystem with the modules that we compiled at `./build-modules`.
  177. You can see that `./build` does that as well, by running:
  178. ....
  179. ./build --dry-run
  180. ....
  181. `--eval-after` is optional: you could just type `insmod hello.ko` in the terminal, but this makes it run automatically at the end of boot, and then drops you into a shell.
  182. If the guest and host are the same arch, typically x86_64, you can speed up boot further with <<kvm>>:
  183. ....
  184. ./run --kvm
  185. ....
  186. All of this put together makes the safe procedure acceptably fast for regular development as well.
  187. It is also easy to GDB step debug kernel modules with our setup, see: xref:gdb-step-debug-kernel-module[xrefstyle=full].
  188. ===== Your first QEMU hack
  189. Not satisfied with mere software? OK then, let's hack up the QEMU x86 CPU identification:
  190. ....
  191. vim submodules/qemu/target/i386/cpu.c
  192. ....
  193. and modify:
  194. ....
  195. .model_id = "QEMU Virtual CPU version " QEMU_HW_VERSION,
  196. ....
  197. to contain:
  198. ....
  199. .model_id = "QEMU Virtual CPU version HACKED " QEMU_HW_VERSION,
  200. ....
  201. then as usual rebuild and re-run:
  202. .....
  203. ./build-qemu
  204. ./run --eval-after 'grep "model name" /proc/cpuinfo'
  205. .....
  206. and once again, there is your message: QEMU communicated it to the Linux kernel, which printed it out.
  207. You have now gone from newb to hardware hacker in a mere 15 minutes, your rate of progress is truly astounding!!!
  208. Seriously though, if you want to be a real hardware hacker, it just can't be done with open source tools as of 2018. The root obstacle is that:
  209. * https://en.wikipedia.org/wiki/Semiconductor_fabrication_plant[Silicon fabs] don't publish reveal their https://en.wikipedia.org/wiki/Design_rule_checking[design rules]
  210. * which implies that there are no decent https://en.wikipedia.org/wiki/Standard_cell[standard cell libraries]. See also: https://www.quora.com/Are-there-good-open-source-standard-cell-libraries-to-learn-IC-synthesis-with-EDA-tools/answer/Ciro-Santilli
  211. * which implies that people can't develop open source https://en.wikipedia.org/wiki/Electronic_design_automation[EDA tools]
  212. * which implies that you can't get decent https://community.cadence.com/cadence_blogs_8/b/di/posts/hls-ppa-is-it-all-you-need-to-know[power, performance and area] estimates
  213. The only thing you can do with open source is purely functional designs with https://en.wikipedia.org/wiki/Verilator[Verilator], but you will never know if it can be actually produced and how efficient it can be.
  214. If you really want to develop semiconductors, your only choice is to join an university or a semiconductor company that has the EDA licenses.
  215. See also: xref:should-you-waste-your-life-with-systems-programming[xrefstyle=full].
  216. While hacking QEMU, you will likely want to GDB step its source. That is trivial since QEMU is just another userland program like any other, but our setup has a shortcut to make it even more convenient, see: xref:debug-the-emulator[xrefstyle=full].
  217. ===== Your first glibc hack
  218. We use <<libc-choice,glibc as our default libc now>>, and it is tracked as an unmodified submodule at link:submodules/glibc[], at the exact same version that Buildroot has it, which can be found at: https://github.com/buildroot/buildroot/blob/2018.05/package/glibc/glibc.mk#L13[package/glibc/glibc.mk]. Buildroot 2018.05 applies no patches.
  219. Let's hack up the `puts` function:
  220. ....
  221. ./build-buildroot -- glibc-reconfigure
  222. ....
  223. with the patch:
  224. ....
  225. diff --git a/libio/ioputs.c b/libio/ioputs.c
  226. index 706b20b492..23185948f3 100644
  227. --- a/libio/ioputs.c
  228. +++ b/libio/ioputs.c
  229. @@ -38,8 +38,9 @@ _IO_puts (const char *str)
  230. if ((_IO_vtable_offset (_IO_stdout) != 0
  231. || _IO_fwide (_IO_stdout, -1) == -1)
  232. && _IO_sputn (_IO_stdout, str, len) == len
  233. + && _IO_sputn (_IO_stdout, " hacked", 7) == 7
  234. && _IO_putc_unlocked ('\n', _IO_stdout) != EOF)
  235. - result = MIN (INT_MAX, len + 1);
  236. + result = MIN (INT_MAX, len + 1 + 7);
  237. _IO_release_lock (_IO_stdout);
  238. return result;
  239. ....
  240. And then:
  241. ....
  242. ./run --eval-after './c/hello.out'
  243. ....
  244. outputs:
  245. ....
  246. hello hacked
  247. ....
  248. Lol!
  249. We can also test our hacked glibc on <<user-mode-simulation>> with:
  250. ....
  251. ./run --userland userland/c/hello.c
  252. ....
  253. I just noticed that this is actually a good way to develop glibc for other archs.
  254. In this example, we got away without recompiling the userland program because we made a change that did not affect the glibc ABI, see this answer for an introduction to ABI stability: https://stackoverflow.com/questions/2171177/what-is-an-application-binary-interface-abi/54967743#54967743
  255. Note that for arch agnostic features that don't rely on bleeding kernel changes that you host doesn't yet have, you can develop glibc natively as explained at:
  256. * https://stackoverflow.com/questions/10412684/how-to-compile-my-own-glibc-c-standard-library-from-source-and-use-it/52454710#52454710
  257. * https://stackoverflow.com/questions/847179/multiple-glibc-libraries-on-a-single-host/52454603#52454603
  258. * https://stackoverflow.com/questions/2856438/how-can-i-link-to-a-specific-glibc-version/52550158#52550158 more focus on symbol versioning, but no one knows how to do it, so I answered
  259. Tested on a30ed0f047523ff2368d421ee2cce0800682c44e + 1.
  260. ===== Your first Binutils hack
  261. Have you ever felt that a single `inc` instruction was not enough? Really? Me too!
  262. So let's hack the <<gnu-gas-assembler>>, which is part of https://en.wikipedia.org/wiki/GNU_Binutils[GNU Binutils], to add a new shiny version of `inc` called... `myinc`!
  263. GCC uses GNU GAS as its backend, so we will test out new mnemonic with an <<gcc-inline-assembly>> test program: link:userland/arch/x86_64/binutils_hack.c[], which is just a copy of link:userland/arch/x86_64/binutils_nohack.c[] but with `myinc` instead of `inc`.
  264. The inline assembly is disabled with an `#ifdef`, so first modify the source to enable that.
  265. Then, try to build userland:
  266. ....
  267. ./build-userland
  268. ....
  269. and watch it fail with:
  270. ....
  271. binutils_hack.c:8: Error: no such instruction: `myinc %rax'
  272. ....
  273. Now, edit the file
  274. ....
  275. vim submodules/binutils-gdb/opcodes/i386-tbl.h
  276. ....
  277. and add a copy of the `"inc"` instruction just next to it, but with the new name `"myinc"`:
  278. ....
  279. diff --git a/opcodes/i386-tbl.h b/opcodes/i386-tbl.h
  280. index af583ce578..3cc341f303 100644
  281. --- a/opcodes/i386-tbl.h
  282. +++ b/opcodes/i386-tbl.h
  283. @@ -1502,6 +1502,19 @@ const insn_template i386_optab[] =
  284. { { { 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  285. 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0,
  286. 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 } } } },
  287. + { "myinc", 1, 0xfe, 0x0, 1,
  288. + { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  289. + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  290. + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  291. + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  292. + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
  293. + { 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  294. + 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0,
  295. + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  296. + 0, 0, 0, 0, 0, 0 },
  297. + { { { 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  298. + 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0,
  299. + 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 } } } },
  300. { "sub", 2, 0x28, None, 1,
  301. { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  303. ....
  304. Finally, rebuild Binutils, userland and test our program with <<user-mode-simulation>>:
  305. ....
  306. ./build-buildroot -- host-binutils-rebuild
  307. ./build-userland --static
  308. ./run --static --userland userland/arch/x86_64/binutils_hack.c
  309. ....
  310. and we se that `myinc` worked since the assert did not fail!
  311. Tested on b60784d59bee993bf0de5cde6c6380dd69420dda + 1.
  312. ===== Your first GCC hack
  313. OK, now time to hack GCC.
  314. For convenience, let's use the <<user-mode-simulation>>.
  315. If we run the program link:userland/c/gcc_hack.c[]:
  316. ....
  317. ./build-userland --static
  318. ./run --static --userland userland/c/gcc_hack.c
  319. ....
  320. it produces the normal boring output:
  321. ....
  322. i = 2
  323. j = 0
  324. ....
  325. So how about we swap `++` and `--` to make things more fun?
  326. Open the file:
  327. ....
  328. vim submodules/gcc/gcc/c/c-parser.c
  329. ....
  330. and find the function `c_parser_postfix_expression_after_primary`.
  331. In that function, swap `case CPP_PLUS_PLUS` and `case CPP_MINUS_MINUS`:
  332. ....
  333. diff --git a/gcc/c/c-parser.c b/gcc/c/c-parser.c
  334. index 101afb8e35f..89535d1759a 100644
  335. --- a/gcc/c/c-parser.c
  336. +++ b/gcc/c/c-parser.c
  337. @@ -8529,7 +8529,7 @@ c_parser_postfix_expression_after_primary (c_parser *parser,
  338. expr.original_type = DECL_BIT_FIELD_TYPE (field);
  339. }
  340. break;
  341. - case CPP_PLUS_PLUS:
  342. + case CPP_MINUS_MINUS:
  343. /* Postincrement. */
  344. start = expr.get_start ();
  345. finish = c_parser_peek_token (parser)->get_finish ();
  346. @@ -8548,7 +8548,7 @@ c_parser_postfix_expression_after_primary (c_parser *parser,
  347. expr.original_code = ERROR_MARK;
  348. expr.original_type = NULL;
  349. break;
  350. - case CPP_MINUS_MINUS:
  351. + case CPP_PLUS_PLUS:
  352. /* Postdecrement. */
  353. start = expr.get_start ();
  354. finish = c_parser_peek_token (parser)->get_finish ();
  355. ....
  356. Now rebuild GCC, the program and re-run it:
  357. ....
  358. ./build-buildroot -- host-gcc-final-rebuild
  359. ./build-userland --static
  360. ./run --static --userland userland/c/gcc_hack.c
  361. ....
  362. and the new ouptut is now:
  363. ....
  364. i = 2
  365. j = 0
  366. ....
  367. We need to use the ugly `-final` thing because GCC has to packages in Buildroot, `-initial` and `-final`: https://stackoverflow.com/questions/54992977/how-to-select-an-override-srcdir-source-for-gcc-when-building-buildroot No one is able to example precisely with a minimal example why this is required:
  368. * https://stackoverflow.com/questions/39883865/why-multiple-passes-for-building-linux-from-scratch-lfs
  369. * https://stackoverflow.com/questions/27457835/why-do-cross-compilers-have-a-two-stage-compilation
  370. ==== About the QEMU Buildroot setup
  371. This is our reference setup, and the best supported one, use it unless you have good reason not to.
  372. It was historically the first one we did, and all sections have been tested with this setup unless explicitly noted.
  373. Read the following sections for further introductory material:
  374. * <<introduction-to-qemu>>
  375. * <<introduction-to-buildroot>>
  376. === Dry run to get commands for your project
  377. One of the major features of this repository is that we try to support the `--dry-run` option really well for all scripts.
  378. This option, as the name suggests, outputs the external commands that would be run (or more precisely: equivalent commands), without actually running them.
  379. This allows you to just clone this repository and get full working commands to integrate into your project, without having to build or use this setup further!
  380. For example, we can obtain a QEMU run for the file link:userland/c/hello.c[] in <<user-mode-simulation>> by adding `--dry-run` to the normal command:
  381. ....
  382. ./run --dry-run --userland userland/c/hello.c
  383. ....
  384. which as of LKMC a18f28e263c91362519ef550150b5c9d75fa3679 + 1 outputs:
  385. ....
  386. + /path/to/linux-kernel-module-cheat/out/qemu/default/opt/x86_64-linux-user/qemu-x86_64 \
  387. -L /path/to/linux-kernel-module-cheat/out/buildroot/build/default/x86_64/target \
  388. -r 5.2.1 \
  389. -seed 0 \
  390. -trace enable=load_file,file=/path/to/linux-kernel-module-cheat/out/run/qemu/x86_64/0/trace.bin \
  391. -cpu max \
  392. /path/to/linux-kernel-module-cheat/out/userland/default/x86_64/c/hello.out \
  393. ;
  394. ....
  395. So observe that the command contains:
  396. * `+`: sign to differentiate it from program stdout, much like bash `-x` output. This is not a valid part of the generated Bash command however.
  397. * the actual command nicely, indented and with arguments broken one per line, but with continuing backslashes so you can just copy paste into a terminal
  398. * `;`: both a valid part of the Bash command, and a visual mark the end of the command
  399. For the specific case of running emulators such as QEMU, the last command is also automatically placed in a file for your convenience and later inspection:
  400. ....
  401. cat "$(./getvar run_dir)/run.sh"
  402. ....
  403. Furthermore, `--dry-run` also automatically specifies, in valid Bash shell syntax:
  404. * environment variables used to run the command with syntax `+ ENV_VAR_1=abc ENV_VAR_2=def ./some/command`
  405. * change in working directory with `+ cd /some/new/path && ./some/command`
  406. === gem5 Buildroot setup
  407. ==== About the gem5 Buildroot setup
  408. This setup is like the <<qemu-buildroot-setup>>, but it uses http://gem5.org/[gem5] instead of QEMU as a system simulator.
  409. QEMU tries to run as fast as possible and give correct results at the end, but it does not tell us how many CPU cycles it takes to do something, just the number of instructions it ran. This kind of simulation is known as functional simulation.
  410. The number of instructions executed is a very poor estimator of performance because in modern computers, a lot of time is spent waiting for memory requests rather than the instructions themselves.
  411. gem5 on the other hand, can simulate the system in more detail than QEMU, including:
  412. * simplified CPU pipeline
  413. * caches
  414. * DRAM timing
  415. and can therefore be used to estimate system performance, see: xref:gem5-run-benchmark[xrefstyle=full] for an example.
  416. The downside of gem5 much slower than QEMU because of the greater simulation detail.
  417. See <<gem5-vs-qemu>> for a more thorough comparison.
  418. ==== gem5 Buildroot setup getting started
  419. For the most part, if you just add the `--emulator gem5` option or `*-gem5` suffix to all commands and everything should magically work.
  420. If you haven't built Buildroot yet for <<qemu-buildroot-setup>>, you can build from the beginning with:
  421. ....
  422. ./build --download-dependencies gem5-buildroot
  423. ./run --emulator gem5
  424. ....
  425. If you have already built previously, don't be afraid: gem5 and QEMU use almost the same root filesystem and kernel, so `./build` will be fast.
  426. Remember that the gem5 boot is <<benchmark-linux-kernel-boot,considerably slower>> than QEMU since the simulation is more detailed.
  427. To get a terminal, either open a new shell and run:
  428. ....
  429. ./gem5-shell
  430. ....
  431. You can quit the shell without killing gem5 by typing tilde followed by a period:
  432. ....
  433. ~.
  434. ....
  435. If you are inside <<tmux>>, which I highly recommend, you can both run gem5 stdout and open the guest terminal on a split window with:
  436. ....
  437. ./run --emulator gem5 --tmux
  438. ....
  439. See also: xref:tmux-gem5[xrefstyle=full].
  440. At the end of boot, it might not be very clear that you have the shell since some <<printk>> messages may appear in front of the prompt like this:
  441. ....
  442. # <6>[ 1.215329] clocksource: tsc: mask: 0xffffffffffffffff max_cycles: 0x1cd486fa865, max_idle_ns: 440795259574 ns
  443. <6>[ 1.215351] clocksource: Switched to clocksource tsc
  444. ....
  445. but if you look closely, the `PS1` prompt marker `#` is there already, just hit enter and a clear prompt line will appear.
  446. If you forgot to open the shell and gem5 exit, you can inspect the terminal output post-mortem at:
  447. ....
  448. less "$(./getvar --emulator gem5 m5out_dir)/system.pc.com_1.device"
  449. ....
  450. More gem5 information is present at: xref:gem5[xrefstyle=full]
  451. Good next steps are:
  452. * <<gem5-run-benchmark>>
  453. * <<m5out-directory>>
  454. * <<m5ops>>
  455. [[docker]]
  456. === Docker host setup
  457. This repository has been tested inside clean https://en.wikipedia.org/wiki/Docker_(software)[Docker] containers.
  458. This is a good option if you are on a Linux host, but the native setup failed due to your weird host distribution, and you have better things to do with your life than to debug it. See also: xref:supported-hosts[xrefstyle=full].
  459. For example, to do a <<qemu-buildroot-setup>> inside Docker, run:
  460. ....
  461. sudo apt-get install docker
  462. ./run-docker create && \
  463. ./run-docker sh -- ./build --download-dependencies qemu-buildroot
  464. ./run-docker sh
  465. ....
  466. You are now left inside a shell in the Docker! From there, just run as usual:
  467. ....
  468. ./run
  469. ....
  470. The host git top level directory is mounted inside the guest with a https://stackoverflow.com/questions/23439126/how-to-mount-a-host-directory-in-a-docker-container[Docker volume], which means for example that you can use your host's GUI text editor directly on the files. Just don't forget that if you nuke that directory on the guest, then it gets nuked on the host as well!
  471. Command breakdown:
  472. * `./run-docker create`: create the image and container.
  473. +
  474. Needed only the very first time you use Docker, or if you run `./run-docker DESTROY` to restart for scratch, or save some disk space.
  475. +
  476. The image and container name is `lkmc`. The container shows under:
  477. +
  478. ....
  479. docker ps -a
  480. ....
  481. +
  482. and the image shows under:
  483. +
  484. ....
  485. docker images
  486. ....
  487. * `./run-docker sh`: open a shell on the container.
  488. +
  489. If it has not been started previously, start it. This can also be done explicitly with:
  490. +
  491. ....
  492. ./run-docker start
  493. ....
  494. +
  495. Quit the shell as usual with `Ctrl-D`
  496. +
  497. This can be called multiple times from different host terminals to open multiple shells.
  498. * `./run-docker stop`: stop the container.
  499. +
  500. This might save a bit of CPU and RAM once you stop working on this project, but it should not be a lot.
  501. * `./run-docker DESTROY`: delete the container and image.
  502. +
  503. This doesn't really clean the build, since we mount the guest's working directory on the host git top-level, so you basically just got rid of the `apt-get` installs.
  504. +
  505. To actually delete the Docker build, run on host:
  506. +
  507. ....
  508. # sudo rm -rf out.docker
  509. ....
  510. To use <<gdb>> from inside Docker, you need a second shell inside the container. You can either do that from another shell with:
  511. ....
  512. ./run-docker sh
  513. ....
  514. or even better, by starting a <<tmux>> session inside the container. We install `tmux` by default in the container.
  515. You can also start a second shell and run a command in it at the same time with:
  516. ....
  517. ./run-docker sh -- ./run-gdb start_kernel
  518. ....
  519. To use <<qemu-graphic-mode>> from Docker, run:
  520. ....
  521. ./run --graphic --vnc
  522. ....
  523. and then on host:
  524. ....
  525. sudo apt-get install vinagre
  526. ./vnc
  527. ....
  528. TODO make files created inside Docker be owned by the current user in host instead of `root`:
  529. * https://stackoverflow.com/questions/33681396/how-do-i-write-to-a-volume-container-as-non-root-in-docker
  530. * https://stackoverflow.com/questions/23544282/what-is-the-best-way-to-manage-permissions-for-docker-shared-volumes
  531. * https://stackoverflow.com/questions/31779802/shared-volume-file-permissions-ownership-docker
  532. [[prebuilt]]
  533. === Prebuilt setup
  534. ==== About the prebuilt setup
  535. This setup uses prebuilt binaries that we upload to GitHub from time to time.
  536. We don't currently provide a full prebuilt because it would be too big to host freely, notably because of the cross toolchain.
  537. Our prebuilts currently include:
  538. * <<qemu-buildroot-setup>> binaries
  539. ** Linux kernel
  540. ** root filesystem
  541. * <<baremetal-setup>> binaries for QEMU
  542. For more details, see our our <<release,release procedure>>.
  543. Advantage of this setup: saves time and disk space on the initial install, which is expensive in largely due to building the toolchain.
  544. The limitations are severe however:
  545. * can't <<gdb,GDB step debug the kernel>>, since the source and cross toolchain with GDB are not available. Buildroot cannot easily use a host toolchain: xref:prebuilt-toolchain[xrefstyle=full].
  546. +
  547. Maybe we could work around this by just downloading the kernel source somehow, and using a host prebuilt GDB, but we felt that it would be too messy and unreliable.
  548. * you won't get the latest version of this repository. Our <<travis>> attempt to automate builds failed, and storing a release for every commit would likely make GitHub mad at us anyways.
  549. * <<gem5>> is not currently supported. The major blocking point is how to avoid distributing the kernel images twice: once for gem5 which uses `vmlinux`, and once for QEMU which uses `arch/*` images, see also:
  550. ** https://github.com/cirosantilli/linux-kernel-module-cheat/issues/79
  551. ** <<vmlinux-vs-bzimage-vs-zimage-vs-image>>.
  552. This setup might be good enough for those developing simulators, as that requires less image modification. But once again, if you are serious about this, why not just let your computer build the <<qemu-buildroot-setup,full featured setup>> while you take a coffee or a nap? :-)
  553. ==== Prebuilt setup getting started
  554. Checkout to the latest tag and use the Ubuntu packaged QEMU to boot Linux:
  555. ....
  556. sudo apt-get install qemu-system-x86
  557. git clone https://github.com/cirosantilli/linux-kernel-module-cheat
  558. cd linux-kernel-module-cheat
  559. git checkout "$(git rev-list --tags --max-count=1)"
  560. ./release-download-latest
  561. unzip lkmc-*.zip
  562. ./run --qemu-which host
  563. ....
  564. You have to checkout to the latest tag to ensure that the scripts match the release format: https://stackoverflow.com/questions/1404796/how-to-get-the-latest-tag-name-in-current-branch-in-git
  565. This is known not to work for aarch64 on an Ubuntu 16.04 host with QEMU 2.5.0, presumably because QEMU is too old, the terminal does not show any output. I haven't investigated why.
  566. Or to run a baremetal example instead:
  567. ....
  568. ./run \
  569. --arch aarch64 \
  570. --baremetal userland/c/hello.c \
  571. --qemu-which host \
  572. ;
  573. ....
  574. Be saner and use our custom built QEMU instead:
  575. ....
  576. ./build --download-dependencies qemu
  577. ./run
  578. ....
  579. This also allows you to <<your-first-qemu-hack,modify QEMU>> if you're into that sort of thing.
  580. To build the kernel modules as in <<your-first-kernel-module-hack>> do:
  581. ....
  582. git submodule update --depth 1 --init --recursive "$(./getvar linux_source_dir)"
  583. ./build-linux --no-modules-install -- modules_prepare
  584. ./build-modules --gcc-which host
  585. ./run
  586. ....
  587. TODO: for now the only way to test those modules out without <<qemu-buildroot-setup-getting-started,building Buildroot>> is with 9p, since we currently rely on Buildroot to manipulate the root filesystem.
  588. Command explanation:
  589. * `modules_prepare` does the minimal build procedure required on the kernel for us to be able to compile the kernel modules, and is way faster than doing a full kernel build. A full kernel build would also work however.
  590. * `--gcc-which host` selects your host Ubuntu packaged GCC, since you don't have the Buildroot toolchain
  591. * `--no-modules-install` is required otherwise the `make modules_install` target we run by default fails, since the kernel wasn't built
  592. To modify the Linux kernel, build and use it as usual:
  593. ....
  594. git submodule update --depth 1 --init --recursive "$(./getvar linux_source_dir)"
  595. ./build-linux
  596. ./run
  597. ....
  598. ////
  599. For gem5, do:
  600. ....
  601. git submodule update --init --depth 1 "$(./getvar linux_source_dir)"
  602. sudo apt-get install qemu-utils
  603. ./build-gem5
  604. ./run --emulator gem5 --qemu-which host
  605. ....
  606. `qemu-utils` is required because we currently distribute `.qcow2` files which <<gem5-qcow2,gem5 can't handle>>, so we need `qemu-img` to extract them first.
  607. The Linux kernel is required for `extract-vmlinux` to convert the compressed kernel image which QEMU understands into the raw vmlinux that gem5 understands: https://superuser.com/questions/298826/how-do-i-uncompress-vmlinuz-to-vmlinux
  608. ////
  609. ////
  610. [[ubuntu]]
  611. === Ubuntu guest setup
  612. ==== About the Ubuntu guest setup
  613. This setup is similar to <<prebuilt>>, but instead of using Buildroot for the root filesystem, it downloads an Ubuntu image with Docker, and uses that as the root filesystem.
  614. The rationale for choice of Ubuntu as a second distribution in addition to Buildroot can be found at: xref:linux-distro-choice[xrefstyle=full]
  615. Advantages over Buildroot:
  616. * saves build time
  617. * you get to play with a huge selection of Debian packages out of the box
  618. * more representative of most non-embedded production systems than BusyBox
  619. Disadvantages:
  620. * less visibility: https://askubuntu.com/questions/82302/how-to-compile-ubuntu-from-source-code The fact that that question has no answer makes me cringe
  621. * less compatibility, e.g. no one knows what the officially supported cross compilers are: https://askubuntu.com/questions/1046294/what-are-the-officially-supported-cross-compilers-for-ubuntu-server-alternative
  622. Docker is used here just as an image download provider since it has a wide variety of images. Why we don't just download the regular Ubuntu disk image:
  623. * that image is not ready to boot, but rather goes into an interactive installer: https://askubuntu.com/questions/884534/how-to-run-ubuntu-16-04-desktop-on-qemu/1046792#1046792
  624. * the default Ubuntu image has a large collection of software, and is large. The docker version is much more minimal.
  625. One alternative would be to use https://wiki.ubuntu.com/Base[Ubuntu base] which can be downloaded from: http://cdimage.ubuntu.com/ubuntu-base That provides a `.tgz` and comes very close to what we obtain with Docker, but without the need for `sudo`.
  626. ==== Ubuntu guest setup getting started
  627. TODO
  628. ....
  629. sudo ./build-docker
  630. ./run --docker
  631. ....
  632. `sudo` is required for Docker operations: https://askubuntu.com/questions/477551/how-can-i-use-docker-without-sudo
  633. ////
  634. [[host]]
  635. === Host kernel module setup
  636. **THIS IS DANGEROUS (AND FUN), YOU HAVE BEEN WARNED**
  637. This method runs the kernel modules directly on your host computer without a VM, and saves you the compilation time and disk usage of the virtual machine method.
  638. It has however severe limitations:
  639. * can't control which kernel version and build options to use. So some of the modules will likely not compile because of kernel API changes, since https://stackoverflow.com/questions/37098482/how-to-build-a-linux-kernel-module-so-that-it-is-compatible-with-all-kernel-rele/45429681#45429681[the Linux kernel does not have a stable kernel module API].
  640. * bugs can easily break you system. E.g.:
  641. ** segfaults can trivially lead to a kernel crash, and require a reboot
  642. ** your disk could get erased. Yes, this can also happen with `sudo` from userland. But you should not use `sudo` when developing newbie programs. And for the kernel you don't have the choice not to use `sudo`.
  643. ** even more subtle system corruption such as https://unix.stackexchange.com/questions/78858/cannot-remove-or-reinsert-kernel-module-after-error-while-inserting-it-without-r[not being able to rmmod]
  644. * can't control which hardware is used, notably the CPU architecture
  645. * can't step debug it with <<gdb,GDB>> easily. The alternatives are https://en.wikipedia.org/wiki/JTAG[JTAG] or <<kgdb>>, but those are less reliable, and require extra hardware.
  646. Still interested?
  647. ....
  648. ./build-modules --gcc-which host --host
  649. ....
  650. Compilation will likely fail for some modules because of kernel or toolchain differences that we can't control on the host.
  651. The best workaround is to compile just your modules with:
  652. ....
  653. ./build-modules --gcc-which host --host -- hello hello2
  654. ....
  655. which is equivalent to:
  656. ....
  657. ./build-modules \
  658. --gcc-which host \
  659. --host \
  660. -- \
  661. kernel_modules/hello.c \
  662. kernel_modules/hello2.c \
  663. ;
  664. ....
  665. Or just remove the `.c` extension from the failing files and try again:
  666. ....
  667. cd "$(./getvar kernel_modules_source_dir)"
  668. mv broken.c broken.c~
  669. ....
  670. Once you manage to compile, and have come to terms with the fact that this may blow up your host, try it out with:
  671. ....
  672. cd "$(./getvar kernel_modules_build_host_subdir)"
  673. sudo insmod hello.ko
  674. # Our module is there.
  675. sudo lsmod | grep hello
  676. # Last message should be: hello init
  677. dmesg -T
  678. sudo rmmod hello
  679. # Last message should be: hello exit
  680. dmesg -T
  681. # Not present anymore
  682. sudo lsmod | grep hello
  683. ....
  684. ==== Hello host
  685. Minimal host build system example:
  686. ....
  687. cd hello_host_kernel_module
  688. make
  689. sudo insmod hello.ko
  690. dmesg
  691. sudo rmmod hello.ko
  692. dmesg
  693. ....
  694. === Userland setup
  695. ==== About the userland setup
  696. In order to test the kernel and emulators, userland content in the form of executables and scripts is of course required, and we store it mostly under:
  697. * link:userland/[]
  698. * <<rootfs_overlay>>
  699. * <<add-new-buildroot-packages>>
  700. When we started this repository, it only contained content that interacted very closely with the kernel, or that had required performance analysis.
  701. However, we soon started to notice that this had an increasing overlap with other userland test repositories: we were duplicating build and test infrastructure and even some examples.
  702. Therefore, we decided to consolidate other userland tutorials that we had scattered around into this repository.
  703. Notable userland content included / moving into this repository includes:
  704. * <<userland-assembly>>
  705. * <<c>>
  706. * <<cpp>>
  707. * <<posix>>
  708. * https://github.com/cirosantilli/algorithm-cheat TODO will be good to move here for performance analysis <<gem5-run-benchmark,with gem5>>
  709. ==== Userland setup getting started
  710. There are several ways to run our <<userland-content>>, notably:
  711. * natively on the host as shown at: xref:userland-setup-getting-started-natively[xrefstyle=full]
  712. +
  713. Can only run examples compatible with your host CPU architecture and OS, but has the fastest setup and runtimes.
  714. * from user mode simulation with:
  715. +
  716. --
  717. ** the host prebuilt toolchain: xref:userland-setup-getting-started-with-prebuilt-toolchain-and-qemu-user-mode[xrefstyle=full]
  718. ** the Buildroot toolchain you built yourself: xref:qemu-user-mode-getting-started[xrefstyle=full]
  719. --
  720. +
  721. This setup:
  722. +
  723. --
  724. ** can run most examples, including those for other CPU architectures, with the notable exception of examples that rely on kernel modules
  725. ** can run reproducible approximate performance experiments with gem5, see e.g. <<bst-vs-heap-vs-hashmap>>
  726. --
  727. * from full system simulation as shown at: xref:qemu-buildroot-setup-getting-started[xrefstyle=full].
  728. +
  729. This is the most reproducible and controlled environment, and all examples work there. But also the slower one to setup.
  730. ===== Userland setup getting started natively
  731. With this setup, we will use the host toolchain and execute executables directly on the host.
  732. No toolchain build is required, so you can just download your distro toolchain and jump straight into it.
  733. Build, run and example, and clean it in-tree with:
  734. ....
  735. sudo apt-get install gcc
  736. cd userland
  737. ./build c/hello
  738. ./c/hello.out
  739. ./build --clean
  740. ....
  741. Source: link:userland/c/hello.c[].
  742. Build an entire directory and test it:
  743. ....
  744. cd userland
  745. ./build c
  746. ./test c
  747. ....
  748. Build the current directory and test it:
  749. ....
  750. cd userland/c
  751. ./build
  752. ./test
  753. ....
  754. As mentioned at <<user-mode-tests>>, tests under link:userland/libs[] require certain optional libraries to be installed, and are not built or tested by default.
  755. You can install those libraries with:
  756. ....
  757. cd linux-kernel-module-cheat
  758. ./build --download-dependencies userland-host
  759. ....
  760. and then build the examples and test with:
  761. ....
  762. ./build --package-all
  763. ./test --package-all
  764. ....
  765. Pass custom compiler options:
  766. ....
  767. ./build --ccflags='-foptimize-sibling-calls -foptimize-strlen' --force-rebuild
  768. ....
  769. Here we used `--force-rebuild` to force rebuild since the sources weren't modified since the last build.
  770. Some CLI options have more specialized flags, e.g. `-O` optimization level:
  771. ....
  772. ./build --optimization-level 3 --force-rebuild
  773. ....
  774. See also <<user-mode-static-executables>> for `--static`.
  775. The `build` scripts inside link:userland/[] are just symlinks to link:build-userland-in-tree[] which you can also use from toplevel as:
  776. ....
  777. ./build-userland-in-tree
  778. ./build-userland-in-tree userland/c
  779. ./build-userland-in-tree userland/c/hello.c
  780. ....
  781. `build-userland-in-tre` is in turn just a thin wrapper around link:build-userland[]:
  782. ....
  783. ./build-userland --gcc-which host --in-tree userland/c
  784. ....
  785. So you can use any option supported by `build-userland` script freely with `build-userland-in-tree` and `build`.
  786. The situation is analogous for link:userland/test[], link:test-executables-in-tree[] and link:test-executables[], which are further documented at: xref:user-mode-tests[xrefstyle=full].
  787. Do a more clean out-of-tree build instead and run the program:
  788. ....
  789. ./build-userland --gcc-which host --userland-build-id host
  790. ./run --emulator native --userland userland/c/hello.c --userland-build-id host
  791. ....
  792. Here we:
  793. * put the host executables in a separate <<build-variants,build-variant>> to avoid conflict with Buildroot builds.
  794. * ran with the `--emulator native` option to run the program natively
  795. In this case you can debub the program with:
  796. ....
  797. ./run --debug-vm --emulator native --userland userland/c/hello.c --userland-build-id host
  798. ....
  799. as shown at: xref:debug-the-emulator[xrefstyle=full], although direct GDB host usage works as well of course.
  800. ===== Userland setup getting started with prebuilt toolchain and QEMU user mode
  801. If you are lazy to built the Buildroot toolchain and QEMU, but want to run e.g. ARM <<userland-assembly>> in <<user-mode-simulation>>, you can get away on Ubuntu 18.04 with just:
  802. ....
  803. sudo apt-get install gcc-aarch64-linux-gnu qemu-system-aarch64
  804. ./build-userland \
  805. --arch aarch64 \
  806. --gcc-which host \
  807. --userland-build-id host \
  808. ;
  809. ./run \
  810. --arch aarch64 \
  811. --qemu-which host \
  812. --userland-build-id host \
  813. --userland userland/c/command_line_arguments.c \
  814. --userland-args 'asdf "qw er"' \
  815. ;
  816. ....
  817. where:
  818. * `--gcc-which host`: use the host toolchain.
  819. +
  820. We must pass this to `./run` as well because QEMU must know which dynamic libraries to use. See also: xref:user-mode-static-executables[xrefstyle=full].
  821. * `--userland-build-id host`: put the host built into a <<build-variants>>
  822. This present the usual trade-offs of using prebuilts as mentioned at: xref:prebuilt[xrefstyle=full].
  823. Other functionality are analogous, e.g. testing:
  824. ....
  825. ./test-executables \
  826. --arch aarch64 \
  827. --gcc-which host \
  828. --qemu-which host \
  829. --userland-build-id host \
  830. ;
  831. ....
  832. and <<user-mode-gdb>>:
  833. ....
  834. ./run \
  835. --arch aarch64 \
  836. --gdb \
  837. --gcc-which host \
  838. --qemu-which host \
  839. --userland-build-id host \
  840. --userland userland/c/command_line_arguments.c \
  841. --userland-args 'asdf "qw er"' \
  842. ;
  843. ....
  844. ===== Userland setup getting started full system
  845. First ensure that <<qemu-buildroot-setup>> is working.
  846. After doing that setup, you can already execute your userland programs from inside QEMU: the only missing step is how to rebuild executables and run them.
  847. And the answer is exactly analogous to what is shown at: xref:your-first-kernel-module-hack[xrefstyle=full]
  848. For example, if we modify link:userland/c/hello.c[] to print out something different, we can just rebuild it with:
  849. ....
  850. ./build-userland
  851. ....
  852. Source: link:build-userland[]. `./build` calls that script automatically for us when doing the initial full build.
  853. Now, run the program either without rebooting use the <<9p>> mount:
  854. ....
  855. /mnt/9p/out_rootfs_overlay/c/hello.out
  856. ....
  857. or shutdown QEMU, add the executable to the root filesystem:
  858. ....
  859. ./build-buildroot
  860. ....
  861. reboot and use the root filesystem as usual:
  862. ....
  863. ./hello.out
  864. ....
  865. === Baremetal setup
  866. ==== About the baremetal setup
  867. This setup does not use the Linux kernel nor Buildroot at all: it just runs your very own minimal OS.
  868. `x86_64` is not currently supported, only `arm` and `aarch64`: I had made some x86 bare metal examples at: https://github.com/cirosantilli/x86-bare-metal-examples but I'm lazy to port them here now. Pull requests are welcome.
  869. The main reason this setup is included in this project, despite the word "Linux" being on the project name, is that a lot of the emulator boilerplate can be reused for both use cases.
  870. This setup allows you to make a tiny OS and that runs just a few instructions, use it to fully control the CPU to better understand the simulators for example, or develop your own OS if you are into that.
  871. You can also use C and a subset of the C standard library because we enable https://en.wikipedia.org/wiki/Newlib[Newlib] by default. See also: https://electronics.stackexchange.com/questions/223929/c-standard-libraries-on-bare-metal/400077#400077
  872. Our C bare-metal compiler is built with https://github.com/crosstool-ng/crosstool-ng[crosstool-NG]. If you have already built <<qemu-buildroot-setup,Buildroot>> previously, you will end up with two GCCs installed. Unfortunately I don't see a solution for this, since we need separate toolchains for Newlib on baremetal and glibc on Linux: https://stackoverflow.com/questions/38956680/difference-between-arm-none-eabi-and-arm-linux-gnueabi/38989869#38989869
  873. ==== Baremetal setup getting started
  874. Every `.c` file inside link:baremetal/[] and `.S` file inside `baremetal/arch/<arch>/` generates a separate baremetal image.
  875. For example, to run link:baremetal/arch/aarch64/dump_regs.c[] in QEMU do:
  876. ....
  877. ./build --arch aarch64 --download-dependencies qemu-baremetal
  878. ./run --arch aarch64 --baremetal baremetal/arch/aarch64/dump_regs.c
  879. ....
  880. And the terminal prints the values of certain system registers. This example prints registers that are only accessible from <<arm-exception-levels,EL1>> or higher, and thus could not be run in userland.
  881. In addition to the examples under link:baremetal/[], several of the <<userland-content,userland examples>> can also be run in baremetal! This is largely due to the <<about-the-baremetal-setup,awesomeness of Newlib>>.
  882. The examples that work include most <<c,C examples>> that don't rely on complicated syscalls such as threads, and almost all the <<userland-assembly>> examples.
  883. The exact list of userland programs that work in baremetal is specified in <<path-properties>> with the `baremetal` property, but you can also easily find it out with a <<baremetal-tests,baremetal test dry run>>:
  884. ....
  885. ./test-executables --arch aarch64 --dry-run --mode baremetal
  886. ....
  887. For example, we can run the C hello world link:userland/c/hello.c[] simply as:
  888. ....
  889. ./run --arch aarch64 --baremetal userland/c/hello.c
  890. ....
  891. and that outputs to the serial port the string:
  892. ....
  893. hello
  894. ....
  895. which QEMU shows on the host terminal.
  896. To modify a baremetal program, simply edit the file, e.g.
  897. ....
  898. vim userland/c/hello.c
  899. ....
  900. and rebuild:
  901. ....
  902. ./build-baremetal --arch aarch64
  903. ./run --arch aarch64 --baremetal userland/c/hello.c
  904. ....
  905. `./build qemu-baremetal` that we run previously is only needed for the initial build. That script calls link:build-baremetal[] for us, in addition to building prerequisites such as QEMU and crosstool-NG.
  906. `./build-baremetal` uses crosstool-NG, and so it must be preceded by link:build-crosstool-ng[], which `./build qemu-baremetal` also calls.
  907. Now let's run link:userland/arch/aarch64/add.S[]:
  908. ....
  909. ./run --arch aarch64 --baremetal userland/arch/aarch64/add.S
  910. ....
  911. This time, the terminal does not print anything, which indicates success: if you look into the source, you will see that we just have an assertion there.
  912. You can see a sample assertion fail in link:userland/c/assert_fail.c[]:
  913. ....
  914. ./run --arch aarch64 --baremetal userland/c/assert_fail.c
  915. ....
  916. and the terminal contains:
  917. ....
  918. lkmc_exit_status_134
  919. error: simulation error detected by parsing logs
  920. ....
  921. and the exit status of our script is 1:
  922. ....
  923. echo $?
  924. ....
  925. You can run all the baremetal examples in one go and check that all assertions passed with:
  926. ....
  927. ./test-executables --arch aarch64 --mode baremetal
  928. ....
  929. To use gem5 instead of QEMU do:
  930. ....
  931. ./build --download-dependencies gem5-baremetal
  932. ./run --arch aarch64 --baremetal userland/c/hello.c --emulator gem5
  933. ....
  934. and then <<qemu-buildroot-setup,as usual>> open a shell with:
  935. ....
  936. ./gem5-shell
  937. ....
  938. Or as usual, <<tmux>> users can do both in one go with:
  939. ....
  940. ./run --arch aarch64 --baremetal userland/c/hello.c --emulator gem5 --tmux
  941. ....
  942. TODO: the carriage returns are a bit different than in QEMU, see: xref:gem5-baremetal-carriage-return[xrefstyle=full].
  943. Note that `./build-baremetal` requires the `--emulator gem5` option, and generates separate executable images for both, as can be seen from:
  944. ....
  945. echo "$(./getvar --arch aarch64 --baremetal userland/c/hello.c --emulator qemu image)"
  946. echo "$(./getvar --arch aarch64 --baremetal userland/c/hello.c --emulator gem5 image)"
  947. ....
  948. This is unlike the Linux kernel that has a single image for both QEMU and gem5:
  949. ....
  950. echo "$(./getvar --arch aarch64 --emulator qemu image)"
  951. echo "$(./getvar --arch aarch64 --emulator gem5 image)"
  952. ....
  953. The reason for that is that on baremetal we don't parse the <<device-tree,device tress>> from memory like the Linux kernel does, which tells the kernel for example the UART address, and many other system parameters.
  954. `gem5` also supports the `RealViewPBX` machine, which represents an older hardware compared to the default `VExpress_GEM5_V1`:
  955. ....
  956. ./build-baremetal --arch aarch64 --emulator gem5 --machine RealViewPBX
  957. ./run --arch aarch64 --baremetal userland/c/hello.c --emulator gem5 --machine RealViewPBX
  958. ....
  959. see also: xref:gem5-arm-platforms[xrefstyle=full].
  960. This generates yet new separate images with new magic constants:
  961. ....
  962. echo "$(./getvar --arch aarch64 --baremetal userland/c/hello.c --emulator gem5 --machine VExpress_GEM5_V1 image)"
  963. echo "$(./getvar --arch aarch64 --baremetal userland/c/hello.c --emulator gem5 --machine RealViewPBX image)"
  964. ....
  965. But just stick to newer and better `VExpress_GEM5_V1` unless you have a good reason to use `RealViewPBX`.
  966. When doing baremetal programming, it is likely that you will want to learn userland assembly first, see: xref:userland-assembly[xrefstyle=full].
  967. For more information on baremetal, see the section: xref:baremetal[xrefstyle=full].
  968. The following subjects are particularly important:
  969. * <<tracing>>
  970. * <<baremetal-gdb-step-debug>>
  971. === Build the documentation
  972. You don't need to depend on GitHub.
  973. For a quick and dirty build, install https://asciidoctor.org/[Asciidoctor] however you like and build:
  974. ....
  975. asciidoctor README.adoc
  976. xdg-open README.html
  977. ....
  978. For development, you will want to do a more controlled build with extra error checking as follows.
  979. For the initial build do:
  980. ....
  981. ./build --download-dependencies docs
  982. ....
  983. which also downloads build dependencies.
  984. Then the following times just to the faster:
  985. ....
  986. ./build-doc
  987. ....
  988. Source: link:build-doc[]
  989. The HTML output is located at:
  990. ....
  991. xdg-open out/README.html
  992. ....
  993. More information about our documentation internals can be found at: xref:documentation[xrefstyle=full]
  994. [[gdb]]
  995. == GDB step debug
  996. === GDB step debug kernel boot
  997. `--gdb-wait` makes QEMU and gem5 wait for a GDB connection, otherwise we could accidentally go past the point we want to break at:
  998. ....
  999. ./run --gdb-wait
  1000. ....
  1001. Say you want to break at `start_kernel`. So on another shell:
  1002. ....
  1003. ./run-gdb start_kernel
  1004. ....
  1005. or at a given line:
  1006. ....
  1007. ./run-gdb init/main.c:1088
  1008. ....
  1009. Now QEMU will stop there, and you can use the normal GDB commands:
  1010. ....
  1011. list
  1012. next
  1013. continue
  1014. ....
  1015. See also:
  1016. * https://stackoverflow.com/questions/11408041/how-to-debug-the-linux-kernel-with-gdb-and-qemu/33203642#33203642
  1017. * https://stackoverflow.com/questions/4943857/linux-kernel-live-debugging-how-its-done-and-what-tools-are-used/42316607#42316607
  1018. ==== GDB step debug kernel boot other archs
  1019. Just don't forget to pass `--arch` to `./run-gdb`, e.g.:
  1020. ....
  1021. ./run --arch aarch64 --gdb-wait
  1022. ....
  1023. and:
  1024. ....
  1025. ./run-gdb --arch aarch64 start_kernel
  1026. ....
  1027. [[kernel-o0]]
  1028. ==== Disable kernel compiler optimizations
  1029. https://stackoverflow.com/questions/29151235/how-to-de-optimize-the-linux-kernel-to-and-compile-it-with-o0
  1030. `O=0` is an impossible dream, `O=2` being the default.
  1031. So get ready for some weird jumps, and `<value optimized out>` fun. Why, Linux, why.
  1032. === GDB step debug kernel post-boot
  1033. Let's observe the kernel `write` system call as it reacts to some userland actions.
  1034. Start QEMU with just:
  1035. ....
  1036. ./run
  1037. ....
  1038. and after boot inside a shell run:
  1039. ....
  1040. ./count.sh
  1041. ....
  1042. which counts to infinity to stdout. Source: link:rootfs_overlay/lkmc/count.sh[].
  1043. Then in another shell, run:
  1044. ....
  1045. ./run-gdb
  1046. ....
  1047. and then hit:
  1048. ....
  1049. Ctrl-C
  1050. break __x64_sys_write
  1051. continue
  1052. continue
  1053. continue
  1054. ....
  1055. And you now control the counting on the first shell from GDB!
  1056. Before v4.17, the symbol name was just `sys_write`, the change happened at https://github.com/torvalds/linux/commit/d5a00528b58cdb2c71206e18bd021e34c4eab878[d5a00528b58cdb2c71206e18bd021e34c4eab878]. As of Linux v 4.19, the function is called `sys_write` in `arm`, and `__arm64_sys_write` in `aarch64`. One good way to find it if the name changes again is to try:
  1057. ....
  1058. rbreak .*sys_write
  1059. ....
  1060. or just have a quick look at the sources!
  1061. When you hit `Ctrl-C`, if we happen to be inside kernel code at that point, which is very likely if there are no heavy background tasks waiting, and we are just waiting on a `sleep` type system call of the command prompt, we can already see the source for the random place inside the kernel where we stopped.
  1062. === tmux
  1063. tmux just makes things even more fun by allowing us to see both the terminal for:
  1064. * emulator stdout
  1065. * <<gdb>>
  1066. at once without dragging windows around!
  1067. First start `tmux` with:
  1068. ....
  1069. tmux
  1070. ....
  1071. Now that you are inside a shell inside tmux, you can start GDB simply with:
  1072. ....
  1073. ./run --gdb
  1074. ....
  1075. which is just a convenient shortcut for:
  1076. ....
  1077. ./run --gdb-wait --tmux --tmux-args start_kernel
  1078. ....
  1079. This splits the terminal into two panes:
  1080. * left: usual QEMU with terminal
  1081. * right: GDB
  1082. and focuses on the GDB pane.
  1083. Now you can navigate with the usual tmux shortcuts:
  1084. * switch between the two panes with: `Ctrl-B O`
  1085. * close either pane by killing its terminal with `Ctrl-D` as usual
  1086. See the tmux manual for further details:
  1087. ....
  1088. man tmux
  1089. ....
  1090. To start again, switch back to the QEMU pane with `Ctrl-O`, kill the emulator, and re-run:
  1091. ....
  1092. ./run --gdb
  1093. ....
  1094. This automatically clears the GDB pane, and starts a new one.
  1095. The option `--tmux-args` determines which options will be passed to the program running on the second tmux pane, and is equivalent to:
  1096. This is equivalent to:
  1097. ....
  1098. ./run --gdb-wait
  1099. ./run-gdb start_kernel
  1100. ....
  1101. Due to Python's CLI parsing quicks, if the link:run-gdb[] arguments start with a dash `-`, you have to use the `=` sign, e.g. to <<gdb-step-debug-early-boot>>:
  1102. ....
  1103. ./run --gdb --tmux-args=--no-continue
  1104. ....
  1105. Bibliography: https://unix.stackexchange.com/questions/152738/how-to-split-a-new-window-and-run-a-command-in-this-new-window-using-tmux/432111#432111
  1106. ==== tmux gem5
  1107. If you are using gem5 instead of QEMU, `--tmux` has a different effect by default: it opens the gem5 terminal instead of the debugger:
  1108. ....
  1109. ./run --emulator gem5 --tmux
  1110. ....
  1111. To open a new pane with GDB instead of the terminal, use:
  1112. ....
  1113. ./run --gdb
  1114. ....
  1115. which is equivalent to:
  1116. ....
  1117. ./run --emulator gem5 --gdb-wait --tmux --tmux-args start_kernel --tmux-program gdb
  1118. ....
  1119. `--tmux-program` implies `--tmux`, so we can just write:
  1120. ....
  1121. ./run --emulator gem5 --gdb-wait --tmux-program gdb
  1122. ....
  1123. If you also want to see both GDB and the terminal with gem5, then you will need to open a separate shell manually as usual with `./gem5-shell`.
  1124. From inside tmux, you can create new terminals on a new window with `Ctrl-B C` split a pane yet again vertically with `Ctrl-B %` or horizontally with `Ctrl-B "`.
  1125. === GDB step debug kernel module
  1126. https://stackoverflow.com/questions/28607538/how-to-debug-linux-kernel-modules-with-qemu/44095831#44095831
  1127. Loadable kernel modules are a bit trickier since the kernel can place them at different memory locations depending on load order.
  1128. So we cannot set the breakpoints before `insmod`.
  1129. However, the Linux kernel GDB scripts offer the `lx-symbols` command, which takes care of that beautifully for us.
  1130. Shell 1:
  1131. ....
  1132. ./run
  1133. ....
  1134. Wait for the boot to end and run:
  1135. ....
  1136. insmod timer.ko
  1137. ....
  1138. Source: link:kernel_modules/timer.c[].
  1139. This prints a message to dmesg every second.
  1140. Shell 2:
  1141. ....
  1142. ./run-gdb
  1143. ....
  1144. In GDB, hit `Ctrl-C`, and note how it says:
  1145. ....
  1146. scanning for modules in /root/linux-kernel-module-cheat/out/kernel_modules/x86_64/kernel_modules
  1147. loading @0xffffffffc0000000: /root/linux-kernel-module-cheat/out/kernel_modules/x86_64/kernel_modules/timer.ko
  1148. ....
  1149. That's `lx-symbols` working! Now simply:
  1150. ....
  1151. break lkmc_timer_callback
  1152. continue
  1153. continue
  1154. continue
  1155. ....
  1156. and we now control the callback from GDB!
  1157. Just don't forget to remove your breakpoints after `rmmod`, or they will point to stale memory locations.
  1158. TODO: why does `break work_func` for `insmod kthread.ko` not very well? Sometimes it breaks but not others.
  1159. [[gdb-step-debug-kernel-module-arm]]
  1160. ==== GDB step debug kernel module insmodded by init on ARM
  1161. TODO on `arm` 51e31cdc2933a774c2a0dc62664ad8acec1d2dbe it does not always work, and `lx-symbols` fails with the message:
  1162. ....
  1163. loading vmlinux
  1164. Traceback (most recent call last):
  1165. File "/linux-kernel-module-cheat//out/arm/buildroot/build/linux-custom/scripts/gdb/linux/symbols.py", line 163, in invoke
  1166. self.load_all_symbols()
  1167. File "/linux-kernel-module-cheat//out/arm/buildroot/build/linux-custom/scripts/gdb/linux/symbols.py", line 150, in load_all_symbols
  1168. [self.load_module_symbols(module) for module in module_list]
  1169. File "/linux-kernel-module-cheat//out/arm/buildroot/build/linux-custom/scripts/gdb/linux/symbols.py", line 110, in load_module_symbols
  1170. module_name = module['name'].string()
  1171. gdb.MemoryError: Cannot access memory at address 0xbf0000cc
  1172. Error occurred in Python command: Cannot access memory at address 0xbf0000cc
  1173. ....
  1174. Can't reproduce on `x86_64` and `aarch64` are fine.
  1175. It is kind of random: if you just `insmod` manually and then immediately `./run-gdb --arch arm`, then it usually works.
  1176. But this fails most of the time: shell 1:
  1177. ....
  1178. ./run --arch arm --eval-after 'insmod hello.ko'
  1179. ....
  1180. shell 2:
  1181. ....
  1182. ./run-gdb --arch arm
  1183. ....
  1184. then hit `Ctrl-C` on shell 2, and voila.
  1185. Then:
  1186. ....
  1187. cat /proc/modules
  1188. ....
  1189. says that the load address is:
  1190. ....
  1191. 0xbf000000
  1192. ....
  1193. so it is close to the failing `0xbf0000cc`.
  1194. `readelf`:
  1195. ....
  1196. ./run-toolchain readelf -- -s "$(./getvar kernel_modules_build_subdir)/hello.ko"
  1197. ....
  1198. does not give any interesting hits at `cc`, no symbol was placed that far.
  1199. ==== GDB module_init
  1200. TODO find a more convenient method. We have working methods, but they are not ideal.
  1201. This is not very easy, since by the time the module finishes loading, and `lx-symbols` can work properly, `module_init` has already finished running!
  1202. Possibly asked at:
  1203. * https://stackoverflow.com/questions/37059320/debug-a-kernel-module-being-loaded
  1204. * https://stackoverflow.com/questions/11888412/debug-the-init-module-call-of-a-linux-kernel-module
  1205. ===== GDB module_init step into it
  1206. This is the best method we've found so far.
  1207. The kernel calls `module_init` synchronously, therefore it is not hard to step into that call.
  1208. As of 4.16, the call happens in `do_one_initcall`, so we can do in shell 1:
  1209. ....
  1210. ./run
  1211. ....
  1212. shell 2 after boot finishes (because there are other calls to `do_init_module` at boot, presumably for the built-in modules):
  1213. ....
  1214. ./run-gdb do_one_initcall
  1215. ....
  1216. then step until the line:
  1217. ....
  1218. 833 ret = fn();
  1219. ....
  1220. which does the actual call, and then step into it.
  1221. For the next time, you can also put a breakpoint there directly:
  1222. ....
  1223. ./run-gdb init/main.c:833
  1224. ....
  1225. How we found this out: first we got <<gdb-module_init-calculate-entry-address>> working, and then we did a `bt`. AKA cheating :-)
  1226. ===== GDB module_init calculate entry address
  1227. This works, but is a bit annoying.
  1228. The key observation is that the load address of kernel modules is deterministic: there is a pre allocated memory region https://www.kernel.org/doc/Documentation/x86/x86_64/mm.txt "module mapping space" filled from bottom up.
  1229. So once we find the address the first time, we can just reuse it afterwards, as long as we don't modify the module.
  1230. Do a fresh boot and get the module:
  1231. ....
  1232. ./run --eval-after './pr_debug.sh;insmod fops.ko;./linux/poweroff.out'
  1233. ....
  1234. The boot must be fresh, because the load address changes every time we insert, even after removing previous modules.
  1235. The base address shows on terminal:
  1236. ....
  1237. 0xffffffffc0000000 .text
  1238. ....
  1239. Now let's find the offset of `myinit`:
  1240. ....
  1241. ./run-toolchain readelf -- \
  1242. -s "$(./getvar kernel_modules_build_subdir)/fops.ko" | \
  1243. grep myinit
  1244. ....
  1245. which gives:
  1246. ....
  1247. 30: 0000000000000240 43 FUNC LOCAL DEFAULT 2 myinit
  1248. ....
  1249. so the offset address is `0x240` and we deduce that the function will be placed at:
  1250. ....
  1251. 0xffffffffc0000000 + 0x240 = 0xffffffffc0000240
  1252. ....
  1253. Now we can just do a fresh boot on shell 1:
  1254. ....
  1255. ./run --eval 'insmod fops.ko;./linux/poweroff.out' --gdb-wait
  1256. ....
  1257. and on shell 2:
  1258. ....
  1259. ./run-gdb '*0xffffffffc0000240'
  1260. ....
  1261. GDB then breaks, and `lx-symbols` works.
  1262. ===== GDB module_init break at the end of sys_init_module
  1263. TODO not working. This could be potentially very convenient.
  1264. The idea here is to break at a point late enough inside `sys_init_module`, at which point `lx-symbols` can be called and do its magic.
  1265. Beware that there are both `sys_init_module` and `sys_finit_module` syscalls, and `insmod` uses `fmodule_init` by default.
  1266. Both call `do_module_init` however, which is what `lx-symbols` hooks to.
  1267. If we try:
  1268. ....
  1269. b sys_finit_module
  1270. ....
  1271. then hitting:
  1272. ....
  1273. n
  1274. ....
  1275. does not break, and insertion happens, likely because of optimizations? <<kernel-o0>>
  1276. Then we try:
  1277. ....
  1278. b do_init_module
  1279. ....
  1280. A naive:
  1281. ....
  1282. fin
  1283. ....
  1284. also fails to break!
  1285. Finally, in despair we notice that <<pr_debug>> prints the kernel load address as explained at <<bypass-lx-symbols>>.
  1286. So, if we set a breakpoint just after that message is printed by searching where that happens on the Linux source code, we must be able to get the correct load address before `init_module` happens.
  1287. ===== GDB module_init add trap instruction
  1288. This is another possibility: we could modify the module source by adding a trap instruction of some kind.
  1289. This appears to be described at: https://www.linuxjournal.com/article/4525
  1290. But it refers to a `gdbstart` script which is not in the tree anymore and beyond my `git log` capabilities.
  1291. And just adding:
  1292. ....
  1293. asm( " int $3");
  1294. ....
  1295. directly gives an <<oops,oops>> as I'd expect.
  1296. ==== Bypass lx-symbols
  1297. Useless, but a good way to show how hardcore you are. Disable `lx-symbols` with:
  1298. ....
  1299. ./run-gdb --no-lxsymbols
  1300. ....
  1301. From inside guest:
  1302. ....
  1303. insmod timer.ko
  1304. cat /proc/modules
  1305. ....
  1306. as mentioned at:
  1307. * https://stackoverflow.com/questions/6384605/how-to-get-address-of-a-kernel-module-loaded-using-insmod/6385818
  1308. * https://unix.stackexchange.com/questions/194405/get-base-address-and-size-of-a-loaded-kernel-module
  1309. This will give a line of form:
  1310. ....
  1311. fops 2327 0 - Live 0xfffffffa00000000
  1312. ....
  1313. And then tell GDB where the module was loaded with:
  1314. ....
  1315. Ctrl-C
  1316. add-symbol-file ../../../rootfs_overlay/x86_64/timer.ko 0xffffffffc0000000
  1317. 0xffffffffc0000000
  1318. ....
  1319. Alternatively, if the module panics before you can read `/proc/modules`, there is a <<pr_debug>> which shows the load address:
  1320. ....
  1321. echo 8 > /proc/sys/kernel/printk
  1322. echo 'file kernel/module.c +p' > /sys/kernel/debug/dynamic_debug/control
  1323. ./linux/myinsmod.out hello.ko
  1324. ....
  1325. And then search for a line of type:
  1326. ....
  1327. [ 84.877482] 0xfffffffa00000000 .text
  1328. ....
  1329. Tested on 4f4749148273c282e80b58c59db1b47049e190bf + 1.
  1330. === GDB step debug early boot
  1331. TODO successfully debug the very first instruction that the Linux kernel runs, before `start_kernel`!
  1332. Break at the very first instruction executed by QEMU:
  1333. ....
  1334. ./run-gdb --no-continue
  1335. ....
  1336. TODO why can't we break at early startup stuff such as:
  1337. ....
  1338. ./run-gdb extract_kernel
  1339. ./run-gdb main
  1340. ....
  1341. Maybe it is because they are being copied around at specific locations instead of being run directly from inside the main image, which is where the debug information points to?
  1342. See also: https://stackoverflow.com/questions/2589845/what-are-the-first-operations-that-the-linux-kernel-executes-on-boot
  1343. <<gem5-tracing>> with `--debug-flags=Exec` does show the right symbols however! So in the worst case, we can just read their source. Amazing.
  1344. v4.19 also added a `CONFIG_HAVE_KERNEL_UNCOMPRESSED=y` option for having the kernel uncompressed which could make following the startup easier, but it is only available on s390. `aarch64` however is already uncompressed by default, so might be the easiest one. See also: xref:vmlinux-vs-bzimage-vs-zimage-vs-image[xrefstyle=full].
  1345. ==== GDB step debug early boot by address
  1346. One possibility is to run:
  1347. ....
  1348. ./trace-boot --arch arm
  1349. ....
  1350. and then find the second address (the first one does not work, already too late maybe):
  1351. ....
  1352. less "$(./getvar --arch arm trace_txt_file)"
  1353. ....
  1354. and break there:
  1355. ....
  1356. ./run --arch arm --gdb-wait
  1357. ./run-gdb --arch arm '*0x1000'
  1358. ....
  1359. but TODO: it does not show the source assembly under `arch/arm`: https://stackoverflow.com/questions/11423784/qemu-arm-linux-kernel-boot-debug-no-source-code
  1360. I also tried to hack `run-gdb` with:
  1361. ....
  1362. @@ -81,7 +81,7 @@ else
  1363. ${gdb} \
  1364. -q \\
  1365. -ex 'add-auto-load-safe-path $(pwd)' \\
  1366. --ex 'file vmlinux' \\
  1367. +-ex 'file arch/arm/boot/compressed/vmlinux' \\
  1368. -ex 'target remote localhost:${port}' \\
  1369. ${brk} \
  1370. -ex 'continue' \\
  1371. ....
  1372. and no I do have the symbols from `arch/arm/boot/compressed/vmlinux'`, but the breaks still don't work.
  1373. === GDB step debug userland processes
  1374. QEMU's `-gdb` GDB breakpoints are set on virtual addresses, so you can in theory debug userland processes as well.
  1375. * https://stackoverflow.com/questions/26271901/is-it-possible-to-use-gdb-and-qemu-to-debug-linux-user-space-programs-and-kernel
  1376. * https://stackoverflow.com/questions/16273614/debug-init-on-qemu-using-gdb
  1377. You will generally want to use <<gdbserver>> for this as it is more reliable, but this method can overcome the following limitations of `gdbserver`:
  1378. * the emulator does not support host to guest networking. This seems to be the case for gem5 as explained at: xref:gem5-host-to-guest-networking[xrefstyle=full]
  1379. * cannot see the start of the `init` process easily
  1380. * `gdbserver` alters the working of the kernel, and makes your run less representative
  1381. Known limitations of direct userland debugging:
  1382. * the kernel might switch context to another process or to the kernel itself e.g. on a system call, and then TODO confirm the PIC would go to weird places and source code would be missing.
  1383. +
  1384. Solutions to this are being researched at: xref:lx-ps[xrefstyle=full].
  1385. * TODO step into shared libraries. If I attempt to load them explicitly:
  1386. +
  1387. ....
  1388. (gdb) sharedlibrary ../../staging/lib/libc.so.0
  1389. No loaded shared libraries match the pattern `../../staging/lib/libc.so.0'.
  1390. ....
  1391. +
  1392. since GDB does not know that libc is loaded.
  1393. ==== GDB step debug userland custom init
  1394. This is the userland debug setup most likely to work, since at init time there is only one userland executable running.
  1395. For executables from the link:userland/[] directory such as link:userland/posix/count.c[]:
  1396. * Shell 1:
  1397. +
  1398. ....
  1399. ./run --gdb-wait --kernel-cli 'init=/lkmc/posix/count.out'
  1400. ....
  1401. * Shell 2:
  1402. +
  1403. ....
  1404. ./run-gdb --userland userland/posix/count.c main
  1405. ....
  1406. +
  1407. Alternatively, we could also pass the full path to the executable:
  1408. +
  1409. ....
  1410. ./run-gdb --userland "$(./getvar userland_build_dir)/posix/count.out" main
  1411. ....
  1412. +
  1413. Path resolution is analogous to <<baremetal-setup-getting-started,that of `./run --baremetal`>>.
  1414. Then, as soon as boot ends, we are left inside a debug session that looks just like what `gdbserver` would produce.
  1415. ==== GDB step debug userland BusyBox init
  1416. BusyBox custom init process:
  1417. * Shell 1:
  1418. +
  1419. ....
  1420. ./run --gdb-wait --kernel-cli 'init=/bin/ls'
  1421. ....
  1422. * Shell 2:
  1423. +
  1424. ....
  1425. ./run-gdb --userland "$(./getvar buildroot_build_build_dir)"/busybox-*/busybox ls_main
  1426. ....
  1427. This follows BusyBox' convention of calling the main for each executable as `<exec>_main` since the `busybox` executable has many "mains".
  1428. BusyBox default init process:
  1429. * Shell 1:
  1430. +
  1431. ....
  1432. ./run --gdb-wait
  1433. ....
  1434. * Shell 2:
  1435. +
  1436. ....
  1437. ./run-gdb --userland "$(./getvar buildroot_build_build_dir)"/busybox-*/busybox init_main
  1438. ....
  1439. `init` cannot be debugged with <<gdbserver>> without modifying the source, or else `/sbin/init` exits early with:
  1440. ....
  1441. "must be run as PID 1"
  1442. ....
  1443. ==== GDB step debug userland non-init
  1444. Non-init process:
  1445. * Shell 1:
  1446. +
  1447. ....
  1448. ./run --gdb-wait
  1449. ....
  1450. * Shell 2:
  1451. +
  1452. ....
  1453. ./run-gdb --userland userland/linux/rand_check.c main
  1454. ....
  1455. * Shell 1 after the boot finishes:
  1456. +
  1457. ....
  1458. ./linux/rand_check.out
  1459. ....
  1460. This is the least reliable setup as there might be other processes that use the given virtual address.
  1461. [[gdb-step-debug-userland-non-init-without-gdb-wait]]
  1462. ===== GDB step debug userland non-init without --gdb-wait
  1463. TODO: if I try <<gdb-step-debug-userland-non-init>> without `--gdb-wait` and the `break main` that we do inside `./run-gdb` says:
  1464. ....
  1465. Cannot access memory at address 0x10604
  1466. ....
  1467. and then GDB never breaks. Tested at ac8663a44a450c3eadafe14031186813f90c21e4 + 1.
  1468. The exact behaviour seems to depend on the architecture:
  1469. * `arm`: happens always
  1470. * `x86_64`: appears to happen only if you try to connect GDB as fast as possible, before init has been reached.
  1471. * `aarch64`: could not observe the problem
  1472. We have also double checked the address with:
  1473. ....
  1474. ./run-toolchain --arch arm readelf -- \
  1475. -s "$(./getvar --arch arm userland_build_dir)/linux/myinsmod.out" | \
  1476. grep main
  1477. ....
  1478. and from GDB:
  1479. ....
  1480. info line main
  1481. ....
  1482. and both give:
  1483. ....
  1484. 000105fc
  1485. ....
  1486. which is just 8 bytes before `0x10604`.
  1487. `gdbserver` also says `0x10604`.
  1488. However, if do a `Ctrl-C` in GDB, and then a direct:
  1489. ....
  1490. b *0x000105fc
  1491. ....
  1492. it works. Why?!
  1493. On GEM5, x86 can also give the `Cannot access memory at address`, so maybe it is also unreliable on QEMU, and works just by coincidence.
  1494. === GDB call
  1495. GDB can call functions as explained at: https://stackoverflow.com/questions/1354731/how-to-evaluate-functions-in-gdb
  1496. However this is failing for us:
  1497. * some symbols are not visible to `call` even though `b` sees them
  1498. * for those that are, `call` fails with an E14 error
  1499. E.g.: if we break on `__x64_sys_write` on `count.sh`:
  1500. ....
  1501. >>> call printk(0, "asdf")
  1502. Could not fetch register "orig_rax"; remote failure reply 'E14'
  1503. >>> b printk
  1504. Breakpoint 2 at 0xffffffff81091bca: file kernel/printk/printk.c, line 1824.
  1505. >>> call fdget_pos(fd)
  1506. No symbol "fdget_pos" in current context.
  1507. >>> b fdget_pos
  1508. Breakpoint 3 at 0xffffffff811615e3: fdget_pos. (9 locations)
  1509. >>>
  1510. ....
  1511. even though `fdget_pos` is the first thing `__x64_sys_write` does:
  1512. ....
  1513. 581 SYSCALL_DEFINE3(write, unsigned int, fd, const char __user *, buf,
  1514. 582 size_t, count)
  1515. 583 {
  1516. 584 struct fd f = fdget_pos(fd);
  1517. ....
  1518. I also noticed that I get the same error:
  1519. ....
  1520. Could not fetch register "orig_rax"; remote failure reply 'E14'
  1521. ....
  1522. when trying to use:
  1523. ....
  1524. fin
  1525. ....
  1526. on many (all?) functions.
  1527. See also: https://github.com/cirosantilli/linux-kernel-module-cheat/issues/19
  1528. === GDB view ARM system registers
  1529. `info all-registers` shows some of them.
  1530. The implementation is described at: https://stackoverflow.com/questions/46415059/how-to-observe-aarch64-system-registers-in-qemu/53043044#53043044
  1531. === GDB step debug multicore userland
  1532. For a more minimal baremetal multicore setup, see: xref:arm-multicore[xrefstyle=full].
  1533. We can set and get which cores the Linux kernel allows a program to run on with `sched_getaffinity` and `sched_setaffinity`:
  1534. ....
  1535. ./run --cpus 2 --eval-after './linux/sched_getaffinity.out'
  1536. ....
  1537. Source: link:userland/linux/sched_getaffinity.c[]
  1538. Sample output:
  1539. ....
  1540. sched_getaffinity = 1 1
  1541. sched_getcpu = 1
  1542. sched_getaffinity = 1 0
  1543. sched_getcpu = 0
  1544. ....
  1545. Which shows us that:
  1546. * initially:
  1547. ** all 2 cores were enabled as shown by `sched_getaffinity = 1 1`
  1548. ** the process was randomly assigned to run on core 1 (the second one) as shown by `sched_getcpu = 1`. If we run this several times, it will also run on core 0 sometimes.
  1549. * then we restrict the affinity to just core 0, and we see that the program was actually moved to core 0
  1550. The number of cores is modified as explained at: xref:number-of-cores[xrefstyle=full]
  1551. `taskset` from the util-linux package sets the initial core affinity of a program:
  1552. ....
  1553. ./build-buildroot \
  1554. --config 'BR2_PACKAGE_UTIL_LINUX=y' \
  1555. --config 'BR2_PACKAGE_UTIL_LINUX_SCHEDUTILS=y' \
  1556. ;
  1557. ./run --eval-after 'taskset -c 1,1 ./linux/sched_getaffinity.out'
  1558. ....
  1559. output:
  1560. ....
  1561. sched_getaffinity = 0 1
  1562. sched_getcpu = 1
  1563. sched_getaffinity = 1 0
  1564. sched_getcpu = 0
  1565. ....
  1566. so we see that the affinity was restricted to the second core from the start.
  1567. Let's do a QEMU observation to justify this example being in the repository with <<gdb-step-debug-userland-non-init,userland breakpoints>>.
  1568. We will run our `./linux/sched_getaffinity.out` infinitely many times, on core 0 and core 1 alternatively:
  1569. ....
  1570. ./run \
  1571. --cpus 2 \
  1572. --eval-after 'i=0; while true; do taskset -c $i,$i ./linux/sched_getaffinity.out; i=$((! $i)); done' \
  1573. --gdb-wait \
  1574. ;
  1575. ....
  1576. on another shell:
  1577. ....
  1578. ./run-gdb --userland "$(./getvar userland_build_dir)/linux/sched_getaffinity.out" main
  1579. ....
  1580. Then, inside GDB:
  1581. ....
  1582. (gdb) info threads
  1583. Id Target Id Frame
  1584. * 1 Thread 1 (CPU#0 [running]) main () at sched_getaffinity.c:30
  1585. 2 Thread 2 (CPU#1 [halted ]) native_safe_halt () at ./arch/x86/include/asm/irqflags.h:55
  1586. (gdb) c
  1587. (gdb) info threads
  1588. Id Target Id Frame
  1589. 1 Thread 1 (CPU#0 [halted ]) native_safe_halt () at ./arch/x86/include/asm/irqflags.h:55
  1590. * 2 Thread 2 (CPU#1 [running]) main () at sched_getaffinity.c:30
  1591. (gdb) c
  1592. ....
  1593. and we observe that `info threads` shows the actual correct core on which the process was restricted to run by `taskset`!
  1594. We should also try it out with kernel modules: https://stackoverflow.com/questions/28347876/set-cpu-affinity-on-a-loadable-linux-kernel-module
  1595. TODO we then tried:
  1596. ....
  1597. ./run --cpus 2 --eval-after './linux/sched_getaffinity_threads.out'
  1598. ....
  1599. and:
  1600. ....
  1601. ./run-gdb --userland "$(./getvar userland_build_dir)/linux/sched_getaffinity_threads.out"
  1602. ....
  1603. to switch between two simultaneous live threads with different affinities, it just didn't break on our threads:
  1604. ....
  1605. b main_thread_0
  1606. ....
  1607. Bibliography:
  1608. * https://stackoverflow.com/questions/10490756/how-to-use-sched-getaffinity-and-sched-setaffinity-in-linux-from-c/50117787#50117787
  1609. * https://stackoverflow.com/questions/42800801/how-to-use-gdb-to-debug-qemu-with-smp-symmetric-multiple-processors
  1610. === Linux kernel GDB scripts
  1611. We source the Linux kernel GDB scripts by default for `lx-symbols`, but they also contains some other goodies worth looking into.
  1612. Those scripts basically parse some in-kernel data structures to offer greater visibility with GDB.
  1613. All defined commands are prefixed by `lx-`, so to get a full list just try to tab complete that.
  1614. There aren't as many as I'd like, and the ones that do exist are pretty self explanatory, but let's give a few examples.
  1615. Show dmesg:
  1616. ....
  1617. lx-dmesg
  1618. ....
  1619. Show the <<kernel-command-line-parameters>>:
  1620. ....
  1621. lx-cmdline
  1622. ....
  1623. Dump the device tree to a `fdtdump.dtb` file in the current directory:
  1624. ....
  1625. lx-fdtdump
  1626. pwd
  1627. ....
  1628. List inserted kernel modules:
  1629. ....
  1630. lx-lsmod
  1631. ....
  1632. Sample output:
  1633. ....
  1634. Address Module Size Used by
  1635. 0xffffff80006d0000 hello 16384 0
  1636. ....
  1637. Bibliography:
  1638. * https://events.static.linuxfound.org/sites/events/files/slides/Debugging%20the%20Linux%20Kernel%20with%20GDB.pdf
  1639. * https://wiki.linaro.org/LandingTeams/ST/GDB
  1640. ==== lx-ps
  1641. List all processes:
  1642. ....
  1643. lx-ps
  1644. ....
  1645. Sample output:
  1646. ....
  1647. 0xffff88000ed08000 1 init
  1648. 0xffff88000ed08ac0 2 kthreadd
  1649. ....
  1650. The second and third fields are obviously PID and process name.
  1651. The first one is more interesting, and contains the address of the `task_struct` in memory.
  1652. This can be confirmed with:
  1653. ....
  1654. p ((struct task_struct)*0xffff88000ed08000
  1655. ....
  1656. which contains the correct PID for all threads I've tried:
  1657. ....
  1658. pid = 1,
  1659. ....
  1660. TODO get the PC of the kthreads: https://stackoverflow.com/questions/26030910/find-program-counter-of-process-in-kernel Then we would be able to see where the threads are stopped in the code!
  1661. On ARM, I tried:
  1662. ....
  1663. task_pt_regs((struct thread_info *)((struct task_struct)*0xffffffc00e8f8000))->uregs[ARM_pc]
  1664. ....
  1665. but `task_pt_regs` is a `#define` and GDB cannot see defines without `-ggdb3`: https://stackoverflow.com/questions/2934006/how-do-i-print-a-defined-constant-in-gdb which are apparently not set?
  1666. Bibliography:
  1667. * https://stackoverflow.com/questions/9561546/thread-aware-gdb-for-kernel
  1668. * https://wiki.linaro.org/LandingTeams/ST/GDB
  1669. * https://events.static.linuxfound.org/sites/events/files/slides/Debugging%20the%20Linux%20Kernel%20with%20GDB.pdf presentation: https://www.youtube.com/watch?v=pqn5hIrz3A8
  1670. === Debug the GDB remote protocol
  1671. For when it breaks again, or you want to add a new feature!
  1672. ....
  1673. ./run --debug
  1674. ./run-gdb --before '-ex "set remotetimeout 99999" -ex "set debug remote 1"' start_kernel
  1675. ....
  1676. See also: https://stackoverflow.com/questions/13496389/gdb-remote-protocol-how-to-analyse-packets
  1677. [[remote-g-packet]]
  1678. ==== Remote 'g' packet reply is too long
  1679. This error means that the GDB server, e.g. in QEMU, sent more registers than the GDB client expected.
  1680. This can happen for the following reasons:
  1681. * you set the architecture of the client wrong, often 32 vs 64 bit as mentioned at: https://stackoverflow.com/questions/4896316/gdb-remote-cross-debugging-fails-with-remote-g-packet-reply-is-too-long
  1682. * there is a bug in the GDB server and the XML description does not match the number of registers actually sent
  1683. * the GDB server does not send XML target descriptions and your GDB expects a different number of registers by default. E.g., gem5 d4b3e064adeeace3c3e7d106801f95c14637c12f does not send the XML files
  1684. The XML target description format is described a bit further at: https://stackoverflow.com/questions/46415059/how-to-observe-aarch64-system-registers-in-qemu/53043044#53043044
  1685. == KGDB
  1686. KGDB is kernel dark magic that allows you to GDB the kernel on real hardware without any extra hardware support.
  1687. It is useless with QEMU since we already have full system visibility with `-gdb`. So the goal of this setup is just to prepare you for what to expect when you will be in the treches of real hardware.
  1688. KGDB is cheaper than JTAG (free) and easier to setup (all you need is serial), but with less visibility as it depends on the kernel working, so e.g.: dies on panic, does not see boot sequence.
  1689. First run the kernel with:
  1690. ....
  1691. ./run --kgdb
  1692. ....
  1693. this passes the following options on the kernel CLI:
  1694. ....
  1695. kgdbwait kgdboc=ttyS1,115200
  1696. ....
  1697. `kgdbwait` tells the kernel to wait for KGDB to connect.
  1698. So the kernel sets things up enough for KGDB to start working, and then boot pauses waiting for connection:
  1699. ....
  1700. <6>[ 4.866050] Serial: 8250/16550 driver, 4 ports, IRQ sharing disabled
  1701. <6>[ 4.893205] 00:05: ttyS0 at I/O 0x3f8 (irq = 4, base_baud = 115200) is a 16550A
  1702. <6>[ 4.916271] 00:06: ttyS1 at I/O 0x2f8 (irq = 3, base_baud = 115200) is a 16550A
  1703. <6>[ 4.987771] KGDB: Registered I/O driver kgdboc
  1704. <2>[ 4.996053] KGDB: Waiting for connection from remote gdb...
  1705. Entering kdb (current=0x(____ptrval____), pid 1) on processor 0 due to Keyboard Entry
  1706. [0]kdb>
  1707. ....
  1708. KGDB expects the connection at `ttyS1`, our second serial port after `ttyS0` which contains the terminal.
  1709. The last line is the KDB prompt, and is covered at: xref:kdb[xrefstyle=full]. Typing now shows nothing because that prompt is expecting input from `ttyS1`.
  1710. Instead, we connect to the serial port `ttyS1` with GDB:
  1711. ....
  1712. ./run-gdb --kgdb --no-continue
  1713. ....
  1714. Once GDB connects, it is left inside the function `kgdb_breakpoint`.
  1715. So now we can set breakpoints and continue as usual.
  1716. For example, in GDB:
  1717. ....
  1718. continue
  1719. ....
  1720. Then in QEMU:
  1721. ....
  1722. ./count.sh &
  1723. ./kgdb.sh
  1724. ....
  1725. link:rootfs_overlay/lkmc/kgdb.sh[] pauses the kernel for KGDB, and gives control back to GDB.
  1726. And now in GDB we do the usual:
  1727. ....
  1728. break __x64_sys_write
  1729. continue
  1730. continue
  1731. continue
  1732. continue
  1733. ....
  1734. And now you can count from KGDB!
  1735. If you do: `break __x64_sys_write` immediately after `./run-gdb --kgdb`, it fails with `KGDB: BP remove failed: <address>`. I think this is because it would break too early on the boot sequence, and KGDB is not yet ready.
  1736. See also:
  1737. * https://github.com/torvalds/linux/blob/v4.9/Documentation/DocBook/kgdb.tmpl
  1738. * https://stackoverflow.com/questions/22004616/qemu-kernel-debugging-with-kgdb/44197715#44197715
  1739. === KGDB ARM
  1740. TODO: we would need a second serial for KGDB to work, but it is not currently supported on `arm` and `aarch64` with `-M virt` that we use: https://unix.stackexchange.com/questions/479085/can-qemu-m-virt-on-arm-aarch64-have-multiple-serial-ttys-like-such-as-pl011-t/479340#479340
  1741. One possible workaround for this would be to use <<kdb-arm>>.
  1742. Main more generic question: https://stackoverflow.com/questions/14155577/how-to-use-kgdb-on-arm
  1743. === KGDB kernel modules
  1744. Just works as you would expect:
  1745. ....
  1746. insmod timer.ko
  1747. ./kgdb.sh
  1748. ....
  1749. In GDB:
  1750. ....
  1751. break lkmc_timer_callback
  1752. continue
  1753. continue
  1754. continue
  1755. ....
  1756. and you now control the count.
  1757. === KDB
  1758. KDB is a way to use KDB directly in your main console, without GDB.
  1759. Advantage over KGDB: you can do everything in one serial. This can actually be important if you only have one serial for both shell and .
  1760. Disadvantage: not as much functionality as GDB, especially when you use Python scripts. Notably, TODO confirm you can't see the the kernel source code and line step as from GDB, since the kernel source is not available on guest (ah, if only debugging information supported full source, or if the kernel had a crazy mechanism to embed it).
  1761. Run QEMU as:
  1762. ....
  1763. ./run --kdb
  1764. ....
  1765. This passes `kgdboc=ttyS0` to the Linux CLI, therefore using our main console. Then QEMU:
  1766. ....
  1767. [0]kdb> go
  1768. ....
  1769. And now the `kdb>` prompt is responsive because it is listening to the main console.
  1770. After boot finishes, run the usual:
  1771. ....
  1772. ./count.sh &
  1773. ./kgdb.sh
  1774. ....
  1775. And you are back in KDB. Now you can count with:
  1776. ....
  1777. [0]kdb> bp __x64_sys_write
  1778. [0]kdb> go
  1779. [0]kdb> go
  1780. [0]kdb> go
  1781. [0]kdb> go
  1782. ....
  1783. And you will break whenever `__x64_sys_write` is hit.
  1784. You can get see further commands with:
  1785. ....
  1786. [0]kdb> help
  1787. ....
  1788. The other KDB commands allow you to step instructions, view memory, registers and some higher level kernel runtime data similar to the superior GDB Python scripts.
  1789. ==== KDB graphic
  1790. You can also use KDB directly from the <<graphics,graphic>> window with:
  1791. ....
  1792. ./run --graphic --kdb
  1793. ....
  1794. This setup could be used to debug the kernel on machines without serial, such as modern desktops.
  1795. This works because `--graphics` adds `kbd` (which stands for `KeyBoarD`!) to `kgdboc`.
  1796. ==== KDB ARM
  1797. TODO neither `arm` and `aarch64` are working as of 1cd1e58b023791606498ca509256cc48e95e4f5b + 1.
  1798. `arm` seems to place and hit the breakpoint correctly, but no matter how many `go` commands I do, the `count.sh` stdout simply does not show.
  1799. `aarch64` seems to place the breakpoint correctly, but after the first `go` the kernel oopses with warning:
  1800. ....
  1801. WARNING: CPU: 0 PID: 46 at /root/linux-kernel-module-cheat/submodules/linux/kernel/smp.c:416 smp_call_function_many+0xdc/0x358
  1802. ....
  1803. and stack trace:
  1804. ....
  1805. smp_call_function_many+0xdc/0x358
  1806. kick_all_cpus_sync+0x30/0x38
  1807. kgdb_flush_swbreak_addr+0x3c/0x48
  1808. dbg_deactivate_sw_breakpoints+0x7c/0xb8
  1809. kgdb_cpu_enter+0x284/0x6a8
  1810. kgdb_handle_exception+0x138/0x240
  1811. kgdb_brk_fn+0x2c/0x40
  1812. brk_handler+0x7c/0xc8
  1813. do_debug_exception+0xa4/0x1c0
  1814. el1_dbg+0x18/0x78
  1815. __arm64_sys_write+0x0/0x30
  1816. el0_svc_handler+0x74/0x90
  1817. el0_svc+0x8/0xc
  1818. ....
  1819. My theory is that every serious ARM developer has JTAG, and no one ever tests this, and the kernel code is just broken.
  1820. == gdbserver
  1821. Step debug userland processes to understand how they are talking to the kernel.
  1822. First build `gdbserver` into the root filesystem:
  1823. ....
  1824. ./build-buildroot --config 'BR2_PACKAGE_GDB=y'
  1825. ....
  1826. Then on guest, to debug link:userland/linux/rand_check.c[]:
  1827. ....
  1828. ./gdbserver.sh ./c/print_argv.out asdf qwer
  1829. ....
  1830. Source: link:rootfs_overlay/lkmc/gdbserver.sh[].
  1831. And on host:
  1832. ....
  1833. ./run-gdb --gdbserver --userland userland/c/command_line_arguments.c main
  1834. ....
  1835. or alternatively with the path to the executable itself:
  1836. ....
  1837. ./run --gdbserver --userland "$(./getvar userland_build_dir)/c/print_argv.out"
  1838. ....
  1839. Bibliography: https://reverseengineering.stackexchange.com/questions/8829/cross-debugging-for-arm-mips-elf-with-qemu-toolchain/16214#16214
  1840. === gdbserver BusyBox
  1841. Analogous to <<gdb-step-debug-userland-processes>>:
  1842. ....
  1843. ./gdbserver.sh ls
  1844. ....
  1845. on host you need:
  1846. ....
  1847. ./run-gdb --gdbserver --userland "$(./getvar buildroot_build_build_dir)"/busybox-*/busybox ls_main
  1848. ....
  1849. === gdbserver libc
  1850. Our setup gives you the rare opportunity to step debug libc and other system libraries.
  1851. For example in the guest:
  1852. ....
  1853. ./gdbserver.sh ./posix/count.out
  1854. ....
  1855. Then on host:
  1856. ....
  1857. ./run-gdb --gdbserver --userland userland/posix/count.c main
  1858. ....
  1859. and inside GDB:
  1860. ....
  1861. break sleep
  1862. continue
  1863. ....
  1864. And you are now left inside the `sleep` function of our default libc implementation uclibc https://cgit.uclibc-ng.org/cgi/cgit/uclibc-ng.git/tree/libc/unistd/sleep.c?h=v1.0.30#n91[`libc/unistd/sleep.c`]!
  1865. You can also step into the `sleep` call:
  1866. ....
  1867. step
  1868. ....
  1869. This is made possible by the GDB command that we use by default:
  1870. ....
  1871. set sysroot ${common_buildroot_build_dir}/staging
  1872. ....
  1873. which automatically finds unstripped shared libraries on the host for us.
  1874. See also: https://stackoverflow.com/questions/8611194/debugging-shared-libraries-with-gdbserver/45252113#45252113
  1875. === gdbserver dynamic loader
  1876. TODO: try to step debug the dynamic loader. Would be even easier if `starti` is available: https://stackoverflow.com/questions/10483544/stopping-at-the-first-machine-code-instruction-in-gdb
  1877. Bibliography: https://stackoverflow.com/questions/20114565/gdb-step-into-dynamic-linkerld-so-code
  1878. == CPU architecture
  1879. The portability of the kernel and toolchains is amazing: change an option and most things magically work on completely different hardware.
  1880. To use `arm` instead of x86 for example:
  1881. ....
  1882. ./build-buildroot --arch arm
  1883. ./run --arch arm
  1884. ....
  1885. Debug:
  1886. ....
  1887. ./run --arch arm --gdb-wait
  1888. # On another terminal.
  1889. ./run-gdb --arch arm
  1890. ....
  1891. We also have one letter shorthand names for the architectures and `--arch` option:
  1892. ....
  1893. # aarch64
  1894. ./run -a A
  1895. # arm
  1896. ./run -a a
  1897. # x86_64
  1898. ./run -a x
  1899. ....
  1900. Known quirks of the supported architectures are documented in this section.
  1901. === x86_64
  1902. ==== ring0
  1903. This example illustrates how reading from the x86 control registers with `mov crX, rax` can only be done from kernel land on ring0.
  1904. From kernel land:
  1905. ....
  1906. insmod ring0.ko
  1907. ....
  1908. works and output the registers, for example:
  1909. ....
  1910. cr0 = 0xFFFF880080050033
  1911. cr2 = 0xFFFFFFFF006A0008
  1912. cr3 = 0xFFFFF0DCDC000
  1913. ....
  1914. However if we try to do it from userland:
  1915. ....
  1916. ./ring0.out
  1917. ....
  1918. stdout gives:
  1919. ....
  1920. Segmentation fault
  1921. ....
  1922. and dmesg outputs:
  1923. ....
  1924. traps: ring0.out[55] general protection ip:40054c sp:7fffffffec20 error:0 in ring0.out[400000+1000]
  1925. ....
  1926. Sources:
  1927. * link:kernel_modules/ring0.c[]
  1928. * link:lkmc/ring0.h[]
  1929. * link:userland/arch/x86_64/ring0.c[]
  1930. In both cases, we attempt to run the exact same code which is shared on the `ring0.h` header file.
  1931. Bibliography:
  1932. * https://stackoverflow.com/questions/7415515/how-to-access-the-control-registers-cr0-cr2-cr3-from-a-program-getting-segmenta/7419306#7419306
  1933. * https://stackoverflow.com/questions/18717016/what-are-ring-0-and-ring-3-in-the-context-of-operating-systems/44483439#44483439
  1934. === arm
  1935. ==== Run arm executable in aarch64
  1936. TODO Can you run arm executables in the aarch64 guest? https://stackoverflow.com/questions/22460589/armv8-running-legacy-32-bit-applications-on-64-bit-os/51466709#51466709
  1937. I've tried:
  1938. ....
  1939. ./run-toolchain --arch aarch64 gcc -- -static ~/test/hello_world.c -o "$(./getvar p9_dir)/a.out"
  1940. ./run --arch aarch64 --eval-after '/mnt/9p/data/a.out'
  1941. ....
  1942. but it fails with:
  1943. ....
  1944. a.out: line 1: syntax error: unexpected word (expecting ")")
  1945. ....
  1946. === MIPS
  1947. We used to "support" it until f8c0502bb2680f2dbe7c1f3d7958f60265347005 (it booted) but dropped since one was testing it often.
  1948. If you want to revive and maintain it, send a pull request.
  1949. === Other architectures
  1950. It should not be too hard to port this repository to any architecture that Buildroot supports. Pull requests are welcome.
  1951. == init
  1952. When the Linux kernel finishes booting, it runs an executable as the first and only userland process. This executable is called the `init` program.
  1953. The init process is then responsible for setting up the entire userland (or destroying everything when you want to have fun).
  1954. This typically means reading some configuration files (e.g. `/etc/initrc`) and forking a bunch of userland executables based on those files, including the very interactive shell that we end up on.
  1955. systemd provides a "popular" init implementation for desktop distros as of 2017.
  1956. BusyBox provides its own minimalistic init implementation which Buildroot, and therefore this repo, uses by default.
  1957. The `init` program can be either an executable shell text file, or a compiled ELF file. It becomes easy to accept this once you see that the `exec` system call handles both cases equally: https://unix.stackexchange.com/questions/174062/can-the-init-process-be-a-shell-script-in-linux/395375#395375
  1958. The `init` executable is searched for in a list of paths in the root filesystem, including `/init`, `/sbin/init` and a few others. For more details see: xref:path-to-init[xrefstyle=full]
  1959. === Replace init
  1960. To have more control over the system, you can replace BusyBox's init with your own.
  1961. The most direct way to replace `init` with our own is to just use the `init=` <<kernel-command-line-parameters,command line parameter>> directly:
  1962. ....
  1963. ./run --kernel-cli 'init=/lkmc/count.sh'
  1964. ....
  1965. This just counts every second forever and does not give you a shell.
  1966. This method is not very flexible however, as it is hard to reliably pass multiple commands and command line arguments to the init with it, as explained at: xref:init-environment[xrefstyle=full].
  1967. For this reason, we have created a more robust helper method with the `--eval` option:
  1968. ....
  1969. ./run --eval 'echo "asdf qwer";insmod hello.ko;./linux/poweroff.out'
  1970. ....
  1971. It is basically a shortcut for:
  1972. ....
  1973. ./run --kernel-cli 'init=/lkmc/eval_base64.sh - lkmc_eval="insmod hello.ko;./linux/poweroff.out"'
  1974. ....
  1975. Source: link:rootfs_overlay/lkmc/eval_base64.sh[].
  1976. This allows quoting and newlines by base64 encoding on host, and decoding on guest, see: xref:kernel-command-line-parameters-escaping[xrefstyle=full].
  1977. It also automatically chooses between `init=` and `rcinit=` for you, see: xref:path-to-init[xrefstyle=full]
  1978. `--eval` replaces BusyBox' init completely, which makes things more minimal, but also has has the following consequences:
  1979. * `/etc/fstab` mounts are not done, notably `/proc` and `/sys`, test it out with:
  1980. +
  1981. ....
  1982. ./run --eval 'echo asdf;ls /proc;ls /sys;echo qwer'
  1983. ....
  1984. * no shell is launched at the end of boot for you to interact with the system. You could explicitly add a `sh` at the end of your commands however:
  1985. +
  1986. ....
  1987. ./run --eval 'echo hello;sh'
  1988. ....
  1989. The best way to overcome those limitations is to use: xref:init-busybox[xrefstyle=full]
  1990. If the script is large, you can add it to a gitignored file and pass that to `--eval` as in:
  1991. ....
  1992. echo '
  1993. cd /lkmc
  1994. insmod hello.ko
  1995. ./linux/poweroff.out
  1996. ' > data/gitignore.sh
  1997. ./run --eval "$(cat data/gitignore.sh)"
  1998. ....
  1999. or add it to a file to the root filesystem guest and rebuild:
  2000. ....
  2001. echo '#!/bin/sh
  2002. cd /lkmc
  2003. insmod hello.ko
  2004. ./linux/poweroff.out
  2005. ' > rootfs_overlay/lkmc/gitignore.sh
  2006. chmod +x rootfs_overlay/lkmc/gitignore.sh
  2007. ./build-buildroot
  2008. ./run --kernel-cli 'init=/lkmc/gitignore.sh'
  2009. ....
  2010. Remember that if your init returns, the kernel will panic, there are just two non-panic possibilities:
  2011. * run forever in a loop or long sleep
  2012. * `poweroff` the machine
  2013. ==== poweroff.out
  2014. Just using BusyBox' `poweroff` at the end of the `init` does not work and the kernel panics:
  2015. ....
  2016. ./run --eval poweroff
  2017. ....
  2018. because BusyBox' `poweroff` tries to do some fancy stuff like killing init, likely to allow userland to shutdown nicely.
  2019. But this fails when we are `init` itself!
  2020. BusyBox' `poweroff` works more brutally and effectively if you add `-f`:
  2021. ....
  2022. ./run --eval 'poweroff -f'
  2023. ....
  2024. but why not just use our minimal `./linux/poweroff.out` and be done with it?
  2025. ....
  2026. ./run --eval './linux/poweroff.out'
  2027. ....
  2028. Source: link:userland/linux/poweroff.c[]
  2029. This also illustrates how to shutdown the computer from C: https://stackoverflow.com/questions/28812514/how-to-shutdown-linux-using-c-or-qt-without-call-to-system
  2030. ==== sleep_forever.out
  2031. I dare you to guess what this does:
  2032. ....
  2033. ./run --eval './posix/sleep_forever.out'
  2034. ....
  2035. Source: link:userland/posix/sleep_forever.c[]
  2036. This executable is a convenient simple init that does not panic and sleeps instead.
  2037. ==== time_boot.out
  2038. Get a reasonable answer to "how long does boot take in guest time?":
  2039. ....
  2040. ./run --eval-after './linux/time_boot.c'
  2041. ....
  2042. Source: link:userland/linux/time_boot.c[]
  2043. That executable writes to `dmesg` directly through `/dev/kmsg` a message of type:
  2044. ....
  2045. [ 2.188242] /path/to/linux-kernel-module-cheat/userland/linux/time_boot.c
  2046. ....
  2047. which tells us that boot took `2.188242` seconds based on the dmesg timestamp.
  2048. Bibliography: https://stackoverflow.com/questions/12683169/measure-time-taken-for-linux-kernel-from-bootup-to-userpace/46517014#46517014
  2049. [[init-busybox]]
  2050. === Run command at the end of BusyBox init
  2051. Use the `--eval-after` option is for you rely on something that BusyBox' init set up for you like `/etc/fstab`:
  2052. ....
  2053. ./run --eval-after 'echo asdf;ls /proc;ls /sys;echo qwer'
  2054. ....
  2055. After the commands run, you are left on an interactive shell.
  2056. The above command is basically equivalent to:
  2057. ....
  2058. ./run --kernel-cli-after-dash 'lkmc_eval="insmod hello.ko;./linux/poweroff.out;"'
  2059. ....
  2060. where the `lkmc_eval` option gets evaled by our default link:rootfs_overlay/etc/init.d/S98[] startup script.
  2061. Except that `--eval-after` is smarter and uses `base64` encoding.
  2062. Alternatively, you can also add the comamdns to run to a new `init.d` entry to run at the end o the BusyBox init:
  2063. ....
  2064. cp rootfs_overlay/etc/init.d/S98 rootfs_overlay/etc/init.d/S99.gitignore
  2065. vim rootfs_overlay/etc/init.d/S99.gitignore
  2066. ./build-buildroot
  2067. ./run
  2068. ....
  2069. and they will be run automatically before the login prompt.
  2070. Scripts under `/etc/init.d` are run by `/etc/init.d/rcS`, which gets called by the line `::sysinit:/etc/init.d/rcS` in link:rootfs_overlay/etc/inittab[`/etc/inittab`].
  2071. === Path to init
  2072. The init is selected at:
  2073. * initrd or initramfs system: `/init`, a custom one can be set with the `rdinit=` <<kernel-command-line-parameters,kernel command line parameter>>
  2074. * otherwise: default is `/sbin/init`, followed by some other paths, a custom one can be set with `init=`
  2075. More details: https://unix.stackexchange.com/questions/30414/what-can-make-passing-init-path-to-program-to-the-kernel-not-start-program-as-i/430614#430614
  2076. === Init environment
  2077. Documented at https://www.kernel.org/doc/html/v4.14/admin-guide/kernel-parameters.html[]:
  2078. ____
  2079. The kernel parses parameters from the kernel command line up to "-"; if it doesn't recognize a parameter and it doesn't contain a '.', the parameter gets passed to init: parameters with '=' go into init's environment, others are passed as command line arguments to init. Everything after "-" is passed as an argument to init.
  2080. ____
  2081. And you can try it out with:
  2082. ....
  2083. ./run --kernel-cli 'init=/lkmc/linux/init_env_poweroff.out - asdf=qwer zxcv'
  2084. ....
  2085. Output:
  2086. ....
  2087. args:
  2088. /lkmc/linux/init_env_poweroff.out
  2089. -
  2090. zxcv
  2091. env:
  2092. HOME=/
  2093. TERM=linux
  2094. asdf=qwer
  2095. ....
  2096. Source: link:userland/linux/init_env_poweroff.c[].
  2097. ==== init arguments
  2098. The annoying dash `-` gets passed as a parameter to `init`, which makes it impossible to use this method for most non custom executables.
  2099. Arguments with dots that come after `-` are still treated specially (of the form `subsystem.somevalue`) and disappear, from args, e.g.:
  2100. ....
  2101. ./run --kernel-cli 'init=/lkmc/linux/init_env_poweroff.out - /lkmc/linux/poweroff.out'
  2102. ....
  2103. outputs:
  2104. ....
  2105. args
  2106. /lkmc/linux/init_env_poweroff.out
  2107. -
  2108. ab
  2109. ....
  2110. so see how `a.b` is gone.
  2111. The simple workaround is to just create a shell script that does it, e.g. as we've done at: link:rootfs_overlay/lkmc/gem5_exit.sh[].
  2112. ==== init environment env
  2113. Wait, where do `HOME` and `TERM` come from? (greps the kernel). Ah, OK, the kernel sets those by default: https://github.com/torvalds/linux/blob/94710cac0ef4ee177a63b5227664b38c95bbf703/init/main.c#L173
  2114. ....
  2115. const char *envp_init[MAX_INIT_ENVS+2] = { "HOME=/", "TERM=linux", NULL, };
  2116. ....
  2117. ==== BusyBox shell init environment
  2118. On top of the Linux kernel, the BusyBox `/bin/sh` shell will also define other variables.
  2119. We can explore the shenanigans that the shell adds on top of the Linux kernel with:
  2120. ....
  2121. ./run --kernel-cli 'init=/bin/sh'
  2122. ....
  2123. From there we observe that:
  2124. ....
  2125. env
  2126. ....
  2127. gives:
  2128. ....
  2129. SHLVL=1
  2130. HOME=/
  2131. TERM=linux
  2132. PWD=/
  2133. ....
  2134. therefore adding `SHLVL` and `PWD` to the default kernel exported variables.
  2135. Furthermore, to increase confusion, if you list all non-exported shell variables https://askubuntu.com/questions/275965/how-to-list-all-variables-names-and-their-current-values with:
  2136. ....
  2137. set
  2138. ....
  2139. then it shows more variables, notably:
  2140. ....
  2141. PATH='/sbin:/usr/sbin:/bin:/usr/bin'
  2142. ....
  2143. ===== BusyBox shell initrc files
  2144. Login shells source some default files, notably:
  2145. ....
  2146. /etc/profile
  2147. $HOME/.profile
  2148. ....
  2149. In our case, `HOME` is set to `/` presumably by `init` at: https://git.busybox.net/busybox/tree/init/init.c?id=5059653882dbd86e3bbf48389f9f81b0fac8cd0a#n1114
  2150. We provide `/.profile` from link:rootfs_overlay/.profile[], and use the default BusyBox `/etc/profile`.
  2151. The shell knows that it is a login shell if the first character of `argv[0]` is `-`, see also: https://stackoverflow.com/questions/2050961/is-argv0-name-of-executable-an-accepted-standard-or-just-a-common-conventi/42291142#42291142
  2152. When we use just `init=/bin/sh`, the Linux kernel sets `argv[0]` to `/bin/sh`, which does not start with `-`.
  2153. However, if you use `::respawn:-/bin/sh` on inttab described at <<tty>>, BusyBox' init sets `argv[0][0]` to `-`, and so does `getty`. This can be observed with:
  2154. ....
  2155. cat /proc/$$/cmdline
  2156. ....
  2157. where `$$` is the PID of the shell itself: https://stackoverflow.com/questions/21063765/get-pid-in-shell-bash
  2158. Bibliography: https://unix.stackexchange.com/questions/176027/ash-profile-configuration-file
  2159. == initrd
  2160. The kernel can boot from an CPIO file, which is a directory serialization format much like tar: https://superuser.com/questions/343915/tar-vs-cpio-what-is-the-difference
  2161. The bootloader, which for us is provided by QEMU itself, is then configured to put that CPIO into memory, and tell the kernel that it is there.
  2162. This is very similar to the kernel image itself, which already gets put into memory by the QEMU `-kernel` option.
  2163. With this setup, you don't even need to give a root filesystem to the kernel: it just does everything in memory in a ramfs.
  2164. To enable initrd instead of the default ext2 disk image, do:
  2165. ....
  2166. ./build-buildroot --initrd
  2167. ./run --initrd
  2168. ....
  2169. By looking at the QEMU run command generated, you can see that we didn't give the `-drive` option at all:
  2170. ....
  2171. cat "$(./getvar run_dir)/run.sh"
  2172. ....
  2173. Instead, we used the QEMU `-initrd` option to point to the `.cpio` filesystem that Buildroot generated for us.
  2174. Try removing that `-initrd` option to watch the kernel panic without rootfs at the end of boot.
  2175. When using `.cpio`, there can be no <<disk-persistency,filesystem persistency>> across boots, since all file operations happen in memory in a tmpfs:
  2176. ....
  2177. date >f
  2178. poweroff
  2179. cat f
  2180. # can't open 'f': No such file or directory
  2181. ....
  2182. which can be good for automated tests, as it ensures that you are using a pristine unmodified system image every time.
  2183. Not however that we already disable disk persistency by default on ext2 filesystems even without `--initrd`: xref:disk-persistency[xrefstyle=full].
  2184. One downside of this method is that it has to put the entire filesystem into memory, and could lead to a panic:
  2185. ....
  2186. end Kernel panic - not syncing: Out of memory and no killable processes...
  2187. ....
  2188. This can be solved by increasing the memory as explained at <<memory-size>>:
  2189. ....
  2190. ./run --initrd --memory 256M
  2191. ....
  2192. The main ingredients to get initrd working are:
  2193. * `BR2_TARGET_ROOTFS_CPIO=y`: make Buildroot generate `images/rootfs.cpio` in addition to the other images.
  2194. +
  2195. It is also possible to compress that image with other options.
  2196. * `qemu -initrd`: make QEMU put the image into memory and tell the kernel about it.
  2197. * `CONFIG_BLK_DEV_INITRD=y`: Compile the kernel with initrd support, see also: https://unix.stackexchange.com/questions/67462/linux-kernel-is-not-finding-the-initrd-correctly/424496#424496
  2198. +
  2199. Buildroot forces that option when `BR2_TARGET_ROOTFS_CPIO=y` is given
  2200. TODO: how does the bootloader inform the kernel where to find initrd? https://unix.stackexchange.com/questions/89923/how-does-linux-load-the-initrd-image
  2201. === initrd in desktop distros
  2202. Most modern desktop distributions have an initrd in their root disk to do early setup.
  2203. The rationale for this is described at: https://en.wikipedia.org/wiki/Initial_ramdisk
  2204. One obvious use case is having an encrypted root filesystem: you keep the initrd in an unencrypted partition, and then setup decryption from there.
  2205. I think GRUB then knows read common disk formats, and then loads that initrd to memory with a `/boot/grub/grub.cfg` directive of type:
  2206. ....
  2207. initrd /initrd.img-4.4.0-108-generic
  2208. ....
  2209. Related: https://stackoverflow.com/questions/6405083/initrd-and-booting-the-linux-kernel
  2210. === initramfs
  2211. initramfs is just like <<initrd>>, but you also glue the image directly to the kernel image itself using the kernel's build system.
  2212. Try it out with:
  2213. ....
  2214. ./build-buildroot --initramfs
  2215. ./build-linux --initramfs
  2216. ./run --initramfs
  2217. ....
  2218. Notice how we had to rebuild the Linux kernel this time around as well after Buildroot, since in that build we will be gluing the CPIO to the kernel image.
  2219. Now, once again, if we look at the QEMU run command generated, we see all that QEMU needs is the `-kernel` option, no `-drive` not even `-initrd`! Pretty cool:
  2220. ....
  2221. cat "$(./getvar run_dir)/run.sh"
  2222. ....
  2223. It is also interesting to observe how this increases the size of the kernel image if you do a:
  2224. ....
  2225. ls -lh "$(./getvar linux_image)"
  2226. ....
  2227. before and after using initramfs, since the `.cpio` is now glued to the kernel image.
  2228. Don't forget that to stop using initramfs, you must rebuild the kernel without `--initramfs` to get rid of the attached CPIO image:
  2229. ....
  2230. ./build-linux
  2231. ./run
  2232. ....
  2233. Alternatively, consider using <<linux-kernel-build-variants>> if you need to switch between initramfs and non initramfs often:
  2234. ....
  2235. ./build-buildroot --initramfs
  2236. ./build-linux --initramfs --linux-build-id initramfs
  2237. ./run --initramfs --linux-build-id
  2238. ....
  2239. Setting up initramfs is very easy: our scripts just set `CONFIG_INITRAMFS_SOURCE` to point to the CPIO path.
  2240. http://nairobi-embedded.org/initramfs_tutorial.html shows a full manual setup.
  2241. === rootfs
  2242. This is how `/proc/mounts` shows the root filesystem:
  2243. * hard disk: `/dev/root on / type ext2 (rw,relatime,block_validity,barrier,user_xattr)`. That file does not exist however.
  2244. * initrd: `rootfs on / type rootfs (rw)`
  2245. * initramfs: `rootfs on / type rootfs (rw)`
  2246. TODO: understand `/dev/root` better:
  2247. * https://unix.stackexchange.com/questions/295060/why-on-some-linux-systems-does-the-root-filesystem-appear-as-dev-root-instead
  2248. * https://superuser.com/questions/1213770/how-do-you-determine-the-root-device-if-dev-root-is-missing
  2249. ==== /dev/root
  2250. See: xref:rootfs[xrefstyle=full]
  2251. === gem5 initrd
  2252. TODO we were not able to get it working yet: https://stackoverflow.com/questions/49261801/how-to-boot-the-linux-kernel-with-initrd-or-initramfs-with-gem5
  2253. This would require gem5 to load the CPIO into memory, just like QEMU. Grepping `initrd` shows some ARM hits under:
  2254. ....
  2255. src/arch/arm/linux/atag.hh
  2256. ....
  2257. but they are commented out.
  2258. === gem5 initramfs
  2259. This could in theory be easier to make work than initrd since the emulator does not have to do anything special.
  2260. However, it didn't: boot fails at the end because it does not see the initramfs, but rather tries to open our dummy root filesystem, which unsurprisingly does not have a format in a way that the kernel understands:
  2261. ....
  2262. VFS: Cannot open root device "sda" or unknown-block(8,0): error -5
  2263. ....
  2264. We think that this might be because gem5 boots directly `vmlinux`, and not from the final compressed images that contain the attached rootfs such as `bzImage`, which is what QEMU does, see also: xref:vmlinux-vs-bzimage-vs-zimage-vs-image[xrefstyle=full].
  2265. To do this failed test, we automatically pass a dummy disk image as of gem5 7fa4c946386e7207ad5859e8ade0bbfc14000d91 since the scripts don't handle a missing `--disk-image` well, much like is currently done for <<baremetal>>.
  2266. Interestingly, using initramfs significantly slows down the gem5 boot, even though it did not work. For example, we've observed a 4x slowdown of as 17062a2e8b6e7888a14c3506e9415989362c58bf for aarch64. This must be because expanding the large attached CPIO must be expensive. We can clearly see from the kernel logs that the kernel just hangs at a point after the message `PCI: CLS 0 bytes, default 64` for a long time before proceeding further.
  2267. == Device tree
  2268. The device tree is a Linux kernel defined data structure that serves to inform the kernel how the hardware is setup.
  2269. <<platform_device>> contains a minimal runnable example of device tree manipulation.
  2270. Device trees serve to reduce the need for hardware vendors to patch the kernel: they just provide a device tree file instead, which is much simpler.
  2271. x86 does not use it device trees, but many other archs to, notably ARM.
  2272. This is notably because ARM boards:
  2273. * typically don't have discoverable hardware extensions like PCI, but rather just put everything on an SoC with magic register addresses
  2274. * are made by a wide variety of vendors due to ARM's licensing business model, which increases variability
  2275. The Linux kernel itself has several device trees under `./arch/<arch>/boot/dts`, see also: https://stackoverflow.com/questions/21670967/how-to-compile-dts-linux-device-tree-source-files-to-dtb/42839737#42839737
  2276. === DTB files
  2277. Files that contain device trees have the `.dtb` extension when compiled, and `.dts` when in text form.
  2278. You can convert between those formats with:
  2279. ....
  2280. "$(./getvar buildroot_host_dir)"/bin/dtc -I dtb -O dts -o a.dts a.dtb
  2281. "$(./getvar buildroot_host_dir)"/bin/dtc -I dts -O dtb -o a.dtb a.dts
  2282. ....
  2283. Buildroot builds the tool due to `BR2_PACKAGE_HOST_DTC=y`.
  2284. On Ubuntu 18.04, the package is named:
  2285. ....
  2286. sudo apt-get install device-tree-compiler
  2287. ....
  2288. See also: https://stackoverflow.com/questions/14000736/tool-to-visualize-the-device-tree-file-dtb-used-by-the-linux-kernel/39931834#39931834
  2289. Device tree files are provided to the emulator just like the root filesystem and the Linux kernel image.
  2290. In real hardware, those components are also often provided separately. For example, on the Raspberry Pi 2, the SD card must contain two partitions:
  2291. * the first contains all magic files, including the Linux kernel and the device tree
  2292. * the second contains the root filesystem
  2293. See also: https://stackoverflow.com/questions/29837892/how-to-run-a-c-program-with-no-os-on-the-raspberry-pi/40063032#40063032
  2294. === Device tree syntax
  2295. Good format descriptions:
  2296. * https://www.raspberrypi.org/documentation/configuration/device-tree.md
  2297. Minimal example
  2298. ....
  2299. /dts-v1/;
  2300. / {
  2301. a;
  2302. };
  2303. ....
  2304. Check correctness with:
  2305. ....
  2306. dtc a.dts
  2307. ....
  2308. Separate nodes are simply merged by node path, e.g.:
  2309. ....
  2310. /dts-v1/;
  2311. / {
  2312. a;
  2313. };
  2314. / {
  2315. b;
  2316. };
  2317. ....
  2318. then `dtc a.dts` gives:
  2319. ....
  2320. /dts-v1/;
  2321. / {
  2322. a;
  2323. b;
  2324. };
  2325. ....
  2326. === Get device tree from a running kernel
  2327. https://unix.stackexchange.com/questions/265890/is-it-possible-to-get-the-information-for-a-device-tree-using-sys-of-a-running/330926#330926
  2328. This is specially interesting because QEMU and gem5 are capable of generating DTBs that match the selected machine depending on dynamic command line parameters for some types of machines.
  2329. So observing the device tree from the guest allows to easily see what the emulator has generated.
  2330. Compile the `dtc` tool into the root filesystem:
  2331. ....
  2332. ./build-buildroot \
  2333. --arch aarch64 \
  2334. --config 'BR2_PACKAGE_DTC=y' \
  2335. --config 'BR2_PACKAGE_DTC_PROGRAMS=y' \
  2336. ;
  2337. ....
  2338. `-M virt` for example, which we use by default for `aarch64`, boots just fine without the `-dtb` option:
  2339. ....
  2340. ./run --arch aarch64
  2341. ....
  2342. Then, from inside the guest:
  2343. ....
  2344. dtc -I fs -O dts /sys/firmware/devicetree/base
  2345. ....
  2346. contains:
  2347. ....
  2348. cpus {
  2349. #address-cells = <0x1>;
  2350. #size-cells = <0x0>;
  2351. cpu@0 {
  2352. compatible = "arm,cortex-a57";
  2353. device_type = "cpu";
  2354. reg = <0x0>;
  2355. };
  2356. };
  2357. ....
  2358. === Device tree emulator generation
  2359. Since emulators know everything about the hardware, they can automatically generate device trees for us, which is very convenient.
  2360. This is the case for both QEMU and gem5.
  2361. For example, if we increase the <<number-of-cores,number of cores>> to 2:
  2362. ....
  2363. ./run --arch aarch64 --cpus 2
  2364. ....
  2365. QEMU automatically adds a second CPU to the DTB!
  2366. ....
  2367. cpu@0 {
  2368. cpu@1 {
  2369. ....
  2370. The action seems to be happening at: `hw/arm/virt.c`.
  2371. You can dump the DTB QEMU generated with:
  2372. ....
  2373. ./run --arch aarch64 -- -machine dumpdtb=dtb.dtb
  2374. ....
  2375. as mentioned at: https://lists.gnu.org/archive/html/qemu-discuss/2017-02/msg00051.html
  2376. <<gem5-fs_biglittle>> 2a9573f5942b5416fb0570cf5cb6cdecba733392 can also generate its own DTB.
  2377. gem5 can generate DTBs on ARM with `--generate-dtb`. The generated DTB is placed in the <<m5out-directory>> named as `system.dtb`.
  2378. == KVM
  2379. https://en.wikipedia.org/wiki/Kernel-based_Virtual_Machine[KVM] is Linux kernel interface that <<benchmark-linux-kernel-boot,greatly speeds up>> execution of virtual machines.
  2380. You can make QEMU or <<gem5-kvm,gem5>> by passing enabling KVM with:
  2381. ....
  2382. ./run --kvm
  2383. ....
  2384. KVM works by running userland instructions natively directly on the real hardware instead of running a software simulation of those instructions.
  2385. Therefore, KVM only works if you the host architecture is the same as the guest architecture. This means that this will likely only work for x86 guests since almost all development machines are x86 nowadays. Unless you are https://www.youtube.com/watch?v=8ItXpmLsINs[running an ARM desktop for some weird reason] :-)
  2386. We don't enable KVM by default because:
  2387. * it limits visibility, since more things are running natively:
  2388. ** can't use <<gdb,GDB>>
  2389. ** can't do <<tracing,instruction tracing>>
  2390. ** on gem5, you lose <<gem5-run-benchmark,cycle counts>> and therefor any notion of performance
  2391. * QEMU kernel boots are already <<benchmark-linux-kernel-boot,fast enough>> for most purposes without it
  2392. One important use case for KVM is to fast forward gem5 execution, often to skip boot, take a <<gem5-checkpoint>>, and then move on to a more detailed and slow simulation
  2393. === KVM arm
  2394. TODO: we haven't gotten it to work yet, but it should be doable, and this is an outline of how to do it. Just don't expect this to tested very often for now.
  2395. We can test KVM on arm by running this repository inside an Ubuntu arm QEMU VM.
  2396. This produces no speedup of course, since the VM is already slow since it cannot use KVM on the x86 host.
  2397. First, obtain an Ubuntu arm64 virtual machine as explained at: https://askubuntu.com/questions/281763/is-there-any-prebuilt-qemu-ubuntu-image32bit-online/1081171#1081171
  2398. Then, from inside that image:
  2399. ....
  2400. sudo apt-get install git
  2401. git clone https://github.com/cirosantilli/linux-kernel-module-cheat
  2402. cd linux-kernel-module-cheat
  2403. sudo ./setup -y
  2404. ....
  2405. and then proceed exactly as in <<prebuilt>>.
  2406. We don't want to build the full Buildroot image inside the VM as that would be way too slow, thus the recommendation for the prebuilt setup.
  2407. TODO: do the right thing and cross compile QEMU and gem5. gem5's Python parts might be a pain. QEMU should be easy: https://stackoverflow.com/questions/26514252/cross-compile-qemu-for-arm
  2408. === gem5 KVM
  2409. While gem5 does have KVM, as of 2019 its support has not been very good, because debugging it is harder and people haven't focused intensively on it.
  2410. X86 was broken with pending patches: https://www.mail-archive.com/gem5-users@gem5.org/msg15046.html It failed immediately on:
  2411. ....
  2412. panic: KVM: Failed to enter virtualized mode (hw reason: 0x80000021)
  2413. ....
  2414. Bibliography:
  2415. * ARM thread: https://stackoverflow.com/questions/53523087/how-to-run-gem5-on-kvm-on-arm-with-multiple-cores
  2416. == User mode simulation
  2417. Both QEMU and gem5 have an user mode simulation mode in addition to full system simulation that we consider elsewhere in this project.
  2418. In QEMU, it is called just <<qemu-user-mode-getting-started,"user mode">>, and in gem5 it is called <<gem5-syscall-emulation-mode,syscall emulation mode>>.
  2419. In both, the basic idea is the same.
  2420. User mode simulation takes regular userland executables of any arch as input and executes them directly, without booting a kernel.
  2421. Instead of simulating the full system, it translates normal instructions like in full system mode, but magically forwards system calls to the host OS.
  2422. Advantages over full system simulation:
  2423. * the simulation may <<user-mode-vs-full-system-benchmark,run faster>> since you don't have to simulate the Linux kernel and several device models
  2424. * you don't need to build your own kernel or root filesystem, which saves time. You still need a toolchain however, but the pre-packaged ones may work fine.
  2425. Disadvantages:
  2426. * lower guest to host portability:
  2427. ** TODO confirm: host OS == guest OS?
  2428. ** TODO confirm: the host Linux kernel should be newer than the kernel the executable was built for.
  2429. +
  2430. It may still work even if that is not the case, but could fail is a missing system call is reached.
  2431. +
  2432. The target Linux kernel of the executable is a GCC toolchain build-time configuration.
  2433. ** emulator implementers have to keep up with libc changes, some of which break even a C hello world due setup code executed before main.
  2434. +
  2435. See also: xref:user-mode-simulation-with-glibc[xrefstyle=full]
  2436. * cannot be used to test the Linux kernel or any devices, and results are less representative of a real system since we are faking more
  2437. === QEMU user mode getting started
  2438. Let's run link:userland/c/command_line_arguments.c[] built with the Buildroot toolchain on QEMU user mode:
  2439. ....
  2440. ./build user-mode-qemu
  2441. ./run \
  2442. --userland userland/c/command_line_arguments.c \
  2443. --userland-args='asdf "qw er"' \
  2444. ;
  2445. ....
  2446. Output:
  2447. ....
  2448. /path/to/linux-kernel-module-cheat/out/userland/default/x86_64/c/print_argv.out
  2449. asdf
  2450. qw er
  2451. ....
  2452. `./run --userland` path resolution is analogous to <<baremetal-setup-getting-started,that of `./run --baremetal`>>.
  2453. `./build user-mode-qemu` first builds Buildroot, and then runs `./build-userland`, which is further documented at: xref:userland-setup[xrefstyle=full]. It also builds QEMU. If you ahve already done a <<qemu-buildroot-setup>> previously, this will be very fast.
  2454. If you modify the userland programs, rebuild simply with:
  2455. ....
  2456. ./build-userland
  2457. ....
  2458. ==== User mode GDB
  2459. It's nice when <<gdb,the obvious>> just works, right?
  2460. ....
  2461. ./run \
  2462. --arch aarch64 \
  2463. --gdb-wait \
  2464. --userland userland/c/command_line_arguments.c \
  2465. --userland-args 'asdf "qw er"' \
  2466. ;
  2467. ....
  2468. and on another shell:
  2469. ....
  2470. ./run-gdb \
  2471. --arch aarch64 \
  2472. --userland userland/c/command_line_arguments.c \
  2473. main \
  2474. ;
  2475. ....
  2476. Or alternatively, if you are using <<tmux>>, do everything in one go with:
  2477. ....
  2478. ./run \
  2479. --arch aarch64 \
  2480. --gdb \
  2481. --userland userland/c/command_line_arguments.c \
  2482. --userland-args 'asdf "qw er"' \
  2483. ;
  2484. ....
  2485. To stop at the very first instruction of a freestanding program, just use `--no-continue`. A good example of this is shown at: xref:freestanding-programs[xrefstyle=full].
  2486. === User mode tests
  2487. Automatically run all userland tests that can be run in user mode simulation, and check that they exit with status 0:
  2488. ....
  2489. ./build --all-archs test-executables-userland
  2490. ./test-executables --all-archs --all-emulators
  2491. ....
  2492. Or just for QEMU:
  2493. ....
  2494. ./build --all-archs test-executables-userland-qemu
  2495. ./test-executables --all-archs --emulator qemu
  2496. ....
  2497. Source: link:test-executables[]
  2498. This script skips a manually configured list of tests, notably:
  2499. * tests that depend on a full running kernel and cannot be run in user mode simulation, e.g. those that rely on kernel modules
  2500. * tests that require user interaction
  2501. * tests that take perceptible ammounts of time
  2502. * known bugs we didn't have time to fix ;-)
  2503. Tests under link:userland/libs/[] depend on certain libraries being available on the target, e.g. <<blas>> for link:userland/libs/openblas[]. They are not run by default, but can be enabled with `--package` and `--package-all`.
  2504. The gem5 tests require building statically with build id `static`, see also: xref:gem5-syscall-emulation-mode[xrefstyle=full]. TODO automate this better.
  2505. See: xref:test-this-repo[xrefstyle=full] for more useful testing tips.
  2506. === User mode Buildroot executables
  2507. If you followed <<qemu-buildroot-setup>>, you can now run the executables created by Buildroot directly as:
  2508. ....
  2509. ./run \
  2510. --userland "$(./getvar buildroot_target_dir)/bin/echo" \
  2511. --userland-args='asdf' \
  2512. ;
  2513. ....
  2514. To easily explore the userland executable environment interactively, you can do:
  2515. ....
  2516. ./run \
  2517. --arch aarch64 \
  2518. --userland "$(./getvar --arch aarch64 buildroot_target_dir)/bin/sh" \
  2519. --terminal \
  2520. ;
  2521. ....
  2522. or:
  2523. ....
  2524. ./run \
  2525. --arch aarch64 \
  2526. --userland "$(./getvar --arch aarch64 buildroot_target_dir)/bin/sh" \
  2527. --userland-args='-c "uname -a && pwd"' \
  2528. ;
  2529. ....
  2530. Here is an interesting examples of this: xref:linux-test-project[xrefstyle=full]
  2531. === User mode simulation with glibc
  2532. At 125d14805f769104f93c510bedaa685a52ec025d we <<libc-choice,moved Buildroot from uClibc to glibc>>, and caused some user mode pain, which we document here.
  2533. ==== FATAL: kernel too old
  2534. glibc has a check for kernel version, likely obtained from the `uname` syscall, and if the kernel is not new enough, it quits.
  2535. Both gem5 and QEMU however allow setting the reported `uname` version from the command line, which we do to always match our toolchain.
  2536. QEMU by default copies the host `uname` value, but we always override it in our scripts.
  2537. Determining the right number to use for the kernel version is of course highly non-trivial and would require an extensive userland test suite, which most emulator don't have.
  2538. ....
  2539. ./run --arch aarch64 --kernel-version 4.18 --userland userland/posix/uname.c
  2540. ....
  2541. Source: link:userland/posix/uname.c[].
  2542. The QEMU source that does this is at: https://github.com/qemu/qemu/blob/v3.1.0/linux-user/syscall.c#L8931
  2543. Bibliography:
  2544. * https://stackoverflow.com/questions/48959349/how-to-solve-fatal-kernel-too-old-when-running-gem5-in-syscall-emulation-se-m
  2545. * https://stackoverflow.com/questions/53085048/how-to-compile-and-run-an-executable-in-gem5-syscall-emulation-mode-with-se-py/53085049#53085049
  2546. * https://gem5-review.googlesource.com/c/public/gem5/+/15855
  2547. The ID is just hardcoded on the source:
  2548. ==== stack smashing detected
  2549. For some reason QEMU / glibc x86_64 picks up the host libc, which breaks things.
  2550. Other archs work as they different host libc is skipped. <<user-mode-static-executables>> also work.
  2551. We have worked around this with with https://bugs.launchpad.net/qemu/+bug/1701798/comments/12 from the thread: https://bugs.launchpad.net/qemu/+bug/1701798 by creating the file: link:rootfs_overlay/etc/ld.so.cache[] which is a symlink to a file that cannot exist: `/dev/null/nonexistent`.
  2552. Reproduction:
  2553. ....
  2554. rm -f "$(./getvar buildroot_target_dir)/etc/ld.so.cache"
  2555. ./run --userland userland/c/hello.c
  2556. ./run --userland userland/c/hello.c --qemu-which host
  2557. ....
  2558. Outcome:
  2559. ....
  2560. *** stack smashing detected ***: <unknown> terminated
  2561. qemu: uncaught target signal 6 (Aborted) - core dumped
  2562. ....
  2563. To get things working again, restore `ld.so.cache` with:
  2564. ....
  2565. ./build-buildroot
  2566. ....
  2567. I've also tested on an Ubuntu 16.04 guest and the failure is different one:
  2568. ....
  2569. qemu: uncaught target signal 4 (Illegal instruction) - core dumped
  2570. ....
  2571. A non-QEMU-specific example of stack smashing is shown at: https://stackoverflow.com/questions/1345670/stack-smashing-detected/51897264#51897264
  2572. Tested at: 2e32389ebf1bedd89c682aa7b8fe42c3c0cf96e5 + 1.
  2573. === User mode static executables
  2574. Example:
  2575. ....
  2576. ./build-userland \
  2577. --arch aarch64 \
  2578. --static \
  2579. ;
  2580. ./run \
  2581. --arch aarch64 \
  2582. --static \
  2583. --userland userland/c/command_line_arguments.c \
  2584. --userland-args 'asdf "qw er"' \
  2585. ;
  2586. ....
  2587. Running dynamically linked executables in QEMU requires pointing it to the root filesystem with the `-L` option so that it can find the dynamic linker and shared libraries.
  2588. We pass `-L` by default, so everything just works.
  2589. However, in case something goes wrong, you can also try statically linked executables, since this mechanism tends to be a bit more stable, for example:
  2590. * gem5 user mode currently only supports static executables as mentioned at: xref:gem5-syscall-emulation-mode[xrefstyle=full]
  2591. * QEMU x86_64 guest on x86_64 host was failing with <<stack-smashing-detected>>, but we found a workaround
  2592. Running statically linked executables sometimes makes things break:
  2593. * <<user-mode-static-executables-with-dynamic-libraries>>
  2594. * TODO understand why:
  2595. +
  2596. ....
  2597. ./run --static --userland userland/c/file_write_read.c
  2598. ....
  2599. fails our assertion that the data was read back correctly:
  2600. +
  2601. ....
  2602. Assertion `strcmp(data, output) == 0' faile
  2603. ....
  2604. ==== User mode static executables with dynamic libraries
  2605. One limitation of static executables is that Buildroot mostly only builds dynamic versions of libraries (the libc is an exception).
  2606. So programs that rely on those libraries might not compile as GCC can't find the `.a` version of the library.
  2607. For example, if we try to build <<blas>> statically:
  2608. ....
  2609. ./build-userland --package openblas --static -- userland/libs/openblas/hello.c
  2610. ....
  2611. it fails with:
  2612. ....
  2613. ld: cannot find -lopenblas
  2614. ....
  2615. `g++` and pthreads also causes issues: https://stackoverflow.com/questions/35116327/when-g-static-link-pthread-cause-segmentation-fault-why
  2616. As a consequence, the following fails:
  2617. ....
  2618. ./run --userland userland/cpp/atomic.cpp --static
  2619. ....
  2620. with error:
  2621. ....
  2622. qemu-x86_64: /path/to/linux-kernel-module-cheat/submodules/qemu/accel/tcg/cpu-exec.c:700: cpu_exec: Assertion `!have_mmap_lock()' failed.
  2623. qemu-x86_64: /path/to/linux-kernel-module-cheat/submodules/qemu/accel/tcg/cpu-exec.c:700: cpu_exec: Assertion `!have_mmap_lock()' failed.
  2624. ....
  2625. and if we manually build and run natively on host it segfaults.
  2626. If we hack the compilation command to do instead:
  2627. ....
  2628. -pthread -Wl,--whole-archive -lpthread -Wl,--no-whole-archive
  2629. ....
  2630. then it works. We should automate that at some point.
  2631. === gem5 syscall emulation mode
  2632. Less robust than QEMU's, but still usable:
  2633. * https://stackoverflow.com/questions/48986597/when-should-you-use-full-system-fs-vs-syscall-emulation-se-with-userland-program
  2634. There are much more unimplemented syscalls in gem5 than in QEMU. Many of those are trivial to implement however.
  2635. As of 185c2730cc78d5adda683d76c0e3b35e7cb534f0, dynamically linked executables only work on x86, and they can only use the host libraries, which is ugly:
  2636. * https://stackoverflow.com/questions/50542222/how-to-run-a-dynamically-linked-executable-syscall-emulation-mode-se-py-in-gem5
  2637. * https://www.mail-archive.com/gem5-users@gem5.org/msg15585.html
  2638. If you try dynamically linked executables on ARM, they fail with:
  2639. ....
  2640. fatal: Unable to open dynamic executable's interpreter.
  2641. ....
  2642. So let's just play with some static ones:
  2643. ....
  2644. ./build-userland \
  2645. --arch aarch64 \
  2646. --static \
  2647. ;
  2648. ./run \
  2649. --arch aarch64 \
  2650. --emulator gem5 \
  2651. --userland userland/c/command_line_arguments.c \
  2652. --userland-args 'asdf "qw er"' \
  2653. ;
  2654. ....
  2655. TODO: how to escape spaces on the command line arguments?
  2656. <<user-mode-gdb,GDB step debug>> also works normally on gem5:
  2657. ....
  2658. ./run \
  2659. --arch aarch64 \
  2660. --emulator gem5 \
  2661. --gdb-wait \
  2662. --static \
  2663. --userland userland/c/command_line_arguments.c \
  2664. --userland-args 'asdf "qw er"' \
  2665. ;
  2666. ./run-gdb \
  2667. --arch aarch64 \
  2668. --emulator gem5 \
  2669. --static \
  2670. --userland userland/c/command_line_arguments.c \
  2671. main \
  2672. ;
  2673. ....
  2674. ==== gem5 syscall emulation exit status
  2675. As of gem5 7fa4c946386e7207ad5859e8ade0bbfc14000d91, the crappy `se.py` script does not forward the exit status of syscall emulation mode, you can test it with:
  2676. ....
  2677. ./run --dry-run --emulator gem5 --static --userland userland/c/false.c
  2678. ....
  2679. Source: link:userland/c/false.c[].
  2680. Then manually run the generated gem5 CLI, and do:
  2681. ....
  2682. echo $?
  2683. ....
  2684. and the output is always `0`.
  2685. Instead, it just outputs a message to stdout just like for <<m5-fail>>:
  2686. ....
  2687. Simulated exit code not 0! Exit code is 1
  2688. ....
  2689. which we parse in link:run[] and then exit with the correct result ourselves...
  2690. Related thread: https://stackoverflow.com/questions/56032347/is-there-a-way-to-identify-if-gem5-run-got-over-successfully
  2691. ==== gem5 syscall emulation mode program stdin
  2692. gem5 shows its own stdout to terminal, and does not allow you to type stdin to programs.
  2693. Instead, you must pass stdin non-interactively with the through a file with the `--se.py --input` option, e.g.:
  2694. ....
  2695. printf a > f
  2696. ./run --emulator gem5 --userland userland/c/getchar.c --static -- --input f
  2697. ....
  2698. leads to gem5 output:
  2699. ....
  2700. enter a character: you entered: a
  2701. ....
  2702. Source: link:userland/c/getchar.c[]
  2703. ==== gem5 syscall emulation mode syscall tracing
  2704. Since gem5 has to implement syscalls itself in syscall emulation mode, it can of course clearly see which syscalls are being made, and we can log them for debug purposes with <<gem5-tracing>>, e.g.:
  2705. ....
  2706. ./run \
  2707. --emulator gem5 \
  2708. --static userland/arch/x86_64/freestanding/linux/hello.S \
  2709. --userland \
  2710. --trace-stdout \
  2711. --trace ExecAll,SyscallBase,SyscallVerbose \
  2712. ;
  2713. ....
  2714. the trace as of f2eeceb1cde13a5ff740727526bf916b356cee38 + 1 contains:
  2715. ....
  2716. 0: system.cpu A0 T0 : @asm_main_after_prologue : mov rdi, 0x1
  2717. 0: system.cpu A0 T0 : @asm_main_after_prologue.0 : MOV_R_I : limm rax, 0x1 : IntAlu : D=0x0000000000000001 flags=(IsInteger|IsMicroop|IsLastMicroop|IsFirstMicroop)
  2718. 1000: system.cpu A0 T0 : @asm_main_after_prologue+7 : mov rdi, 0x1
  2719. 1000: system.cpu A0 T0 : @asm_main_after_prologue+7.0 : MOV_R_I : limm rdi, 0x1 : IntAlu : D=0x0000000000000001 flags=(IsInteger|IsMicroop|IsLastMicroop|IsFirstMicroop)
  2720. 2000: system.cpu A0 T0 : @asm_main_after_prologue+14 : lea rsi, DS:[rip + 0x19]
  2721. 2000: system.cpu A0 T0 : @asm_main_after_prologue+14.0 : LEA_R_P : rdip t7, %ctrl153, : IntAlu : D=0x000000000040008d flags=(IsInteger|IsMicroop|IsDelayedCommit|IsFirstMicroop)
  2722. 2500: system.cpu A0 T0 : @asm_main_after_prologue+14.1 : LEA_R_P : lea rsi, DS:[t7 + 0x19] : IntAlu : D=0x00000000004000a6 flags=(IsInteger|IsMicroop|IsLastMicroop)
  2723. 3500: system.cpu A0 T0 : @asm_main_after_prologue+21 : mov rdi, 0x6
  2724. 3500: system.cpu A0 T0 : @asm_main_after_prologue+21.0 : MOV_R_I : limm rdx, 0x6 : IntAlu : D=0x0000000000000006 flags=(IsInteger|IsMicroop|IsLastMicroop|IsFirstMicroop)
  2725. 4000: system.cpu: T0 : syscall write called w/arguments 1, 4194470, 6, 0, 0, 0
  2726. hello
  2727. 4000: system.cpu: T0 : syscall write returns 6
  2728. 4000: system.cpu A0 T0 : @asm_main_after_prologue+28 : syscall eax : IntAlu : flags=(IsInteger|IsSerializeAfter|IsNonSpeculative|IsSyscall)
  2729. 5000: system.cpu A0 T0 : @asm_main_after_prologue+30 : mov rdi, 0x3c
  2730. 5000: system.cpu A0 T0 : @asm_main_after_prologue+30.0 : MOV_R_I : limm rax, 0x3c : IntAlu : D=0x000000000000003c flags=(IsInteger|IsMicroop|IsLastMicroop|IsFirstMicroop)
  2731. 6000: system.cpu A0 T0 : @asm_main_after_prologue+37 : mov rdi, 0
  2732. 6000: system.cpu A0 T0 : @asm_main_after_prologue+37.0 : MOV_R_I : limm rdi, 0 : IntAlu : D=0x0000000000000000 flags=(IsInteger|IsMicroop|IsLastMicroop|IsFirstMicroop)
  2733. 6500: system.cpu: T0 : syscall exit called w/arguments 0, 4194470, 6, 0, 0, 0
  2734. 6500: system.cpu: T0 : syscall exit returns 0
  2735. 6500: system.cpu A0 T0 : @asm_main_after_prologue+44 : syscall eax : IntAlu : flags=(IsInteger|IsSerializeAfter|IsNonSpeculative|IsSyscall)
  2736. ....
  2737. so we see that two syscall lines were added for each syscall, showing the syscall inputs and exit status, just like a mini `strace`!
  2738. === QEMU user mode quirks
  2739. ==== QEMU user mode does not show stdout immediately
  2740. At 8d8307ac0710164701f6e14c99a69ee172ccbb70 + 1, I noticed that if you run link:userland/posix/count.c[]:
  2741. ....
  2742. ./run --userland userland/posix/count_to.c --userland-args 3
  2743. ....
  2744. it first waits for 3 seconds, then the program exits, and then it dumps all the stdout at once, instead of counting once every second as expected.
  2745. The same can be reproduced by copying the raw QEMU command and piping it through `tee`, so I don't think it is a bug in our setup:
  2746. ....
  2747. /path/to/linux-kernel-module-cheat/out/qemu/default/x86_64-linux-user/qemu-x86_64 \
  2748. -L /path/to/linux-kernel-module-cheat/out/buildroot/build/default/x86_64/target \
  2749. /path/to/linux-kernel-module-cheat/out/userland/default/x86_64/posix/count.out \
  2750. 3 \
  2751. | tee
  2752. ....
  2753. TODO: investigate further and then possibly post on QEMU mailing list.
  2754. ===== QEMU user mode does not show errors
  2755. Similarly to <<qemu-user-mode-does-not-show-stdout-immediately>>, QEMU error messages do not show at all through pipes.
  2756. In particular, it does not say anything if you pass it a non-existing executable:
  2757. ....
  2758. qemu-x86_64 asdf | cat
  2759. ....
  2760. So we just check ourselves manually
  2761. == Kernel module utilities
  2762. === insmod
  2763. https://git.busybox.net/busybox/tree/modutils/insmod.c?h=1_29_3[Provided by BusyBox]:
  2764. ....
  2765. ./run --eval-after 'insmod hello.ko'
  2766. ....
  2767. === myinsmod
  2768. If you are feeling raw, you can insert and remove modules with our own minimal module inserter and remover!
  2769. ....
  2770. # init_module
  2771. ./linux/myinsmod.out hello.ko
  2772. # finit_module
  2773. ./linux/myinsmod.out hello.ko "" 1
  2774. ./linux/myrmmod.out hello
  2775. ....
  2776. which teaches you how it is done from C code.
  2777. Source:
  2778. * link:userland/linux/myinsmod.c[]
  2779. * link:userland/linux/myrmmod.c[]
  2780. The Linux kernel offers two system calls for module insertion:
  2781. * `init_module`
  2782. * `finit_module`
  2783. and:
  2784. ....
  2785. man init_module
  2786. ....
  2787. documents that:
  2788. ____
  2789. The finit_module() system call is like init_module(), but reads the module to be loaded from the file descriptor fd. It is useful when the authenticity of a kernel module can be determined from its location in the filesystem; in cases where that is possible, the overhead of using cryptographically signed modules to determine the authenticity of a module can be avoided. The param_values argument is as for init_module().
  2790. ____
  2791. `finit` is newer and was added only in v3.8. More rationale: https://lwn.net/Articles/519010/
  2792. Bibliography: https://stackoverflow.com/questions/5947286/how-to-load-linux-kernel-modules-from-c-code
  2793. === modprobe
  2794. Implemented as a BusyBox applet by default: https://git.busybox.net/busybox/tree/modutils/modprobe.c?h=1_29_stable
  2795. `modprobe` searches for modules installed under:
  2796. ....
  2797. ls /lib/modules/<kernel_version>
  2798. ....
  2799. and specified in the `modules.order` file.
  2800. This is the default install path for `CONFIG_SOME_MOD=m` modules built with `make modules_install` in the Linux kernel tree, with root path given by `INSTALL_MOD_PATH`, and therefore canonical in that sense.
  2801. Currently, there are only two kinds of kernel modules that you can try out with `modprobe`:
  2802. * modules built with Buildroot, see: xref:kernel_modules-buildroot-package[xrefstyle=full]
  2803. * modules built from the kernel tree itself, see: xref:dummy-irq[xrefstyle=full]
  2804. We are not installing out custom `./build-modules` modules there, because:
  2805. * we don't know the right way. Why is there no `install` or `install_modules` target for kernel modules?
  2806. +
  2807. This can of course be solved by running Buildroot in verbose mode, and copying whatever it is doing, initial exploration at: https://stackoverflow.com/questions/22783793/how-to-install-kernel-modules-from-source-code-error-while-make-process/53169078#53169078
  2808. * we would have to think how to not have to include the kernel modules twice in the root filesystem, but still have <<9p>> working for fast development as described at: xref:your-first-kernel-module-hack[xrefstyle=full]
  2809. === kmod
  2810. The more "reference" kernel.org implementation of `lsmod`, `insmod`, `rmmod`, etc.: https://git.kernel.org/pub/scm/utils/kernel/kmod/kmod.git
  2811. Default implementation on desktop distros such as Ubuntu 16.04, where e.g.:
  2812. ....
  2813. ls -l /bin/lsmod
  2814. ....
  2815. gives:
  2816. ....
  2817. lrwxrwxrwx 1 root root 4 Jul 25 15:35 /bin/lsmod -> kmod
  2818. ....
  2819. and:
  2820. ....
  2821. dpkg -l | grep -Ei
  2822. ....
  2823. contains:
  2824. ....
  2825. ii kmod 22-1ubuntu5 amd64 tools for managing Linux kernel modules
  2826. ....
  2827. BusyBox also implements its own version of those executables, see e.g. <<modprobe>>. Here we will only describe features that differ from kmod to the BusyBox implementation.
  2828. ==== module-init-tools
  2829. Name of a predecessor set of tools.
  2830. ==== kmod modprobe
  2831. kmod's `modprobe` can also load modules under different names to avoid conflicts, e.g.:
  2832. ....
  2833. sudo modprobe vmhgfs -o vm_hgfs
  2834. ....
  2835. == Filesystems
  2836. === OverlayFS
  2837. https://en.wikipedia.org/wiki/OverlayFS[OverlayFS] is a filesystem merged in the Linux kernel in 3.18.
  2838. As the name suggests, OverlayFS allows you to merge multiple directories into one. The following minimal runnable examples should give you an intuition on how it works:
  2839. * https://askubuntu.com/questions/109413/how-do-i-use-overlayfs/1075564#1075564
  2840. * https://stackoverflow.com/questions/31044982/how-to-use-multiple-lower-layers-in-overlayfs/52792397#52792397
  2841. We are very interested in this filesystem because we are looking for a way to make host cross compiled executables appear on the guest root `/` without reboot.
  2842. This would have several advantages:
  2843. * makes it faster to test modified guest programs
  2844. ** not rebooting is fundamental for <<gem5>>, where the reboot is very costly.
  2845. ** no need to regenerate the root filesystem at all and reboot
  2846. ** overcomes the `check_bin_arch` problem as shown at: xref:rpath[xrefstyle=full]
  2847. * we could keep the base root filesystem very small, which implies:
  2848. ** less host disk usage, no need to copy the entire `./getvar out_rootfs_overlay_dir` to the image again
  2849. ** no need to worry about <<br2_target_rootfs_ext2_size>>
  2850. We can already make host files appear on the guest with <<9p>>, but they appear on a subdirectory instead of the root.
  2851. If they would appear on the root instead, that would be even more awesome, because you would just use the exact same paths relative to the root transparently.
  2852. For example, we wouldn't have to mess around with variables such as `PATH` and `LD_LIBRARY_PATH`.
  2853. The idea is to:
  2854. * 9P mount our overlay directory `./getvar out_rootfs_overlay_dir` on the guest, which we already do at `/mnt/9p/out_rootfs_overlay`
  2855. * then create an overlay with that directory and the root, and `chroot` into it.
  2856. +
  2857. I was unable to mount directly to `/` avoid the `chroot`:
  2858. ** https://stackoverflow.com/questions/41119656/how-can-i-overlayfs-the-root-filesystem-on-linux
  2859. ** https://unix.stackexchange.com/questions/316018/how-to-use-overlayfs-to-protect-the-root-filesystem
  2860. ** https://unix.stackexchange.com/questions/420646/mount-root-as-overlayfs
  2861. We already have a prototype of this running from `fstab` on guest at `/mnt/overlay`, but it has the following shortcomings:
  2862. * changes to underlying filesystems are not visible on the overlay unless you remount with `mount -r remount /mnt/overlay`, as mentioned https://github.com/torvalds/linux/blob/v4.18/Documentation/filesystems/overlayfs.txt#L332[on the kernel docs]:
  2863. +
  2864. ....
  2865. Changes to the underlying filesystems while part of a mounted overlay
  2866. filesystem are not allowed. If the underlying filesystem is changed,
  2867. the behavior of the overlay is undefined, though it will not result in
  2868. a crash or deadlock.
  2869. ....
  2870. +
  2871. This makes everything very inconvenient if you are inside `chroot` action. You would have to leave `chroot`, remount, then come back.
  2872. * the overlay does not contain sub-filesystems, e.g. `/proc`. We would have to re-mount them. But should be doable with some automation.
  2873. Even more awesome than `chroot` would be to `pivot_root`, but I couldn't get that working either:
  2874. * https://stackoverflow.com/questions/28015688/pivot-root-device-or-resource-busy
  2875. * https://unix.stackexchange.com/questions/179788/pivot-root-device-or-resource-busy
  2876. === Secondary disk
  2877. A simpler and possibly less overhead alternative to <<9P>> would be to generate a secondary disk image with the benchmark you want to rebuild.
  2878. Then you can `umount` and re-mount on guest without reboot.
  2879. We don't support this yet, but it should not be too hard to hack it up, maybe by hooking into link:rootfs-post-build-script[].
  2880. This was not possible from gem5 `fs.py` as of 60600f09c25255b3c8f72da7fb49100e2682093a: https://stackoverflow.com/questions/50862906/how-to-attach-multiple-disk-images-in-a-simulation-with-gem5-fs-py/51037661#51037661
  2881. == Graphics
  2882. Both QEMU and gem5 are capable of outputting graphics to the screen, and taking mouse and keyboard input.
  2883. https://unix.stackexchange.com/questions/307390/what-is-the-difference-between-ttys0-ttyusb0-and-ttyama0-in-linux
  2884. === QEMU text mode
  2885. Text mode is the default mode for QEMU.
  2886. The opposite of text mode is <<qemu-graphic-mode>>
  2887. In text mode, we just show the serial console directly on the current terminal, without opening a QEMU GUI window.
  2888. You cannot see any graphics from text mode, but text operations in this mode, including:
  2889. * scrolling up: xref:scroll-up-in-graphic-mode[xrefstyle=full]
  2890. * copy paste to and from the terminal
  2891. making this a good default, unless you really need to use with graphics.
  2892. Text mode works by sending the terminal character by character to a serial device.
  2893. This is different from a display screen, where each character is a bunch of pixels, and it would be much harder to convert that into actual terminal text.
  2894. For more details, see:
  2895. * https://unix.stackexchange.com/questions/307390/what-is-the-difference-between-ttys0-ttyusb0-and-ttyama0-in-linux
  2896. * <<tty>>
  2897. Note that you can still see an image even in text mode with the VNC:
  2898. ....
  2899. ./run --vnc
  2900. ....
  2901. and on another terminal:
  2902. ....
  2903. ./vnc
  2904. ....
  2905. but there is not terminal on the VNC window, just the <<config_logo>> penguin.
  2906. ==== Quit QEMU from text mode
  2907. https://superuser.com/questions/1087859/how-to-quit-the-qemu-monitor-when-not-using-a-gui
  2908. However, our QEMU setup captures Ctrl + C and other common signals and sends them to the guest, which makes it hard to quit QEMU for the first time since there is no GUI either.
  2909. The simplest way to quit QEMU, is to do:
  2910. ....
  2911. Ctrl-A X
  2912. ....
  2913. Alternative methods include:
  2914. * `quit` command on the <<qemu-monitor>>
  2915. * `pkill qemu`
  2916. === QEMU graphic mode
  2917. Enable graphic mode with:
  2918. ....
  2919. ./run --graphic
  2920. ....
  2921. Outcome: you see a penguin due to <<config_logo>>.
  2922. For a more exciting GUI experience, see: xref:x11[xrefstyle=full]
  2923. Text mode is the default due to the following considerable advantages:
  2924. * copy and paste commands and stdout output to / from host
  2925. * get full panic traces when you start making the kernel crash :-) See also: https://unix.stackexchange.com/questions/208260/how-to-scroll-up-after-a-kernel-panic
  2926. * have a large scroll buffer, and be able to search it, e.g. by using tmux on host
  2927. * one less window floating around to think about in addition to your shell :-)
  2928. * graphics mode has only been properly tested on `x86_64`.
  2929. Text mode has the following limitations over graphics mode:
  2930. * you can't see graphics such as those produced by <<x11>>
  2931. * very early kernel messages such as `early console in extract_kernel` only show on the GUI, since at such early stages, not even the serial has been setup.
  2932. `x86_64` has a VGA device enabled by default, as can be seen as:
  2933. ....
  2934. ./qemu-monitor info qtree
  2935. ....
  2936. and the Linux kernel picks it up through the https://en.wikipedia.org/wiki/Linux_framebuffer[fbdev] graphics system as can be seen from:
  2937. ....
  2938. cat /dev/urandom > /dev/fb0
  2939. ....
  2940. flooding the screen with colors. See also: https://superuser.com/questions/223094/how-do-i-know-if-i-have-kms-enabled
  2941. ==== Scroll up in graphic mode
  2942. Scroll up in <<qemu-graphic-mode>>:
  2943. ....
  2944. Shift-PgUp
  2945. ....
  2946. but I never managed to increase that buffer:
  2947. * https://askubuntu.com/questions/709697/how-to-increase-scrollback-lines-in-ubuntu14-04-2-server-edition
  2948. * https://unix.stackexchange.com/questions/346018/how-to-increase-the-scrollback-buffer-size-for-tty
  2949. The superior alternative is to use text mode and GNU screen or <<tmux>>.
  2950. ==== QEMU Graphic mode arm
  2951. ===== QEMU graphic mode arm terminal
  2952. TODO: on arm, we see the penguin and some boot messages, but don't get a shell at then end:
  2953. ....
  2954. ./run --arch aarch64 --graphic
  2955. ....
  2956. I think it does not work because the graphic window is <<drm>> only, i.e.:
  2957. ....
  2958. cat /dev/urandom > /dev/fb0
  2959. ....
  2960. fails with:
  2961. ....
  2962. cat: write error: No space left on device
  2963. ....
  2964. and has no effect, and the Linux kernel does not appear to have a built-in DRM console as it does for fbdev with <<fbcon,fbcon>>.
  2965. There is however one out-of-tree implementation: <<kmscon>>.
  2966. ===== QEMU graphic mode arm terminal implementation
  2967. `arm` and `aarch64` rely on the QEMU CLI option:
  2968. ....
  2969. -device virtio-gpu-pci
  2970. ....
  2971. and the kernel config options:
  2972. ....
  2973. CONFIG_DRM=y
  2974. CONFIG_DRM_VIRTIO_GPU=y
  2975. ....
  2976. Unlike x86, `arm` and `aarch64` don't have a display device attached by default, thus the need for `virtio-gpu-pci`.
  2977. See also https://wiki.qemu.org/Documentation/Platforms/ARM (recently edited and corrected by yours truly... :-)).
  2978. ===== QEMU graphic mode arm VGA
  2979. TODO: how to use VGA on ARM? https://stackoverflow.com/questions/20811203/how-can-i-output-to-vga-through-qemu-arm Tried:
  2980. ....
  2981. -device VGA
  2982. ....
  2983. But https://github.com/qemu/qemu/blob/v2.12.0/docs/config/mach-virt-graphical.cfg#L264 says:
  2984. ....
  2985. # We use virtio-gpu because the legacy VGA framebuffer is
  2986. # very troublesome on aarch64, and virtio-gpu is the only
  2987. # video device that doesn't implement it.
  2988. ....
  2989. so maybe it is not possible?
  2990. === gem5 graphic mode
  2991. gem5 does not have a "text mode", since it cannot redirect the Linux terminal to same host terminal where the executable is running: you are always forced to connect to the terminal with `gem-shell`.
  2992. TODO could not get it working on `x86_64`, only ARM.
  2993. Overview: https://stackoverflow.com/questions/50364863/how-to-get-graphical-gui-output-and-user-touch-keyboard-mouse-input-in-a-ful/50364864#50364864
  2994. More concretely, first build the kernel with the <<gem5-arm-linux-kernel-patches>>, and then run:
  2995. ....
  2996. ./build-linux \
  2997. --arch arm \
  2998. --custom-config-file-gem5 \
  2999. --linux-build-id gem5-v4.15 \
  3000. ;
  3001. ./run --arch arm --emulator gem5 --linux-build-id gem5-v4.15
  3002. ....
  3003. and then on another shell:
  3004. ....
  3005. vinagre localhost:5900
  3006. ....
  3007. The <<config_logo>> penguin only appears after several seconds, together with kernel messages of type:
  3008. ....
  3009. [ 0.152755] [drm] found ARM HDLCD version r0p0
  3010. [ 0.152790] hdlcd 2b000000.hdlcd: bound virt-encoder (ops 0x80935f94)
  3011. [ 0.152795] [drm] Supports vblank timestamp caching Rev 2 (21.10.2013).
  3012. [ 0.152799] [drm] No driver support for vblank timestamp query.
  3013. [ 0.215179] Console: switching to colour frame buffer device 240x67
  3014. [ 0.230389] hdlcd 2b000000.hdlcd: fb0: frame buffer device
  3015. [ 0.230509] [drm] Initialized hdlcd 1.0.0 20151021 for 2b000000.hdlcd on minor 0
  3016. ....
  3017. The port `5900` is incremented by one if you already have something running on that port, `gem5` stdout tells us the right port on stdout as:
  3018. ....
  3019. system.vncserver: Listening for connections on port 5900
  3020. ....
  3021. and when we connect it shows a message:
  3022. ....
  3023. info: VNC client attached
  3024. ....
  3025. Alternatively, you can also dump each new frame to an image file with `--frame-capture`:
  3026. ....
  3027. ./run \
  3028. --arch arm \
  3029. --emulator gem5 \
  3030. --linux-build-id gem5-v4.15 \
  3031. -- --frame-capture \
  3032. ;
  3033. ....
  3034. This creates on compressed PNG whenever the screen image changes inside the <<m5out-directory>> with filename of type:
  3035. ....
  3036. frames_system.vncserver/fb.<frame-index>.<timestamp>.png.gz
  3037. ....
  3038. It is fun to see how we get one new frame whenever the white underscore cursor appears and reappears under the penguin!
  3039. The last frame is always available uncompressed at: `system.framebuffer.png`.
  3040. TODO <<kmscube>> failed on `aarch64` with:
  3041. ....
  3042. kmscube[706]: unhandled level 2 translation fault (11) at 0x00000000, esr 0x92000006, in libgbm.so.1.0.0[7fbf6a6000+e000]
  3043. ....
  3044. Tested on: https://github.com/cirosantilli/linux-kernel-module-cheat/commit/38fd6153d965ba20145f53dc1bb3ba34b336bde9[38fd6153d965ba20145f53dc1bb3ba34b336bde9]
  3045. ==== Graphic mode gem5 aarch64
  3046. For `aarch64` we also need to configure the kernel with link:linux_config/display[]:
  3047. ....
  3048. git -C "$(./getvar linux_source_dir)" fetch https://gem5.googlesource.com/arm/linux gem5/v4.15:gem5/v4.15
  3049. git -C "$(./getvar linux_source_dir)" checkout gem5/v4.15
  3050. ./build-linux \
  3051. --arch aarch64 \
  3052. --config-fragment linux_config/display \
  3053. --custom-config-file-gem5 \
  3054. --linux-build-id gem5-v4.15 \
  3055. ;
  3056. git -C "$(./getvar linux_source_dir)" checkout -
  3057. ./run --arch aarch64 --emulator gem5 --linux-build-id gem5-v4.15
  3058. ....
  3059. This is because the gem5 `aarch64` defconfig does not enable HDLCD like the 32 bit one `arm` one for some reason.
  3060. ==== gem5 graphic mode DP650
  3061. TODO get working. There is an unmerged patchset at: https://gem5-review.googlesource.com/c/public/gem5/+/11036/1
  3062. The DP650 is a newer display hardware than HDLCD. TODO is its interface publicly documented anywhere? Since it has a gem5 model and https://github.com/torvalds/linux/blob/v4.19/drivers/gpu/drm/arm/Kconfig#L39[in-tree Linux kernel support], that information cannot be secret?
  3063. The key option to enable support in Linux is `DRM_MALI_DISPLAY=y` which we enable at link:linux_config/display[].
  3064. Build the kernel exactly as for <<graphic-mode-gem5-aarch64>> and then run with:
  3065. ....
  3066. ./run --arch aarch64 --dp650 --emulator gem5 --linux-build-id gem5-v4.15
  3067. ....
  3068. ==== gem5 graphic mode internals
  3069. We cannot use mainline Linux because the <<gem5-arm-linux-kernel-patches>> are required at least to provide the `CONFIG_DRM_VIRT_ENCODER` option.
  3070. gem5 emulates the http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0541c/CHDBAIDI.html[HDLCD] ARM Holdings hardware for `arm` and `aarch64`.
  3071. The kernel uses HDLCD to implement the <<drm>> interface, the required kernel config options are present at: link:linux_config/display[].
  3072. TODO: minimize out the `--custom-config-file`. If we just remove it on `arm`: it does not work with a failing dmesg:
  3073. ....
  3074. [ 0.066208] [drm] found ARM HDLCD version r0p0
  3075. [ 0.066241] hdlcd 2b000000.hdlcd: bound virt-encoder (ops drm_vencoder_ops)
  3076. [ 0.066247] [drm] Supports vblank timestamp caching Rev 2 (21.10.2013).
  3077. [ 0.066252] [drm] No driver support for vblank timestamp query.
  3078. [ 0.066276] hdlcd 2b000000.hdlcd: Cannot do DMA to address 0x0000000000000000
  3079. [ 0.066281] swiotlb: coherent allocation failed for device 2b000000.hdlcd size=8294400
  3080. [ 0.066288] CPU: 0 PID: 1 Comm: swapper/0 Not tainted 4.15.0 #1
  3081. [ 0.066293] Hardware name: V2P-AARCH64 (DT)
  3082. [ 0.066296] Call trace:
  3083. [ 0.066301] dump_backtrace+0x0/0x1b0
  3084. [ 0.066306] show_stack+0x24/0x30
  3085. [ 0.066311] dump_stack+0xb8/0xf0
  3086. [ 0.066316] swiotlb_alloc_coherent+0x17c/0x190
  3087. [ 0.066321] __dma_alloc+0x68/0x160
  3088. [ 0.066325] drm_gem_cma_create+0x98/0x120
  3089. [ 0.066330] drm_fbdev_cma_create+0x74/0x2e0
  3090. [ 0.066335] __drm_fb_helper_initial_config_and_unlock+0x1d8/0x3a0
  3091. [ 0.066341] drm_fb_helper_initial_config+0x4c/0x58
  3092. [ 0.066347] drm_fbdev_cma_init_with_funcs+0x98/0x148
  3093. [ 0.066352] drm_fbdev_cma_init+0x40/0x50
  3094. [ 0.066357] hdlcd_drm_bind+0x220/0x428
  3095. [ 0.066362] try_to_bring_up_master+0x21c/0x2b8
  3096. [ 0.066367] component_master_add_with_match+0xa8/0xf0
  3097. [ 0.066372] hdlcd_probe+0x60/0x78
  3098. [ 0.066377] platform_drv_probe+0x60/0xc8
  3099. [ 0.066382] driver_probe_device+0x30c/0x478
  3100. [ 0.066388] __driver_attach+0x10c/0x128
  3101. [ 0.066393] bus_for_each_dev+0x70/0xb0
  3102. [ 0.066398] driver_attach+0x30/0x40
  3103. [ 0.066402] bus_add_driver+0x1d0/0x298
  3104. [ 0.066408] driver_register+0x68/0x100
  3105. [ 0.066413] __platform_driver_register+0x54/0x60
  3106. [ 0.066418] hdlcd_platform_driver_init+0x20/0x28
  3107. [ 0.066424] do_one_initcall+0x44/0x130
  3108. [ 0.066428] kernel_init_freeable+0x13c/0x1d8
  3109. [ 0.066433] kernel_init+0x18/0x108
  3110. [ 0.066438] ret_from_fork+0x10/0x1c
  3111. [ 0.066444] hdlcd 2b000000.hdlcd: Failed to set initial hw configuration.
  3112. [ 0.066470] hdlcd 2b000000.hdlcd: master bind failed: -12
  3113. [ 0.066477] hdlcd: probe of 2b000000.hdlcd failed with error -12
  3114. ....
  3115. So what other options are missing from `gem5_defconfig`? It would be cool to minimize it out to better understand the options.
  3116. [[x11]]
  3117. === X11 Buildroot
  3118. Once you've seen the `CONFIG_LOGO` penguin as a sanity check, you can try to go for a cooler X11 Buildroot setup.
  3119. Build and run:
  3120. ....
  3121. ./build-buildroot --config-fragment buildroot_config/x11
  3122. ./run --graphic
  3123. ....
  3124. Inside QEMU:
  3125. ....
  3126. startx
  3127. ....
  3128. And then from the GUI you can start exciting graphical programs such as:
  3129. ....
  3130. xcalc
  3131. xeyes
  3132. ....
  3133. Outcome: xref:image-x11[xrefstyle=full]
  3134. [[image-x11]]
  3135. .X11 Buildroot graphical user interface screenshot
  3136. [link=x11.png]
  3137. image::x11.png[]
  3138. We don't build X11 by default because it takes a considerable amount of time (about 20%), and is not expected to be used by most users: you need to pass the `-x` flag to enable it.
  3139. More details: https://unix.stackexchange.com/questions/70931/how-to-install-x11-on-my-own-linux-buildroot-system/306116#306116
  3140. Not sure how well that graphics stack represents real systems, but if it does it would be a good way to understand how it works.
  3141. To x11 packages have an `xserver` prefix as in:
  3142. ....
  3143. ./build-buildroot --config-fragment buildroot_config/x11 -- xserver_xorg-server-reconfigure
  3144. ....
  3145. the easiest way to find them out is to just list `"$(./getvar buildroot_build_build_dir)/x*`.
  3146. TODO as of: c2696c978d6ca88e8b8599c92b1beeda80eb62b2 I noticed that `startx` leads to a <<bug_on>>:
  3147. ....
  3148. [ 2.809104] WARNING: CPU: 0 PID: 51 at drivers/gpu/drm/ttm/ttm_bo_vm.c:304 ttm_bo_vm_open+0x37/0x40
  3149. ....
  3150. ==== X11 Buildroot mouse not moving
  3151. TODO 9076c1d9bcc13b6efdb8ef502274f846d8d4e6a1 I'm 100% sure that it was working before, but I didn't run it forever, and it stopped working at some point. Needs bisection, on whatever commit last touched x11 stuff.
  3152. * https://askubuntu.com/questions/730891/how-can-i-get-a-mouse-cursor-in-qemu
  3153. * https://stackoverflow.com/questions/19665412/mouse-and-keyboard-not-working-in-qemu-emulator
  3154. `-show-cursor` did not help, I just get to see the host cursor, but the guest cursor still does not move.
  3155. Doing:
  3156. ....
  3157. watch -n 1 grep i8042 /proc/interrupts
  3158. ....
  3159. shows that interrupts do happen when mouse and keyboard presses are done, so I expect that it is some wrong either with:
  3160. * QEMU. Same behaviour if I try the host's QEMU 2.10.1 however.
  3161. * X11 configuration. We do have `BR2_PACKAGE_XDRIVER_XF86_INPUT_MOUSE=y`.
  3162. `/var/log/Xorg.0.log` contains the following interesting lines:
  3163. ....
  3164. [ 27.549] (II) LoadModule: "mouse"
  3165. [ 27.549] (II) Loading /usr/lib/xorg/modules/input/mouse_drv.so
  3166. [ 27.590] (EE) <default pointer>: Cannot find which device to use.
  3167. [ 27.590] (EE) <default pointer>: cannot open input device
  3168. [ 27.590] (EE) PreInit returned 2 for "<default pointer>"
  3169. [ 27.590] (II) UnloadModule: "mouse"
  3170. ....
  3171. The file `/dev/inputs/mice` does not exist.
  3172. Note that our current link:kernel_confi_fragment sets:
  3173. ....
  3174. # CONFIG_INPUT_MOUSE is not set
  3175. # CONFIG_INPUT_MOUSEDEV_PSAUX is not set
  3176. ....
  3177. for gem5, so you might want to remove those lines to debug this.
  3178. ==== X11 Buildroot ARM
  3179. On ARM, `startx` hangs at a message:
  3180. ....
  3181. vgaarb: this pci device is not a vga device
  3182. ....
  3183. and nothing shows on the screen, and:
  3184. ....
  3185. grep EE /var/log/Xorg.0.log
  3186. ....
  3187. says:
  3188. ....
  3189. (EE) Failed to load module "modesetting" (module does not exist, 0)
  3190. ....
  3191. A friend told me this but I haven't tried it yet:
  3192. * `xf86-video-modesetting` is likely the missing ingredient, but it does not seem possible to activate it from Buildroot currently without patching things.
  3193. * `xf86-video-fbdev` should work as well, but we need to make sure fbdev is enabled, and maybe add some line to the `Xorg.conf`
  3194. == Networking
  3195. === Enable networking
  3196. We disable networking by default because it starts an userland process, and we want to keep the number of userland processes to a minimum to make the system more understandable as explained at: xref:resource-tradeoff-guidelines[xrefstyle=full]
  3197. To enable networking on Buildroot, simply run:
  3198. ....
  3199. ifup -a
  3200. ....
  3201. That command goes over all (`-a`) the interfaces in `/etc/network/interfaces` and brings them up.
  3202. Then test it with:
  3203. ....
  3204. wget google.com
  3205. cat index.html
  3206. ....
  3207. Disable networking with:
  3208. ....
  3209. ifdown -a
  3210. ....
  3211. To enable networking by default after boot, use the methods documented at <<init-busybox>>.
  3212. === ping
  3213. `ping` does not work within QEMU by default, e.g.:
  3214. ....
  3215. ping google.com
  3216. ....
  3217. hangs after printing the header:
  3218. ....
  3219. PING google.com (216.58.204.46): 56 data bytes
  3220. ....
  3221. Here Ciro describes how to get it working: https://unix.stackexchange.com/questions/473448/how-to-ping-from-the-qemu-guest-to-an-external-url
  3222. Further bibliography: https://superuser.com/questions/787400/qemu-user-mode-networking-doesnt-work
  3223. === Guest host networking
  3224. In this section we discuss how to interact between the guest and the host through networking.
  3225. First ensure that you can access the external network since that is easier to get working, see: xref:networking[xrefstyle=full].
  3226. ==== Host to guest networking
  3227. ===== nc host to guest
  3228. With `nc` we can create the most minimal example possible as a sanity check.
  3229. On guest run:
  3230. ....
  3231. nc -l -p 45455
  3232. ....
  3233. Then on host run:
  3234. ....
  3235. echo asdf | nc localhost 45455
  3236. ....
  3237. `asdf` appears on the guest.
  3238. This uses:
  3239. * BusyBox' `nc` utility, which is enabled with `CONFIG_NC=y`
  3240. * `nc` from the `netcat-openbsd` package on an Ubuntu 18.04 host
  3241. Only this specific port works by default since we have forwarded it on the QEMU command line.
  3242. We us this exact procedure to connect to <<gdbserver>>.
  3243. ===== ssh into guest
  3244. Not enabled by default due to the build / runtime overhead. To enable, build with:
  3245. ....
  3246. ./build-buildroot --config 'BR2_PACKAGE_OPENSSH=y'
  3247. ....
  3248. Then inside the guest turn on sshd:
  3249. ....
  3250. ./sshd.sh
  3251. ....
  3252. Source: link:rootfs_overlay/lkmc/sshd.sh[]
  3253. And finally on host:
  3254. ....
  3255. ssh root@localhost -p 45456
  3256. ....
  3257. Bibliography: https://unix.stackexchange.com/questions/124681/how-to-ssh-from-host-to-guest-using-qemu/307557#307557
  3258. ===== gem5 host to guest networking
  3259. Could not do port forwarding from host to guest, and therefore could not use `gdbserver`: https://stackoverflow.com/questions/48941494/how-to-do-port-forwarding-from-guest-to-host-in-gem5
  3260. ==== Guest to host networking
  3261. First <<enable-networking>>.
  3262. Then in the host, start a server:
  3263. ....
  3264. python -m SimpleHTTPServer 8000
  3265. ....
  3266. And then in the guest, find the IP we need to hit with:
  3267. ....
  3268. ip rounte
  3269. ....
  3270. which gives:
  3271. .....
  3272. default via 10.0.2.2 dev eth0
  3273. 10.0.2.0/24 dev eth0 scope link src 10.0.2.15
  3274. .....
  3275. so we use in the guest:
  3276. ....
  3277. wget 10.0.2.2:8000
  3278. ....
  3279. Bibliography:
  3280. * https://serverfault.com/questions/769874/how-to-forward-a-port-from-guest-to-host-in-qemu-kvm/951835#951835
  3281. * https://unix.stackexchange.com/questions/78953/qemu-how-to-ping-host-network/547698#547698
  3282. === 9P
  3283. The https://en.wikipedia.org/wiki/9P_(protocol)[9p protocol] allows the guest to mount a host directory.
  3284. Both QEMU and <<9p-gem5>> support 9P.
  3285. ==== 9P vs NFS
  3286. All of 9P and NFS (and sshfs) allow sharing directories between guest and host.
  3287. Advantages of 9P
  3288. * requires `sudo` on the host to mount
  3289. * we could share a guest directory to the host, but this would require running a server on the guest, which adds <<resource-tradeoff-guidelines,simulation overhead>>
  3290. +
  3291. Furthermore, this would be inconvenient, since what we usually want to do is to share host cross built files with the guest, and to do that we would have to copy the files over after the guest starts the server.
  3292. * QEMU implements 9P natively, which makes it very stable and convenient, and must mean it is a simpler protocol than NFS as one would expect.
  3293. +
  3294. This is not the case for gem5 7bfb7f3a43f382eb49853f47b140bfd6caad0fb8 unfortunately, which relies on the https://github.com/chaos/diod[diod] host daemon, although it is not unfeasible that future versions could implement it natively as well.
  3295. Advantages of NFS:
  3296. * way more widely used and therefore stable and available, not to mention that it also works on real hardware.
  3297. * the name does not start with a digit, which is an invalid identifier in all programming languages known to man. Who in their right mind would call a software project as such? It does not even match the natural order of Plan 9; Plan then 9: P9!
  3298. ==== 9P getting started
  3299. As usual, we have already set everything up for you. On host:
  3300. ....
  3301. cd "$(./getvar p9_dir)"
  3302. uname -a > host
  3303. ....
  3304. Guest:
  3305. ....
  3306. cd /mnt/9p/data
  3307. cat host
  3308. uname -a > guest
  3309. ....
  3310. Host:
  3311. ....
  3312. cat guest
  3313. ....
  3314. The main ingredients for this are:
  3315. * `9P` settings in our <<kernel-configs-about,kernel configs>>
  3316. * `9p` entry on our link:rootfs_overlay/etc/fstab[]
  3317. +
  3318. Alternatively, you could also mount your own with:
  3319. +
  3320. ....
  3321. mkdir /mnt/my9p
  3322. mount -t 9p -o trans=virtio,version=9p2000.L host0 /mnt/my9p
  3323. ....
  3324. +
  3325. where mount tag `host0` is set by the emulator (`mount_tag` flag on QEMU CLI), and can be found in the guest with: `cat /sys/bus/virtio/drivers/9pnet_virtio/virtio0/mount_tag` as documented at: https://www.kernel.org/doc/Documentation/filesystems/9p.txt[].
  3326. * Launch QEMU with `-virtfs` as in your link:run[] script
  3327. +
  3328. When we tried:
  3329. +
  3330. ....
  3331. security_model=mapped
  3332. ....
  3333. +
  3334. writes from guest failed due to user mismatch problems: https://serverfault.com/questions/342801/read-write-access-for-passthrough-9p-filesystems-with-libvirt-qemu
  3335. Bibliography:
  3336. * https://superuser.com/questions/628169/how-to-share-a-directory-with-the-host-without-networking-in-qemu
  3337. * https://wiki.qemu.org/Documentation/9psetup
  3338. ==== 9P gem5
  3339. TODO seems possible! Lets do it:
  3340. * http://gem5.org/wiki/images/b/b8/Summit2017_wa_devlib.pdf
  3341. * http://gem5.org/WA-gem5
  3342. From the source, there is just one exported tag named `gem5`, so we could try on the guest:
  3343. ....
  3344. mkdir -p /mnt/9p/gem5
  3345. mount -t 9p -o trans=virtio,version=9p2000.L gem5 /mnt/9p/data
  3346. ....
  3347. ==== NFS
  3348. TODO: get working.
  3349. <<9p>> is better with emulation, but let's just get this working for fun.
  3350. First make sure that this works: xref:guest-to-host-networking[xrefstyle=full].
  3351. Then, build the kernel with NFS support:
  3352. ....
  3353. ./build-linux --config-fragment linux_config/nfs
  3354. ....
  3355. Now on host:
  3356. ....
  3357. sudo apt-get install nfs-kernel-server
  3358. ....
  3359. Now edit `/etc/exports` to contain:
  3360. ....
  3361. /tmp *(rw,sync,no_root_squash,no_subtree_check)
  3362. ....
  3363. and restart the server:
  3364. ....
  3365. sudo systemctl restart nfs-kernel-server
  3366. ....
  3367. Now on guest:
  3368. ....
  3369. mkdir /mnt/nfs
  3370. mount -t nfs 10.0.2.2:/tmp /mnt/nfs
  3371. ....
  3372. TODO: failing with:
  3373. ....
  3374. mount: mounting 10.0.2.2:/tmp on /mnt/nfs failed: No such device
  3375. ....
  3376. And now the `/tmp` directory from host is not mounted on guest!
  3377. If you don't want to start the NFS server after the next boot automatically so save resources, https://askubuntu.com/questions/19320/how-to-enable-or-disable-services[do]:
  3378. ....
  3379. systemctl disable nfs-kernel-server
  3380. ....
  3381. == Linux kernel
  3382. === Linux kernel configuration
  3383. ==== Modify kernel config
  3384. To modify a single option on top of our <<kernel-configs-about,default kernel configs>>, do:
  3385. ....
  3386. ./build-linux --config 'CONFIG_FORTIFY_SOURCE=y'
  3387. ....
  3388. Kernel modules depend on certain kernel configs, and therefore in general you might have to clean and rebuild the kernel modules after changing the kernel config:
  3389. ....
  3390. ./build-modules --clean
  3391. ./build-modules
  3392. ....
  3393. and then proceed as in <<your-first-kernel-module-hack>>.
  3394. You might often get way without rebuilding the kernel modules however.
  3395. To use an extra kernel config fragment file on top of our defaults, do:
  3396. ....
  3397. printf '
  3398. CONFIG_IKCONFIG=y
  3399. CONFIG_IKCONFIG_PROC=y
  3400. ' > data/myconfig
  3401. ./build-linux --config-fragment 'data/myconfig'
  3402. ....
  3403. To use just your own exact `.config` instead of our defaults ones, use:
  3404. ....
  3405. ./build-linux --custom-config-file data/myconfig
  3406. ....
  3407. There is also a shortcut `--custom-config-file` to use the <<gem5-arm-linux-kernel-patches>>.
  3408. The following options can all be used together, sorted by decreasing config setting power precedence:
  3409. * `--config`
  3410. * `--config-fragment`
  3411. * `--custom-config-file`
  3412. To do a clean menu config yourself and use that for the build, do:
  3413. ....
  3414. ./build-linux --clean
  3415. ./build-linux --custom-config-target menuconfig
  3416. ....
  3417. But remember that every new build re-configures the kernel by default, so to keep your configs you will need to use on further builds:
  3418. ....
  3419. ./build-linux --no-configure
  3420. ....
  3421. So what you likely want to do instead is to save that as a new `defconfig` and use it later as:
  3422. ....
  3423. ./build-linux --no-configure --no-modules-install savedefconfig
  3424. cp "$(./getvar linux_build_dir)/defconfig" data/myconfig
  3425. ./build-linux --custom-config-file data/myconfig
  3426. ....
  3427. You can also use other config generating targets such as `defconfig` with the same method as shown at: xref:linux-kernel-defconfig[xrefstyle=full].
  3428. ==== Find the kernel config
  3429. Get the build config in guest:
  3430. ....
  3431. zcat /proc/config.gz
  3432. ....
  3433. or with our shortcut:
  3434. ....
  3435. ./conf.sh
  3436. ....
  3437. or to conveniently grep for a specific option case insensitively:
  3438. ....
  3439. ./conf.sh ikconfig
  3440. ....
  3441. Source: link:rootfs_overlay/lkmc/conf.sh[].
  3442. This is enabled by:
  3443. ....
  3444. CONFIG_IKCONFIG=y
  3445. CONFIG_IKCONFIG_PROC=y
  3446. ....
  3447. From host:
  3448. ....
  3449. cat "$(./getvar linux_config)"
  3450. ....
  3451. Just for fun https://stackoverflow.com/questions/14958192/how-to-get-the-config-from-a-linux-kernel-image/14958263#14958263[]:
  3452. ....
  3453. ./linux/scripts/extract-ikconfig "$(./getvar vmlinux)"
  3454. ....
  3455. although this can be useful when someone gives you a random image.
  3456. [[kernel-configs-about]]
  3457. ==== About our Linux kernel configs
  3458. By default, link:build-linux[] generates a `.config` that is a mixture of:
  3459. * a base config extracted from Buildroot's minimal per machine `.config`, which has the minimal options needed to boot as explained at: xref:buildroot-kernel-config[xrefstyle=full].
  3460. * small overlays put top of that
  3461. To find out which kernel configs are being used exactly, simply run:
  3462. ....
  3463. ./build-linux --dry-run
  3464. ....
  3465. and look for the `merge_config.sh` call. This script from the Linux kernel tree, as the name suggests, merges multiple configuration files into one as explained at: https://unix.stackexchange.com/questions/224887/how-to-script-make-menuconfig-to-automate-linux-kernel-build-configuration/450407#450407
  3466. For each arch, the base of our configs are named as:
  3467. ....
  3468. linux_config/buildroot-<arch>
  3469. ....
  3470. e.g.: link:linux_config/buildroot-x86_64[].
  3471. These configs are extracted directly from a Buildroot build with link:update-buildroot-kernel-configs[].
  3472. Note that Buildroot can `sed` override some of the configurations, e.g. it forces `CONFIG_BLK_DEV_INITRD=y` when `BR2_TARGET_ROOTFS_CPIO` is on. For this reason, those configs are not simply copy pasted from Buildroot files, but rather from a Buildroot kernel build, and then minimized with `make savedefconfig`: https://stackoverflow.com/questions/27899104/how-to-create-a-defconfig-file-from-a-config
  3473. On top of those, we add the following by default:
  3474. * link:linux_config/min[]: see: xref:linux-kernel-min-config[xrefstyle=full]
  3475. * link:linux_config/default[]: other optional configs that we enable by default because they increase visibility, or expose some cool feature, and don't significantly increase build time nor add significant runtime overhead
  3476. +
  3477. We have since observed that the kernel size itself is very bloated compared to `defconfig` as shown at: xref:linux-kernel-defconfig[xrefstyle=full].
  3478. [[buildroot-kernel-config]]
  3479. ===== About Buildroot's kernel configs
  3480. To see Buildroot's base configs, start from https://github.com/buildroot/buildroot/blob/2018.05/configs/qemu_x86_64_defconfig[`buildroot/configs/qemu_x86_64_defconfig`].
  3481. That file contains `BR2_LINUX_KERNEL_CUSTOM_CONFIG_FILE="board/qemu/x86_64/linux-4.15.config"`, which points to the base config file used: https://github.com/buildroot/buildroot/blob/2018.05/board/qemu/x86_64/linux-4.15.config[board/qemu/x86_64/linux-4.15.config].
  3482. `arm`, on the other hand, uses https://github.com/buildroot/buildroot/blob/2018.05/configs/qemu_arm_vexpress_defconfig[`buildroot/configs/qemu_arm_vexpress_defconfig`], which contains `BR2_LINUX_KERNEL_DEFCONFIG="vexpress"`, and therefore just does a `make vexpress_defconfig`, and gets its config from the Linux kernel tree itself.
  3483. ====== Linux kernel defconfig
  3484. To boot https://stackoverflow.com/questions/41885015/what-exactly-does-linux-kernels-make-defconfig-do[defconfig] from disk on Linux and see a shell, all we need is these missing virtio options:
  3485. ....
  3486. ./build-linux \
  3487. --linux-build-id defconfig \
  3488. --custom-config-target defconfig \
  3489. --config CONFIG_VIRTIO_PCI=y \
  3490. --config CONFIG_VIRTIO_BLK=y \
  3491. ;
  3492. ./run --linux-build-id defconfig
  3493. ....
  3494. Oh, and check this out:
  3495. ....
  3496. du -h \
  3497. "$(./getvar vmlinux)" \
  3498. "$(./getvar --linux-build-id defconfig vmlinux)" \
  3499. ;
  3500. ....
  3501. Output:
  3502. ....
  3503. 360M /path/to/linux-kernel-module-cheat/out/linux/default/x86_64/vmlinux
  3504. 47M /path/to/linux-kernel-module-cheat/out/linux/defconfig/x86_64/vmlinux
  3505. ....
  3506. Brutal. Where did we go wrong?
  3507. The extra virtio options are not needed if we use <<initrd>>:
  3508. ....
  3509. ./build-linux \
  3510. --linux-build-id defconfig \
  3511. --custom-config-target defconfig \
  3512. ;
  3513. ./run --initrd --linux-build-id defconfig
  3514. ....
  3515. On aarch64, we can boot from initrd with:
  3516. ....
  3517. ./build-linux \
  3518. --arch aarch64 \
  3519. --linux-build-id defconfig \
  3520. --custom-config-target defconfig \
  3521. ;
  3522. ./run \
  3523. --arch aarch64 \
  3524. --initrd \
  3525. --linux-build-id defconfig \
  3526. --memory 2G \
  3527. ;
  3528. ....
  3529. We need the 2G of memory because the CPIO is 600MiB due to a humongous amount of loadable kernel modules!
  3530. In aarch64, the size situation is inverted from x86_64, and this can be seen on the vmlinux size as well:
  3531. ....
  3532. 118M /path/to/linux-kernel-module-cheat/out/linux/default/aarch64/vmlinux
  3533. 240M /path/to/linux-kernel-module-cheat/out/linux/defconfig/aarch64/vmlinux
  3534. ....
  3535. So it seems that the ARM devs decided rather than creating a minimal config that boots QEMU, to try and make a single config that boots every board in existence. Terrible!
  3536. Bibliography: https://unix.stackexchange.com/questions/29439/compiling-the-kernel-with-default-configurations/204512#204512
  3537. Tested on 1e2b7f1e5e9e3073863dc17e25b2455c8ebdeadd + 1.
  3538. ====== Linux kernel min config
  3539. link:linux_config/min[] contains minimal tweaks required to boot gem5 or for using our slightly different QEMU command line options than Buildroot on all archs.
  3540. It is one of the default config fragments we use, as explained at: xref:kernel-configs-about[xrefstyle=full]>.
  3541. Having the same config working for both QEMU and gem5 (oh, the hours of bisection) means that you can deal with functional matters in QEMU, which runs much faster, and switch to gem5 only for performance issues.
  3542. We can build just with `min` on top of the base config with:
  3543. ....
  3544. ./build-linux \
  3545. --arch aarch64 \
  3546. --config-fragment linux_config/min \
  3547. --custom-config-file linux_config/buildroot-aarch64 \
  3548. --linux-build-id min \
  3549. ;
  3550. ....
  3551. vmlinux had a very similar size to the default. It seems that link:linux_config/buildroot-aarch64[] contains or implies most link:linux_config/default[] options already? TODO: that seems odd, really?
  3552. Tested on 649d06d6758cefd080d04dc47fd6a5a26a620874 + 1.
  3553. ===== Notable alternate gem5 kernel configs
  3554. Other configs which we had previously tested at 4e0d9af81fcce2ce4e777cb82a1990d7c2ca7c1e are:
  3555. * `arm` and `aarch64` configs present in the official ARM gem5 Linux kernel fork as described at: xref:gem5-arm-linux-kernel-patches[xrefstyle=full]. Some of the configs present there are added by the patches.
  3556. * Jason's magic `x86_64` config: http://web.archive.org/web/20171229121642/http://www.lowepower.com/jason/files/config which is referenced at: http://web.archive.org/web/20171229121525/http://www.lowepower.com/jason/setting-up-gem5-full-system.html[]. QEMU boots with that by removing `# CONFIG_VIRTIO_PCI is not set`.
  3557. === Kernel version
  3558. ==== Find the kernel version
  3559. We try to use the latest possible kernel major release version.
  3560. In QEMU:
  3561. ....
  3562. cat /proc/version
  3563. ....
  3564. or in the source:
  3565. ....
  3566. cd "$(./getvar linux_source_dir)"
  3567. git log | grep -E ' Linux [0-9]+\.' | head
  3568. ....
  3569. ==== Update the Linux kernel
  3570. During update all you kernel modules may break since the kernel API is not stable.
  3571. They are usually trivial breaks of things moving around headers or to sub-structs.
  3572. The userland, however, should simply not break, as Linus enforces strict backwards compatibility of userland interfaces.
  3573. This backwards compatibility is just awesome, it makes getting and running the latest master painless.
  3574. This also makes this repo the perfect setup to develop the Linux kernel.
  3575. In case something breaks while updating the Linux kernel, you can try to bisect it to understand the root cause, see: xref:bisection[xrefstyle=full].
  3576. ===== Update the Linux kernel LKMC procedure
  3577. First, use use the branching procedure described at: xref:update-a-forked-submodule[xrefstyle=full]
  3578. Because the kernel is so central to this repository, almost all tests must be re-run, so basically just follow the full testing procedure described at: xref:test-this-repo[xrefstyle=full]. The only tests that can be skipped are essentially the <<baremetal>> tests.
  3579. Before comitting, don't forget to update:
  3580. * the `linux_kernel_version` constant in link:common.py[]
  3581. * the tagline of this repository on:
  3582. ** this README
  3583. ** the GitHub project description
  3584. ==== Downgrade the Linux kernel
  3585. The kernel is not forward compatible, however, so downgrading the Linux kernel requires downgrading the userland too to the latest Buildroot branch that supports it.
  3586. The default Linux kernel version is bumped in Buildroot with commit messages of type:
  3587. ....
  3588. linux: bump default to version 4.9.6
  3589. ....
  3590. So you can try:
  3591. ....
  3592. git log --grep 'linux: bump default to version'
  3593. ....
  3594. Those commits change `BR2_LINUX_KERNEL_LATEST_VERSION` in `/linux/Config.in`.
  3595. You should then look up if there is a branch that supports that kernel. Staying on branches is a good idea as they will get backports, in particular ones that fix the build as newer host versions come out.
  3596. Finally, after downgrading Buildroot, if something does not work, you might also have to make some changes to how this repo uses Buildroot, as the Buildroot configuration options might have changed.
  3597. We don't expect those changes to be very difficult. A good way to approach the task is to:
  3598. * do a dry run build to get the equivalent Bash commands used:
  3599. +
  3600. ....
  3601. ./build-buildroot --dry-run
  3602. ....
  3603. * build the Buildroot documentation for the version you are going to use, and check if all Buildroot build commands make sense there
  3604. Then, if you spot an option that is wrong, some grepping in this repo should quickly point you to the code you need to modify.
  3605. It also possible that you will need to apply some patches from newer Buildroot versions for it to build, due to incompatibilities with the host Ubuntu packages and that Buildroot version. Just read the error message, and try:
  3606. * `git log master -- packages/<pkg>`
  3607. * Google the error message for mailing list hits
  3608. Successful port reports:
  3609. * v3.18: https://github.com/cirosantilli/linux-kernel-module-cheat/issues/39#issuecomment-438525481
  3610. === Kernel command line parameters
  3611. Bootloaders can pass a string as input to the Linux kernel when it is booting to control its behaviour, much like the `execve` system call does to userland processes.
  3612. This allows us to control the behaviour of the kernel without rebuilding anything.
  3613. With QEMU, QEMU itself acts as the bootloader, and provides the `-append` option and we expose it through `./run --kernel-cli`, e.g.:
  3614. ....
  3615. ./run --kernel-cli 'foo bar'
  3616. ....
  3617. Then inside the host, you can check which options were given with:
  3618. ....
  3619. cat /proc/cmdline
  3620. ....
  3621. They are also printed at the beginning of the boot message:
  3622. ....
  3623. dmesg | grep "Command line"
  3624. ....
  3625. See also:
  3626. * https://unix.stackexchange.com/questions/48601/how-to-display-the-linux-kernel-command-line-parameters-given-for-the-current-bo
  3627. * https://askubuntu.com/questions/32654/how-do-i-find-the-boot-parameters-used-by-the-running-kernel
  3628. The arguments are documented in the kernel documentation: https://www.kernel.org/doc/html/v4.14/admin-guide/kernel-parameters.html
  3629. When dealing with real boards, extra command line options are provided on some magic bootloader configuration file, e.g.:
  3630. * GRUB configuration files: https://askubuntu.com/questions/19486/how-do-i-add-a-kernel-boot-parameter
  3631. * Raspberry pi `/boot/cmdline.txt` on a magic partition: https://raspberrypi.stackexchange.com/questions/14839/how-to-change-the-kernel-commandline-for-archlinuxarm-on-raspberry-pi-effectly
  3632. ==== Kernel command line parameters escaping
  3633. Double quotes can be used to escape spaces as in `opt="a b"`, but double quotes themselves cannot be escaped, e.g. `opt"a\"b"`
  3634. This even lead us to use base64 encoding with `--eval`!
  3635. ==== Kernel command line parameters definition points
  3636. There are two methods:
  3637. * `__setup` as in:
  3638. +
  3639. ....
  3640. __setup("console=", console_setup);
  3641. ....
  3642. * `core_param` as in:
  3643. +
  3644. ....
  3645. core_param(panic, panic_timeout, int, 0644);
  3646. ....
  3647. `core_param` suggests how they are different:
  3648. ....
  3649. /**
  3650. * core_param - define a historical core kernel parameter.
  3651. ...
  3652. * core_param is just like module_param(), but cannot be modular and
  3653. * doesn't add a prefix (such as "printk."). This is for compatibility
  3654. * with __setup(), and it makes sense as truly core parameters aren't
  3655. * tied to the particular file they're in.
  3656. */
  3657. ....
  3658. ==== rw
  3659. By default, the Linux kernel mounts the root filesystem as readonly. TODO rationale?
  3660. This cannot be observed in the default BusyBox init, because by default our link:rootfs_overlay/etc/inittab[] does:
  3661. ....
  3662. /bin/mount -o remount,rw /
  3663. ....
  3664. Analogously, Ubuntu 18.04 does in its fstab something like:
  3665. ....
  3666. UUID=/dev/sda1 / ext4 errors=remount-ro 0 1
  3667. ....
  3668. which uses default mount `rw` flags.
  3669. We have however removed those setups init setups to keep things more minimal, and replaced them with the `rw` kernel boot parameter makes the root mounted as writable.
  3670. To observe the default readonly behaviour, hack the link:run[] script to remove <<replace-init,replace init>>, and then run on a raw shell:
  3671. ....
  3672. ./run --kernel-cli 'init=/bin/sh'
  3673. ....
  3674. Now try to do:
  3675. ....
  3676. touch a
  3677. ....
  3678. which fails with:
  3679. ....
  3680. touch: a: Read-only file system
  3681. ....
  3682. We can also observe the read-onlyness with:
  3683. ....
  3684. mount -t proc /proc
  3685. mount
  3686. ....
  3687. which contains:
  3688. ....
  3689. /dev/root on / type ext2 (ro,relatime,block_validity,barrier,user_xattr)
  3690. ....
  3691. and so it is Read Only as shown by `ro`.
  3692. ==== norandmaps
  3693. Disable userland address space randomization. Test it out by running <<rand_check-out>> twice:
  3694. ....
  3695. ./run --eval-after './linux/rand_check.out;./linux/poweroff.out'
  3696. ./run --eval-after './linux/rand_check.out;./linux/poweroff.out'
  3697. ....
  3698. If we remove it from our link:run[] script by hacking it up, the addresses shown by `linux/rand_check.out` vary across boots.
  3699. Equivalent to:
  3700. ....
  3701. echo 0 > /proc/sys/kernel/randomize_va_space
  3702. ....
  3703. === printk
  3704. `printk` is the most simple and widely used way of getting information from the kernel, so you should familiarize yourself with its basic configuration.
  3705. We use `printk` a lot in our kernel modules, and it shows on the terminal by default, along with stdout and what you type.
  3706. Hide all `printk` messages:
  3707. ....
  3708. dmesg -n 1
  3709. ....
  3710. or equivalently:
  3711. ....
  3712. echo 1 > /proc/sys/kernel/printk
  3713. ....
  3714. See also: https://superuser.com/questions/351387/how-to-stop-kernel-messages-from-flooding-my-console
  3715. Do it with a <<kernel-command-line-parameters>> to affect the boot itself:
  3716. ....
  3717. ./run --kernel-cli 'loglevel=5'
  3718. ....
  3719. and now only boot warning messages or worse show, which is useful to identify problems.
  3720. Our default `printk` format is:
  3721. ....
  3722. <LEVEL>[TIMESTAMP] MESSAGE
  3723. ....
  3724. e.g.:
  3725. ....
  3726. <6>[ 2.979121] Freeing unused kernel memory: 2024K
  3727. ....
  3728. where:
  3729. * `LEVEL`: higher means less serious
  3730. * `TIMESTAMP`: seconds since boot
  3731. This format is selected by the following boot options:
  3732. * `console_msg_format=syslog`: add the `<LEVEL>` part. Added in v4.16.
  3733. * `printk.time=y`: add the `[TIMESTAMP]` part
  3734. The debug highest level is a bit more magic, see: xref:pr_debug[xrefstyle=full] for more info.
  3735. ==== /proc/sys/kernel/printk
  3736. The current printk level can be obtained with:
  3737. ....
  3738. cat /proc/sys/kernel/printk
  3739. ....
  3740. As of `87e846fc1f9c57840e143513ebd69c638bd37aa8` this prints:
  3741. ....
  3742. 7 4 1 7
  3743. ....
  3744. which contains:
  3745. * `7`: current log level, modifiable by previously mentioned methods
  3746. * `4`: documented as: "printk's without a loglevel use this": TODO what does that mean, how to call `printk` without a log level?
  3747. * `1`: minimum log level that still prints something (`0` prints nothing)
  3748. * `7`: default log level
  3749. We start at the boot time default after boot by default, as can be seen from:
  3750. ....
  3751. insmod myprintk.ko
  3752. ....
  3753. which outputs something like:
  3754. ....
  3755. <1>[ 12.494429] pr_alert
  3756. <2>[ 12.494666] pr_crit
  3757. <3>[ 12.494823] pr_err
  3758. <4>[ 12.494911] pr_warning
  3759. <5>[ 12.495170] pr_notice
  3760. <6>[ 12.495327] pr_info
  3761. ....
  3762. Source: link:kernel_modules/myprintk.c[]
  3763. This proc entry is defined at: https://github.com/torvalds/linux/blob/v5.1/kernel/sysctl.c#L839
  3764. ....
  3765. #if defined CONFIG_PRINTK
  3766. {
  3767. .procname = "printk",
  3768. .data = &console_loglevel,
  3769. .maxlen = 4*sizeof(int),
  3770. .mode = 0644,
  3771. .proc_handler = proc_dointvec,
  3772. },
  3773. ....
  3774. which teaches us that printk can be completely disabled at compile time:
  3775. ....
  3776. config PRINTK
  3777. default y
  3778. bool "Enable support for printk" if EXPERT
  3779. select IRQ_WORK
  3780. help
  3781. This option enables normal printk support. Removing it
  3782. eliminates most of the message strings from the kernel image
  3783. and makes the kernel more or less silent. As this makes it
  3784. very difficult to diagnose system problems, saying N here is
  3785. strongly discouraged.
  3786. ....
  3787. `console_loglevel` is defined at:
  3788. ....
  3789. #define console_loglevel (console_printk[0])
  3790. ....
  3791. and `console_printk` is an array with 4 ints:
  3792. ....
  3793. int console_printk[4] = {
  3794. CONSOLE_LOGLEVEL_DEFAULT, /* console_loglevel */
  3795. MESSAGE_LOGLEVEL_DEFAULT, /* default_message_loglevel */
  3796. CONSOLE_LOGLEVEL_MIN, /* minimum_console_loglevel */
  3797. CONSOLE_LOGLEVEL_DEFAULT, /* default_console_loglevel */
  3798. };
  3799. ....
  3800. and then we see that the default is configurable with `CONFIG_CONSOLE_LOGLEVEL_DEFAULT`:
  3801. ....
  3802. /*
  3803. * Default used to be hard-coded at 7, quiet used to be hardcoded at 4,
  3804. * we're now allowing both to be set from kernel config.
  3805. */
  3806. #define CONSOLE_LOGLEVEL_DEFAULT CONFIG_CONSOLE_LOGLEVEL_DEFAULT
  3807. #define CONSOLE_LOGLEVEL_QUIET CONFIG_CONSOLE_LOGLEVEL_QUIET
  3808. ....
  3809. The message loglevel default is explained at:
  3810. ....
  3811. /* printk's without a loglevel use this.. */
  3812. #define MESSAGE_LOGLEVEL_DEFAULT CONFIG_MESSAGE_LOGLEVEL_DEFAULT
  3813. ....
  3814. The min is just hardcoded to one as you would expect, with some amazing kernel comedy around it:
  3815. ....
  3816. /* We show everything that is MORE important than this.. */
  3817. #define CONSOLE_LOGLEVEL_SILENT 0 /* Mum's the word */
  3818. #define CONSOLE_LOGLEVEL_MIN 1 /* Minimum loglevel we let people use */
  3819. #define CONSOLE_LOGLEVEL_DEBUG 10 /* issue debug messages */
  3820. #define CONSOLE_LOGLEVEL_MOTORMOUTH 15 /* You can't shut this one up */
  3821. ....
  3822. We then also learn about the useless `quiet` and `debug` kernel parameters at:
  3823. ....
  3824. config CONSOLE_LOGLEVEL_QUIET
  3825. int "quiet console loglevel (1-15)"
  3826. range 1 15
  3827. default "4"
  3828. help
  3829. loglevel to use when "quiet" is passed on the kernel commandline.
  3830. When "quiet" is passed on the kernel commandline this loglevel
  3831. will be used as the loglevel. IOW passing "quiet" will be the
  3832. equivalent of passing "loglevel=<CONSOLE_LOGLEVEL_QUIET>"
  3833. ....
  3834. which explains the useless reason why that number is special. This is implemented at:
  3835. ....
  3836. static int __init debug_kernel(char *str)
  3837. {
  3838. console_loglevel = CONSOLE_LOGLEVEL_DEBUG;
  3839. return 0;
  3840. }
  3841. static int __init quiet_kernel(char *str)
  3842. {
  3843. console_loglevel = CONSOLE_LOGLEVEL_QUIET;
  3844. return 0;
  3845. }
  3846. early_param("debug", debug_kernel);
  3847. early_param("quiet", quiet_kernel);
  3848. ....
  3849. ==== ignore_loglevel
  3850. ....
  3851. ./run --kernel-cli 'ignore_loglevel'
  3852. ....
  3853. enables all log levels, and is basically the same as:
  3854. ....
  3855. ./run --kernel-cli 'loglevel=8'
  3856. ....
  3857. except that you don't need to know what is the maximum level.
  3858. ==== pr_debug
  3859. https://stackoverflow.com/questions/28936199/why-is-pr-debug-of-the-linux-kernel-not-giving-any-output/49835405#49835405
  3860. Debug messages are not printable by default without recompiling.
  3861. But the awesome `CONFIG_DYNAMIC_DEBUG=y` option which we enable by default allows us to do:
  3862. ....
  3863. echo 8 > /proc/sys/kernel/printk
  3864. echo 'file kernel/module.c +p' > /sys/kernel/debug/dynamic_debug/control
  3865. ./linux/myinsmod.out hello.ko
  3866. ....
  3867. and we have a shortcut at:
  3868. ....
  3869. ./pr_debug.sh
  3870. ....
  3871. Source: link:rootfs_overlay/lkmc/pr_debug.sh[].
  3872. Syntax: https://www.kernel.org/doc/html/v4.11/admin-guide/dynamic-debug-howto.html
  3873. Wildcards are also accepted, e.g. enable all messages from all files:
  3874. ....
  3875. echo 'file * +p' > /sys/kernel/debug/dynamic_debug/control
  3876. ....
  3877. TODO: why is this not working:
  3878. ....
  3879. echo 'func sys_init_module +p' > /sys/kernel/debug/dynamic_debug/control
  3880. ....
  3881. Enable messages in specific modules:
  3882. ....
  3883. echo 8 > /proc/sys/kernel/printk
  3884. echo 'module myprintk +p' > /sys/kernel/debug/dynamic_debug/control
  3885. insmod myprintk.ko
  3886. ....
  3887. Source: link:kernel_modules/myprintk.c[]
  3888. This outputs the `pr_debug` message:
  3889. ....
  3890. printk debug
  3891. ....
  3892. but TODO: it also shows debug messages even without enabling them explicitly:
  3893. ....
  3894. echo 8 > /proc/sys/kernel/printk
  3895. insmod myprintk.ko
  3896. ....
  3897. and it shows as enabled:
  3898. ....
  3899. # grep myprintk /sys/kernel/debug/dynamic_debug/control
  3900. /root/linux-kernel-module-cheat/out/kernel_modules/x86_64/kernel_modules/panic.c:12 [myprintk]myinit =p "pr_debug\012"
  3901. ....
  3902. Enable `pr_debug` for boot messages as well, before we can reach userland and write to `/proc`:
  3903. ....
  3904. ./run --kernel-cli 'dyndbg="file * +p" loglevel=8'
  3905. ....
  3906. Get ready for the noisiest boot ever, I think it overflows the `printk` buffer and funny things happen.
  3907. ===== pr_debug != printk(KERN_DEBUG
  3908. When `CONFIG_DYNAMIC_DEBUG` is set, `printk(KERN_DEBUG` is not the exact same as `pr_debug(` since `printk(KERN_DEBUG` messages are visible with:
  3909. ....
  3910. ./run --kernel-cli 'initcall_debug logleve=8'
  3911. ....
  3912. which outputs lines of type:
  3913. ....
  3914. <7>[ 1.756680] calling clk_disable_unused+0x0/0x130 @ 1
  3915. <7>[ 1.757003] initcall clk_disable_unused+0x0/0x130 returned 0 after 111 usecs
  3916. ....
  3917. which are `printk(KERN_DEBUG` inside `init/main.c` in v4.16.
  3918. Mentioned at: https://stackoverflow.com/questions/37272109/how-to-get-details-of-all-modules-drivers-got-initialized-probed-during-kernel-b
  3919. This likely comes from the ifdef split at `init/main.c`:
  3920. ....
  3921. /* If you are writing a driver, please use dev_dbg instead */
  3922. #if defined(CONFIG_DYNAMIC_DEBUG)
  3923. #include <linux/dynamic_debug.h>
  3924. /* dynamic_pr_debug() uses pr_fmt() internally so we don't need it here */
  3925. #define pr_debug(fmt, ...) \
  3926. dynamic_pr_debug(fmt, ##__VA_ARGS__)
  3927. #elif defined(DEBUG)
  3928. #define pr_debug(fmt, ...) \
  3929. printk(KERN_DEBUG pr_fmt(fmt), ##__VA_ARGS__)
  3930. #else
  3931. #define pr_debug(fmt, ...) \
  3932. no_printk(KERN_DEBUG pr_fmt(fmt), ##__VA_ARGS__)
  3933. #endif
  3934. ....
  3935. === Linux kernel entry point
  3936. `start_kernel` is a good definition of it: https://stackoverflow.com/questions/18266063/does-kernel-have-main-function/33422401#33422401
  3937. === Kernel module APIs
  3938. ==== Kernel module parameters
  3939. The Linux kernel allows passing module parameters at insertion time <<myinsmod,through the `init_module` and `finit_module` system calls>>.
  3940. The `insmod` tool exposes that as:
  3941. ....
  3942. insmod params.ko i=3 j=4
  3943. ....
  3944. Parameters are declared in the module as:
  3945. ....
  3946. static u32 i = 0;
  3947. module_param(i, int, S_IRUSR | S_IWUSR);
  3948. MODULE_PARM_DESC(i, "my favorite int");
  3949. ....
  3950. Automated test:
  3951. ....
  3952. ./params.sh
  3953. echo $?
  3954. ....
  3955. Outcome: the test passes:
  3956. ....
  3957. 0
  3958. ....
  3959. Sources:
  3960. * link:kernel_modules/params.c[]
  3961. * link:rootfs_overlay/lkmc/params.sh[]
  3962. As shown in the example, module parameters can also be read and modified at runtime from <<sysfs>>.
  3963. We can obtain the help text of the parameters with:
  3964. ....
  3965. modinfo params.ko
  3966. ....
  3967. The output contains:
  3968. ....
  3969. parm: j:my second favorite int
  3970. parm: i:my favorite int
  3971. ....
  3972. ===== modprobe.conf
  3973. <<modprobe>> insertion can also set default parameters via the link:rootfs_overlay/etc/modprobe.conf[`/etc/modprobe.conf`] file:
  3974. ....
  3975. modprobe params
  3976. cat /sys/kernel/debug/lkmc_params
  3977. ....
  3978. Output:
  3979. ....
  3980. 12 34
  3981. ....
  3982. This is specially important when loading modules with <<kernel-module-dependencies>> or else we would have no opportunity of passing those.
  3983. `modprobe.conf` doesn't actually insmod anything for us: https://superuser.com/questions/397842/automatically-load-kernel-module-at-boot-angstrom/1267464#1267464
  3984. ==== Kernel module dependencies
  3985. One module can depend on symbols of another module that are exported with `EXPORT_SYMBOL`:
  3986. ....
  3987. ./dep.sh
  3988. echo $?
  3989. ....
  3990. Outcome: the test passes:
  3991. ....
  3992. 0
  3993. ....
  3994. Sources:
  3995. * link:kernel_modules/dep.c[]
  3996. * link:kernel_modules/dep2.c[]
  3997. * link:rootfs_overlay/lkmc/dep.sh[]
  3998. The kernel deduces dependencies based on the `EXPORT_SYMBOL` that each module uses.
  3999. Symbols exported by `EXPORT_SYMBOL` can be seen with:
  4000. ....
  4001. insmod dep.ko
  4002. grep lkmc_dep /proc/kallsyms
  4003. ....
  4004. sample output:
  4005. ....
  4006. ffffffffc0001030 r __ksymtab_lkmc_dep [dep]
  4007. ffffffffc000104d r __kstrtab_lkmc_dep [dep]
  4008. ffffffffc0002300 B lkmc_dep [dep]
  4009. ....
  4010. This requires `CONFIG_KALLSYMS_ALL=y`.
  4011. Dependency information is stored by the kernel module build system in the `.ko` files' <<module_info>>, e.g.:
  4012. ....
  4013. modinfo dep2.ko
  4014. ....
  4015. contains:
  4016. ....
  4017. depends: dep
  4018. ....
  4019. We can double check with:
  4020. ....
  4021. strings 3 dep2.ko | grep -E 'depends'
  4022. ....
  4023. The output contains:
  4024. ....
  4025. depends=dep
  4026. ....
  4027. Module dependencies are also stored at:
  4028. ....
  4029. cd /lib/module/*
  4030. grep dep modules.dep
  4031. ....
  4032. Output:
  4033. ....
  4034. extra/dep2.ko: extra/dep.ko
  4035. extra/dep.ko:
  4036. ....
  4037. TODO: what for, and at which point point does Buildroot / BusyBox generate that file?
  4038. ===== Kernel module dependencies with modprobe
  4039. Unlike `insmod`, <<modprobe>> deals with kernel module dependencies for us.
  4040. First get <<kernel_modules-buildroot-package>> working.
  4041. Then, for example:
  4042. ....
  4043. modprobe buildroot_dep2
  4044. ....
  4045. outputs to dmesg:
  4046. ....
  4047. 42
  4048. ....
  4049. and then:
  4050. ....
  4051. lsmod
  4052. ....
  4053. outputs:
  4054. ....
  4055. Module Size Used by Tainted: G
  4056. buildroot_dep2 16384 0
  4057. buildroot_dep 16384 1 buildroot_dep2
  4058. ....
  4059. Sources:
  4060. * link:buildroot_packages/kernel_modules/buildroot_dep.c[]
  4061. * link:buildroot_packages/kernel_modules/buildroot_dep2.c[]
  4062. Removal also removes required modules that have zero usage count:
  4063. ....
  4064. modprobe -r buildroot_dep2
  4065. ....
  4066. `modprobe` uses information from the `modules.dep` file to decide the required dependencies. That file contains:
  4067. ....
  4068. extra/buildroot_dep2.ko: extra/buildroot_dep.ko
  4069. ....
  4070. Bibliography:
  4071. * https://askubuntu.com/questions/20070/whats-the-difference-between-insmod-and-modprobe
  4072. * https://stackoverflow.com/questions/22891705/whats-the-difference-between-insmod-and-modprobe
  4073. ==== MODULE_INFO
  4074. Module metadata is stored on module files at compile time. Some of the fields can be retrieved through the `THIS_MODULE` `struct module`:
  4075. ....
  4076. insmod module_info.ko
  4077. ....
  4078. Dmesg output:
  4079. ....
  4080. name = module_info
  4081. version = 1.0
  4082. ....
  4083. Source: link:kernel_modules/module_info.c[]
  4084. Some of those are also present on sysfs:
  4085. ....
  4086. cat /sys/module/module_info/version
  4087. ....
  4088. Output:
  4089. ....
  4090. 1.0
  4091. ....
  4092. And we can also observe them with the `modinfo` command line utility:
  4093. ....
  4094. modinfo module_info.ko
  4095. ....
  4096. sample output:
  4097. ....
  4098. filename: module_info.ko
  4099. license: GPL
  4100. version: 1.0
  4101. srcversion: AF3DE8A8CFCDEB6B00E35B6
  4102. depends:
  4103. vermagic: 4.17.0 SMP mod_unload modversions
  4104. ....
  4105. Module information is stored in a special `.modinfo` section of the ELF file:
  4106. ....
  4107. ./run-toolchain readelf -- -SW "$(./getvar kernel_modules_build_subdir)/module_info.ko"
  4108. ....
  4109. contains:
  4110. ....
  4111. [ 5] .modinfo PROGBITS 0000000000000000 0000d8 000096 00 A 0 0 8
  4112. ....
  4113. and:
  4114. ....
  4115. ./run-toolchain readelf -- -x .modinfo "$(./getvar kernel_modules_build_subdir)/module_info.ko"
  4116. ....
  4117. gives:
  4118. ....
  4119. 0x00000000 6c696365 6e73653d 47504c00 76657273 license=GPL.vers
  4120. 0x00000010 696f6e3d 312e3000 61736466 3d717765 ion=1.0.asdf=qwe
  4121. 0x00000020 72000000 00000000 73726376 65727369 r.......srcversi
  4122. 0x00000030 6f6e3d41 46334445 38413843 46434445 on=AF3DE8A8CFCDE
  4123. 0x00000040 42364230 30453335 42360000 00000000 B6B00E35B6......
  4124. 0x00000050 64657065 6e64733d 006e616d 653d6d6f depends=.name=mo
  4125. 0x00000060 64756c65 5f696e66 6f007665 726d6167 dule_info.vermag
  4126. 0x00000070 69633d34 2e31372e 3020534d 50206d6f ic=4.17.0 SMP mo
  4127. 0x00000080 645f756e 6c6f6164 206d6f64 76657273 d_unload modvers
  4128. 0x00000090 696f6e73 2000 ions .
  4129. ....
  4130. I think a dedicated section is used to allow the Linux kernel and command line tools to easily parse that information from the ELF file as we've done with `readelf`.
  4131. Bibliography:
  4132. * https://stackoverflow.com/questions/19467150/significance-of-this-module-in-linux-driver/49812248#49812248
  4133. * https://stackoverflow.com/questions/4839024/how-to-find-the-version-of-a-compiled-kernel-module/42556565#42556565
  4134. * https://unix.stackexchange.com/questions/238167/how-to-understand-the-modinfo-output
  4135. ==== vermagic
  4136. Vermagic is a magic string present in the kernel and on <<module_info>> of kernel modules. It is used to verify that the kernel module was compiled against a compatible kernel version and relevant configuration:
  4137. ....
  4138. insmod vermagic.ko
  4139. ....
  4140. Possible dmesg output:
  4141. ....
  4142. VERMAGIC_STRING = 4.17.0 SMP mod_unload modversions
  4143. ....
  4144. Source: link:kernel_modules/vermagic.c[]
  4145. If we artificially create a mismatch with `MODULE_INFO(vermagic`, the insmod fails with:
  4146. ....
  4147. insmod: can't insert 'vermagic_fail.ko': invalid module format
  4148. ....
  4149. and `dmesg` says the expected and found vermagic found:
  4150. ....
  4151. vermagic_fail: version magic 'asdfqwer' should be '4.17.0 SMP mod_unload modversions '
  4152. ....
  4153. Source: link:kernel_modules/vermagic_fail.c[]
  4154. The kernel's vermagic is defined based on compile time configurations at https://github.com/torvalds/linux/blob/v4.17/include/linux/vermagic.h#L35[include/linux/vermagic.h]:
  4155. ....
  4156. #define VERMAGIC_STRING \
  4157. UTS_RELEASE " " \
  4158. MODULE_VERMAGIC_SMP MODULE_VERMAGIC_PREEMPT \
  4159. MODULE_VERMAGIC_MODULE_UNLOAD MODULE_VERMAGIC_MODVERSIONS \
  4160. MODULE_ARCH_VERMAGIC \
  4161. MODULE_RANDSTRUCT_PLUGIN
  4162. ....
  4163. The `SMP` part of the string for example is defined on the same file based on the value of `CONFIG_SMP`:
  4164. ....
  4165. #ifdef CONFIG_SMP
  4166. #define MODULE_VERMAGIC_SMP "SMP "
  4167. #else
  4168. #define MODULE_VERMAGIC_SMP ""
  4169. ....
  4170. TODO how to get the vermagic from running kernel from userland? https://lists.kernelnewbies.org/pipermail/kernelnewbies/2012-October/006306.html
  4171. <<kmod-modprobe>> has a flag to skip the vermagic check:
  4172. ....
  4173. --force-modversion
  4174. ....
  4175. This option just strips `modversion` information from the module before loading, so it is not a kernel feature.
  4176. ==== init_module
  4177. `init_module` and `cleanup_module` are an older alternative to the `module_init` and `module_exit` macros:
  4178. ....
  4179. insmod init_module.ko
  4180. rmmod init_module
  4181. ....
  4182. Dmesg output:
  4183. ....
  4184. init_module
  4185. cleanup_module
  4186. ....
  4187. Source: link:kernel_modules/init_module.c[]
  4188. TODO why were `module_init` and `module_exit` created? https://stackoverflow.com/questions/3218320/what-is-the-difference-between-module-init-and-init-module-in-a-linux-kernel-mod
  4189. ==== Floating point in kernel modules
  4190. It is generally hard / impossible to use floating point operations in the kernel. TODO understand details.
  4191. A quick (x86-only for now because lazy) example is shown at: link:kernel_modules/float.c[]
  4192. Usage:
  4193. ....
  4194. insmod float.ko myfloat=1 enable_fpu=1
  4195. ....
  4196. We have to call: `kernel_fpu_begin()` before starting FPU operations, and `kernel_fpu_end()` when we are done. This particular example however did not blow up without it at lkmc 7f917af66b17373505f6c21d75af9331d624b3a9 + 1:
  4197. ....
  4198. insmod float.ko myfloat=1 enable_fpu=0
  4199. ....
  4200. The v5.1 documentation under https://github.com/cirosantilli/linux/blob/v5.1/arch/x86/include/asm/fpu/api.h#L15[arch/x86/include/asm/fpu/api.h] reads:
  4201. ....
  4202. * Use kernel_fpu_begin/end() if you intend to use FPU in kernel context. It
  4203. * disables preemption so be careful if you intend to use it for long periods
  4204. * of time.
  4205. ....
  4206. The example sets in the link:kernel_modules/Makefile[]:
  4207. ....
  4208. CFLAGS_REMOVE_float.o += -mno-sse -mno-sse2
  4209. ....
  4210. to avoid:
  4211. ....
  4212. error: SSE register return with SSE disabled
  4213. ....
  4214. We found those flags with `./build-modules --verbose`.
  4215. Bibliography:
  4216. * https://stackoverflow.com/questions/13886338/use-of-floating-point-in-the-linux-kernel
  4217. * https://stackoverflow.com/questions/15883947/why-am-i-able-to-perform-floating-point-operations-inside-a-linux-kernel-module/47056242
  4218. * https://stackoverflow.com/questions/1556142/sse-register-return-with-sse-disabled
  4219. === Kernel panic and oops
  4220. To test out kernel panics and oops in controlled circumstances, try out the modules:
  4221. ....
  4222. insmod panic.ko
  4223. insmod oops.ko
  4224. ....
  4225. Source:
  4226. * link:kernel_modules/panic.c[]
  4227. * link:kernel_modules/oops.c[]
  4228. A panic can also be generated with:
  4229. ....
  4230. echo c > /proc/sysrq-trigger
  4231. ....
  4232. Panic vs oops: https://unix.stackexchange.com/questions/91854/whats-the-difference-between-a-kernel-oops-and-a-kernel-panic
  4233. How to generate them:
  4234. * https://unix.stackexchange.com/questions/66197/how-to-cause-kernel-panic-with-a-single-command
  4235. * https://stackoverflow.com/questions/23484147/generate-kernel-oops-or-crash-in-the-code
  4236. When a panic happens, <<linux-kernel-magic-keys,`Shift-PgUp`>> does not work as it normally does, and it is hard to get the logs if on are on <<qemu-graphic-mode>>:
  4237. * https://superuser.com/questions/848412/scrolling-up-the-failed-screen-with-kernel-panic
  4238. * https://superuser.com/questions/269228/write-qemu-booting-virtual-machine-output-to-a-file
  4239. * http://www.reactos.org/wiki/QEMU#Redirect_to_a_file
  4240. ==== Kernel panic
  4241. On panic, the kernel dies, and so does our terminal.
  4242. The panic trace looks like:
  4243. ....
  4244. panic: loading out-of-tree module taints kernel.
  4245. panic myinit
  4246. Kernel panic - not syncing: hello panic
  4247. CPU: 0 PID: 53 Comm: insmod Tainted: G O 4.16.0 #6
  4248. Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS rel-1.11.0-0-g63451fca13-prebuilt.qemu-project.org 04/01/2014
  4249. Call Trace:
  4250. dump_stack+0x7d/0xba
  4251. ? 0xffffffffc0000000
  4252. panic+0xda/0x213
  4253. ? printk+0x43/0x4b
  4254. ? 0xffffffffc0000000
  4255. myinit+0x1d/0x20 [panic]
  4256. do_one_initcall+0x3e/0x170
  4257. do_init_module+0x5b/0x210
  4258. load_module+0x2035/0x29d0
  4259. ? kernel_read_file+0x7d/0x140
  4260. ? SyS_finit_module+0xa8/0xb0
  4261. SyS_finit_module+0xa8/0xb0
  4262. do_syscall_64+0x6f/0x310
  4263. ? trace_hardirqs_off_thunk+0x1a/0x32
  4264. entry_SYSCALL_64_after_hwframe+0x42/0xb7
  4265. RIP: 0033:0x7ffff7b36206
  4266. RSP: 002b:00007fffffffeb78 EFLAGS: 00000206 ORIG_RAX: 0000000000000139
  4267. RAX: ffffffffffffffda RBX: 000000000000005c RCX: 00007ffff7b36206
  4268. RDX: 0000000000000000 RSI: 000000000069e010 RDI: 0000000000000003
  4269. RBP: 000000000069e010 R08: 00007ffff7ddd320 R09: 0000000000000000
  4270. R10: 00007ffff7ddd320 R11: 0000000000000206 R12: 0000000000000003
  4271. R13: 00007fffffffef4a R14: 0000000000000000 R15: 0000000000000000
  4272. Kernel Offset: disabled
  4273. ---[ end Kernel panic - not syncing: hello panic
  4274. ....
  4275. Notice how our panic message `hello panic` is visible at:
  4276. ....
  4277. Kernel panic - not syncing: hello panic
  4278. ....
  4279. ===== Kernel module stack trace to source line
  4280. The log shows which module each symbol belongs to if any, e.g.:
  4281. ....
  4282. myinit+0x1d/0x20 [panic]
  4283. ....
  4284. says that the function `myinit` is in the module `panic`.
  4285. To find the line that panicked, do:
  4286. ....
  4287. ./run-gdb
  4288. ....
  4289. and then:
  4290. ....
  4291. info line *(myinit+0x1d)
  4292. ....
  4293. which gives us the correct line:
  4294. ....
  4295. Line 7 of "/root/linux-kernel-module-cheat/out/kernel_modules/x86_64/kernel_modules/panic.c" starts at address 0xbf00001c <myinit+28> and ends at 0xbf00002c <myexit>.
  4296. ....
  4297. as explained at: https://stackoverflow.com/questions/8545931/using-gdb-to-convert-addresses-to-lines/27576029#27576029
  4298. The exact same thing can be done post mortem with:
  4299. ....
  4300. ./run-toolchain gdb -- \
  4301. -batch \
  4302. -ex 'info line *(myinit+0x1d)' \
  4303. "$(./getvar kernel_modules_build_subdir)/panic.ko" \
  4304. ;
  4305. ....
  4306. Related:
  4307. * https://stackoverflow.com/questions/6151538/addr2line-on-kernel-module
  4308. * https://stackoverflow.com/questions/13468286/how-to-read-understand-analyze-and-debug-a-linux-kernel-panic
  4309. ===== BUG_ON
  4310. Basically just calls `panic("BUG!")` for most archs.
  4311. ===== Exit emulator on panic
  4312. For testing purposes, it is very useful to quit the emulator automatically with exit status non zero in case of kernel panic, instead of just hanging forever.
  4313. ====== Exit QEMU on panic
  4314. Enabled by default with:
  4315. * `panic=-1` command line option which reboots the kernel immediately on panic, see: xref:reboot-on-panic[xrefstyle=full]
  4316. * QEMU `-no-reboot`, which makes QEMU exit when the guest tries to reboot
  4317. Also asked at https://unix.stackexchange.com/questions/443017/can-i-make-qemu-exit-with-failure-on-kernel-panic which also mentions the x86_64 `-device pvpanic`, but I don't see much advantage to it.
  4318. TODO neither method exits with exit status different from 0, so for now we are just grepping the logs for panic messages, which sucks.
  4319. One possibility that gets close would be to use <<gdb>> to break at the `panic` function, and then send a <<qemu-monitor-from-gdb>> `quit` command if that happens, but I don't see a way to exit with non-zero status to indicate error.
  4320. ====== Exit gem5 on panic
  4321. gem5 9048ef0ffbf21bedb803b785fb68f83e95c04db8 (January 2019) can detect panics automatically if the option `system.panic_on_panic` is on.
  4322. It parses kernel symbols and detecting when the PC reaches the address of the `panic` function. gem5 then prints to stdout:
  4323. ....
  4324. Kernel panic in simulated kernel
  4325. ....
  4326. and exits with status -6.
  4327. At gem5 ff52563a214c71fcd1e21e9f00ad839612032e3b (July 2018) behaviour was different, and just exited 0: https://www.mail-archive.com/gem5-users@gem5.org/msg15870.html TODO find fixing commit.
  4328. We enable the `system.panic_on_panic` option by default on `arm` and `aarch64`, which makes gem5 exit immediately in case of panic, which is awesome!
  4329. If we don't set `system.panic_on_panic`, then gem5 just hangs on an infinite guest loop.
  4330. TODO: why doesn't gem5 x86 ff52563a214c71fcd1e21e9f00ad839612032e3b support `system.panic_on_panic` as well? Trying to set `system.panic_on_panic` there fails with:
  4331. ....
  4332. tried to set or access non-existentobject parameter: panic_on_panic
  4333. ....
  4334. However, at that commit panic on x86 makes gem5 crash with:
  4335. ....
  4336. panic: i8042 "System reset" command not implemented.
  4337. ....
  4338. which is a good side effect of an unimplemented hardware feature, since the simulation actually stops.
  4339. The implementation of panic detection happens at: https://github.com/gem5/gem5/blob/1da285dfcc31b904afc27e440544d006aae25b38/src/arch/arm/linux/system.cc#L73
  4340. ....
  4341. kernelPanicEvent = addKernelFuncEventOrPanic<Linux::KernelPanicEvent>(
  4342. "panic", "Kernel panic in simulated kernel", dmesg_output);
  4343. ....
  4344. Here we see that the symbol `"panic"` for the `panic()` function is the one being tracked.
  4345. Related thread: https://stackoverflow.com/questions/56032347/is-there-a-way-to-identify-if-gem5-run-got-over-successfully
  4346. ===== Reboot on panic
  4347. Make the kernel reboot after n seconds after panic:
  4348. ....
  4349. echo 1 > /proc/sys/kernel/panic
  4350. ....
  4351. Can also be controlled with the `panic=` kernel boot parameter.
  4352. `0` to disable, `-1` to reboot immediately.
  4353. Bibliography:
  4354. * https://github.com/torvalds/linux/blob/v4.17/Documentation/admin-guide/kernel-parameters.txt#L2931
  4355. * https://unix.stackexchange.com/questions/29567/how-to-configure-the-linux-kernel-to-reboot-on-panic/29569#29569
  4356. ===== Panic trace show addresses instead of symbols
  4357. If `CONFIG_KALLSYMS=n`, then addresses are shown on traces instead of symbol plus offset.
  4358. In v4.16 it does not seem possible to configure that at runtime. GDB step debugging with:
  4359. ....
  4360. ./run --eval-after 'insmod dump_stack.ko' --gdb-wait --tmux-args dump_stack
  4361. ....
  4362. shows that traces are printed at `arch/x86/kernel/dumpstack.c`:
  4363. ....
  4364. static void printk_stack_address(unsigned long address, int reliable,
  4365. char *log_lvl)
  4366. {
  4367. touch_nmi_watchdog();
  4368. printk("%s %s%pB\n", log_lvl, reliable ? "" : "? ", (void *)address);
  4369. }
  4370. ....
  4371. and `%pB` is documented at `Documentation/core-api/printk-formats.rst`:
  4372. ....
  4373. If KALLSYMS are disabled then the symbol address is printed instead.
  4374. ....
  4375. I wasn't able do disable `CONFIG_KALLSYMS` to test this this out however, it is being selected by some other option? But I then used `make menuconfig` to see which options select it, and they were all off...
  4376. [[oops]]
  4377. ==== Kernel oops
  4378. On oops, the shell still lives after.
  4379. However we:
  4380. * leave the normal control flow, and `oops after` never gets printed: an interrupt is serviced
  4381. * cannot `rmmod oops` afterwards
  4382. It is possible to make `oops` lead to panics always with:
  4383. ....
  4384. echo 1 > /proc/sys/kernel/panic_on_oops
  4385. insmod oops.ko
  4386. ....
  4387. An oops stack trace looks like:
  4388. ....
  4389. BUG: unable to handle kernel NULL pointer dereference at 0000000000000000
  4390. IP: myinit+0x18/0x30 [oops]
  4391. PGD dccf067 P4D dccf067 PUD dcc1067 PMD 0
  4392. Oops: 0002 [#1] SMP NOPTI
  4393. Modules linked in: oops(O+)
  4394. CPU: 0 PID: 53 Comm: insmod Tainted: G O 4.16.0 #6
  4395. Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS rel-1.11.0-0-g63451fca13-prebuilt.qemu-project.org 04/01/2014
  4396. RIP: 0010:myinit+0x18/0x30 [oops]
  4397. RSP: 0018:ffffc900000d3cb0 EFLAGS: 00000282
  4398. RAX: 000000000000000b RBX: ffffffffc0000000 RCX: ffffffff81e3e3a8
  4399. RDX: 0000000000000001 RSI: 0000000000000086 RDI: ffffffffc0001033
  4400. RBP: ffffc900000d3e30 R08: 69796d2073706f6f R09: 000000000000013b
  4401. R10: ffffea0000373280 R11: ffffffff822d8b2d R12: 0000000000000000
  4402. R13: ffffffffc0002050 R14: ffffffffc0002000 R15: ffff88000dc934c8
  4403. FS: 00007ffff7ff66a0(0000) GS:ffff88000fc00000(0000) knlGS:0000000000000000
  4404. CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033
  4405. CR2: 0000000000000000 CR3: 000000000dcd2000 CR4: 00000000000006f0
  4406. Call Trace:
  4407. do_one_initcall+0x3e/0x170
  4408. do_init_module+0x5b/0x210
  4409. load_module+0x2035/0x29d0
  4410. ? SyS_finit_module+0xa8/0xb0
  4411. SyS_finit_module+0xa8/0xb0
  4412. do_syscall_64+0x6f/0x310
  4413. ? trace_hardirqs_off_thunk+0x1a/0x32
  4414. entry_SYSCALL_64_after_hwframe+0x42/0xb7
  4415. RIP: 0033:0x7ffff7b36206
  4416. RSP: 002b:00007fffffffeb78 EFLAGS: 00000206 ORIG_RAX: 0000000000000139
  4417. RAX: ffffffffffffffda RBX: 000000000000005c RCX: 00007ffff7b36206
  4418. RDX: 0000000000000000 RSI: 000000000069e010 RDI: 0000000000000003
  4419. RBP: 000000000069e010 R08: 00007ffff7ddd320 R09: 0000000000000000
  4420. R10: 00007ffff7ddd320 R11: 0000000000000206 R12: 0000000000000003
  4421. R13: 00007fffffffef4b R14: 0000000000000000 R15: 0000000000000000
  4422. Code: <c7> 04 25 00 00 00 00 00 00 00 00 e8 b2 33 09 c1 31 c0 c3 0f 1f 44
  4423. RIP: myinit+0x18/0x30 [oops] RSP: ffffc900000d3cb0
  4424. CR2: 0000000000000000
  4425. ---[ end trace 3cdb4e9d9842b503 ]---
  4426. ....
  4427. To find the line that oopsed, look at the `RIP` register:
  4428. ....
  4429. RIP: 0010:myinit+0x18/0x30 [oops]
  4430. ....
  4431. and then on GDB:
  4432. ....
  4433. ./run-gdb
  4434. ....
  4435. run
  4436. ....
  4437. info line *(myinit+0x18)
  4438. ....
  4439. which gives us the correct line:
  4440. ....
  4441. Line 7 of "/root/linux-kernel-module-cheat/out/kernel_modules/x86_64/kernel_modules/panic.c" starts at address 0xbf00001c <myinit+28> and ends at 0xbf00002c <myexit>.
  4442. ....
  4443. This-did not work on `arm` due to <<gdb-step-debug-kernel-module-arm>> so we need to either:
  4444. * <<gdb-module_init>>
  4445. * <<kernel-module-stack-trace-to-source-line>> post-mortem method
  4446. ==== dump_stack
  4447. The `dump_stack` function produces a stack trace much like panic and oops, but causes no problems and we return to the normal control flow, and can cleanly remove the module afterwards:
  4448. ....
  4449. insmod dump_stack.ko
  4450. ....
  4451. Source: link:kernel_modules/dump_stack.c[]
  4452. ==== WARN_ON
  4453. The `WARN_ON` macro basically just calls <<dump_stack,dump_stack>>.
  4454. One extra side effect is that we can make it also panic with:
  4455. ....
  4456. echo 1 > /proc/sys/kernel/panic_on_warn
  4457. insmod warn_on.ko
  4458. ....
  4459. Source: link:kernel_modules/warn_on.c[]
  4460. Can also be activated with the `panic_on_warn` boot parameter.
  4461. === Pseudo filesystems
  4462. Pseudo filesystems are filesystems that don't represent actual files in a hard disk, but rather allow us to do special operations on filesystem-related system calls.
  4463. What each pseudo-file does for each related system call does is defined by its <<file-operations>>.
  4464. Bibliography:
  4465. * https://superuser.com/questions/1198292/what-is-a-pseudo-file-system-in-linux
  4466. * https://en.wikipedia.org/wiki/Synthetic_file_system
  4467. ==== debugfs
  4468. Debugfs is the simplest pseudo filesystem to play around with:
  4469. ....
  4470. ./debugfs.sh
  4471. echo $?
  4472. ....
  4473. Outcome: the test passes:
  4474. ....
  4475. 0
  4476. ....
  4477. Sources:
  4478. * link:kernel_modules/debugfs.c[]
  4479. * link:rootfs_overlay/lkmc/debugfs.sh[]
  4480. Debugfs is made specifically to help test kernel stuff. Just mount, set <<file-operations>>, and we are done.
  4481. For this reason, it is the filesystem that we use whenever possible in our tests.
  4482. `debugfs.sh` explicitly mounts a debugfs at a custom location, but the most common mount point is `/sys/kernel/debug`.
  4483. This mount not done automatically by the kernel however: we, like most distros, do it from userland with our link:rootfs_overlay/etc/fstab[fstab].
  4484. Debugfs support requires the kernel to be compiled with `CONFIG_DEBUG_FS=y`.
  4485. Only the more basic file operations can be implemented in debugfs, e.g. `mmap` never gets called:
  4486. * https://patchwork.kernel.org/patch/9252557/
  4487. * https://github.com/torvalds/linux/blob/v4.9/fs/debugfs/file.c#L212
  4488. Bibliography: https://github.com/chadversary/debugfs-tutorial
  4489. ==== procfs
  4490. Procfs is just another fops entry point:
  4491. ....
  4492. ./procfs.sh
  4493. echo $?
  4494. ....
  4495. Outcome: the test passes:
  4496. ....
  4497. 0
  4498. ....
  4499. Procfs is a little less convenient than <<debugfs>>, but is more used in serious applications.
  4500. Procfs can run all system calls, including ones that debugfs can't, e.g. <<mmap>>.
  4501. Sources:
  4502. * link:kernel_modules/procfs.c[]
  4503. * link:rootfs_overlay/lkmc/procfs.sh[]
  4504. Bibliography:
  4505. * https://superuser.com/questions/619955/how-does-proc-work/1442571#1442571
  4506. * https://stackoverflow.com/questions/8516021/proc-create-example-for-kernel-module/18924359#18924359
  4507. [[proc-version]]
  4508. ===== /proc/version
  4509. Its data is shared with `uname()`, which is a <<posix,POSIX C>> function and has a Linux syscall to back it up.
  4510. Where the data comes from and how to modify it:
  4511. * https://unix.stackexchange.com/questions/136959/where-does-uname-get-its-information-from/485962#485962
  4512. * https://stackoverflow.com/questions/23424174/how-to-customize-or-remove-extra-linux-kernel-version-details-shown-at-boot
  4513. In this repo, leaking host information, and to make builds more reproducible, we are setting:
  4514. - user and date to dummy values with `KBUILD_BUILD_USER` and `KBUILD_BUILD_TIMESTAMP`
  4515. - hostname to the kernel git commit with `KBUILD_BUILD_HOST` and `KBUILD_BUILD_VERSION`
  4516. A sample result is:
  4517. ....
  4518. Linux version 4.19.0-dirty (lkmc@84df9525b0c27f3ebc2ebb1864fa62a97fdedb7d) (gcc version 6.4.0 (Buildroot 2018.05-00002-gbc60382b8f)) #1 SMP Thu Jan 1 00:00:00 UTC 1970
  4519. ....
  4520. ==== sysfs
  4521. Sysfs is more restricted than <<procfs>>, as it does not take an arbitrary `file_operations`:
  4522. ....
  4523. ./sysfs.sh
  4524. echo $?
  4525. ....
  4526. Outcome: the test passes:
  4527. ....
  4528. 0
  4529. ....
  4530. Sources:
  4531. * link:kernel_modules/sysfs.c[]
  4532. * link:rootfs_overlay/lkmc/sysfs.sh[]
  4533. Vs procfs:
  4534. * https://unix.stackexchange.com/questions/4884/what-is-the-difference-between-procfs-and-sysfs/382315#382315
  4535. * https://stackoverflow.com/questions/37237835/how-to-attach-file-operations-to-sysfs-attribute-in-platform-driver
  4536. * https://serverfault.com/questions/65261/linux-proc-sys-kernel-vs-sys-kernel
  4537. You basically can only do `open`, `close`, `read`, `write`, and `lseek` on sysfs files.
  4538. It is similar to a <<seq_file>> file operation, except that write is also implemented.
  4539. TODO: what are those `kobject` structs? Make a more complex example that shows what they can do.
  4540. Bibliography:
  4541. * https://github.com/t3rm1n4l/kern-dev-tutorial/blob/1f036ef40fc4378f5c8d2842e55bcea7c6f8894a/05-sysfs/sysfs.c
  4542. * https://www.kernel.org/doc/Documentation/kobject.txt
  4543. * https://www.quora.com/What-are-kernel-objects-Kobj
  4544. * http://www.makelinux.net/ldd3/chp-14-sect-1
  4545. * https://www.win.tue.nl/~aeb/linux/lk/lk-13.html
  4546. ==== Character devices
  4547. Character devices can have arbitrary <<file-operations>> associated to them:
  4548. ....
  4549. ./character_device.sh
  4550. echo $?
  4551. ....
  4552. Outcome: the test passes:
  4553. ....
  4554. 0
  4555. ....
  4556. Sources:
  4557. * link:rootfs_overlay/lkmc/character_device.sh[]
  4558. * link:rootfs_overlay/lkmc/mknoddev.sh[]
  4559. * link:kernel_modules/character_device.c[]
  4560. Unlike <<procfs>> entires, character device files are created with userland `mknod` or `mknodat` syscalls:
  4561. ....
  4562. mknod </dev/path_to_dev> c <major> <minor>
  4563. ....
  4564. Intuitively, for physical devices like keyboards, the major number maps to which driver, and the minor number maps to which device it is.
  4565. A single driver can drive multiple compatible devices.
  4566. The major and minor numbers can be observed with:
  4567. ....
  4568. ls -l /dev/urandom
  4569. ....
  4570. Output:
  4571. ....
  4572. crw-rw-rw- 1 root root 1, 9 Jun 29 05:45 /dev/urandom
  4573. ....
  4574. which means:
  4575. * `c` (first letter): this is a character device. Would be `b` for a block device.
  4576. * `1, 9`: the major number is `1`, and the minor `9`
  4577. To avoid device number conflicts when registering the driver we:
  4578. * ask the kernel to allocate a free major number for us with: `register_chrdev(0`
  4579. * find ouf which number was assigned by grepping `/proc/devices` for the kernel module name
  4580. Bibliography: https://unix.stackexchange.com/questions/37829/understanding-character-device-or-character-special-files/371758#371758
  4581. ===== Automatically create character device file on insmod
  4582. And also destroy it on `rmmod`:
  4583. ....
  4584. ./character_device_create.sh
  4585. echo $?
  4586. ....
  4587. Outcome: the test passes:
  4588. ....
  4589. 0
  4590. ....
  4591. Sources:
  4592. * link:kernel_modules/character_device_create.c[]
  4593. * link:rootfs_overlay/lkmc/character_device_create.sh[]
  4594. Bibliography: https://stackoverflow.com/questions/5970595/how-to-create-a-device-node-from-the-init-module-code-of-a-linux-kernel-module/45531867#45531867
  4595. === Pseudo files
  4596. ==== File operations
  4597. File operations are the main method of userland driver communication. `struct file_operations` determines what the kernel will do on filesystem system calls of <<pseudo-filesystems>>.
  4598. This example illustrates the most basic system calls: `open`, `read`, `write`, `close` and `lseek`:
  4599. ....
  4600. ./fops.sh
  4601. echo $?
  4602. ....
  4603. Outcome: the test passes:
  4604. ....
  4605. 0
  4606. ....
  4607. Sources:
  4608. * link:kernel_modules/fops.c[]
  4609. * link:rootfs_overlay/lkmc/fops.sh[]
  4610. Then give this a try:
  4611. ....
  4612. sh -x ./fops.sh
  4613. ....
  4614. We have put printks on each fop, so this allows you to see which system calls are being made for each command.
  4615. No, there no official documentation: https://stackoverflow.com/questions/15213932/what-are-the-struct-file-operations-arguments
  4616. ==== seq_file
  4617. Writing trivial read <<file-operations>> is repetitive and error prone. The `seq_file` API makes the process much easier for those trivial cases:
  4618. ....
  4619. ./seq_file.sh
  4620. echo $?
  4621. ....
  4622. Outcome: the test passes:
  4623. ....
  4624. 0
  4625. ....
  4626. Sources:
  4627. * link:kernel_modules/seq_file.c[]
  4628. * link:rootfs_overlay/lkmc/seq_file.sh[]
  4629. In this example we create a debugfs file that behaves just like a file that contains:
  4630. ....
  4631. 0
  4632. 1
  4633. 2
  4634. ....
  4635. However, we only store a single integer in memory and calculate the file on the fly in an iterator fashion.
  4636. `seq_file` does not provide `write`: https://stackoverflow.com/questions/30710517/how-to-implement-a-writable-proc-file-by-using-seq-file-in-a-driver-module
  4637. Bibliography:
  4638. * https://github.com/torvalds/linux/blob/v4.17/Documentation/filesystems/seq_file.txt[Documentation/filesystems/seq_file.txt]
  4639. * https://stackoverflow.com/questions/25399112/how-to-use-a-seq-file-in-linux-modules
  4640. ===== seq_file single_open
  4641. If you have the entire read output upfront, `single_open` is an even more convenient version of <<seq_file>>:
  4642. ....
  4643. ./seq_file.sh
  4644. echo $?
  4645. ....
  4646. Outcome: the test passes:
  4647. ....
  4648. 0
  4649. ....
  4650. Sources:
  4651. * link:kernel_modules/seq_file_single_open.c[]
  4652. * link:rootfs_overlay/lkmc/seq_file_single_open.sh[]
  4653. This example produces a debugfs file that behaves like a file that contains:
  4654. ....
  4655. ab
  4656. cd
  4657. ....
  4658. ==== poll
  4659. The poll system call allows an user process to do a non-busy wait on a kernel event:
  4660. ....
  4661. ./poll.sh
  4662. ....
  4663. Outcome: `jiffies` gets printed to stdout every second from userland.
  4664. Sources:
  4665. * link:kernel_modules/poll.c[]
  4666. * link:rootfs_overlay/lkmc/poll.sh[]
  4667. Typically, we are waiting for some hardware to make some piece of data available available to the kernel.
  4668. The hardware notifies the kernel that the data is ready with an interrupt.
  4669. To simplify this example, we just fake the hardware interrupts with a <<kthread>> that sleeps for a second in an infinite loop.
  4670. Bibliography: https://stackoverflow.com/questions/30035776/how-to-add-poll-function-to-the-kernel-module-code/44645336#44645336
  4671. ==== ioctl
  4672. The `ioctl` system call is the best way to pass an arbitrary number of parameters to the kernel in a single go:
  4673. ....
  4674. ./ioctl.sh
  4675. echo $?
  4676. ....
  4677. Outcome: the test passes:
  4678. ....
  4679. 0
  4680. ....
  4681. Sources:
  4682. * link:kernel_modules/ioctl.c[]
  4683. * link:lkmc/ioctl.h[]
  4684. * link:userland/kernel_modules/ioctl.c[]
  4685. * link:rootfs_overlay/lkmc/ioctl.sh[]
  4686. `ioctl` is one of the most important methods of communication with real device drivers, which often take several fields as input.
  4687. `ioctl` takes as input:
  4688. * an integer `request` : it usually identifies what type of operation we want to do on this call
  4689. * an untyped pointer to memory: can be anything, but is typically a pointer to a `struct`
  4690. +
  4691. The type of the `struct` often depends on the `request` input
  4692. +
  4693. This `struct` is defined on a uapi-style C header that is used both to compile the kernel module and the userland executable.
  4694. +
  4695. The fields of this `struct` can be thought of as arbitrary input parameters.
  4696. And the output is:
  4697. * an integer return value. `man ioctl` documents:
  4698. +
  4699. ____
  4700. Usually, on success zero is returned. A few `ioctl()` requests use the return value as an output parameter and return a nonnegative value on success. On error, -1 is returned, and errno is set appropriately.
  4701. ____
  4702. * the input pointer data may be overwritten to contain arbitrary output
  4703. Bibliography:
  4704. * https://stackoverflow.com/questions/2264384/how-do-i-use-ioctl-to-manipulate-my-kernel-module/44613896#44613896
  4705. * https://askubuntu.com/questions/54239/problem-with-ioctl-in-a-simple-kernel-module/926675#926675
  4706. ==== mmap
  4707. The `mmap` system call allows us to share memory between user and kernel space without copying:
  4708. ....
  4709. ./mmap.sh
  4710. echo $?
  4711. ....
  4712. Outcome: the test passes:
  4713. ....
  4714. 0
  4715. ....
  4716. Sources:
  4717. * link:kernel_modules/mmap.c[]
  4718. * link:userland/kernel_modules/mmap.c[]
  4719. * link:rootfs_overlay/lkmc/mmap.sh[]
  4720. In this example, we make a tiny 4 byte kernel buffer available to user-space, and we then modify it on userspace, and check that the kernel can see the modification.
  4721. `mmap`, like most more complex <<file-operations>>, does not work with <<debugfs>> as of 4.9, so we use a <<procfs>> file for it.
  4722. Example adapted from: https://coherentmusings.wordpress.com/2014/06/10/implementing-mmap-for-transferring-data-from-user-space-to-kernel-space/
  4723. Bibliography:
  4724. * https://stackoverflow.com/questions/10760479/mmap-kernel-buffer-to-user-space/10770582#10770582
  4725. * https://stackoverflow.com/questions/1623008/allocating-memory-for-user-space-from-kernel-thread
  4726. * https://stackoverflow.com/questions/6967933/mmap-mapping-in-user-space-a-kernel-buffer-allocated-with-kmalloc
  4727. * https://github.com/jeremytrimble/ezdma
  4728. * https://github.com/simonjhall/dma
  4729. * https://github.com/ikwzm/udmabuf
  4730. ==== Anonymous inode
  4731. Anonymous inodes allow getting multiple file descriptors from a single filesystem entry, which reduces namespace pollution compared to creating multiple device files:
  4732. ....
  4733. ./anonymous_inode.sh
  4734. echo $?
  4735. ....
  4736. Outcome: the test passes:
  4737. ....
  4738. 0
  4739. ....
  4740. Sources:
  4741. * link:kernel_modules/anonymous_inode.c[]
  4742. * link:lkmc/anonymous_inode.h[]
  4743. * link:userland/kernel_modules/anonymous_inode.c[]
  4744. * link:rootfs_overlay/lkmc/anonymous_inode.sh[]
  4745. This example gets an anonymous inode via <<ioctl>> from a debugfs entry by using `anon_inode_getfd`.
  4746. Reads to that inode return the sequence: `1`, `10`, `100`, ... `10000000`, `1`, `100`, ...
  4747. Bibliography: https://stackoverflow.com/questions/4508998/what-is-an-anonymous-inode-in-linux/44388030#44388030
  4748. ==== netlink sockets
  4749. Netlink sockets offer a socket API for kernel / userland communication:
  4750. ....
  4751. ./netlink.sh
  4752. echo $?
  4753. ....
  4754. Outcome: the test passes:
  4755. ....
  4756. 0
  4757. ....
  4758. Sources:
  4759. * link:kernel_modules/netlink.c[]
  4760. * link:lkmc/netlink.h[]
  4761. * link:userland/kernel_modules/netlink.c[]
  4762. * link:rootfs_overlay/lkmc/netlink.sh[]
  4763. Launch multiple user requests in parallel to stress our socket:
  4764. ....
  4765. insmod netlink.ko sleep=1
  4766. for i in `seq 16`; do ./netlink.out & done
  4767. ....
  4768. TODO: what is the advantage over `read`, `write` and `poll`? https://stackoverflow.com/questions/16727212/how-netlink-socket-in-linux-kernel-is-different-from-normal-polling-done-by-appl
  4769. Bibliography:
  4770. * https://stackoverflow.com/questions/3299386/how-to-use-netlink-socket-to-communicate-with-a-kernel-module
  4771. * https://en.wikipedia.org/wiki/Netlink
  4772. === kthread
  4773. Kernel threads are managed exactly like userland threads; they also have a backing `task_struct`, and are scheduled with the same mechanism:
  4774. ....
  4775. insmod kthread.ko
  4776. ....
  4777. Source: link:kernel_modules/kthread.c[]
  4778. Outcome: dmesg counts from `0` to `9` once every second infinitely many times:
  4779. ....
  4780. 0
  4781. 1
  4782. 2
  4783. ...
  4784. 8
  4785. 9
  4786. 0
  4787. 1
  4788. 2
  4789. ...
  4790. ....
  4791. The count stops when we `rmmod`:
  4792. ....
  4793. rmmod kthread
  4794. ....
  4795. The sleep is done with `usleep_range`, see: xref:sleep[xrefstyle=full].
  4796. Bibliography:
  4797. * https://stackoverflow.com/questions/10177641/proper-way-of-handling-threads-in-kernel
  4798. * https://stackoverflow.com/questions/4084708/how-to-wait-for-a-linux-kernel-thread-kthreadto-exit
  4799. ==== kthreads
  4800. Let's launch two threads and see if they actually run in parallel:
  4801. ....
  4802. insmod kthreads.ko
  4803. ....
  4804. Source: link:kernel_modules/kthreads.c[]
  4805. Outcome: two threads count to dmesg from `0` to `9` in parallel.
  4806. Each line has output of form:
  4807. ....
  4808. <thread_id> <count>
  4809. ....
  4810. Possible very likely outcome:
  4811. ....
  4812. 1 0
  4813. 2 0
  4814. 1 1
  4815. 2 1
  4816. 1 2
  4817. 2 2
  4818. 1 3
  4819. 2 3
  4820. ....
  4821. The threads almost always interleaved nicely, thus confirming that they are actually running in parallel.
  4822. ==== sleep
  4823. Count to dmesg every one second from `0` up to `n - 1`:
  4824. ....
  4825. insmod sleep.ko n=5
  4826. ....
  4827. Source: link:kernel_modules/sleep.c[]
  4828. The sleep is done with a call to https://github.com/torvalds/linux/blob/v4.17/kernel/time/timer.c#L1984[`usleep_range`] directly inside `module_init` for simplicity.
  4829. Bibliography:
  4830. * https://stackoverflow.com/questions/15994603/how-to-sleep-in-the-linux-kernel/44153288#44153288
  4831. * https://github.com/torvalds/linux/blob/v4.17/Documentation/timers/timers-howto.txt
  4832. ==== Workqueues
  4833. A more convenient front-end for <<kthread>>:
  4834. ....
  4835. insmod workqueue_cheat.ko
  4836. ....
  4837. Outcome: count from `0` to `9` infinitely many times
  4838. Stop counting:
  4839. ....
  4840. rmmod workqueue_cheat
  4841. ....
  4842. Source: link:kernel_modules/workqueue_cheat.c[]
  4843. The workqueue thread is killed after the worker function returns.
  4844. We can't call the module just `workqueue.c` because there is already a built-in with that name: https://unix.stackexchange.com/questions/364956/how-can-insmod-fail-with-kernel-module-is-already-loaded-even-is-lsmod-does-not
  4845. Bibliography: https://github.com/torvalds/linux/blob/v4.17/Documentation/core-api/workqueue.rst
  4846. ===== Workqueue from workqueue
  4847. Count from `0` to `9` every second infinitely many times by scheduling a new work item from a work item:
  4848. ....
  4849. insmod work_from_work.ko
  4850. ....
  4851. Stop:
  4852. ....
  4853. rmmod work_from_work
  4854. ....
  4855. The sleep is done indirectly through: https://github.com/torvalds/linux/blob/v4.17/include/linux/workqueue.h#L522[`queue_delayed_work`], which waits the specified time before scheduling the work.
  4856. Source: link:kernel_modules/work_from_work.c[]
  4857. ==== schedule
  4858. Let's block the entire kernel! Yay:
  4859. .....
  4860. ./run --eval-after 'dmesg -n 1;insmod schedule.ko schedule=0'
  4861. .....
  4862. Outcome: the system hangs, the only way out is to kill the VM.
  4863. Source: link:kernel_modules/schedule.c[]
  4864. kthreads only allow interrupting if you call `schedule()`, and the `schedule=0` <<kernel-module-parameters,kernel module parameter>> turns it off.
  4865. Sleep functions like `usleep_range` also end up calling schedule.
  4866. If we allow `schedule()` to be called, then the system becomes responsive:
  4867. .....
  4868. ./run --eval-after 'dmesg -n 1;insmod schedule.ko schedule=1'
  4869. .....
  4870. and we can observe the counting with:
  4871. ....
  4872. dmesg -w
  4873. ....
  4874. The system also responds if we <<number-of-cores,add another core>>:
  4875. ....
  4876. ./run --cpus 2 --eval-after 'dmesg -n 1;insmod schedule.ko schedule=0'
  4877. ....
  4878. ==== Wait queues
  4879. Wait queues are a way to make a thread sleep until an event happens on the queue:
  4880. ....
  4881. insmod wait_queue.c
  4882. ....
  4883. Dmesg output:
  4884. ....
  4885. 0 0
  4886. 1 0
  4887. 2 0
  4888. # Wait one second.
  4889. 0 1
  4890. 1 1
  4891. 2 1
  4892. # Wait one second.
  4893. 0 2
  4894. 1 2
  4895. 2 2
  4896. ...
  4897. ....
  4898. Stop the count:
  4899. ....
  4900. rmmod wait_queue
  4901. ....
  4902. Source: link:kernel_modules/wait_queue.c[]
  4903. This example launches three threads:
  4904. * one thread generates events every with https://github.com/torvalds/linux/blob/v4.17/include/linux/wait.h#L195[`wake_up`]
  4905. * the other two threads wait for that with https://github.com/torvalds/linux/blob/v4.17/include/linux/wait.h#L286[`wait_event`], and print a dmesg when it happens.
  4906. +
  4907. The `wait_event` macro works a bit like:
  4908. +
  4909. ....
  4910. while (!cond)
  4911. sleep_until_event
  4912. ....
  4913. === Timers
  4914. Count from `0` to `9` infinitely many times in 1 second intervals using timers:
  4915. ....
  4916. insmod timer.ko
  4917. ....
  4918. Stop counting:
  4919. ....
  4920. rmmod timer
  4921. ....
  4922. Source: link:kernel_modules/timer.c[]
  4923. Timers are callbacks that run when an interrupt happens, from the interrupt context itself.
  4924. Therefore they produce more accurate timing than thread scheduling, which is more complex, but you can't do too much work inside of them.
  4925. Bibliography:
  4926. * https://stackoverflow.com/questions/10812858/timers-in-linux-device-drivers
  4927. * https://gist.github.com/yagihiro/310149
  4928. === IRQ
  4929. ==== irq.ko
  4930. Brute force monitor every shared interrupt that will accept us:
  4931. ....
  4932. ./run --eval-after 'insmod irq.ko' --graphic
  4933. ....
  4934. Source: link:kernel_modules/irq.c[].
  4935. Now try the following:
  4936. * press a keyboard key and then release it after a few seconds
  4937. * press a mouse key, and release it after a few seconds
  4938. * move the mouse around
  4939. Outcome: dmesg shows which IRQ was fired for each action through messages of type:
  4940. ....
  4941. handler irq = 1 dev = 250
  4942. ....
  4943. `dev` is the character device for the module and never changes, as can be confirmed by:
  4944. ....
  4945. grep lkmc_irq /proc/devices
  4946. ....
  4947. The IRQs that we observe are:
  4948. * `1` for keyboard press and release.
  4949. +
  4950. If you hold the key down for a while, it starts firing at a constant rate. So this happens at the hardware level!
  4951. * `12` mouse actions
  4952. This only works if for IRQs for which the other handlers are registered as `IRQF_SHARED`.
  4953. We can see which ones are those, either via dmesg messages of type:
  4954. ....
  4955. genirq: Flags mismatch irq 0. 00000080 (myirqhandler0) vs. 00015a00 (timer)
  4956. request_irq irq = 0 ret = -16
  4957. request_irq irq = 1 ret = 0
  4958. ....
  4959. which indicate that `0` is not, but `1` is, or with:
  4960. ....
  4961. cat /proc/interrupts
  4962. ....
  4963. which shows:
  4964. ....
  4965. 0: 31 IO-APIC 2-edge timer
  4966. 1: 9 IO-APIC 1-edge i8042, myirqhandler0
  4967. ....
  4968. so only `1` has `myirqhandler0` attached but not `0`.
  4969. The <<qemu-monitor>> also has some interrupt statistics for x86_64:
  4970. ....
  4971. ./qemu-monitor info irq
  4972. ....
  4973. TODO: properly understand how each IRQ maps to what number.
  4974. ==== dummy-irq
  4975. The Linux kernel v4.16 mainline also has a `dummy-irq` module at `drivers/misc/dummy-irq.c` for monitoring a single IRQ.
  4976. We build it by default with:
  4977. ....
  4978. CONFIG_DUMMY_IRQ=m
  4979. ....
  4980. And then you can do
  4981. ....
  4982. ./run --graphic
  4983. ....
  4984. and in guest:
  4985. ....
  4986. modprobe dummy-irq irq=1
  4987. ....
  4988. Outcome: when you click a key on the keyboard, dmesg shows:
  4989. ....
  4990. dummy-irq: interrupt occurred on IRQ 1
  4991. ....
  4992. However, this module is intended to fire only once as can be seen from its source:
  4993. ....
  4994. static int count = 0;
  4995. if (count == 0) {
  4996. printk(KERN_INFO "dummy-irq: interrupt occurred on IRQ %d\n",
  4997. irq);
  4998. count++;
  4999. }
  5000. ....
  5001. and furthermore interrupt `1` and `12` happen immediately TODO why, were they somehow pending?
  5002. So so see something interesting, you need to monitor an interrupt that is more rare than the keyboard, e.g. <<platform_device>>.
  5003. ==== /proc/interrupts
  5004. In the guest with <<qemu-graphic-mode>>:
  5005. ....
  5006. watch -n 1 cat /proc/interrupts
  5007. ....
  5008. Then see how clicking the mouse and keyboard affect the interrupt counts.
  5009. This confirms that:
  5010. * 1: keyboard
  5011. * 12: mouse click and drags
  5012. The module also shows which handlers are registered for each IRQ, as we have observed at <<irq-ko>>
  5013. When in text mode, we can also observe interrupt line 4 with handler `ttyS0` increase continuously as IO goes through the UART.
  5014. === Kernel utility functions
  5015. https://github.com/torvalds/linux/blob/v4.17/Documentation/core-api/kernel-api.rst
  5016. ==== kstrto
  5017. Convert a string to an integer:
  5018. ....
  5019. ./kstrto.sh
  5020. echo $?
  5021. ....
  5022. Outcome: the test passes:
  5023. ....
  5024. 0
  5025. ....
  5026. Sources:
  5027. * link:kernel_modules/kstrto.c[]
  5028. * link:rootfs_overlay/lkmc/kstrto.sh[]
  5029. Bibliography: https://stackoverflow.com/questions/6139493/how-convert-char-to-int-in-linux-kernel/49811658#49811658
  5030. ==== virt_to_phys
  5031. Convert a virtual address to physical:
  5032. ....
  5033. insmod virt_to_phys.ko
  5034. cat /sys/kernel/debug/lkmc_virt_to_phys
  5035. ....
  5036. Source: link:kernel_modules/virt_to_phys.c[]
  5037. Sample output:
  5038. ....
  5039. *kmalloc_ptr = 0x12345678
  5040. kmalloc_ptr = ffff88000e169ae8
  5041. virt_to_phys(kmalloc_ptr) = 0xe169ae8
  5042. static_var = 0x12345678
  5043. &static_var = ffffffffc0002308
  5044. virt_to_phys(&static_var) = 0x40002308
  5045. ....
  5046. We can confirm that the `kmalloc_ptr` translation worked with:
  5047. ....
  5048. ./qemu-monitor 'xp 0xe169ae8'
  5049. ....
  5050. which reads four bytes from a given physical address, and gives the expected:
  5051. ....
  5052. 000000000e169ae8: 0x12345678
  5053. ....
  5054. TODO it only works for kmalloc however, for the static variable:
  5055. ....
  5056. ./qemu-monitor 'xp 0x40002308'
  5057. ....
  5058. it gave a wrong value of `00000000`.
  5059. Bibliography:
  5060. * https://stackoverflow.com/questions/5748492/is-there-any-api-for-determining-the-physical-address-from-virtual-address-in-li/45128487#45128487
  5061. * https://stackoverflow.com/questions/39134990/mmap-of-dev-mem-fails-with-invalid-argument-for-virt-to-phys-address-but-addre/45127582#45127582
  5062. * https://stackoverflow.com/questions/43325205/can-we-use-virt-to-phys-for-user-space-memory-in-kernel-module
  5063. ===== Userland physical address experiments
  5064. Only tested in x86_64.
  5065. The Linux kernel exposes physical addresses to userland through:
  5066. * `/proc/<pid>/maps`
  5067. * `/proc/<pid>/pagemap`
  5068. * `/dev/mem`
  5069. In this section we will play with them.
  5070. First get a virtual address to play with:
  5071. ....
  5072. ./posix/virt_to_phys_test.out &
  5073. ....
  5074. Source: link:userland/posix/virt_to_phys_test.c[]
  5075. Sample output:
  5076. ....
  5077. vaddr 0x600800
  5078. pid 110
  5079. ....
  5080. The program:
  5081. * allocates a `volatile` variable and sets is value to `0x12345678`
  5082. * prints the virtual address of the variable, and the program PID
  5083. * runs a while loop until until the value of the variable gets mysteriously changed somehow, e.g. by nasty tinkerers like us
  5084. Then, translate the virtual address to physical using `/proc/<pid>/maps` and `/proc/<pid>/pagemap`:
  5085. ....
  5086. ./linux/virt_to_phys_user.out 110 0x600800
  5087. ....
  5088. Sample output physical address:
  5089. ....
  5090. 0x7c7b800
  5091. ....
  5092. Source: link:userland/linux/virt_to_phys_user.c[]
  5093. Now we can verify that `linux/virt_to_phys_user.out` gave the correct physical address in the following ways:
  5094. * <<qemu-xp>>
  5095. * <<dev-mem>>
  5096. Bibliography:
  5097. * https://stackoverflow.com/questions/17021214/decode-proc-pid-pagemap-entry/45126141#45126141
  5098. * https://stackoverflow.com/questions/6284810/proc-pid-pagemaps-and-proc-pid-maps-linux/45500208#45500208
  5099. ====== QEMU xp
  5100. The `xp` <<qemu-monitor>> command reads memory at a given physical address.
  5101. First launch `linux/virt_to_phys_user.out` as described at <<userland-physical-address-experiments>>.
  5102. On a second terminal, use QEMU to read the physical address:
  5103. ....
  5104. ./qemu-monitor 'xp 0x7c7b800'
  5105. ....
  5106. Output:
  5107. ....
  5108. 0000000007c7b800: 0x12345678
  5109. ....
  5110. Yes!!! We read the correct value from the physical address.
  5111. We could not find however to write to memory from the QEMU monitor, boring.
  5112. [[dev-mem]]
  5113. ====== /dev/mem
  5114. `/dev/mem` exposes access to physical addresses, and we use it through the convenient `devmem` BusyBox utility.
  5115. First launch `linux/virt_to_phys_user.out` as described at <<userland-physical-address-experiments>>.
  5116. Next, read from the physical address:
  5117. ....
  5118. devmem 0x7c7b800
  5119. ....
  5120. Possible output:
  5121. ....
  5122. Memory mapped at address 0x7ff7dbe01000.
  5123. Value at address 0X7C7B800 (0x7ff7dbe01800): 0x12345678
  5124. ....
  5125. which shows that the physical memory contains the expected value `0x12345678`.
  5126. `0x7ff7dbe01000` is a new virtual address that `devmem` maps to the physical address to be able to read from it.
  5127. Modify the physical memory:
  5128. ....
  5129. devmem 0x7c7b800 w 0x9abcdef0
  5130. ....
  5131. After one second, we see on the screen:
  5132. ....
  5133. i 9abcdef0
  5134. [1]+ Done ./posix/virt_to_phys_test.out
  5135. ....
  5136. so the value changed, and the `while` loop exited!
  5137. This example requires:
  5138. * `CONFIG_STRICT_DEVMEM=n`, otherwise `devmem` fails with:
  5139. +
  5140. ....
  5141. devmem: mmap: Operation not permitted
  5142. ....
  5143. * `nopat` kernel parameter
  5144. which we set by default.
  5145. Bibliography: https://stackoverflow.com/questions/11891979/how-to-access-mmaped-dev-mem-without-crashing-the-linux-kernel
  5146. ====== pagemap_dump.out
  5147. Dump the physical address of all pages mapped to a given process using `/proc/<pid>/maps` and `/proc/<pid>/pagemap`.
  5148. First launch `linux/virt_to_phys_user.out` as described at <<userland-physical-address-experiments>>. Suppose that the output was:
  5149. ....
  5150. # ./posix/virt_to_phys_test.out &
  5151. vaddr 0x601048
  5152. pid 63
  5153. # ./linux/virt_to_phys_user.out 63 0x601048
  5154. 0x1a61048
  5155. ....
  5156. Now obtain the page map for the process:
  5157. ....
  5158. ./linux/pagemap_dump.out 63
  5159. ....
  5160. Sample output excerpt:
  5161. ....
  5162. vaddr pfn soft-dirty file/shared swapped present library
  5163. 400000 1ede 0 1 0 1 ./posix/virt_to_phys_test.out
  5164. 600000 1a6f 0 0 0 1 ./posix/virt_to_phys_test.out
  5165. 601000 1a61 0 0 0 1 ./posix/virt_to_phys_test.out
  5166. 602000 2208 0 0 0 1 [heap]
  5167. 603000 220b 0 0 0 1 [heap]
  5168. 7ffff78ec000 1fd4 0 1 0 1 /lib/libuClibc-1.0.30.so
  5169. ....
  5170. Source: link:userland/linux/pagemap_dump.c[]
  5171. Adapted from: https://github.com/dwks/pagemap/blob/8a25747bc79d6080c8b94eac80807a4dceeda57a/pagemap2.c
  5172. Meaning of the flags:
  5173. * `vaddr`: first virtual address of a page the belongs to the process. Notably:
  5174. +
  5175. ....
  5176. ./run-toolchain readelf -- -l "$(./getvar userland_build_dir)/posix/virt_to_phys_test.out"
  5177. ....
  5178. +
  5179. contains:
  5180. +
  5181. ....
  5182. Type Offset VirtAddr PhysAddr
  5183. FileSiz MemSiz Flags Align
  5184. ...
  5185. LOAD 0x0000000000000000 0x0000000000400000 0x0000000000400000
  5186. 0x000000000000075c 0x000000000000075c R E 0x200000
  5187. LOAD 0x0000000000000e98 0x0000000000600e98 0x0000000000600e98
  5188. 0x00000000000001b4 0x0000000000000218 RW 0x200000
  5189. Section to Segment mapping:
  5190. Segment Sections...
  5191. ...
  5192. 02 .interp .hash .dynsym .dynstr .rela.plt .init .plt .text .fini .rodata .eh_frame_hdr .eh_frame
  5193. 03 .ctors .dtors .jcr .dynamic .got.plt .data .bss
  5194. ....
  5195. +
  5196. from which we deduce that:
  5197. +
  5198. ** `400000` is the text segment
  5199. ** `600000` is the data segment
  5200. * `pfn`: add three zeroes to it, and you have the physical address.
  5201. +
  5202. Three zeroes is 12 bits which is 4kB, which is the size of a page.
  5203. +
  5204. For example, the virtual address `0x601000` has `pfn` of `0x1a61`, which means that its physical address is `0x1a61000`
  5205. +
  5206. This is consistent with what `linux/virt_to_phys_user.out` told us: the virtual address `0x601048` has physical address `0x1a61048`.
  5207. +
  5208. `048` corresponds to the three last zeroes, and is the offset within the page.
  5209. +
  5210. Also, this value falls inside `0x601000`, which as previously analyzed is the data section, which is the normal location for global variables such as ours.
  5211. * `soft-dirty`: TODO
  5212. * `file/shared`: TODO. `1` seems to indicate that the page can be shared across processes, possibly for read-only pages? E.g. the text segment has `1`, but the data has `0`.
  5213. * `swapped`: TODO swapped to disk?
  5214. * `present`: TODO vs swapped?
  5215. * `library`: which executable owns that page
  5216. This program works in two steps:
  5217. * parse the human readable lines lines from `/proc/<pid>/maps`. This files contains lines of form:
  5218. +
  5219. ....
  5220. 7ffff7b6d000-7ffff7bdd000 r-xp 00000000 fe:00 658 /lib/libuClibc-1.0.22.so
  5221. ....
  5222. +
  5223. which tells us that:
  5224. +
  5225. ** `7f8af99f8000-7f8af99ff000` is a virtual address range that belong to the process, possibly containing multiple pages.
  5226. ** `/lib/libuClibc-1.0.22.so` is the name of the library that owns that memory
  5227. * loop over each page of each address range, and ask `/proc/<pid>/pagemap` for more information about that page, including the physical address
  5228. === Linux kernel tracing
  5229. Good overviews:
  5230. * http://www.brendangregg.com/blog/2015-07-08/choosing-a-linux-tracer.html by Brendan Greg, AKA the master of tracing. Also: https://github.com/brendangregg/perf-tools
  5231. * https://jvns.ca/blog/2017/07/05/linux-tracing-systems/
  5232. I hope to have examples of all methods some day, since I'm obsessed with visibility.
  5233. ==== CONFIG_PROC_EVENTS
  5234. Logs proc events such as process creation to a link:kernel_modules/netlink.c[netlink socket].
  5235. We then have a userland program that listens to the events and prints them out:
  5236. ....
  5237. # ./linux/proc_events.out &
  5238. # set mcast listen ok
  5239. # sleep 2 & sleep 1
  5240. fork: parent tid=48 pid=48 -> child tid=79 pid=79
  5241. fork: parent tid=48 pid=48 -> child tid=80 pid=80
  5242. exec: tid=80 pid=80
  5243. exec: tid=79 pid=79
  5244. # exit: tid=80 pid=80 exit_code=0
  5245. exit: tid=79 pid=79 exit_code=0
  5246. echo a
  5247. a
  5248. #
  5249. ....
  5250. Source: link:userland/linux/proc_events.c[]
  5251. TODO: why `exit: tid=79` shows after `exit: tid=80`?
  5252. Note how `echo a` is a Bash built-in, and therefore does not spawn a new process.
  5253. TODO: why does this produce no output?
  5254. ....
  5255. ./linux/proc_events.out >f &
  5256. ....
  5257. * https://stackoverflow.com/questions/6075013/detect-launching-of-programs-on-linux-platform/8255487#8255487
  5258. * https://serverfault.com/questions/199654/does-anyone-know-a-simple-way-to-monitor-root-process-spawn
  5259. * https://unix.stackexchange.com/questions/260162/how-to-track-newly-created-processes
  5260. TODO can you get process data such as UID and process arguments? It seems not since `exec_proc_event` contains so little data: https://github.com/torvalds/linux/blob/v4.16/include/uapi/linux/cn_proc.h#L80 We could try to immediately read it from `/proc`, but there is a risk that the process finished and another one took its PID, so it wouldn't be reliable.
  5261. * https://unix.stackexchange.com/questions/163681/print-pids-and-names-of-processes-as-they-are-created/163689 requests process name
  5262. * https://serverfault.com/questions/199654/does-anyone-know-a-simple-way-to-monitor-root-process-spawn requests UID
  5263. ===== CONFIG_PROC_EVENTS aarch64
  5264. 0111ca406bdfa6fd65a2605d353583b4c4051781 was failing with:
  5265. ....
  5266. >>> kernel_modules 1.0 Building
  5267. /usr/bin/make -j8 -C '/linux-kernel-module-cheat//out/aarch64/buildroot/build/kernel_modules-1.0/user' BR2_PACKAGE_OPENBLAS="" CC="/linux-kernel-module-cheat//out/aarch64/buildroot/host/bin/aarch64-buildroot-linux-uclibc-gcc" LD="/linux-kernel-module-cheat//out/aarch64/buildroot/host/bin/aarch64-buildroot-linux-uclibc-ld"
  5268. /linux-kernel-module-cheat//out/aarch64/buildroot/host/bin/aarch64-buildroot-linux-uclibc-gcc -ggdb3 -fopenmp -O0 -std=c99 -Wall -Werror -Wextra -o 'proc_events.out' 'proc_events.c'
  5269. In file included from /linux-kernel-module-cheat//out/aarch64/buildroot/host/aarch64-buildroot-linux-uclibc/sysroot/usr/include/signal.h:329:0,
  5270. from proc_events.c:12:
  5271. /linux-kernel-module-cheat//out/aarch64/buildroot/host/aarch64-buildroot-linux-uclibc/sysroot/usr/include/sys/ucontext.h:50:16: error: field ‘uc_mcontext’ has incomplete type
  5272. mcontext_t uc_mcontext;
  5273. ^~~~~~~~~~~
  5274. ....
  5275. so we commented it out.
  5276. Related threads:
  5277. * https://mailman.uclibc-ng.org/pipermail/devel/2018-January/001624.html
  5278. * https://github.com/DynamoRIO/dynamorio/issues/2356
  5279. If we try to naively update uclibc to 1.0.29 with `buildroot_override`, which contains the above mentioned patch, clean `aarch64` test build fails with:
  5280. ....
  5281. ../utils/ldd.c: In function 'elf_find_dynamic':
  5282. ../utils/ldd.c:238:12: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
  5283. return (void *)byteswap_to_host(dynp->d_un.d_val);
  5284. ^
  5285. /tmp/user/20321/cciGScKB.o: In function `process_line_callback':
  5286. msgmerge.c:(.text+0x22): undefined reference to `escape'
  5287. /tmp/user/20321/cciGScKB.o: In function `process':
  5288. msgmerge.c:(.text+0xf6): undefined reference to `poparser_init'
  5289. msgmerge.c:(.text+0x11e): undefined reference to `poparser_feed_line'
  5290. msgmerge.c:(.text+0x128): undefined reference to `poparser_finish'
  5291. collect2: error: ld returned 1 exit status
  5292. Makefile.in:120: recipe for target '../utils/msgmerge.host' failed
  5293. make[2]: *** [../utils/msgmerge.host] Error 1
  5294. make[2]: *** Waiting for unfinished jobs....
  5295. /tmp/user/20321/ccF8V8jF.o: In function `process':
  5296. msgfmt.c:(.text+0xbf3): undefined reference to `poparser_init'
  5297. msgfmt.c:(.text+0xc1f): undefined reference to `poparser_feed_line'
  5298. msgfmt.c:(.text+0xc2b): undefined reference to `poparser_finish'
  5299. collect2: error: ld returned 1 exit status
  5300. Makefile.in:120: recipe for target '../utils/msgfmt.host' failed
  5301. make[2]: *** [../utils/msgfmt.host] Error 1
  5302. package/pkg-generic.mk:227: recipe for target '/data/git/linux-kernel-module-cheat/out/aarch64/buildroot/build/uclibc-custom/.stamp_built' failed
  5303. make[1]: *** [/data/git/linux-kernel-module-cheat/out/aarch64/buildroot/build/uclibc-custom/.stamp_built] Error 2
  5304. Makefile:79: recipe for target '_all' failed
  5305. make: *** [_all] Error 2
  5306. ....
  5307. Buildroot master has already moved to uclibc 1.0.29 at f8546e836784c17aa26970f6345db9d515411700, but it is not yet in any tag... so I'm not tempted to update it yet just for this.
  5308. ==== ftrace
  5309. Trace a single function:
  5310. ....
  5311. cd /sys/kernel/debug/tracing/
  5312. # Stop tracing.
  5313. echo 0 > tracing_on
  5314. # Clear previous trace.
  5315. echo > trace
  5316. # List the available tracers, and pick one.
  5317. cat available_tracers
  5318. echo function > current_tracer
  5319. # List all functions that can be traced
  5320. # cat available_filter_functions
  5321. # Choose one.
  5322. echo __kmalloc > set_ftrace_filter
  5323. # Confirm that only __kmalloc is enabled.
  5324. cat enabled_functions
  5325. echo 1 > tracing_on
  5326. # Latest events.
  5327. head trace
  5328. # Observe trace continuously, and drain seen events out.
  5329. cat trace_pipe &
  5330. ....
  5331. Sample output:
  5332. ....
  5333. # tracer: function
  5334. #
  5335. # entries-in-buffer/entries-written: 97/97 #P:1
  5336. #
  5337. # _-----=> irqs-off
  5338. # / _----=> need-resched
  5339. # | / _---=> hardirq/softirq
  5340. # || / _--=> preempt-depth
  5341. # ||| / delay
  5342. # TASK-PID CPU# |||| TIMESTAMP FUNCTION
  5343. # | | | |||| | |
  5344. head-228 [000] .... 825.534637: __kmalloc <-load_elf_phdrs
  5345. head-228 [000] .... 825.534692: __kmalloc <-load_elf_binary
  5346. head-228 [000] .... 825.534815: __kmalloc <-load_elf_phdrs
  5347. head-228 [000] .... 825.550917: __kmalloc <-__seq_open_private
  5348. head-228 [000] .... 825.550953: __kmalloc <-tracing_open
  5349. head-229 [000] .... 826.756585: __kmalloc <-load_elf_phdrs
  5350. head-229 [000] .... 826.756627: __kmalloc <-load_elf_binary
  5351. head-229 [000] .... 826.756719: __kmalloc <-load_elf_phdrs
  5352. head-229 [000] .... 826.773796: __kmalloc <-__seq_open_private
  5353. head-229 [000] .... 826.773835: __kmalloc <-tracing_open
  5354. head-230 [000] .... 827.174988: __kmalloc <-load_elf_phdrs
  5355. head-230 [000] .... 827.175046: __kmalloc <-load_elf_binary
  5356. head-230 [000] .... 827.175171: __kmalloc <-load_elf_phdrs
  5357. ....
  5358. Trace all possible functions, and draw a call graph:
  5359. ....
  5360. echo 1 > max_graph_depth
  5361. echo 1 > events/enable
  5362. echo function_graph > current_tracer
  5363. ....
  5364. Sample output:
  5365. ....
  5366. # CPU DURATION FUNCTION CALLS
  5367. # | | | | | | |
  5368. 0) 2.173 us | } /* ntp_tick_length */
  5369. 0) | timekeeping_update() {
  5370. 0) 4.176 us | ntp_get_next_leap();
  5371. 0) 5.016 us | update_vsyscall();
  5372. 0) | raw_notifier_call_chain() {
  5373. 0) 2.241 us | notifier_call_chain();
  5374. 0) + 19.879 us | }
  5375. 0) 3.144 us | update_fast_timekeeper();
  5376. 0) 2.738 us | update_fast_timekeeper();
  5377. 0) ! 117.147 us | }
  5378. 0) | _raw_spin_unlock_irqrestore() {
  5379. 0) 4.045 us | _raw_write_unlock_irqrestore();
  5380. 0) + 22.066 us | }
  5381. 0) ! 265.278 us | } /* update_wall_time */
  5382. ....
  5383. TODO: what do `+` and `!` mean?
  5384. Each `enable` under the `events/` tree enables a certain set of functions, the higher the `enable` more functions are enabled.
  5385. TODO: can you get function arguments? https://stackoverflow.com/questions/27608752/does-ftrace-allow-capture-of-system-call-arguments-to-the-linux-kernel-or-only
  5386. ===== ftrace system calls
  5387. https://stackoverflow.com/questions/29840213/how-do-i-trace-a-system-call-in-linux/51856306#51856306
  5388. ===== trace-cmd
  5389. TODO example:
  5390. ....
  5391. ./build-buildroot --config 'BR2_PACKAGE_TRACE_CMD=y'
  5392. ....
  5393. ==== Kprobes
  5394. kprobes is an instrumentation mechanism that injects arbitrary code at a given address in a trap instruction, much like GDB. Oh, the good old kernel. :-)
  5395. ....
  5396. ./build-linux --config 'CONFIG_KPROBES=y'
  5397. ....
  5398. Then on guest:
  5399. ....
  5400. insmod kprobe_example.ko
  5401. sleep 4 & sleep 4 &'
  5402. ....
  5403. Outcome: dmesg outputs on every fork:
  5404. ....
  5405. <_do_fork> pre_handler: p->addr = 0x00000000e1360063, ip = ffffffff810531d1, flags = 0x246
  5406. <_do_fork> post_handler: p->addr = 0x00000000e1360063, flags = 0x246
  5407. <_do_fork> pre_handler: p->addr = 0x00000000e1360063, ip = ffffffff810531d1, flags = 0x246
  5408. <_do_fork> post_handler: p->addr = 0x00000000e1360063, flags = 0x246
  5409. ....
  5410. Source: link:kernel_modules/kprobe_example.c[]
  5411. TODO: it does not work if I try to immediately launch `sleep`, why?
  5412. ....
  5413. insmod kprobe_example.ko
  5414. sleep 4 & sleep 4 &
  5415. ....
  5416. I don't think your code can refer to the surrounding kernel code however: the only visible thing is the value of the registers.
  5417. You can then hack it up to read the stack and read argument values, but do you really want to?
  5418. There is also a kprobes + ftrace based mechanism with `CONFIG_KPROBE_EVENTS=y` which does read the memory for us based on format strings that indicate type... https://github.com/torvalds/linux/blob/v4.16/Documentation/trace/kprobetrace.txt Horrendous. Used by: https://github.com/brendangregg/perf-tools/blob/98d42a2a1493d2d1c651a5c396e015d4f082eb20/execsnoop
  5419. Bibliography:
  5420. * https://github.com/torvalds/linux/blob/v4.16/Documentation/kprobes.txt
  5421. * https://github.com/torvalds/linux/blob/v4.17/samples/kprobes/kprobe_example.c
  5422. ==== Count boot instructions
  5423. TODO: didn't port during refactor after 3b0a343647bed577586989fb702b760bd280844a. Reimplementing should not be hard.
  5424. * https://www.quora.com/How-many-instructions-does-a-typical-Linux-kernel-boot-take
  5425. * https://github.com/cirosantilli/chat/issues/31
  5426. * https://rwmj.wordpress.com/2016/03/17/tracing-qemu-guest-execution/
  5427. * `qemu/docs/tracing.txt` and `qemu/docs/replay.txt`
  5428. * https://stackoverflow.com/questions/39149446/how-to-use-qemus-simple-trace-backend/46497873#46497873
  5429. Results (boot not excluded) are shown at: xref:table-boot-instruction-counts[xrefstyle=full]
  5430. [[table-boot-instruction-counts]]
  5431. .Boot instruction counts for various setups
  5432. [options="header"]
  5433. |===
  5434. |Commit |Arch |Simulator |Instruction count
  5435. |7228f75ac74c896417fb8c5ba3d375a14ed4d36b
  5436. |arm
  5437. |QEMU
  5438. |680k
  5439. |7228f75ac74c896417fb8c5ba3d375a14ed4d36b
  5440. |arm
  5441. |gem5 AtomicSimpleCPU
  5442. |160M
  5443. |7228f75ac74c896417fb8c5ba3d375a14ed4d36b
  5444. |arm
  5445. |gem5 HPI
  5446. |155M
  5447. |7228f75ac74c896417fb8c5ba3d375a14ed4d36b
  5448. |x86_64
  5449. |QEMU
  5450. |3M
  5451. |7228f75ac74c896417fb8c5ba3d375a14ed4d36b
  5452. |x86_64
  5453. |gem5 AtomicSimpleCPU
  5454. |528M
  5455. |===
  5456. QEMU:
  5457. ....
  5458. ./trace-boot --arch x86_64
  5459. ....
  5460. sample output:
  5461. ....
  5462. instructions 1833863
  5463. entry_address 0x1000000
  5464. instructions_firmware 20708
  5465. ....
  5466. gem5:
  5467. ....
  5468. ./run --arch aarch64 --emulator gem5 --eval 'm5 exit'
  5469. # Or:
  5470. # ./run --arch aarch64 --emulator gem5 --eval 'm5 exit' -- --cpu-type=HPI --caches
  5471. ./gem5-stat --arch aarch64 sim_insts
  5472. ....
  5473. Notes:
  5474. * `0x1000000` is the address where QEMU puts the Linux kernel at with `-kernel` in x86.
  5475. +
  5476. It can be found from:
  5477. +
  5478. ....
  5479. ./run-toolchain readelf -- -e "$(./getvar vmlinux)" | grep Entry
  5480. ....
  5481. +
  5482. TODO confirm further. If I try to break there with:
  5483. +
  5484. ....
  5485. ./run-gdb *0x1000000
  5486. ....
  5487. +
  5488. but I have no corresponding source line. Also note that this line is not actually the first line, since the kernel messages such as `early console in extract_kernel` have already shown on screen at that point. This does not break at all:
  5489. +
  5490. ....
  5491. ./run-gdb extract_kernel
  5492. ....
  5493. +
  5494. It only appears once on every log I've seen so far, checked with `grep 0x1000000 trace.txt`
  5495. +
  5496. Then when we count the instructions that run before the kernel entry point, there is only about 100k instructions, which is insignificant compared to the kernel boot itself.
  5497. +
  5498. TODO `--arch arm` and `--arch aarch64` does not count firmware instructions properly because the entry point address of the ELF file (`ffffff8008080000` for `aarch64`) does not show up on the trace at all. Tested on https://github.com/cirosantilli/linux-kernel-module-cheat/commit/f8c0502bb2680f2dbe7c1f3d7958f60265347005[f8c0502bb2680f2dbe7c1f3d7958f60265347005].
  5499. * We can also discount the instructions after `init` runs by using `readelf` to get the initial address of `init`. One easy way to do that now is to just run:
  5500. +
  5501. ....
  5502. ./run-gdb --userland "$(./getvar userland_build_dir)/linux/poweroff.out" main
  5503. ....
  5504. +
  5505. And get that from the traces, e.g. if the address is `4003a0`, then we search:
  5506. +
  5507. ....
  5508. grep -n 4003a0 trace.txt
  5509. ....
  5510. +
  5511. I have observed a single match for that instruction, so it must be the init, and there were only 20k instructions after it, so the impact is negligible.
  5512. * to disable networking. Is replacing `init` enough?
  5513. +
  5514. --
  5515. ** https://superuser.com/questions/181254/how-do-you-boot-linux-with-networking-disabled
  5516. ** https://superuser.com/questions/684005/how-does-one-permanently-disable-gnu-linux-networking/1255015#1255015
  5517. --
  5518. +
  5519. `CONFIG_NET=n` did not significantly reduce instruction counts, so maybe replacing `init` is enough.
  5520. * gem5 simulates memory latencies. So I think that the CPU loops idle while waiting for memory, and counts will be higher.
  5521. === Linux kernel hardening
  5522. Make it harder to get hacked and easier to notice that you were, at the cost of some (small?) runtime overhead.
  5523. ==== CONFIG_FORTIFY_SOURCE
  5524. Detects buffer overflows for us:
  5525. ....
  5526. ./build-linux --config 'CONFIG_FORTIFY_SOURCE=y' --linux-build-id fortify
  5527. ./build-modules --clean
  5528. ./build-modules
  5529. ./build-buildroot
  5530. ./run --eval-after 'insmod strlen_overflow.ko' --linux-build-id fortify
  5531. ....
  5532. Possible dmesg output:
  5533. ....
  5534. strlen_overflow: loading out-of-tree module taints kernel.
  5535. detected buffer overflow in strlen
  5536. ------------[ cut here ]------------
  5537. ....
  5538. followed by a trace.
  5539. You may not get this error because this depends on `strlen` overflowing at least until the next page: if a random `\0` appears soon enough, it won't blow up as desired.
  5540. TODO not always reproducible. Find a more reproducible failure. I could not observe it on:
  5541. ....
  5542. insmod memcpy_overflow.ko
  5543. ....
  5544. Source: link:kernel_modules/strlen_overflow.c[]
  5545. Bibliography: https://www.reddit.com/r/hacking/comments/8h4qxk/what_a_buffer_overflow_in_the_linux_kernel_looks/
  5546. ==== Linux security modules
  5547. https://en.wikipedia.org/wiki/Linux_Security_Modules
  5548. ===== SELinux
  5549. TODO get a hello world permission control working:
  5550. ....
  5551. ./build-linux \
  5552. --config-fragment linux_config/selinux \
  5553. --linux-build-id selinux \
  5554. ;
  5555. ./build-buildroot --config 'BR2_PACKAGE_REFPOLICY=y'
  5556. ./run --enable-kvm --linux-build-id selinux
  5557. ....
  5558. Source: link:linux_config/selinux[]
  5559. This builds:
  5560. * `BR2_PACKAGE_REFPOLICY`, which includes a reference `/etc/selinux/config` policy: https://github.com/SELinuxProject/refpolicy
  5561. +
  5562. refpolicy in turn depends on:
  5563. * `BR2_PACKAGE_SETOOLS`, which contains tools such as `getenforced`: https://github.com/SELinuxProject/setools
  5564. +
  5565. setools depends on:
  5566. * `BR2_PACKAGE_LIBSELINUX`, which is the backing userland library
  5567. After boot finishes, we see:
  5568. ....
  5569. Starting auditd: mkdir: invalid option -- 'Z'
  5570. ....
  5571. which comes from `/etc/init.d/S01auditd`, because BusyBox' `mkdir` does not have the crazy `-Z` option like Ubuntu. That's amazing!
  5572. The kernel logs contain:
  5573. ....
  5574. SELinux: Initializing.
  5575. ....
  5576. Inside the guest we now have:
  5577. ....
  5578. getenforce
  5579. ....
  5580. which initially says:
  5581. ....
  5582. Disabled
  5583. ....
  5584. TODO: if we try to enforce:
  5585. ....
  5586. setenforce 1
  5587. ....
  5588. it does not work and outputs:
  5589. ....
  5590. setenforce: SELinux is disabled
  5591. ....
  5592. SELinux requires glibc as mentioned at: xref:libc-choice[xrefstyle=full].
  5593. === User mode Linux
  5594. I once got https://en.wikipedia.org/wiki/User-mode_Linux[UML] running on a minimal Buildroot setup at: https://unix.stackexchange.com/questions/73203/how-to-create-rootfs-for-user-mode-linux-on-fedora-18/372207#372207
  5595. But in part because it is dying, I didn't spend much effort to integrate it into this repo, although it would be a good fit in principle, since it is essentially a virtualization method.
  5596. Maybe some brave soul will send a pull request one day.
  5597. === UIO
  5598. UIO is a kernel subsystem that allows to do certain types of driver operations from userland.
  5599. This would be awesome to improve debuggability and safety of kernel modules.
  5600. VFIO looks like a newer and better UIO replacement, but there do not exist any examples of how to use it: https://stackoverflow.com/questions/49309162/interfacing-with-qemu-edu-device-via-userspace-i-o-uio-linux-driver
  5601. TODO get something interesting working. I currently don't understand the behaviour very well.
  5602. TODO how to ACK interrupts? How to ensure that every interrupt gets handled separately?
  5603. TODO how to write to registers. Currently using `/dev/mem` and `lspci`.
  5604. This example should handle interrupts from userland and print a message to stdout:
  5605. ....
  5606. ./uio_read.sh
  5607. ....
  5608. TODO: what is the expected behaviour? I should have documented this when I wrote this stuff, and I'm that lazy right now that I'm in the middle of a refactor :-)
  5609. UIO interface in a nutshell:
  5610. * blocking read / poll: waits until interrupts
  5611. * `write`: call `irqcontrol` callback. Default: 0 or 1 to enable / disable interrupts.
  5612. * `mmap`: access device memory
  5613. Sources:
  5614. * link:userland/kernel_modules/uio_read.c[]
  5615. * link:rootfs_overlay/lkmc/uio_read.sh[]
  5616. Bibliography:
  5617. * https://stackoverflow.com/questions/15286772/userspace-vs-kernel-space-driver
  5618. * https://01.org/linuxgraphics/gfx-docs/drm/driver-api/uio-howto.html
  5619. * https://stackoverflow.com/questions/7986260/linux-interrupt-handling-in-user-space
  5620. * https://yurovsky.github.io/2014/10/10/linux-uio-gpio-interrupt/
  5621. * https://github.com/bmartini/zynq-axis/blob/65a3a448fda1f0ea4977adfba899eb487201853d/dev/axis.c
  5622. * https://yurovsky.github.io/2014/10/10/linux-uio-gpio-interrupt/
  5623. * http://nairobi-embedded.org/uio_example.html that website has QEMU examples for everything as usual. The example has a kernel-side which creates the memory mappings and is used by the user.
  5624. * https://stackoverflow.com/questions/49309162/interfacing-with-qemu-edu-device-via-userspace-i-o-uio-linux-driver
  5625. * userland driver stability questions:
  5626. ** https://stackoverflow.com/questions/8030758/getting-kernel-version-from-linux-kernel-module-at-runtime/45430233#45430233
  5627. ** https://stackoverflow.com/questions/37098482/how-to-build-a-linux-kernel-module-so-that-it-is-compatible-with-all-kernel-rele/45429681#45429681
  5628. ** https://liquidat.wordpress.com/2007/07/21/linux-kernel-2623-to-have-stable-userspace-driver-api/
  5629. === Linux kernel interactive stuff
  5630. [[fbcon]]
  5631. ==== Linux kernel console fun
  5632. Requires <<graphics>>.
  5633. You can also try those on the `Ctrl-Alt-F3` of your Ubuntu host, but it is much more fun inside a VM!
  5634. Stop the cursor from blinking:
  5635. ....
  5636. echo 0 > /sys/class/graphics/fbcon/cursor_blink
  5637. ....
  5638. Rotate the console 90 degrees! https://askubuntu.com/questions/237963/how-do-i-rotate-my-display-when-not-using-an-x-server
  5639. ....
  5640. echo 1 > /sys/class/graphics/fbcon/rotate
  5641. ....
  5642. Relies on: `CONFIG_FRAMEBUFFER_CONSOLE_ROTATION=y`.
  5643. Documented under: `Documentation/fb/`.
  5644. TODO: font and keymap. Mentioned at: https://cmcenroe.me/2017/05/05/linux-console.html and I think can be done with BusyBox `loadkmap` and `loadfont`, we just have to understand their formats, related:
  5645. * https://unix.stackexchange.com/questions/177024/remap-keyboard-on-the-linux-console
  5646. * https://superuser.com/questions/194202/remapping-keys-system-wide-in-linux-not-just-in-x
  5647. ==== Linux kernel magic keys
  5648. Requires <<graphics>>.
  5649. Let's have some fun.
  5650. I think most are implemented under:
  5651. ....
  5652. drivers/tty
  5653. ....
  5654. TODO find all.
  5655. Scroll up / down the terminal:
  5656. ....
  5657. Shift-PgDown
  5658. Shift-PgUp
  5659. ....
  5660. Or inside `./qemu-monitor`:
  5661. ....
  5662. sendkey shift-pgup
  5663. sendkey shift-pgdown
  5664. ....
  5665. ===== Ctrl Alt Del
  5666. If you run in <<qemu-graphic-mode>>:
  5667. ....
  5668. ./run --graphic
  5669. ....
  5670. and then from the graphic window you enter the keys:
  5671. ....
  5672. Ctrl-Alt-Del
  5673. ....
  5674. then this runs the following command on the guest:
  5675. ....
  5676. /sbin/reboot
  5677. ....
  5678. This is enabled from our link:rootfs_overlay/etc/inittab[]:
  5679. ....
  5680. ::ctrlaltdel:/sbin/reboot
  5681. ....
  5682. This leads Linux to try to reboot, and QEMU shutdowns due to the `-no-reboot` option which we set by default for, see: xref:exit-emulator-on-panic[xrefstyle=full].
  5683. Here is a minimal example of Ctrl Alt Del:
  5684. ....
  5685. ./run --kernel-cli 'init=/lkmc/linux/ctrl_alt_del.out' --graphic
  5686. ....
  5687. Source: link:userland/linux/ctrl_alt_del.c[]
  5688. When you hit `Ctrl-Alt-Del` in the guest, our tiny init handles a `SIGINT` sent by the kernel and outputs to stdout:
  5689. ....
  5690. cad
  5691. ....
  5692. To map between `man 2 reboot` and the uClibc `RB_*` magic constants see:
  5693. ....
  5694. less "$(./getvar buildroot_build_build_dir)"/uclibc-*/include/sys/reboot.h"
  5695. ....
  5696. The procfs mechanism is documented at:
  5697. ....
  5698. less linux/Documentation/sysctl/kernel.txt
  5699. ....
  5700. which says:
  5701. ....
  5702. When the value in this file is 0, ctrl-alt-del is trapped and
  5703. sent to the init(1) program to handle a graceful restart.
  5704. When, however, the value is > 0, Linux's reaction to a Vulcan
  5705. Nerve Pinch (tm) will be an immediate reboot, without even
  5706. syncing its dirty buffers.
  5707. Note: when a program (like dosemu) has the keyboard in 'raw'
  5708. mode, the ctrl-alt-del is intercepted by the program before it
  5709. ever reaches the kernel tty layer, and it's up to the program
  5710. to decide what to do with it.
  5711. ....
  5712. Under the hood, behaviour is controlled by the `reboot` syscall:
  5713. ....
  5714. man 2 reboot
  5715. ....
  5716. `reboot` system calls can set either of the these behaviours for `Ctrl-Alt-Del`:
  5717. * do a hard shutdown syscall. Set in uClibc C code with:
  5718. +
  5719. ....
  5720. reboot(RB_ENABLE_CAD)
  5721. ....
  5722. +
  5723. or from procfs with:
  5724. +
  5725. ....
  5726. echo 1 > /proc/sys/kernel/ctrl-alt-del
  5727. ....
  5728. +
  5729. Done by BusyBox' `reboot -f`.
  5730. * send a SIGINT to the init process. This is what BusyBox' init does, and it then execs the string set in `inittab`.
  5731. +
  5732. Set in uclibc C code with:
  5733. +
  5734. ....
  5735. reboot(RB_DISABLE_CAD)
  5736. ....
  5737. +
  5738. or from procfs with:
  5739. +
  5740. ....
  5741. echo 0 > /proc/sys/kernel/ctrl-alt-del
  5742. ....
  5743. +
  5744. Done by BusyBox' `reboot`.
  5745. When a BusyBox init is with the signal, it prints the following lines:
  5746. ....
  5747. The system is going down NOW!
  5748. Sent SIGTERM to all processes
  5749. Sent SIGKILL to all processes
  5750. Requesting system reboot
  5751. ....
  5752. On busybox-1.29.2's init at init/init.c we see how the kill signals are sent:
  5753. ....
  5754. static void run_shutdown_and_kill_processes(void)
  5755. {
  5756. /* Run everything to be run at "shutdown". This is done _prior_
  5757. * to killing everything, in case people wish to use scripts to
  5758. * shut things down gracefully... */
  5759. run_actions(SHUTDOWN);
  5760. message(L_CONSOLE | L_LOG, "The system is going down NOW!");
  5761. /* Send signals to every process _except_ pid 1 */
  5762. kill(-1, SIGTERM);
  5763. message(L_CONSOLE, "Sent SIG%s to all processes", "TERM");
  5764. sync();
  5765. sleep(1);
  5766. kill(-1, SIGKILL);
  5767. message(L_CONSOLE, "Sent SIG%s to all processes", "KILL");
  5768. sync();
  5769. /*sleep(1); - callers take care about making a pause */
  5770. }
  5771. ....
  5772. and `run_shutdown_and_kill_processes` is called from:
  5773. ....
  5774. /* The SIGPWR/SIGUSR[12]/SIGTERM handler */
  5775. static void halt_reboot_pwoff(int sig) NORETURN;
  5776. static void halt_reboot_pwoff(int sig)
  5777. ....
  5778. which also prints the final line:
  5779. ....
  5780. message(L_CONSOLE, "Requesting system %s", m);
  5781. ....
  5782. which is set as the signal handler via TODO.
  5783. Bibliography:
  5784. * https://superuser.com/questions/193652/does-linux-have-a-ctrlaltdel-equivalent/1324415#1324415
  5785. * https://unix.stackexchange.com/questions/42573/meaning-and-commands-for-ctrlaltdel/444969#444969
  5786. ===== SysRq
  5787. We cannot test these actual shortcuts on QEMU since the host captures them at a lower level, but from:
  5788. ....
  5789. ./qemu-monitor
  5790. ....
  5791. we can for example crash the system with:
  5792. ....
  5793. sendkey alt-sysrq-c
  5794. ....
  5795. Same but boring because no magic key:
  5796. ....
  5797. echo c > /proc/sysrq-trigger
  5798. ....
  5799. Implemented in:
  5800. ....
  5801. drivers/tty/sysrq.c
  5802. ....
  5803. On your host, on modern systems that don't have the `SysRq` key you can do:
  5804. ....
  5805. Alt-PrtSc-space
  5806. ....
  5807. which prints a message to `dmesg` of type:
  5808. ....
  5809. sysrq: SysRq : HELP : loglevel(0-9) reboot(b) crash(c) terminate-all-tasks(e) memory-full-oom-kill(f) kill-all-tasks(i) thaw-filesystems(j) sak(k) show-backtrace-all-active-cpus(l) show-memory-usage(m) nice-all-RT-tasks(n) poweroff(o) show-registers(p) show-all-timers(q) unraw(r) sync(s) show-task-states(t) unmount(u) show-blocked-tasks(w) dump-ftrace-buffer(z)
  5810. ....
  5811. Individual SysRq can be enabled or disabled with the bitmask:
  5812. ....
  5813. /proc/sys/kernel/sysrq
  5814. ....
  5815. The bitmask is documented at:
  5816. ....
  5817. less linux/Documentation/admin-guide/sysrq.rst
  5818. ....
  5819. Bibliography: https://en.wikipedia.org/wiki/Magic_SysRq_key
  5820. ==== TTY
  5821. In order to play with TTYs, do this:
  5822. ....
  5823. printf '
  5824. tty2::respawn:/sbin/getty -n -L -l /lkmc/loginroot.sh tty2 0 vt100
  5825. tty3::respawn:-/bin/sh
  5826. tty4::respawn:/sbin/getty 0 tty4
  5827. tty63::respawn:-/bin/sh
  5828. ::respawn:/sbin/getty -L ttyS0 0 vt100
  5829. ::respawn:/sbin/getty -L ttyS1 0 vt100
  5830. ::respawn:/sbin/getty -L ttyS2 0 vt100
  5831. # Leave one serial empty.
  5832. #::respawn:/sbin/getty -L ttyS3 0 vt100
  5833. ' >> rootfs_overlay/etc/inittab
  5834. ./build-buildroot
  5835. ./run --graphic -- \
  5836. -serial telnet::1235,server,nowait \
  5837. -serial vc:800x600 \
  5838. -serial telnet::1236,server,nowait \
  5839. ;
  5840. ....
  5841. and on a second shell:
  5842. ....
  5843. telnet localhost 1235
  5844. ....
  5845. We don't add more TTYs by default because it would spawn more processes, even if we use `askfirst` instead of `respawn`.
  5846. On the GUI, switch TTYs with:
  5847. * `Alt-Left` or `Alt-Right:` go to previous / next populated `/dev/ttyN` TTY. Skips over empty TTYs.
  5848. * `Alt-Fn`: go to the nth TTY. If it is not populated, don't go there.
  5849. * `chvt <n>`: go to the n-th virtual TTY, even if it is empty: https://superuser.com/questions/33065/console-commands-to-change-virtual-ttys-in-linux-and-openbsd
  5850. You can also test this on most hosts such as Ubuntu 18.04, except that when in the GUI, you must use `Ctrl-Alt-Fx` to switch to another terminal.
  5851. Next, we also have the following shells running on the serial ports, hit enter to activate them:
  5852. * `/dev/ttyS0`: first shell that was used to run QEMU, corresponds to QEMU's `-serial mon:stdio`.
  5853. +
  5854. It would also work if we used `-serial stdio`, but:
  5855. +
  5856. --
  5857. ** `Ctrl-C` would kill QEMU instead of going to the guest
  5858. ** `Ctrl-A C` wouldn't open the QEMU console there
  5859. --
  5860. +
  5861. see also: https://stackoverflow.com/questions/49716931/how-to-run-qemu-with-nographic-and-monitor-but-still-be-able-to-send-ctrlc-to
  5862. * `/dev/ttyS1`: second shell running `telnet`
  5863. * `/dev/ttyS2`: go on the GUI and enter `Ctrl-Alt-2`, corresponds to QEMU's `-serial vc`. Go back to the main console with `Ctrl-Alt-1`.
  5864. although we cannot change between terminals from there.
  5865. Each populated TTY contains a "shell":
  5866. * `-/bin/sh`: goes directly into an `sh` without a login prompt.
  5867. +
  5868. The trailing dash `-` can be used on any command. It makes the command that follows take over the TTY, which is what we typically want for interactive shells: https://askubuntu.com/questions/902998/how-to-check-which-tty-am-i-using
  5869. +
  5870. The `getty` executable however also does this operation and therefore dispenses the `-`.
  5871. * `/sbin/getty` asks for password, and then gives you an `sh`
  5872. +
  5873. We can overcome the password prompt with the `-l /lkmc/loginroot.sh` technique explained at: https://askubuntu.com/questions/902998/how-to-check-which-tty-am-i-using but I don't see any advantage over `-/bin/sh` currently.
  5874. Identify the current TTY with the command:
  5875. ....
  5876. tty
  5877. ....
  5878. Bibliography:
  5879. * https://unix.stackexchange.com/questions/270272/how-to-get-the-tty-in-which-bash-is-running/270372
  5880. * https://unix.stackexchange.com/questions/187319/how-to-get-the-real-name-of-the-controlling-terminal
  5881. * https://unix.stackexchange.com/questions/77796/how-to-get-the-current-terminal-name
  5882. * https://askubuntu.com/questions/902998/how-to-check-which-tty-am-i-using
  5883. This outputs:
  5884. * `/dev/console` for the initial GUI terminal. But I think it is the same as `/dev/tty1`, because if I try to do
  5885. +
  5886. ....
  5887. tty1::respawn:-/bin/sh
  5888. ....
  5889. +
  5890. it makes the terminal go crazy, as if multiple processes are randomly eating up the characters.
  5891. * `/dev/ttyN` for the other graphic TTYs. Note that there are only 63 available ones, from `/dev/tty1` to `/dev/tty63` (`/dev/tty0` is the current one): https://superuser.com/questions/449781/why-is-there-so-many-linux-dev-tty[]. I think this is determined by:
  5892. +
  5893. ....
  5894. #define MAX_NR_CONSOLES 63
  5895. ....
  5896. +
  5897. in `linux/include/uapi/linux/vt.h`.
  5898. * `/dev/ttySN` for the text shells.
  5899. +
  5900. These are Serial ports, see this to understand what those represent physically: https://unix.stackexchange.com/questions/307390/what-is-the-difference-between-ttys0-ttyusb0-and-ttyama0-in-linux/367882#367882
  5901. +
  5902. There are only 4 serial ports, I think this is determined by QEMU. TODO check.
  5903. +
  5904. See also: https://stackoverflow.com/questions/16706423/two-instances-of-busybox-on-separate-serial-lines-ttysn
  5905. Get the TTY in bulk for all processes:
  5906. ....
  5907. ./psa.sh
  5908. ....
  5909. Source: link:rootfs_overlay/lkmc/psa.sh[].
  5910. The TTY appears under the `TT` section, which is enabled by `-o tty`. This shows the TTY device number, e.g.:
  5911. ....
  5912. 4,1
  5913. ....
  5914. and we can then confirm it with:
  5915. ....
  5916. ls -l /dev/tty1
  5917. ....
  5918. Next try:
  5919. ....
  5920. insmod kthread.ko
  5921. ....
  5922. and switch between virtual terminals, to understand that the dmesg goes to whatever current virtual terminal you are on, but not the others, and not to the serial terminals.
  5923. Bibliography:
  5924. * https://serverfault.com/questions/119736/how-to-enable-multiple-virtual-consoles-on-linux
  5925. * https://github.com/mirror/busybox/blob/1_28_3/examples/inittab#L60
  5926. * http://web.archive.org/web/20180117124612/http://nairobi-embedded.org/qemu_serial_port_system_console.html
  5927. ===== Start a getty from outside of init
  5928. TODO: https://unix.stackexchange.com/questions/196704/getty-start-from-command-line
  5929. TODO: how to place an `sh` directly on a TTY as well without `getty`?
  5930. If I try the exact same command that the `inittab` is doing from a regular shell after boot:
  5931. ....
  5932. /sbin/getty 0 tty1
  5933. ....
  5934. it fails with:
  5935. ....
  5936. getty: setsid: Operation not permitted
  5937. ....
  5938. The following however works:
  5939. ....
  5940. ./run --eval 'getty 0 tty1 & getty 0 tty2 & getty 0 tty3 & sleep 99999999' --graphic
  5941. ....
  5942. presumably because it is being called from `init` directly?
  5943. Outcome: `Alt-Right` cycles between three TTYs, `tty1` being the default one that appears under the boot messages.
  5944. `man 2 setsid` says that there is only one failure possibility:
  5945. ____
  5946. EPERM The process group ID of any process equals the PID of the calling process. Thus, in particular, setsid() fails if the calling process is already a process group leader.
  5947. ____
  5948. We can get some visibility into it to try and solve the problem with:
  5949. ....
  5950. ./psa.sh
  5951. ....
  5952. ===== console kernel boot parameter
  5953. Take the command described at <<tty>> and try adding the following:
  5954. * `-e 'console=tty7'`: boot messages still show on `/dev/tty1` (TODO how to change that?), but we don't get a shell at the end of boot there.
  5955. +
  5956. Instead, the shell appears on `/dev/tty7`.
  5957. * `-e 'console=tty2'` like `/dev/tty7`, but `/dev/tty2` is broken, because we have two shells there:
  5958. ** one due to the `::respawn:-/bin/sh` entry which uses whatever `console` points to
  5959. ** another one due to the `tty2::respawn:/sbin/getty` entry we added
  5960. * `-e 'console=ttyS0'` much like `tty2`, but messages show only on serial, and the terminal is broken due to having multiple shells on it
  5961. * `-e 'console=tty1 console=ttyS0'`: boot messages show on both `tty1` and `ttyS0`, but only `S0` gets a shell because it came last
  5962. ==== CONFIG_LOGO
  5963. If you run in <<graphics>>, then you get a Penguin image for <<number-of-cores,every core>> above the console! https://askubuntu.com/questions/80938/is-it-possible-to-get-the-tux-logo-on-the-text-based-boot
  5964. This is due to the https://github.com/torvalds/linux/blob/v4.17/drivers/video/logo/Kconfig#L5[`CONFIG_LOGO=y`] option which we enable by default.
  5965. `reset` on the terminal then kills the poor penguins.
  5966. When `CONFIG_LOGO=y` is set, the logo can be disabled at boot with:
  5967. ....
  5968. ./run --kernel-cli 'logo.nologo'
  5969. ....
  5970. * https://stackoverflow.com/questions/39872463/how-can-i-disable-the-startup-penguins-and-boot-text-on-linaro-ubuntu
  5971. * https://unix.stackexchange.com/questions/332198/centos-remove-penguin-logo-at-startup
  5972. Looks like a recompile is needed to modify the image...
  5973. * https://superuser.com/questions/736423/changing-kernel-bootsplash-image
  5974. * https://unix.stackexchange.com/questions/153975/how-to-change-boot-logo-in-linux-mint
  5975. === DRM
  5976. DRM / DRI is the new interface that supersedes `fbdev`:
  5977. ....
  5978. ./build-buildroot --config 'BR2_PACKAGE_LIBDRM=y'
  5979. ./build-userland --package libdrm -- userland/libs/libdrm/modeset.c
  5980. ./run --eval-after './libs/libdrm/modeset.out' --graphic
  5981. ....
  5982. Source: link:userland/libs/libdrm/modeset.c[]
  5983. Outcome: for a few seconds, the screen that contains the terminal gets taken over by changing colors of the rainbow.
  5984. TODO not working for `aarch64`, it takes over the screen for a few seconds and the kernel messages disappear, but the screen stays black all the time.
  5985. ....
  5986. ./build-buildroot --config 'BR2_PACKAGE_LIBDRM=y'
  5987. ./build-userland --package libdrm
  5988. ./build-buildroot
  5989. ./run --eval-after './libs/libdrm/modeset.out' --graphic
  5990. ....
  5991. <<kmscube>> however worked, which means that it must be a bug with this demo?
  5992. We set `CONFIG_DRM=y` on our default kernel configuration, and it creates one device file for each display:
  5993. ....
  5994. # ls -l /dev/dri
  5995. total 0
  5996. crw------- 1 root root 226, 0 May 28 09:41 card0
  5997. # grep 226 /proc/devices
  5998. 226 drm
  5999. # ls /sys/module/drm /sys/module/drm_kms_helper/
  6000. ....
  6001. Try creating new displays:
  6002. ....
  6003. ./run --arch aarch64 --graphic -- -device virtio-gpu-pci
  6004. ....
  6005. to see multiple `/dev/dri/cardN`, and then use a different display with:
  6006. ....
  6007. ./run --eval-after './libs/libdrm/modeset.out' --graphic
  6008. ....
  6009. Bibliography:
  6010. * https://dri.freedesktop.org/wiki/DRM/
  6011. * https://en.wikipedia.org/wiki/Direct_Rendering_Infrastructure
  6012. * https://en.wikipedia.org/wiki/Direct_Rendering_Manager
  6013. * https://en.wikipedia.org/wiki/Mode_setting KMS
  6014. Tested on: https://github.com/cirosantilli/linux-kernel-module-cheat/commit/93e383902ebcc03d8a7ac0d65961c0e62af9612b[93e383902ebcc03d8a7ac0d65961c0e62af9612b]
  6015. ==== kmscube
  6016. ....
  6017. ./build-buildroot --config-fragment buildroot_config/kmscube
  6018. ....
  6019. Outcome: a colored spinning cube coded in OpenGL + EGL takes over your display and spins forever: https://www.youtube.com/watch?v=CqgJMgfxjsk
  6020. It is a bit amusing to see OpenGL running outside of a window manager window like that: https://stackoverflow.com/questions/3804065/using-opengl-without-a-window-manager-in-linux/50669152#50669152
  6021. TODO: it is very slow, about 1FPS. I tried Buildroot master ad684c20d146b220dd04a85dbf2533c69ec8ee52 with:
  6022. ....
  6023. make qemu_x86_64_defconfig
  6024. printf "
  6025. BR2_CCACHE=y
  6026. BR2_PACKAGE_HOST_QEMU=y
  6027. BR2_PACKAGE_HOST_QEMU_LINUX_USER_MODE=n
  6028. BR2_PACKAGE_HOST_QEMU_SYSTEM_MODE=y
  6029. BR2_PACKAGE_HOST_QEMU_VDE2=y
  6030. BR2_PACKAGE_KMSCUBE=y
  6031. BR2_PACKAGE_MESA3D=y
  6032. BR2_PACKAGE_MESA3D_DRI_DRIVER_SWRAST=y
  6033. BR2_PACKAGE_MESA3D_OPENGL_EGL=y
  6034. BR2_PACKAGE_MESA3D_OPENGL_ES=y
  6035. BR2_TOOLCHAIN_BUILDROOT_CXX=y
  6036. " >> .config
  6037. ....
  6038. and the FPS was much better, I estimate something like 15FPS.
  6039. On Ubuntu 18.04 with NVIDIA proprietary drivers:
  6040. ....
  6041. sudo apt-get instll kmscube
  6042. kmscube
  6043. ....
  6044. fails with:
  6045. ....
  6046. drmModeGetResources failed: Invalid argument
  6047. failed to initialize legacy DRM
  6048. ....
  6049. See also: https://github.com/robclark/kmscube/issues/12 and https://stackoverflow.com/questions/26920835/can-egl-application-run-in-console-mode/26921287#26921287
  6050. Tested on: https://github.com/cirosantilli/linux-kernel-module-cheat/commit/2903771275372ccfecc2b025edbb0d04c4016930[2903771275372ccfecc2b025edbb0d04c4016930]
  6051. ==== kmscon
  6052. TODO get working.
  6053. Implements a console for <<drm>>.
  6054. The Linux kernel has a built-in fbdev console called <<fbcon>> but not for <<drm>> it seems.
  6055. The upstream project seems dead with last commit in 2014: https://www.freedesktop.org/wiki/Software/kmscon/
  6056. Build failed in Ubuntu 18.04 with: https://github.com/dvdhrm/kmscon/issues/131 but this fork compiled but didn't run on host: https://github.com/Aetf/kmscon/issues/2#issuecomment-392484043
  6057. Haven't tested the fork on QEMU too much insanity.
  6058. ==== libdri2
  6059. TODO get working.
  6060. Looks like a more raw alternative to libdrm:
  6061. ....
  6062. ./build-buildroot --config 'BR2_PACKABE_LIBDRI2=y'
  6063. wget \
  6064. -O "$(./getvar userland_source_dir)/dri2test.c" \
  6065. https://raw.githubusercontent.com/robclark/libdri2/master/test/dri2test.c \
  6066. ;
  6067. ./build-userland
  6068. ....
  6069. but then I noticed that that example requires multiple files, and I don't feel like integrating it into our build.
  6070. When I build it on Ubuntu 18.04 host, it does not generate any executable, so I'm confused.
  6071. === Linux kernel testing
  6072. Bibliography: https://stackoverflow.com/questions/3177338/how-is-the-linux-kernel-tested
  6073. ==== Linux Test Project
  6074. https://github.com/linux-test-project/ltp
  6075. Tests a lot of Linux and POSIX userland visible interfaces.
  6076. Buildroot already has a package, so it is trivial to build it:
  6077. ....
  6078. ./build-buildroot --config 'BR2_PACKAGE_LTP_TESTSUITE=y'
  6079. ....
  6080. So now let's try and see if the `exit` system call is working:
  6081. ....
  6082. /usr/lib/ltp-testsuite/testcases/bin/exit01
  6083. ....
  6084. which gives successful output:
  6085. ....
  6086. exit01 1 TPASS : exit() test PASSED
  6087. ....
  6088. and has source code at: https://github.com/linux-test-project/ltp/blob/20190115/testcases/kernel/syscalls/exit/exit01.c
  6089. Besides testing any kernel modifications you make, LTP can also be used to the system call implementation of <<user-mode-simulation>> as shown at <<user-mode-buildroot-executables>>:
  6090. ....
  6091. ./run --userland "$(./getvar buildroot_target_dir)/usr/lib/ltp-testsuite/testcases/bin/exit01"
  6092. ....
  6093. Tested at: 287c83f3f99db8c1ff9bbc85a79576da6a78e986 + 1.
  6094. ==== stress
  6095. <<posix>> userland stress. Two versions:
  6096. ....
  6097. ./build-buildroot \
  6098. --config 'BR2_PACKAGE_STRESS=y' \
  6099. --config 'BR2_PACKAGE_STRESS_NG=y' \
  6100. ;
  6101. ....
  6102. `STRESS_NG` is likely the best, but it requires glibc, see: xref:libc-choice[xrefstyle=full].
  6103. Websites:
  6104. * https://people.seas.harvard.edu/~apw/stress/
  6105. * https://github.com/ColinIanKing/stress-ng
  6106. `stress` usage:
  6107. ....
  6108. stress --help
  6109. stress -c 16 &
  6110. ps
  6111. ....
  6112. and notice how 16 threads were created in addition to a parent worker thread.
  6113. It just runs forever, so kill it when you get tired:
  6114. ....
  6115. kill %1
  6116. ....
  6117. `stress -c 1 -t 1` makes gem5 irresponsive for a very long time.
  6118. === Linux kernel build system
  6119. ==== vmlinux vs bzImage vs zImage vs Image
  6120. Between all archs on QEMU and gem5 we touch all of those kernel built output files.
  6121. We are trying to maintain a description of each at: https://unix.stackexchange.com/questions/5518/what-is-the-difference-between-the-following-kernel-makefile-terms-vmlinux-vml/482978#482978
  6122. QEMU does not seem able to boot ELF files like `vmlinux`: https://superuser.com/questions/1376944/can-qemu-boot-linux-from-vmlinux-instead-of-bzimage
  6123. Converting `arch/*` images to `vmlinux` is possible in theory x86 with https://github.com/torvalds/linux/blob/v5.1/scripts/extract-vmlinux[`extract-vmlinux`] but we didn't get any gem5 boots working from images generated like that for some reason, see: https://github.com/cirosantilli/linux-kernel-module-cheat/issues/79
  6124. == Xen
  6125. TODO: get prototype working and then properly integrate:
  6126. ....
  6127. ./build-xen
  6128. ....
  6129. Source: link:build-xen[]
  6130. This script attempts to build Xen for aarch64 and feed it into QEMU through link:submodules/boot-wrapper-aarch64[]
  6131. TODO: other archs not yet attempted.
  6132. The current bad behaviour is that it prints just:
  6133. ....
  6134. Boot-wrapper v0.2
  6135. ....
  6136. and nothing else.
  6137. We will also need `CONFIG_XEN=y` on the Linux kernel, but first Xen should print some Xen messages before the kernel is ever reached.
  6138. If we pass to QEMU the xen image directly instead of the boot wrapper one:
  6139. ....
  6140. -kernel ../xen/xen/xen
  6141. ....
  6142. then Xen messages do show up! So it seems that the configuration failure lies in the boot wrapper itself rather than Xen.
  6143. Maybe it is also possible to run Xen directly like this: QEMU can already load multiple images at different memory locations with the generic loader: https://github.com/qemu/qemu/blob/master/docs/generic-loader.txt which looks something along:
  6144. ....
  6145. -kernel file1.elf -device loader,file=file2.elf
  6146. ....
  6147. so as long as we craft the correct DTB and feed it into Xen so that it can see the kernel, it should work. TODO does QEMU support patching the auto-generated DTB with pre-generated options? In the worst case we can just dump it hand hack it up though with `-machine dumpdtb`, see: xref:device-tree-emulator-generation[xrefstyle=full].
  6148. Bibliography:
  6149. * this attempt was based on: https://wiki.xenproject.org/wiki/Xen_ARM_with_Virtualization_Extensions/FastModels which is the documentation for the ARM Fast Models closed source simulators.
  6150. * https://wiki.xenproject.org/wiki/Xen_ARM_with_Virtualization_Extensions/qemu-system-aarch64 this is the only QEMU aarch64 Xen page on the web. It uses the Ubuntu aarc64 image, which has EDK2.
  6151. +
  6152. I however see no joy on blobs. Buildroot does not seem to support EDK 2.
  6153. Link on readme https://stackoverflow.com/questions/49348453/xen-on-qemu-with-arm64-architecture
  6154. == U-Boot
  6155. https://en.wikipedia.org/wiki/Das_U-Boot
  6156. U-Boot is a popular bootloader.
  6157. It can read disk filesystems, and Buildroot supports it, so we could in theory put it into memory, and let it find a kernel image from the root filesystem and boot that, but I didn't manage to get it working yet: https://stackoverflow.com/questions/58028789/how-to-boot-linux-aarch64-with-u-boot-with-buildroot-on-qemu
  6158. == QEMU
  6159. === Introduction to QEMU
  6160. https://en.wikipedia.org/wiki/QEMU[QEMU] is a system simulator: it simulates a CPU and devices such as interrupt handlers, timers, UART, screen, keyboard, etc.
  6161. If you are familiar with https://en.wikipedia.org/wiki/VirtualBox[VirtualBox], then QEMU then basically does the same thing: it opens a "window" inside your desktop that can run an operating system inside your operating system.
  6162. Also both can use very similar techniques: either https://en.wikipedia.org/wiki/Binary_translation[binary translation] or <<KVM>>. VirtualBox' binary translator is / was based on QEMU's it seems: https://en.wikipedia.org/wiki/VirtualBox#Software-based_virtualization
  6163. The huge advantage of QEMU over VirtualBox is that is supports cross arch simulation, e.g. simulate an ARM guest on an x86 host.
  6164. QEMU is likely the leading cross arch system simulator as of 2018. It is even the default <<android>> simulator that developers get with Android Studio 3 to develop apps without real hardware.
  6165. Another advantage of QEMU over virtual box is that it doesn't have Oracle' hands all all over it, more like RedHat + ARM.
  6166. Another advantage of QEMU is that is has no nice configuration GUI. Because who needs GUIs when you have 50 million semi-documented CLI options? Android Studio adds a custom GUI configuration tool on top of it.
  6167. QEMU is also supported by Buildroot in-tree, see e.g.: https://github.com/buildroot/buildroot/blob/2018.05/configs/qemu_aarch64_virt_defconfig We however just build our own manually with link:build-qemu[], as it gives more flexibility, and building QEMU is very easy!
  6168. All of this makes QEMU the natural choice of reference system simulator for this repo.
  6169. === Disk persistency
  6170. We disable disk persistency for both QEMU and gem5 by default, to prevent the emulator from putting the image in an unknown state.
  6171. For QEMU, this is done by passing the `snapshot` option to `-drive`, and for gem5 it is the default behaviour.
  6172. If you hack up our link:run[] script to remove that option, then:
  6173. ....
  6174. ./run --eval-after 'date >f;poweroff'
  6175. ....
  6176. followed by:
  6177. ....
  6178. ./run --eval-after 'cat f'
  6179. ....
  6180. gives the date, because `poweroff` without `-n` syncs before shutdown.
  6181. The `sync` command also saves the disk:
  6182. ....
  6183. sync
  6184. ....
  6185. When you do:
  6186. ....
  6187. ./build-buildroot
  6188. ....
  6189. the disk image gets overwritten by a fresh filesystem and you lose all changes.
  6190. Remember that if you forcibly turn QEMU off without `sync` or `poweroff` from inside the VM, e.g. by closing the QEMU window, disk changes may not be saved.
  6191. Persistency is also turned off when booting from <<initrd>> with a CPIO instead of with a disk.
  6192. Disk persistency is useful to re-run shell commands from the history of a previous session with `Ctrl-R`, but we felt that the loss of determinism was not worth it.
  6193. ==== gem5 disk persistency
  6194. TODO how to make gem5 disk writes persistent?
  6195. As of cadb92f2df916dbb47f428fd1ec4932a2e1f0f48 there are some `read_only` entries in the <<gem5-config-ini>> under cow sections, but hacking them to true did not work:
  6196. ....
  6197. diff --git a/configs/common/FSConfig.py b/configs/common/FSConfig.py
  6198. index 17498c42b..76b8b351d 100644
  6199. --- a/configs/common/FSConfig.py
  6200. +++ b/configs/common/FSConfig.py
  6201. @@ -60,7 +60,7 @@ os_types = { 'alpha' : [ 'linux' ],
  6202. }
  6203. class CowIdeDisk(IdeDisk):
  6204. - image = CowDiskImage(child=RawDiskImage(read_only=True),
  6205. + image = CowDiskImage(child=RawDiskImage(read_only=False),
  6206. read_only=False)
  6207. def childImage(self, ci):
  6208. ....
  6209. The directory of interest is `src/dev/storage`.
  6210. === gem5 qcow2
  6211. qcow2 does not appear supported, there are not hits in the source tree, and there is a mention on Nate's 2009 wishlist: http://gem5.org/Nate%27s_Wish_List
  6212. This would be good to allow storing smaller sparse ext2 images locally on disk.
  6213. === Snapshot
  6214. QEMU allows us to take snapshots at any time through the monitor.
  6215. You can then restore CPU, memory and disk state back at any time.
  6216. qcow2 filesystems must be used for that to work.
  6217. To test it out, login into the VM with and run:
  6218. ....
  6219. ./run --eval-after 'umount /mnt/9p/*;./count.sh'
  6220. ....
  6221. On another shell, take a snapshot:
  6222. ....
  6223. ./qemu-monitor savevm my_snap_id
  6224. ....
  6225. The counting continues.
  6226. Restore the snapshot:
  6227. ....
  6228. ./qemu-monitor loadvm my_snap_id
  6229. ....
  6230. and the counting goes back to where we saved. This shows that CPU and memory states were reverted.
  6231. The `umount` is needed because snapshotting conflicts with <<9p>>, which we felt is a more valuable default. If you forget to unmount, the following error appears on the QEMU monitor:
  6232. .....
  6233. Migration is disabled when VirtFS export path '/linux-kernel-module-cheat/out/x86_64/buildroot/build' is mounted in the guest using mount_tag 'host_out'
  6234. .....
  6235. We can also verify that the disk state is also reversed. Guest:
  6236. ....
  6237. echo 0 >f
  6238. ....
  6239. Monitor:
  6240. ....
  6241. ./qemu-monitor savevm my_snap_id
  6242. ....
  6243. Guest:
  6244. ....
  6245. echo 1 >f
  6246. ....
  6247. Monitor:
  6248. ....
  6249. ./qemu-monitor loadvm my_snap_id
  6250. ....
  6251. Guest:
  6252. ....
  6253. cat f
  6254. ....
  6255. And the output is `0`.
  6256. Our setup does not allow for snapshotting while using <<initrd>>.
  6257. Bibliography: https://stackoverflow.com/questions/40227651/does-qemu-emulator-have-checkpoint-function/48724371#48724371
  6258. ==== Snapshot internals
  6259. Snapshots are stored inside the `.qcow2` images themselves.
  6260. They can be observed with:
  6261. ....
  6262. "$(./getvar buildroot_host_dir)/bin/qemu-img" info "$(./getvar qcow2_file)"
  6263. ....
  6264. which after `savevm my_snap_id` and `savevm asdf` contains an output of type:
  6265. ....
  6266. image: out/x86_64/buildroot/images/rootfs.ext2.qcow2
  6267. file format: qcow2
  6268. virtual size: 512M (536870912 bytes)
  6269. disk size: 180M
  6270. cluster_size: 65536
  6271. Snapshot list:
  6272. ID TAG VM SIZE DATE VM CLOCK
  6273. 1 my_snap_id 47M 2018-04-27 21:17:50 00:00:15.251
  6274. 2 asdf 47M 2018-04-27 21:20:39 00:00:18.583
  6275. Format specific information:
  6276. compat: 1.1
  6277. lazy refcounts: false
  6278. refcount bits: 16
  6279. corrupt: false
  6280. ....
  6281. As a consequence:
  6282. * it is possible to restore snapshots across boots, since they stay on the same image the entire time
  6283. * it is not possible to use snapshots with <<initrd>> in our setup, since we don't pass `-drive` at all when initrd is enabled
  6284. === Device models
  6285. This section documents:
  6286. * how to interact with peripheral hardware device models through device drivers
  6287. * how to write your own hardware device models for our emulators, see also: https://stackoverflow.com/questions/28315265/how-to-add-a-new-device-in-qemu-source-code
  6288. For the more complex interfaces, we focus on simplified educational devices, either:
  6289. * present in the QEMU upstream:
  6290. ** <<qemu-edu>>
  6291. * added in https://github.com/cirosantilli/qemu[our fork of QEMU]:
  6292. ** <<pci_min>>
  6293. ** <<platform_device>>
  6294. ==== PCI
  6295. Only tested in x86.
  6296. ===== pci_min
  6297. PCI driver for our minimal `pci_min.c` QEMU fork device:
  6298. ....
  6299. ./run -- -device lkmc_pci_min
  6300. ....
  6301. then:
  6302. ....
  6303. insmod pci_min.ko
  6304. ....
  6305. Sources:
  6306. * Kernel module: link:kernel_modules/pci_min.c[].
  6307. * QEMU device: https://github.com/cirosantilli/qemu/blob/lkmc/hw/misc/lkmc_pci_min.c
  6308. Outcome:
  6309. ....
  6310. <4>[ 10.608241] pci_min: loading out-of-tree module taints kernel.
  6311. <6>[ 10.609935] probe
  6312. <6>[ 10.651881] dev->irq = 11
  6313. lkmc_pci_min mmio_write addr = 0 val = 12345678 size = 4
  6314. <6>[ 10.668515] irq_handler irq = 11 dev = 251
  6315. lkmc_pci_min mmio_write addr = 4 val = 0 size = 4
  6316. ....
  6317. What happened:
  6318. * right at probe time, we write to a register
  6319. * our hardware model is coded such that it generates an interrupt when written to
  6320. * the Linux kernel interrupt handler write to another register, which tells the hardware to stop sending interrupts
  6321. Kernel messages and printks from inside QEMU are shown all together, to see that more clearly, run in <<qemu-graphic-mode>> instead.
  6322. We don't enable the device by default because it does not work for vanilla QEMU, which we often want to test with this repository.
  6323. Probe already does a MMIO write, which generates an IRQ and tests everything.
  6324. [[qemu-edu]]
  6325. ===== QEMU edu PCI device
  6326. Small upstream educational PCI device:
  6327. ....
  6328. ./qemu_edu.sh
  6329. ....
  6330. This tests a lot of features of the edu device, to understand the results, compare the inputs with the documentation of the hardware: https://github.com/qemu/qemu/blob/v2.12.0/docs/specs/edu.txt
  6331. Sources:
  6332. * kernel module: link:kernel_modules/qemu_edu.c[]
  6333. * QEMU device: https://github.com/qemu/qemu/blob/v2.12.0/hw/misc/edu.c
  6334. * test script: link:rootfs_overlay/lkmc/qemu_edu.sh[]
  6335. Works because we add to our default QEMU CLI:
  6336. ....
  6337. -device edu
  6338. ....
  6339. This example uses:
  6340. * the QEMU `edu` educational device, which is a minimal educational in-tree PCI example
  6341. * the `pci.ko` kernel module, which exercises the `edu` hardware.
  6342. +
  6343. I've contacted the awesome original author author of `edu` https://github.com/jirislaby[Jiri Slaby], and he told there is no official kernel module example because this was created for a kernel module university course that he gives, and he didn't want to give away answers. https://github.com/cirosantilli/how-to-teach-efficiently[I don't agree with that philosophy], so students, cheat away with this repo and go make startups instead.
  6344. TODO exercise DMA on the kernel module. The `edu` hardware model has that feature:
  6345. * https://stackoverflow.com/questions/32592734/are-there-any-dma-driver-example-pcie-and-fpga/44716747#44716747
  6346. * https://stackoverflow.com/questions/17913679/how-to-instantiate-and-use-a-dma-driver-linux-module
  6347. ===== Manipulate PCI registers directly
  6348. In this section we will try to interact with PCI devices directly from userland without kernel modules.
  6349. First identify the PCI device with:
  6350. ....
  6351. lspci
  6352. ....
  6353. In our case for example, we see:
  6354. ....
  6355. 00:06.0 Unclassified device [00ff]: Device 1234:11e8 (rev 10)
  6356. 00:07.0 Unclassified device [00ff]: Device 1234:11e9
  6357. ....
  6358. which we identify as being `edu` and `pci_min` respectively by the magic numbers: `1234:11e?`
  6359. Alternatively, we can also do use the QEMU monitor:
  6360. ....
  6361. ./qemu-monitor info qtree
  6362. ....
  6363. which gives:
  6364. ....
  6365. dev: lkmc_pci_min, id ""
  6366. addr = 07.0
  6367. romfile = ""
  6368. rombar = 1 (0x1)
  6369. multifunction = false
  6370. command_serr_enable = true
  6371. x-pcie-lnksta-dllla = true
  6372. x-pcie-extcap-init = true
  6373. class Class 00ff, addr 00:07.0, pci id 1234:11e9 (sub 1af4:1100)
  6374. bar 0: mem at 0xfeb54000 [0xfeb54007]
  6375. dev: edu, id ""
  6376. addr = 06.0
  6377. romfile = ""
  6378. rombar = 1 (0x1)
  6379. multifunction = false
  6380. command_serr_enable = true
  6381. x-pcie-lnksta-dllla = true
  6382. x-pcie-extcap-init = true
  6383. class Class 00ff, addr 00:06.0, pci id 1234:11e8 (sub 1af4:1100)
  6384. bar 0: mem at 0xfea00000 [0xfeafffff]
  6385. ....
  6386. See also: https://serverfault.com/questions/587189/list-all-devices-emulated-for-a-vm/913622#913622
  6387. Read the configuration registers as binary:
  6388. ....
  6389. hexdump /sys/bus/pci/devices/0000:00:06.0/config
  6390. ....
  6391. Get nice human readable names and offsets of the registers and some enums:
  6392. ....
  6393. setpci --dumpregs
  6394. ....
  6395. Get the values of a given config register from its human readable name, either with either bus or device id:
  6396. ....
  6397. setpci -s 0000:00:06.0 BASE_ADDRESS_0
  6398. setpci -d 1234:11e9 BASE_ADDRESS_0
  6399. ....
  6400. Note however that `BASE_ADDRESS_0` also appears when you do:
  6401. ....
  6402. lspci -v
  6403. ....
  6404. as:
  6405. ....
  6406. Memory at feb54000
  6407. ....
  6408. Then you can try messing with that address with <<dev-mem>>:
  6409. ....
  6410. devmem 0xfeb54000 w 0x12345678
  6411. ....
  6412. which writes to the first register of our <<pci_min>> device.
  6413. The device then fires an interrupt at irq 11, which is unhandled, which leads the kernel to say you are a bad boy:
  6414. ....
  6415. lkmc_pci_min mmio_write addr = 0 val = 12345678 size = 4
  6416. <5>[ 1064.042435] random: crng init done
  6417. <3>[ 1065.567742] irq 11: nobody cared (try booting with the "irqpoll" option)
  6418. ....
  6419. followed by a trace.
  6420. Next, also try using our <<irq-ko>> IRQ monitoring module before triggering the interrupt:
  6421. ....
  6422. insmod irq.ko
  6423. devmem 0xfeb54000 w 0x12345678
  6424. ....
  6425. Our kernel module handles the interrupt, but does not acknowledge it like our proper <<pci_min>> kernel module, and so it keeps firing, which leads to infinitely many messages being printed:
  6426. ....
  6427. handler irq = 11 dev = 251
  6428. ....
  6429. ===== pciutils
  6430. There are two versions of `setpci` and `lspci`:
  6431. * a simple one from BusyBox
  6432. * a more complete one from https://github.com/pciutils/pciutils[pciutils] which Buildroot has a package for, and is the default on Ubuntu 18.04 host. This is the one we enable by default.
  6433. ===== Introduction to PCI
  6434. The PCI standard is non-free, obviously like everything in low level: https://pcisig.com/specifications but Google gives several illegal PDF hits :-)
  6435. And of course, the best documentation available is: http://wiki.osdev.org/PCI
  6436. Like every other hardware, we could interact with PCI on x86 using only IO instructions and memory operations.
  6437. But PCI is a complex communication protocol that the Linux kernel implements beautifully for us, so let's use the kernel API.
  6438. Bibliography:
  6439. * edu device source and spec in QEMU tree:
  6440. ** https://github.com/qemu/qemu/blob/v2.7.0/hw/misc/edu.c
  6441. ** https://github.com/qemu/qemu/blob/v2.7.0/docs/specs/edu.txt
  6442. * http://www.zarb.org/~trem/kernel/pci/pci-driver.c inb outb runnable example (no device)
  6443. * LDD3 PCI chapter
  6444. * another QEMU device + module, but using a custom QEMU device:
  6445. ** https://github.com/levex/kernel-qemu-pci/blob/31fc9355161b87cea8946b49857447ddd34c7aa6/module/levpci.c
  6446. ** https://github.com/levex/kernel-qemu-pci/blob/31fc9355161b87cea8946b49857447ddd34c7aa6/qemu/hw/char/lev-pci.c
  6447. * https://is.muni.cz/el/1433/podzim2016/PB173/um/65218991/ course given by the creator of the edu device. In Czech, and only describes API
  6448. * http://nairobi-embedded.org/linux_pci_device_driver.html
  6449. ===== PCI BFD
  6450. `lspci -k` shows something like:
  6451. ....
  6452. 00:04.0 Class 00ff: 1234:11e8 lkmc_pci
  6453. ....
  6454. Meaning of the first numbers:
  6455. ....
  6456. <8:bus>:<5:device>.<3:function>
  6457. ....
  6458. Often abbreviated to BDF.
  6459. * bus: groups PCI slots
  6460. * device: maps to one slot
  6461. * function: https://stackoverflow.com/questions/19223394/what-is-the-function-number-in-pci/44735372#44735372
  6462. Sometimes a fourth number is also added, e.g.:
  6463. ....
  6464. 0000:00:04.0
  6465. ....
  6466. TODO is that the domain?
  6467. Class: pure magic: https://www-s.acm.illinois.edu/sigops/2007/roll_your_own/7.c.1.html TODO: does it have any side effects? Set in the edu device at:
  6468. ....
  6469. k->class_id = PCI_CLASS_OTHERS
  6470. ....
  6471. ===== PCI BAR
  6472. https://stackoverflow.com/questions/30190050/what-is-base-address-register-bar-in-pcie/44716618#44716618
  6473. Each PCI device has 6 BAR IOs (base address register) as per the PCI spec.
  6474. Each BAR corresponds to an address range that can be used to communicate with the PCI.
  6475. Each BAR is of one of the two types:
  6476. * `IORESOURCE_IO`: must be accessed with `inX` and `outX`
  6477. * `IORESOURCE_MEM`: must be accessed with `ioreadX` and `iowriteX`. This is the saner method apparently, and what the edu device uses.
  6478. The length of each region is defined by the hardware, and communicated to software via the configuration registers.
  6479. The Linux kernel automatically parses the 64 bytes of standardized configuration registers for us.
  6480. QEMU devices register those regions with:
  6481. ....
  6482. memory_region_init_io(&edu->mmio, OBJECT(edu), &edu_mmio_ops, edu,
  6483. "edu-mmio", 1 << 20);
  6484. pci_register_bar(pdev, 0, PCI_BASE_ADDRESS_SPACE_MEMORY, &edu->mmio);
  6485. ....
  6486. ==== GPIO
  6487. TODO: broken. Was working before we moved `arm` from `-M versatilepb` to `-M virt` around af210a76711b7fa4554dcc2abd0ddacfc810dfd4. Either make it work on `-M virt` if that is possible, or document precisely how to make it work with `versatilepb`, or hopefully `vexpress` which is newer.
  6488. QEMU does not have a very nice mechanism to observe GPIO activity: https://raspberrypi.stackexchange.com/questions/56373/is-it-possible-to-get-the-state-of-the-leds-and-gpios-in-a-qemu-emulation-like-t/69267#69267
  6489. The best you can do is to hack our link:build[] script to add:
  6490. ....
  6491. HOST_QEMU_OPTS='--extra-cflags=-DDEBUG_PL061=1'
  6492. ....
  6493. where http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.ddi0190b/index.html[PL061] is the dominating ARM Holdings hardware that handles GPIO.
  6494. Then compile with:
  6495. ....
  6496. ./build-buildroot --arch arm --config-fragment buildroot_config/gpio
  6497. ./build-linux --config-fragment linux_config/gpio
  6498. ....
  6499. then test it out with:
  6500. ....
  6501. ./gpio.sh
  6502. ....
  6503. Source: link:rootfs_overlay/lkmc/gpio.sh[]
  6504. Buildroot's Linux tools package provides some GPIO CLI tools: `lsgpio`, `gpio-event-mon`, `gpio-hammer`, TODO document them here.
  6505. ==== LEDs
  6506. TODO: broken when `arm` moved to `-M virt`, same as <<gpio>>.
  6507. Hack QEMU's `hw/misc/arm_sysctl.c` with a printf:
  6508. ....
  6509. static void arm_sysctl_write(void *opaque, hwaddr offset,
  6510. uint64_t val, unsigned size)
  6511. {
  6512. arm_sysctl_state *s = (arm_sysctl_state *)opaque;
  6513. switch (offset) {
  6514. case 0x08: /* LED */
  6515. printf("LED val = %llx\n", (unsigned long long)val);
  6516. ....
  6517. and then rebuild with:
  6518. ....
  6519. ./build-qemu --arch arm
  6520. ./build-linux --arch arm --config-fragment linux_config/leds
  6521. ....
  6522. But beware that one of the LEDs has a heartbeat trigger by default (specified on dts), so it will produce a lot of output.
  6523. And then activate it with:
  6524. ....
  6525. cd /sys/class/leds/versatile:0
  6526. cat max_brightness
  6527. echo 255 >brightness
  6528. ....
  6529. Relevant QEMU files:
  6530. * `hw/arm/versatilepb.c`
  6531. * `hw/misc/arm_sysctl.c`
  6532. Relevant kernel files:
  6533. * `arch/arm/boot/dts/versatile-pb.dts`
  6534. * `drivers/leds/led-class.c`
  6535. * `drivers/leds/leds-sysctl.c`
  6536. ==== platform_device
  6537. Minimal platform device example coded into the `-M versatilepb` SoC of our QEMU fork.
  6538. Using this device now requires checking out to the branch:
  6539. ....
  6540. git checkout platform-device
  6541. git submodule sync
  6542. ....
  6543. before building, it does not work on master.
  6544. Rationale: we found out that the kernels that build for `qemu -M versatilepb` don't work on gem5 because `versatilepb` is an old pre-v7 platform, and gem5 requires armv7. So we migrated over to `-M virt` to have a single kernel for both gem5 and QEMU, and broke this since the single kernel was more important. TODO port to `-M virt`.
  6545. The module itself can be found at: https://github.com/cirosantilli/linux-kernel-module-cheat/blob/platform-device/kernel_modules/platform_device.c
  6546. Uses:
  6547. * `hw/misc/lkmc_platform_device.c` minimal device added in our QEMU fork to `-M versatilepb`
  6548. * the device tree entry we added to our Linux kernel fork: https://github.com/cirosantilli/linux/blob/361bb623671a52a36a077a6dd45843389a687a33/arch/arm/boot/dts/versatile-pb.dts#L42
  6549. Expected outcome after insmod:
  6550. * QEMU reports MMIO with printfs
  6551. * IRQs are generated and handled by this module, which logs to dmesg
  6552. Without insmoding this module, try writing to the register with <<dev-mem>>:
  6553. ....
  6554. devmem 0x101e9000 w 0x12345678
  6555. ....
  6556. We can also observe the interrupt with <<dummy-irq>>:
  6557. ....
  6558. modprobe dummy-irq irq=34
  6559. insmod platform_device.ko
  6560. ....
  6561. The IRQ number `34` was found by on the dmesg after:
  6562. ....
  6563. insmod platform_device.ko
  6564. ....
  6565. Bibliography: https://stackoverflow.com/questions/28315265/how-to-add-a-new-device-in-qemu-source-code/44612957#44612957
  6566. ==== gem5 educational hardware models
  6567. TODO get some working!
  6568. http://gedare-csphd.blogspot.co.uk/2013/02/adding-simple-io-device-to-gem5.html
  6569. === QEMU monitor
  6570. The QEMU monitor is a magic terminal that allows you to send text commands to the QEMU VM itself: https://en.wikibooks.org/wiki/QEMU/Monitor
  6571. While QEMU is running, on another terminal, run:
  6572. ....
  6573. ./qemu-monitor
  6574. ....
  6575. or send one command such as `info qtree` and quit the monitor:
  6576. ....
  6577. ./qemu-monitor info qtree
  6578. ....
  6579. or equivalently:
  6580. ....
  6581. echo 'info qtree' | ./qemu-monitor
  6582. ....
  6583. Source: link:qemu-monitor[]
  6584. `qemu-monitor` uses the `-monitor` QEMU command line option, which makes the monitor listen from a socket.
  6585. Alternatively, we can also enter the QEMU monitor from inside `-nographics` <<qemu-text-mode>> with:
  6586. ....
  6587. Ctrl-A C
  6588. ....
  6589. and go back to the terminal with:
  6590. ....
  6591. Ctrl-A C
  6592. ....
  6593. * https://stackoverflow.com/questions/14165158/how-to-switch-to-qemu-monitor-console-when-running-with-curses
  6594. * https://superuser.com/questions/488263/how-to-switch-to-the-qemu-control-panel-with-nographics
  6595. When in graphic mode, we can do it from the GUI:
  6596. ....
  6597. Ctrl-Alt ?
  6598. ....
  6599. where `?` is a digit `1`, or `2`, or, `3`, etc. depending on what else is available on the GUI: serial, parallel and frame buffer.
  6600. Finally, we can also access QEMU monitor commands directly from <<gdb>> with the `monitor` command:
  6601. ....
  6602. ./run-gdb
  6603. ....
  6604. then inside that shell:
  6605. ....
  6606. monitor info qtree
  6607. ....
  6608. This way you can use both QEMU monitor and GDB commands to inspect the guest from inside a single shell! Pretty awesome.
  6609. In general, `./qemu-monitor` is the best option, as it:
  6610. * works on both modes
  6611. * allows to use the host Bash history to re-run one off commands
  6612. * allows you to search the output of commands on your host shell even when in graphic mode
  6613. Getting everything to work required careful choice of QEMU command line options:
  6614. * https://stackoverflow.com/questions/49716931/how-to-run-qemu-with-nographic-and-monitor-but-still-be-able-to-send-ctrlc-to/49751144#49751144
  6615. * https://unix.stackexchange.com/questions/167165/how-to-pass-ctrl-c-to-the-guest-when-running-qemu-with-nographic/436321#436321
  6616. ==== QEMU monitor from guest
  6617. Peter Maydell said potentially not possible nicely as of August 2018: https://stackoverflow.com/questions/51747744/how-to-run-a-qemu-monitor-command-from-inside-the-guest/51764110#51764110
  6618. It is also worth looking into the QEMU Guest Agent tool `qemu-gq` that can be enabled with:
  6619. ....
  6620. ./build-buildroot --config 'BR2_PACKAGE_QEMU=y'
  6621. ....
  6622. See also: https://superuser.com/questions/930588/how-to-pass-commands-noninteractively-to-running-qemu-from-the-guest-qmp-via-te
  6623. ==== QEMU monitor from GDB
  6624. When doing <<gdb>> it is possible to send QEMU monitor commands through the GDB `monitor` command, which saves you the trouble of opening yet another shell.
  6625. Try for example:
  6626. ....
  6627. monitor help
  6628. monitor info qtree
  6629. ....
  6630. === Debug the emulator
  6631. When you start hacking QEMU or gem5, it is useful to see what is going on inside the emulator themselves.
  6632. This is of course trivial since they are just regular userland programs on the host, but we make it a bit easier with:
  6633. ....
  6634. ./run --debug-vm
  6635. ....
  6636. Or for a faster development loop:
  6637. ....
  6638. ./run --debug-vm-args '-ex "break qemu_add_opts" -ex "run"'
  6639. ....
  6640. Our default emulator builds are optimized with `gcc -O2 -g`. To use `-O0` instead, build and run with:
  6641. ....
  6642. ./build-qemu --qemu-build-type debug --verbose
  6643. ./run --debug-vm
  6644. ./build-gem5 --gem5-build-type debug --verbose
  6645. ./run --debug-vm --emulator-gem5
  6646. ....
  6647. The `--verbose` is optional, but shows clearly each GCC build command so that you can confirm what `--*-build-type` is doing.
  6648. The build outputs are automatically stored in a different directories for optimized and debug builds, which prevents `debug` files from overwriting `opt` ones. Therefore, `--gem5-build-id` is not required.
  6649. The price to pay for debuggability is high however: a Linux kernel boot was about 3x slower in QEMU and 14 times slower in gem5 debug compared to opt, see benchmarks at: xref:benchmark-linux-kernel-boot[xrefstyle=full]
  6650. When in <<qemu-text-mode>>, using `--debug-vm` makes Ctrl-C not get passed to the QEMU guest anymore: it is instead captured by GDB itself, so allow breaking. So e.g. you won't be able to easily quit from a guest program like:
  6651. ....
  6652. sleep 10
  6653. ....
  6654. In graphic mode, make sure that you never click inside the QEMU graphic while debugging, otherwise you mouse gets captured forever, and the only solution I can find is to go to a TTY with `Ctrl-Alt-F1` and `kill` QEMU.
  6655. You can still send key presses to QEMU however even without the mouse capture, just either click on the title bar, or alt tab to give it focus.
  6656. ==== Reverse debug the emulator
  6657. While step debugging any complex program, you always end up feeling the need to step in reverse to reach the last call to some function that was called before the failure point, in order to trace back the problem to the actual bug source.
  6658. While GDB "has" this feature, it is just too broken to be usable, and so we expose the amazing Mozilla RR tool conveniently in this repo: https://stackoverflow.com/questions/1470434/how-does-reverse-debugging-work/53063242#53063242
  6659. Before the first usage:
  6660. ....
  6661. echo 'kernel.perf_event_paranoid=1' | sudo tee -a /etc/sysctl.conf
  6662. sudo sysctl -p
  6663. ....
  6664. Then use it with your content of interest, for example:
  6665. ....
  6666. ./run --debug-vm-rr --userland userland/c/hello.c
  6667. ....
  6668. This will first run the program once until completion, and then restart the program at the very first instruction at `_start` and leave you in a GDB shell.
  6669. From there, run the program until your point of interest, e.g.:
  6670. ....
  6671. break qemu_add_opts
  6672. continue
  6673. ....
  6674. and you can now reliably use reverse debugging commands such as `reverse-continue`, `reverse-finish` and `reverse-next`!
  6675. To restart debugging again after quitting `rr`, simply run on your host terminal:
  6676. ....
  6677. rr replay
  6678. ....
  6679. Programs often tend to blow up in very low frames that use values passed in from higher frames. In those cases, remember that just like with forward debugging, you can't just go:
  6680. ....
  6681. up
  6682. up
  6683. up
  6684. reverse-next
  6685. ....
  6686. but rather, you must:
  6687. ....
  6688. reverse-finish
  6689. reverse-finish
  6690. reverse-finish
  6691. reverse-next
  6692. ....
  6693. ==== Debug gem5 Python scripts
  6694. Start pdb at the first instruction:
  6695. ....
  6696. ./run --emulator gem5 --gem5-exe-args='--pdb' --terminal
  6697. ....
  6698. Requires `--terminal` as we must be on foreground.
  6699. Alternatively, you can add to the point of the code where you want to break the usual:
  6700. ....
  6701. import ipdb; ipdb.set_trace()
  6702. ....
  6703. and then run with:
  6704. ....
  6705. ./run --emulator gem5 --terminal
  6706. ....
  6707. TODO test PyCharm: https://stackoverflow.com/questions/51982735/writing-gem5-configuration-scripts-with-pycharm
  6708. === Tracing
  6709. QEMU can log several different events.
  6710. The most interesting are events which show instructions that QEMU ran, for which we have a helper:
  6711. ....
  6712. ./trace-boot --arch x86_64
  6713. ....
  6714. Under the hood, this uses QEMU's `-trace` option.
  6715. You can then inspect the address of each instruction run:
  6716. ....
  6717. less "$(./getvar --arch x86_64 run_dir)/trace.txt"
  6718. ....
  6719. Sample output excerpt:
  6720. ....
  6721. exec_tb 0.000 pid=10692 tb=0x7fb4f8000040 pc=0xfffffff0
  6722. exec_tb 35.391 pid=10692 tb=0x7fb4f8000180 pc=0xfe05b
  6723. exec_tb 21.047 pid=10692 tb=0x7fb4f8000340 pc=0xfe066
  6724. exec_tb 12.197 pid=10692 tb=0x7fb4f8000480 pc=0xfe06a
  6725. ....
  6726. Get the list of available trace events:
  6727. ....
  6728. ./run --trace help
  6729. ....
  6730. TODO: any way to show the actualy disassembled instruction executed directly from there? Possible with <<qemu-d-tracing>>.
  6731. Enable other specific trace events:
  6732. ....
  6733. ./run --trace trace1,trace2
  6734. ./qemu-trace2txt -a "$arch"
  6735. less "$(./getvar -a "$arch" run_dir)/trace.txt"
  6736. ....
  6737. This functionality relies on the following setup:
  6738. * `./configure --enable-trace-backends=simple`. This logs in a binary format to the trace file.
  6739. +
  6740. It makes 3x execution faster than the default trace backend which logs human readable data to stdout.
  6741. +
  6742. Logging with the default backend `log` greatly slows down the CPU, and in particular leads to this boot message:
  6743. +
  6744. ....
  6745. All QSes seen, last rcu_sched kthread activity 5252 (4294901421-4294896169), jiffies_till_next_fqs=1, root ->qsmask 0x0
  6746. swapper/0 R running task 0 1 0 0x00000008
  6747. ffff880007c03ef8 ffffffff8107aa5d ffff880007c16b40 ffffffff81a3b100
  6748. ffff880007c03f60 ffffffff810a41d1 0000000000000000 0000000007c03f20
  6749. fffffffffffffedc 0000000000000004 fffffffffffffedc ffffffff00000000
  6750. Call Trace:
  6751. <IRQ> [<ffffffff8107aa5d>] sched_show_task+0xcd/0x130
  6752. [<ffffffff810a41d1>] rcu_check_callbacks+0x871/0x880
  6753. [<ffffffff810a799f>] update_process_times+0x2f/0x60
  6754. ....
  6755. +
  6756. in which the boot appears to hang for a considerable time.
  6757. * patch QEMU source to remove the `disable` from `exec_tb` in the `trace-events` file. See also: https://rwmj.wordpress.com/2016/03/17/tracing-qemu-guest-execution/
  6758. ==== QEMU -d tracing
  6759. QEMU also has a second trace mechanism in addition to `-trace`, find out the events with:
  6760. ....
  6761. ./run -- -d help
  6762. ....
  6763. Let's pick the one that dumps executed instructions, `in_asm`:
  6764. ....
  6765. ./run --eval './linux/poweroff.out' -- -D out/trace.txt -d in_asm
  6766. less out/trace.txt
  6767. ....
  6768. Sample output excerpt:
  6769. ....
  6770. ----------------
  6771. IN:
  6772. 0xfffffff0: ea 5b e0 00 f0 ljmpw $0xf000:$0xe05b
  6773. ----------------
  6774. IN:
  6775. 0x000fe05b: 2e 66 83 3e 88 61 00 cmpl $0, %cs:0x6188
  6776. 0x000fe062: 0f 85 7b f0 jne 0xd0e1
  6777. ....
  6778. TODO: after `IN:`, symbol names are meant to show, which is awesome, but I don't get any. I do see them however when running a bare metal example from: https://github.com/cirosantilli/newlib-examples/tree/900a9725947b1f375323c7da54f69e8049158881
  6779. TODO: what is the point of having two mechanisms, `-trace` and `-d`? `-d` tracing is cool because it does not require a messy recompile, and it can also show symbols.
  6780. ==== QEMU trace register values
  6781. TODO: is it possible to show the register values for each instruction?
  6782. This would include the memory values read into the registers.
  6783. Asked at: https://superuser.com/questions/1377764/how-to-trace-the-register-values-of-executed-instructions-in-qemu
  6784. Seems impossible due to optimizations that QEMU does:
  6785. * https://lists.gnu.org/archive/html/qemu-devel/2015-06/msg07479.html
  6786. * https://lists.gnu.org/archive/html/qemu-devel/2014-04/msg02856.html
  6787. * https://lists.gnu.org/archive/html/qemu-devel/2012-08/msg03057.html
  6788. PANDA can list memory addresses, so I bet it can also decode the instructions: https://github.com/panda-re/panda/blob/883c85fa35f35e84a323ed3d464ff40030f06bd6/panda/docs/LINE_Censorship.md I wonder why they don't just upstream those things to QEMU's tracing: https://github.com/panda-re/panda/issues/290
  6789. gem5 can do it as shown at: xref:gem5-tracing[xrefstyle=full].
  6790. ==== QEMU trace memory accesses
  6791. Not possible apparently, not even with the `memory_region_ops_read` and `memory_region_ops_write` trace events, Peter comments https://lists.gnu.org/archive/html/qemu-devel/2015-06/msg07482.html
  6792. ____
  6793. No. You will miss all the fast-path memory accesses, which are
  6794. done with custom generated assembly in the TCG backend. In
  6795. general QEMU is not designed to support this kind of monitoring
  6796. of guest operations.
  6797. ____
  6798. Related question: https://reverseengineering.stackexchange.com/questions/12260/how-to-log-all-memory-accesses-read-and-write-including-the-memory-content-in
  6799. ==== Trace source lines
  6800. We can further use Binutils' `addr2line` to get the line that corresponds to each address:
  6801. ....
  6802. ./trace-boot --arch x86_64
  6803. ./trace2line --arch x86_64
  6804. less "$(./getvar --arch x86_64 run_dir)/trace-lines.txt"
  6805. ....
  6806. The last commands takes several seconds.
  6807. The format is as follows:
  6808. ....
  6809. 39368 _static_cpu_has arch/x86/include/asm/cpufeature.h:148
  6810. ....
  6811. Where:
  6812. * `39368`: number of consecutive times that a line ran. Makes the output much shorter and more meaningful
  6813. * `_static_cpu_has`: name of the function that contains the line
  6814. * `arch/x86/include/asm/cpufeature.h:148`: file and line
  6815. This could of course all be done with GDB, but it would likely be too slow to be practical.
  6816. TODO do even more awesome offline post-mortem analysis things, such as:
  6817. * detect if we are in userspace or kernelspace. Should be a simple matter of reading the
  6818. * read kernel data structures, and determine the current thread. Maybe we can reuse / extend the kernel's GDB Python scripts??
  6819. ==== QEMU record and replay
  6820. QEMU runs, unlike gem5, are not deterministic by default, however it does support a record and replay mechanism that allows you to replay a previous run deterministically.
  6821. This awesome feature allows you to examine a single run as many times as you would like until you understand everything:
  6822. ....
  6823. # Record a run.
  6824. ./run --eval-after './linux/rand_check.out;./linux/poweroff.out;' --record
  6825. # Replay the run.
  6826. ./run --eval-after './linux/rand_check.out;./linux/poweroff.out;' --replay
  6827. ....
  6828. A convenient shortcut to do both at once to test the feature is:
  6829. ....
  6830. ./qemu-rr --eval-after './linux/rand_check.out;./linux/poweroff.out;'
  6831. ....
  6832. By comparing the terminal output of both runs, we can see that they are the exact same, including things which normally differ across runs:
  6833. * timestamps of dmesg output
  6834. * <<rand_check-out>> output
  6835. The record and replay feature was revived around QEMU v3.0.0. It existed earlier but it rot completely. As of v3.0.0 it is still flaky: sometimes we get deadlocks, and only a limited number of command line arguments are supported.
  6836. Documented at: https://github.com/qemu/qemu/blob/v2.12.0/docs/replay.txt
  6837. TODO: using `-r` as above leads to a kernel warning:
  6838. ....
  6839. rcu_sched detected stalls on CPUs/tasks
  6840. ....
  6841. TODO: replay deadlocks intermittently at disk operations, last kernel message:
  6842. ....
  6843. EXT4-fs (sda): re-mounted. Opts: block_validity,barrier,user_xattr
  6844. ....
  6845. TODO replay with network gets stuck:
  6846. ....
  6847. ./qemu-rr --eval-after 'ifup -a;wget -S google.com;./linux/poweroff.out;'
  6848. ....
  6849. after the message:
  6850. ....
  6851. adding dns 10.0.2.3
  6852. ....
  6853. There is explicit network support on the QEMU patches, but either it is buggy or we are not using the correct magic options.
  6854. Solved on unmerged c42634d8e3428cfa60672c3ba89cabefc720cde9 from https://github.com/ispras/qemu/tree/rr-180725
  6855. TODO `arm` and `aarch64` only seem to work with initrd since I cannot plug a working IDE disk device? See also: https://lists.gnu.org/archive/html/qemu-devel/2018-02/msg05245.html
  6856. Then, when I tried with <<initrd>> and no disk:
  6857. ....
  6858. ./build-buildroot --arch aarch64 --initrd
  6859. ./qemu-rr --arch aarch64 --eval-after './linux/rand_check.out;./linux/poweroff.out;' --initrd
  6860. ....
  6861. QEMU crashes with:
  6862. ....
  6863. ERROR:replay/replay-time.c:49:replay_read_clock: assertion failed: (replay_file && replay_mutex_locked())
  6864. ....
  6865. I had the same error previously on x86-64, but it was fixed: https://bugs.launchpad.net/qemu/+bug/1762179 so maybe the forgot to fix it for `aarch64`?
  6866. Solved on unmerged c42634d8e3428cfa60672c3ba89cabefc720cde9 from https://github.com/ispras/qemu/tree/rr-180725
  6867. ===== QEMU reverse debugging
  6868. TODO get working.
  6869. QEMU replays support checkpointing, and this allows for a simplistic "reverse debugging" implementation proposed at https://lists.gnu.org/archive/html/qemu-devel/2018-06/msg00478.html on the unmerged https://github.com/ispras/qemu/tree/rr-180725[]:
  6870. ....
  6871. ./run --eval-after './linux/rand_check.out;./linux/poweroff.out;' --record
  6872. ./run --eval-after './linux/rand_check.out;./linux/poweroff.out;' --replay --gdb-wait
  6873. ....
  6874. On another shell:
  6875. ....
  6876. ./run-gdb start_kernel
  6877. ....
  6878. In GDB:
  6879. ....
  6880. n
  6881. n
  6882. n
  6883. n
  6884. reverse-continue
  6885. ....
  6886. and we are back at `start_kernel`
  6887. ==== QEMU trace multicore
  6888. TODO: is there any way to distinguish which instruction runs on each core? Doing:
  6889. ....
  6890. ./run --arch x86_64 --cpus 2 --eval './linux/poweroff.out' --trace exec_tb
  6891. ./qemu-trace2txt
  6892. ....
  6893. just appears to output both cores intertwined without any clear differentiation.
  6894. ==== QEMU get guest instruction count
  6895. TODO: https://stackoverflow.com/questions/58766571/how-to-count-the-number-of-guest-instructions-qemu-executed-from-the-beginning-t
  6896. ==== gem5 tracing
  6897. gem5 provides also provides a tracing mechanism documented at: http://www.gem5.org/Trace_Based_Debugging[]:
  6898. ....
  6899. ./run --arch aarch64 --eval 'm5 exit' --emulator gem5 --trace ExecAll
  6900. less "$(./getvar --arch aarch64 run_dir)/trace.txt"
  6901. ....
  6902. Our wrapper just forwards the options to the `--debug-flags` gem5 option.
  6903. Keep in mind however that the disassembly is very broken in several places as of 2019q2, so you can't always trust it.
  6904. Output the trace to stdout instead of a file:
  6905. ....
  6906. ./run \
  6907. --arch aarch64 \
  6908. --emulator gem5 \
  6909. --eval 'm5 exit' \
  6910. --trace ExecAll \
  6911. --trace-stdout \
  6912. ;
  6913. ....
  6914. We also have a shortcut for `--trace ExecAll -trace-stdout` with `--trace-insts-stdout`
  6915. ....
  6916. ./run \
  6917. --arch aarch64 \
  6918. --emulator gem5 \
  6919. --eval 'm5 exit' \
  6920. --trace-insts-stdout \
  6921. ;
  6922. ....
  6923. Be warned, the trace is humongous, at 16Gb.
  6924. This would produce a lot of output however, so you will likely not want that when tracing a Linux kernel boot instructions. But it can be very convenient for smaller traces such as <<baremetal>>.
  6925. List all available debug flags:
  6926. ....
  6927. ./run --arch aarch64 --gem5-exe-args='--debug-help' --emulator gem5
  6928. ....
  6929. but to understand most of them you have to look at the source code:
  6930. ....
  6931. less "$(./getvar gem5_source_dir)/src/cpu/SConscript"
  6932. less "$(./getvar gem5_source_dir)/src/cpu/exetrace.cc"
  6933. ....
  6934. The most important trace flags to know about are:
  6935. * <<gem5-execall-trace-format,`ExecAll`>>
  6936. * `Faults`: CPU exceptions / interrupts, see an example at: <<arm-svc-instruction>>
  6937. * <<gem5-registers-trace-format,`Registers`>>
  6938. * <<gem5-syscall-emulation-mode-syscall-tracing,`SyscallBase`, `SyscallVerbose`>>
  6939. Trace internals are discussed at: <<gem5-trace-internals>>.
  6940. As can be seen on the `Sconstruct`, `Exec` is just an alias that enables a set of flags.
  6941. We can make the trace smaller by naming the trace file as `trace.txt.gz`, which enables GZIP compression, but that is not currently exposed on our scripts, since you usually just need something human readable to work on.
  6942. Enabling tracing made the runtime about 4x slower on the <<p51>>, with or without `.gz` compression.
  6943. Trace the source lines just like <<trace-source-lines,for QEMU>> with:
  6944. ....
  6945. ./trace-boot --arch aarch64 --emulator gem5
  6946. ./trace2line --arch aarch64 --emulator gem5
  6947. less "$(./getvar --arch aarch64 run_dir)/trace-lines.txt"
  6948. ....
  6949. TODO: 7452d399290c9c1fc6366cdad129ef442f323564 `./trace2line` this is too slow and takes hours. QEMU's processing of 170k events takes 7 seconds. gem5's processing is analogous, but there are 140M events, so it should take 7000 seconds ~ 2 hours which seems consistent with what I observe, so maybe there is no way to speed this up... The workaround is to just use gem5's `ExecSymbol` to get function granularity, and then GDB individually if line detail is needed?
  6950. ===== gem5 trace internals
  6951. gem5 traces are generated from `DPRINTF(<trace-id>` calls scattered throughout the code, except for `ExecAll` instruction traces, which uses `Debug::ExecEnable` directly..
  6952. The trace IDs are themselves encoded in `SConscript` files, e.g.:
  6953. ....
  6954. DebugFlag('Event'
  6955. ....
  6956. in `src/cpu/SConscript`.
  6957. The build system then automatically adds the options to the `--debug-flags`.
  6958. For this entry, the build system then generates a file `build/ARM/debug/ExecEnable.hh`, which contains:
  6959. ....
  6960. namespace Debug {
  6961. class SimpleFlag;
  6962. extern SimpleFlag ExecEnable;
  6963. }
  6964. ....
  6965. and must be included in from callers of `DPRINTF(` as `<debug/ExecEnable.hh>`.
  6966. Tested in b4879ae5b0b6644e6836b0881e4da05c64a6550d.
  6967. ===== gem5 ExecAll trace format
  6968. This debug flag traces all instructions.
  6969. The output format is of type:
  6970. ....
  6971. 25007000: system.cpu T0 : @start_kernel : stp
  6972. 25007000: system.cpu T0 : @start_kernel.0 : addxi_uop ureg0, sp, #-112 : IntAlu : D=0xffffff8008913f90
  6973. 25007500: system.cpu T0 : @start_kernel.1 : strxi_uop x29, [ureg0] : MemWrite : D=0x0000000000000000 A=0xffffff8008913f90
  6974. 25008000: system.cpu T0 : @start_kernel.2 : strxi_uop x30, [ureg0, #8] : MemWrite : D=0x0000000000000000 A=0xffffff8008913f98
  6975. 25008500: system.cpu T0 : @start_kernel.3 : addxi_uop sp, ureg0, #0 : IntAlu : D=0xffffff8008913f90
  6976. ....
  6977. There are two types of lines:
  6978. * full instructions, as the first line. Only shown if the `ExecMacro` flag is given.
  6979. * micro ops that constitute the instruction, the lines that follow. Yes, `aarch64` also has microops: https://superuser.com/questions/934752/do-arm-processors-like-cortex-a9-use-microcode/934755#934755[]. Only shown if the `ExecMicro` flag is given.
  6980. Breakdown:
  6981. * `25007500`: time count in some unit. Note how the microops execute at further timestamps.
  6982. * `system.cpu`: distinguishes between CPUs when there are more than one. For example, running xref:arm-multicore[xrefstyle=full] with two cores produces `system.cpu0` and `system.cpu1`
  6983. * `T0`: thread number. TODO: https://superuser.com/questions/133082/hyper-threading-and-dual-core-whats-the-difference/995858#995858[hyperthread]? How to play with it?
  6984. +
  6985. `config`.ini has `--param 'system.multi_thread = True' --param 'system.cpu[0].numThreads = 2'`, but in <<arm-multicore>> the first one alone does not produce `T1`, and with the second one simulation blows up with:
  6986. +
  6987. ....
  6988. fatal: fatal condition interrupts.size() != numThreads occurred: CPU system.cpu has 1 interrupt controllers, but is expecting one per thread (2)
  6989. ....
  6990. * `@start_kernel`: we are in the `start_kernel` function. Awesome feature! Implemented with libelf https://sourceforge.net/projects/elftoolchain/ copy pasted in-tree `ext/libelf`. To get raw addresses, remove the `ExecSymbol`, which is enabled by `Exec`. This can be done with `Exec,-ExecSymbol`.
  6991. * `.1` as in `@start_kernel.1`: index of the microop
  6992. * `stp`: instruction disassembly. Note however that the disassembly of many instructions are very broken as of 2019q2, and you can't just trust them blindly.
  6993. * `strxi_uop x29, [ureg0]`: microop disassembly.
  6994. * `MemWrite : D=0x0000000000000000 A=0xffffff8008913f90`: a memory write microop:
  6995. ** `D` stands for data, and represents the value that was written to memory or to a register
  6996. ** `A` stands for address, and represents the address to which the value was written. It only shows when data is being written to memory, but not to registers.
  6997. The best way to verify all of this is to write some <<baremetal,baremetal code>>
  6998. ===== gem5 Registers trace format
  6999. This flag shows a more detailed register usage than <<gem5-execall-trace-format>>.
  7000. For example, if we run in LKMC 0323e81bff1d55b978a4b36b9701570b59b981eb:
  7001. ....
  7002. ./run --arch aarch64 --baremetal userland/arch/aarch64/add.S --emulator gem5 --trace ExecAll,Registers --trace-stdout
  7003. ....
  7004. then the stdout contains:
  7005. ....
  7006. 31000: system.cpu A0 T0 : @main_after_prologue : movz x0, #1, #0 : IntAlu : D=0x0000000000000001 flags=(IsInteger)
  7007. 31500: system.cpu.[tid:0]: Setting int reg 34 (34) to 0.
  7008. 31500: system.cpu.[tid:0]: Reading int reg 0 (0) as 0x1.
  7009. 31500: system.cpu.[tid:0]: Setting int reg 1 (1) to 0x3.
  7010. 31500: system.cpu A0 T0 : @main_after_prologue+4 : add x1, x0, #2 : IntAlu : D=0x0000000000000003 flags=(IsInteger)
  7011. 32000: system.cpu.[tid:0]: Setting int reg 34 (34) to 0.
  7012. 32000: system.cpu.[tid:0]: Reading int reg 1 (1) as 0x3.
  7013. 32000: system.cpu.[tid:0]: Reading int reg 31 (34) as 0.
  7014. 32000: system.cpu.[tid:0]: Setting int reg 0 (0) to 0x3.
  7015. ....
  7016. which corresponds to the two following instructions:
  7017. ....
  7018. mov x0, 1
  7019. add x1, x0, 2
  7020. ....
  7021. TODO that format is either buggy or is very difficult to understand:
  7022. * what is `34`? Presumably some flags register?
  7023. * what do the numbers in parenthesis mean at `31 (34)`? Presumably some flags register?
  7024. * why is the first instruction setting `reg 1` and the second one `reg 0`, given that the first sets `x0` and the second `x1`?
  7025. ===== gem5 TARMAC traces
  7026. https://stackoverflow.com/questions/54882466/how-to-use-the-tarmac-tracer-with-gem5
  7027. ===== gem5 tracing internals
  7028. As of gem5 16eeee5356585441a49d05c78abc328ef09f7ace the default tracer is `ExeTracer`. It is set at:
  7029. ....
  7030. src/cpu/BaseCPU.py:63:default_tracer = ExeTracer()
  7031. ....
  7032. which then gets used at:
  7033. ....
  7034. class BaseCPU(ClockedObject):
  7035. [...]
  7036. tracer = Param.InstTracer(default_tracer, "Instruction tracer")
  7037. ....
  7038. All tracers derive from the common `InstTracer` base class:
  7039. ....
  7040. git grep ': InstTracer'
  7041. ....
  7042. gives:
  7043. ....
  7044. src/arch/arm/tracers/tarmac_parser.hh:218: TarmacParser(const Params *p) : InstTracer(p), startPc(p->start_pc),
  7045. src/arch/arm/tracers/tarmac_tracer.cc:57: : InstTracer(p),
  7046. src/cpu/exetrace.hh:67: ExeTracer(const Params *params) : InstTracer(params)
  7047. src/cpu/inst_pb_trace.cc:72: : InstTracer(p), buf(nullptr), bufSize(0), curMsg(nullptr)
  7048. src/cpu/inteltrace.hh:63: IntelTrace(const IntelTraceParams *p) : InstTracer(p)
  7049. ....
  7050. As mentioned at <<gem5-tarmac-traces>>, there appears to be no way to select those currently without hacking the config scripts.
  7051. TARMAC is described at: <<gem5-tarmac-traces>>.
  7052. TODO: are `IntelTrace` and `TarmacParser` useful for anything or just relics?
  7053. Then there is also the `NativeTrace` class:
  7054. ....
  7055. src/cpu/nativetrace.hh:68:class NativeTrace : public ExeTracer
  7056. ....
  7057. which gets implemented in a few different ISAs, but not all:
  7058. ....
  7059. src/arch/arm/nativetrace.hh:40:class ArmNativeTrace : public NativeTrace
  7060. src/arch/sparc/nativetrace.hh:41:class SparcNativeTrace : public NativeTrace
  7061. src/arch/x86/nativetrace.hh:41:class X86NativeTrace : public NativeTrace
  7062. ....
  7063. TODO: I can't find any usages of those classes from in-tree configs.
  7064. === QEMU GUI is unresponsive
  7065. Sometimes in Ubuntu 14.04, after the QEMU SDL GUI starts, it does not get updated after keyboard strokes, and there are artifacts like disappearing text.
  7066. We have not managed to track this problem down yet, but the following workaround always works:
  7067. ....
  7068. Ctrl-Shift-U
  7069. Ctrl-C
  7070. root
  7071. ....
  7072. This started happening when we switched to building QEMU through Buildroot, and has not been observed on later Ubuntu.
  7073. Using text mode is another workaround if you don't need GUI features.
  7074. == gem5
  7075. Getting started at: xref:gem5-buildroot-setup[xrefstyle=full].
  7076. === gem5 vs QEMU
  7077. * advantages of gem5:
  7078. ** simulates a generic more realistic <<gem5-cpu-types,optionally pipelined and out-of-order>> CPU cycle by cycle, including a realistic DRAM memory access model with latencies, caches and page table manipulations. This allows us to:
  7079. +
  7080. --
  7081. *** do much more realistic performance benchmarking with it, which makes absolutely no sense in QEMU, which is purely functional
  7082. *** make certain functional observations that are not possible in QEMU, e.g.:
  7083. **** use Linux kernel APIs that flush cache memory like DMA, which are crucial for driver development. In QEMU, the driver would still work even if we forget to flush caches.
  7084. **** spectre / meltdown:
  7085. ***** https://www.mail-archive.com/gem5-users@gem5.org/msg15319.html
  7086. ***** https://github.com/jlpresearch/gem5/tree/spectre-test
  7087. --
  7088. +
  7089. It is not of course truly cycle accurate, as that:
  7090. +
  7091. --
  7092. ** would require exposing proprietary information of the CPU designs: https://stackoverflow.com/questions/17454955/can-you-check-performance-of-a-program-running-with-qemu-simulator/33580850#33580850[]
  7093. ** would make the simulation even slower TODO confirm, by how much
  7094. --
  7095. +
  7096. but the approximation is reasonable.
  7097. +
  7098. It is used mostly for microarchitecture research purposes: when you are making a new chip technology, you don't really need to specialize enormously to an existing microarchitecture, but rather develop something that will work with a wide range of future architectures.
  7099. ** runs are deterministic by default, unlike QEMU which has a special <<qemu-record-and-replay>> mode, that requires first playing the content once and then replaying
  7100. ** gem5 ARM at least appears to implement more low level CPU functionality than QEMU, e.g. QEMU only added EL2 in 2018: https://stackoverflow.com/questions/42824706/qemu-system-aarch64-entering-el1-when-emulating-a53-power-up See also: xref:arm-exception-levels[xrefstyle=full]
  7101. ** gem5 offers more advanced logging, even for non micro architectural things which QEMU models in some way, e.g. <<qemu-trace-memory-accesses>>, because QEMU's binary translation optimizations reduce visibility
  7102. * disadvantages of gem5:
  7103. ** slower than QEMU, see: xref:benchmark-linux-kernel-boot[xrefstyle=full]
  7104. +
  7105. This implies that the user base is much smaller, since no Android devs.
  7106. +
  7107. Instead, we have only chip makers, who keep everything that really works closed, and researchers, who can't version track or document code properly >:-) And this implies that:
  7108. +
  7109. --
  7110. *** the documentation is more scarce
  7111. *** it takes longer to support new hardware features
  7112. --
  7113. +
  7114. Well, not that AOSP is that much better anyways.
  7115. ** not sure: gem5 has BSD license while QEMU has GPL
  7116. +
  7117. This suits chip makers that want to distribute forks with secret IP to their customers.
  7118. +
  7119. On the other hand, the chip makers tend to upstream less, and the project becomes more crappy in average :-)
  7120. ** gem5 is way more complex and harder to modify and maintain
  7121. +
  7122. The only hairy thing in QEMU is the binary code generation.
  7123. +
  7124. gem5 however has tended towards horrendous intensive <<gem5-code-generation,code generation>> in order to support all its different hardware types
  7125. === gem5 run benchmark
  7126. OK, this is why we used gem5 in the first place, performance measurements!
  7127. Let's see how many cycles <<dhrystone>>, which Buildroot provides, takes for a few different input parameters.
  7128. We will do that for various input parameters on full system by taking a checkpoint after the boot finishes a fast atomic CPU boot, and then we will restore in a more detailed mode and run the benchmark:
  7129. ....
  7130. ./build-buildroot --config 'BR2_PACKAGE_DHRYSTONE=y'
  7131. # Boot fast, take checkpoint, and exit.
  7132. ./run --arch aarch64 --emulator gem5 --eval-after './gem5.sh'
  7133. # Restore the checkpoint after boot, and benchmark with input 1000.
  7134. ./run \
  7135. --arch aarch64 \
  7136. --emulator gem5 \
  7137. --eval-after './gem5.sh' \
  7138. --gem5-readfile 'm5 resetstats;dhrystone 1000;m5 dumpstats' \
  7139. --gem5-restore 1 \
  7140. -- \
  7141. --cpu-type=HPI \
  7142. --restore-with-cpu=HPI \
  7143. --caches \
  7144. --l2cache \
  7145. --l1d_size=64kB \
  7146. --l1i_size=64kB \
  7147. --l2_size=256kB \
  7148. ;
  7149. # Get the value for number of cycles.
  7150. # head because there are two lines: our dumpstats and the
  7151. # automatic dumpstats at the end which we don't care about.
  7152. ./gem5-stat --arch aarch64 | head -n 1
  7153. # Now for input 10000.
  7154. ./run \
  7155. --arch aarch64 \
  7156. --emulator gem5 \
  7157. --eval-after './gem5.sh' \
  7158. --gem5-readfile 'm5 resetstats;dhrystone 10000;m5 dumpstats' \
  7159. --gem5-restore 1 \
  7160. -- \
  7161. --cpu-type=HPI \
  7162. --restore-with-cpu=HPI \
  7163. --caches \
  7164. --l2cache \
  7165. --l1d_size=64kB \
  7166. --l1i_size=64kB \
  7167. --l2_size=256kB \
  7168. ;
  7169. ./gem5-stat --arch aarch64 | head -n 1
  7170. ....
  7171. If you ever need a shell to quickly inspect the system state after boot, you can just use:
  7172. ....
  7173. ./run \
  7174. --arch aarch64 \
  7175. --emulator gem5 \
  7176. --eval-after './gem5.sh' \
  7177. --gem5-readfile 'sh' \
  7178. --gem5-restore 1 \
  7179. ....
  7180. This procedure is further automated and DRYed up at:
  7181. ....
  7182. ./gem5-bench-dhrystone
  7183. cat out/gem5-bench-dhrystone.txt
  7184. ....
  7185. Source: link:gem5-bench-dhrystone[]
  7186. Output at 2438410c25e200d9766c8c65773ee7469b599e4a + 1:
  7187. ....
  7188. n cycles
  7189. 1000 13665219
  7190. 10000 20559002
  7191. 100000 85977065
  7192. ....
  7193. so as expected, the Dhrystone run with a larger input parameter `100000` took more cycles than the ones with smaller input parameters.
  7194. The `gem5-stats` commands output the approximate number of CPU cycles it took Dhrystone to run.
  7195. A more naive and simpler to understand approach would be a direct:
  7196. ....
  7197. ./run --arch aarch64 --emulator gem5 --eval 'm5 checkpoint;m5 resetstats;dhrystone 10000;m5 exit'
  7198. ....
  7199. but the problem is that this method does not allow to easily run a different script without running the boot again. The `./gem5.sh` script works around that by using <<m5-readfile>> as explained further at: xref:gem5-restore-new-script[xrefstyle=full].
  7200. Now you can play a fun little game with your friends:
  7201. * pick a computational problem
  7202. * make a program that solves the computation problem, and outputs output to stdout
  7203. * write the code that runs the correct computation in the smallest number of cycles possible
  7204. To find out why your program is slow, a good first step is to have a look at the <<gem5-m5out-stats-txt-file>>.
  7205. ==== Skip extra benchmark instructions
  7206. A few imperfections of our <<gem5-run-benchmark,benchmarking method>> are:
  7207. * when we do `m5 resetstats` and `m5 exit`, there is some time passed before the `exec` system call returns and the actual benchmark starts and ends
  7208. * the benchmark outputs to stdout, which means so extra cycles in addition to the actual computation. But TODO: how to get the output to check that it is correct without such IO cycles?
  7209. Solutions to these problems include:
  7210. * modify benchmark code with instrumentation directly, see <<m5ops-instructions>> for an example.
  7211. * monitor known addresses TODO possible? Create an example.
  7212. Discussion at: https://stackoverflow.com/questions/48944587/how-to-count-the-number-of-cpu-clock-cycles-between-the-start-and-end-of-a-bench/48944588#48944588
  7213. Those problems should be insignificant if the benchmark runs for long enough however.
  7214. ==== gem5 system parameters
  7215. Besides optimizing a program for a given CPU setup, chip developers can also do the inverse, and optimize the chip for a given benchmark!
  7216. The rabbit hole is likely deep, but let's scratch a bit of the surface.
  7217. ===== Number of cores
  7218. ....
  7219. ./run --arch arm --cpus 2 --emulator gem5
  7220. ....
  7221. Check with:
  7222. ....
  7223. cat /proc/cpuinfo
  7224. getconf _NPROCESSORS_CONF
  7225. ....
  7226. ====== QEMU user mode multithreading
  7227. TODO why in <<user-mode-simulation>> QEMU always shows the number of cores of the host. E.g., both of the following output the same as `nproc` on the host:
  7228. ....
  7229. nproc
  7230. ./run --userland userland/cpp/thread_hardware_concurrency.cpp
  7231. ./run --cpus 2 --userland userland/cpp/thread_hardware_concurrency.cpp
  7232. ....
  7233. This random page suggests that QEMU splits one host thread thread per guest thread, and thus presumably delegates context switching to the host kernel: https://qemu.weilnetz.de/w64/2012/2012-12-04/qemu-tech.html#User-emulation-specific-details
  7234. We can confirm that with:
  7235. ....
  7236. ./run --userland userland/posix/pthread_count.c --userland-args 4
  7237. ps Haux | grep qemu | wc
  7238. ....
  7239. Remember <<qemu-user-mode-does-not-show-stdout-immediately>> though.
  7240. At 369a47fc6e5c2f4a7f911c1c058b6088f8824463 + 1 QEMU appears to spawn 3 host threads plus one for every new guest thread created. Remember that link:userland/posix/pthread_count.c[] spawns N + 1 total threads if you count the `main` thread.
  7241. ====== gem5 syscall emulation multithreading
  7242. gem5 user mode multithreading has been particularly flaky compared <<qemu-user-mode-multithreading,to QEMU's>>.
  7243. You have the limitation that you must have at least one core per guest thread, otherwise `pthread_create` fails. For example:
  7244. ....
  7245. ./run --cpus 1 --emulator gem5 --static --userland userland/posix/pthread_self.c --userland-args 1
  7246. ....
  7247. fails because that process has a total of 2 threads: one for `main` and one extra thread spawned: link:userland/posix/pthread_self.c[] The error message is:
  7248. ....
  7249. pthread_create: Resource temporarily unavailable
  7250. ....
  7251. It works however if we add on extra CPU:
  7252. ....
  7253. ./run --cpus 2 --emulator gem5 --static --userland userland/posix/pthread_self.c --userland-args 1
  7254. ....
  7255. This has to do with the fact that gem5 has a more simplistic thread implementation that does not spawn one host thread per guest thread CPU. Maybe this is required to achieve reproducible runs? What is the task switch algorithm then?
  7256. gem5 threading does however show the expected number of cores, e.g.:
  7257. ....
  7258. ./run --cpus 1 --userland userland/cpp/thread_hardware_concurrency.cpp --emulator gem5 --static
  7259. ./run --cpus 2 --userland userland/cpp/thread_hardware_concurrency.cpp --emulator gem5 --static
  7260. ....
  7261. outputs `1` and `2` respectively.
  7262. TODO: aarch64 seems to failing to spawn more than 2 threads at 369a47fc6e5c2f4a7f911c1c058b6088f8824463 + 1:
  7263. ....
  7264. ./run --arch aarch64 --cpus 3 --emulator gem5 --static --userland userland/posix/pthread_self.c --userland-args 2
  7265. ....
  7266. fails with:
  7267. ....
  7268. Exiting @ tick 18446744073709551615 because simulate() limit reached
  7269. ....
  7270. ====== gem5 se.py user mode with 2 or more pthreads fails with because simulate() limit reached
  7271. See bug report at: https://github.com/cirosantilli/linux-kernel-module-cheat/issues/81
  7272. Related: <<gem5-simulate-limit-reached>>.
  7273. ====== gem5 ARM full system with more than 8 cores
  7274. https://stackoverflow.com/questions/50248067/how-to-run-a-gem5-arm-aarch64-full-system-simulation-with-fs-py-with-more-than-8
  7275. Build the kernel with the <<gem5-arm-linux-kernel-patches>>, and then run:
  7276. ....
  7277. ./run \
  7278. --arch aarch64 \
  7279. --linux-build-id gem5-v4.15 \
  7280. --emulator gem5 \
  7281. --cpus 16 \
  7282. -- \
  7283. --param 'system.realview.gic.gem5_extensions = True' \
  7284. ;
  7285. ....
  7286. ===== gem5 cache size
  7287. https://stackoverflow.com/questions/49624061/how-to-run-gem5-simulator-in-fs-mode-without-cache/49634544#49634544
  7288. A quick `+./run --emulator gem5 -- -h+` leads us to the options:
  7289. ....
  7290. --caches
  7291. --l1d_size=1024
  7292. --l1i_size=1024
  7293. --l2cache
  7294. --l2_size=1024
  7295. --l3_size=1024
  7296. ....
  7297. But keep in mind that it only affects benchmark performance of the most detailed CPU types as shown at: xref:table-gem5-cache-cpu-type[xrefstyle=full].
  7298. [[table-gem5-cache-cpu-type]]
  7299. .gem5 cache support in function of CPU type
  7300. [options="header"]
  7301. |===
  7302. |arch |CPU type |caches used
  7303. |X86
  7304. |`AtomicSimpleCPU`
  7305. |no
  7306. |X86
  7307. |`DerivO3CPU`
  7308. |?*
  7309. |ARM
  7310. |`AtomicSimpleCPU`
  7311. |no
  7312. |ARM
  7313. |`HPI`
  7314. |yes
  7315. |===
  7316. {empty}*: couldn't test because of:
  7317. * https://stackoverflow.com/questions/49011096/how-to-switch-cpu-models-in-gem5-after-restoring-a-checkpoint-and-then-observe-t
  7318. Cache sizes can in theory be checked with the methods described at: https://superuser.com/questions/55776/finding-l2-cache-size-in-linux[]:
  7319. ....
  7320. getconf -a | grep CACHE
  7321. lscpu
  7322. cat /sys/devices/system/cpu/cpu0/cache/index2/size
  7323. ....
  7324. but for some reason the Linux kernel is not seeing the cache sizes:
  7325. * https://stackoverflow.com/questions/49008792/why-doesnt-the-linux-kernel-see-the-cache-sizes-in-the-gem5-emulator-in-full-sy
  7326. * http://gem5-users.gem5.narkive.com/4xVBlf3c/verify-cache-configuration
  7327. Behaviour breakdown:
  7328. * arm QEMU and gem5 (both `AtomicSimpleCPU` or `HPI`), x86 gem5: `/sys` files don't exist, and `getconf` and `lscpu` value empty
  7329. * x86 QEMU: `/sys` files exist, but `getconf` and `lscpu` values still empty
  7330. So we take a performance measurement approach instead:
  7331. ....
  7332. ./gem5-bench-cache -- --arch aarch64
  7333. cat "$(./getvar --arch aarch64 run_dir)/bench-cache.txt"
  7334. ....
  7335. which gives:
  7336. ....
  7337. cmd ./run --emulator gem5 --arch aarch64 --gem5-readfile "dhrystone 1000" --gem5-restore 1 -- --caches --l2cache --l1d_size=1024 --l1i_size=1024 --l2_size=1024 --l3_size=1024 --cpu-type=HPI --restore-with-cpu=HPI
  7338. time 23.82
  7339. exit_status 0
  7340. cycles 93284622
  7341. instructions 4393457
  7342. cmd ./run --emulator gem5 --arch aarch64 --gem5-readfile "dhrystone 1000" --gem5-restore 1 -- --caches --l2cache --l1d_size=1024kB --l1i_size=1024kB --l2_size=1024kB --l3_size=1024kB --cpu-type=HPI --restore-with-cpu=HPI
  7343. time 14.91
  7344. exit_status 0
  7345. cycles 10128985
  7346. instructions 4211458
  7347. cmd ./run --emulator gem5 --arch aarch64 --gem5-readfile "dhrystone 10000" --gem5-restore 1 -- --caches --l2cache --l1d_size=1024 --l1i_size=1024 --l2_size=1024 --l3_size=1024 --cpu-type=HPI --restore-with-cpu=HPI
  7348. time 51.87
  7349. exit_status 0
  7350. cycles 188803630
  7351. instructions 12401336
  7352. cmd ./run --emulator gem5 --arch aarch64 --gem5-readfile "dhrystone 10000" --gem5-restore 1 -- --caches --l2cache --l1d_size=1024kB --l1i_size=1024kB --l2_size=1024kB --l3_size=1024kB --cpu-type=HPI --restore-with-cpu=HPI
  7353. time 35.35
  7354. exit_status 0
  7355. cycles 20715757
  7356. instructions 12192527
  7357. cmd ./run --emulator gem5 --arch aarch64 --gem5-readfile "dhrystone 100000" --gem5-restore 1 -- --caches --l2cache --l1d_size=1024 --l1i_size=1024 --l2_size=1024 --l3_size=1024 --cpu-type=HPI --restore-with-cpu=HPI
  7358. time 339.07
  7359. exit_status 0
  7360. cycles 1176559936
  7361. instructions 94222791
  7362. cmd ./run --emulator gem5 --arch aarch64 --gem5-readfile "dhrystone 100000" --gem5-restore 1 -- --caches --l2cache --l1d_size=1024kB --l1i_size=1024kB --l2_size=1024kB --l3_size=1024kB --cpu-type=HPI --restore-with-cpu=HPI
  7363. time 240.37
  7364. exit_status 0
  7365. cycles 125666679
  7366. instructions 91738770
  7367. ....
  7368. We make the following conclusions:
  7369. * the number of instructions almost does not change: the CPU is waiting for memory all the extra time. TODO: why does it change at all?
  7370. * the wall clock execution time is not directionally proportional to the number of cycles: here we had a 10x cycle increase, but only 2x time increase. This suggests that the simulation of cycles in which the CPU is waiting for memory to come back is faster.
  7371. ===== gem5 memory latency
  7372. TODO These look promising:
  7373. ....
  7374. --list-mem-types
  7375. --mem-type=MEM_TYPE
  7376. --mem-channels=MEM_CHANNELS
  7377. --mem-ranks=MEM_RANKS
  7378. --mem-size=MEM_SIZE
  7379. ....
  7380. TODO: now to verify this with the Linux kernel? Besides raw performance benchmarks.
  7381. ===== Memory size
  7382. ....
  7383. ./run --memory 512M
  7384. ....
  7385. We can verify this on the guest directly from the kernel with:
  7386. ....
  7387. cat /proc/meminfo
  7388. ....
  7389. as of LKMC 1e969e832f66cb5a72d12d57c53fb09e9721d589 this output contains:
  7390. ....
  7391. MemTotal: 498472 kB
  7392. ....
  7393. which we expand with:
  7394. ....
  7395. printf '0x%X\n' $((498472 * 1024))
  7396. ....
  7397. to:
  7398. ....
  7399. 0x1E6CA000
  7400. ....
  7401. TODO: why is this value a bit smaller than 512M?
  7402. `free` also gives the same result:
  7403. ....
  7404. free -b
  7405. ....
  7406. contains:
  7407. ....
  7408. total used free shared buffers cached
  7409. Mem: 510435328 20385792 490049536 0 503808 2760704
  7410. -/+ buffers/cache: 17121280 493314048
  7411. Swap: 0 0 0
  7412. ....
  7413. which we expand with:
  7414. ....
  7415. printf '0x%X\n' 510435328$((498472 * 1024)
  7416. ....
  7417. `man free` from Ubuntu's procps 3.3.15 tells us that `free` obtains this information from `/proc/meminfo` as well.
  7418. From C, we can get this information with `sysconf(_SC_PHYS_PAGES)` or `get_phys_pages()`:
  7419. ....
  7420. ./linux/total_memory.out
  7421. ....
  7422. Source: link:userland/linux/total_memory.c[]
  7423. Output:
  7424. ....
  7425. sysconf(_SC_PHYS_PAGES) * sysconf(_SC_PAGESIZE) = 0x1E6CA000
  7426. sysconf(_SC_AVPHYS_PAGES) * sysconf(_SC_PAGESIZE) = 0x1D178000
  7427. get_phys_pages() * sysconf(_SC_PAGESIZE) = 0x1E6CA000
  7428. get_avphys_pages() * sysconf(_SC_PAGESIZE) = 0x1D178000
  7429. ....
  7430. This is mentioned at: https://stackoverflow.com/questions/22670257/getting-ram-size-in-c-linux-non-precise-result/22670407#22670407
  7431. AV means available and gives the free memory: https://stackoverflow.com/questions/14386856/c-check-available-ram/57659190#57659190
  7432. ===== gem5 disk and network latency
  7433. TODO These look promising:
  7434. ....
  7435. --ethernet-linkspeed
  7436. --ethernet-linkdelay
  7437. ....
  7438. and also: `gem5-dist`: https://publish.illinois.edu/icsl-pdgem5/
  7439. ===== gem5 clock frequency
  7440. Clock frequency: TODO how does it affect performance in benchmarks?
  7441. ....
  7442. ./run --arch aarch64 --emulator gem5 -- --cpu-clock 10000000
  7443. ....
  7444. Check with:
  7445. ....
  7446. m5 resetstats
  7447. sleep 10
  7448. m5 dumpstats
  7449. ....
  7450. and then:
  7451. ....
  7452. ./gem5-stat --arch aarch64
  7453. ....
  7454. TODO: why doesn't this exist:
  7455. ....
  7456. ls /sys/devices/system/cpu/cpu0/cpufreq
  7457. ....
  7458. ==== Interesting benchmarks
  7459. Buildroot built-in libraries, mostly under Libraries > Other:
  7460. * Armadillo `C++`: linear algebra
  7461. * fftw: Fourier transform
  7462. * Flann
  7463. * GSL: various
  7464. * liblinear
  7465. * libspacialindex
  7466. * libtommath
  7467. * qhull
  7468. Open source but not in Buildroot:
  7469. * https://github.com/kozyraki/stamp transactional memory benchmarks
  7470. There are not yet enabled, but it should be easy to so, see: xref:add-new-buildroot-packages[xrefstyle=full]
  7471. ===== Dhrystone
  7472. https://en.wikipedia.org/wiki/Dhrystone
  7473. Created in the 80's, it is not a representative measure of performance in modern computers anymore. It has mostly been replaced by https://en.wikipedia.org/wiki/SPECint[SPEC], which is... closed source! Unbelievable.
  7474. <<buildroot>> has a `dhrystone` package, but because it is so interesting to us, we decided to also build it ourselves, which allows things like static and baremetal compilation more easily.
  7475. Build and run on QEMU <<user-mode-simulation>>:
  7476. ....
  7477. git submodule update --init submodules/dhrystone
  7478. ./build-dhrystone --mode userland
  7479. ./run --userland "$(./getvar userland_build_dir)/submodules/dhrystone/dhrystone"
  7480. ....
  7481. Build and run on gem5 user mode:
  7482. ....
  7483. ./build-dhrystone --mode userland --static --force-rebuild
  7484. ./run --emulator gem5 --userland "$(./getvar userland_build_dir)/submodules/dhrystone/dhrystone"
  7485. ....
  7486. TODO automate run more nicely.
  7487. Build for <<baremetal>> execution and run it in baremetal QEMU:
  7488. ....
  7489. # Build our Newlib stubs.
  7490. ./build-baremetal --arch aarch64
  7491. ./build-dhrystone --arch aarch64 --mode baremetal
  7492. ./run --arch aarch64 --baremetal "$(./getvar baremetal_build_dir)/submodules/dhrystone/dhrystone"
  7493. ....
  7494. TODO: fix the build, just need to factor out all run arguments from link:build-baremetal[] into link:common.py[] and it should just work, no missing syscalls.
  7495. If you really want the Buildroot package for some reason, build it with:
  7496. ....
  7497. ./build-buildroot --config 'BR2_PACKAGE_DHRYSTONE=y'
  7498. ....
  7499. and run inside the guest from `PATH` with:
  7500. ....
  7501. dhrystone
  7502. ....
  7503. ===== BST vs heap vs hashmap
  7504. The following benchmark setup works both:
  7505. * on host through timers + https://stackoverflow.com/questions/51952471/why-do-i-get-a-constant-instead-of-logarithmic-curve-for-an-insert-time-benchmar/51953081#51953081[granule]
  7506. * gem5 with <<m5ops-instructions,dumpstats>>, which can get more precise results with `granule == 1`
  7507. It has been used to answer:
  7508. * BST vs heap: https://stackoverflow.com/questions/6147243/heap-vs-binary-search-tree-bst/29548834#29548834
  7509. * `std::set`: https://stackoverflow.com/questions/2558153/what-is-the-underlying-data-structure-of-a-stl-set-in-c/51944661#51944661
  7510. * `std::map`: https://stackoverflow.com/questions/18414579/what-data-structure-is-inside-stdmap-in-c/51945119#51945119
  7511. To benchmark on the host, we do:
  7512. ....
  7513. ./build-userland-in-tree --force-rebuild --optimization-level 3 ./userland/cpp/bst_vs_heap_vs_hashmap.cpp
  7514. ./userland/cpp/bst_vs_heap_vs_hashmap.out 10000000 10000 | tee bst_vs_heap_vs_hashmap.dat
  7515. gnuplot \
  7516. -e 'input_noext="bst_vs_heap_vs_hashmap"' \
  7517. -e 'heap_zoom_max=50' \
  7518. -e 'hashmap_zoom_max=400' \
  7519. ./bst-vs-heap-vs-hashmap.gnuplot \
  7520. ;
  7521. xdg-open bst_vs_heap_vs_hashmap.tmp.png
  7522. ....
  7523. The parameters `heap_zoom_max` and `hashmap_zoom_max` are chosen manually interactively to best showcase the regions of interest in those plots.
  7524. First we build the benchmark with <<m5ops-instructions>> enabled, and then we run it and extract the stats:
  7525. ....
  7526. ./build-userland \
  7527. --arch x86_64 \
  7528. --ccflags='-DLKMC_M5OPS_ENABLE=1' \
  7529. --force-rebuild userland/cpp/bst_vs_heap_vs_hashmap.cpp \
  7530. --static \
  7531. --optimization-level 3 \
  7532. ;
  7533. ./run \
  7534. --arch x86_64 \
  7535. --emulator gem5 \
  7536. --static \
  7537. --userland userland/cpp/bst_vs_heap_vs_hashmap.cpp \
  7538. --userland-args='100000' \
  7539. -- \
  7540. --cpu-type=DerivO3CPU \
  7541. --caches \
  7542. --l2cache \
  7543. --l1d_size=32kB \
  7544. --l1i_size=32kB \
  7545. --l2_size=256kB \
  7546. --l3_size=20MB \
  7547. ;
  7548. ./bst-vs-heap-vs-hashmap-gem5-stats --arch x86_64 | tee bst_vs_heap_vs_hashmap_gem5.dat
  7549. gnuplot \
  7550. -e 'input_noext="bst_vs_heap_vs_hashmap_gem5"' \
  7551. -e 'heap_zoom_max=500' \
  7552. -e 'hashmap_zoom_max=400' \
  7553. ./bst-vs-heap-vs-hashmap.gnuplot \
  7554. ;
  7555. xdg-open bst_vs_heap_vs_hashmap_gem5.tmp.png
  7556. ....
  7557. TODO: the gem5 simulation blows up on a tcmalloc allocation somewhere near 25k elements as of 3fdd83c2c58327d9714fa2347c724b78d7c05e2b + 1, likely linked to the extreme inefficiency of the stats collection?
  7558. The cache sizes were chosen to match the host <<p51>> to improve the comparison. Ideally we should also use the same standard library.
  7559. Note that this will take a long time, and will produce a humongous ~40Gb stats file as explained at: xref:gem5-only-dump-selected-stats[xrefstyle=full]
  7560. Sources:
  7561. * link:userland/cpp/bst_vs_heap_vs_hashmap.cpp[]
  7562. * link:bst-vs-heap-vs-hashmap-gem5-stats[]
  7563. * link:bst-vs-heap-vs-hashmap.gnuplot[]
  7564. ===== BLAS
  7565. Buildroot supports it, which makes everything just trivial:
  7566. ....
  7567. ./build-buildroot --config 'BR2_PACKAGE_OPENBLAS=y'
  7568. ./build-userland --package openblas -- userland/libs/openblas/hello.c
  7569. ./run --eval-after './libs/openblas/hello.out; echo $?'
  7570. ....
  7571. Outcome: the test passes:
  7572. ....
  7573. 0
  7574. ....
  7575. Source: link:userland/libs/openblas/hello.c[]
  7576. The test performs a general matrix multiplication:
  7577. ....
  7578. | 1.0 -3.0 | | 1.0 2.0 1.0 | | 0.5 0.5 0.5 | | 11.0 - 9.0 5.0 |
  7579. 1 * | 2.0 4.0 | * | -3.0 4.0 -1.0 | + 2 * | 0.5 0.5 0.5 | = | - 9.0 21.0 -1.0 |
  7580. | 1.0 -1.0 | | 0.5 0.5 0.5 | | 5.0 - 1.0 3.0 |
  7581. ....
  7582. This can be deduced from the Fortran interfaces at
  7583. ....
  7584. less "$(./getvar buildroot_build_build_dir)"/openblas-*/reference/dgemmf.f
  7585. ....
  7586. which we can map to our call as:
  7587. ....
  7588. C := alpha*op( A )*op( B ) + beta*C,
  7589. SUBROUTINE DGEMMF( TRANA, TRANB, M,N,K, ALPHA,A,LDA,B,LDB,BETA,C,LDC)
  7590. cblas_dgemm( CblasColMajor, CblasNoTrans, CblasTrans,3,3,2 ,1, A,3, B,3, 2 ,C,3 );
  7591. ....
  7592. ===== Eigen
  7593. Header only linear algebra library with a mainline Buildroot package:
  7594. ....
  7595. ./build-buildroot --config 'BR2_PACKAGE_EIGEN=y'
  7596. ./build-userland --package eigen -- userland/libs/eigen/hello.cpp
  7597. ....
  7598. Just create an array and print it:
  7599. ....
  7600. ./run --eval-after './libs/eigen/hello.out'
  7601. ....
  7602. Output:
  7603. ....
  7604. 3 -1
  7605. 2.5 1.5
  7606. ....
  7607. Source: link:userland/libs/eigen/hello.cpp[]
  7608. This example just creates a matrix and prints it out.
  7609. Tested on: https://github.com/cirosantilli/linux-kernel-module-cheat/commit/a4bdcf102c068762bb1ef26c591fcf71e5907525[a4bdcf102c068762bb1ef26c591fcf71e5907525]
  7610. ===== PARSEC benchmark
  7611. We have ported parts of the http://parsec.cs.princeton.edu[PARSEC benchmark] for cross compilation at: https://github.com/cirosantilli/parsec-benchmark See the documentation on that repo to find out which benchmarks have been ported. Some of the benchmarks were are segfaulting, they are documented in that repo.
  7612. There are two ways to run PARSEC with this repo:
  7613. * <<parsec-benchmark-without-parsecmgmt,without `pasecmgmt`>>, most likely what you want
  7614. * <<parsec-benchmark-with-parsecmgmt,with `pasecmgmt`>>
  7615. ====== PARSEC benchmark without parsecmgmt
  7616. ....
  7617. ./build --arch arm --download-dependencies gem5-buildroot parsec-benchmark
  7618. ./build-buildroot --arch arm --config 'BR2_PACKAGE_PARSEC_BENCHMARK=y'
  7619. ./run --arch arm --emulator gem5
  7620. ....
  7621. Once inside the guest, launch one of the `test` input sized benchmarks manually as in:
  7622. ....
  7623. cd /parsec/ext/splash2x/apps/fmm/run
  7624. ../inst/arm-linux.gcc/bin/fmm 1 < input_1
  7625. ....
  7626. To find run out how to run many of the benchmarks, have a look at the `test.sh` script of the `parse-benchmark` repo.
  7627. From the guest, you can also run it as:
  7628. ....
  7629. cd /parsec
  7630. ./test.sh
  7631. ....
  7632. but this might be a bit time consuming in gem5.
  7633. ====== PARSEC change the input size
  7634. Running a benchmark of a size different than `test`, e.g. `simsmall`, requires a rebuild with:
  7635. ....
  7636. ./build-buildroot \
  7637. --arch arm \
  7638. --config 'BR2_PACKAGE_PARSEC_BENCHMARK=y' \
  7639. --config 'BR2_PACKAGE_PARSEC_BENCHMARK_INPUT_SIZE="simsmall"' \
  7640. -- parsec_benchmark-reconfigure \
  7641. ;
  7642. ....
  7643. Large input may also require tweaking:
  7644. * <<br2_target_rootfs_ext2_size>> if the unpacked inputs are large
  7645. * <<memory-size>>, unless you want to meet the OOM killer, which is admittedly kind of fun
  7646. `test.sh` only contains the run commands for the `test` size, and cannot be used for `simsmall`.
  7647. The easiest thing to do, is to https://superuser.com/questions/231002/how-can-i-search-within-the-output-buffer-of-a-tmux-shell/1253137#1253137[scroll up on the host shell] after the build, and look for a line of type:
  7648. ....
  7649. Running /root/linux-kernel-module-cheat/out/aarch64/buildroot/build/parsec-benchmark-custom/ext/splash2x/apps/ocean_ncp/inst/aarch64-linux.gcc/bin/ocean_ncp -n2050 -p1 -e1e-07 -r20000 -t28800
  7650. ....
  7651. and then tweak the command found in `test.sh` accordingly.
  7652. Yes, we do run the benchmarks on host just to unpack / generate inputs. They are expected fail to run since they were build for the guest instead of host, including for x86_64 guest which has a different interpreter than the host's (see `file myexecutable`).
  7653. The rebuild is required because we unpack input files on the host.
  7654. Separating input sizes also allows to create smaller images when only running the smaller benchmarks.
  7655. This limitation exists because `parsecmgmt` generates the input files just before running via the Bash scripts, but we can't run `parsecmgmt` on gem5 as it is too slow!
  7656. One option would be to do that inside the guest with QEMU.
  7657. Also, we can't generate all input sizes at once, because many of them have the same name and would overwrite one another...
  7658. PARSEC simply wasn't designed with non native machines in mind...
  7659. ====== PARSEC benchmark with parsecmgmt
  7660. Most users won't want to use this method because:
  7661. * running the `parsecmgmt` Bash scripts takes forever before it ever starts running the actual benchmarks on gem5
  7662. +
  7663. Running on QEMU is feasible, but not the main use case, since QEMU cannot be used for performance measurements
  7664. * it requires putting the full `.tar` inputs on the guest, which makes the image twice as large (1x for the `.tar`, 1x for the unpacked input files)
  7665. It would be awesome if it were possible to use this method, since this is what Parsec supports officially, and so:
  7666. * you don't have to dig into what raw command to run
  7667. * there is an easy way to run all the benchmarks in one go to test them out
  7668. * you can just run any of the benchmarks that you want
  7669. but it simply is not feasible in gem5 because it takes too long.
  7670. If you still want to run this, try it out with:
  7671. ....
  7672. ./build-buildroot \
  7673. --arch aarch64 \
  7674. --config 'BR2_PACKAGE_PARSEC_BENCHMARK=y' \
  7675. --config 'BR2_PACKAGE_PARSEC_BENCHMARK_PARSECMGMT=y' \
  7676. --config 'BR2_TARGET_ROOTFS_EXT2_SIZE="3G"' \
  7677. -- parsec_benchmark-reconfigure \
  7678. ;
  7679. ....
  7680. And then you can run it just as you would on the host:
  7681. ....
  7682. cd /parsec/
  7683. bash
  7684. . env.sh
  7685. parsecmgmt -a run -p splash2x.fmm -i test
  7686. ....
  7687. ====== PARSEC uninstall
  7688. If you want to remove PARSEC later, Buildroot doesn't provide an automated package removal mechanism as mentioned at: xref:remove-buildroot-packages[xrefstyle=full], but the following procedure should be satisfactory:
  7689. ....
  7690. rm -rf \
  7691. "$(./getvar buildroot_download_dir)"/parsec-* \
  7692. "$(./getvar buildroot_build_dir)"/build/parsec-* \
  7693. "$(./getvar buildroot_build_dir)"/build/packages-file-list.txt \
  7694. "$(./getvar buildroot_build_dir)"/images/rootfs.* \
  7695. "$(./getvar buildroot_build_dir)"/target/parsec-* \
  7696. ;
  7697. ./build-buildroot --arch arm
  7698. ....
  7699. ====== PARSEC benchmark hacking
  7700. If you end up going inside link:submodules/parsec-benchmark[] to hack up the benchmark (you will!), these tips will be helpful.
  7701. Buildroot was not designed to deal with large images, and currently cross rebuilds are a bit slow, due to some image generation and validation steps.
  7702. A few workarounds are:
  7703. * develop in host first as much as you can. Our PARSEC fork supports it.
  7704. +
  7705. If you do this, don't forget to do a:
  7706. +
  7707. ....
  7708. cd "$(./getvar parsec_source_dir)"
  7709. git clean -xdf .
  7710. ....
  7711. before going for the cross compile build.
  7712. +
  7713. * patch Buildroot to work well, and keep cross compiling all the way. This should be totally viable, and we should do it.
  7714. +
  7715. Don't forget to explicitly rebuild PARSEC with:
  7716. +
  7717. ....
  7718. ./build-buildroot \
  7719. --arch arm \
  7720. --config 'BR2_PACKAGE_PARSEC_BENCHMARK=y' \
  7721. -- parsec_benchmark-reconfigure \
  7722. ;
  7723. ....
  7724. +
  7725. You may also want to test if your patches are still functionally correct inside of QEMU first, which is a faster emulator.
  7726. * sell your soul, and compile natively inside the guest. We won't do this, not only because it is evil, but also because Buildroot explicitly does not support it: https://buildroot.org/downloads/manual/manual.html#faq-no-compiler-on-target ARM employees have been known to do this: https://github.com/arm-university/arm-gem5-rsk/blob/aa3b51b175a0f3b6e75c9c856092ae0c8f2a7cdc/parsec_patches/qemu-patch.diff
  7727. === gem5 kernel command line parameters
  7728. Analogous <<kernel-command-line-parameters,to QEMU>>:
  7729. ....
  7730. ./run --arch arm --kernel-cli 'init=/lkmc/linux/poweroff.out' --emulator gem5
  7731. ....
  7732. Internals: when we give `--command-line=` to gem5, it overrides default command lines, including some mandatory ones which are required to boot properly.
  7733. Our run script hardcodes the require options in the default `--command-line` and appends extra options given by `-e`.
  7734. To find the default options in the first place, we removed `--command-line` and ran:
  7735. ....
  7736. ./run --arch arm --emulator gem5
  7737. ....
  7738. and then looked at the line of the Linux kernel that starts with:
  7739. ....
  7740. Kernel command line:
  7741. ....
  7742. [[gem5-gdb]]
  7743. === gem5 GDB step debug
  7744. ==== gem5 GDB step debug kernel
  7745. Analogous <<gdb,to QEMU>>, on the first shell:
  7746. ....
  7747. ./run --arch arm --emulator gem5 --gdb-wait
  7748. ....
  7749. On the second shell:
  7750. ....
  7751. ./run-gdb --arch arm --emulator gem5
  7752. ....
  7753. On a third shell:
  7754. ....
  7755. ./gem5-shell
  7756. ....
  7757. When you want to break, just do a `Ctrl-C` on GDB shell, and then `continue`.
  7758. And we now see the boot messages, and then get a shell. Now try the `./count.sh` procedure described for QEMU at: xref:gdb-step-debug-kernel-post-boot[xrefstyle=full].
  7759. ==== gem5 GDB step debug userland process
  7760. We are unable to use `gdbserver` because of networking as mentioned at: xref:gem5-host-to-guest-networking[xrefstyle=full]
  7761. The alternative is to do as in <<gdb-step-debug-userland-processes>>.
  7762. Next, follow the exact same steps explained at <<gdb-step-debug-userland-non-init-without-gdb-wait>>, but passing `--emulator gem5` to every command as usual.
  7763. But then TODO (I'll still go crazy one of those days): for `arm`, while debugging `./linux/myinsmod.out hello.ko`, after then line:
  7764. ....
  7765. 23 if (argc < 3) {
  7766. 24 params = "";
  7767. ....
  7768. I press `n`, it just runs the program until the end, instead of stopping on the next line of execution. The module does get inserted normally.
  7769. TODO:
  7770. ....
  7771. ./run-gdb --arch arm --emulator gem5 --userland gem5-1.0/gem5/util/m5/m5 main
  7772. ....
  7773. breaks when `m5` is run on guest, but does not show the source code.
  7774. === gem5 checkpoint
  7775. Analogous to QEMU's <<snapshot>>, but better since it can be started from inside the guest, so we can easily checkpoint after a specific guest event, e.g. just before `init` is done.
  7776. Documentation: http://gem5.org/Checkpoints
  7777. ....
  7778. ./run --arch arm --emulator gem5
  7779. ....
  7780. In the guest, wait for the boot to end and run:
  7781. ....
  7782. m5 checkpoint
  7783. ....
  7784. where <<m5>> is a guest utility present inside the gem5 tree which we cross-compiled and installed into the guest.
  7785. To restore the checkpoint, kill the VM and run:
  7786. ....
  7787. ./run --arch arm --emulator gem5 --gem5-restore 1
  7788. ....
  7789. The `--gem5-restore` option restores the checkpoint that was created most recently.
  7790. Let's create a second checkpoint to see how it works, in guest:
  7791. ....
  7792. date >f
  7793. m5 checkpoint
  7794. ....
  7795. Kill the VM, and try it out:
  7796. ....
  7797. ./run --arch arm --emulator gem5 --gem5-restore 1
  7798. ....
  7799. Here we use `--gem5-restore 1` again, since the second snapshot we took is now the most recent one
  7800. Now in the guest:
  7801. ....
  7802. cat f
  7803. ....
  7804. contains the `date`. The file `f` wouldn't exist had we used the first checkpoint with `--gem5-restore 2`, which is the second most recent snapshot taken.
  7805. If you automate things with <<kernel-command-line-parameters>> as in:
  7806. ....
  7807. ./run --arch arm --eval 'm5 checkpoint;m5 resetstats;dhrystone 1000;m5 exit' --emulator gem5
  7808. ....
  7809. Then there is no need to pass the kernel command line again to gem5 for replay:
  7810. ....
  7811. ./run --arch arm --emulator gem5 --gem5-restore 1
  7812. ....
  7813. since boot has already happened, and the parameters are already in the RAM of the snapshot.
  7814. ==== gem5 checkpoint internals
  7815. Checkpoints are stored inside the <<m5out-directory>> at:
  7816. ....
  7817. "$(./getvar --emulator gem5 m5out_dir)/cpt.<checkpoint-time>"
  7818. ....
  7819. where `<checkpoint-time>` is the cycle number at which the checkpoint was taken.
  7820. `fs.py` exposes the `-r N` flag to restore checkpoints, which N-th checkpoint with the largest `<checkpoint-time>`: https://github.com/gem5/gem5/blob/e02ec0c24d56bce4a0d8636a340e15cd223d1930/configs/common/Simulation.py#L118
  7821. However, that interface is bad because if you had taken previous checkpoints, you have no idea what `N` to use, unless you memorize which checkpoint was taken at which cycle.
  7822. Therefore, just use our superior `--gem5-restore` flag, which uses directory timestamps to determine which checkpoint you created most recently.
  7823. The `-r N` integer value is just pure `fs.py` sugar, the backend at `m5.instantiate` just takes the actual tracepoint directory path as input.
  7824. [[gem5-restore-new-script]]
  7825. ==== gem5 checkpoint restore and run a different script
  7826. You want to automate running several tests from a single pristine post-boot state.
  7827. The problem is that boot takes forever, and after the checkpoint, the memory and disk states are fixed, so you can't for example:
  7828. * hack up an existing rc script, since the disk is fixed
  7829. * inject new kernel boot command line options, since those have already been put into memory by the bootloader
  7830. There is however a few loopholes, <<m5-readfile>> being the simplest, as it reads whatever is present on the host.
  7831. So we can do it like:
  7832. ....
  7833. # Boot, checkpoint and exit.
  7834. printf 'echo "setup run";m5 exit' > "$(./getvar gem5_readfile_file)"
  7835. ./run --emulator gem5 --eval 'm5 checkpoint;m5 readfile > /tmp/gem5.sh && sh /tmp/gem5.sh'
  7836. # Restore and run the first benchmark.
  7837. printf 'echo "first benchmark";m5 exit' > "$(./getvar gem5_readfile_file)"
  7838. ./run --emulator gem5 --gem5-restore 1
  7839. # Restore and run the second benchmark.
  7840. printf 'echo "second benchmark";m5 exit' > "$(./getvar gem5_readfile_file)"
  7841. ./run --emulator gem5 --gem5-restore 1
  7842. # If something weird happened, create an interactive shell to examine the system.
  7843. printf 'sh' > "$(./getvar gem5_readfile_file)"
  7844. ./run --emulator gem5 --gem5-restore 1
  7845. ....
  7846. Since this is such a common setup, we provide the following helpers for this operation:
  7847. * `./run --gem5-readfile` is a convenient way to set the `m5 readfile` file contents from a string in the command line, e.g.:
  7848. +
  7849. ....
  7850. # Boot, checkpoint and exit.
  7851. ./run --emulator gem5 --eval './gem5.sh' --gem5-readfile 'echo "setup run"'
  7852. # Restore and run the first benchmark.
  7853. ./run --emulator gem5 --gem5-restore 1 --gem5-readfile 'echo "first benchmark"'
  7854. # Restore and run the second benchmark.
  7855. ./run --emulator gem5 --gem5-restore 1 --gem5-readfile 'echo "second benchmark"'
  7856. ....
  7857. * link:rootfs_overlay/lkmc/gem5.sh[]. This script is analogous to gem5's in-tree https://github.com/gem5/gem5/blob/2b4b94d0556c2d03172ebff63f7fc502c3c26ff8/configs/boot/hack_back_ckpt.rcS[hack_back_ckpt.rcS], but with less noise.
  7858. +
  7859. Usage:
  7860. +
  7861. ....
  7862. # Boot, checkpoint and exit.
  7863. ./run --emulator gem5 --eval './gem5.sh' --gem5-readfile 'echo "setup run"'
  7864. # Restore and run the first benchmark.
  7865. ./run --emulator gem5 --gem5-restore 1 --gem5-readfile 'echo "first benchmark"'
  7866. # Restore and run the second benchmark.
  7867. ./run --emulator gem5 --gem5-restore 1 --gem5-readfile 'echo "second benchmark"'
  7868. ....
  7869. Their usage is also exemplified at <<gem5-run-benchmark>>.
  7870. If you forgot to use an appropriate `--eval` for your boot and the simulation is already running, link:rootfs_overlay/lkmc/gem5.sh[] can be used directly from an interactive guest shell.
  7871. First we reset the readfile to something that runs quickly:
  7872. ....
  7873. printf 'echo "first benchmark"' > "$(./getvar gem5_readfile_file)"
  7874. ....
  7875. and then in the guest, take a checkpoint and exit:
  7876. ....
  7877. ./gem5.sh
  7878. ....
  7879. Now the guest is in a state where readfile will be executed automatically without interactive intervention:
  7880. ....
  7881. ./run --emulator gem5 --gem5-restore 1 --gem5-readfile 'echo "first benchmark"'
  7882. ./run --emulator gem5 --gem5-restore 1 --gem5-readfile 'echo "second benchmark"'
  7883. ....
  7884. Other loophole possibilities to execute different benchmarks non-interactively include:
  7885. * <<9p>>
  7886. * <<secondary-disk>>
  7887. * `expect` as mentioned at: https://stackoverflow.com/questions/7013137/automating-telnet-session-using-bash-scripts
  7888. +
  7889. ....
  7890. #!/usr/bin/expect
  7891. spawn telnet localhost 3456
  7892. expect "# $"
  7893. send "pwd\r"
  7894. send "ls /\r"
  7895. send "m5 exit\r"
  7896. expect eof
  7897. ....
  7898. +
  7899. This is ugly however as it is not deterministic.
  7900. https://www.mail-archive.com/gem5-users@gem5.org/msg15233.html
  7901. ==== gem5 restore checkpoint with a different CPU
  7902. gem5 can switch to a different CPU model when restoring a checkpoint.
  7903. A common combo is to boot Linux with a fast CPU, make a checkpoint and then replay the benchmark of interest with a slower CPU.
  7904. An illustrative interactive run:
  7905. ....
  7906. ./run --arch arm --emulator gem5
  7907. ....
  7908. In guest:
  7909. ....
  7910. m5 checkpoint
  7911. ....
  7912. And then restore the checkpoint with a different CPU:
  7913. ....
  7914. ./run --arch arm --emulator gem5 --gem5-restore 1 -- --caches --restore-with-cpu=HPI
  7915. ....
  7916. === Pass extra options to gem5
  7917. Remember that in the gem5 command line, we can either pass options to the script being run as in:
  7918. ....
  7919. build/X86/gem5.opt configs/examples/fs.py --some-option
  7920. ....
  7921. or to the gem5 executable itself:
  7922. ....
  7923. build/X86/gem5.opt --some-option configs/examples/fs.py
  7924. ....
  7925. Pass options to the script in our setup use:
  7926. * get help:
  7927. +
  7928. ....
  7929. ./run --emulator gem5 -- -h
  7930. ....
  7931. * boot with the more detailed and slow `HPI` CPU model:
  7932. +
  7933. ....
  7934. ./run --arch arm --emulator gem5 -- --caches --cpu-type=HPI
  7935. ....
  7936. To pass options to the `gem5` executable we expose the `--gem5-exe-args` option:
  7937. * get help:
  7938. +
  7939. ....
  7940. ./run --gem5-exe-args='-h' --emulator gem5
  7941. ....
  7942. === m5ops
  7943. m5ops are magic instructions which lead gem5 to do magic things, like quitting or dumping stats.
  7944. Documentation: http://gem5.org/M5ops
  7945. There are two main ways to use m5ops:
  7946. * <<m5>>
  7947. * <<m5ops-instructions>>
  7948. `m5` is convenient if you only want to take snapshots before or after the benchmark, without altering its source code. It uses the <<m5ops-instructions>> as its backend.
  7949. `m5` cannot should / should not be used however:
  7950. * in bare metal setups
  7951. * when you want to call the instructions from inside interest points of your benchmark. Otherwise you add the syscall overhead to the benchmark, which is more intrusive and might affect results.
  7952. +
  7953. Why not just hardcode some <<m5ops-instructions>> as in our example instead, since you are going to modify the source of the benchmark anyways?
  7954. ==== m5
  7955. `m5` is a guest command line utility that is installed and run on the guest, that serves as a CLI front-end for the <<m5ops>>
  7956. Its source is present in the gem5 tree: https://github.com/gem5/gem5/blob/6925bf55005c118dc2580ba83e0fa10b31839ef9/util/m5/m5.c
  7957. It is possible to guess what most tools do from the corresponding <<m5ops>>, but let's at least document the less obvious ones here.
  7958. ===== m5 exit
  7959. End the simulation.
  7960. Sane Python scripts will exit gem5 with status 0, which is what `fs.py` does.
  7961. ===== m5 fail
  7962. End the simulation with a failure exit event:
  7963. ....
  7964. m5 fail 1
  7965. ....
  7966. Sane Python scripts would use that as the exit status of gem5, which would be useful for testing purposes, but `fs.py` at 200281b08ca21f0d2678e23063f088960d3c0819 just prints an error message:
  7967. ....
  7968. Simulated exit code not 0! Exit code is 1
  7969. ....
  7970. and exits with status 0.
  7971. We then parse that string ourselves in link:run[] and exit with the correct status...
  7972. TODO: it used to be like that, but it actually got changed to just print the message. Why? https://gem5-review.googlesource.com/c/public/gem5/+/4880
  7973. `m5 fail` is just a superset of `m5 exit`, which is just:
  7974. ....
  7975. m5 fail 0
  7976. ....
  7977. as can be seen from the source: https://github.com/gem5/gem5/blob/50a57c0376c02c912a978c4443dd58caebe0f173/src/sim/pseudo_inst.cc#L303
  7978. ===== m5 writefile
  7979. Send a guest file to the host. <<9p>> is a more advanced alternative.
  7980. Guest:
  7981. ....
  7982. echo mycontent > myfileguest
  7983. m5 writefile myfileguest myfilehost
  7984. ....
  7985. Host:
  7986. ....
  7987. cat "$(./getvar --arch aarch64 --emulator gem5 m5out_dir)/myfilehost"
  7988. ....
  7989. Does not work for subdirectories, gem5 crashes:
  7990. ....
  7991. m5 writefile myfileguest mydirhost/myfilehost
  7992. ....
  7993. ===== m5 readfile
  7994. Read a host file pointed to by the `fs.py --script` option to stdout.
  7995. https://stackoverflow.com/questions/49516399/how-to-use-m5-readfile-and-m5-execfile-in-gem5/49538051#49538051
  7996. Host:
  7997. ....
  7998. date > "$(./getvar gem5_readfile_file)"
  7999. ....
  8000. Guest:
  8001. ....
  8002. m5 readfile
  8003. ....
  8004. Outcome: date shows on guest.
  8005. ===== m5 initparam
  8006. Ermm, just another <<m5-readfile>> that only takes integers and only from CLI options? Is this software so redundant?
  8007. Host:
  8008. ....
  8009. ./run --emulator gem5 --gem5-restore 1 -- --initparam 13
  8010. ./run --emulator gem5 --gem5-restore 1 -- --initparam 42
  8011. ....
  8012. Guest:
  8013. ....
  8014. m5 initparm
  8015. ....
  8016. Outputs the given paramter.
  8017. ===== m5 execfile
  8018. Trivial combination of `m5 readfile` + execute the script.
  8019. Host:
  8020. ....
  8021. printf '#!/bin/sh
  8022. echo asdf
  8023. ' > "$(./getvar gem5_readfile_file)"
  8024. ....
  8025. Guest:
  8026. ....
  8027. touch /tmp/execfile
  8028. chmod +x /tmp/execfile
  8029. m5 execfile
  8030. ....
  8031. Outcome:
  8032. ....
  8033. adsf
  8034. ....
  8035. ==== m5ops instructions
  8036. gem5 allocates some magic instructions on unused instruction encodings for convenient guest instrumentation.
  8037. Those instructions are exposed through the <<m5>> in tree executable.
  8038. To make things simpler to understand, you can play around with our own minimized educational `m5` subset link:userland/c/m5ops.c[].
  8039. The instructions used by `./c/m5ops.out` are present in link:lkmc/m5ops.h[] in a very simple to understand and reuse inline assembly form.
  8040. To use that file, first rebuild `m5ops.out` with the m5ops instructions enabled and install it on the root filesystem:
  8041. ....
  8042. ./build-userland \
  8043. --arch aarch64 \
  8044. --ccflags='-DLKMC_M5OPS_ENABLE=1' \
  8045. --force-rebuild \
  8046. --static \
  8047. userland/c/m5ops.c \
  8048. ;
  8049. ./build-buildroot --arch aarch64
  8050. ....
  8051. We don't enable `-DLKMC_M5OPS_ENABLE=1` by default on userland executables because we try to use a single image for both gem5, QEMU and <<userland-setup-getting-started-natively,native>>, and those instructions would break the latter two. We enable it in the <<baremetal-setup>> by default since we already have different images for QEMU and gem5 there.
  8052. Then, from inside <<gem5-buildroot-setup>>, test it out with:
  8053. ....
  8054. # checkpoint
  8055. ./c/m5ops.out c
  8056. # dumpstats
  8057. ./c/m5ops.out d
  8058. # exit
  8059. ./c/m5ops.out e
  8060. # dump resetstats
  8061. ./c/m5ops.out r
  8062. ....
  8063. In theory, the cleanest way to add m5ops to your benchmarks would be to do exactly what the `m5` tool does:
  8064. * include https://github.com/gem5/gem5/blob/05c4c2b566ce351ab217b2bd7035562aa7a76570/include/gem5/asm/generic/m5ops.h[`include/gem5/asm/generic/m5ops.h`]
  8065. * link with the `.o` file under `util/m5` for the correct arch, e.g. `m5op_arm_A64.o` for aarch64.
  8066. However, I think it is usually not worth the trouble of hacking up the build system of the benchmark to do this, and I recommend just hardcoding in a few raw instructions here and there, and managing it with version control + `sed`.
  8067. Bibliography:
  8068. * https://stackoverflow.com/questions/56506154/how-to-analyze-only-interest-area-in-source-code-by-using-gem5/56506419#56506419
  8069. * https://www.mail-archive.com/gem5-users@gem5.org/msg15418.html
  8070. ===== m5ops instructions interface
  8071. Let's study how <<m5>> uses them:
  8072. * https://github.com/gem5/gem5/blob/05c4c2b566ce351ab217b2bd7035562aa7a76570/include/gem5/asm/generic/m5ops.h[`include/gem5/asm/generic/m5ops.h`]: defines the magic constants that represent the instructions
  8073. * https://github.com/gem5/gem5/blob/05c4c2b566ce351ab217b2bd7035562aa7a76570/util/m5/m5op_arm_A64.S[`util/m5/m5op_arm_A64.S`]: use the magic constants that represent the instructions using C preprocessor magic
  8074. * https://github.com/gem5/gem5/blob/05c4c2b566ce351ab217b2bd7035562aa7a76570/util/m5/m5.c[`util/m5/m5.c`]: the actual executable. Gets linked to `m5op_arm_A64.S` which defines a function for each m5op.
  8075. We notice that there are two different implementations for each arch:
  8076. * magic instructions, which don't exist in the corresponding arch
  8077. * magic memory addresses on a given page
  8078. TODO: what is the advantage of magic memory addresses? Because you have to do more setup work by telling the kernel never to touch the magic page. For the magic instructions, the only thing that could go wrong is if you run some crazy kind of fuzzing workload that generates random instructions.
  8079. Then, in aarch64 magic instructions for example, the lines:
  8080. ....
  8081. .macro m5op_func, name, func, subfunc
  8082. .globl \name
  8083. \name:
  8084. .long 0xff000110 | (\func << 16) | (\subfunc << 12)
  8085. ret
  8086. ....
  8087. define a simple function function for each m5op. Here we see that:
  8088. * `0xff000110` is a base mask for the magic non-existing instruction
  8089. * `\func` and `\subfunc` are OR-applied on top of the base mask, and define m5op this is.
  8090. +
  8091. Those values will loop over the magic constants defined in `m5ops.h` with the deferred preprocessor idiom.
  8092. +
  8093. For example, `exit` is `0x21` due to:
  8094. +
  8095. ....
  8096. #define M5OP_EXIT 0x21
  8097. ....
  8098. Finally, `m5.c` calls the defined functions as in:
  8099. ....
  8100. m5_exit(ints[0]);
  8101. ....
  8102. Therefore, the runtime "argument" that gets passed to the instruction, e.g. the delay in ticks until the exit for `m5 exit`, gets passed directly through the https://en.wikipedia.org/wiki/Calling_convention#ARM_(A64)[aarch64 calling convention].
  8103. Keep in mind that for all archs, `m5.c` does the calls with 64-bit integers:
  8104. ....
  8105. uint64_t ints[2] = {0,0};
  8106. parse_int_args(argc, argv, ints, argc);
  8107. m5_fail(ints[1], ints[0]);
  8108. ....
  8109. Therefore, for example:
  8110. * aarch64 uses `x0` for the first argument and `x1` for the second, since each is 64 bits log already
  8111. * arm uses `r0` and `r1` for the first argument, and `r2` and `r3` for the second, since each register is only 32 bits long
  8112. That convention specifies that `x0` to `x7` contain the function arguments, so `x0` contains the first argument, and `x1` the second.
  8113. In our `m5ops` example, we just hardcode everything in the assembly one-liners we are producing.
  8114. We ignore the `\subfunc` since it is always 0 on the ops that interest us.
  8115. ===== m5op annotations
  8116. `include/gem5/asm/generic/m5ops.h` also describes some annotation instructions.
  8117. What they mean: https://stackoverflow.com/questions/50583962/what-are-the-gem5-annotations-mops-magic-instructions-and-how-to-use-them
  8118. === gem5 arm Linux kernel patches
  8119. https://gem5.googlesource.com/arm/linux/ contains an ARM Linux kernel forks with a few gem5 specific Linux kernel patches on top of mainline created by ARM Holdings on top of a few upstream kernel releases.
  8120. Our link:build[] script automatically adds that remote for us as `gem5-arm`.
  8121. The patches are optional: the vanilla kernel does boot. But they add some interesting gem5-specific optimizations, instrumentations and device support.
  8122. The patches also <<notable-alternate-gem5-kernel-configs,add defconfigs>> that are known to work well with gem5.
  8123. E.g. for arm v4.9 there is: https://gem5.googlesource.com/arm/linux/+/917e007a4150d26a0aa95e4f5353ba72753669c7/arch/arm/configs/gem5_defconfig[].
  8124. In order to use those patches and their associated configs, and, we recommend using <<linux-kernel-build-variants>> as:
  8125. ....
  8126. git -C "$(./getvar linux_source_dir)" fetch gem5-arm:gem5/v4.15
  8127. git -C "$(./getvar linux_source_dir)" checkout gem5/v4.15
  8128. ./build-linux \
  8129. --arch aarch64 \
  8130. --custom-config-file-gem5 \
  8131. --linux-build-id gem5-v4.15 \
  8132. ;
  8133. git -C "$(./getvar linux_source_dir)" checkout -
  8134. ./run \
  8135. --arch aarch64 \
  8136. --emulator gem5 \
  8137. --linux-build-id gem5-v4.15 \
  8138. ;
  8139. ....
  8140. QEMU also boots that kernel successfully:
  8141. ....
  8142. ./run \
  8143. --arch aarch64 \
  8144. --linux-build-id gem5-v4.15 \
  8145. ;
  8146. ....
  8147. but glibc kernel version checks make init fail with:
  8148. ....
  8149. FATAL: kernel too old
  8150. ....
  8151. because glibc was built to expect a newer Linux kernel as shown at: xref:fatal-kernel-too-old[xrefstyle=full]. Your choices to sole this are:
  8152. * see if there is a more recent gem5 kernel available, or port your patch of interest to the newest kernel
  8153. * modify this repo to use <<libc-choice,uClibc>>, which is not hard because of Buildroot
  8154. * patch glibc to remove that check, which is easy because glibc is in a submodule of this repo
  8155. It is obviously not possible to understand what they actually do from their commit message, so let's explain them one by one here as we understand them:
  8156. * `drm: Add component-aware simple encoder` allows you to see images through VNC, see: xref:gem5-graphic-mode[xrefstyle=full]
  8157. * `gem5: Add support for gem5's extended GIC mode` adds support for more than 8 cores, see: xref:gem5-arm-full-system-with-more-than-8-cores[xrefstyle=full]
  8158. Tested on 649d06d6758cefd080d04dc47fd6a5a26a620874 + 1.
  8159. ==== gem5 arm Linux kernel patches boot speedup
  8160. We have observed that with the kernel patches, boot is 2x faster, falling from 1m40s to 50s.
  8161. With https://stackoverflow.com/questions/49797246/how-to-monitor-for-how-much-time-each-line-of-stdout-was-the-last-output-line-in/49797547#49797547[`ts`], we see that a large part of the difference is at the message:
  8162. ....
  8163. clocksource: Switched to clocksource arch_sys_counter
  8164. ....
  8165. which takes 4s on the patched kernel, and 30s on the unpatched one! TODO understand why, especially if it is a config difference, or if it actually comes from a patch.
  8166. === m5out directory
  8167. When you run gem5, it generates an `m5out` directory at:
  8168. ....
  8169. echo $(./getvar --arch arm --emulator gem5 m5out_dir)"
  8170. ....
  8171. The location of that directory can be set with `./gem5.opt -d`, and defaults to `./m5out`.
  8172. The files in that directory contains some very important information about the run, and you should become familiar with every one of them.
  8173. [[gem5-m5out-system-terminal-file]]
  8174. ==== gem5 m5out/system.terminal file
  8175. Contains UART output, both from the Linux kernel or from the baremetal system.
  8176. Can also be seen live on <<m5term>>.
  8177. [[gem5-m5out-stats-txt-file]]
  8178. ==== gem5 m5out/stats.txt file
  8179. This file contains important statistics about the run:
  8180. ....
  8181. cat "$(./getvar --arch aarch64 m5out_dir)/stats.txt"
  8182. ....
  8183. Whenever we run `m5 dumpstats` or `m5 exit`, a section with the following format is added to that file:
  8184. ....
  8185. ---------- Begin Simulation Statistics ----------
  8186. [the stats]
  8187. ---------- End Simulation Statistics ----------
  8188. ....
  8189. That file contains several important execution metrics, e.g. number of cycles and several types of cache misses:
  8190. ....
  8191. system.cpu.numCycles
  8192. system.cpu.dtb.inst_misses
  8193. system.cpu.dtb.inst_hits
  8194. ....
  8195. For x86, it is interesting to try and correlate `numCycles` with:
  8196. ===== gem5 only dump selected stats
  8197. TODO
  8198. https://stackoverflow.com/questions/52014953/how-to-dump-only-a-single-or-certain-selected-stats-in-gem5
  8199. To prevent the stats file from becoming humongous.
  8200. ==== gem5 config.ini
  8201. The `m5out/config.ini` file, contains a very good high level description of the system:
  8202. ....
  8203. less $(./getvar --arch arm --emulator gem5 m5out_dir)"
  8204. ....
  8205. That file contains a tree representation of the system, sample excerpt:
  8206. ....
  8207. [root]
  8208. type=Root
  8209. children=system
  8210. full_system=true
  8211. [system]
  8212. type=ArmSystem
  8213. children=cpu cpu_clk_domain
  8214. auto_reset_addr_64=false
  8215. semihosting=Null
  8216. [system.cpu]
  8217. type=AtomicSimpleCPU
  8218. children=dstage2_mmu dtb interrupts isa istage2_mmu itb tracer
  8219. branchPred=Null
  8220. [system.cpu_clk_domain]
  8221. type=SrcClockDomain
  8222. clock=500
  8223. ....
  8224. Each node has:
  8225. * a list of child nodes, e.g. `system` is a child of `root`, and both `cpu` and `cpu_clk_domain` are children of `system`
  8226. * a list of parameters, e.g. `system.semihosting` is `Null`, which means that <<semihosting>> was turned off
  8227. ** the `type` parameter shows is present on every node, and it maps to a `Python` object that inherits from `SimObject`.
  8228. +
  8229. For example, `AtomicSimpleCPU` maps is defined at https://github.com/gem5/gem5/blob/05c4c2b566ce351ab217b2bd7035562aa7a76570/src/cpu/simple/AtomicSimpleCPU.py#L45[src/cpu/simple/AtomicSimpleCPU.py].
  8230. You can also get a simplified graphical view of the tree with:
  8231. ....
  8232. xdg-open "$(./getvar --arch arm --emulator gem5 m5out_dir)/config.dot.pdf"
  8233. ....
  8234. Modifying the `config.ini` file manually does nothing since it gets overwritten every time.
  8235. Set custom configs with the `--param` option of `fs.py`, e.g. we can make gem5 wait for GDB to connect with:
  8236. ....
  8237. fs.py --param 'system.cpu[0].wait_for_remote_gdb = True'
  8238. ....
  8239. More complex settings involving new classes however require patching the config files, although it is easy to hack this up. See for example: link:patches/manual/gem5-semihost.patch[].
  8240. === m5term
  8241. We use the `m5term` in-tree executable to connect to the terminal instead of a direct `telnet`.
  8242. If you use `telnet` directly, it mostly works, but certain interactive features don't, e.g.:
  8243. * up and down arrows for history navigation
  8244. * tab to complete paths
  8245. * `Ctrl-C` to kill processes
  8246. TODO understand in detail what `m5term` does differently than `telnet`.
  8247. === gem5 Python scripts without rebuild
  8248. We have made a crazy setup that allows you to just `cd` into `submodules/gem5`, and edit Python scripts directly there.
  8249. This is not normally possible with Buildroot, since normal Buildroot packages first copy files to the output directory (`$(./getvar -a <arch> buildroot_build_build_dir)/<pkg>`), and then build there.
  8250. So if you modified the Python scripts with this setup, you would still need to `./build` to copy the modified files over.
  8251. For gem5 specifically however, we have hacked up the build so that we `cd` into the `submodules/gem5` tree, and then do an https://stackoverflow.com/questions/54343515/how-to-build-gem5-out-of-tree/54343516#54343516[out of tree] build to `out/common/gem5`.
  8252. Another advantage of this method is the we factor out the `arm` and `aarch64` gem5 builds which are identical and large, as well as the smaller arch generic pieces.
  8253. Using Buildroot for gem5 is still convenient because we use it to:
  8254. * to cross build `m5` for us
  8255. * check timestamps and skip the gem5 build when it is not requested
  8256. The out of build tree is required, because otherwise Buildroot would copy the output build of all archs to each arch directory, resulting in `arch^2` build copies, which is significant.
  8257. === gem5 fs_bigLITTLE
  8258. By default, we use `configs/example/fs.py` script.
  8259. The `--gem5-script biglittle` option enables the alternative `configs/example/arm/fs_bigLITTLE.py` script instead:
  8260. ....
  8261. ./run --arch aarch64 --emulator gem5 --gem5-script biglittle
  8262. ....
  8263. Advantages over `fs.py`:
  8264. * more representative of mobile ARM SoCs, which almost always have big little cluster
  8265. * simpler than `fs.py`, and therefore easier to understand and modify
  8266. Disadvantages over `fs.py`:
  8267. * only works for ARM, not other archs
  8268. * not as many configuration options as `fs.py`, many things are hardcoded
  8269. We setup 2 big and 2 small CPUs, but `cat /proc/cpuinfo` shows 4 identical CPUs instead of 2 of two different types, likely because gem5 does not expose some informational register much like the caches: https://www.mail-archive.com/gem5-users@gem5.org/msg15426.html <<gem5-config-ini>> does show that the two big ones are `DerivO3CPU` and the small ones are `MinorCPU`.
  8270. TODO: why is the `--dtb` required despite `fs_bigLITTLE.py` having a DTB generation capability? Without it, nothing shows on terminal, and the simulation terminates with `simulate() limit reached @ 18446744073709551615`. The magic `vmlinux.vexpress_gem5_v1.20170616` works however without a DTB.
  8271. Tested on: https://github.com/cirosantilli/linux-kernel-module-cheat/commit/18c1c823feda65f8b54cd38e261c282eee01ed9f[18c1c823feda65f8b54cd38e261c282eee01ed9f]
  8272. === gem5 unit tests
  8273. https://stackoverflow.com/questions/52279971/how-to-run-the-gem5-unit-tests
  8274. These are just very small GTest tests that test a single class in isolation, they don't run any executables.
  8275. Build the unit tests and run them:
  8276. ....
  8277. ./build-gem5 --unit-tests
  8278. ....
  8279. Running individual unit tests is not yet exposed, but it is easy to do: while running the full tests, GTest prints each test command being run, e.g.:
  8280. ....
  8281. /path/to/build/ARM/base/circlebuf.test.opt --gtest_output=xml:/path/to/build/ARM/unittests.opt/base/circlebuf.test.xml
  8282. [==========] Running 4 tests from 1 test case.
  8283. [----------] Global test environment set-up.
  8284. [----------] 4 tests from CircleBufTest
  8285. [ RUN ] CircleBufTest.BasicReadWriteNoOverflow
  8286. [ OK ] CircleBufTest.BasicReadWriteNoOverflow (0 ms)
  8287. [ RUN ] CircleBufTest.SingleWriteOverflow
  8288. [ OK ] CircleBufTest.SingleWriteOverflow (0 ms)
  8289. [ RUN ] CircleBufTest.MultiWriteOverflow
  8290. [ OK ] CircleBufTest.MultiWriteOverflow (0 ms)
  8291. [ RUN ] CircleBufTest.PointerWrapAround
  8292. [ OK ] CircleBufTest.PointerWrapAround (0 ms)
  8293. [----------] 4 tests from CircleBufTest (0 ms total)
  8294. [----------] Global test environment tear-down
  8295. [==========] 4 tests from 1 test case ran. (0 ms total)
  8296. [ PASSED ] 4 tests.
  8297. ....
  8298. so you can just copy paste the command.
  8299. Building individual tests is possible with:
  8300. ....
  8301. ./build-gem5 --unit-test base/circlebuf.test
  8302. ....
  8303. This does not run the test however.
  8304. Note that the command and it's corresponding results don't need to show consecutively on stdout because tests are run in parallel. You just have to match them based on the class name `CircleBufTest` to the file `circlebuf.test.cpp`.
  8305. === gem5 regression tests
  8306. https://stackoverflow.com/questions/52279971/how-to-run-the-gem5-unit-tests
  8307. Running the larger 2019 regression tests is exposed for example with:
  8308. ....
  8309. ./gem5-regression --arch aarch64 -- --length quick
  8310. ....
  8311. TODO skip the build by default with `--skip-build` since we already manage it with `./build-gem5`. But we can't do this because it is the build step that downloads the test binaries. We need to find a way to either download the binaries without building, or to pass the exact same scons build options through `test/main.py`.
  8312. === gem5 simulate() limit reached
  8313. This error happens when the following instruction limits are reached:
  8314. ....
  8315. system.cpu[0].max_insts_all_threads
  8316. system.cpu[0].max_insts_any_thread
  8317. ....
  8318. If the parameter is not set, it defaults to `0`, which is magic and means the huge maximum value of `uint64_t`: 0xFFFFFFFFFFFFFFFF, which in practice would require a very long simulation if at least one CPU were live.
  8319. So this usually means all CPUs are in a sleep state, and no events are scheduled in the future, which usually indicates a bug in either gem5 or guest code, leading gem5 to blow up.
  8320. Still, fs.py at gem5 08c79a194d1a3430801c04f37d13216cc9ec1da3 does not exit with non-zero status due to this... and so we just parse it out just as for <<m5-fail>>...
  8321. A trivial and very direct way to see message would be:
  8322. ....
  8323. ./run \
  8324. --emulator gem5 \
  8325. --static \
  8326. --userland \userland/arch/x86_64/freestanding/linux/hello.S \
  8327. --trace-insts-stdout \
  8328. -- \
  8329. --param 'system.cpu[0].max_insts_all_threads = 3' \
  8330. ;
  8331. ....
  8332. which as of lkmc 402059ed22432bb351d42eb10900e5a8e06aa623 runs only the first three instructions and quits!
  8333. ....
  8334. info: Entering event queue @ 0. Starting simulation...
  8335. 0: system.cpu A0 T0 : @asm_main_after_prologue : mov rdi, 0x1
  8336. 0: system.cpu A0 T0 : @asm_main_after_prologue.0 : MOV_R_I : limm rax, 0x1 : IntAlu : D=0x0000000000000001 flags=(IsInteger|IsMicroop|IsLastMicroop|IsFirstMicroop)
  8337. 1000: system.cpu A0 T0 : @asm_main_after_prologue+7 : mov rdi, 0x1
  8338. 1000: system.cpu A0 T0 : @asm_main_after_prologue+7.0 : MOV_R_I : limm rdi, 0x1 : IntAlu : D=0x0000000000000001 flags=(IsInteger|IsMicroop|IsLastMicroop|IsFirstMicroop)
  8339. 2000: system.cpu A0 T0 : @asm_main_after_prologue+14 : lea rsi, DS:[rip + 0x19]
  8340. 2000: system.cpu A0 T0 : @asm_main_after_prologue+14.0 : LEA_R_P : rdip t7, %ctrl153, : IntAlu : D=0x000000000040008d flags=(IsInteger|IsMicroop|IsDelayedCommit|IsFirstMicroop)
  8341. 2500: system.cpu A0 T0 : @asm_main_after_prologue+14.1 : LEA_R_P : lea rsi, DS:[t7 + 0x19] : IntAlu : D=0x00000000004000a6 flags=(IsInteger|IsMicroop|IsLastMicroop)
  8342. Exiting @ tick 3000 because all threads reached the max instruction count
  8343. ....
  8344. The exact same can be achieved with the older hardcoded `--maxinsts` mechanism present in `se.py` and `fs.py`:
  8345. ....
  8346. ./run \
  8347. --emulator gem5 \
  8348. --static \
  8349. --userland \userland/arch/x86_64/freestanding/linux/hello.S \
  8350. --trace-insts-stdout \
  8351. -- \
  8352. --maxinsts 3
  8353. ;
  8354. ....
  8355. The message also shows on <<user-mode-simulation>> deadlocks, for example in link:userland/posix/pthread_deadlock.c[]:
  8356. ....
  8357. ./run \
  8358. --emulator gem5 \
  8359. --static \
  8360. --userland userland/posix/pthread_deadlock.c \
  8361. --userland-args 1 \
  8362. ;
  8363. ....
  8364. ends in:
  8365. ....
  8366. Exiting @ tick 18446744073709551615 because simulate() limit reached
  8367. ....
  8368. where 18446744073709551615 is 0xFFFFFFFFFFFFFFFF in decimal.
  8369. And there is a <<baremetal>> example at link:baremetal/arch/aarch64/no_bootloader/wfe_loop.S[] that dies on <<arm-wfe-and-sev-instructions,WFE>>:
  8370. ....
  8371. ./run \
  8372. --arch aarch64 \
  8373. --baremetal baremetal/arch/aarch64/no_bootloader/wfe_loop.S \
  8374. --emulator gem5 \
  8375. --trace-insts-stdout \
  8376. ;
  8377. ....
  8378. which gives:
  8379. ....
  8380. info: Entering event queue @ 0. Starting simulation...
  8381. 0: system.cpu A0 T0 : @lkmc_start : wfe : IntAlu : D=0x0000000000000000 flags=(IsSerializeAfter|IsNonSpeculative|IsQuiesce|IsUnverifiable)
  8382. 1000: system.cpu A0 T0 : @lkmc_start+4 : b <lkmc_start> : IntAlu : flags=(IsControl|IsDirectControl|IsUncondControl)
  8383. 1500: system.cpu A0 T0 : @lkmc_start : wfe : IntAlu : D=0x0000000000000000 flags=(IsSerializeAfter|IsNonSpeculative|IsQuiesce|IsUnverifiable)
  8384. Exiting @ tick 18446744073709551615 because simulate() limit reached
  8385. ....
  8386. Other examples of the message:
  8387. * <<arm-multicore>> with a single CPU stays stopped at an WFE sleep instruction
  8388. * this sample bug on se.py multithreading: https://github.com/cirosantilli/linux-kernel-module-cheat/issues/81
  8389. === gem5 build options
  8390. In order to use different build options, you might also want to use <<gem5-build-variants>> to keep the build outputs separate from one another.
  8391. ==== gem5 debug build
  8392. Explained at: xref:debug-the-emulator[xrefstyle=full].
  8393. ==== gem5 clang build
  8394. TODO test properly, benchmark vs GCC.
  8395. ....
  8396. sudo apt-get install clang
  8397. ./build-gem5 --clang
  8398. ./run --clang --emulator gem5
  8399. ....
  8400. ==== gem5 sanitation build
  8401. If there gem5 appears to have a C++ undefined behaviour bug, which is often very difficult to track down, you can try to build it with the following extra SCons options:
  8402. ....
  8403. ./build-gem5 --gem5-build-id san --verbose -- --with-ubsan --without-tcmalloc
  8404. ....
  8405. This will make GCC do a lot of extra sanitation checks at compile and run time.
  8406. As a result, the build and runtime will be way slower than normal, but that still might be the fastest way to solve undefined behaviour problems.
  8407. Ideally, we should also be able to run it with asan with `--with-asan`, but if we try then the build fails at gem5 16eeee5356585441a49d05c78abc328ef09f7ace (with two ubsan trivial fixes I'll push soon):
  8408. ....
  8409. =================================================================
  8410. ==9621==ERROR: LeakSanitizer: detected memory leaks
  8411. Direct leak of 371712 byte(s) in 107 object(s) allocated from:
  8412. #0 0x7ff039804448 in malloc (/usr/lib/x86_64-linux-gnu/libasan.so.5+0x10c448)
  8413. #1 0x7ff03950d065 in dictresize ../Objects/dictobject.c:643
  8414. Direct leak of 23728 byte(s) in 26 object(s) allocated from:
  8415. #0 0x7ff039804448 in malloc (/usr/lib/x86_64-linux-gnu/libasan.so.5+0x10c448)
  8416. #1 0x7ff03945e40d in _PyObject_GC_Malloc ../Modules/gcmodule.c:1499
  8417. #2 0x7ff03945e40d in _PyObject_GC_Malloc ../Modules/gcmodule.c:1493
  8418. Direct leak of 2928 byte(s) in 43 object(s) allocated from:
  8419. #0 0x7ff03980487e in __interceptor_realloc (/usr/lib/x86_64-linux-gnu/libasan.so.5+0x10c87e)
  8420. #1 0x7ff03951d763 in list_resize ../Objects/listobject.c:62
  8421. #2 0x7ff03951d763 in app1 ../Objects/listobject.c:277
  8422. #3 0x7ff03951d763 in PyList_Append ../Objects/listobject.c:289
  8423. Direct leak of 2002 byte(s) in 3 object(s) allocated from:
  8424. #0 0x7ff039804448 in malloc (/usr/lib/x86_64-linux-gnu/libasan.so.5+0x10c448)
  8425. #1 0x7ff0394fd813 in PyString_FromStringAndSize ../Objects/stringobject.c:88
  8426. #2 0x7ff0394fd813 in PyString_FromStringAndSize ../Objects/stringobject.c:57 Direct leak of 40 byte(s) in 2 object(s) allocated from: #0 0x7ff039804448 in malloc (/usr/lib/x86_64-linux-gnu/libasan.so.5+0x10c448)
  8427. #1 0x7ff03951ea4b in PyList_New ../Objects/listobject.c:152
  8428. Indirect leak of 10384 byte(s) in 11 object(s) allocated from: #0 0x7ff039804448 in malloc (/usr/lib/x86_64-linux-gnu/libasan.so.5+0x10c448) #1 0x7ff03945e40d in _PyObject_GC_Malloc ../Modules/gcmodule.c:1499 #2 0x7ff03945e40d in _PyObject_GC_Malloc ../Modules/gcmodule.c:1493
  8429. Indirect leak of 4089 byte(s) in 6 object(s) allocated from:
  8430. #0 0x7ff039804448 in malloc (/usr/lib/x86_64-linux-gnu/libasan.so.5+0x10c448)
  8431. #1 0x7ff0394fd648 in PyString_FromString ../Objects/stringobject.c:143
  8432. Indirect leak of 2090 byte(s) in 3 object(s) allocated from:
  8433. #0 0x7ff039804448 in malloc (/usr/lib/x86_64-linux-gnu/libasan.so.5+0x10c448) #1 0x7ff0394eb36f in type_new ../Objects/typeobject.c:2421 #2 0x7ff0394eb36f in type_new ../Objects/typeobject.c:2094
  8434. Indirect leak of 1346 byte(s) in 2 object(s) allocated from:
  8435. #0 0x7ff039804448 in malloc (/usr/lib/x86_64-linux-gnu/libasan.so.5+0x10c448)
  8436. #1 0x7ff0394fd813 in PyString_FromStringAndSize ../Objects/stringobject.c:88 #2 0x7ff0394fd813 in PyString_FromStringAndSize ../Objects/stringobject.c:57 SUMMARY: AddressSanitizer: 418319 byte(s) leaked in 203 allocation(s).
  8437. ....
  8438. From the message, this appears however to be a Python / pyenv11 bug however and not in gem5 specifically. I think it worked when I tried it in the past in an older gem5 / Ubuntu.
  8439. ==== gem5 Ruby build
  8440. Ruby is a system that includes the SLICC domain specific language to describe memory systems: http://gem5.org/Ruby
  8441. It seems to have usage outside of gem5, but the naming overload with the link:https://en.wikipedia.org/wiki/Ruby_(programming_language)[Ruby programming language], which also has link:https://thoughtbot.com/blog/writing-a-domain-specific-language-in-ruby[domain specific languages] as a concept, makes it impossible to google anything about it!
  8442. Ruby is activated at compile time with the `PROTOCOL` flag, which specifies the desired memory system time.
  8443. For example, to use a two level https://en.wikipedia.org/wiki/MESI_protocol[MESI] https://en.wikipedia.org/wiki/Cache_coherence[cache coherence protocol], we can do:
  8444. ....
  8445. ./build-gem5 --arch aarch64 --gem5-build-id ruby -- PROTOCOL=MESI_Two_Level
  8446. ./run --arch aarch64 --emulator -gem5 --gem5-build-id ruby -- --ruby
  8447. ....
  8448. and during build we see a humongous line of type:
  8449. ....
  8450. [ SLICC] src/mem/protocol/MESI_Two_Level.slicc -> ARM/mem/protocol/AccessPermission.cc, ARM/mem/protocol/AccessPermission.hh, ...
  8451. ....
  8452. which shows that dozens of C++ files are being generated from Ruby SLICC.
  8453. TODO observe it doing something during a run.
  8454. The relevant source files live in the source tree under:
  8455. ....
  8456. src/mem/protocol/MESI_Two_Level*
  8457. ....
  8458. We already pass the `SLICC_HTML` flag by default to the build, which generates an HTML summary of each memory protocol under:
  8459. ....
  8460. xdg-open "$(./getvar --arch aarch64 --gem5-build-id ruby gem5_build_build_dir)/ARM/mem/protocol/html/index.html"
  8461. ....
  8462. A minimized ruby config which was not merged upstream can be found for study at: https://gem5-review.googlesource.com/c/public/gem5/+/13599/1
  8463. ==== gem5 Python 3 build
  8464. Python 3 support was mostly added in 2019 Q3 at arounda347a1a68b8a6e370334be3a1d2d66675891e0f1 but remained buggy for some time afterwards.
  8465. In an Ubuntu 18.04 host where `python` is `python2` by default, build with Python 3 instead with:
  8466. ....
  8467. ./build-gem5 --gem5-build-id python3 -- PYTHON_CONFIG=python3-config
  8468. ....
  8469. Python 3 is then automatically used when running if you use that build.
  8470. === gem5 CPU types
  8471. gem5 has a few in tree CPU models for different purposes.
  8472. In fs.py and se.py, those are selectable with the `--cpu-type` option.
  8473. TODO are there any public performance correlations between those models and real cores? The information to make accurate models isn't generally public for non-free CPUs, so either you must either rely vendor provided models or on experiments/reverse engineering.
  8474. ==== gem5 BaseSimpleCPU
  8475. Simple abstract CPU without a pipeline.
  8476. They are therefore completely unrealistic. But they also run much faster.
  8477. Implementations:
  8478. * `AtomicSimpleCPU`: the default one. Memory accesses happen instantaneously. The fastest simulation except for KVM, but not realistic at all.
  8479. +
  8480. Useful to <<gem5-restore-checkpoint-with-a-different-cpu,boot Linux fast and then checkpoint and switch to a more detailed CPU>>.
  8481. * `TimingSimpleCPU`: memory accesses are realistic, but the CPU has no pipeline. The simulation is faster than detailed models, but slower than `AtomicSimpleCPU`. TODO: application?
  8482. <<gem5-kvm,KVM CPUs>> are an alternative way of fast forwarding boot when they work.
  8483. ==== gem5 MinorCPU
  8484. Generic in-order core that does not model any specific CPU.
  8485. Its C++ implementation that can be parametrized to more closely match real cores.
  8486. Note that since gem5 is highly parametrizable, the parametrization could even change which instructions a CPU can execute by altering its available https://en.wikipedia.org/wiki/Execution_unit[functional units], which are used to model performance.
  8487. For example, `MinorCPU` allows all implemented instructions, including <<arm-sve>> instructions, but a derived class modelling, say, an https://en.wikipedia.org/wiki/ARM_Cortex-A7[ARM Cortex A7 core], might not, since SVE is a newer feature and the A7 core does not have SVE.
  8488. The weird name "Minor" stands for "M (TODO what is M) IN ONder".
  8489. Its 4 stage pipeline is described at the "MinorCPU" section of <<gem5-arm-rsk>>.
  8490. As of 2019, in-order cores are mostly present in low power / cost contexts, for example little cores of https://en.wikipedia.org/wiki/ARM_big.LITTLE[ARM bigLITTLE].
  8491. The following models extend the `MinorCPU` class by parametrization to make it match existing CPUs more closely:
  8492. * `HPI`: derived from `MinorCPU`.
  8493. +
  8494. Created by Ashkan Tousi in 2017 while working at ARM.
  8495. +
  8496. According to <<gem5-arm-rsk>>:
  8497. +
  8498. ____
  8499. The HPI CPU timing model is tuned to be representative of a modern in-order Armv8-A implementation.
  8500. ____
  8501. +
  8502. * `ex5_LITTLE`: derived from `MinorCPU`. Description reads:
  8503. +
  8504. ____
  8505. ex5 LITTLE core (based on the ARM Cortex-A7)
  8506. ____
  8507. +
  8508. Implemented by Pierre-Yves Péneau from LIRMM, which is a research lab in Montpellier, France, in 2017.
  8509. ==== gem5 DeriveO3CPU
  8510. Generic out-of-order core. "O3" Stands for "Out Of Order"!
  8511. Analogous to <<gem5-minorcpu,MinorCPU>>, but modelling an out of order core instead of in order.
  8512. Existing parametrizations:
  8513. * `ex5_big`: big corresponding to `ex5_LITTLE`, by same author at same time. It description reads:
  8514. +
  8515. ____
  8516. ex5 big core (based on the ARM Cortex-A15)
  8517. ____
  8518. ==== gem5 ARM RSK
  8519. https://github.com/arm-university/arm-gem5-rsk/blob/aa3b51b175a0f3b6e75c9c856092ae0c8f2a7cdc/gem5_rsk.pdf
  8520. Dated 2017, it contains a good overview of gem5 CPUs.
  8521. === gem5 ARM platforms
  8522. The gem5 platform is selectable with the `--machine` option, which is named after the analogous QEMU `-machine` option, and which sets the `--machine-type`.
  8523. Each platform represents a different system with different devices, memory and interrupt setup.
  8524. TODO: describe the main characteristics of each platform, as of gem5 5e83d703522a71ec4f3eb61a01acd8c53f6f3860:
  8525. * `VExpress_GEM5_V1`: good sane base platform
  8526. * `VExpress_GEM5_V1_DPU`: `VExpress_GEM5_V1` with DP650 instead of HDLCD, selected automatically by `./run --dp650`, see also: <<gem5-graphic-mode-dp650>>
  8527. * `VExpress_GEM5_V2`: VExpress_GEM5_V1 with GICv3, uses a different bootloader `arm/aarch64_bootloader/boot_emm_v2.arm64` TODO is it because of GICv3?
  8528. * anything that does not start with: `VExpress_GEM5_`: old and bad, don't use them
  8529. === gem5 internals
  8530. Internals under other sections:
  8531. * <<gem5-trace-internals>>
  8532. * <<gem5-checkpoint-internals>>
  8533. * <<gem5-graphic-mode-internals>>
  8534. ==== gem5 Eclipse configuration
  8535. In order to develop complex C++ software such as gem5, a good IDE setup is fundamental.
  8536. The best setup I've reached is with Eclipse. It is not perfect, and there is a learning curve, but is worth it.
  8537. I recommend the following settings, tested in Eclipse 2019.09, Ubuntu 18.04:
  8538. * fix all missing stdlib headers: https://stackoverflow.com/questions/10373788/how-to-solve-unresolved-inclusion-iostream-in-a-c-file-in-eclipse-cdt/51099533#51099533
  8539. * use spaces instead of tabs: Window, Preferences, Code Style, C/C++, Formatter, New, Edit, Tab Policy, Spaces Only
  8540. * add to the include search path:
  8541. ** ./src/ in the source tree
  8542. ** the ISA specific build directory which contains some self-generated stuff, e.g.: out/gem5/default/build/ARM
  8543. To run and GDB step debug the executable, just copy the full command line from the output `./run`, and configure it into Eclipse.
  8544. ==== gem5 Python C++ interaction
  8545. The interaction uses the Python C extension interface https://docs.python.org/2/extending/extending.html interface through the pybind11 helper library: https://github.com/pybind/pybind11
  8546. The C++ executable both:
  8547. * starts running the Python executable
  8548. * provides Python classes written in C++ for that Python code to use
  8549. An example of this can be found at:
  8550. * https://docs.python.org/2/extending/embedding.html#extending-embedded-python
  8551. * https://github.com/pybind/pybind11/tree/v2.2.3/tests/test_embed
  8552. then gem5 magic `simobject` class adds some crazy stuff on top of it further... is is a mess. in particular, it auto generates `params/` headers. TODO: why is this mess needed at all? pybind11 seems to handle constructor arguments just fine:
  8553. * https://github.com/pybind/pybind11/blob/v2.2.3/tests/test_class.py#L77
  8554. * https://github.com/pybind/pybind11/blob/v2.2.3/tests/test_class.cpp#L41
  8555. Let's study `BadDevice` for example:
  8556. `src/dev/BadDevice.py` defines `devicename`:
  8557. ....
  8558. class BadDevice(BasicPioDevice):
  8559. type = 'BadDevice'
  8560. cxx_header = "dev/baddev.hh"
  8561. devicename = Param.String("Name of device to error on")
  8562. ....
  8563. The object is created in Python for example from `src/dev/alpha/Tsunami.py` as:
  8564. ....
  8565. fb = BadDevice(pio_addr=0x801fc0003d0, devicename='FrameBuffer')
  8566. ....
  8567. Since `BadDevice` has no `+__init__+` method, and neither `BasicPioDevice`, it all just falls through until the SimObject.__init__ constructor.
  8568. This constructor will loop through the inheritance chain and give the Python parameters to the C++ BadDeviceParams class as follows.
  8569. The auto-generated `build/ARM/params/BadDevice.hh` file defines BadDeviceParams in C++:
  8570. ....
  8571. #ifndef __PARAMS__BadDevice__
  8572. #define __PARAMS__BadDevice__
  8573. class BadDevice;
  8574. #include <cstddef>
  8575. #include <string>
  8576. #include "params/BasicPioDevice.hh"
  8577. struct BadDeviceParams
  8578. : public BasicPioDeviceParams
  8579. {
  8580. BadDevice * create();
  8581. std::string devicename;
  8582. };
  8583. #endif // __PARAMS__BadDevice__
  8584. ....
  8585. and `./python/_m5/param_BadDevice.cc` defines the param Python from C++ with pybind11:
  8586. ....
  8587. namespace py = pybind11;
  8588. static void
  8589. module_init(py::module &m_internal)
  8590. {
  8591. py::module m = m_internal.def_submodule("param_BadDevice");
  8592. py::class_<BadDeviceParams, BasicPioDeviceParams, std::unique_ptr<BadDeviceParams, py::nodelete>>(m, "BadDeviceParams")
  8593. .def(py::init<>())
  8594. .def("create", &BadDeviceParams::create)
  8595. .def_readwrite("devicename", &BadDeviceParams::devicename)
  8596. ;
  8597. py::class_<BadDevice, BasicPioDevice, std::unique_ptr<BadDevice, py::nodelete>>(m, "BadDevice")
  8598. ;
  8599. }
  8600. static EmbeddedPyBind embed_obj("BadDevice", module_init, "BasicPioDevice");
  8601. ....
  8602. `src/dev/baddev.hh` then uses the parameters on the constructor:
  8603. ....
  8604. class BadDevice : public BasicPioDevice
  8605. {
  8606. private:
  8607. std::string devname;
  8608. public:
  8609. typedef BadDeviceParams Params;
  8610. protected:
  8611. const Params *
  8612. params() const
  8613. {
  8614. return dynamic_cast<const Params *>(_params);
  8615. }
  8616. public:
  8617. /**
  8618. * Constructor for the Baddev Class.
  8619. * @param p object parameters
  8620. * @param a base address of the write
  8621. */
  8622. BadDevice(Params *p);
  8623. ....
  8624. `src/dev/baddev.cc` then uses the parameter:
  8625. ....
  8626. BadDevice::BadDevice(Params *p)
  8627. : BasicPioDevice(p, 0x10), devname(p->devicename)
  8628. {
  8629. }
  8630. ....
  8631. Tested on gem5 08c79a194d1a3430801c04f37d13216cc9ec1da3.
  8632. ==== gem5 entry point
  8633. The main is at: `src/sim/main.cc`. It calls:
  8634. ....
  8635. ret = initM5Python();
  8636. ....
  8637. src/sim/init.cc:
  8638. ....
  8639. 230 int
  8640. 231 initM5Python()
  8641. 232 {
  8642. 233 EmbeddedPyBind::initAll();
  8643. 234 return EmbeddedPython::initAll();
  8644. 235 }
  8645. ....
  8646. `initAll` basically just initializes the `_m5` Python object, which is used across multiple `.py`.
  8647. Back on `main`:
  8648. ....
  8649. ret = m5Main(argc, argv);
  8650. ....
  8651. which goes to:
  8652. ....
  8653. result = PyRun_String(*command, Py_file_input, dict, dict);
  8654. ....
  8655. with commands looping over:
  8656. ....
  8657. import m5
  8658. m5.main()
  8659. ....
  8660. which leads into:
  8661. ....
  8662. src/python/m5/main.py#main
  8663. ....
  8664. which finally calls your config file like `fs.py` with:
  8665. ....
  8666. filename = sys.argv[0]
  8667. filedata = file(filename, 'r').read()
  8668. filecode = compile(filedata, filename, 'exec')
  8669. [...]
  8670. exec filecode in scope
  8671. ....
  8672. TODO: the file path name appears to be passed as a command line argument to the Python script, but I didn't have the patience to fully understand the details.
  8673. The Python config files then set the entire system up in Python, and finally call `m5.simulate()` to run the actual simulation. This function has a C++ native implementation at:
  8674. ....
  8675. src/sim/simulate.cc
  8676. ....
  8677. and that is where doSimLoop the main event loop, `doSimLoop` gets called and starts kicking off the <<gem5-event-queue>>.
  8678. Tested at gem5 b4879ae5b0b6644e6836b0881e4da05c64a6550d.
  8679. ==== gem5 event queue
  8680. gem5 is an event based simulator, and as such the event queue is of of the crucial elements in the system.
  8681. The gem5 event queue stores one callback event for each future point in time.
  8682. The event queue is implemented in the class `EventQueue` in the file `src/sim/eventq.hh`.
  8683. Not all times need to have an associated event: if a given time has no events, gem5 just skips it and jumps to the next event: the queue is basically a linked list of events.
  8684. Important examples of events include:
  8685. * CPU ticks
  8686. * TODO peripherals and memory
  8687. At the beginning of simulation, gem5 sets up exactly two events:
  8688. * the first CPU cycle
  8689. * one exit event at the end of time which triggers <<gem5-simulate-limit-reached>>
  8690. Tick events then get triggered one by one as simulation progresses, in addition to any other system events.
  8691. The `EventQueue` class has one awesome `dump()` function that prints a human friendly representation of the queue, and can be easily called from GDB. TODO example.
  8692. We can also observe what is going on in the event queue with the `Event` <<gem5-tracing,debug flag>>.
  8693. Event execution is done at `EventQueue::serviceOne()`:
  8694. ....
  8695. Event *exit_event = eventq->serviceOne();
  8696. ....
  8697. This calls the `Event::process` method of the event.
  8698. ===== gem5 event queue AtomicSimpleCPU syscall emulation freestanding example analysis
  8699. Let's now analyze every single event on a minimal <<gem5-syscall-emulation-mode>> in the <<gem5-cpu-types,simplest CPU that we have>>:
  8700. ....
  8701. ./run \
  8702. --arch aarch64 \
  8703. --emulator gem5 \
  8704. --userland userland/arch/aarch64/freestanding/linux/hello.S \
  8705. --trace Event \
  8706. --trace-stdout \
  8707. ;
  8708. ....
  8709. At LKMC a0ea29835b9bacc6aa1cceb24c79d895315991d4 + 1 this outputs:
  8710. ....
  8711. 0: AtomicSimpleCPU tick.wrapped_function_event: EventFunctionWrapped event scheduled @ 0
  8712. **** REAL SIMULATION ****
  8713. 0: Event_70: generic event scheduled @ 0
  8714. info: Entering event queue @ 0. Starting simulation...
  8715. 0: Event_70: generic event rescheduled @ 18446744073709551615
  8716. 0: AtomicSimpleCPU tick.wrapped_function_event: EventFunctionWrapped event rescheduled @ 500
  8717. 500: AtomicSimpleCPU tick.wrapped_function_event: EventFunctionWrapped event rescheduled @ 1000
  8718. 1000: AtomicSimpleCPU tick.wrapped_function_event: EventFunctionWrapped event rescheduled @ 1500
  8719. 1500: AtomicSimpleCPU tick.wrapped_function_event: EventFunctionWrapped event rescheduled @ 2000
  8720. hello
  8721. 2000: AtomicSimpleCPU tick.wrapped_function_event: EventFunctionWrapped event rescheduled @ 2500
  8722. 2500: AtomicSimpleCPU tick.wrapped_function_event: EventFunctionWrapped event rescheduled @ 3000
  8723. 3000: AtomicSimpleCPU tick.wrapped_function_event: EventFunctionWrapped event rescheduled @ 3500
  8724. 3500: Event_71: generic event scheduled @ 3500
  8725. ....
  8726. which we immediately guess means that there is one event per tick when comparing to the `ExecAll` trace:
  8727. ....
  8728. 0: system.cpu A0 T0 : @asm_main_after_prologue : movz x0, #1, #0 : IntAlu : D=0x0000000000000001 flags=(IsInteger)
  8729. 500: system.cpu A0 T0 : @asm_main_after_prologue+4 : adr x1, #28 : IntAlu : D=0x0000000000400098 flags=(IsInteger)
  8730. 1000: system.cpu A0 T0 : @asm_main_after_prologue+8 : ldr w2, #4194464 : MemRead : D=0x0000000000000006 A=0x4000a0 flags=(IsInteger|IsMemRef|IsLoad)
  8731. 1500: system.cpu A0 T0 : @asm_main_after_prologue+12 : movz x8, #64, #0 : IntAlu : D=0x0000000000000040 flags=(IsInteger)
  8732. 2000: system.cpu A0 T0 : @asm_main_after_prologue+16 : svc #0x0 : IntAlu : flags=(IsSerializeAfter|IsNonSpeculative|IsSyscall)
  8733. hello
  8734. 2500: system.cpu A0 T0 : @asm_main_after_prologue+20 : movz x0, #0, #0 : IntAlu : D=0x0000000000000000 flags=(IsInteger)
  8735. 3000: system.cpu A0 T0 : @asm_main_after_prologue+24 : movz x8, #93, #0 : IntAlu : D=0x000000000000005d flags=(IsInteger)
  8736. 3500: system.cpu A0 T0 : @asm_main_after_prologue+28 : svc #0x0 : IntAlu : flags=(IsSerializeAfter|IsNonSpeculative|IsSyscall)
  8737. Exiting @ tick 3500 because exiting with last active thread context
  8738. ....
  8739. On the event trace, we can see:
  8740. * `AtomicSimpleCPU tick.wrapped_function_event: EventFunctionWrapped event scheduled @ 0` schedules a tick event for time `0`, and this leads to the first clock tick
  8741. * `0: Event_70: generic event scheduled @ 0`: schedules the end of time event for time `0`, which is later rescheduled to the actual end of time: `0: Event_70: generic event rescheduled @ 18446744073709551615`
  8742. * at `0: AtomicSimpleCPU tick.wrapped_function_event: EventFunctionWrapped event rescheduled @ 500` the first clock tick must have finished running, and so to represent the next one, it was simply rescheduled for the next time `500`! This is done at the end of `AtomicSimpleCPU::tick()`:
  8743. +
  8744. ....
  8745. if (_status != Idle)
  8746. reschedule(tickEvent, curTick() + latency, true);
  8747. ....
  8748. * at `3500: Event_71: generic event scheduled @ 3500` the exit system call is called and the simulation ends.
  8749. +
  8750. A new event is scheduled for the current time itself. TODO what is this event?
  8751. Let's study the first event. From GDB, it's stack trace is:
  8752. ....
  8753. Trace::OstreamLogger::logMessage() at trace.cc:149 0x5555593b3b1e
  8754. void Trace::Logger::dprintf_flag<char const*, char const*, unsigned long>() at 0x55555949e603
  8755. void Trace::Logger::dprintf<char const*, char const*, unsigned long>() at 0x55555949de58
  8756. Event::trace() at eventq.cc:395 0x55555946d109
  8757. EventQueue::schedule() at eventq_impl.hh:65 0x555557195441
  8758. EventManager::schedule() at eventq.hh:746 0x555557194aa2
  8759. AtomicSimpleCPU::activateContext() at atomic.cc:239 0x555559075531
  8760. SimpleThread::activate() at simple_thread.cc:177 0x555559545a63
  8761. Process::initState() at process.cc:283 0x555559484011
  8762. ArmProcess64::initState() at process.cc:126 0x55555730827a
  8763. ArmLinuxProcess64::initState() at process.cc:1,777 0x5555572d5e5e
  8764. ....
  8765. The interesting call is at `AtomicSimpleCPU::activateContext`:
  8766. ....
  8767. schedule(tickEvent, clockEdge(Cycles(0)));
  8768. ....
  8769. which calls `EventManager::schedule`.
  8770. `AtomicSimpleCPU` is an `EventManager` because `SimObject` inherits from it.
  8771. `tickEvent` is an `EventFunctionWrapper` which contains a `std::function<void(void)> callback;`, and is initialized in the constructor as:
  8772. ....
  8773. tickEvent([this]{ tick(); }, "AtomicSimpleCPU tick",
  8774. false, Event::CPU_Tick_Pri),
  8775. ....
  8776. So that's how the main atomic tick loop works, fully understood!
  8777. The second event has backtrace:
  8778. ....
  8779. Trace::OstreamLogger::logMessage() at trace.cc:149 0x5555593b3b1e
  8780. void Trace::Logger::dprintf_flag<char const*, char const*, unsigned long>() at 0x55555949e603
  8781. void Trace::Logger::dprintf<char const*, char const*, unsigned long>() at 0x55555949de58
  8782. Event::trace() at eventq.cc:395 0x55555946d109
  8783. EventQueue::schedule() at eventq_impl.hh:65 0x555557195441
  8784. BaseGlobalEvent::schedule() at global_event.cc:78 0x55555946d6f1
  8785. GlobalEvent::GlobalEvent() at 0x55555949d177
  8786. GlobalSimLoopExitEvent::GlobalSimLoopExitEvent() at sim_events.cc:61 0x555559474470
  8787. simulate() at simulate.cc:104 0x555559476d6f
  8788. ....
  8789. so gets scheduled automatically at object creation `simulate()` through the `GlobalEvent()` constructor:
  8790. ....
  8791. simulate_limit_event =
  8792. new GlobalSimLoopExitEvent(mainEventQueue[0]->getCurTick(),
  8793. "simulate() limit reached", 0);
  8794. ....
  8795. This event indicates that the simulation should finish by overriding `bool isExitEvent()` which gets checked in the main simulation at `EventQueue::serviceOne`:
  8796. ....
  8797. if (event->isExitEvent()) {
  8798. assert(!event->flags.isSet(Event::Managed) ||
  8799. !event->flags.isSet(Event::IsMainQueue)); // would be silly
  8800. return event;
  8801. ....
  8802. And at long, we can guess without reading the code that `Event_71` is comes from the SE implementation of the exit syscall, so let's just confirm, the trace contains:
  8803. ....
  8804. exitSimLoop() at sim_events.cc:97 0x5555594746e0
  8805. exitImpl() at syscall_emul.cc:215 0x55555948c046
  8806. exitFunc() at syscall_emul.cc:225 0x55555948c147
  8807. SyscallDesc::doSyscall() at syscall_desc.cc:72 0x5555594949b6
  8808. Process::syscall() at process.cc:401 0x555559484717
  8809. SimpleThread::syscall() at 0x555559558059
  8810. ArmISA::SupervisorCall::invoke() at faults.cc:856 0x5555572950d7
  8811. BaseSimpleCPU::advancePC() at base.cc:681 0x555559083133
  8812. AtomicSimpleCPU::tick() at atomic.cc:757 0x55555907834c
  8813. ....
  8814. and `exitSimLoop()` does:
  8815. ....
  8816. new GlobalSimLoopExitEvent(when + simQuantum, message, exit_code, repeat);
  8817. ....
  8818. Tested at b4879ae5b0b6644e6836b0881e4da05c64a6550d.
  8819. ===== gem5 event queue MinorCPU syscall emulation freestanding example analysis
  8820. The events <<gem5-event-queue-atomicsimplecpu-syscall-emulation-freestanding-example-analysis,for the Atomic CPU>> were pretty simple: basically just ticks.
  8821. But as we venture into <<gem5-cpu-types,more complex CPU models>> such as `MinorCPU`, the events get much more complex and interesting.
  8822. TODO: analyze the trace for:
  8823. ....
  8824. ./run \
  8825. --arch aarch64 \
  8826. --emulator gem5 \
  8827. --userland userland/arch/aarch64/freestanding/linux/hello.S \
  8828. --trace Event \
  8829. --trace-stdout \
  8830. -- \
  8831. --cpu-type MinorCPU \
  8832. --caches \
  8833. ;
  8834. ....
  8835. ==== gem5 stats internals
  8836. This describes the internals of the <<gem5-m5out-stats-txt-file>>.
  8837. GDB call stack to `dumpstats`:
  8838. ....
  8839. Stats::pythonDump () at build/ARM/python/pybind11/stats.cc:58
  8840. Stats::StatEvent::process() ()
  8841. GlobalEvent::BarrierEvent::process (this=0x555559fa6a80) at build/ARM/sim/global_event.cc:131
  8842. EventQueue::serviceOne (this=this@entry=0x555558c36080) at build/ARM/sim/eventq.cc:228
  8843. doSimLoop (eventq=0x555558c36080) at build/ARM/sim/simulate.cc:219
  8844. simulate (num_cycles=<optimized out>) at build/ARM/sim/simulate.cc:132
  8845. ....
  8846. `Stats::pythonDump` does:
  8847. ....
  8848. void
  8849. pythonDump()
  8850. {
  8851. py::module m = py::module::import("m5.stats");
  8852. m.attr("dump")();
  8853. }
  8854. ....
  8855. This calls `src/python/m5/stats/__init__.py` in `def dump` does the main dumping
  8856. That function does notably:
  8857. ....
  8858. for output in outputList:
  8859. if output.valid():
  8860. output.begin()
  8861. for stat in stats_list:
  8862. stat.visit(output)
  8863. output.end()
  8864. ....
  8865. `begin` and `end` are defined in C++ and output the header and tail respectively
  8866. ....
  8867. void
  8868. Text::begin()
  8869. {
  8870. ccprintf(*stream, "\n---------- Begin Simulation Statistics ----------\n");
  8871. }
  8872. void
  8873. Text::end()
  8874. {
  8875. ccprintf(*stream, "\n---------- End Simulation Statistics ----------\n");
  8876. stream->flush();
  8877. }
  8878. ....
  8879. `stats_list` contains the stats, and `stat.visit` prints them, `outputList` contains by default just the text output. I don't see any other types of output in gem5, but likely JSON / binary formats could be envisioned.
  8880. Tested in gem5 b4879ae5b0b6644e6836b0881e4da05c64a6550d.
  8881. ==== gem5 code generation
  8882. gem5 uses a ton of code generation, which makes the project horrendous:
  8883. * lots of magic happen on top of pybind11, which is already magic, to more automatically glue the C++ and Python worlds: <<gem5-python-c-interaction>>
  8884. * .isa code which describes most of the instructions
  8885. * <<gem5-ruby-build,Ruby>> for memory systems
  8886. To find the definition of generated code, do a:
  8887. ....
  8888. grep -I -r build/ 'code of interest'
  8889. ....
  8890. where:
  8891. * `-I`: ignore binray file matches on built objects
  8892. * `-r`: ignore symlinks due to <<why-are-all-c-symlinked-into-the-gem5-build-dir>> as explained at https://stackoverflow.com/questions/21738574/how-do-you-exclude-symlinks-in-a-grep
  8893. The code generation exists partly to support insanely generic cross ISA instructions mapping to one compute model, where it might be reasonable.
  8894. But it has been widely overused to insanity. It likely also exists partly because when the project started in 2003 C++ compilers weren't that good, so you couldn't rely on features like templates that much.
  8895. ===== gem5 THE_ISA
  8896. Generated code at: `build/<ISA>/config/the_isa.hh` which contains amongst other lines:
  8897. ....
  8898. #define X86_ISA 8
  8899. enum class Arch {
  8900. X86ISA = X86_ISA
  8901. };
  8902. #define THE_ISA X86_ISA
  8903. ....
  8904. Generation code: `src/SConscript` at `def makeTheISA`.
  8905. Tested on gem5 211869ea950f3cc3116655f06b1d46d3fa39fb3a.
  8906. Bibliography: https://www.mail-archive.com/gem5-users@gem5.org/msg16989.html
  8907. ==== gem5 build system
  8908. ===== gem5 polymorphic ISA includes
  8909. E.g. `src/cpu/decode_cache.hh` includes:
  8910. ....
  8911. #include "arch/isa_traits.hh"
  8912. ....
  8913. which in turn is meant to refer to files of form:
  8914. ....
  8915. src/arch/<isa>/isa_traits.hh
  8916. ....
  8917. What happens is that the build system creates a file:
  8918. ....
  8919. build/ARM/arch/isa_traits.hh
  8920. ....
  8921. which contains just:
  8922. ....
  8923. #include "arch/arm/isa_traits.hh"
  8924. ....
  8925. and puts that in the `-I` include path during build.
  8926. It appears to be possible to deal with it using preprocessor macros, but it is ugly: https://stackoverflow.com/questions/3178946/using-define-to-include-another-file-in-c-c/3179218#3179218
  8927. In addition to the header polymorphism, gem5 also namespaces classes with `TheISA::`, e.g. in `src/cpu/decode_cache.hh`:
  8928. ....
  8929. Value items[TheISA::PageBytes];
  8930. ....
  8931. which is defined at:
  8932. ...
  8933. build/ARM/config/the_isa.hh
  8934. ...
  8935. as:
  8936. ....
  8937. #define TheISA ArmISA
  8938. ....
  8939. and forces already `arm/` specific headers to define their symbols under:
  8940. ....
  8941. namespace ArmISA
  8942. ....
  8943. so I don't see the point of this pattern, why not just us `PageBytes` directly? Looks like a documentation mechanism to indicate that a certain symbol is ISA specific.
  8944. Tested in gem5 2a242c5f59a54bc6b8953f82486f7e6fe0aa9b3d.
  8945. ===== Why are all C++ symlinked into the gem5 build dir?
  8946. Some scons madness.
  8947. https://scons.org/doc/2.4.1/HTML/scons-user.html#idp1378838508 generates hard links by default.
  8948. Then the a5bc2291391b0497fdc60fdc960e07bcecebfb8f SConstruct use symlinks in a futile attempt to make things better for editors or build systems from the past century.
  8949. It was not possible to disable the symlinks automatically for the entire project when I last asked: https://stackoverflow.com/questions/53656787/how-to-set-disable-duplicate-0-for-all-scons-build-variants-without-repeating-th
  8950. The horrendous downsides of this are:
  8951. * when <<debug-the-emulator,debugging the emulator>>, it shows you directories inside the build directory rather than in the source tree
  8952. * it is harder to separate which files are <<gem5-code-generation,generated>> and which are in-tree when grepping for code generated definitions
  8953. == Buildroot
  8954. === Introduction to Buildroot
  8955. https://en.wikipedia.org/wiki/Buildroot[Buildroot] is a set of Make scripts that download and compile from source compatible versions of:
  8956. * GCC
  8957. * Linux kernel
  8958. * C standard library: Buildroot supports several implementations, see: xref:libc-choice[xrefstyle=full]
  8959. * https://en.wikipedia.org/wiki/BusyBox[BusyBox]: provides the shell and basic command line utilities
  8960. It therefore produces a pristine, blob-less, debuggable setup, where all moving parts are configured to work perfectly together.
  8961. Perhaps the awesomeness of Buildroot only sinks in once you notice that all it takes is 4 commands as explained at xref:buildroot-hello-world[xrefstyle=full].
  8962. This repo basically wraps around that, and tries to make everything even more awesome for kernel developers.
  8963. The downsides of Buildroot are:
  8964. * the first build takes a while, but it is well worth it
  8965. * the selection of software packages is relatively limited if compared to Debian, e.g. no Java or Python package in guest out of the box.
  8966. +
  8967. In theory, any software can be packaged, and the Buildroot side is easy.
  8968. +
  8969. The hard part is dealing with crappy third party build systems and huge dependency chains.
  8970. === Custom Buildroot configs
  8971. We provide the following mechanisms:
  8972. * `./build-buildroot --config-fragment data/br2`: append the Buildroot configuration file `data/br2` to a single build. Must be passed every time you run `./build`. The format is the same as link:buildroot_config/default[].
  8973. * `./build-buildroot --config 'BR2_SOME_OPTION="myval"'`: append a single option to a single build.
  8974. For example, if you decide to <<enable-buildroot-compiler-optimizations>> after an initial build is finished, you must <<clean-the-build>> and rebuild:
  8975. ....
  8976. ./build-buildroot \
  8977. --config 'BR2_OPTIMIZE_3=y' \
  8978. --config 'BR2_PACKAGE_SAMPLE_PACKAGE=y' \
  8979. --
  8980. sample_package-dirclean \
  8981. sample_package-reconfigure \
  8982. ;
  8983. ....
  8984. as explained at: https://buildroot.org/downloads/manual/manual.html#rebuild-pkg
  8985. The clean is necessary because the source files didn't change, so `make` would just check the timestamps and not build anything.
  8986. You will then likely want to make those more permanent as explained at: xref:default-command-line-arguments[xrefstyle=full].
  8987. ==== Enable Buildroot compiler optimizations
  8988. If you are benchmarking compiled programs instead of hand written assembly, remember that we configure Buildroot to disable optimizations by default with:
  8989. ....
  8990. BR2_OPTIMIZE_0=y
  8991. ....
  8992. to improve the debugging experience.
  8993. You will likely want to change that to:
  8994. ....
  8995. BR2_OPTIMIZE_3=y
  8996. ....
  8997. Our link:buildroot_packages/sample_package[] package correctly forwards the Buildroot options to the build with `$(TARGET_CONFIGURE_OPTS)`, so you don't have to do any extra work.
  8998. Don't forget to do that if you are <<add-new-buildroot-packages,adding a new package>> with your own build system.
  8999. Then, you have two choices:
  9000. * if you already have a full `-O0` build, you can choose to rebuild just your package of interest to save some time as described at: xref:custom-buildroot-configs[xrefstyle=full]
  9001. +
  9002. ....
  9003. ./build-buildroot \
  9004. --config 'BR2_OPTIMIZE_3=y' \
  9005. --config 'BR2_PACKAGE_SAMPLE_PACKAGE=y' \
  9006. -- \
  9007. sample_package-dirclean \
  9008. sample_package-reconfigure \
  9009. ;
  9010. ....
  9011. +
  9012. However, this approach might not be representative since calls to an unoptimized libc and other libraries will have a negative performance impact.
  9013. +
  9014. Maybe you can get away with rebuilding libc, but I'm not sure that it will work properly.
  9015. +
  9016. Kernel-wise it should be fine though as mentioned at: xref:kernel-o0[xrefstyle=full]
  9017. * <<clean-the-build,clean the build>> and rebuild from scratch:
  9018. +
  9019. ....
  9020. mv out out~
  9021. ./build-buildroot --config 'BR2_OPTIMIZE_3=y'
  9022. ....
  9023. === Find Buildroot options with make menuconfig
  9024. `make menuconfig` is a convenient way to find Buildroot configurations:
  9025. ....
  9026. cd "$(./getvar buildroot_build_dir)"
  9027. make menuconfig
  9028. ....
  9029. Hit `/` and search for the settings.
  9030. Save and quit.
  9031. ....
  9032. diff -u .config.olg .config
  9033. ....
  9034. Then copy and paste the diff additions to link:buildroot_config/default[] to make them permanent.
  9035. === Change user
  9036. At startup, we login automatically as the `root` user.
  9037. If you want to switch to another user to test some permissions, we have already created an `user0` user through the link:user_table[] file, and you can just login as that user with:
  9038. ....
  9039. login user0
  9040. ....
  9041. and password:
  9042. ....
  9043. a
  9044. ....
  9045. Then test that the user changed with:
  9046. ....
  9047. id
  9048. ....
  9049. which gives:
  9050. ....
  9051. uid=1000(user0) gid=1000(user0) groups=1000(user0)
  9052. ....
  9053. ==== Login as a non-root user without password
  9054. Replace on `inittab`:
  9055. ....
  9056. ::respawn:-/bin/sh
  9057. ....
  9058. with:
  9059. ....
  9060. ::respawn:-/bin/login -f user0
  9061. ....
  9062. `-f` forces login without asking for the password.
  9063. === Add new Buildroot packages
  9064. First, see if you can't get away without actually adding a new package, for example:
  9065. * if you have a standalone C file with no dependencies besides the C standard library to be compiled with GCC, just add a new file under link:buildroot_packages/sample_package[] and you are done
  9066. * if you have a dependency on a library, first check if Buildroot doesn't have a package for it already with `ls buildroot/package`. If yes, just enable that package as explained at: xref:custom-buildroot-configs[xrefstyle=full]
  9067. If none of those methods are flexible enough for you, you can just fork or hack up link:buildroot_packages/sample_package[] the sample package to do what you want.
  9068. For how to use that package, see: xref:buildroot_packages-directory[xrefstyle=full].
  9069. Then iterate trying to do what you want and reading the manual until it works: https://buildroot.org/downloads/manual/manual.html
  9070. === Remove Buildroot packages
  9071. Once you've built a package in to the image, there is no easy way to remove it.
  9072. Documented at: https://github.com/buildroot/buildroot/blob/2017.08/docs/manual/rebuilding-packages.txt#L90[]
  9073. Also mentioned at: https://stackoverflow.com/questions/47320800/how-to-clean-only-target-in-buildroot
  9074. See this for a sample manual workaround: xref:parsec-uninstall[xrefstyle=full].
  9075. === BR2_TARGET_ROOTFS_EXT2_SIZE
  9076. When adding new large package to the Buildroot root filesystem, it may fail with the message:
  9077. ....
  9078. Maybe you need to increase the filesystem size (BR2_TARGET_ROOTFS_EXT2_SIZE)
  9079. ....
  9080. The solution is to simply add:
  9081. ....
  9082. ./build-buildroot --config 'BR2_TARGET_ROOTFS_EXT2_SIZE="512M"'
  9083. ....
  9084. where 512Mb is "large enough".
  9085. Note that dots cannot be used as in `1.5G`, so just use Megs as in `1500M` instead.
  9086. Unfortunately, TODO we don't have a perfect way to find the right value for `BR2_TARGET_ROOTFS_EXT2_SIZE`. One good heuristic is:
  9087. ....
  9088. du -hsx "$(./getvar --arch arm buildroot_target_dir)"
  9089. ....
  9090. Some promising ways to overcome this problem include:
  9091. * <<squashfs>>
  9092. TODO benchmark: would gem5 suffer a considerable disk read performance hit due to decompressing SquashFS?
  9093. * libguestfs: https://serverfault.com/questions/246835/convert-directory-to-qemu-kvm-virtual-disk-image/916697#916697[], in particular http://libguestfs.org/guestfish.1.html#vfs-minimum-size[`vfs-minimum-size`]
  9094. * use methods described at: xref:gem5-restore-new-script[xrefstyle=full] instead of putting builds on the root filesystem
  9095. Bibliography: https://stackoverflow.com/questions/49211241/is-there-a-way-to-automatically-detect-the-minimum-required-br2-target-rootfs-ex
  9096. ==== SquashFS
  9097. https://en.wikipedia.org/wiki/SquashFS[SquashFS] creation with `mksquashfs` does not take fixed sizes, and I have successfully booted from it, but it is readonly, which is unacceptable.
  9098. But then we could mount https://wiki.debian.org/ramfs[ramfs] on top of it with <<overlayfs>> to make it writable, but my attempts failed exactly as mentioned at <<overlayfs>>.
  9099. This is the exact unanswered question: https://unix.stackexchange.com/questions/343484/mounting-squashfs-image-with-read-write-overlay-for-rootfs
  9100. [[rpath]]
  9101. === Buildroot rebuild is slow when the root filesystem is large
  9102. Buildroot is not designed for large root filesystem images, and the rebuild becomes very slow when we add a large package to it.
  9103. This is due mainly to the `pkg-generic` `GLOBAL_INSTRUMENTATION_HOOKS` sanitation which go over the entire tree doing complex operations... I no like, in particular `check_bin_arch` and `check_host_rpath`
  9104. We have applied https://github.com/cirosantilli/buildroot/commit/983fe7910a73923a4331e7d576a1e93841d53812[983fe7910a73923a4331e7d576a1e93841d53812] to out Buildroot fork which removes part of the pain by not running:
  9105. ....
  9106. >>> Sanitizing RPATH in target tree
  9107. ....
  9108. which contributed to a large part of the slowness.
  9109. Test how Buildroot deals with many files with:
  9110. ....
  9111. ./build-buildroot \
  9112. --config 'BR2_PACKAGE_LKMC_MANY_FILES=y' \
  9113. -- \
  9114. lkmc_many_files-reconfigure \
  9115. |& \
  9116. ts -i '%.s' \
  9117. ;
  9118. ./build-buildroot |& ts -i '%.s'
  9119. ....
  9120. and notice how the second build, which does not rebuilt the package at all, still gets stuck in the `RPATH` check forever without our Buildroot patch.
  9121. === Report upstream bugs
  9122. When asking for help on upstream repositories outside of this repository, you will need to provide the commands that you are running in detail without referencing our scripts.
  9123. For example, QEMU developers will only want to see the final QEMU command that you are running.
  9124. For the configure and build, search for the `Building` and `Configuring` parts of the build log, then try to strip down all Buildroot related paths, to keep only options that seem to matter.
  9125. We make that easy by building commands as strings, and then echoing them before evaling.
  9126. So for example when you run:
  9127. ....
  9128. ./run --arch arm
  9129. ....
  9130. the very first stdout output of that script is the actual QEMU command that is being run.
  9131. The command is also saved to a file for convenience:
  9132. ....
  9133. cat "$(./getvar --arch arm run_cmd_file)"
  9134. ....
  9135. which you can manually modify and execute during your experiments later:
  9136. ....
  9137. vim "$(./getvar --arch arm run_cmd_file)"
  9138. ./"$(./getvar --arch arm run_cmd_file)"
  9139. ....
  9140. If you are not already on the master of the given component, you can do that neatly with <<build-variants>>.
  9141. E.g., to check if a QEMU bug is still present on `master`, you can do as explained at <<qemu-build-variants>>:
  9142. ....
  9143. git -C "$(./getvar qemu_source_dir)" checkout master
  9144. ./build-qemu --clean --qemu-build-id master
  9145. ./build-qemu --qemu-build-id master
  9146. git -C "$(./getvar qemu_source_dir)" checkout -
  9147. ./run --qemu-build-id master
  9148. ....
  9149. Then, you will also want to do a <<bisection>> to pinpoint the exact commit to blame, and CC that developer.
  9150. Finally, give the images you used save upstream developers' time as shown at: xref:release-zip[xrefstyle=full].
  9151. For Buildroot problems, you should wither provide the config you have:
  9152. ....
  9153. ./getvar buildroot_config_file
  9154. ....
  9155. or try to reproduce with a minimal config, see: https://github.com/cirosantilli/buildroot/tree/in-tree-package-master
  9156. === libc choice
  9157. Buildroot supports several libc implementations, including:
  9158. * https://en.wikipedia.org/wiki/GNU_C_Library[glibc]
  9159. * https://en.wikipedia.org/wiki/UClibc[uClibc]
  9160. We currently use glibc, which is selected by:
  9161. ....
  9162. BR2_TOOLCHAIN_BUILDROOT_GLIBC=y
  9163. ....
  9164. Ideally we would like to use uClibc, as it is more minimal and easier to understand, but unfortunately there are some very few packages that use some weird glibc extension that uClibc hasn't implemented yet, e.g.:
  9165. * <<selinux>>. Trivial unmerged fix at: http://lists.busybox.net/pipermail/buildroot/2017-July/197793.html just missing the uClibc option to expose `fts.h`...
  9166. * <<stress>>
  9167. The full list of unsupported packages can be found by grepping the Buildroot source:
  9168. ....
  9169. git -C "$(./getvar buildroot_source_dir)" grep 'depends on BR2_TOOLCHAIN_USES_GLIBC'
  9170. ....
  9171. One "downside" of glibc is that it exercises much more kernel functionality on its more bloated pre-main init, which breaks user mode C hello worlds more often, see: xref:user-mode-simulation-with-glibc[xrefstyle=full]. I quote "downside" because glibc is actually exposing emulator bugs which we should actually go and fix.
  9172. === Buildroot hello world
  9173. This repo doesn't do much more other than setting a bunch of Buildroot configurations and building it.
  9174. The minimal work you have to do to get QEMU to boot Buildroot from scratch is tiny if, about 4 commands!
  9175. Here are some good working commands for several ISAs:
  9176. * x86_64 https://unix.stackexchange.com/questions/44062/how-to-use-qemu-to-run-build-root-linux-images/543075#543075
  9177. ** x86_64 X11 https://unix.stackexchange.com/questions/70931/how-to-install-x11-on-my-own-linux-buildroot-system/306116#306116 Also mentioned at: xref:x11[xrefstyle=full].
  9178. * aarch64 https://stackoverflow.com/questions/47557262/how-to-download-the-torvalds-linux-kernel-master-recompile-it-and-boot-it-wi/49349237#49349237
  9179. ** aarch64 U-Boot: https://stackoverflow.com/questions/58028789/how-to-boot-linux-aarch64-with-u-boot-with-buildroot-on-qemu Also mentioned at: xref:u-boot[xrefsultye=full].
  9180. * arm https://stackoverflow.com/questions/38320066/how-to-run-linux-on-a-qemu-arm-versatile-machine/44099299#44099299
  9181. * PPC <https://stackoverflow.com/questions/48021127/build-powerpc-kernel-and-boot-powerpc-kernel-on-qemu/49349262#49349262> just work commands for PPC, comment on how to replace kernel
  9182. These can come in handy if you want to debug something in Buildroot itself and possibly report an upstream bug.
  9183. === Update the toolchain
  9184. Users of this repo will often want to update the compilation toolchain to the latest version to get fresh new features like new ISA instructions.
  9185. Because the toolchain is so complex and tightly knitted with the rest of the system, this is more of an art than a science.
  9186. However, it is not something to be feared, and you will get there without help in most cases.
  9187. In this section we cover the most common cases.
  9188. ==== Update GCC: GCC supported by Buildroot
  9189. This is of course the simplest case.
  9190. You can quickly determine all the GCC versions supported by Buildroot by looking at:
  9191. ....
  9192. submodules/buildroot/package/gcc/Config.in.host
  9193. ....
  9194. For example, in Buildroot 2018.08, which was used at LKMC 5d10529c10ad8a4777b0bac1543320df0c89a1ce, the default toolchain was 7.3.0, and the latest supported one was 8.2.0.
  9195. To just upgrade the toolchain to 8.2.0, and rebuild some userland executables to later run them, we could do:
  9196. ....
  9197. cd submodules/gcc
  9198. git fetch up
  9199. git checkout -b lkmc-gcc-8_2_0-release gcc-8_2_0-release
  9200. git am ../buildroot/package/gcc/8.2.0/*
  9201. cd ../..
  9202. ./build-buildroot \
  9203. --arch aarch64 \
  9204. --buildroot-build-id gcc-8-2 \
  9205. --config 'BR2_GCC_VERSION_8_X=y' \
  9206. --config 'BR2_GCC_VERSION="8.2.0"' \
  9207. --no-all \
  9208. -- \
  9209. toolchain \
  9210. ;
  9211. ./build-userland \
  9212. --arch aarch64 \
  9213. --buildroot-build-id gcc-8-2 \
  9214. --out-rootfs-overlay-dir-prefix gcc-8-2 \
  9215. --userland-build-id gcc-8-2 \
  9216. ;
  9217. ./build-buildroot --arch aarch64
  9218. ....
  9219. where the `toolchain` Buildroot target builds only Buildroot: https://stackoverflow.com/questions/44521150/buildroot-install-and-build-the-toolchain-only
  9220. Note that this setup did not overwrite any of our default Buildroot due to careful namespacing with our `gcc-8-2` prefix!
  9221. Now you can either run the executables on <<user-mode-simulation>> with:
  9222. ....
  9223. ./run --arch aarch64 --userland userland/c/hello.c --userland-build-id gcc-8-2
  9224. ....
  9225. or in full system with:
  9226. ....
  9227. ./run --arch aarch64 --eval-after './gcc-8-2/c/hello.out'
  9228. ....
  9229. where the `gcc-8-2` prefix was added by `--out-rootfs-overlay-dir-prefix`.
  9230. <<arm-sve>> support was only added to GCC 8 and can be enabled with the flag: `-march=armv8.2-a+sve`.
  9231. We already even had a C SVE test in-tree, but it was disabled because the old toolchain does not support it.
  9232. So once the new GCC 8 toolchain was built, we can first enable that test by editing the <<path-properties>> file to not skip C SVE tests anymore:
  9233. ....
  9234. #os.path.splitext(self.path_components[-1])[1] == '.c' and self['arm_sve']
  9235. ....
  9236. and then rebuild run one of the experiments from <<change-arm-sve-vector-length-in-emulators>>:
  9237. ....
  9238. ./build-userland \
  9239. --arch aarch64 \
  9240. --buildroot-build-id gcc-8-2 \
  9241. --force-rebuild \
  9242. --march=armv8.2-a+sve \
  9243. --out-rootfs-overlay-dir-prefix gcc-8-2 \
  9244. --static \
  9245. --userland-build-id gcc-8-2 \
  9246. ;
  9247. ./run \
  9248. --arch aarch64 \
  9249. --userland userland/arch/aarch64/inline_asm/sve_addvl.c \
  9250. --userland-build-id gcc-8-2 \
  9251. --static \
  9252. --gem5-worktree master \
  9253. -- \
  9254. --param 'system.cpu[:].isa[:].sve_vl_se = 4' \
  9255. ....
  9256. Bibliography:
  9257. * https://github.com/cirosantilli/linux-kernel-module-cheat/issues/87
  9258. ==== Update GCC: GCC not supported by Buildroot
  9259. Now it gets fun, but well, guess what, we will try to do the same as xref:update-gcc-gcc-supported-by-buildroot[xrefstyle=full] but:
  9260. * pick the Buildroot version that comes closest to the GCC you want
  9261. * if any `git am` patches don't apply, skip them
  9262. Now, if things fail, you can try:
  9263. * if the GCC version is supported by a newer Buildroot version:
  9264. ** quick and dirty: see what they are doing differently there, and patch it in here
  9265. ** golden star: upgrade our default Buildroot, <<test-this-repo,test it well>>, and send a pull request!
  9266. * otherwise: OK, go and patch Buildroot, time to become a Buildroot dev
  9267. Known setups:
  9268. * Buildroot 2018.08:
  9269. ** GCC 8.3.0: OK
  9270. ** GCC 9.2.0: KO https://github.com/cirosantilli/linux-kernel-module-cheat/issues/97
  9271. == Userland content
  9272. This section documents our test and educational userland content, such as <<c>>, <<cpp>> and <<posix>> examples, present mostly under link:userland/[].
  9273. Getting started at: xref:userland-setup[xrefstyle=full]
  9274. Userland assembly content is located at: xref:userland-assembly[xrefstyle=full]. It was split from this section basically because we were hitting the HTML `h6` limit, stupid web :-)
  9275. This content makes up the bulk of the link:userland/[] directory.
  9276. The quickest way to run the arch agnostic examples, which comprise the majority of the examples, is natively as shown at: xref:userland-setup-getting-started-natively[xrefstyle=full]
  9277. This section was originally moved in here from: https://github.com/cirosantilli/cpp-cheat
  9278. === C
  9279. Programs under link:userland/c/[] are examples of https://en.wikipedia.org/wiki/ANSI_C[ANSI C] programming:
  9280. * link:userland/c/hello.c[]
  9281. * `main` and environment
  9282. ** link:userland/c/return0.c[]
  9283. ** link:userland/c/return1.c[]
  9284. ** link:userland/c/return2.c[]
  9285. ** link:userland/c/exit0.c[]
  9286. ** link:userland/c/exit1.c[]
  9287. ** link:userland/c/exit2.c[]
  9288. ** link:userland/c/command_line_arguments.c[]: print one command line argument per line using `argc` and `argv`.
  9289. +
  9290. Good sanity check for user mode: <<qemu-user-mode-getting-started>>
  9291. * Standard library
  9292. ** `assert.h`
  9293. *** link:userland/c/assert_fail.c[]
  9294. ** `stdlib.h`
  9295. *** exit
  9296. **** link:userland/c/abort.c[]
  9297. ** `stdio.h`
  9298. *** link:userland/c/getchar.c[]
  9299. *** link:userland/c/snprintf.c[]
  9300. *** link:userland/c/stderr.c[]
  9301. *** File IO
  9302. **** link:userland/c/file_write_read.c[]
  9303. **** link:userland/linux/open_o_tmpfile.c[]: https://stackoverflow.com/questions/4508998/what-is-an-anonymous-inode-in-linux/44388030#44388030
  9304. * Fun
  9305. ** link:userland/c/loop.c[]
  9306. ==== malloc
  9307. Allocate memory! Vs using the stack: https://stackoverflow.com/questions/4584089/what-is-the-function-of-the-push-pop-instructions-used-on-registers-in-x86-ass/33583134#33583134
  9308. link:userland/c/malloc.c[]: `malloc` hello world: allocate two ints and use them.
  9309. Linux 5.1 / glibc 2.29 implements it with the <<mmap,`mmap` system call>>.
  9310. `malloc` leads to the infinite joys of <<memory-leaks>>.
  9311. ===== malloc implementation
  9312. TODO: the exact answer is going to be hard.
  9313. But at least let's verify that large `malloc` calls use the `mmap` syscall with:
  9314. ....
  9315. strace -x ./c/malloc_size.out 0x100000 2>&1 | grep mmap | tail -n 1
  9316. strace -x ./c/malloc_size.out 0x200000 2>&1 | grep mmap | tail -n 1
  9317. strace -x ./c/malloc_size.out 0x400000 2>&1 | grep mmap | tail -n 1
  9318. ....
  9319. Source: link:userland/c/malloc_size.c[].
  9320. From this we sese that the last `mmap` calls are:
  9321. ....
  9322. mmap(NULL, 1052672, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7ffff7ef2000
  9323. mmap(NULL, 2101248, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7ffff7271000
  9324. mmap(NULL, 4198400, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7ffff7071000
  9325. ....
  9326. which in hex are:
  9327. ....
  9328. printf '%x\n' 1052672
  9329. # 101000
  9330. printf '%x\n' 2101248
  9331. # 201000
  9332. printf '%x\n' 4198400
  9333. # 401000
  9334. ....
  9335. so we figured out the pattern: those 1, 2, and 4 MiB mallocs are mmaping N + 0x1000 bytes.
  9336. ===== malloc maximum size
  9337. General overview at: https://stackoverflow.com/questions/2798330/maximum-memory-which-malloc-can-allocate
  9338. See also:
  9339. * https://stackoverflow.com/questions/13127855/what-is-the-size-limit-for-mmap
  9340. * https://stackoverflow.com/questions/7504139/malloc-allocates-memory-more-than-ram
  9341. From <<memory-size>> and `./run --help`, we see that at we set the emulator memory by default to 256MB. Let's see how much Linux allows us to malloc.
  9342. Then from <<malloc-implementation>> we see that `malloc` is implemented with `mmap`. Therefore, let's simplify the problam and try to understand what is the larges mmap we can do first. This way we can ignore how glibc implements malloc for now.
  9343. In Linux, the maximum `mmap` value in controlled by:
  9344. ....
  9345. cat /proc/sys/vm/overcommit_memory
  9346. ....
  9347. which is documented in `man proc`.
  9348. The default value is `0`, which I can't find a precise documentation for. `2` is precisly documented but I'm lazy to do all calculations. So let's just verify `0` vs `1` by trying to `mmap` 1GiB of memory:
  9349. ....
  9350. echo 0 > /proc/sys/vm/overcommit_memory
  9351. ./linux/mmap_anonymous.out 0x40000000
  9352. echo 1 > /proc/sys/vm/overcommit_memory
  9353. ./linux/mmap_anonymous.out 0x40000000
  9354. ....
  9355. Source: link:userland/linux/mmap_anonymous.c[]
  9356. With `0`, we get a failure:
  9357. ....
  9358. mmap: Cannot allocate memory
  9359. ....
  9360. but with `1` the allocation works.
  9361. We are allowed to allocate more than the actual memory + swap because the memory is only virtual, as explained at: https://stackoverflow.com/questions/7880784/what-is-rss-and-vsz-in-linux-memory-management/57453334#57453334
  9362. If we start using the pages, the OOM killer would sooner or later step in and kill our process: <<linux-out-of-memory-killer>>.
  9363. ====== Linux out-of-memory killer
  9364. We can observe the OOM in LKMC 1e969e832f66cb5a72d12d57c53fb09e9721d589 which defaults to 256MiB of memory with:
  9365. ....
  9366. echo 1 > /proc/sys/vm/overcommit_memory
  9367. ./linux/mmap_anonymous_touch.out 0x40000000 0x8000000
  9368. ....
  9369. This first allows memory overcommit so to that the program can mmap 1GiB, 4x more than total RAM without failing as mentioned at <<malloc-maximum-size>>.
  9370. It then walks over every page and writes a value in it to ensure that it is used.
  9371. A <<fork-bomb>> is another example that can trigger the OOM killer.
  9372. Algorithm used by the OOM: https://unix.stackexchange.com/questions/153585/how-does-the-oom-killer-decide-which-process-to-kill-first
  9373. ==== C multithreading
  9374. Added in C11!
  9375. * link:userland/c/atomic.c[]: `atomic_int` and `thrd_create`
  9376. Bibliography:
  9377. * https://stackoverflow.com/questions/3908031/how-to-multithread-c-code/52453354#52453354
  9378. ==== GCC C extensions
  9379. ===== C empty struct
  9380. Example: link:userland/gcc/empty_struct.c[]
  9381. Documentation: https://gcc.gnu.org/onlinedocs/gcc-8.2.0/gcc/Empty-Structures.html#Empty-Structures
  9382. Question: https://stackoverflow.com/questions/24685399/c-empty-struct-what-does-this-mean-do
  9383. ===== OpenMP
  9384. GCC implements the <<OpenMP>> threading implementation: https://stackoverflow.com/questions/3949901/pthreads-vs-openmp
  9385. Example: link:userland/gcc/openmp.c[]
  9386. The implementation is built into GCC itself. It is enabled at GCC compile time by `BR2_GCC_ENABLE_OPENMP=y` on Buildroot, and at program compile time by `-fopenmp`.
  9387. It seems to be easier to use for compute parallelism and more language agnostic than POSIX threads.
  9388. pthreads are more versatile though and allow for a superset of OpenMP.
  9389. The implementation lives under `libgomp` in the GCC tree, and is documented at: https://gcc.gnu.org/onlinedocs/libgomp/
  9390. `strace` shows that OpenMP makes `clone()` syscalls in Linux. TODO: does it actually call `pthread_` functions, or does it make syscalls directly? Or in other words, can it work on <<freestanding-programs>>? A quick grep shows many references to pthreads.
  9391. [[cpp]]
  9392. === C++
  9393. Programs under link:userland/cpp/[] are examples of https://en.wikipedia.org/wiki/C%2B%2B#Standardization[ISO C] programming.
  9394. * link:userland/cpp/empty.cpp[]
  9395. * link:userland/cpp/hello.cpp[]
  9396. * templates
  9397. ** link:userland/cpp/template.cpp[]: basic example
  9398. ** link:userland/cpp/template_class_with_static_member.cpp[]: https://stackoverflow.com/questions/3229883/static-member-initialization-in-a-class-template
  9399. ** link:userland/cpp/if_constexpr.cpp[]: C++17 `if constexpr`
  9400. * iostream
  9401. ** link:userland/cpp/copyfmt.cpp[]: `std::copyfmt` restores stream state, see also: https://stackoverflow.com/questions/12560291/set-back-default-floating-point-print-precision-in-c/53673686#53673686
  9402. * fstream
  9403. ** link:userland/cpp/file_write_read.cpp[]
  9404. ** link:userland/cpp/temporary_directory.cpp[]: illustrates `std::filesystem::temp_directory_path` and answers https://stackoverflow.com/questions/3379956/how-to-create-a-temporary-directory-in-c/58454949#58454949
  9405. * random
  9406. ** link:userland/cpp/random.cpp[]
  9407. [[cpp-multithreading]]
  9408. ==== C++ multithreading
  9409. * https://en.cppreference.com/w/cpp/header/thread[`<thread>`]
  9410. ** link:userland/cpp/count.cpp[] Exemplifies: `std::this_thread::sleep_for`
  9411. ** link:userland/cpp/thread_hardware_concurrency.cpp[] `std::thread::hardware_concurrency`
  9412. ** link:userland/cpp/thread_get_id.cpp[] `std::thread::get_id`
  9413. ** link:userland/cpp/thread_return_value.cpp[]: how to return a value from a thread
  9414. * https://en.cppreference.com/w/cpp/header/atomic[`<atomic>`]: <<cpp17>> 32 "Atomic operations library"
  9415. ** link:userland/cpp/atomic.cpp[]
  9416. [[cpp-standards]]
  9417. ==== C++ standards
  9418. Like for C, you have to pay for the standards... insane. So we just use the closest free drafts instead.
  9419. https://stackoverflow.com/questions/81656/where-do-i-find-the-current-c-or-c-standard-documents
  9420. [[cpp17]]
  9421. ===== C++17 N4659 standards draft
  9422. http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/n4659.pdf
  9423. === POSIX
  9424. Programs under link:userland/posix/[] are examples of POSIX C programming.
  9425. These links provide a clear overview of what POSIX is:
  9426. * https://stackoverflow.com/questions/1780599/what-is-the-meaning-of-posix/31865755#31865755
  9427. * https://unix.stackexchange.com/questions/11983/what-exactly-is-posix/220877#220877
  9428. ==== unistd.h
  9429. * link:userland/posix/count.c[] illustrates `sleep()`
  9430. * link:userland/posix/count_to.c[] minor variation of link:userland/posix/count.c[]
  9431. ==== fork
  9432. POSIX' multiprocess API. Contrast with <<pthreads>> which are for threads.
  9433. Example: link:userland/posix/fork.c[]
  9434. Sample <<userland-setup-getting-started-natively,native userland output>> on Ubuntu 19.04 at 762cd8d601b7db06aa289c0fca7b40696299a868 + 1:
  9435. ....
  9436. before fork before fork pid=13038 ppid=4805
  9437. after fork after fork pid=13038 ppid=4805
  9438. after (pid == 0) after (pid == 0) pid=13038 ppid=4805
  9439. after fork after fork pid=13039 ppid=13038
  9440. inside (pid == 0) inside (pid == 0) pid=13039 ppid=13038
  9441. after wait after wait pid=13038 ppid=4805
  9442. fork() return = 13039
  9443. ....
  9444. Read the source comments and understand everything that is going on!
  9445. ===== Fork bomb
  9446. https://en.wikipedia.org/wiki/Fork_bomb
  9447. DANGER! Only run this on your host if you have saved all data you care about! Better run it inside an emulator! QEMU v4.0.0 <<user-mode-simulation,user mode>> is not safe enough either because it is very native does not limit guest memory, so it will still blow up the host!
  9448. So without further ado, let's rock with either:
  9449. ....
  9450. ./run --eval-after './posix/fork_bomb.out danger'
  9451. ./run --eval-after './fork_bomb.sh danger'
  9452. ....
  9453. Sources:
  9454. * link:userland/posix/fork_bomb.c[]
  9455. * link:rootfs_overlay/lkmc/fork_bomb.sh[]
  9456. Outcome for the C version on LKMC 762cd8d601b7db06aa289c0fca7b40696299a868 + 1: after a few seconds of an unresponsive shell, we get a visit form the <<linux-out-of-memory-killer>>, and the system is restored!
  9457. ==== pthreads
  9458. POSIX' multithreading API. Contrast with <<fork>> which is for processes.
  9459. This was for a looong time the only "portable" multithreading alternative, until <<cpp-multithreading,C++11 finally added threads>>, thus also extending the portability to Windows.
  9460. * link:userland/posix/pthread_count.c[]
  9461. * link:userland/posix/pthread_deadlock.c[]
  9462. * link:userland/posix/pthread_self.c[]
  9463. ==== sysconf
  9464. https://pubs.opengroup.org/onlinepubs/9699919799/functions/sysconf.html
  9465. Examples:
  9466. * link:userland/posix/sysconf.c[]
  9467. * link:userland/linux/sysconf.c[] showcases Linux extensions to POSIX
  9468. Get lots of info on the system configuration.
  9469. The constants can also be viewed accessed on my Ubuntu 18.04 host with:
  9470. ....
  9471. getconf -a
  9472. ....
  9473. `getconf` is also specified by POSIX at: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/getconf.html but not the `-a` option which shows all configurations.
  9474. ==== mmap
  9475. The mmap system call allows advanced memory operations.
  9476. mmap is notably used to implement the <<malloc,malloc ANSI C>> function, replacing the previously used break system call.
  9477. Linux adds has several POSIX extension flags to it.
  9478. [[mmap-map-anonymous]]
  9479. ===== mmap MAP_ANONYMOUS
  9480. Basic `mmap` example, do the same as link:userland/c/malloc.c[], but with `mmap`.
  9481. Example: link:userland/linux/mmap_anonymous.c[]
  9482. In POSIX 7 mmap always maps to a file.
  9483. If we add the MAP_ANONYMOUS Linux extension however, this is not required, and mmap can be used to allocate memory like malloc.
  9484. Answers: https://stackoverflow.com/questions/4779188/how-to-use-mmap-to-allocate-a-memory-in-heap
  9485. ===== mmap file
  9486. Memory mapped file example: link:userland/posix/mmap_file.c[]
  9487. The example creates a file, mmaps to it, writes to maped memory, and then closes the file.
  9488. We then read the file and confirm it was written to.
  9489. ===== brk
  9490. Previously <<posix>>, but was deprecated in favor of <<malloc>>
  9491. Example: link:userland/linux/brk.c[]
  9492. The example allocates two ints and uses them, and then deallocates back.
  9493. Bibliography: https://stackoverflow.com/questions/6988487/what-does-the-brk-system-call-do/31082353#31082353
  9494. ==== socket
  9495. A bit like `read` and `write`, but from / to the Internet!
  9496. * link:userland/posix/wget.c[] tiny `wget` re-implementation. See: https://stackoverflow.com/questions/11208299/how-to-make-an-http-get-request-in-c-without-libcurl/35680609#35680609
  9497. === Userland multithreading
  9498. The following sections are related to multithreading in userland:
  9499. * language topics:
  9500. ** <<c-multithreading>>
  9501. ** <<cpp-multithreading>>
  9502. ** <<pthreads>>
  9503. * ISA topics:
  9504. ** <<x86-thread-synchronization-primitives>>
  9505. ** <<arm-lse>>
  9506. * emulator topics:
  9507. ** <<qemu-user-mode-multithreading>>
  9508. ** <<gem5-syscall-emulation-multithreading>>
  9509. === C debugging
  9510. Let's group the hard-to-debug undefined-behaviour-like stuff found in C / C+ here and how to tackle those problems.
  9511. ==== Stack smashing
  9512. https://stackoverflow.com/questions/1345670/stack-smashing-detected/51897264#51897264
  9513. Example:: link:userland/c/smash_stack.c[]
  9514. Leads to the dreadful "Stack smashing detected" message. Which is infinitely better than a silent break in any case.
  9515. ==== Memory leaks
  9516. How to debug: https://stackoverflow.com/questions/6261201/how-to-find-memory-leak-in-a-c-code-project/57877190#57877190
  9517. Example: link:userland/c/memory_leak.c[]
  9518. === Interpreted languages
  9519. Maybe some day someone will use this setup to study the performance of interpreters:
  9520. * <<node-js>>
  9521. === Node.js
  9522. Parent section: <<interpreted-languages>>.
  9523. Install the interpreter with:
  9524. ....
  9525. ./build-buildroot --config 'BR2_PACKAGE_NODEJS=y'
  9526. ....
  9527. TODO: broken as of 3c3deb14dc8d6511680595dc42cb627d5781746d + 1:
  9528. ....
  9529. ERROR: package host-nodejs installs executables without proper RPATH
  9530. ....
  9531. Examples:
  9532. * String
  9533. ** link:rootfs_overlay/lkmc/nodejs/alphanumeric.js[]: https://stackoverflow.com/questions/4444477/how-to-tell-if-a-string-contains-a-certain-character-in-javascript/58359106#58359106
  9534. * `process`
  9535. ** link:rootfs_overlay/lkmc/nodejs/command_line_arguments.js[]
  9536. * `fs`
  9537. ** link:rootfs_overlay/lkmc/nodejs/file_write_read.js[]
  9538. ** link:rootfs_overlay/lkmc/nodejs/read_stdin_to_string.js[] Question: https://stackoverflow.com/questions/30441025/read-all-text-from-stdin-to-a-string
  9539. === Userland content bibliography
  9540. * The Linux Programming Interface by Michael Kerrisk https://www.amazon.co.uk/Linux-Programming-Interface-System-Handbook/dp/1593272200 Lots of open source POSIX examples: https://github.com/cirosantilli/linux-programming-interface-kerrisk
  9541. == Userland assembly
  9542. Programs under `userland/arch/<arch>/` are examples of userland assembly programming.
  9543. This section will document ISA agnostic concepts, and you should read it first.
  9544. ISA specifics are covered at:
  9545. * <<x86-userland-assembly>> under link:userland/arch/x86_64/[], originally migrated from: https://github.com/cirosantilli/x86-assembly-cheat
  9546. * <<arm-userland-assembly>> originally migrated from https://github.com/cirosantilli/arm-assembly-cheat under:
  9547. ** link:userland/arch/arm/[]
  9548. ** link:userland/arch/aarch64/[]
  9549. Like other userland programs, these programs can be run as explained at: xref:userland-setup[xrefstyle=full].
  9550. As a quick reminder, the fastest setups to get started are:
  9551. * <<userland-setup-getting-started-natively>> if your host can run the examples, e.g. x86 example on an x86 host:
  9552. * <<userland-setup-getting-started-with-prebuilt-toolchain-and-qemu-user-mode>> otherwise
  9553. However, as usual, it is saner to build your toolchain as explained at: xref:qemu-user-mode-getting-started[xrefstyle=full].
  9554. The first examples you should look into are:
  9555. * add
  9556. ** link:userland/arch/x86_64/add.S[]
  9557. ** link:userland/arch/arm/add.S[]
  9558. ** link:userland/arch/aarch64/add.S[]
  9559. * mov between register and memory
  9560. ** link:userland/arch/x86_64/mov.S[]
  9561. ** <<arm-mov-instruction>>
  9562. ** <<arm-load-and-store-instructions>>
  9563. * addressing modes
  9564. ** <<x86-addressing-modes>>
  9565. ** <<arm-addressing-modes>>
  9566. * registers, see: xref:assembly-registers[xrefstyle=full]
  9567. * jumping:
  9568. ** <<x86-control-transfer-instructions>>
  9569. ** <<arm-branch-instructions>>
  9570. * SIMD
  9571. ** <<x86-simd>>
  9572. ** <<arm-simd>>
  9573. The add examples in particular:
  9574. * introduce the basics of how a given assembly works: how many inputs / outputs, who is input and output, can it use memory or just registers, etc.
  9575. +
  9576. It is then a big copy paste for most other data instructions.
  9577. * verify that the venerable ADD instruction and our assertions are working
  9578. Now try to modify modify the x86_64 add program to see the assertion fail:
  9579. ....
  9580. LKMC_ASSERT_EQ(%rax, $4)
  9581. ....
  9582. because 1 + 2 tends to equal 3 instead of 4.
  9583. And then watch the assertion fail:
  9584. ....
  9585. ./build-userland
  9586. ./run --userland userland/arch/x86_64/add.S
  9587. ....
  9588. with error message:
  9589. ....
  9590. assert_eq_64 failed
  9591. val1 0x3
  9592. val2 0x4
  9593. error: asm_main returned 1 at line 8
  9594. ....
  9595. and notice how the error message gives both:
  9596. * the actual assembly source line number where the failing assert was
  9597. * the actual and expected values
  9598. Other infrastructure sanity checks that you might want to look into include:
  9599. * link:userland/arch/empty.S[]
  9600. * `LKMC_FAIL` tests
  9601. ** link:userland/arch/lkmc_assert_fail.S[]
  9602. * `LKMC_ASSERT_EQ` tests
  9603. ** link:userland/arch/x86_64/lkmc_assert_eq_fail.S[]
  9604. ** link:userland/arch/arm/lkmc_assert_eq_fail.S[]
  9605. ** link:userland/arch/aarch64/lkmc_assert_eq_fail.S[]
  9606. * `LKMC_ASSERT_MEMCMP` tests
  9607. ** link:userland/arch/x86_64/lkmc_assert_memcmp_fail.S[]
  9608. ** link:userland/arch/arm/lkmc_assert_memcmp_fail.S[]
  9609. ** link:userland/arch/aarch64/lkmc_assert_memcmp_fail.S[]
  9610. === Assembly registers
  9611. After seeing an <<userland-assembly,ADD hello world>>, you need to learn the general registers:
  9612. * x86, see: xref:x86-registers[xrefstyle=full]
  9613. * arm
  9614. ** link:userland/arch/arm/registers.S[]
  9615. * aarch64
  9616. ** link:userland/arch/aarch64/registers.S[]
  9617. ** link:userland/arch/aarch64/pc.S[]
  9618. Bibliography: <<armarm7>> A2.3 "ARM core registers".
  9619. ==== ARMv8 aarch64 x31 register
  9620. Example: link:userland/arch/aarch64/x31.S[]
  9621. There is no X31 name, and the encoding can have two different names depending on the instruction:
  9622. * XZR: zero register:
  9623. ** https://stackoverflow.com/questions/42788696/why-might-one-use-the-xzr-register-instead-of-the-literal-0-on-armv8
  9624. ** https://community.arm.com/processors/f/discussions/3185/wzr-xzr-register-s-purpose
  9625. * SP: stack pointer
  9626. To make things more confusing, some aliases can take either name, which makes them alias to different things, e.g. MOV accepts both:
  9627. ....
  9628. mov x0, sp
  9629. mov x0, xzr
  9630. ....
  9631. and the first one is an alias to ADD while the second an alias to <<arm-bitwise-instructions,ORR>>.
  9632. The difference is documented on a per instruction basis. Instructions that encode 31 as SP say:
  9633. ....
  9634. if d == 31 then
  9635. SP[] = result;
  9636. else
  9637. X[d] = result;
  9638. ....
  9639. And then those that don't say that, B1.2.1 "Registers in AArch64 state" implies the zero register:
  9640. ____
  9641. In instruction encodings, the value 0b11111 (31) is used to indicate the ZR (zero register). This
  9642. indicates that the argument takes the value zero, but does not indicate that the ZR is implemented
  9643. as a physical register.
  9644. ____
  9645. This is also described on <<armarm8>> C1.2.5 "Register names":
  9646. ____
  9647. There is no register named W31 or X31.
  9648. The name SP represents the stack pointer for 64-bit operands where an encoding of the value 31 in the
  9649. corresponding register field is interpreted as a read or write of the current stack pointer. When instructions
  9650. do not interpret this operand encoding as the stack pointer, use of the name SP is an error.
  9651. The name XZR represents the zero register for 64-bit operands where an encoding of the value 31 in the
  9652. corresponding register field is interpreted as returning zero when read or discarding the result when written.
  9653. When instructions do not interpret this operand encoding as the zero register, use of the name XZR is an error
  9654. ____
  9655. === Floating point assembly
  9656. Keep in mind that many ISAs started floating point as an optional thing, and it later got better integrated into the main CPU, side by side with SIMD.
  9657. For this reason, there are sometimes multiple ways to do floating point operations in each ISA.
  9658. Let's start as usual with floating point addition + register file:
  9659. * arm
  9660. ** <<arm-vadd-instruction>>
  9661. ** <<arm-vfp-registers>>
  9662. * aarch64
  9663. ** <<armv8-aarch64-fadd-instruction>>
  9664. ** <<armv8-aarch64-floating-point-registers>>
  9665. === SIMD assembly
  9666. Much like ADD for non-SIMD, start learning SIMD instructions by looking at the integer and floating point SIMD ADD instructions of each ISA:
  9667. * x86
  9668. ** <<x86-sse-data-transfer-instructions,ADDPD>>
  9669. ** <<x86-paddq-instruction>>
  9670. * arm
  9671. ** <<arm-vadd-instruction>>
  9672. * aarch64
  9673. ** <<armv8-aarch64-add-vector-instruction>>
  9674. ** <<armv8-aarch64-fadd-instruction>>
  9675. Then it is just a huge copy paste of infinite boring details:
  9676. * <<x86-simd>>
  9677. * <<arm-simd>>
  9678. To debug these instructoins, you can see the register values in GDB with:
  9679. ....
  9680. info registers float
  9681. ....
  9682. or alternatively with register names (here the ARMv8 V0 register):
  9683. ....
  9684. print $v0
  9685. ....
  9686. as mentioned at:
  9687. * https://stackoverflow.com/questions/5429137/how-to-print-register-values-in-gdb/38036152#38036152
  9688. * https://reverseengineering.stackexchange.com/questions/8992/floating-point-registers-on-arm/20623#20623
  9689. Bibliography: https://stackoverflow.com/questions/1389712/getting-started-with-intel-x86-sse-simd-instructions/56409539#56409539
  9690. ==== FMA instruction
  9691. Fused multiply add:
  9692. * x86: xref:x86-fma[xrefstyle=full]
  9693. Bibliography:
  9694. * https://en.wikipedia.org/wiki/Multiply–accumulate_operation
  9695. * https://en.wikipedia.org/wiki/FMA_instruction_set
  9696. Particularly important numerical analysis instruction, that is used in particular for;
  9697. * Dot product
  9698. * Matrix multiplication
  9699. FMA is so important that <<ieee-754>> specifies it with single precision drop compared to a separate add and multiply!
  9700. Micro-op fun: https://stackoverflow.com/questions/28630864/how-is-fma-implemented
  9701. Historically, FMA instructions have been added relatively late to instruction sets.
  9702. === User vs system assembly
  9703. By "userland assembly", we mean "the parts of the ISA which can be freely used from userland".
  9704. Most ISAs are divided into a system and userland part, and to running the system part requires elevated privileges such as <<ring0>> in x86.
  9705. One big difference between both is that we can run userland assembly on <<userland-setup>>, which is easier to get running and debug.
  9706. In particular, most userland assembly examples link to the C standard library, see: xref:userland-assembly-c-standard-library[xrefstyle=full].
  9707. Userland assembly is generally simpler, and a pre-requisite for <<baremetal-setup>>.
  9708. System-land assembly cheats will be put under: xref:baremetal-setup[xrefstyle=full].
  9709. === Userland assembly C standard library
  9710. All examples except the <<freestanding-programs>> link to the C standard library.
  9711. This allows using the C standard library for IO, which is very convenient and portable across host OSes.
  9712. It also exposes other non-IO functionality that is very convenient such as `memcmp`.
  9713. The C standard library infrastructure is implemented in the common userland / baremetal source files:
  9714. * link:lkmc.c[]
  9715. * link:lkmc.h[]
  9716. * link:lkmc/aarch64.h[]
  9717. * link:lkmc/arm.h[]
  9718. * link:lkmc/x86_64.h[]
  9719. ==== Freestanding programs
  9720. Unlike most our other assembly examples, which use the C standard library for portability, examples under `freestanding/` directories don't link to the C standard library:
  9721. * link:userland/arch/x86_64/freestanding/[]
  9722. * link:userland/arch/arm/freestanding/[]
  9723. * link:userland/arch/aarch64/freestanding/[]
  9724. As a result, those examples cannot do IO portably, and so they make raw system calls and only be run on one given OS, e.g. <<linux-system-calls>>.
  9725. Such executables are called freestanding because they don't execute the glibc initialization code, but rather start directly on our custom hand written assembly.
  9726. In order to GDB step debug those executables, you will want to use `--no-continue`, e.g.:
  9727. ....
  9728. ./run --arch aarch64 --userland userland/arch/aarch64/freestanding/linux/hello.S --gdb-wait
  9729. ./run-gdb --arch aarch64 --no-continue --userland userland/arch/aarch64/freestanding/linux/hello.S
  9730. ....
  9731. or in one go with <<tmux>>:
  9732. ....
  9733. ./run \
  9734. --arch aarch64 \
  9735. --gdb-wait \
  9736. --tmux-args=--no-continue \
  9737. --userland userland/arch/aarch64/freestanding/linux/hello.S \
  9738. ;
  9739. ....
  9740. You are now left on the very first instruction of our tiny executable!
  9741. This is analogous to <<baremetal-gdb-step-debug,step debugging baremetal examples>>.
  9742. ===== nostartfiles programs
  9743. Assembly examples under `nostartfiles` directories can use the standard library, but they don't use the pre-`main` boilerplate and start directly at our explicitly given `_start`:
  9744. * link:userland/arch/aarch64/freestanding/[]
  9745. I'm not sure how much stdlib functionality is supposed to work without the pre-main stuff, but I guess we'll just have to find out!
  9746. === GCC inline assembly
  9747. Examples under `arch/<arch>/c/` directories show to how use inline assembly from higher level languages such as C:
  9748. * x86_64
  9749. ** link:userland/arch/x86_64/inline_asm/inc.c[]
  9750. ** link:userland/arch/x86_64/inline_asm/add.c[]
  9751. ** link:userland/arch/x86_64/inline_asm/sqrt_x87.c[] Shows how to use the <<x86-x87-fpu-instructions>> from inline assembly. Bibliography: https://stackoverflow.com/questions/6514537/how-do-i-specify-immediate-floating-point-numbers-with-inline-assembly/52906126#52906126
  9752. * arm
  9753. ** link:userland/arch/arm/inline_asm/inc.c[]
  9754. ** link:userland/arch/arm/inline_asm/inc_memory.c[]
  9755. ** link:userland/arch/arm/inline_asm/inc_memory_global.c[]
  9756. ** link:userland/arch/arm/inline_asm/add.c[]
  9757. * aarch64
  9758. ** link:userland/arch/aarch64/inline_asm/earlyclobber.c[]
  9759. ** link:userland/arch/aarch64/inline_asm/inc.c[]
  9760. ** link:userland/arch/aarch64/inline_asm/multiline.cpp[]
  9761. ==== GCC inline assembly register variables
  9762. Used notably in some of the <<linux-system-calls>> setups:
  9763. * link:userland/arch/arm/inline_asm/reg_var.c[]
  9764. * link:userland/arch/aarch64/inline_asm/reg_var.c[]
  9765. * link:userland/arch/aarch64/inline_asm/reg_var_float.c[]
  9766. In x86, makes it possible to access variables not exposed with the one letter register constraints.
  9767. In arm, it is the only way to achieve this effect: https://stackoverflow.com/questions/10831792/how-to-use-specific-register-in-arm-inline-assembler
  9768. This feature notably useful for making system calls from C, see: xref:linux-system-calls[xrefstyle=full].
  9769. Documentation: https://gcc.gnu.org/onlinedocs/gcc-4.4.2/gcc/Explicit-Reg-Vars.html
  9770. ==== GCC inline assembly scratch registers
  9771. How to use temporary registers in inline assembly:
  9772. * x86_64
  9773. ** link:userland/arch/x86_64/inline_asm/scratch.c[]
  9774. ** link:userland/arch/x86_64/inline_asm/scratch_hardcode.c[]
  9775. Bibliography: https://stackoverflow.com/questions/6682733/gcc-prohibit-use-of-some-registers/54963829#54963829
  9776. ==== GCC inline assembly early-clobbers
  9777. An example of using the `&` early-clobber modifier: link:userland/arch/aarch64/earlyclobber.c
  9778. More details at: https://stackoverflow.com/questions/15819794/when-to-use-earlyclobber-constraint-in-extended-gcc-inline-assembly/54853663#54853663
  9779. The assertion may fail without it. It actually does fail in GCC 8.2.0.
  9780. ==== GCC inline assembly floating point ARM
  9781. Not documented as of GCC 8.2, but possible: https://stackoverflow.com/questions/53960240/armv8-floating-point-output-inline-assembly
  9782. * link:userland/arch/arm/inline_asm/inc_float.c[]
  9783. * link:userland/arch/aarch64/inline_asm/inc_float.c[]
  9784. ==== GCC intrinsics
  9785. Pre-existing C wrappers using inline assembly, this is what production programs should use instead of inline assembly for SIMD:
  9786. * x86_64
  9787. ** link:userland/arch/x86_64/intrinsics/paddq.c[]. Intrinsics version of link:userland/arch/x86_64/paddq.S[]
  9788. ** link:userland/arch/x86_64/intrinsics/addpd.c[]. Intrinsics version of link:userland/arch/x86_64/addpd.S[]
  9789. ===== GCC x86 intrinsics
  9790. Good official cheatsheet with all intrinsics and what they expand to: https://software.intel.com/sites/landingpage/IntrinsicsGuide
  9791. The functions use the the following naming convention:
  9792. ....
  9793. <vector_size>_<intrin_op>_<suffix>
  9794. ....
  9795. where:
  9796. * `<vector_size>`:
  9797. ** `mm`: 128-bit vectors (SSE)
  9798. ** `mm256`: 256-bit vectors (AVX and AVX2)
  9799. ** `mm512`: 512-bit vectors (AVX512)
  9800. * `<intrin_op>`: operation of the intrinsic function, e.g. add, sub, mul, etc.
  9801. * `<suffix>`: data type:
  9802. ** `ps`: 4 floats (Packed Single)
  9803. ** `pd`: 2 doubles (Packed Double)
  9804. ** `ss`: 1 float (Single Single), often the lowest order one
  9805. ** `sd`: 1 double (Single Double)
  9806. ** `si128`: 128-bits of integers of any size
  9807. ** `ep<int_type>` integer types, e.g.:
  9808. *** `epi32`: 32 bit signed integers
  9809. *** `epu16`: 16 bit unsigned integers
  9810. Data types:
  9811. * `__m128`: four floats
  9812. * `__m128d`: two doubles
  9813. * `__m128i`: integers: 8 x 16-bit, 4 x 32-bit, 2 x 64-bit
  9814. The headers to include are clarified at: https://stackoverflow.com/questions/11228855/header-files-for-x86-simd-intrinsics
  9815. ....
  9816. x86intrin.h everything
  9817. mmintrin.h MMX
  9818. xmmintrin.h SSE
  9819. emmintrin.h SSE2
  9820. pmmintrin.h SSE3
  9821. tmmintrin.h SSSE3
  9822. smmintrin.h SSE4.1
  9823. nmmintrin.h SSE4.2
  9824. ammintrin.h SSE4A
  9825. wmmintrin.h AES
  9826. immintrin.h AVX
  9827. zmmintrin.h AVX512
  9828. ....
  9829. Present in `gcc-7_3_0-release` tree at: `gcc/config/i386/x86intrin.h`.
  9830. Bibliography:
  9831. * https://www.cs.virginia.edu/~cr4bd/3330/S2018/simdref.html
  9832. * https://software.intel.com/en-us/articles/how-to-use-intrinsics
  9833. === Linux system calls
  9834. The following <<userland-setup>> programs illustrate how to make system calls:
  9835. * x86_64
  9836. ** link:userland/arch/x86_64/freestanding/linux/hello.S[]
  9837. ** link:userland/arch/x86_64/freestanding/linux/int_system_call.S[]
  9838. ** link:userland/arch/x86_64/inline_asm/freestanding/linux/hello.c[]
  9839. ** link:userland/arch/x86_64/inline_asm/freestanding/linux/hello_regvar.c[]
  9840. * arm
  9841. ** link:userland/arch/arm/freestanding/linux/hello.S[]
  9842. ** link:userland/arch/arm/inline_asm/freestanding/linux/hello.c[]
  9843. * aarch64
  9844. ** link:userland/arch/aarch64/freestanding/linux/hello.S[]
  9845. ** link:userland/arch/aarch64/inline_asm/freestanding/linux/hello.c[]
  9846. ** link:userland/arch/aarch64/inline_asm/freestanding/linux/hello_clobbers.c[]
  9847. Determining the ARM syscall numbers:
  9848. * https://reverseengineering.stackexchange.com/questions/16917/arm64-syscalls-table
  9849. * arm: https://github.com/torvalds/linux/blob/v4.17/arch/arm/tools/syscall.tbl
  9850. * aarch64: https://github.com/torvalds/linux/blob/v4.17/include/uapi/asm-generic/unistd.h
  9851. Determining the ARM syscall interface:
  9852. * https://stackoverflow.com/questions/12946958/what-is-the-interface-for-arm-system-calls-and-where-is-it-defined-in-the-linux
  9853. * https://stackoverflow.com/questions/45742869/linux-syscall-conventions-for-armv8
  9854. Questions about the C inline assembly examples:
  9855. * x86_64: https://stackoverflow.com/questions/9506353/how-to-invoke-a-system-call-via-sysenter-in-inline-assembly/54956854#54956854
  9856. * ARM: https://stackoverflow.com/questions/21729497/doing-a-syscall-without-libc-using-arm-inline-assembly
  9857. === Linux calling conventions
  9858. A summary of results is shown at: xref:table-linux-calling-conventions[xrefstyle=full].
  9859. [[table-linux-calling-conventions]]
  9860. .Summary of Linux calling conventions for several architectures
  9861. [options="header"]
  9862. |===
  9863. |arch |arguments |return value |callee saved registers
  9864. |x86_64
  9865. |rdi, rsi, rdx, rcx, r8, r9, xmm0–7
  9866. |rax, rdx
  9867. |rbx, rbp, r12–r15
  9868. |arm
  9869. |r0-r3
  9870. |r0-r3
  9871. |r4-r11
  9872. |aarch64
  9873. |x0-x7
  9874. |x0-x7
  9875. |x19-x29
  9876. |===
  9877. ==== x86_64 calling convention
  9878. Examples:
  9879. * link:lkmc/x86_64.h[] `ENTRY` and `EXIT`
  9880. One important catch is that the stack must always be aligned to 16-bits before making calls: https://stackoverflow.com/questions/56324948/why-does-calling-the-c-abort-function-from-an-x86-64-assembly-function-lead-to
  9881. Bibliography:
  9882. * https://en.wikipedia.org/wiki/X86_calling_conventions#System_V_AMD64_ABI
  9883. * https://stackoverflow.com/questions/18024672/what-registers-are-preserved-through-a-linux-x86-64-function-call/55207335#55207335
  9884. ==== ARM calling convention
  9885. Call C standard library functions from assembly and vice versa.
  9886. * arm
  9887. ** link:lkmc/arm.h[] `ENTRY` and `EXIT`
  9888. ** link:userland/arch/arm/linux/c_from_asm.S[]
  9889. * aarch64
  9890. ** link:lkmc/aarch64.h[] `ENTRY` and `EXIT`
  9891. ** link:userland/arch/aarch64/inline_asm/linux/asm_from_c.c[]
  9892. ARM Architecture Procedure Call Standard (AAPCS) is the name that ARM Holdings gives to the calling convention.
  9893. Official specification: http://infocenter.arm.com/help/topic/com.arm.doc.ihi0042f/IHI0042F_aapcs.pdf
  9894. Bibliography:
  9895. * https://en.wikipedia.org/wiki/Calling_convention#ARM_(A32) Wiki contains the master list as usual.
  9896. * https://stackoverflow.com/questions/8422287/calling-c-functions-from-arm-assembly
  9897. * https://stackoverflow.com/questions/261419/arm-to-c-calling-convention-registers-to-save
  9898. * https://stackoverflow.com/questions/10494848/arm-whats-the-difference-between-apcs-and-aapcs-abi
  9899. === GNU GAS assembler
  9900. https://en.wikipedia.org/wiki/GNU_Assembler[GNU GAS] is the default assembler used by GDB, and therefore it completely dominates in Linux.
  9901. The Linux kernel in particular uses GNU GAS assembly extensively for the arch specific parts under `arch/`.
  9902. ==== GNU GAS assembler comments
  9903. In this tutorial, we use exclusively C Preprocessor `/**/` comments because:
  9904. * they are the same for all archs
  9905. * we are already stuck to the C Preprocessor because GNU GAS macros are unusable so we need `#define`
  9906. * mixing `#` GNU GAS comments and `#define` is a bad idea ;-)
  9907. But just in case you want to suffer, see this full explanation of GNU GAS comments: https://stackoverflow.com/questions/15663280/how-to-make-the-gnu-assembler-use-a-slash-for-comments/51991349#51991349
  9908. Examples:
  9909. * link:userland/arch/arm/comments.S[]
  9910. * link:userland/arch/aarch64/comments.S[]
  9911. ==== GNU GAS assembler immediates
  9912. Summary:
  9913. * x86 always dollar `$` everywhere.
  9914. * ARM: can use either `#`, `$` or nothing depending on v7 vs v8 and <<gnu-gas-assembler-arm-unified-syntax,`.syntax unified`>>.
  9915. +
  9916. Fuller explanation at: https://stackoverflow.com/questions/21652884/is-the-hash-required-for-immediate-values-in-arm-assembly/51987780#51987780
  9917. Examples:
  9918. * link:userland/arch/arm/immediates.S[]
  9919. * link:userland/arch/aarch64/immediates.S[]
  9920. ==== GNU GAS assembler data sizes
  9921. Let's see how many bytes go into each data type:
  9922. * link:userland/arch/x86_64/gas_data_sizes.S[]
  9923. * link:userland/arch/arm/gas_data_sizes.S[]
  9924. * link:userland/arch/aarch64/gas_data_sizes.S[]
  9925. The results are shown at: xref:table-gas-data-sizes[xrefstyle=full].
  9926. [[table-gas-data-sizes]]
  9927. .Summary of GNU GAS assembler data sizes
  9928. [options="header"]
  9929. |===
  9930. |.byte |.word |.long |.quad |.octa
  9931. |x86
  9932. |1
  9933. |2
  9934. |4
  9935. |8
  9936. |16
  9937. |arm
  9938. |1
  9939. |4
  9940. |4
  9941. |8
  9942. |16
  9943. |aarch64
  9944. |1
  9945. |4
  9946. |4
  9947. |8
  9948. |16
  9949. |===
  9950. and also keep in mind that according to the manual:
  9951. * `.int` is the same as `.long`
  9952. * `.hword` is the same as `.short` which is usually the same as `.word`
  9953. Bibliography:
  9954. * https://sourceware.org/binutils/docs-2.32/as/Pseudo-Ops.html#Pseudo-Ops
  9955. * https://stackoverflow.com/questions/43005411/how-does-the-quad-directive-work-in-assembly/43006616
  9956. * https://gist.github.com/steakknife/d47d0b19a24817f48027
  9957. ===== GNU GAS assembler ARM specifics
  9958. ====== GNU GAS assembler ARM unified syntax
  9959. There are two types of ARMv7 assemblies:
  9960. * `.syntax divided`
  9961. * `.syntax unified`
  9962. They are very similar, but unified is the new and better one, which we use in this tutorial.
  9963. Unfortunately, for backwards compatibility, GNU AS 2.31.1 and GCC 8.2.0 still use `.syntax divided` by default.
  9964. The concept of unified assembly is mentioned in ARM's official assembler documentation: http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0473c/BABJIHGJ.html and is often called Unified Assembly Language (UAL).
  9965. Some of the differences include:
  9966. * `#` is optional in unified syntax int literals, see <<gnu-gas-assembler-immediates>>
  9967. * many mnemonics changed:
  9968. ** most of them are condition code position changes, e.g. ANDSEQ vs ANDEQS: https://stackoverflow.com/questions/51184921/wierd-gcc-behaviour-with-arm-assembler-andseq-instruction
  9969. ** but there are some more drastic ones, e.g. SWI vs <<arm-svc-instruction,SVC>>: https://stackoverflow.com/questions/8459279/are-arm-instructuons-swi-and-svc-exactly-same-thing/54078731#54078731
  9970. * cannot have implicit destination with shift, see: xref:arm-shift-suffixes[xrefstyle=full]
  9971. ===== GNU GAS assembler ARM .n and .w suffixes
  9972. When reading disassembly, many instructions have either a `.n` or `.w` suffix.
  9973. `.n` means narrow, and stands for the <<arm-instruction-encodings,Thumb encoding>> of an instructions, while `.w` means wide and stands for the ARM encoding.
  9974. Bibliography: https://stackoverflow.com/questions/27147043/n-suffix-to-branch-instruction
  9975. ==== GNU GAS assembler char literals
  9976. link:userland/arch/x86_64/char_literals.S[]
  9977. https://stackoverflow.com/questions/33246811/how-to-use-character-literals-in-gnu-gas-to-replace-numbers
  9978. This syntax plays horribly with the C preprocessor:
  9979. ....
  9980. MACRO($'a)
  9981. ....
  9982. fails because cpp treats string and char literals magically.
  9983. === NOP instructions
  9984. * x86: link:userland/arch/x86_64/nop.S[NOP]
  9985. * ARM: xref:arm-nop-instruction[xrefstyle=full]
  9986. No OPeration.
  9987. Does nothing except take up one processor cycle and occupy some instruction memory.
  9988. Applications: https://stackoverflow.com/questions/234906/whats-the-purpose-of-the-nop-opcode
  9989. == x86 userland assembly
  9990. Arch agnostic infrastructure getting started at: xref:userland-assembly[xrefstyle=full].
  9991. === x86 registers
  9992. link:userland/arch/x86_64/registers.S
  9993. ....
  9994. |-----------------------------------------------|
  9995. | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 |
  9996. |-----------------------------------------------|
  9997. | | | AH | AL |
  9998. |-----------------------------------------------|
  9999. | | | AX |
  10000. |-----------------------------------------------|
  10001. | | EAX |
  10002. |-----------------------------------------------|
  10003. | RAX |
  10004. |-----------------------------------------------|
  10005. ....
  10006. For the newer x86_64 registers, the naming convention is somewhat saner:
  10007. ....
  10008. |-----------------------------------------------|
  10009. | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 |
  10010. |-----------------------------------------------|
  10011. | | |R12H |R12L |
  10012. |-----------------------------------------------|
  10013. | | | R12W |
  10014. |-----------------------------------------------|
  10015. | | R12D |
  10016. |-----------------------------------------------|
  10017. | R12 |
  10018. |-----------------------------------------------|
  10019. ....
  10020. Most of the 8 older x86 general purpose registers are not "really" general purpose in the sense that a few instructions magically use them without an explicit encoding. This is reflected in their names:
  10021. * RAX: Accumulator. The general place where you add, subtract and otherwise manipulate results in-place. Magic for example for <<x86-binary-arithmetic-instructions,MUL>>.
  10022. * RCX, RSI, RDI: Counter, Source and Destination. Used in <<x86-string-instructions>>
  10023. ==== x86 FLAGS registers
  10024. https://en.wikipedia.org/wiki/FLAGS_register
  10025. TODO: add some more info here. Just need a link placeholder for now.
  10026. === x86 addressing modes
  10027. Example: link:userland/arch/x86_64/address_modes.S[]
  10028. Several x86 instructions can calculate addresses of a complex form:
  10029. ....
  10030. s:a(b, c, d)
  10031. ....
  10032. which expands to:
  10033. ....
  10034. a + b + c * d
  10035. ....
  10036. Where the instruction encoding allows for:
  10037. * `a`: any 8 or 32-bit general purpose register
  10038. * `b`: any 32-bit general purpose register except ESP
  10039. * `c`: 1, 2, 4 or 8 (encoded in 2 SIB bits)
  10040. * `d`: immediate constant
  10041. * `s`: a segment register. Cannot be tested simply from userland, so we won't talk about them here. See: https://github.com/cirosantilli/x86-bare-metal-examples/blob/6606a2647d44bc14e6fd695c0ea2b6b7a5f04ca3/segment_registers_real_mode.S
  10042. The common compiler usage is:
  10043. * `a`: base pointer
  10044. * `b`: array offset
  10045. * `c` and `d`: struct offset
  10046. Bibliography:
  10047. * <<intel-manual-1>> 3.7.5 "Specifying an Offset"
  10048. * https://sourceware.org/binutils/docs-2.18/as/i386_002dMemory.html
  10049. === x86 data transfer instructions
  10050. 5.1.1 "Data Transfer Instructions"
  10051. * link:userland/arch/x86_64/lea.S[]: LEA
  10052. * Integer typecasts
  10053. ** link:userland/arch/x86_64/movzx.S[]: MOVZX
  10054. ** link:userland/arch/x86_64/movsx.S[]: MOVSX
  10055. * link:userland/arch/x86_64/bswap.S[]: BSWAP: convert between little endian and big endian
  10056. * link:userland/arch/x86_64/pushf.S[] PUSHF: <<x86-push-and-pop-instructions,push and pop>> the <<x86-flags-registers>> to / from the stack
  10057. ==== x86 exchange instructions
  10058. <<intel-manual-1>> 7.3.1.2 "Exchange Instructions":
  10059. * link:userland/arch/x86_64/xadd.S[] XADD: exchange and add. This is how C++ `<atomic>`'s' `++` is implemented in GCC 5.1. TODO: why is the exchange part needed?
  10060. * link:userland/arch/x86_64/xchg.S[] XCHG: exchange two values
  10061. TODO: concrete multi-thread <<gcc-inline-assembly>> examples of how all those instructions are normally used as synchronization primitives.
  10062. ===== x86 CMPXCHG instruction
  10063. link:userland/arch/x86_64/cmpxchg.S[]
  10064. CMPXCHG: compare and exchange. `cmpxchg a, b` does:
  10065. ....
  10066. if (RAX == b) {
  10067. ZF = 1
  10068. b = a
  10069. } else {
  10070. ZF = 0
  10071. RAX = b
  10072. }
  10073. ....
  10074. TODO application: https://stackoverflow.com/questions/6935442/x86-spinlock-using-cmpxchg
  10075. ==== x86 PUSH and POP instructions
  10076. link:userland/arch/x86_64/push.S[]
  10077. `push %rax` is basically equivalent to:
  10078. ....
  10079. sub $8, %rsp
  10080. mov %rax, (%rsp)
  10081. ....
  10082. and `pop %rax`:
  10083. ....
  10084. mov (%rsp), %rax
  10085. add $8, %rsp
  10086. ....
  10087. Why do those instructions exist at all vs MOV / ADD / SUB: https://stackoverflow.com/questions/4584089/what-is-the-function-of-push-pop-registers-in-x86-assembly/33583134#33583134
  10088. ==== x86 CQTO and CLTQ instructions
  10089. Examples:
  10090. * link:userland/arch/x86_64/cqto.S[] CQTO
  10091. * link:userland/arch/x86_64/cltq.S[] CLTQ
  10092. Instructions without E suffix: sign extend RAX into RDX:RAX.
  10093. Instructions E suffix: sign extend withing RAX itself.
  10094. Common combo with IDIV 32-bit, which takes the input from EDX:EAX: so you need to set up EDX before calling it.
  10095. Has some Intel vs AT&T name overload hell:
  10096. * https://stackoverflow.com/questions/6555094/what-does-cltq-do-in-assembly/45386217#45386217
  10097. * https://stackoverflow.com/questions/17170388/trying-to-understand-the-assembly-instruction-cltd-on-x86/50315201#50315201
  10098. * https://sourceware.org/binutils/docs/as/i386_002dMnemonics.html
  10099. GNU GAS accepts both syntaxes, see: xref:table-cqto-cltq[xrefstyle=full].
  10100. [[table-cqto-cltq]]
  10101. .CQTO and CLTQ family Intel vs AT&T
  10102. [options="header", cols="3*<"]
  10103. |===
  10104. |Intel |AT&T |From |To
  10105. |CBW
  10106. |CBTW
  10107. |AL
  10108. |AX
  10109. |CWDE
  10110. |CWTL
  10111. |AX
  10112. |EAX
  10113. |CWD
  10114. |CWTD
  10115. |AX
  10116. |DX:AX
  10117. |CDQ
  10118. |CLTD
  10119. |EAX
  10120. |EDX:EAX
  10121. |CDQE
  10122. |CLTQ
  10123. |EAX
  10124. |RAX
  10125. |CQO
  10126. |CQTO
  10127. |RAX
  10128. |RDX:RAX
  10129. |===
  10130. ==== x86 CMOVcc instructions
  10131. * link:userland/arch/x86_64/cmovcc.S[]: CMOVcc
  10132. mov if a condition is met:
  10133. ....
  10134. CMOVcc a, b
  10135. ....
  10136. Equals:
  10137. ....
  10138. if(flag) a = b
  10139. ....
  10140. where `cc` are the same flags as Jcc.
  10141. Vs jmp:
  10142. * https://stackoverflow.com/questions/14131096/why-is-a-conditional-move-not-vulnerable-for-branch-prediction-failure
  10143. * https://stackoverflow.com/questions/27136961/what-is-it-about-cmov-which-improves-cpu-pipeline-performance
  10144. * https://stackoverflow.com/questions/26154488/difference-between-conditional-instructions-cmov-and-jump-instructions
  10145. * https://stackoverflow.com/questions/6754454/speed-difference-between-if-else-and-ternary-operator-in-c?lq=1#comment8007791_6754495
  10146. Not necessarily faster because of branch prediction.
  10147. This is partly why the ternary `?` C operator exists: https://stackoverflow.com/questions/3565368/ternary-operator-vs-if-else
  10148. It is interesting to compare this with ARMv7 conditional execution: which is available for all instructions, as shown at: xref:arm-conditional-execution[xrefstyle=full].
  10149. === x86 binary arithmetic instructions
  10150. <<intel-manual-1>> 5.1.2 "Binary Arithmetic Instructions":
  10151. * link:userland/arch/x86_64/add.S[]: ADD
  10152. ** link:userland/arch/x86_64/inc.S[]: INC
  10153. ** link:userland/arch/x86_64/adc.S[]: ADC
  10154. * link:userland/arch/x86_64/sub.S[]: SUB
  10155. ** link:userland/arch/x86_64/dec.S[]: DEC
  10156. ** link:userland/arch/x86_64/sbb.S[]: SBB
  10157. * link:userland/arch/x86_64/mul.S[]: MUL
  10158. ** link:userland/arch/x86_64/neg.S[]: NEG
  10159. ** link:userland/arch/x86_64/imul.S[]: IMUL
  10160. * link:userland/arch/x86_64/div.S[]: DIV
  10161. ** link:userland/arch/x86_64/div_overflow.S[]: DIV overflow
  10162. ** link:userland/arch/x86_64/div_zero.S[]: DIV zero
  10163. ** link:userland/arch/x86_64/idiv.S[]: IDIV
  10164. * link:userland/arch/x86_64/cmp.S[]: CMP
  10165. === x86 logical instructions
  10166. <<intel-manual-1>> 5.1.4 "Logical Instructions"
  10167. * link:userland/arch/x86_64/and.S[]: AND
  10168. * link:userland/arch/x86_64/not.S[]: NOT
  10169. * link:userland/arch/x86_64/or.S[]: OR
  10170. * link:userland/arch/x86_64/xor.S[]: XOR
  10171. === x86 shift and rotate instructions
  10172. <<intel-manual-1>> 5.1.5 "Shift and Rotate Instructions"
  10173. * link:userland/arch/x86_64/shl.S[SHL and SHR]
  10174. +
  10175. SHift left or Right and insert 0.
  10176. +
  10177. CF == the bit that got shifted out.
  10178. +
  10179. Application: quick unsigned multiply and divide by powers of 2.
  10180. * link:userland/arch/x86_64/sal.S[SAL and SAR]
  10181. +
  10182. Application: signed multiply and divide by powers of 2.
  10183. +
  10184. Mnemonics: Shift Arithmetic Left and Right
  10185. +
  10186. Keeps the same sign on right shift.
  10187. +
  10188. Not directly exposed in C, for which signed shift is undetermined behavior, but does exist in Java via the `>>>` operator. C compilers can omit it however.
  10189. +
  10190. SHL and SAL are exactly the same and have the same encoding: https://stackoverflow.com/questions/8373415/difference-between-shl-and-sal-in-80x86/56621271#56621271
  10191. * link:userland/arch/x86_64/rol.S[]: ROL and ROR
  10192. +
  10193. Rotates the bit that is going out around to the other side.
  10194. * link:userland/arch/x86_64/rol.S[]: RCL and RCR
  10195. +
  10196. Like ROL and ROR, but insert the carry bit instead, which effectively generates a rotation of 8 + 1 bits. TODO application.
  10197. === x86 bit and byte instructions
  10198. <<intel-manual-1>> 5.1.6 "Bit and Byte Instructions"
  10199. * link:userland/arch/x86_64/bt.S[]: BT
  10200. +
  10201. Bit test: test if the Nth bit a bit of a register is set and store the result in the CF FLAG.
  10202. +
  10203. ....
  10204. CF = reg[N]
  10205. ....
  10206. * link:userland/arch/x86_64/btr.S[]: BTR
  10207. +
  10208. Do a BT and then set the bit to 0.
  10209. * link:userland/arch/x86_64/btc.S[]: BTC
  10210. +
  10211. Do a BT and then swap the value of the tested bit.
  10212. * link:userland/arch/x86_64/setcc.S[]: SETcc
  10213. +
  10214. Set a byte of a register to 0 or 1 depending on the cc condition.
  10215. +
  10216. Bibliography: https://stackoverflow.com/questions/1406783/how-to-read-and-write-x86-flags-registers-directly/30952577#30952577
  10217. * link:userland/arch/x86_64/popcnt.S[]: POPCNT
  10218. +
  10219. Count the number of 1 bits.
  10220. * link:userland/arch/x86_64/test.S[]: TEST
  10221. +
  10222. Like <<x86-binary-arithmetic-instructions,CMP>> but does AND instead of SUB:
  10223. +
  10224. ....
  10225. ZF = (!(X && Y)) ? 1 : 0
  10226. ....
  10227. === x86 control transfer instructions
  10228. <<intel-manual-1>> 5.1.7 "Control Transfer Instructions"
  10229. * link:userland/arch/x86_64/jmp.S[]: JMP
  10230. ** link:userland/arch/x86_64/jmp_indirect.S[]: JMP indirect
  10231. ==== x86 Jcc instructions
  10232. link:userland/arch/x86_64/jcc.S[]
  10233. Jump if certain conditions of the flags register are met.
  10234. Jcc includes the instructions:
  10235. * JZ, JNZ
  10236. ** JE, JNE: same as JZ, with two separate manual entries that say almost the same thing, lol: https://stackoverflow.com/questions/14267081/difference-between-je-jne-and-jz-jnz/14267662#14267662
  10237. * JG: greater than, signed
  10238. ** JA: Above: greater than, unsigned
  10239. * JL: less than, signed
  10240. ** JB below: less than, unsigned
  10241. * JC: carry
  10242. * JO: overflow
  10243. * JP: parity. Why it exists: https://stackoverflow.com/questions/25707130/what-is-the-purpose-of-the-parity-flag-on-a-cpu
  10244. * JPE: parity even
  10245. * JPO: parity odd
  10246. JG vs JA and JL vs JB:
  10247. * https://stackoverflow.com/questions/9617877/assembly-jg-jnle-jl-jnge-after-cmp/56613928#56613928
  10248. * https://stackoverflow.com/questions/20906639/difference-between-ja-and-jg-in-assembly
  10249. ==== x86 LOOP instruction
  10250. link:userland/arch/x86_64/loop.S[]
  10251. Vs <<x86-jcc-instructions,Jcc>>: https://stackoverflow.com/questions/6805692/x86-assembly-programming-loops-with-ecx-and-loop-instruction-versus-jmp-jcond Holy CISC!
  10252. ==== x86 string instructions
  10253. <<intel-manual-1>> 5.1.8 "String Instructions"
  10254. These instructions do some operation on an array item, and automatically update the index to the next item:
  10255. * First example explained in more detail
  10256. ** link:userland/arch/x86_64/stos.S[]: STOS: STOre String: store register to memory. STOSD is called STOSL in GNU GAS as usual: https://stackoverflow.com/questions/6211629/gcc-inline-assembly-error-no-such-instruction-stosd
  10257. * Further examples
  10258. ** link:userland/arch/x86_64/cmps.S[]: CMPS: CoMPare Strings: compare two values in memory with addresses given by RSI and RDI. Could be used to implement `memcmp`. Store the result in JZ as usual.
  10259. ** link:userland/arch/x86_64/lods.S[]: LODS: LOaD String: load from memory to register.
  10260. ** link:userland/arch/x86_64/movs.S[]: MOVS: MOV String: move from one memory to another with addresses given by RSI and RDI. Could be used to implement `memmov`.
  10261. ** link:userland/arch/x86_64/scas.S[]: SCAS: SCan String: compare memory to the value in a register. Could be used to implement `strchr`.
  10262. The RSI and RDI registers are actually named after these intructions! S is the source of string instructions, D is the destination of string instructions: https://stackoverflow.com/questions/1856320/purpose-of-esi-edi-registers
  10263. The direction of the index increment depends on the direction flag of the FLAGS register: 0 means forward and 1 means backward: https://stackoverflow.com/questions/9636691/what-are-cld-and-std-for-in-x86-assembly-language-what-does-df-do
  10264. These instructions were originally developed to speed up "string" operations such as those present in the `<string.h>` header of the C standard library.
  10265. However, as computer architecture evolved, those instructions might not offer considerable speedups anymore, and modern glibc such as 2.29 just uses <<x86-simd>> operations instead:, see also: https://stackoverflow.com/questions/33480999/how-can-the-rep-stosb-instruction-execute-faster-than-the-equivalent-loop
  10266. ===== x86 REP prefix
  10267. Example: link:userland/arch/x86_64/rep.S[]
  10268. Repeat a string instruction RCX times:
  10269. As the repetitions happen:
  10270. * RCX decreases, until it reaches 0
  10271. * RDI and RSI increase
  10272. The variants: REPZ, REPNZ (alias REPE, REPNE) repeat a given instruction until something happens.
  10273. REP and REPZ also additionally stop if the comparison operation they repeat fails.
  10274. * REP: INS, OUTS, MOVS, LODS, and STOS
  10275. * REPZ: CMPS and SCAS
  10276. ==== x86 ENTER and LEAVE instructions
  10277. link:userland/arch/x86_64/enter.S[]
  10278. These instructions were designed to allocate and deallocate function stack frames in the prologue and epilogue: https://stackoverflow.com/questions/5959890/enter-vs-push-ebp-mov-ebp-esp-sub-esp-imm-and-leave-vs-mov-esp-ebp
  10279. ENTER appears obsolete and is kept mostly for backwards compatibility. LEAVE is still emitted by some compilers.
  10280. ENTER A, B is basically equivalent to:
  10281. ....
  10282. push %rbp
  10283. mov %rsp, %rbp
  10284. sub %rsp, A
  10285. ....
  10286. which implies an allocation of:
  10287. * one dword to remember EBP
  10288. * A bytes for local function variables
  10289. I didn't have the patience to study the B parameter, and it does not seem to be used often: https://stackoverflow.com/questions/26323215/do-any-languages-compilers-utilize-the-x86-enter-instruction-with-a-nonzero-ne
  10290. LEAVE is equivalent to:
  10291. ....
  10292. mov %rbp, %rsp
  10293. pop %rbp
  10294. ....
  10295. which restores RSP and RBP to the values they had before the prologue.
  10296. === x86 miscellaneous instructions
  10297. <<intel-manual-1>> 5.1.13 "Miscellaneous Instructions"
  10298. NOP: xref:nop-instructions[xrefstyle=full]
  10299. === x86 random number generator instructions
  10300. <<intel-manual-1>> 5.1.15 Random Number Generator Instructions
  10301. Example: link:userland/arch/x86_64/rdrand.S[]: RDRAND
  10302. If you run that executable multiple times, it prints a random number every time to stdout.
  10303. RDRAND is a true random number generator!
  10304. This Intel engineer says its based on quantum effects: https://stackoverflow.com/questions/17616960/true-random-numbers-with-c11-and-rdrand/18004959#18004959
  10305. Generated some polemic when kernel devs wanted to use it as part of `/dev/random`, because it could be used as a cryptographic backdoor by Intel since it is a black box.
  10306. RDRAND sets the carry flag when data is ready so we must loop if the carry flag isn't set.
  10307. ==== x86 CPUID instruction
  10308. Example: link:userland/arch/x86_64/cpuid.S[]
  10309. Fills EAX, EBX, ECX and EDX with CPU information.
  10310. The exact data to show depends on the value of EAX, and for a few cases instructions ECX. When it depends on ECX, it is called a sub-leaf. Out test program prints `eax == 0`.
  10311. On <<p51>> for example the output EAX, EBX, ECX and EDX are:
  10312. ....
  10313. 0x00000016
  10314. 0x756E6547
  10315. 0x6C65746E
  10316. 0x49656E69
  10317. ....
  10318. EBX and ECX are easy to interpret:
  10319. * EBX: 75 6e 65 47 == 'u', 'n', 'e', 'G' in ASCII
  10320. * ECX: 6C 65 74 6E == 'l', 'e', 't', 'n'
  10321. so we see the string `Genu ntel` which is a shorthand for "Genuine Intel". Ha, I wonder if they had serious CPU pirating problems in the past? :-)
  10322. Information available includes:
  10323. * vendor
  10324. * version
  10325. * features (mmx, simd, rdrand, etc.) <http://en.wikipedia.org/wiki/CPUID# EAX.3D1:_Processor_Info_and_Feature_Bits>
  10326. * caches
  10327. * tlbs http://en.wikipedia.org/wiki/Translation_lookaside_buffer
  10328. The cool thing about this instruction is that it allows you to check the CPU specs and take alternative actions based on that inside your program.
  10329. On Linux, the capacity part of this information is parsed and made available at `cat /proc/cpuinfo`. See: http://unix.stackexchange.com/questions/43539/what-do-the-flags-in-proc-cpuinfo-mean
  10330. There is also the `cpuinfo` command line tool that parses the CPUID instruction from the command line. Source: http://www.etallen.com/cpuid.html
  10331. === x86 x87 FPU instructions
  10332. <<intel-manual-1>> 5.2 "X87 FPU INSTRUCTIONS"
  10333. Old floating point unit that you should likely not use anymore, prefer instead the newer <<x86-simd>> instructions.
  10334. * FPU basic examples, start here
  10335. ** link:userland/arch/x86_64/fadd.S[] FADD. The x76 FPU works on a stack of floating point numbers.
  10336. ** link:userland/arch/x86_64/faddp.S[] FADDP. Instructions with the P suffix also Pop the stack. This is often what you want for most computations, where the intermediate results don't matter.
  10337. ** link:userland/arch/x86_64/fldl_literal.S[] FLDL literal. It does not seem possible to either https://stackoverflow.com/questions/6514537/how-do-i-specify-immediate-floating-point-numbers-with-inline-assembly
  10338. *** load floating point immediates into x86 x87 FPU registers
  10339. *** encode floating point literals in x86 instructions, including MOV
  10340. * Bulk instructions
  10341. ** link:userland/arch/x86_64/fabs.S[] FABS: absolute value: `ST0 = |ST0|`
  10342. ** link:userland/arch/x86_64/fchs.S[] FCHS: change sign: `ST0 = -ST0`
  10343. ** link:userland/arch/x86_64/fild.S[] FILD: Integer Load. Convert integer to float.
  10344. ** link:userland/arch/x86_64/fld1.S[] FLD1: Push 1.0 to ST0. CISC!
  10345. ** link:userland/arch/x86_64/fldz.S[] FLDZ: Push 0.0 to ST0.
  10346. ** link:userland/arch/x86_64/fscale.S[] FSCALE: `ST0 = ST0 * 2 ^ RoundTowardZero(ST1)`
  10347. ** link:userland/arch/x86_64/fsqrt.S[] FSQRT: square root
  10348. ** link:userland/arch/x86_64/fxch.S[] FXCH: swap ST0 and another register
  10349. The ST0-ST7 x87 FPU registers are actually 80-bits wide, this can be seen from GDB with:
  10350. ....
  10351. i r st0 st1
  10352. ....
  10353. By counting the number of hex digits, we have 20 digits instead of 16!
  10354. Instructions such as FLDL convert standard <<ieee-754>> 64-bit values from memory into this custom 80-bit format.
  10355. * https://stackoverflow.com/questions/3206101/extended-80-bit-double-floating-point-in-x87-not-sse2-we-dont-miss-it
  10356. * https://en.wikipedia.org/wiki/Extended_precision#x86_extended_precision_format
  10357. ==== x86 x87 FPU vs SIMD
  10358. https://stackoverflow.com/questions/1844669/benefits-of-x87-over-sse
  10359. Modern x86 has two main ways of doing floating point operations:
  10360. * <<x86-x87-fpu-instructions>>
  10361. * <<x86-simd>>
  10362. Advantages of FPU:
  10363. * present in old CPUs, while SSE2 is only required in x86-64
  10364. * contains some instructions no present in SSE, e.g. trigonometric
  10365. * higher precision: FPU holds 80 bit Intel extension, while SSE2 only does up to 64 bit operations despite having the 128-bit register
  10366. In GCC, you can choose between them with `-mfpmath=`.
  10367. === x86 SIMD
  10368. Parent section: xref:simd-assembly[xrefstyle=full]
  10369. History:
  10370. * https://en.wikipedia.org/wiki/MMX_(instruction_set)[MMX]: MultiMedia eXtension (unofficial name). 1997. MM0-MM7 64-bit registers.
  10371. * https://en.wikipedia.org/wiki/Streaming_SIMD_Extensions[SSE]: Streaming SIMD Extensions. 1999. XMM0-XMM7 128-bit registers, XMM0-XMM15 for AMD in 64-bit mode.
  10372. * https://en.wikipedia.org/wiki/SSE2[SSE2]: 2004
  10373. * https://en.wikipedia.org/wiki/SSE3[SSE3]: 2006
  10374. * https://en.wikipedia.org/wiki/SSE4[SSE4]: 2006
  10375. * https://en.wikipedia.org/wiki/Advanced_Vector_Extensions[AVX]: Advanced Vector Extensions. 2011. YMM0–YMM15 256-bit registers in 64-bit mode. Extension of XMM.
  10376. * AVX2:2013
  10377. * AVX-512: 2016. 512-bit ZMM registers. Extension of YMM.
  10378. ==== x86 SSE instructions
  10379. <<intel-manual-1>> 5.5 "SSE INSTRUCTIONS"
  10380. ===== x86 SSE data transfer instructions
  10381. <<intel-manual-1>> 5.5.1.1 "SSE Data Transfer Instructions"
  10382. * link:userland/arch/x86_64/movaps.S[]: MOVAPS: move 4 x 32-bits between two XMM registeres or XMM registers and 16-byte aligned memory
  10383. * link:userland/arch/x86_64/movaps.S[]: MOVUPS: like MOVAPS but also works for unaligned memory
  10384. * link:userland/arch/x86_64/movss.S[]: MOVSS: move 32-bits between two XMM registeres or XMM registers and memory
  10385. ===== x86 SSE packed arithmetic instructions
  10386. <<intel-manual-1>> 5.5.1.2 "SSE Packed Arithmetic Instructions"
  10387. * link:userland/arch/x86_64/addpd.S[]: ADDPS, ADDPD: good first instruction to learn <<simd-assembly>>.
  10388. ===== x86 SSE conversion instructions
  10389. <<intel-manual-1>> 5.5.1.6 "SSE Conversion Instructions"
  10390. ==== x86 SSE2 instructions
  10391. <<intel-manual-1>> 5.6 "SSE2 INSTRUCTIONS"
  10392. * link:userland/arch/x86_64/cvttss2si.S[]: CVTTSS2SI: convert 32-bit floating point to 32-bit integer, store the result in a general purpose register. Round towards 0.
  10393. ===== x86 PADDQ instruction
  10394. link:userland/arch/x86_64/paddq.S[]: PADDQ, PADDL, PADDW, PADDB
  10395. Good first instruction to learn <<simd-assembly>>.
  10396. [[x86-fma]]
  10397. ==== x86 fused multiply add (FMA)
  10398. <<intel-manual-1>> 5.15 "FUSED-MULTIPLY-ADD (FMA)"
  10399. * link:userland/arch/x86_64/vfmadd132pd.S[]: VFMADD132PD: "Multiply packed double-precision floating-point values from xmm1 and xmm3/mem, add to xmm2 and put result in xmm1." TODO: but I don't understand the manual, experimentally on <<p51>> Ubuntu 19.04 host the result is stored in XMM2!
  10400. These instructions were not part of any SSEn set: they actually have a dedicated CPUID flag for it! It appears under `/proc/cpuinfo` as `fma`. They were introduced into AVX512F however.
  10401. They are also unusual for x86 instructions in that they take 3 operands, as you would intuitively expect from the definition of FMA.
  10402. === x86 system instructions
  10403. <<intel-manual-1>> 5.20 "SYSTEM INSTRUCTIONS"
  10404. ==== x86 RDTSC instruction
  10405. Sources:
  10406. * link:userland/arch/x86_64/rdtsc.S[]
  10407. * link:userland/arch/x86_64/intrinsics/rdtsc.c[]
  10408. Try running the programs multiple times, and watch the value increase, and then try to correlate it with `/proc/cpuinfo` frequency!
  10409. ....
  10410. while true; do sleep 1 && ./userland/arch/x86_64/rdtsc.out; done
  10411. ....
  10412. RDTSC stores its output to EDX:EAX, even in 64-bit mode, top bits are zeroed out.
  10413. TODO: review this section, make a more controlled userland experiment with <<m5ops>> instrumentation.
  10414. Let's have some fun and try to correlate the <<gem5-m5out-stats-txt-file>> `system.cpu.numCycles` cycle count with the https://en.wikipedia.org/wiki/Time_Stamp_Counter[x86 RDTSC instruction] that is supposed to do the same thing:
  10415. ....
  10416. ./build-userland --static userland/arch/x86_64/inline_asm/rdtsc.S
  10417. ./run --eval './arch/x86_64/rdtsc.out;m5 exit;' --emulator gem5
  10418. ./gem5-stat
  10419. ....
  10420. RDTSC outputs a cycle count which we compare with gem5's `gem5-stat`:
  10421. * `3828578153`: RDTSC
  10422. * `3830832635`: `gem5-stat`
  10423. which gives pretty close results, and serve as a nice sanity check that the cycle counter is coherent.
  10424. It is also nice to see that RDTSC is a bit smaller than the `stats.txt` value, since the latter also includes the exec syscall for `m5`.
  10425. Bibliography:
  10426. * https://en.wikipedia.org/wiki/Time_Stamp_Counter
  10427. * https://stackoverflow.com/questions/13772567/how-to-get-the-cpu-cycle-count-in-x86-64-from-c
  10428. * https://stackoverflow.com/questions/9887839/clock-cycle-count-wth-gcc/9887979
  10429. ===== x86 RDTSCP instruction
  10430. RDTSCP is like RDTSP, but it also stores the CPU ID into ECX: this is convenient because the value of RDTSC depends on which core we are currently on, so you often also want the core ID when you want the RDTSC.
  10431. Sources:
  10432. * link:userland/arch/x86_64/rdtscp.S[]
  10433. * link:userland/arch/x86_64/intrinsics/rdtscp.c[]
  10434. We can observe its operation with the good and old `taskset`, for example:
  10435. ....
  10436. taskset -c 0 ./userland/arch/x86_64/rdtscp.out | tail -n 1
  10437. taskset -c 1 ./userland/arch/x86_64/rdtscp.out | tail -n 1
  10438. ....
  10439. produces:
  10440. ....
  10441. 0x00000000
  10442. 0x00000001
  10443. ....
  10444. There is also the RDPID instruction that reads just the processor ID, but it appears to be very new for QEMU 4.0.0 or <<p51>>, as it fails with SIGILL on both.
  10445. Bibliography: https://stackoverflow.com/questions/22310028/is-there-an-x86-instruction-to-tell-which-core-the-instruction-is-being-run-on/56622112#56622112
  10446. ===== ARM PMCCNTR register
  10447. TODO We didn't manage to find a working ARM analogue to <<x86-rdtsc-instruction>>: link:kernel_modules/pmccntr.c[] is oopsing, and even it if weren't, it likely won't give the cycle count since boot since it needs to be activate before it starts counting anything:
  10448. * https://stackoverflow.com/questions/40454157/is-there-an-equivalent-instruction-to-rdtsc-in-arm
  10449. * https://stackoverflow.com/questions/31620375/arm-cortex-a7-returning-pmccntr-0-in-kernel-mode-and-illegal-instruction-in-u/31649809#31649809
  10450. * https://blog.regehr.org/archives/794
  10451. === x86 thread synchronization primitives
  10452. ==== x86 LOCK prefix
  10453. Inline assembly example at: link:userland/cpp/atomic.cpp[]
  10454. Ensures that memory modifications are visible across all CPUs, which is fundamental for thread synchronization.
  10455. Apparently already automatically implied by some of the <<x86-exchange-instructions>>
  10456. Bibliography:
  10457. * https://stackoverflow.com/questions/8891067/what-does-the-lock-instruction-mean-in-x86-assembly/56803909#56803909
  10458. * https://stackoverflow.com/questions/980999/what-does-multicore-assembly-language-look-like/33651438#33651438
  10459. === x86 assembly bibliography
  10460. ==== x86 official bibliography
  10461. [[intel-manual]]
  10462. ===== Intel 64 and IA-32 Architectures Software Developer's Manuals
  10463. We are using the May 2019 version unless otherwise noted.
  10464. There are a few download forms at: https://software.intel.com/en-us/articles/intel-sdm
  10465. The single PDF one is useless however because it does not have a unified ToC nor inter Volume links, so I just download the 4-part one.
  10466. The Volumes are well split, so it is usually easy to guess where you should look into.
  10467. Also I can't find older versions on the website easily, so I just web archive everything.
  10468. [[intel-manual-1]]
  10469. ====== Intel 64 and IA-32 Architectures Software Developer's Manuals Volume 1
  10470. Userland basics: http://web.archive.org/web/20190606075544/https://software.intel.com/sites/default/files/managed/a4/60/253665-sdm-vol-1.pdf
  10471. [[intel-manual-2]]
  10472. ====== Intel 64 and IA-32 Architectures Software Developer's Manuals Volume 2
  10473. Instruction list: http://web.archive.org/web/20190606075330/https://software.intel.com/sites/default/files/managed/a4/60/325383-sdm-vol-2abcd.pdf
  10474. [[intel-manual-3]]
  10475. ====== Intel 64 and IA-32 Architectures Software Developer's Manuals Volume 3
  10476. Kernel land: http://web.archive.org/web/20190606075534/https://software.intel.com/sites/default/files/managed/a4/60/325384-sdm-vol-3abcd.pdf
  10477. [[intel-manual-4]]
  10478. ====== Intel 64 and IA-32 Architectures Software Developer's Manuals Volume 4
  10479. Model specific extensions: http://web.archive.org/web/20190606075325/https://software.intel.com/sites/default/files/managed/22/0d/335592-sdm-vol-4.pdf
  10480. == ARM userland assembly
  10481. Arch general getting started at: xref:userland-assembly[xrefstyle=full].
  10482. Instructions here loosely grouped based on that of the <<armarm7>> Chapter A4 "The Instruction Sets".
  10483. We cover here mostly ARMv7, and then treat aarch64 differentially, since much of the ARMv7 userland is the same in aarch32.
  10484. === Introduction to the ARM architecture
  10485. The https://en.wikipedia.org/wiki/ARM_architecture[ARM architecture] is has been used on the vast majority of mobile phones in the 2010's, and on a large fraction of micro controllers.
  10486. It competes with <<x86-userland-assembly>> because its implementations are designed for low power consumption, which is a major requirement of the cell phone market.
  10487. ARM is generally considered a RISC instruction set, although there are some more complex instructions which would not generally be classified as purely RISC.
  10488. ARM is developed by the British funded company ARM Holdings: https://en.wikipedia.org/wiki/Arm_Holdings which originated as a joint venture between Acorn Computers, Apple and VLSI Technology in 1990.
  10489. ARM Holdings was bought by the Japanese giant SoftBank in 2016.
  10490. ==== ARMv8 vs ARMv7 vs AArch64 vs AArch32
  10491. ARMv7 is the older architecture described at: <<armarm7>>.
  10492. ARMv8 is the newer architecture ISA https://developer.arm.com/docs/den0024/latest/preface[released in 2013] and described at: <<armarm8>>. It can be in either of two states:
  10493. * <<aarch32>>
  10494. * aarch64
  10495. In the lose terminology of this repository:
  10496. * `arm` means basically AArch32
  10497. * `aarch64` means ARMv8 AArch64
  10498. ARMv8 has https://en.wikipedia.org/wiki/ARM_architecture#ARMv8-A[had several updates] since its release:
  10499. * v8.1: 2014
  10500. * v8.2: 2016
  10501. * v8.3: 2016
  10502. * v8.4: TODO
  10503. * v8.5: 2018
  10504. They are described at: <<armarm8>> A1.7 "ARMv8 architecture extensions".
  10505. ===== AArch32
  10506. 32-bit mode of operation of ARMv8.
  10507. Userland is highly / fully backwards compatible with ARMv7:
  10508. * https://stackoverflow.com/questions/42972096/armv8-backward-compatibility-with-armv7-snapdragon-820-vs-cortex-a15
  10509. * https://stackoverflow.com/questions/31848185/does-armv8-aarch32-mode-has-backward-compatible-with-armv4-armv5-or-armv6
  10510. For this reason, QEMU and GAS seems to enable both AArch32 and ARMv7 under `arm` rather than `aarch64`.
  10511. There are however some extensions over ARMv7, many of them are functionality that ARMv8 has and that designers decided to backport on AArch32 as well, e.g.:
  10512. * <<armv8-aarch32-vcvta-instruction>>
  10513. ===== AArch32 vs AArch64
  10514. A great summary of differences can be found at: https://en.wikipedia.org/wiki/ARM_architecture#AArch64_features
  10515. Some random ones:
  10516. * aarch32 has two encodings: Thumb and ARM: xref:arm-instruction-encodings[xrefstyle=full]
  10517. * in ARMv8, the stack can be enforced to 16-byte alignment: xref:armv8-aarch64-stack-alignment[xrefstyle=full]
  10518. ==== Free ARM implementations
  10519. The ARM instruction set is itself protected by patents / copyright / whatever, and you have to pay ARM Holdings a licence to implement it, even if you are creating your own custom Verilog code.
  10520. ARM has already sued people in the past for implementing ARM ISA: http://www.eetimes.com/author.asp?section_id=36&doc_id=1287452
  10521. http://semiengineering.com/an-alternative-to-x86-arm-architectures/ mentions that:
  10522. ____
  10523. Asanovic joked that the shortest unit of time is not the moment between a traffic light turning green in New York City and the cab driver behind the first vehicle blowing the horn; it’s someone announcing that they have created an open-source, ARM-compatible core and receiving a “cease and desist” letter from a law firm representing ARM.
  10524. ____
  10525. This licensing however does have the following fairness to it: ARM Holdings invents a lot of money in making a great open source software environment for the ARM ISA, so it is only natural that it should be able to get some money from hardware manufacturers for using their ISA.
  10526. Patents for very old ISAs however have expired, Amber is one implementation of those: https://en.wikipedia.org/wiki/Amber_%28processor_core%29 TODO does it have any application?
  10527. Generally, it is mostly large companies that implement the CPUs themselves. For example, the https://en.wikipedia.org/wiki/Apple_A12[Apple A12 chip], which is used in iPhones, has verilog designs:
  10528. ____
  10529. The A12 features an Apple-designed 64-bit ARMv8.3-A six-core CPU, with two high-performance cores running at 2.49 GHz called Vortex and four energy-efficient cores called Tempest.
  10530. ____
  10531. ARM designed CPUs however are mostly called `Coretx-A<id>`: https://en.wikipedia.org/wiki/List_of_applications_of_ARM_cores Vortex and Tempest are Apple designed ones.
  10532. Bibliography: https://www.quora.com/Why-is-it-that-you-need-a-license-from-ARM-to-design-an-ARM-CPU-How-are-the-instruction-sets-protected
  10533. ==== ARM instruction encodings
  10534. Understanding the basics of instruction encodings is fundamental to help you to remember what instructions do and why some things are possible or not, notably the <<arm-ldr-pseudo-instruction>> and the <<arm-adr-instruction,ADRP instruction>>.
  10535. aarch32 has two "instruction sets", which to look just like encodings.
  10536. The encodings are:
  10537. * A32: every instruction is 4 bytes long. Can encode every instruction.
  10538. * T32: most common instructions are 2 bytes long. Many others less common ones are 4 bytes long.
  10539. +
  10540. T stands for "Thumb", which is the original name for the technology, <<armarm8>> A1.3.2 "The ARM instruction sets" says:
  10541. +
  10542. ____
  10543. In previous documentation, these instruction sets were called the ARM and Thumb instruction sets
  10544. ____
  10545. +
  10546. See also: <<armarm8>> F2.1.3 "Instruction encodings".
  10547. Within each instruction set, there can be multiple encodings for a given function, and they are noted simply as:
  10548. * A1, A2, ...: A32 encodings
  10549. * T1, T2, ..m: T32 encodings
  10550. The state bit `PSTATE.T` determines if the processor is in thumb mode or not. <<armarm8>> says that this bit it can only be read from <<arm-bx-instruction>>
  10551. https://stackoverflow.com/questions/22660025/how-can-i-tell-if-i-am-in-arm-mode-or-thumb-mode-in-gdb
  10552. TODO: details: https://stackoverflow.com/questions/22660025/how-can-i-tell-if-i-am-in-arm-mode-or-thumb-mode-in-gdb says it is `0x20 & CPSR`.
  10553. This RISC-y mostly fixed instruction length design likely makes processor design easier and allows for certain optimizations, at the cost of slightly more complex assembly, as you can't encode 4 / 8 byte addresses in a single instruction. Totally worth it IMHO.
  10554. This design can be contrasted with x86, which has widely variable instruction length.
  10555. We can swap between A32 and T32 with the BX and BLX instructions: http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.kui0100a/armasm_cihfddaf.htm puts it really nicely:
  10556. ____
  10557. * The BL and BLX instructions copy the address of the next instruction into lr (r14, the link register).
  10558. * The BX and BLX instructions can change the processor state from ARM to Thumb, or from Thumb to ARM.
  10559. ** BLX label always changes the state.
  10560. ** BX Rm and BLX Rm derive the target state from bit[0] of Rm:
  10561. *** if bit[0] of Rm is 0, the processor changes to, or remains in, ARM state
  10562. *** if bit[0] of Rm is 1, the processor changes to, or remains in, Thumb state.
  10563. The BXJ instruction changes the processor state to Jazelle.
  10564. ____
  10565. Bibliography:
  10566. * https://stackoverflow.com/questions/28669905/what-is-the-difference-between-the-arm-thumb-and-thumb-2-instruction-encodings
  10567. ===== ARM Thumb encoding
  10568. Thumb examples are available at:
  10569. * link:userland/arch/arm/thumb.S[]
  10570. * link:userland/arch/arm/freestanding/linux/hello_thumb.S[]
  10571. For both of them, we can check that we are in thumb from inside GDB with:
  10572. * `disassemble`, and observe that some of the instructions are only 2 bytes long instead of always 4 as in ARM
  10573. * `print $cpsr & 0x20` which is `1` on thumb and `0` otherwise
  10574. You should contrast those examples with similar non-thumb ones of course.
  10575. We also note that thumbness of those sources is determined solely by the `.thumb_func` directive, which implies that there must be some metadata to allow the linker to decide how that code should be called:
  10576. * for the freestanding example, this is determined by the first bit of the entry address ELF header as mentioned at: https://stackoverflow.com/questions/20369440/can-start-be-the-thumb-function/20374451#20374451
  10577. +
  10578. We verify that with:
  10579. +
  10580. ....
  10581. ./run-toolchain --arch arm readelf -- -h "$(./getvar --arch arm userland_build_dir)/arch/arm/freestanding/linux/hello_thumb.out"
  10582. ....
  10583. +
  10584. The Linux kernel must use that to decide put the CPU in thumb mode: that could be done simply with a regular BX.
  10585. * on the non-freestanding one, the linker uses some ELF metadata to decide that `main` is thumb and jumps to it appropriately: https://reverseengineering.stackexchange.com/questions/6080/how-to-detect-thumb-mode-in-arm-disassembly
  10586. +
  10587. TODO details. Does the linker then resolve thumbness with address relocation? Doesn't this imply that the compiler cannot generate BL (never changes) or BLX (always changes) across object files, only BX (target state controlled by lower bit)?
  10588. ===== ARM big endian mode
  10589. ARM can switch between big and little endian mode on the fly!
  10590. However, everyone only uses little endian, so the big endian ecosystem is not as supported.
  10591. TODO is there any advantage of using big endian?
  10592. Here Peter mentions that QEMU does "support" big endian in theory, but that there are no machines for it not sure what that implies: https://stackoverflow.com/questions/41571643/emulatin-big-endian-arm-system-with-qemu
  10593. We can try it out quickly in user mode with:
  10594. ....
  10595. touch userland/arch/aarch64/freestanding/linux/hello.S
  10596. ./build-userland --arch aarch64 --ccflags=-mbig-endian userland/arch/aarch64/freestanding/linux/hello.S
  10597. ./run --arch aarch64 --userland userland/arch/aarch64/freestanding/linux/hello.S
  10598. ....
  10599. and it fails with:
  10600. ....
  10601. Invalid ELF image for this architecture
  10602. ....
  10603. From this we can guess that the big endian metadata is actually stored in the <<elf>> file, and confirm that with:
  10604. ....
  10605. ./run-toolchain \
  10606. --arch aarch64 \
  10607. readelf \
  10608. -- \
  10609. --file-header "$(./getvar --arch aarch64 userland_build_dir)/arch/aarch64/freestanding/linux/hello.out" \
  10610. ;
  10611. ....
  10612. which contains:
  10613. ....
  10614. Data: 2's complement, big endian
  10615. ....
  10616. instead of the default:
  10617. ....
  10618. Data: 2's complement, little endian
  10619. ....
  10620. TODO does the Linux kernel support running big endian executables? I tried after building the big endian executable:
  10621. ....
  10622. ./build-buildroot --arch aarch64
  10623. ./run --arch aarch64 --eval-after ./arch/aarch64/freestanding/linux/hello.out
  10624. ....
  10625. but that failed with:
  10626. ....
  10627. /lkmc/arch/aarch64/freestanding/linux/hello.out: line 1: ELF@x@0@8@: not found
  10628. /lkmc/arch/aarch64/freestanding/linux/hello.out: line 2: @@: not found
  10629. /lkmc/arch/aarch64/freestanding/linux/hello.out: line 3: syntax error: unexpected ")"
  10630. ....
  10631. TODO:
  10632. * can you compile the Linux kernel itself as big endian? Looks like yes since there is a https://github.com/torvalds/linux/blob/v5.1/arch/arm64/Kconfig#L791[`config CPU_BIG_ENDIAN`] See also: https://unix.stackexchange.com/questions/378829/getting-big-endian-linux-build-to-boot-on-arm-with-u-boot
  10633. * how can be is the endianess be checked and modified in the CPU?
  10634. === ARM branch instructions
  10635. ==== ARM B instruction
  10636. Unconditional branch.
  10637. Example: link:userland/arch/arm/b.S[]
  10638. The encoding stores PC offsets in 24 bits. The destination must be a multiple of 4, which is easy since all instructions are 4 bytes.
  10639. This allows for 26 bit long jumps, which is 64 MiB.
  10640. TODO: what to do if we want to jump longer than that?
  10641. ==== ARM BEQ instruction
  10642. Branch if equal based on the status registers.
  10643. Examples:
  10644. * link:userland/arch/arm/beq.S[].
  10645. * link:userland/arch/aarch64/beq.S[].
  10646. The family of instructions includes:
  10647. * BEQ: branch if equal
  10648. * BNE: branch if not equal
  10649. * BLE: less or equal
  10650. * BGE: greater or equal
  10651. * BLT: less than
  10652. * BGT: greater than
  10653. ==== ARM BL instruction
  10654. Branch with link, i.e. branch and store the return address on the RL register.
  10655. Example: link:userland/arch/arm/bl.S[]
  10656. This is the major way to make function calls.
  10657. The current ARM / Thumb mode is encoded in the least significant bit of lr.
  10658. ===== ARM BX instruction
  10659. See: xref:arm-thumb-encoding[xrefstyle=full]
  10660. ===== ARMv8 aarch64 ret instruction
  10661. Example: link:userland/arch/aarch64/ret.S[]
  10662. ARMv8 AArch64 only:
  10663. * there is no BX in AArch64 since no Thumb to worry about, so it is called just BR
  10664. * the RET instruction was added in addition to BR, with the following differences:
  10665. ** provides a hint that this is a function call return
  10666. ** has a default argument X30 if none is given. This is where BL puts the return value.
  10667. See also: https://stackoverflow.com/questions/32304646/arm-assembly-branch-to-address-inside-register-or-memory/54145818#54145818
  10668. ==== ARM CBZ instruction
  10669. Compare and branch if zero.
  10670. Example: link:userland/arch/aarch64/cbz.S[]
  10671. Only in ARMv8 and ARMv7 Thumb mode, not in armv7 ARM mode.
  10672. Very handy!
  10673. ==== ARM conditional execution
  10674. Weirdly, <<arm-b-instruction>> and family are not the only instructions that can execute conditionally on the flags: the same also applies to most instructions, e.g. ADD.
  10675. Example: link:userland/arch/arm/cond.S[]
  10676. Just add the usual `eq`, `ne`, etc. suffixes just as for B.
  10677. The list of all extensions is documented at <<armarm7>> "A8.3 Conditional execution".
  10678. === ARM load and store instructions
  10679. In ARM, there are only two instruction families that do memory access:
  10680. * <<arm-ldr-instruction>> to load from memory to registers
  10681. * <<arm-str-instruction>> to store from registers to memory
  10682. Everything else works on register and immediates.
  10683. This is part of the RISC-y beauty of the ARM instruction set, unlike x86 in which several operations can read from memory, and helps to predict how to optimize for a given CPU pipeline.
  10684. This kind of architecture is called a https://en.wikipedia.org/wiki/Load/store_architecture[Load/store architecture].
  10685. ==== ARM LDR instruction
  10686. ===== ARM LDR pseudo-instruction
  10687. LDR can be either a regular instruction that loads stuff into memory, or also a pseudo-instruction (assembler magic): http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0041c/Babbfdih.html
  10688. The pseudo instruction version is when an equal sign appears on one of the operators.
  10689. The LDR pseudo instruction can automatically create hidden variables in a place called the "literal pool", and load them from memory with PC relative loads.
  10690. Example: link:userland/arch/arm/ldr_pseudo.S[]
  10691. This is done basically because all instructions are 32-bit wide, and there is not enough space to encode 32-bit addresses in them.
  10692. Bibliography:
  10693. * https://stackoverflow.com/questions/37840754/what-does-an-equals-sign-on-the-right-side-of-a-ldr-instruction-in-arm-mean
  10694. * https://stackoverflow.com/questions/17214962/what-is-the-difference-between-label-equals-sign-and-label-brackets-in-ar
  10695. * https://stackoverflow.com/questions/14046686/why-use-ldr-over-mov-or-vice-versa-in-arm-assembly
  10696. ===== ARM addressing modes
  10697. Example: link:userland/arch/arm/address_modes.S[]
  10698. Load and store instructions can update the source register with the following modes:
  10699. * offset: add an offset, don't change the address register. Notation:
  10700. +
  10701. ....
  10702. ldr r1, [r0, 4]
  10703. ....
  10704. * pre-indexed: change the address register, and then use it modified. Notation:
  10705. +
  10706. ....
  10707. ldr r1, [r0, 4]!
  10708. ....
  10709. * post-indexed: use the address register unmodified, and then modify it. Notation:
  10710. +
  10711. ....
  10712. ldr r1, [r0], 4
  10713. ....
  10714. The offset itself can come from the following sources:
  10715. * immediate
  10716. * register
  10717. * scaled register: left shift the register and use that as an offset
  10718. The indexed modes are convenient to loop over arrays.
  10719. Bibliography: <<armarm7>>:
  10720. * A4.6.5 "Addressing modes"
  10721. * A8.5 "Memory accesses"
  10722. <<armarm8>>: C1.3.3 "Load/Store addressing modes"
  10723. ====== ARM loop over array
  10724. As an application of the post-indexed addressing mode, let's increment an array.
  10725. Example: link:userland/arch/arm/inc_array.S[]
  10726. ===== ARM LDRH and LDRB instructions
  10727. There are LDR variants that load less than full 4 bytes:
  10728. * link:userland/arch/arm/ldrb.S[]: load byte
  10729. * link:userland/arch/arm/ldrh.S[]: load half word
  10730. These also have signed and unsigned versions to either zero or one extend the result:
  10731. * link:userland/arch/aarch64/ldrsw.S[]: load byte and sign extend
  10732. ==== ARM STR instruction
  10733. Store from memory into registers.
  10734. Example: link:userland/arch/arm/str.S[]
  10735. Basically everything that applies to <<arm-ldr-instruction>> also applies here so we won't go into much detail.
  10736. ===== ARMv8 aarch64 STR instruction
  10737. PC-relative STR is not possible in aarch64.
  10738. For LDR it works <<arm-ldr-instruction,as in aarch32>>.
  10739. As a result, it is not possible to load from the literal pool for STR.
  10740. Example: link:userland/arch/aarch64/str.S[]
  10741. This can be seen from <<armarm8>> C3.2.1 "Load/Store register": LDR simply has on extra PC encoding that STR does not.
  10742. ===== ARMv8 aarch64 LDP and STP instructions
  10743. Push a pair of registers to the stack.
  10744. TODO minimal example. Currently used in `LKMC_PROLOGUE` at link:lkmc/aarch64.h[] since it is the main way to restore register state.
  10745. ====== ARMV8 aarch64 stack alignment
  10746. In ARMv8, the stack can be enforced to 16-byte alignment.
  10747. This is why the main way to push things to stack is with 8-byte pair pushes with the <<armv8-aarch64-ldp-and-stp-instructions>>.
  10748. <<armarm8-db>> C1.3.3 "Load/Store addressing modes" says:
  10749. ____
  10750. When stack alignment checking is enabled by system software and the base register is the SP, the current stack pointer must be initially quadword aligned, that is aligned to 16 bytes. Misalignment generates a Stack Alignment fault. The offset does not have to be a multiple of 16 bytes unless the specific Load/Store instruction requires this. SP cannot be used as a register offset.
  10751. ____
  10752. <<armarm8-db>> C3.2 "Loads and stores" says:
  10753. ____
  10754. The additional control bits SCTLR_ELx.SA and SCTLR_EL1.SA0 control whether the stack pointer must be quadword aligned when used as a base register. See SP alignment checking on page D1-2164. Using a misaligned stack pointer generates an SP alignment fault exception.
  10755. ____
  10756. <<armarm8-db>> D1.8.2 "SP alignment checking" is then the main section.
  10757. TODO: what does the ABI say on this? Why don't I observe faults on QEMU as mentioned at: https://stackoverflow.com/questions/212466/what-is-a-bus-error/31877230#31877230
  10758. See also:
  10759. * https://stackoverflow.com/questions/38535738/does-aarch64-support-unaligned-access
  10760. ==== ARM LDMIA instruction
  10761. Pop values form stack into the register and optionally update the address register.
  10762. STMDB is the push version.
  10763. Example: link:userland/arch/arm/ldmia.S[]
  10764. The mnemonics stand for:
  10765. * STMDB: STore Multiple Decrement Before
  10766. * LDMIA: LoaD Multiple Increment After
  10767. Example: link:userland/arch/arm/push.S[]
  10768. PUSH and POP are just mnemonics STDMDB and LDMIA using the stack pointer SP as address register:
  10769. ....
  10770. stmdb sp!, reglist
  10771. ldmia sp!, reglist
  10772. ....
  10773. The `!` indicates that we want to update the register.
  10774. The registers are encoded as single bits inside the instruction: each bit represents one register.
  10775. As a consequence, the push order is fixed no matter how you write the assembly instruction: there is just not enough space to encode ordering.
  10776. AArch64 loses those instructions, likely because it was not possible anymore to encode all registers: https://stackoverflow.com/questions/27941220/push-lr-and-pop-lr-in-arm-arch64 and replaces them with the <<armv8-aarch64-ldp-and-stp-instructions>>
  10777. === ARM data processing instructions
  10778. Arithmetic:
  10779. * link:userland/arch/arm/mul.S[]: multiply
  10780. * link:userland/arch/arm/sub.S[]: subtract
  10781. * link:userland/arch/arm/rbit.S[]: reverse bit order
  10782. * link:userland/arch/arm/rev.S[]: reverse byte order
  10783. * link:userland/arch/arm/tst.S[]
  10784. ==== ARM CSET instruction
  10785. Example: link:userland/arch/aarch64/cset.S[]
  10786. Set a register conditionally depending on the condition flags:
  10787. ARMv8-only, likely because in ARMv8 you can't have conditional suffixes for every instruction.
  10788. ==== ARM bitwise instructions
  10789. * link:userland/arch/arm/and.S[] AND
  10790. * EOR: exclusive OR
  10791. * link:userland/arch/arm/orr.S[]: OR
  10792. * link:userland/arch/arm/clz.S[]: count leading zeroes
  10793. ===== ARM BIC instruction
  10794. Bitwise Bit Clear: clear some bits.
  10795. ....
  10796. dest = left & ~right
  10797. ....
  10798. Example: link:userland/arch/arm/bic.S[]
  10799. ===== ARM UBFM instruction
  10800. Unsigned Bitfield Move.
  10801. ____
  10802. copies any number of low-order bits from a source register into the same number of adjacent bits at any position in the destination register, with zeros in the upper and lower bits.
  10803. ____
  10804. Example: link:userland/arch/aarch64/ubfm.S[]
  10805. TODO: explain full behaviour. Very complicated. Has several simpler to understand aliases.
  10806. ====== ARM UBFX instruction
  10807. Alias for:
  10808. ....
  10809. UBFM <Wd>, <Wn>, #<lsb>, #(<lsb>+<width>-1)
  10810. ....
  10811. Example: link:userland/arch/aarch64/ubfx.S[]
  10812. The operation:
  10813. ....
  10814. UBFX dest, src, lsb, width
  10815. ....
  10816. does:
  10817. ....
  10818. dest = (src & ((1 << width) - 1)) >> lsb;
  10819. ....
  10820. Bibliography: https://stackoverflow.com/questions/8366625/arm-bit-field-extract
  10821. ===== ARM BFM instruction
  10822. TODO: explain. Similar to <<arm-ubfm-instruction,UBFM>> but leave untouched bits unmodified.
  10823. ====== ARM BFI instruction
  10824. Examples:
  10825. * link:userland/arch/arm/bfi.S[]
  10826. * link:userland/arch/aarch64/bfi.S[]
  10827. Move the lower bits of source register into any position in the destination:
  10828. * ARMv8: an alias for <<arm-bfm-instruction>>
  10829. * ARMv7: a real instruction
  10830. ==== ARM MOV instruction
  10831. Move an immediate to a register, or a register to another register.
  10832. Cannot load from or to memory, since only the LDR and STR instruction families can do that in ARM as mentioned at: xref:arm-load-and-store-instructions[xrefstyle=full].
  10833. Example: link:userland/arch/arm/mov.S[]
  10834. Since every instruction <<arm-instruction-encodings,has a fixed 4 byte size>>, there is not enough space to encode arbitrary 32-bit immediates in a single instruction, since some of the bits are needed to actually encode the instruction itself.
  10835. The solutions to this problem are mentioned at:
  10836. * https://stackoverflow.com/questions/38689886/loading-32-bit-values-to-a-register-in-arm-assembly
  10837. * https://community.arm.com/processors/b/blog/posts/how-to-load-constants-in-assembly-for-arm-architecture
  10838. Summary of solutions:
  10839. * <<arm-movw-and-movt-instructions>>
  10840. * place it in memory. But then how to load the address, which is also a 32-bit value?
  10841. ** use pc-relative addressing if the memory is close enough
  10842. ** use <<arm-bitwise-instructions,ORR>> encodable shifted immediates
  10843. The blog article summarizes nicely which immediates can be encoded and the design rationale:
  10844. ____
  10845. An Operand 2 immediate must obey the following rule to fit in the instruction: an 8-bit value rotated right by an even number of bits between 0 and 30 (inclusive). This allows for constants such as 0xFF (0xFF rotated right by 0), 0xFF00 (0xFF rotated right by 24) or 0xF000000F (0xFF rotated right by 4).
  10846. In software - especially in languages like C - constants tend to be small. When they are not small they tend to be bit masks. Operand 2 immediates provide a reasonable compromise between constant coverage and encoding space; most common constants can be encoded directly.
  10847. ____
  10848. Assemblers however support magic memory allocations which may hide what is truly going on: https://stackoverflow.com/questions/14046686/why-use-ldr-over-mov-or-vice-versa-in-arm-assembly Always ask your friendly disassembly for a good confirmation.
  10849. ===== ARM movw and movt instructions
  10850. Set the higher or lower 16 bits of a register to an immediate in one go.
  10851. Example: link:userland/arch/arm/movw.S[]
  10852. The armv8 version analogue is <<armv8-aarch64-movk-instruction>>.
  10853. ===== ARMv8 aarch64 movk instruction
  10854. Fill a 64 bit register with 4 16-bit instructions one at a time.
  10855. Similar to <<arm-movw-and-movt-instructions>> in v7.
  10856. Example: link:userland/arch/aarch64/movk.S[]
  10857. Bibliography: https://stackoverflow.com/questions/27938768/moving-a-32-bit-constant-in-arm-arch64-register
  10858. ===== ARMv8 aarch64 movn instruction
  10859. Set 16-bits negated and the rest to `1`.
  10860. Example: link:userland/arch/aarch64/movn.S[]
  10861. ==== ARM data processing instruction suffixes
  10862. ===== ARM shift suffixes
  10863. Most data processing instructions can also optionally shift the second register operand.
  10864. Example: link:userland/arch/arm/shift.S[]
  10865. The shift types are:
  10866. * LSR and LFL: Logical Shift Right / Left. Insert zeroes.
  10867. * ROR: Rotate Right / Left. Wrap bits around.
  10868. * ASR: Arithmetic Shift Right. Keep sign.
  10869. Documented at: <<armarm7>> "A4.4.1 Standard data-processing instructions"
  10870. ===== ARM S suffix
  10871. Example: link:userland/arch/arm/s_suffix.S[]
  10872. The `S` suffix, present on most <<arm-data-processing-instructions>>, makes the instruction also set the Status register flags that control conditional jumps.
  10873. If the result of the operation is `0`, then it triggers BEQ, since comparison is a subtraction, with success on 0.
  10874. CMP sets the flags by default of course.
  10875. ==== ARM ADR instruction
  10876. Similar rationale to the <<arm-ldr-pseudo-instruction>>, allowing to easily store a PC-relative reachable address into a register in one go, to overcome the 4-byte fixed instruction size.
  10877. Examples:
  10878. * link:userland/arch/arm/adr.S[]
  10879. * link:userland/arch/aarch64/adr.S[]
  10880. * link:userland/arch/aarch64/adrp.S[]
  10881. More details: https://stackoverflow.com/questions/41906688/what-are-the-semantics-of-adrp-and-adrl-instructions-in-arm-assembly/54042899#54042899
  10882. ===== ARM ADRL instruction
  10883. See: xref:arm-adr-instruction[xrefstyle=full].
  10884. === ARM miscellaneous instructions
  10885. ==== ARM NOP instruction
  10886. Parent section: xref:nop-instructions[xrefstyle=full]
  10887. There are a few different ways to encode NOP, notably MOV a register into itself, and a dedicated miscellaneous instruction.
  10888. Example: link:userland/arch/arm/nop.S[]
  10889. Try disassembling the executable to see what the assembler is emitting:
  10890. ....
  10891. gdb-multiarch -batch -ex 'arch arm' -ex "file v7/nop.out" -ex "disassemble/rs asm_main_after_prologue"
  10892. ....
  10893. Bibliography: https://stackoverflow.com/questions/1875491/nop-for-iphone-binaries
  10894. ==== ARM UDF instruction
  10895. Guaranteed undefined! Therefore raise illegal instruction signal. Used by GCC `__builtin_trap` apparently: https://stackoverflow.com/questions/16081618/programmatically-cause-undefined-instruction-exception
  10896. * link:userland/arch/arm/udf.S[]
  10897. * link:userland/arch/aarch64/udf.S[]
  10898. Why GNU GAS 2.29 does not have a mnemonic for it in A64 because it is very recent: shows in <<armarm8-db>> but not `ca`.
  10899. === ARM SIMD
  10900. Parent section: xref:simd-assembly[xrefstyle=full]
  10901. ==== ARM VFP
  10902. The name for the ARMv7 and AArch32 floating point and SIMD instructions / registers.
  10903. Vector Floating Point extension.
  10904. TODO I think it was optional in ARMv7, find quote.
  10905. VFP has several revisions, named as VFPv1, VFPv2, etc. TODO: announcement dates.
  10906. As mentioned at: https://stackoverflow.com/questions/37790029/what-is-difference-between-arm64-and-armhf/48954012#48954012 the Linux kernel shows those capabilities in `/proc/cpuinfo` with flags such as `vfp`, `vfpv3` and others, see:
  10907. * https://github.com/torvalds/linux/blob/v4.18/arch/arm/kernel/setup.c#L1199
  10908. * https://github.com/torvalds/linux/blob/v4.18/arch/arm64/kernel/cpuinfo.c#L95
  10909. When a certain version of VFP is present on a CPU, the compiler prefix typically contains the `hf` characters which stands for Hard Float, e.g.: `arm-linux-gnueabihf`. This means that the compiler will emit VFP instructions instead of just using software implementations.
  10910. Bibliography:
  10911. * <<armarm7>> Appendix D6 "Common VFP Subarchitecture Specification". It is not part of the ISA, but just an extension. TODO: that spec does not seem to have the instructions documented, and instruction like VMOV just live with the main instructions. Is VMOV part of VFP?
  10912. * https://mindplusplus.wordpress.com/2013/06/25/arm-vfp-vector-programming-part-1-introduction/
  10913. * https://en.wikipedia.org/wiki/ARM_architecture#Floating-point_(VFP)
  10914. ===== ARM VFP registers
  10915. TODO example
  10916. <<armarm8>> E1.3.1 "The SIMD and floating-point register file" Figure E1-1 "SIMD and floating-point register file, AArch32 operation":
  10917. ....
  10918. +-----+-----+-----+
  10919. | S0 | | |
  10920. +-----+ D0 + |
  10921. | S1 | | |
  10922. +-----+-----+ Q0 |
  10923. | S2 | | |
  10924. +-----+ D1 + |
  10925. | S3 | | |
  10926. +-----+-----+-----+
  10927. | S4 | | |
  10928. +-----+ D2 + |
  10929. | S5 | | |
  10930. +-----+-----+ Q1 |
  10931. | S6 | | |
  10932. +-----+ D3 + |
  10933. | S7 | | |
  10934. +-----+-----+-----+
  10935. ....
  10936. Note how Sn is weirdly packed inside Dn, and Dn weirdly packed inside Qn, likely for historical reasons.
  10937. And you can't access the higher bytes at D16 or greater with Sn.
  10938. ===== ARM VADD instruction
  10939. * link:userland/arch/arm/vadd_scalar.S[]: see also: xref:floating-point-assembly[xrefstyle=full]
  10940. * link:userland/arch/arm/vadd_vector.S[]: see also: xref:simd-assembly[xrefstyle=full]
  10941. ===== ARM VCVT instruction
  10942. Example: link:userland/arch/arm/vcvt.S[]
  10943. Convert between integers and floating point.
  10944. <<armarm7>> on rounding:
  10945. ____
  10946. The floating-point to fixed-point operation uses the Round towards Zero rounding mode. The fixed-point to floating-point operation uses the Round to Nearest rounding mode.
  10947. ____
  10948. Notice how the opcode takes two types.
  10949. E.g., in our 32-bit float to 32-bit unsigned example we use:
  10950. ....
  10951. vld1.32.f32
  10952. ....
  10953. ====== ARM VCVTR instruction
  10954. Example: link:userland/arch/arm/vcvtr.S[]
  10955. Like <<arm-vcvt-instruction>>, but the rounding mode is selected by the FPSCR.RMode field.
  10956. Selecting rounding mode explicitly per instruction was apparently not possible in ARMv7, but was made possible in <<aarch32>> e.g. with <<armv8-aarch32-vcvta-instruction>>.
  10957. Rounding mode selection is exposed in the ANSI C standard through https://en.cppreference.com/w/c/numeric/fenv/feround[`fesetround`].
  10958. TODO: is the initial rounding mode specified by the ELF standard? Could not find a reference.
  10959. ====== ARMv8 AArch32 VCVTA instruction
  10960. Example: link:userland/arch/arm/vcvt.S[]
  10961. Added in ARMv8 <<aarch32>> only, not present in ARMv7.
  10962. In ARMv7, to use a non-round-to-zero rounding mode, you had to set the rounding mode with FPSCR and use the R version of the instruction e.g. <<arm-vcvtr-instruction>>.
  10963. Now in AArch32 it is possible to do it explicitly per-instruction.
  10964. Also there was no ties to away mode in ARMv7. This mode does not exist in C99 either.
  10965. ==== ARMv8 Advanced SIMD and floating-point support
  10966. The <<armarm8>> specifies floating point and SIMD support in the main architecture at A1.5 "Advanced SIMD and floating-point support".
  10967. The feature is often refered to simply as "SIMD&FP" throughout the manual.
  10968. The Linux kernel shows `/proc/cpuinfo` compatibility as `neon`, which is yet another intermediate name that came up at some point, see: xref:arm-neon[xrefstyle=full].
  10969. Vs <<arm-vfp>>: https://stackoverflow.com/questions/4097034/arm-cortex-a8-whats-the-difference-between-vfp-and-neon
  10970. ===== ARMv8 floating point availability
  10971. Support is semi-mandatory. <<armarm8>> A1.5 "Advanced SIMD and floating-point support":
  10972. ____
  10973. ARMv8 can support the following levels of support for Advanced SIMD and floating-point instructions:
  10974. - Full SIMD and floating-point support without exception trapping.
  10975. - Full SIMD and floating-point support with exception trapping.
  10976. - No floating-point or SIMD support. This option is licensed only for implementations targeting specialized markets.
  10977. Note: All systems that support standard operating systems with rich application environments provide hardware
  10978. support for Advanced SIMD and floating-point. It is a requirement of the ARM Procedure Call Standard for
  10979. AArch64, see Procedure Call Standard for the ARM 64-bit Architecture.
  10980. ____
  10981. Therefore it is in theory optional, but highly available.
  10982. This is unlike ARMv7, where floating point is completely optional through <<arm-vfp>>.
  10983. ===== ARM NEON
  10984. Just an informal name for the "Advanced SIMD instructions"? Very confusing.
  10985. <<armarm8>> F2.9 "Additional information about Advanced SIMD and floating-point instructions" says:
  10986. ____
  10987. The Advanced SIMD architecture, its associated implementations, and supporting software, are commonly referred to as NEON technology.
  10988. ____
  10989. https://developer.arm.com/technologies/neon mentions that is is present on both ARMv7 and ARMv8:
  10990. ____
  10991. NEON technology was introduced to the Armv7-A and Armv7-R profiles. It is also now an extension to the Armv8-A and Armv8-R profiles.
  10992. ____
  10993. ==== ARMv8 AArch64 floating point registers
  10994. TODO example.
  10995. <<armarm8>> B1.2.1 "Registers in AArch64 state" describes the registers:
  10996. ____
  10997. 32 SIMD&FP registers, V0 to V31. Each register can be accessed as:
  10998. * A 128-bit register named Q0 to Q31.
  10999. * A 64-bit register named D0 to D31.
  11000. * A 32-bit register named S0 to S31.
  11001. * A 16-bit register named H0 to H31.
  11002. * An 8-bit register named B0 to B31.
  11003. ____
  11004. Notice how Sn is very different between v7 <<arm-vfp-registers>> and v8! In v7 it goes across Dn, and in v8 inside each Dn:
  11005. ....
  11006. 128 64 32 16 8 0
  11007. +---------------------------+-------------------+-------+---+---+
  11008. | Vn |
  11009. +---------------------------------------------------------------+
  11010. | Qn |
  11011. +---------------------------+-----------------------------------+
  11012. | Dn |
  11013. +-----------------------------------+
  11014. | Sn |
  11015. +---------------+
  11016. | Hn |
  11017. +-------+
  11018. |Bn |
  11019. +---+
  11020. ....
  11021. ===== ARMv8 aarch64 add vector instruction
  11022. link:userland/arch/aarch64/add_vector.S[]
  11023. Good first instruction to learn SIMD: <<simd-assembly>>.
  11024. ===== ARMv8 aarch64 FADD instruction
  11025. * link:userland/arch/aarch64/fadd_vector.S[]: see also: xref:simd-assembly[xrefstyle=full]
  11026. * link:userland/arch/aarch64/fadd_scalar.S[]: see also: xref:floating-point-assembly[xrefstyle=full]
  11027. ====== ARM FADD vs VADD
  11028. It is very confusing, but FADDS and FADDD in Aarch32 are <<gnu-gas-assembler-arm-unified-syntax,pre-UAL>> for `vadd.f32` and `vadd.f64` which we use in this tutorial, see: xref:arm-vadd-instruction[xrefstyle=full]
  11029. The same goes for most ARMv7 mnemonics: `f*` is old, and `v*` is the newer better syntax.
  11030. But then, in ARMv8, they decided to use <<armv8-aarch64-fadd-instruction>> as the main floating point add name, and get rid of VADD!
  11031. Also keep in mind that fused multiply add is FMADD.
  11032. Examples at: xref:simd-assembly[xrefstyle=full]
  11033. ===== ARMv8 aarch64 ld2 instruction
  11034. Example: link:userland/arch/aarch64/ld2.S[]
  11035. We can load multiple vectors interleaved from memory in one single instruction!
  11036. This is why the `ldN` instructions take an argument list denoted by `{}` for the registers, much like armv7 <<arm-ldmia-instruction>>.
  11037. There are analogous LD3 and LD4 instruction.
  11038. ==== ARM SIMD bibliography
  11039. * GNU GAS tests under https://sourceware.org/git/gitweb.cgi?p=binutils-gdb.git;a=tree;f=gas/testsuite/gas/aarch64;hb=00f223631fa9803b783515a2f667f86997e2cdbe[`gas/testsuite/gas/aarch64`]
  11040. * https://stackoverflow.com/questions/2851421/is-there-a-good-reference-for-arm-neon-intrinsics
  11041. * assembly optimized libraries:
  11042. ** https://github.com/projectNe10/Ne10
  11043. ==== ARM SVE
  11044. Scalable Vector Extension.
  11045. Examples:
  11046. * link:userland/arch/aarch64/sve.S[]
  11047. To understand it, the first thing you have to look at is the execution example at Fig 1 of: https://alastairreid.github.io/papers/sve-ieee-micro-2017.pdf
  11048. aarch64 only, newer than <<arm-neon>>.
  11049. It is called Scalable because it does not specify the vector width! Therefore we don't have to worry about new vector width instructions every few years! Hurray!
  11050. The instructions then allow:
  11051. * incrementing loop index by the vector length without explicitly hardcoding it
  11052. * when the last loop is reached, extra bytes that are not multiples of the vector length get automatically masked out by the predicate register, and have no effect
  11053. Added to QEMU in 3.0.0 and gem5 in 2019 Q3.
  11054. TODO announcement date. Possibly 2017: https://alastairreid.github.io/papers/sve-ieee-micro-2017.pdf There is also a 2016 mention: https://community.arm.com/tools/hpc/b/hpc/posts/technology-update-the-scalable-vector-extension-sve-for-the-armv8-a-architecture
  11055. The Linux kernel shows `/proc/cpuinfo` compatibility as `sve`.
  11056. Official spec: https://developer.arm.com/docs/100891/latest/sve-overview/introducing-sve
  11057. SVE support is indicated by `ID_AA64PFR0_EL1.SVE` which is dumped from link:baremetal/arch/aarch64/dump_regs.c[].
  11058. Using SVE normally requires setting the CPACR_EL1.FPEN and ZEN bits, which as as of lkmc 29fd625f3fda79f5e0ee6cac43517ba74340d513 + 1 we also enable in our <<baremetal-bootloaders>>, see also: <<aarch64-baremetal-neon-setup>>.
  11059. ===== ARM SVE VADDL instruction
  11060. Get the SVE vector length. The following programs do that and print it to stdout:
  11061. * link:userland/arch/aarch64/inline_asm/sve_addvl.c[]
  11062. * link:userland/arch/aarch64/sve_addvl.S[]
  11063. ===== Change ARM SVE vector length in emulators
  11064. gem5 covered at: https://stackoverflow.com/questions/57692765/how-to-change-the-gem5-arm-sve-vector-length
  11065. It is fun to observe this directly with the <<arm-sve-vaddl-instruction>> in SE:
  11066. ....
  11067. ./run --arch aarch64 --userland userland/arch/aarch64/sve_addvl.S --static --emulator gem5 -- --param 'system.cpu[:].isa[:].sve_vl_se = 1'
  11068. ./run --arch aarch64 --userland userland/arch/aarch64/sve_addvl.S --static --emulator gem5 -- --param 'system.cpu[:].isa[:].sve_vl_se = 2'
  11069. ./run --arch aarch64 --userland userland/arch/aarch64/sve_addvl.S --static --emulator gem5 -- --param 'system.cpu[:].isa[:].sve_vl_se = 4'
  11070. ....
  11071. which consecutively:
  11072. ....
  11073. 0x0000000000000080
  11074. 0x0000000000000100
  11075. 0x0000000000000200
  11076. ....
  11077. which are multiples of 128.
  11078. TODO how to set it on QEMU at runtime? As of LKMC 37b93ecfbb5a1fcbd0c631dd0b42c5b9f2f8a89a + 1 QEMU outputs:
  11079. ....
  11080. 0x0000000000000800
  11081. ....
  11082. ===== SVE bibliography
  11083. * https://www.rico.cat/files/ICS18-gem5-sve-tutorial.pdf step by step of a complete code execution examples, the best initial tutorial so far
  11084. * https://static.docs.arm.com/dui0965/c/DUI0965C_scalable_vector_extension_guide.pdf
  11085. * https://developer.arm.com/products/software-development-tools/hpc/documentation/writing-inline-sve-assembly quick inlining guide
  11086. ====== SVE spec
  11087. <<armarm8>> A1.7 "ARMv8 architecture extensions" says:
  11088. ____
  11089. SVE is an optional extension to ARMv8.2. That is, SVE requires the implementation of ARMv8.2.
  11090. ____
  11091. A1.7.8 "The Scalable Vector Extension (SVE)": then says that only changes to the existing registers are described in that manual, and that you should look instead at the "ARM Architecture Reference Manual Supplement, The Scalable Vector Extension (SVE), for ARMv8-A."
  11092. We then download the zip from: https://developer.arm.com/docs/ddi0584/latest/arm-architecture-reference-manual-supplement-the-scalable-vector-extension-sve-for-armv8-a and it contains the PDF: `DDI0584A_d_SVE_supp_armv8A.pdf` which we use here.
  11093. That document then describes the SVE instructions and registers.
  11094. === ARMv8 architecture extensions
  11095. ==== ARMv8.1 architecture extension
  11096. <<armarm8-db>> A1.7.3 "The ARMv8.1 architecture extension"
  11097. [[arm-lse]]
  11098. ===== ARM Large System Extensions (LSE)
  11099. <<armarm8-db>> "ARMv8.1-LSE, ARMv8.1 Large System Extensions"
  11100. * LDADD: link:userland/cpp/atomic.cpp[]
  11101. Bibliography:
  11102. * https://stackoverflow.com/questions/21535058/arm64-ldxr-stxr-vs-ldaxr-stlxr
  11103. * https://preshing.com/20120710/memory-barriers-are-like-source-control-operations/
  11104. === ARM assembly bibliography
  11105. ==== ARM non-official bibliography
  11106. Good getting started tutorials:
  11107. * http://www.davespace.co.uk/arm/introduction-to-arm/
  11108. * https://azeria-labs.com/writing-arm-assembly-part-1/
  11109. * https://thinkingeek.com/arm-assembler-raspberry-pi/
  11110. * http://bob.cs.sonoma.edu/IntroCompOrg-RPi/app-make.html
  11111. ==== ARM official bibliography
  11112. The official manuals were stored in http://infocenter.arm.com but as of 2017 they started to slowly move to https://developer.arm.com[].
  11113. Each revision of a document has a "ARM DDI" unique document identifier.
  11114. The "ARM Architecture Reference Manuals" are the official canonical ISA documentation document. In this repository, we always reference the following revisions:
  11115. Bibliography: https://www.quora.com/Where-can-I-find-the-official-documentation-of-ARM-instruction-set-architectures-ISAs
  11116. [[armarm7]]
  11117. ===== ARMv7 architecture reference manual
  11118. https://developer.arm.com/products/architecture/a-profile/docs/ddi0406/latest/arm-architecture-reference-manual-armv7-a-and-armv7-r-edition
  11119. The official comprehensive ARMv7 reference.
  11120. We use by default: DDI 0406C.d: https://static.docs.arm.com/ddi0406/cd/DDI0406C_d_armv7ar_arm.pdf
  11121. [[armarm8]]
  11122. ===== ARMv8 architecture reference manual
  11123. https://static.docs.arm.com/ddi0487/ca/DDI0487C_a_armv8_arm.pdf
  11124. Latest version: https://developer.arm.com/docs/ddi0487/latest/arm-architecture-reference-manual-armv8-for-armv8-a-architecture-profile
  11125. Versions are determined by two letteres in lexicographical order, e.g.:
  11126. * a
  11127. * af
  11128. * aj
  11129. * aj
  11130. * b
  11131. * ba
  11132. * bb
  11133. * ca
  11134. The link: https://static.docs.arm.com/ddi0487/ca/DDI0487C_a_armv8_arm.pdf is the `ca` version for example.
  11135. The official comprehensive ARMv8 reference.
  11136. ISA quick references can be found in some places:
  11137. * https://web.archive.org/web/20161009122630/http://infocenter.arm.com/help/topic/com.arm.doc.qrc0001m/QRC0001_UAL.pdf
  11138. [[armarm8-db]]
  11139. ===== ARMv8 architecture reference manual db
  11140. https://static.docs.arm.com/ddi0487/db/DDI0487D_b_armv8_arm.pdf
  11141. [[armv8-programmers-guide]]
  11142. ===== Programmer's Guide for ARMv8-A
  11143. https://static.docs.arm.com/den0024/a/DEN0024A_v8_architecture_PG.pdf
  11144. A more terse human readable introduction to the ARM architecture than the reference manuals.
  11145. Does not have as many assembly code examples as you'd hope however...
  11146. Latest version at: https://developer.arm.com/docs/den0024/latest/preface
  11147. ===== Arm A64 Instruction Set Architecture: Future Architecture Technologies in the A architecture profile Documentation
  11148. https://developer.arm.com/docs/ddi0602/b
  11149. This page contains the documentation of architecture features that were publicly announced but haven't been merged into the main spec yet.
  11150. ===== ARM processor documentation
  11151. ARM also releases documentation specific to each given processor.
  11152. This adds extra details to the more portable <<armarm8>> ISA documentation.
  11153. [[arm-cortex15-trm]]
  11154. ====== ARM Cortex-A15 MPCore Processor Technical Reference Manual r4p0
  11155. http://infocenter.arm.com/help/topic/com.arm.doc.ddi0438i/DDI0438I_cortex_a15_r4p0_trm.pdf
  11156. 2013.
  11157. == ELF
  11158. https://en.wikipedia.org/wiki/Executable_and_Linkable_Format
  11159. This is the main format for executables, object files (`.o`) and shared libraries (`.so`) in Linux.
  11160. An introduction to the format can be found at: https://cirosantilli.com/elf-hello-world
  11161. == IEEE 754
  11162. https://en.wikipedia.org/wiki/IEEE_754
  11163. Examples:
  11164. * link:userland/arch/x86_64/ieee754.S[]
  11165. * link:lkmc/float.h[]. Bibliography: https://stackoverflow.com/questions/52905648/how-to-use-hexadecimal-floating-point-literals-in-gnu-gas/56818851#56818851
  11166. * https://stackoverflow.com/questions/8341395/what-is-a-subnormal-floating-point-number/53203428#53203428
  11167. * https://stackoverflow.com/questions/18118408/what-is-difference-between-quiet-nan-and-signaling-nan/55648118#55648118
  11168. * https://stackoverflow.com/questions/2618059/in-java-what-does-nan-mean/55673220#55673220
  11169. == Baremetal
  11170. Getting started at: xref:baremetal-setup[xrefstyle=full]
  11171. === Baremetal GDB step debug
  11172. GDB step debug works on baremetal exactly as it does on the Linux kernel, which is described at: xref:gdb[xrefstyle=full].
  11173. Except that is is even cooler here since we can easily control and understand every single instruction that is being run!
  11174. For example, on the first shell:
  11175. ....
  11176. ./run --arch arm --baremetal userland/c/hello.c --gdb-wait
  11177. ....
  11178. then on the second shell:
  11179. ....
  11180. ./run-gdb --arch arm --baremetal userland/c/hello.c -- main
  11181. ....
  11182. Or if you are a <<tmux,tmux pro>>, do everything in one go with:
  11183. ....
  11184. ./run --arch arm --baremetal userland/c/hello.c --gdb
  11185. ....
  11186. Alternatively, to start from the very first executed instruction of our tiny <<baremetal-bootloaders>>:
  11187. ....
  11188. ./run \
  11189. --arch arm \
  11190. --baremetal userland/c/hello.c \
  11191. --gdb-wait \
  11192. --tmux-args=--no-continue \
  11193. ;
  11194. ....
  11195. analogously to what is done for <<freestanding-programs>>.
  11196. Now you can just `stepi` to when jumping into main to go to the C code in link:userland/c/hello.c[].
  11197. This is specially interesting for the executables that don't use the bootloader from under `baremetal/arch/<arch>/no_bootloader/*.S`, e.g.:
  11198. ....
  11199. ./run \
  11200. --arch arm \
  11201. --baremetal baremetal/arch/arm/no_bootloader/semihost_exit.S \
  11202. --gdb-wait \
  11203. --tmux-args=--no-continue \
  11204. ;
  11205. ....
  11206. The cool thing about those examples is that you start at the very first instruction of your program, which gives more control.
  11207. Examples without bootloader are somewhat analogous to user mode <<freestanding-programs>>.
  11208. === Baremetal bootloaders
  11209. As can be seen from <<baremetal-gdb-step-debug>>, all examples under link:baremetal/[], with the exception of `baremetal/arch/<arch>/no_bootloader`, start from our tiny bootloaders:
  11210. * link:baremetal/lib/arm.S[]
  11211. * link:baremetal/lib/aarch64.S[]
  11212. Out simplistic bootloaders basically setup up just enough system state to allow calling:
  11213. * C functions such as `exit` from the assembly examples
  11214. * the `main` of C examples itself
  11215. The most important things that we setup in the bootloaders are:
  11216. * the stack pointer
  11217. * NEON: xref:aarch64-baremetal-neon-setup[xrefstyle=full]
  11218. * TODO: we don't do this currently but maybe we should setup BSS
  11219. The C functions that become available as a result are:
  11220. * Newlib functions implemented at link:baremetal/lib/syscalls.c[]
  11221. * `lkmc_` non-Newlib functions implemented at link:lkmc.c[]
  11222. It is not possible to call those C functions from the examples that don't use a bootloader.
  11223. For this reason, we tend to create examples with bootloaders, as it is easier to write them portably.
  11224. === Semihosting
  11225. Semihosting is a publicly documented interface specified by ARM Holdings that allows us to do some magic operations very useful in development.
  11226. Semihosting is implemented both on some real devices and on simulators such as QEMU and <<gem5-semihosting>>.
  11227. It is documented at: https://developer.arm.com/docs/100863/latest/introduction
  11228. For example, all the following code make QEMU exit:
  11229. ....
  11230. ./run --arch arm --baremetal baremetal/arch/arm/semihost_exit.S
  11231. ./run --arch arm --baremetal baremetal/arch/arm/no_bootloader/semihost_exit.S
  11232. ./run --arch aarch64 --baremetal baremetal/arch/aarch64/semihost_exit.S
  11233. ./run --arch aarch64 --baremetal baremetal/arch/aarch64/no_bootloader/semihost_exit.S
  11234. ....
  11235. Sources:
  11236. * link:baremetal/arch/arm/semihost_exit.S[]
  11237. * link:baremetal/arch/arm/no_bootloader/semihost_exit.S[]
  11238. * link:baremetal/arch/aarch64/semihost_exit.S[]
  11239. * link:baremetal/arch/aarch64/no_bootloader/semihost_exit.S[]
  11240. That `arm` program program contains the code:
  11241. ....
  11242. mov r0, #0x18
  11243. ldr r1, =#0x20026
  11244. svc 0x00123456
  11245. ....
  11246. and we can see from the docs that `0x18` stands for the `SYS_EXIT` command.
  11247. This is also how we implement the `exit(0)` system call in C for QEMU, which is used for example at link:userland/c/exit0.c[] through the Newlib via the `_exit` function at link:baremetal/lib/syscalls.c[].
  11248. Other magic operations we can do with semihosting besides exiting the on the host include:
  11249. * read and write to host stdin and stdout
  11250. * read and write to host files
  11251. Alternatives exist for some semihosting operations, e.g.:
  11252. * UART IO for host stdin and stdout in both emulators and real hardware
  11253. * <<m5ops>> for <<gem5>>, e.g. `m5 exit` makes the emulator quit
  11254. The big advantage of semihosting is that it is standardized across all ARM boards, and therefore allows you to make a single image that does those magic operations instead of having to compile multiple images with different magic addresses.
  11255. The downside of semihosting is that it is ARM specific. TODO is it an open standard that other vendors can implement?
  11256. In QEMU, we enable semihosting with:
  11257. ....
  11258. -semihosting
  11259. ....
  11260. Newlib 9c84bfd47922aad4881f80243320422b621c95dc already has a semi-hosting implementation at:
  11261. ....
  11262. newlib/libc/sys/arm/syscalls.c
  11263. ....
  11264. TODO: how to use it? Possible through crosstool-NG? In the worst case we could just copy it.
  11265. Bibliography:
  11266. * https://stackoverflow.com/questions/31990487/how-to-cleanly-exit-qemu-after-executing-bare-metal-program-without-user-interve/40957928#40957928
  11267. * https://balau82.wordpress.com/2010/11/04/qemu-arm-semihosting/
  11268. ==== gem5 semihosting
  11269. For gem5, you need:
  11270. ....
  11271. patch -d "$(./getvar gem5_source_dir)" -p 1 < patches/manual/gem5-semihost.patch
  11272. ....
  11273. https://stackoverflow.com/questions/52475268/how-to-enable-arm-semihosting-in-gem5/52475269#52475269
  11274. === gem5 baremetal carriage return
  11275. TODO: our example is printing newlines without automatic carriage return `\r` as in:
  11276. ....
  11277. enter a character
  11278. got: a
  11279. ....
  11280. We use `m5term` by default, and if we try `telnet` instead:
  11281. ....
  11282. telnet localhost 3456
  11283. ....
  11284. it does add the carriage returns automatically.
  11285. === Baremetal host packaged toolchain
  11286. For `arm`, some baremetal examples compile fine with:
  11287. ....
  11288. sudo apt-get install gcc-arm-none-eabi qemu-system-arm
  11289. ./build-baremetal --arch arm --gcc-which host-baremetal
  11290. ./run --arch arm --baremetal userland/c/hello.c --qemu-which host
  11291. ....
  11292. However, there are as usual limitations to using prebuilts:
  11293. * certain examples fail to build with the Ubuntu packaged toolchain. E.g.: link:userland/c/exit0.c[] fails with:
  11294. +
  11295. ....
  11296. /usr/lib/gcc/arm-none-eabi/6.3.1/../../../arm-none-eabi/lib/libg.a(lib_a-fini.o): In function `__libc_fini_array':
  11297. /build/newlib-8gJlYR/newlib-2.4.0.20160527/build/arm-none-eabi/newlib/libc/misc/../../../../../newlib/libc/misc/fini.c:33: undefined reference to `_fini'
  11298. collect2: error: ld returned 1 exit status
  11299. ....
  11300. +
  11301. with the prebuilt toolchain, and I'm lazy to debug.
  11302. * there seems to to be no analogous `aarch64` Ubuntu package to `gcc-arm-none-eabi`: https://askubuntu.com/questions/1049249/is-there-a-package-with-the-aarch64-version-of-gcc-arm-none-eabi-for-bare-metal
  11303. [[baremetal-cpp]]
  11304. === Baremetal C++
  11305. TODO not working as of 8825222579767f2ee7e46ffd8204b9e509440759 + 1. Not yet properly researched / reported upstream yet.
  11306. Should not be hard in theory since `libstdc++` is just part of GCC, as shown at: https://stackoverflow.com/questions/21872229/how-to-edit-and-re-build-the-gcc-libstdc-c-standard-library-source/51946224#51946224
  11307. To test it out, I first hack link:common.py[] to enable `C++`:
  11308. ....
  11309. consts['baremetal_build_in_exts'] = consts['build_in_exts']
  11310. ....
  11311. and then I hack link:userland/arch/aarch64/inline_asm/multiline.cpp[] to consist only of an empty main:
  11312. ....
  11313. int main() {}
  11314. ....
  11315. then for example:
  11316. ....
  11317. ./build-baremetal --arch aarch64
  11318. ./run --arch aarch64 --baremetal userland/arch/aarch64/inline_asm/multiline.cpp
  11319. ....
  11320. fails with:
  11321. ....
  11322. rom: requested regions overlap (rom dtb. free=0x00000000000000a0, addr=0x0000000000000000)
  11323. qemu-system-aarch64: rom check and register reset failed
  11324. ....
  11325. and the gem5 build fails completely:
  11326. ....
  11327. ./build-baremetal --arch aarch64 --emulator gem5 userland/arch/aarch64/inline_asm/multiline.cpp
  11328. ....
  11329. fails with:
  11330. ....
  11331. /tmp/ccFd2YIB.o:(.eh_frame+0x1c): relocation truncated to fit: R_AARCH64_PREL32 against `.text'
  11332. collect2: error: ld returned 1 exit status
  11333. ....
  11334. === GDB builtin CPU simulator
  11335. It is incredible, but GDB also has a CPU simulator inside of it as documented at: https://sourceware.org/gdb/onlinedocs/gdb/Target-Commands.html
  11336. TODO: any advantage over QEMU? I doubt it, mostly using it as as toy for now:
  11337. Without running `./run`, do directly:
  11338. ....
  11339. ./run-gdb --arch arm --baremetal userland/c/hello.c --sim
  11340. ....
  11341. Then inside GDB:
  11342. ....
  11343. load
  11344. starti
  11345. ....
  11346. and now you can debug normally.
  11347. Enabled with the crosstool-NG configuration:
  11348. ....
  11349. CT_GDB_CROSS_SIM=y
  11350. ....
  11351. which by grepping crosstool-NG we can see does on GDB:
  11352. ....
  11353. ./configure --enable-sim
  11354. ....
  11355. Those are not set by default on `gdb-multiarch` in Ubuntu 16.04.
  11356. Bibliography:
  11357. * https://stackoverflow.com/questions/49470659/arm-none-eabi-gdb-undefined-target-command-sim
  11358. * http://cs107e.github.io/guides/gdb/
  11359. ==== GDB builtin CPU simulator userland
  11360. Since I had this compiled, I also decided to try it out on userland.
  11361. I was also able to run a freestanding Linux userland example on it: https://github.com/cirosantilli/arm-assembly-cheat/blob/cd232dcaf32c0ba6399b407e0b143d19b6ec15f4/v7/linux/hello.S
  11362. It just ignores the <<arm-svc-instruction>> however, and does not forward syscalls to the host like QEMU does.
  11363. Then I tried a glibc example: https://github.com/cirosantilli/arm-assembly-cheat/blob/cd232dcaf32c0ba6399b407e0b143d19b6ec15f4/v7/mov.S
  11364. First it wouldn't break, so I added `-static` to the `Makefile`, and then it started failing with:
  11365. ....
  11366. Unhandled v6 thumb insn
  11367. ....
  11368. Doing:
  11369. ....
  11370. help architecture
  11371. ....
  11372. shows ARM version up to `armv6`, so maybe `armv6` is not implemented?
  11373. === ARM baremetal
  11374. In this section we will focus on learning ARM architecture concepts that can only learnt on baremetal setups.
  11375. Userland information can be found at: https://github.com/cirosantilli/arm-assembly-cheat
  11376. ==== ARM exception levels
  11377. ARM exception levels are analogous to x86 <<ring0,rings>>.
  11378. The current EL can be determined by reading from certain registers, which we do with bit disassembly at:
  11379. ....
  11380. ./run --arch arm --baremetal userland/arch/arm/dump_regs.c
  11381. ./run --arch aarch64 --baremetal baremetal/arch/aarch64/dump_regs.c
  11382. ....
  11383. The relevant bits are:
  11384. * arm: `CPSR.M`
  11385. * aarch64: `CurrentEl.EL`. This register is not accessible from EL0 for some weird reason however.
  11386. Sources:
  11387. * link:baremetal/arch/arm/dump_regs.c[]
  11388. * link:baremetal/arch/aarch64/dump_regs.c[]
  11389. The instructions that find the ARM EL are explained at: https://stackoverflow.com/questions/31787617/what-is-the-current-execution-mode-exception-level-etc
  11390. The lower ELs are not mandated by the architecture, and can be controlled through command line options in QEMU and gem5.
  11391. In QEMU, you can configure the lowest EL as explained at https://stackoverflow.com/questions/42824706/qemu-system-aarch64-entering-el1-when-emulating-a53-power-up
  11392. ....
  11393. ./run --arch arm --baremetal userland/arch/arm/dump_regs.c | grep CPSR.M
  11394. ./run --arch arm --baremetal userland/arch/arm/dump_regs.c -- -machine virtualization=on | grep CPSR.M
  11395. ./run --arch arm --baremetal userland/arch/arm/dump_regs.c -- -machine secure=on | grep CPSR.M
  11396. ./run --arch aarch64 --baremetal baremetal/arch/aarch64/dump_regs.c | grep CurrentEL.EL
  11397. ./run --arch aarch64 --baremetal baremetal/arch/aarch64/dump_regs.c -- -machine virtualization=on | grep CurrentEL.EL
  11398. ./run --arch aarch64 --baremetal baremetal/arch/aarch64/dump_regs.c -- -machine secure=on | grep CurrentEL.EL
  11399. ....
  11400. outputs respectively:
  11401. ....
  11402. CPSR.M 0x3
  11403. CPSR.M 0x3
  11404. CPSR.M 0x3
  11405. CurrentEL.EL 0x1
  11406. CurrentEL.EL 0x2
  11407. CurrentEL.EL 0x3
  11408. ....
  11409. TODO: why is arm `CPSR.M` stuck at `0x3` which equals Supervisor mode?
  11410. In gem5, you can configure the lowest EL with:
  11411. ....
  11412. ./run --arch arm --baremetal userland/arch/arm/dump_regs.c --emulator gem5
  11413. grep CPSR.M "$(./getvar --arch arm --emulator gem5 gem5_guest_terminal_file)"
  11414. ./run --arch arm --baremetal userland/arch/arm/dump_regs.c --emulator gem5 -- --param 'system.have_virtualization = True'
  11415. grep CPSR.M "$(./getvar --arch arm --emulator gem5 gem5_guest_terminal_file)"
  11416. ./run --arch arm --baremetal userland/arch/arm/dump_regs.c --emulator gem5 -- --param 'system.have_security = True'
  11417. grep CPSR.M "$(./getvar --arch arm --emulator gem5 gem5_guest_terminal_file)"
  11418. ./run --arch aarch64 --baremetal baremetal/arch/aarch64/dump_regs.c --emulator gem5
  11419. grep CurrentEL.EL "$(./getvar --arch aarch64 --emulator gem5 gem5_guest_terminal_file)"
  11420. ./run --arch aarch64 --baremetal baremetal/arch/aarch64/dump_regs.c --emulator gem5 -- --param 'system.have_virtualization = True'
  11421. grep CurrentEL.EL "$(./getvar --arch aarch64 --emulator gem5 gem5_guest_terminal_file)"
  11422. ./run --arch aarch64 --baremetal baremetal/arch/aarch64/dump_regs.c --emulator gem5 -- --param 'system.have_security = True'
  11423. grep CurrentEL.EL "$(./getvar --arch aarch64 --emulator gem5 gem5_guest_terminal_file)"
  11424. ....
  11425. output:
  11426. ....
  11427. CPSR.M 0x3
  11428. CPSR.M 0xA
  11429. CPSR.M 0x3
  11430. CurrentEL.EL 0x1
  11431. CurrentEL.EL 0x2
  11432. CurrentEL.EL 0x3
  11433. ....
  11434. TODO: the call:
  11435. ....
  11436. ./run --arch arm --baremetal userland/arch/arm/dump_regs.c --emulator gem5 -- --param 'system.have_virtualization = True'
  11437. ....
  11438. started failing with an exception since https://github.com/cirosantilli/linux-kernel-module-cheat/commit/add6eedb76636b8f443b815c6b2dd160afdb7ff4 at the instruction:
  11439. ....
  11440. vmsr fpexc, r0
  11441. ....
  11442. in link:baremetal/lib/arm.S[]. That patch however enables SIMD in baremetal, which I feel is more important.
  11443. According to <<armarm7>>, access to that register is controlled by other registers `NSACR.{CP11, CP10}` and `HCPTR` so those must be turned off, but I'm lazy to investigate now, even just trying to dump those registers in link:userland/arch/arm/dump_regs.c[] also leads to exceptions...
  11444. ===== ARM change exception level
  11445. TODO. Create a minimal runnable example of going into EL0 and jumping to EL1.
  11446. ===== ARM SP0 vs SPx
  11447. See <<armarm8-db>> D1.6.2 "The stack pointer registers".
  11448. TODO create a minimal runnable example.
  11449. TODO: how to select to use SP0 in an exception handler?
  11450. ==== ARM SVC instruction
  11451. This is the most basic example of exception handling we have.
  11452. We a handler for SVC, do an SVC, and observe that the handler got called and returned from C and assembly:
  11453. ....
  11454. ./run --arch aarch64 --baremetal baremetal/arch/aarch64/svc.c
  11455. ./run --arch aarch64 --baremetal baremetal/arch/aarch64/svc_asm.S
  11456. ....
  11457. Sources:
  11458. * link:baremetal/arch/aarch64/svc.c[]
  11459. * link:baremetal/arch/aarch64/svc_asm.S[]
  11460. Sample output for the C one:
  11461. ....
  11462. DAIF 0x3C0
  11463. SPSEL 0x1
  11464. VBAR_EL1 0x40000800
  11465. after_svc 0x4000209c
  11466. lkmc_vector_trap_handler
  11467. exc_type 0x11
  11468. exc_type is LKMC_VECTOR_SYNC_SPX
  11469. ESR 0x5600ABCD
  11470. ESR.EC 0x15
  11471. ESR.EC.ISS.imm16 0xABCD
  11472. SP 0x4200C510
  11473. ELR 0x4000209C
  11474. SPSR 0x600003C5
  11475. x0 0x0
  11476. x1 0x1
  11477. x2 0x15
  11478. x3 0x15
  11479. x4 0x4000A178
  11480. x5 0xFFFFFFF6
  11481. x6 0x4200C390
  11482. x7 0x78
  11483. x8 0x1
  11484. x9 0x14
  11485. x10 0x0
  11486. x11 0x0
  11487. x12 0x0
  11488. x13 0x0
  11489. x14 0x0
  11490. x15 0x0
  11491. x16 0x0
  11492. x17 0x0
  11493. x18 0x0
  11494. x19 0x0
  11495. x20 0x0
  11496. x21 0x0
  11497. x22 0x0
  11498. x23 0x0
  11499. x24 0x0
  11500. x25 0x0
  11501. x26 0x0
  11502. x27 0x0
  11503. x28 0x0
  11504. x29 0x4200C510
  11505. x30 0x40002064
  11506. ....
  11507. The C code does an:
  11508. ....
  11509. svc 0xABCD
  11510. ....
  11511. and the value 0xABCD appears at the bottom of <<arm-esr-register>>:
  11512. ....
  11513. ESR 0x5600ABCD
  11514. ESR.EC 0x15
  11515. ESR.EC.ISS.imm16 0xABCD
  11516. ....
  11517. The other important register is the <<arm-elr-register>>, which contains the return address after the exception.
  11518. From the output, we can see that it matches the value as obtained by taking the address of a label placed just after the SVC:
  11519. ....
  11520. after_svc 0x4000209c
  11521. ELR 0x4000209C
  11522. ....
  11523. Both QEMU and gem5 are able to trace interrupts in addition to instructions, and it is instructive to enable both and have a look at the traces.
  11524. With <<qemu-d-tracing>>:
  11525. ....
  11526. ./run \
  11527. --arch aarch64 \
  11528. --baremetal baremetal/arch/aarch64/svc.c \
  11529. -- -d in_asm,int \
  11530. ;
  11531. ....
  11532. the output at 8f73910dd1fc1fa6dc6904ae406b7598cdcd96d7 contains:
  11533. ....
  11534. ----------------
  11535. IN: main
  11536. 0x40002098: d41579a1 svc #0xabcd
  11537. Taking exception 2 [SVC]
  11538. ...from EL1 to EL1
  11539. ...with ESR 0x15/0x5600abcd
  11540. ...with ELR 0x4000209c
  11541. ...to EL1 PC 0x40000a00 PSTATE 0x3c5
  11542. ----------------
  11543. IN:
  11544. 0x40000a00: 14000225 b #0x40001294
  11545. ----------------
  11546. IN:
  11547. 0x40001294: a9bf7bfd stp x29, x30, [sp, #-0x10]!
  11548. 0x40001298: a9bf73fb stp x27, x28, [sp, #-0x10]!
  11549. 0x4000129c: a9bf6bf9 stp x25, x26, [sp, #-0x10]!
  11550. 0x400012a0: a9bf63f7 stp x23, x24, [sp, #-0x10]!
  11551. 0x400012a4: a9bf5bf5 stp x21, x22, [sp, #-0x10]!
  11552. 0x400012a8: a9bf53f3 stp x19, x20, [sp, #-0x10]!
  11553. 0x400012ac: a9bf4bf1 stp x17, x18, [sp, #-0x10]!
  11554. 0x400012b0: a9bf43ef stp x15, x16, [sp, #-0x10]!
  11555. 0x400012b4: a9bf3bed stp x13, x14, [sp, #-0x10]!
  11556. 0x400012b8: a9bf33eb stp x11, x12, [sp, #-0x10]!
  11557. 0x400012bc: a9bf2be9 stp x9, x10, [sp, #-0x10]!
  11558. 0x400012c0: a9bf23e7 stp x7, x8, [sp, #-0x10]!
  11559. 0x400012c4: a9bf1be5 stp x5, x6, [sp, #-0x10]!
  11560. 0x400012c8: a9bf13e3 stp x3, x4, [sp, #-0x10]!
  11561. 0x400012cc: a9bf0be1 stp x1, x2, [sp, #-0x10]!
  11562. 0x400012d0: d5384015 mrs x21, spsr_el1
  11563. 0x400012d4: a9bf03f5 stp x21, x0, [sp, #-0x10]!
  11564. 0x400012d8: d5384035 mrs x21, elr_el1
  11565. 0x400012dc: a9bf57ff stp xzr, x21, [sp, #-0x10]!
  11566. 0x400012e0: d2800235 movz x21, #0x11
  11567. 0x400012e4: d5385216 mrs x22, esr_el1
  11568. 0x400012e8: a9bf5bf5 stp x21, x22, [sp, #-0x10]!
  11569. 0x400012ec: 910003f5 mov x21, sp
  11570. 0x400012f0: 910482b5 add x21, x21, #0x120
  11571. 0x400012f4: f9000bf5 str x21, [sp, #0x10]
  11572. 0x400012f8: 910003e0 mov x0, sp
  11573. 0x400012fc: 9400023f bl #0x40001bf8
  11574. ----------------
  11575. IN: lkmc_vector_trap_handler
  11576. 0x40001bf8: a9bd7bfd stp x29, x30, [sp, #-0x30]!
  11577. ....
  11578. And with <<gem5-tracing>>:
  11579. ....
  11580. ./run \
  11581. --arch aarch64 \
  11582. --baremetal baremetal/arch/aarch64/svc_asm.S \
  11583. --trace ExecAll,Faults \
  11584. --trace-stdout \
  11585. ;
  11586. ....
  11587. the output contains:
  11588. ....
  11589. 4000: system.cpu A0 T0 : @main+8 : svc #0x0 : IntAlu : flags=(IsSerializeAfter|IsNonSpeculative|IsSyscall)
  11590. 4000: Supervisor Call: Invoking Fault (AArch64 target EL):Supervisor Call cpsr:0x3c5 PC:0x80000808 elr:0x8000080c newVec: 0x80001200
  11591. 4500: system.cpu A0 T0 : @vector_table+512 : b <_curr_el_spx_sync> : IntAlu : flags=(IsControl|IsDirectControl|IsUncondControl)
  11592. ....
  11593. So we see in both cases that the:
  11594. * SVC is done
  11595. * an exception happens, and the PC jumps to address 0x40000a00. From our custom terminal prints further on, we see that this equals `VBAR_EL1 + 0x200`.
  11596. +
  11597. According to the format of the <<armv8-exception-vector-table-format>>, we see that the `+ 0x200` means that we are jumping in the Current EL with SPx.
  11598. +
  11599. This can also be deduced from the message `exc_type is LKMC_VECTOR_SYNC_SPX`: we just manually store a different integer for every exception vector type in our handler code to be able to tell what happened.
  11600. +
  11601. This is the one used because we are jumping <<arm-exception-levels,from EL1 to EL1>>.
  11602. +
  11603. We set VBAR_EL1 to that address ourselves <<baremetal-bootloaders,in the bootloader>>.
  11604. * at 0x40000a00 a `b #0x40001294` is done and then at 0x40001294 boilerplate preparation is done for lkmc_vector_trap_handler starting with several STP instructions.
  11605. +
  11606. We have coded both of those in our vector table macro madness. As of LKMC 8f73910dd1fc1fa6dc6904ae406b7598cdcd96d7, both come from link:lkmc/aarch64.h[]:
  11607. +
  11608. ** `b #0x40001294` comes from: `LKMC_VECTOR_ENTRY`
  11609. ** the STP come from: `LKMC_VECTOR_BUILD_TRAPFRAME`
  11610. +
  11611. We jump immediately from inside `LKMC_VECTOR_ENTRY` to `LKMC_VECTOR_BUILD_TRAPFRAME` because we can only use 0x80 bytes of instructions for each one before reaching the next handler, so we might as well get it over with by jumping into a memory region without those constraints.
  11612. +
  11613. TODO: why doesn't QEMU show our nice symbol names? gem5 shows them fine, and `nm` says they are there!
  11614. +
  11615. ....
  11616. 0000000040000800 T lkmc_vector_table
  11617. 0000000040001294 T lkmc_vector_build_trapframe_curr_el_spx_sync
  11618. ....
  11619. The exception return happens at the end of `lkmc_vector_trap_handler`:
  11620. ....
  11621. ----------------
  11622. IN: lkmc_vector_trap_handler
  11623. 0x40002000: d503201f nop
  11624. 0x40002004: a8c37bfd ldp x29, x30, [sp], #0x30
  11625. 0x40002008: d65f03c0 ret
  11626. ----------------
  11627. IN:
  11628. 0x40001300: 910043ff add sp, sp, #0x10
  11629. 0x40001304: a8c15bf5 ldp x21, x22, [sp], #0x10
  11630. 0x40001308: d5184036 msr elr_el1, x22
  11631. ----------------
  11632. IN:
  11633. 0x4000130c: a8c103f5 ldp x21, x0, [sp], #0x10
  11634. 0x40001310: d5184015 msr spsr_el1, x21
  11635. ----------------
  11636. IN:
  11637. 0x40001314: a8c10be1 ldp x1, x2, [sp], #0x10
  11638. 0x40001318: a8c113e3 ldp x3, x4, [sp], #0x10
  11639. 0x4000131c: a8c11be5 ldp x5, x6, [sp], #0x10
  11640. 0x40001320: a8c123e7 ldp x7, x8, [sp], #0x10
  11641. 0x40001324: a8c12be9 ldp x9, x10, [sp], #0x10
  11642. 0x40001328: a8c133eb ldp x11, x12, [sp], #0x10
  11643. 0x4000132c: a8c13bed ldp x13, x14, [sp], #0x10
  11644. 0x40001330: a8c143ef ldp x15, x16, [sp], #0x10
  11645. 0x40001334: a8c14bf1 ldp x17, x18, [sp], #0x10
  11646. 0x40001338: a8c153f3 ldp x19, x20, [sp], #0x10
  11647. 0x4000133c: a8c15bf5 ldp x21, x22, [sp], #0x10
  11648. 0x40001340: a8c163f7 ldp x23, x24, [sp], #0x10
  11649. 0x40001344: a8c16bf9 ldp x25, x26, [sp], #0x10
  11650. 0x40001348: a8c173fb ldp x27, x28, [sp], #0x10
  11651. 0x4000134c: a8c17bfd ldp x29, x30, [sp], #0x10
  11652. 0x40001350: d69f03e0 eret
  11653. Exception return from AArch64 EL1 to AArch64 EL1 PC 0x4000209c
  11654. ----------------
  11655. IN: main
  11656. 0x4000209c: d0000040 adrp x0, #0x4000c000
  11657. ....
  11658. which does an `eret` and jumps back to 0x4000209c, which is 4 bytes and therefore one instruction after where SVC was taken at 0x40002098.
  11659. In QEMU, and then we just continue running from the exception handler address.
  11660. On the terminal output, we observe the initial values of:
  11661. * DAIF: 0x3c0, i.e. 4 bits (6 to 9) set to 1, which means that exceptions are masked for each exception type: Synchronous, System error, IRQ and FIQ.
  11662. +
  11663. This reset value is defined by <<armarm8>> C5.2.2 "DAIF, Interrupt Mask Bits".
  11664. * SPSel: 0x1, which means: use SPx instead of SP0.
  11665. +
  11666. This reset value is defined by <<armarm8>> C5.2.16 "SPSel, Stack Pointer Select".
  11667. * VBAR_EL1: 0x0 holds the base address of the vector table
  11668. +
  11669. This reset value is defined UNKNOWN by <<armarm8>> D10.2.116 "VBAR_EL1, Vector Base Address Register (EL1)", so we must set it to something ourselves to have greater portability.
  11670. Bibliography:
  11671. * https://github.com/torvalds/linux/blob/v4.20/arch/arm64/kernel/entry.S#L430 this is where the kernel defines the vector table
  11672. * https://github.com/dwelch67/qemu_arm_samples/tree/07162ba087111e0df3f44fd857d1b4e82458a56d/swi01
  11673. * https://github.com/NienfengYao/armv8-bare-metal/blob/572c6f95880e70aa92fe9fed4b8ad7697082a764/vector.S#L168
  11674. * https://stackoverflow.com/questions/24162109/arm-assembly-code-and-svc-numbering/57064062#57064062
  11675. * https://stackoverflow.com/questions/44991264/armv8-exception-vectors-and-handling
  11676. ===== ARMv8 exception vector table format
  11677. The vector table format is described on <<armarm8>> Table D1-7 "Vector offsets from vector table base address".
  11678. A good representation of the format of the vector table can also be found at <<armv8-programmers-guide>> Table 10-2 "Vector table offsets from vector table base address".
  11679. The first part of the table contains: xref:table-armv8-vector-handlers[xrefstyle=full].
  11680. [[table-armv8-vector-handlers]]
  11681. .Summary of ARMv8 vector handlers
  11682. [options="header"]
  11683. |===
  11684. |Address |Exception type |Description
  11685. |VBAR_ELn + 0x000
  11686. |Synchronous
  11687. |Current EL with SP0
  11688. |VBAR_ELn + 0x080
  11689. |IRQ/vIRQ
  11690. |Current EL with SP0
  11691. |VBAR_ELn + 0x100
  11692. |FIQ/vFIQ
  11693. |Current EL with SP0
  11694. |VBAR_ELn + 0x180
  11695. |SError/vSError
  11696. |Current EL with SP0
  11697. |VBAR_ELn + 0x200
  11698. |Synchronous
  11699. |Current EL with SPx
  11700. |VBAR_ELn + 0x280
  11701. |IRQ/vIRQ
  11702. |Current EL with SPx
  11703. |VBAR_ELn + 0x300
  11704. |FIQ/vFIQ
  11705. |Current EL with SPx
  11706. |VBAR_ELn + 0x380
  11707. |SError/vSError
  11708. |Lower EL using AArch64
  11709. |VBAR_ELn + 0x400
  11710. |Synchronous
  11711. |Lower EL using AArch64
  11712. |VBAR_ELn + 0x480
  11713. |IRQ/vIRQ
  11714. |Lower EL using AArch64
  11715. |VBAR_ELn + 0x500
  11716. |FIQ/vFIQ
  11717. |Lower EL using AArch64
  11718. |VBAR_ELn + 0x580
  11719. |SError/vSError
  11720. |Lower EL using AArch64
  11721. |VBAR_ELn + 0x600
  11722. |Synchronous
  11723. |Lower EL using AArch32
  11724. |VBAR_ELn + 0x680
  11725. |IRQ/vIRQ
  11726. |Lower EL using AArch32
  11727. |VBAR_ELn + 0x700
  11728. |FIQ/vFIQ
  11729. |Lower EL using AArch32
  11730. |VBAR_ELn + 0x780
  11731. |SError/vSError
  11732. |Lower EL using AArch32
  11733. |===
  11734. and the following other parts are analogous, but referring to SPx and lower ELs.
  11735. Now, to fully understand this table, we need the following concepts:
  11736. * Synchronous: what happens for example when we do an <<arm-svc-instruction>>.
  11737. +
  11738. It is called synchronous because the CPU is generating it itself from an instruction, unlike an interrupt generated by a device like a keyboard, which ends up in an IRQ or FIQ
  11739. * IRQ: an example can be found at: <<arm-timer>>
  11740. * TODO FIQ vs IRQ
  11741. * TODO SError
  11742. * EL changes: <<arm-change-exception-level>>
  11743. * SP0 vs SPx: <<arm-sp0-vs-spx>>.
  11744. ===== ARM ESR register
  11745. Exception Syndrome Register.
  11746. See example at: xref:arm-svc-instruction[xrefstyle=full]
  11747. Documentation: <<armarm8-db>> D12.2.36 "ESR_EL1, Exception Syndrome Register (EL1)".
  11748. ===== ARM ELR register
  11749. Exception Link Register.
  11750. See the example at: xref:arm-svc-instruction[xrefstyle=full]
  11751. ==== ARM multicore
  11752. Examples:
  11753. ....
  11754. ./run --arch aarch64 --baremetal baremetal/arch/aarch64/no_bootloader/multicore_asm.S --cpus 2
  11755. ./run --arch aarch64 --baremetal baremetal/arch/aarch64/no_bootloader/multicore_asm.S --cpus 2 --emulator gem5
  11756. ./run --arch aarch64 --baremetal baremetal/arch/aarch64/multicore.c --cpus 2
  11757. ./run --arch aarch64 --baremetal baremetal/arch/aarch64/multicore.c --cpus 2 --emulator gem5
  11758. ./run --arch arm --baremetal baremetal/arch/arm/no_bootloader/multicore_asm.S --cpus 2
  11759. ./run --arch arm --baremetal baremetal/arch/arm/no_bootloader/multicore_asm.S --cpus 2 --emulator gem5
  11760. # TODO not working, hangs.
  11761. # ./run --arch arm --baremetal baremetal/arch/arm/multicore.c --cpus 2
  11762. ./run --arch arm --baremetal baremetal/arch/arm/multicore.c --cpus 2 --emulator gem5
  11763. ....
  11764. Sources:
  11765. * link:baremetal/arch/aarch64/no_bootloader/multicore_asm.S[]
  11766. * link:baremetal/arch/aarch64/multicore.c[]
  11767. * link:baremetal/arch/arm/no_bootloader/multicore_asm.S[]
  11768. * link:baremetal/arch/arm/multicore.c[]
  11769. CPU 0 of this program enters a spinlock loop: it repeatedly checks if a given memory address is 1.
  11770. So, we need CPU 1 to come to the rescue and set that memory address to 1, otherwise CPU 0 will be stuck there forever!
  11771. Don't believe me? Then try:
  11772. ....
  11773. ./run --arch aarch64 --baremetal baremetal/arch/aarch64/multicore.c --cpus 1
  11774. ....
  11775. and watch it hang forever.
  11776. Note that if you try the same thing on gem5:
  11777. ....
  11778. ./run --arch aarch64 --baremetal baremetal/arch/aarch64/multicore.c --cpus 1 --emulator gem5
  11779. ....
  11780. then the gem5 actually exits with <<gem5-simulate-limit-reached>> as opposed to the expected:
  11781. ....
  11782. Exiting @ tick 36500 because m5_exit instruction encountered
  11783. ....
  11784. since gem5 is able to detect when nothing will ever happen, and exits.
  11785. When GDB step debugging, switch between cores with the usual `thread` commands, see also: xref:gdb-step-debug-multicore-userland[xrefstyle=full].
  11786. Bibliography: https://stackoverflow.com/questions/980999/what-does-multicore-assembly-language-look-like/33651438#33651438
  11787. ===== ARM WFE and SEV instructions
  11788. The WFE and SEV instructions are just hints: a compliant implementation can treat them as NOPs.
  11789. However, likely no implementation likely does (TODO confirm), since:
  11790. * WFE puts the core in a low power mode
  11791. * SEV wakes up cores from a low power mode
  11792. and power consumption is key in ARM applications.
  11793. In QEMU 3.0.0, SEV is a NOPs, and WFE might be, but I'm not sure, see: https://github.com/qemu/qemu/blob/v3.0.0/target/arm/translate-a64.c#L1423
  11794. ....
  11795. case 2: /* WFE */
  11796. if (!(tb_cflags(s->base.tb) & CF_PARALLEL)) {
  11797. s->base.is_jmp = DISAS_WFE;
  11798. }
  11799. return;
  11800. case 4: /* SEV */
  11801. case 5: /* SEVL */
  11802. /* we treat all as NOP at least for now */
  11803. return;
  11804. ....
  11805. TODO: what does the WFE code do? How can it not be a NOP if SEV is a NOP? https://github.com/qemu/qemu/blob/v3.0.0/target/arm/translate.c#L4609 might explain why, but it is Chinese to me (I only understand 30% ;-)):
  11806. ....
  11807. * For WFI we will halt the vCPU until an IRQ. For WFE and YIELD we
  11808. * only call the helper when running single threaded TCG code to ensure
  11809. * the next round-robin scheduled vCPU gets a crack. In MTTCG mode we
  11810. * just skip this instruction. Currently the SEV/SEVL instructions
  11811. * which are *one* of many ways to wake the CPU from WFE are not
  11812. * implemented so we can't sleep like WFI does.
  11813. */
  11814. ....
  11815. For gem5 however, if we comment out the SVE instruction, then it actually exits with `simulate() limit reached`, so the CPU truly never wakes up, which is a more realistic behaviour.
  11816. The following Raspberry Pi bibliography helped us get this sample up and running:
  11817. * https://github.com/bztsrc/raspi3-tutorial/tree/a3f069b794aeebef633dbe1af3610784d55a0efa/02_multicorec
  11818. * https://github.com/dwelch67/raspberrypi/tree/a09771a1d5a0b53d8e7a461948dc226c5467aeec/multi00
  11819. * https://github.com/LdB-ECM/Raspberry-Pi/blob/3b628a2c113b3997ffdb408db03093b2953e4961/Multicore/SmartStart64.S
  11820. * https://github.com/LdB-ECM/Raspberry-Pi/blob/3b628a2c113b3997ffdb408db03093b2953e4961/Multicore/SmartStart32.S
  11821. ===== ARM PSCI
  11822. In QEMU, CPU 1 starts in a halted state. This can be observed from GDB, where:
  11823. ....
  11824. info threads
  11825. ....
  11826. shows something like:
  11827. ....
  11828. * 1 Thread 1 (CPU#0 [running]) lkmc_start
  11829. 2 Thread 2 (CPU#1 [halted ]) lkmc_start
  11830. ....
  11831. To wake up CPU 1 on QEMU, we must use the Power State Coordination Interface (PSCI) which is documented at: https://developer.arm.com/docs/den0022/latest/arm-power-state-coordination-interface-platform-design-document[].
  11832. This interface uses HVC calls, and the calling convention is documented at "SMC CALLING CONVENTION" https://developer.arm.com/docs/den0028/latest[].
  11833. If we boot the Linux kernel on QEMU and <<get-device-tree-from-a-running-kernel,dump the auto-generated device tree>>, we observe that it contains the address of the PSCI CPU_ON call:
  11834. ....
  11835. psci {
  11836. method = "hvc";
  11837. compatible = "arm,psci-0.2", "arm,psci";
  11838. cpu_on = <0xc4000003>;
  11839. migrate = <0xc4000005>;
  11840. cpu_suspend = <0xc4000001>;
  11841. cpu_off = <0x84000002>;
  11842. };
  11843. ....
  11844. The Linux kernel wakes up the secondary cores in this exact same way at: https://github.com/torvalds/linux/blob/v4.19/drivers/firmware/psci.c#L122 We first actually got it working here by grepping the kernel and step debugging that call :-)
  11845. In gem5, CPU 1 starts woken up from the start, so PSCI is not needed. TODO gem5 actually blows up if we try to do the HVC call, understand why.
  11846. Bibliography: https://stackoverflow.com/questions/20055754/arm-start-wakeup-bringup-the-other-cpu-cores-aps-and-pass-execution-start-addre/53473447#53473447
  11847. ===== ARM DMB instruction
  11848. TODO: create and study a minimal examples in gem5 where the DMB instruction leads to less cycles: https://stackoverflow.com/questions/15491751/real-life-use-cases-of-barriers-dsb-dmb-isb-in-arm
  11849. ==== ARM timer
  11850. The ARM timer is the simplest way to generate hardware interrupts periodically, and therefore serves as the simples example of <<arm-gic>> usage.
  11851. Working on QEMU: link:baremetal/arch/aarch64/timer.c[]
  11852. ....
  11853. ./run --arch aarch64 --baremetal baremetal/arch/aarch64/timer.c
  11854. ....
  11855. Output at lkmc d8dae268c0a3e4e361002aca3b382fedd77f2567 + 1:
  11856. ....
  11857. cntv_ctl_el0 0x0
  11858. cntfrq_el0 0x3B9ACA0
  11859. cntv_cval_el0 0x0
  11860. cntvct_el0 0x105113
  11861. cntvct_el0 0x1080BC
  11862. cntvct_el0 0x10A118
  11863. IRQ number 0x1B
  11864. cntvct_el0 0x14D25B
  11865. cntv_cval_el0 0x3CE9CD6
  11866. IRQ number 0x1B
  11867. cntvct_el0 0x3CF516F
  11868. cntv_cval_el0 0x7893217
  11869. IRQ number 0x1B
  11870. cntvct_el0 0x789B733
  11871. cntv_cval_el0 0xB439642
  11872. ....
  11873. and new `IRQ number` section appears every second, when a clock interrupt is raised!
  11874. TODO make work on gem5. Fails with <<gem5-simulate-limit-reached>> at the first WFI done in main, which means that the interrupt is never raised.
  11875. Once an interrupt is raised, the interrupt itself sets up a new interrupt to happen in one second in the future after `cntv_cval_el0` is reached by the counter.
  11876. The timer is part of the aarch64 specification itself and is documented at: <<armarm8-db>> Chapter D10 "The Generic Timer in AArch64 state". The key registers to keep in mind are:
  11877. * `CNTVCT_EL0`: "Counter-timer Virtual Count register". The increasing current counter value.
  11878. * `CNTFRQ_EL0`: "Counter-timer Frequency register". "Indicates the system counter clock frequency, in Hz."
  11879. * `CNTV_CTL_EL0`: "Counter-timer Virtual Timer Control register". This control register is very simple and only has three fields:
  11880. ** `CNTV_CTL_EL0.ISTATUS` bit: set to 1 when the timer condition is met
  11881. ** `CNTV_CTL_EL0.IMASK` bit: if 1, the interrupt does not happen when `ISTATUS` becomes one
  11882. ** `CNTV_CTL_EL0.ENABLE` bit: if 0, the counter is turned off, interrupts don't happen
  11883. * `CNTV_CVAL_EL0`: "Counter-timer Virtual Timer CompareValue register". The interrupt happens when `CNTVCT_EL0` reaches the value in this register.
  11884. Due to <<gem5-vs-qemu,QEMU's non-determinism>>, each consecutive run has slightly different output values.
  11885. From the terminal output, we can see that the initial clock frequency is 0x3B9ACA0 == 62500000 Hz == 62.5MHz. Grepping QEMU source for that string leads us to:
  11886. ....
  11887. /* Scale factor for generic timers, ie number of ns per tick.
  11888. * This gives a 62.5MHz timer.
  11889. */
  11890. #define GTIMER_SCALE 16
  11891. ....
  11892. which in turn is used to set the initial reset value of the clock:
  11893. ....
  11894. { .name = "CNTFRQ_EL0", .state = ARM_CP_STATE_AA64,
  11895. .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 0,
  11896. .access = PL1_RW | PL0_R, .accessfn = gt_cntfrq_access,
  11897. .fieldoffset = offsetof(CPUARMState, cp15.c14_cntfrq),
  11898. .resetvalue = (1000 * 1000 * 1000) / GTIMER_SCALE,
  11899. ....
  11900. where `(1000 * 1000 * 1000) / 16 == 62500000`.
  11901. Trying to set the frequency on QEMU by writing to the CNTFRQ register does change the value of future reads, but has no effect on the actual clock frequency as commented on the QEMU source code https://github.com/qemu/qemu/blob/v4.0.0/target/arm/helper.c#L2647
  11902. ....
  11903. static const ARMCPRegInfo generic_timer_cp_reginfo[] = {
  11904. /* Note that CNTFRQ is purely reads-as-written for the benefit
  11905. * of software; writing it doesn't actually change the timer frequency.
  11906. * Our reset value matches the fixed frequency we implement the timer at.
  11907. */
  11908. { .name = "CNTFRQ", .cp = 15, .crn = 14, .crm = 0, .opc1 = 0, .opc2 = 0,
  11909. .type = ARM_CP_ALIAS,
  11910. .access = PL1_RW | PL0_R, .accessfn = gt_cntfrq_access,
  11911. .fieldoffset = offsetoflow32(CPUARMState, cp15.c14_cntfrq),
  11912. },
  11913. ....
  11914. At each interrupt, we increase the compare value `CVAL` by about 1x the clock frequency 0x3B9ACA0 so that it will fire again in one second, e.g. `0x3CE9CD6 - 0x14D25B == 3B9CA7B`. The increment is not perfect because the counter keeps ticking even while our register read and print instructions are running inside the interrupt handler!
  11915. We then observe that the next interrupt happens soon after CNTV_CVAL_EL0 is reached by CNTVCT_EL0:
  11916. ....
  11917. cntv_cval_el0 0x3CE9CD6
  11918. IRQ number 0x1B
  11919. cntvct_el0 0x3CF516F
  11920. ....
  11921. Bibliography:
  11922. * https://stackoverflow.com/questions/51094092/how-to-make-timer-irq-work-on-qemu-machine-virt-cpu-cortex-a57
  11923. * https://stackoverflow.com/questions/44198483/arm-timers-and-interrupts
  11924. ==== ARM GIC
  11925. Generic Interrupt Controller.
  11926. Examples:
  11927. * xref:arm-timer[]
  11928. ARM publishes both a GIC standard architecture specification, and specific implementations of these specifications.
  11929. The specification can be found at: https://developer.arm.com/docs/ihi0069/latest
  11930. As of 2019Q2 the latest version if v4.0, often called GICv4: https://static.docs.arm.com/ihi0069/e/Q1-IHI0069E_gic_architecture_specification_v3.1_19_01_21.pdf
  11931. That document clarifies that GICv2 is a legacy specification only:
  11932. ....
  11933. Version 2.0 (GICv2) is only described in terms of the GICv3 optional support for legacy operation
  11934. ....
  11935. The specific models have names of type GIC-600, GIC-500, etc.
  11936. In QEMU v4.0.0, the GICv3 can be selected with an extra `-machine gic_version=3` option.
  11937. In gem5 3126e84db773f64e46b1d02a9a27892bf6612d30, the GIC is determined by selecting the platform as explained at: <<gem5-arm-platforms>>.
  11938. ==== ARM paging
  11939. TODO create a minimal working aarch64 example analogous to the x86 one at: https://github.com/cirosantilli/x86-bare-metal-examples/blob/6dc9a73830fc05358d8d66128f740ef9906f7677/paging.S
  11940. A general introduction to paging with x86 examples can be found at: https://cirosantilli.com/x86-paging[].
  11941. ARM paging is documented at <<armarm8-db>> Chapter D5 and is mostly called VMSAv8 in the ARMv8 manual (Virtual Memory System Architecture).
  11942. Paging is enabled by the `SCTLR_EL1.M` bit.
  11943. The base table address is selected by the register documented at <<armarm8-db>> D12.2.111 "TTBR0_EL1, Translation Table Base Register 0 (EL1)".
  11944. There is also a `TTBR1_EL1` register, which is for the second translation stage to speed up virtualization: https://en.wikipedia.org/wiki/Second_Level_Address_Translation and will not be used in this section.
  11945. The translation types are described at: <<armarm8-db>> D5.2.4 "Memory translation granule size".
  11946. From this we can see that the translation scheme uses up to 4 levels (0 to 3) and has possible granule sizes 4KiB, 16KiB and 64KiB.
  11947. Page table formats are described at <<armarm8-db>> D5.3.1 "VMSAv8-64 translation table level 0, level 1, and level 2 descriptor formats".
  11948. ==== ARM baremetal bibliography
  11949. First, also consider the userland bibliography: xref:arm-assembly-bibliography[xrefstyle=full].
  11950. The most useful ARM baremetal example sets we've seen so far are:
  11951. * https://github.com/dwelch67/raspberrypi real hardware
  11952. * https://github.com/dwelch67/qemu_arm_samples QEMU `-m vexpress`
  11953. * https://github.com/bztsrc/raspi3-tutorial real hardware + QEMU `-m raspi`
  11954. * https://github.com/LdB-ECM/Raspberry-Pi real hardware
  11955. * https://github.com/BrianSidebotham/arm-tutorial-rpi
  11956. ===== NienfengYao/armv8-bare-metal
  11957. https://github.com/NienfengYao/armv8-bare-metal
  11958. The only QEMU `-m virt` aarch64 example set that I can find on the web. Awesome.
  11959. A large part of the code is taken from the awesome educational OS under 2-clause BSD as can be seen from file headers: https://github.com/takeharukato/sample-tsk-sw/tree/ce7973aa5d46c9eedb58309de43df3b09d4f8d8d/hal/aarch64 but Nienfeng largely minimized it.
  11960. I needed the following minor patches: https://github.com/NienfengYao/armv8-bare-metal/pull/1
  11961. Handles an SVC and setups and handles the timer about once per second.
  11962. The source claims GICv3, however if I try to add `-machine gic_version=3` on their command line with our QEMU v4.0.0, then it blows up at:
  11963. ....
  11964. static void init_gicc(void)
  11965. {
  11966. uint32_t pending_irq;
  11967. /* Disable CPU interface */
  11968. *REG_GIC_GICC_CTLR = GICC_CTLR_DISABLE;
  11969. ....
  11970. which tries to write to 0x8010000 according to GDB.
  11971. Without `-machine`, QEMU's DTB clearly states GICv2, so I'm starting to wonder if Nienfeng just made a mistake there? The QEMU GICv3 DTB contains:
  11972. ....
  11973. reg = <0x0 0x8000000 0x0 0x10000 0x0 0x80a0000 0x0 0xf60000>;
  11974. ....
  11975. and the GICv2 one:
  11976. ....
  11977. reg = <0x0 0x8000000 0x0 0x10000 0x0 0x8010000 0x0 0x10000>;
  11978. ....
  11979. which further confirms that the exception is correct: v2 has a register range at 0x8010000 while in v3 it moved to 0x80a0000 and 0x8010000 is empty.
  11980. The original source does not mention GICv3 anywhere, only https://github.com/takeharukato/sample-tsk-sw/blob/c7bbc9dce6b14660bcce8d20735f8c6ebb09396b/hal/aarch64/gic-pl390.c[pl390], which is a specific GIC model that predates the GICv2 spec I believe.
  11981. TODO if I hack `#define GIC_GICC_BASE (GIC_BASE + 0xa0000)`, then it goes a bit further, but the next loop never ends.
  11982. ===== tukl-msd/gem5.bare-metal
  11983. https://github.com/tukl-msd/gem5.bare-metal
  11984. Reiterated at: https://stackoverflow.com/questions/43682311/uart-communication-in-gem5-with-arm-bare-metal
  11985. Basic gem5 aarch64 baremetal setup that just works. Does serial IO and timer through GICv2. Usage:
  11986. ....
  11987. # Build gem5.
  11988. git clone https://gem5.googlesource.com/public/gem5
  11989. cd gem5
  11990. git checkout 60600f09c25255b3c8f72da7fb49100e2682093a
  11991. scons --ignore-style -j`nproc` build/ARM/gem5.opt
  11992. cd ..
  11993. # Build example.
  11994. sudo apt-get install gcc-arm-none-eabi
  11995. git clone https://github.com/tukl-msd/gem5.bare-metal
  11996. cd gem5.bare-metal
  11997. git checkout 6ad1069d4299b775b5491e9252739166bfac9bfe
  11998. cd Simple
  11999. make CROSS_COMPILE_DIR=/usr/bin
  12000. # Run example.
  12001. ../../gem5/default/build/ARM/gem5.opt' \
  12002. ../../gem5/configs/example/fs.py' \
  12003. --bare-metal \
  12004. --disk-image="$(pwd)/../common/fake.iso" \
  12005. --kernel="$(pwd)/main.elf" \
  12006. --machine-type=RealView_PBX \
  12007. --mem-size=256MB \
  12008. ;
  12009. ....
  12010. === How we got some baremetal stuff to work
  12011. It is nice when thing just work.
  12012. But you can also learn a thing or two from how I actually made them work in the first place.
  12013. ==== Find the UART address
  12014. Enter the QEMU console:
  12015. ....
  12016. Ctrl-X C
  12017. ....
  12018. Then do:
  12019. ....
  12020. info mtree
  12021. ....
  12022. And look for `pl011`:
  12023. ....
  12024. 0000000009000000-0000000009000fff (prio 0, i/o): pl011
  12025. ....
  12026. On gem5, it is easy to find it on the source. We are using the machine `RealView_PBX`, and a quick grep leads us to: https://github.com/gem5/gem5/blob/a27ce59a39ec8fa20a3c4e9fa53e9b3db1199e91/src/dev/arm/RealView.py#L615
  12027. ....
  12028. class RealViewPBX(RealView):
  12029. uart = Pl011(pio_addr=0x10009000, int_num=44)
  12030. ....
  12031. ==== aarch64 baremetal NEON setup
  12032. Inside link:baremetal/lib/aarch64.S[] there is a chunk of code that enables floating point operations:
  12033. ....
  12034. mov x1, 0x3 << 20
  12035. msr cpacr_el1, x1
  12036. isb
  12037. ....
  12038. CPACR_EL1 is documented at <<armarm8>> D10.2.29 "CPACR_EL1, Architectural Feature Access Control Register".
  12039. Here we touch the CPACR_EL1.FPEN bits to 3, which enable floating point operations:
  12040. ____
  12041. 11 This control does not cause any instructions to be trapped.
  12042. ____
  12043. We later also added an enable for the CPACR_EL1.ZEN bits, which are needed for <<arm-sve>>.
  12044. Without CPACR_EL1.FPEN, the `printf`:
  12045. ....
  12046. printf("got: %c\n", c);
  12047. ....
  12048. compiled to a:
  12049. ....
  12050. str q0, [sp, #80]
  12051. ....
  12052. which uses NEON registers, and goes into an exception loop.
  12053. It was a bit confusing because there was a previous `printf`:
  12054. ....
  12055. printf("enter a character\n");
  12056. ....
  12057. which did not blow up because GCC compiles it into `puts` directly since it has no arguments, and that does not generate NEON instructions.
  12058. The last instructions ran was found with:
  12059. ....
  12060. while(1)
  12061. stepi
  12062. end
  12063. ....
  12064. or by hacking the QEMU CLI to contain:
  12065. .....
  12066. -D log.log -d in_asm
  12067. .....
  12068. I could not find any previous NEON instruction executed so this led me to suspect that some NEON initialization was required:
  12069. * http://infocenter.arm.com/help/topic/com.arm.doc.dai0527a/DAI0527A_baremetal_boot_code_for_ARMv8_A_processors.pdf "Bare-metal Boot Code for ARMv8-A Processors"
  12070. * https://community.arm.com/processors/f/discussions/5409/how-to-enable-neon-in-cortex-a8
  12071. * https://stackoverflow.com/questions/19231197/enable-neon-on-arm-cortex-a-series
  12072. We then tried to copy the code from the "Bare-metal Boot Code for ARMv8-A Processors" document:
  12073. ....
  12074. // Disable trapping of accessing in EL3 and EL2.
  12075. MSR CPTR_EL3, XZR
  12076. MSR CPTR_EL3, XZR
  12077. // Disable access trapping in EL1 and EL0.
  12078. MOV X1, #(0x3 << 20) // FPEN disables trapping to EL1.
  12079. MSR CPACR_EL1, X1
  12080. ISB
  12081. ....
  12082. but it entered an exception loop at `MSR CPTR_EL3, XZR`.
  12083. We then found out that QEMU <<arm-exception-levels,starts in EL1>>, and so we kept just the EL1 part, and it worked. Related:
  12084. * https://stackoverflow.com/questions/42824706/qemu-system-aarch64-entering-el1-when-emulating-a53-power-up
  12085. * https://stackoverflow.com/questions/37299524/neon-support-in-armv8-system-mode-qemu
  12086. === Baremetal tests
  12087. Baremetal tests work exactly like <<user-mode-tests>>, except that you have to add the `--mode baremetal` option, for example:
  12088. ....
  12089. ./test-executables --mode baremetal --arch aarch64
  12090. ....
  12091. In baremetal, we detect if tests failed by parsing logs for the <<magic-failure-string>>.
  12092. See: xref:test-this-repo[xrefstyle=full] for more useful testing tips.
  12093. == Android
  12094. Remember: Android AOSP is a huge undocumented piece of bloatware. It's integration into this repo will likely never be super good.
  12095. Verbose setup description: https://stackoverflow.com/questions/1809774/how-to-compile-the-android-aosp-kernel-and-test-it-with-the-android-emulator/48310014#48310014
  12096. Download, build and run with the prebuilt AOSP QEMU emulator and the AOSP kernel:
  12097. ....
  12098. ./build-android \
  12099. --android-base-dir /path/to/your/hd \
  12100. --android-version 8.1.0_r60 \
  12101. download \
  12102. build \
  12103. ;
  12104. ./run-android \
  12105. --android-base-dir /path/to/your/hd \
  12106. --android-version 8.1.0_r60 \
  12107. ;
  12108. ....
  12109. Sources:
  12110. * link:build-android[]
  12111. * link:run-android[]
  12112. TODO how to hack the AOSP kernel, userland and emulator?
  12113. Other archs work as well as usual with `--arch` parameter. However, running in non-x86 is very slow due to the lack of KVM.
  12114. Tested on: `8.1.0_r60`.
  12115. === Android image structure
  12116. https://source.android.com/devices/bootloader/partitions-images
  12117. The messy AOSP generates a ton of images instead of just one.
  12118. When the emulator launches, we can see them through QEMU `-drive` arguments:
  12119. ....
  12120. emulator: argv[21] = "-initrd"
  12121. emulator: argv[22] = "/data/aosp/8.1.0_r60/out/target/product/generic_x86_64/ramdisk.img"
  12122. emulator: argv[23] = "-drive"
  12123. emulator: argv[24] = "if=none,index=0,id=system,file=/path/to/aosp/8.1.0_r60/out/target/product/generic_x86_64/system-qemu.img,read-only"
  12124. emulator: argv[25] = "-device"
  12125. emulator: argv[26] = "virtio-blk-pci,drive=system,iothread=disk-iothread,modern-pio-notify"
  12126. emulator: argv[27] = "-drive"
  12127. emulator: argv[28] = "if=none,index=1,id=cache,file=/path/to/aosp/8.1.0_r60/out/target/product/generic_x86_64/cache.img.qcow2,overlap-check=none,cache=unsafe,l2-cache-size=1048576"
  12128. emulator: argv[29] = "-device"
  12129. emulator: argv[30] = "virtio-blk-pci,drive=cache,iothread=disk-iothread,modern-pio-notify"
  12130. emulator: argv[31] = "-drive"
  12131. emulator: argv[32] = "if=none,index=2,id=userdata,file=/path/to/aosp/8.1.0_r60/out/target/product/generic_x86_64/userdata-qemu.img.qcow2,overlap-check=none,cache=unsafe,l2-cache-size=1048576"
  12132. emulator: argv[33] = "-device"
  12133. emulator: argv[34] = "virtio-blk-pci,drive=userdata,iothread=disk-iothread,modern-pio-notify"
  12134. emulator: argv[35] = "-drive"
  12135. emulator: argv[36] = "if=none,index=3,id=encrypt,file=/path/to/aosp/8.1.0_r60/out/target/product/generic_x86_64/encryptionkey.img.qcow2,overlap-check=none,cache=unsafe,l2-cache-size=1048576"
  12136. emulator: argv[37] = "-device"
  12137. emulator: argv[38] = "virtio-blk-pci,drive=encrypt,iothread=disk-iothread,modern-pio-notify"
  12138. emulator: argv[39] = "-drive"
  12139. emulator: argv[40] = "if=none,index=4,id=vendor,file=/path/to/aosp/8.1.0_r60/out/target/product/generic_x86_64/vendor-qemu.img,read-only"
  12140. emulator: argv[41] = "-device"
  12141. emulator: argv[42] = "virtio-blk-pci,drive=vendor,iothread=disk-iothread,modern-pio-notify"
  12142. ....
  12143. The root directory is the <<initrd>> given on the QEMU CLI, which `/proc/mounts` reports at:
  12144. ....
  12145. rootfs on / type rootfs (ro,seclabel,size=886392k,nr_inodes=221598)
  12146. ....
  12147. This contains the <<android-init>>, which through `.rc` must be mounting mounts the drives int o the right places TODO find exact point.
  12148. The drive order is:
  12149. ....
  12150. system
  12151. cache
  12152. userdata
  12153. encryptionkey
  12154. vendor-qemu
  12155. ....
  12156. Then, on the terminal:
  12157. ....
  12158. mount | grep vd
  12159. ....
  12160. gives:
  12161. ....
  12162. /dev/block/vda1 on /system type ext4 (ro,seclabel,relatime,data=ordered)
  12163. /dev/block/vde1 on /vendor type ext4 (ro,seclabel,relatime,data=ordered)
  12164. /dev/block/vdb on /cache type ext4 (rw,seclabel,nosuid,nodev,noatime,errors=panic,data=ordered)
  12165. ....
  12166. and we see that the order of `vda`, `vdb`, etc. matches that in which `-drive` were given to QEMU.
  12167. Tested on: `8.1.0_r60`.
  12168. ==== Android images read-only
  12169. From `mount`, we can see that some of the mounted images are `ro`.
  12170. Basically, every image that was given to QEMU as qcow2 is writable, and that qcow2 is an overlay over the actual original image.
  12171. In order to make `/system` and `/vendor` writable by using qcow2 for them as well, we must use the `-writable-system` option:
  12172. ....
  12173. ./run-android -- -writable-system
  12174. ....
  12175. * https://android.stackexchange.com/questions/110927/how-to-mount-system-rewritable-or-read-only-rw-ro/207200#207200
  12176. * https://stackoverflow.com/questions/13089694/adb-remount-permission-denied-but-able-to-access-super-user-in-shell-android/43163693#43163693
  12177. then:
  12178. ....
  12179. su
  12180. mount -o rw,remount /system
  12181. date >/system/a
  12182. ....
  12183. Now reboot, and relaunch with `-writable-system` once again to pick up the modified qcow2 images:
  12184. ....
  12185. ./run-android -- -writable-system
  12186. ....
  12187. and the newly created file is still there:
  12188. ....
  12189. date >/system/a
  12190. ....
  12191. `/system` and `/vendor` can be nuked quickly with:
  12192. ....
  12193. ./build-android --extra-args snod
  12194. ./build-android --extra-args vnod
  12195. ....
  12196. as mentioned at: https://stackoverflow.com/questions/29023406/how-to-just-build-android-system-image and on:
  12197. ....
  12198. ./build-android --extra-args help
  12199. ....
  12200. Tested on: `8.1.0_r60`.
  12201. ==== Android /data partition
  12202. When I install an app like F-Droid, it goes under `/data` according to:
  12203. ....
  12204. find / -iname '*fdroid*'
  12205. ....
  12206. and it <<disk-persistency,persists across boots>>.
  12207. `/data` is behind a RW LVM device:
  12208. ....
  12209. /dev/block/dm-0 on /data type ext4 (rw,seclabel,nosuid,nodev,noatime,errors=panic,data=ordered)
  12210. ....
  12211. but TODO I can't find where it comes from since I don't have the CLI tools mentioned at:
  12212. * https://superuser.com/questions/131519/what-is-this-dm-0-device
  12213. * https://unix.stackexchange.com/questions/185057/where-does-lvm-store-its-configuration
  12214. However, by looking at:
  12215. ....
  12216. ./run-android -- -help
  12217. ....
  12218. we see:
  12219. ....
  12220. -data <file> data image (default <datadir>/userdata-qemu.img
  12221. ....
  12222. which confirms the suspicion that this data goes in `userdata-qemu.img`.
  12223. To reset images to their original state, just remove the qcow2 overlay and regenerate it: https://stackoverflow.com/questions/54446680/how-to-reset-the-userdata-image-when-building-android-aosp-and-running-it-on-the
  12224. Tested on: `8.1.0_r60`.
  12225. === Install Android apps
  12226. I don't know how to download files from the web on Vanilla android, the default browser does not download anything, and there is no `wget`:
  12227. * https://android.stackexchange.com/questions/6984/how-to-download-files-from-the-web-in-the-android-browser
  12228. * https://stackoverflow.com/questions/26775079/wget-in-android-terminal
  12229. Installing with `adb install` does however work: https://stackoverflow.com/questions/7076240/install-an-apk-file-from-command-prompt
  12230. https://f-droid.org[F-Droid] installed fine like that, however it does not have permission to install apps: https://www.maketecheasier.com/install-apps-from-unknown-sources-android/
  12231. And the `Settings` app crashes so I can't change it, logcat contains:
  12232. ....
  12233. No service published for: wifip2p
  12234. ....
  12235. which is mentioned at: https://stackoverflow.com/questions/47839955/android-8-settings-app-crashes-on-emulator-with-clean-aosp-build
  12236. We also tried to enable it from the command line with:
  12237. ....
  12238. settings put secure install_non_market_apps 1
  12239. ....
  12240. as mentioned at: https://android.stackexchange.com/questions/77280/allow-unknown-sources-from-terminal-without-going-to-settings-app but it didn't work either.
  12241. No person alive seems to know how to pre-install apps on AOSP: https://stackoverflow.com/questions/6249458/pre-installing-android-application
  12242. Tested on: `8.1.0_r60`.
  12243. === Android init
  12244. For Linux in general, see: xref:init[xrefstyle=full].
  12245. The `/init` executable interprets the `/init.rc` files, which is in a custom Android init system language: https://android.googlesource.com/platform/system/core/+/ee0e63f71d90537bb0570e77aa8a699cc222cfaf/init/README.md
  12246. The top of that file then sources other `.rc` files present on the root directory:
  12247. ....
  12248. import /init.environ.rc
  12249. import /init.usb.rc
  12250. import /init.${ro.hardware}.rc
  12251. import /vendor/etc/init/hw/init.${ro.hardware}.rc
  12252. import /init.usb.configfs.rc
  12253. import /init.${ro.zygote}.rc
  12254. ....
  12255. TODO: how is `ro.hardware` determined? https://stackoverflow.com/questions/20572781/android-boot-where-is-the-init-hardware-rc-read-in-init-c-where-are-servic It is a system property and can be obtained with:
  12256. ....
  12257. getprop ro.hardware
  12258. ....
  12259. This gives:
  12260. ....
  12261. ranchu
  12262. ....
  12263. which is the codename for the QEMU virtual platform we are running on: https://www.oreilly.com/library/view/android-system-programming/9781787125360/9736a97c-cd09-40c3-b14d-955717648302.xhtml
  12264. TODO: is it possible to add a custom `.rc` file without modifying the initrd that <<android-image-structure,gets mounted on root>>? https://stackoverflow.com/questions/9768103/make-persistent-changes-to-init-rc
  12265. Tested on: `8.1.0_r60`.
  12266. == Benchmark this repo
  12267. TODO: didn't fully port during refactor after 3b0a343647bed577586989fb702b760bd280844a. Reimplementing should not be hard.
  12268. In this section document how benchmark builds and runs of this repo, and how to investigate what the bottleneck is.
  12269. Ideally, we should setup an automated build server that benchmarks those things continuously for us, but our <<travis>> attempt failed.
  12270. So currently, we are running benchmarks manually when it seems reasonable and uploading them to: https://github.com/cirosantilli/linux-kernel-module-cheat-regression
  12271. All benchmarks were run on the <<p51>> machine, unless stated otherwise.
  12272. Run all benchmarks and upload the results:
  12273. ....
  12274. cd ..
  12275. git clone https://github.com/cirosantilli/linux-kernel-module-cheat-regression
  12276. cd -
  12277. ./bench-all -A
  12278. ....
  12279. === Continuous integraion
  12280. We have exploreed a few Continuous integration solutions.
  12281. We haven't setup any of them yet.
  12282. ==== Travis
  12283. We tried to automate it on Travis with link:.travis.yml[] but it hits the current 50 minute job timeout: https://travis-ci.org/cirosantilli/linux-kernel-module-cheat/builds/296454523 And I bet it would likely hit a disk maxout either way if it went on.
  12284. ==== CircleCI
  12285. This setup sucessfully built gem5 on every commit: link:.circleci/config.yml[]
  12286. Enabling it is however blocked on: https://github.com/cirosantilli/linux-kernel-module-cheat/issues/79 so we disabled the builds on the web UI.
  12287. If that ever gets done, we will also need to:
  12288. * convert this to a nightly with a workflow, to save server resources: https://circleci.com/docs/2.0/configuration-reference/#triggers
  12289. * download the prebuilt disk images and enable caches to save the images across runs
  12290. A build took about 1 hour of a core, and the free tier allows for 1000 minutes per month: https://circleci.com/pricing/ so about 17 hours. The cheapest non-free setup seems to be 50 dollars per month gets us infinite build minutes per month and 2 containers, so we could scale things to run in under 24 hours.
  12291. There is no result reporting web UI however... but neither does GitLab CI: https://gitlab.com/gitlab-org/gitlab-ce/issues/17081
  12292. === Benchmark this repo benchmarks
  12293. ==== Benchmark Linux kernel boot
  12294. Run all kernel boot benchmarks for one arch:
  12295. ....
  12296. ./build-test-boot --size 3 && ./test-boot --all-archs --all-emulators --size 3
  12297. cat "$(./getvar test_boot_benchmark_file)"
  12298. ....
  12299. Sample results at 8fb9db39316d43a6dbd571e04dd46ae73915027f:
  12300. ....
  12301. cmd ./run --arch x86_64 --eval './linux/poweroff.out'
  12302. time 8.25
  12303. exit_status 0
  12304. cmd ./run --arch x86_64 --eval './linux/poweroff.out' --kvm
  12305. time 1.22
  12306. exit_status 0
  12307. cmd ./run --arch x86_64 --eval './linux/poweroff.out' --trace exec_tb
  12308. time 8.83
  12309. exit_status 0
  12310. instructions 2244297
  12311. cmd ./run --arch x86_64 --eval 'm5 exit' --emulator gem5
  12312. time 213.39
  12313. exit_status 0
  12314. instructions 318486337
  12315. cmd ./run --arch arm --eval './linux/poweroff.out'
  12316. time 6.62
  12317. exit_status 0
  12318. cmd ./run --arch arm --eval './linux/poweroff.out' --trace exec_tb
  12319. time 6.90
  12320. exit_status 0
  12321. instructions 776374
  12322. cmd ./run --arch arm --eval 'm5 exit' --emulator gem5
  12323. time 118.46
  12324. exit_status 0
  12325. instructions 153023392
  12326. cmd ./run --arch arm --eval 'm5 exit' --emulator gem5 -- --cpu-type=HPI --caches --l2cache --l1d_size=1024kB --l1i_size=1024kB --l2_size=1024kB --l3_size=1024kB
  12327. time 2250.40
  12328. exit_status 0
  12329. instructions 151981914
  12330. cmd ./run --arch aarch64 --eval './linux/poweroff.out'
  12331. time 4.94
  12332. exit_status 0
  12333. cmd ./run --arch aarch64 --eval './linux/poweroff.out' --trace exec_tb
  12334. time 5.04
  12335. exit_status 0
  12336. instructions 233162
  12337. cmd ./run --arch aarch64 --eval 'm5 exit' --emulator gem5
  12338. time 70.89
  12339. exit_status 0
  12340. instructions 124346081
  12341. cmd ./run --arch aarch64 --eval 'm5 exit' --emulator gem5 -- --cpu-type=HPI --caches --l2cache --l1d_size=1024kB --l1i_size=1024kB --l2_size=1024kB --l3_size=1024kB
  12342. time 381.86
  12343. exit_status 0
  12344. instructions 124564620
  12345. cmd ./run --arch aarch64 --eval 'm5 exit' --emulator gem5 --gem5-build-type fast
  12346. time 58.00
  12347. exit_status 0
  12348. instructions 124346081
  12349. cmd ./run --arch aarch64 --eval 'm5 exit' --emulator gem5 --gem5-build-type debug
  12350. time 1022.03
  12351. exit_status 0
  12352. instructions 124346081
  12353. ....
  12354. TODO: aarch64 gem5 and QEMU use the same kernel, so why is the gem5 instruction count so much much higher?
  12355. ===== gem5 arm HPI boot takes much longer than aarch64
  12356. TODO 62f6870e4e0b384c4bd2d514116247e81b241251 takes 33 minutes to finish at 62f6870e4e0b384c4bd2d514116247e81b241251:
  12357. ....
  12358. cmd ./run --arch arm --eval 'm5 exit' --emulator gem5 -- --caches --cpu-type=HPI
  12359. ....
  12360. while aarch64 only 7 minutes.
  12361. I had previously documented on README 10 minutes at: 2eff007f7c3458be240c673c32bb33892a45d3a0 found with `git log` search for `10 minutes`. But then I checked out there, run it, and kernel panics before any messages come out. Lol?
  12362. Logs of the runs can be found at: https://github.com/cirosantilli-work/gem5-issues/tree/0df13e862b50ae20fcd10bae1a9a53e55d01caac/arm-hpi-slow
  12363. The cycle count is higher for `arm`, 350M vs 250M for `aarch64`, not nowhere near the 5x runtime time increase.
  12364. A quick look at the boot logs show that they are basically identical in structure: the same operations appear more ore less on both, and there isn't one specific huge time pit in arm: it is just that every individual operation seems to be taking a lot longer.
  12365. ===== gem5 x86_64 DerivO3CPU boot panics
  12366. https://github.com/cirosantilli-work/gem5-issues/issues/2
  12367. ....
  12368. Kernel panic - not syncing: Attempted to kill the idle task!
  12369. ....
  12370. ==== Benchmark emulators on userland executables
  12371. Let's see how fast our simulators are running some well known or easy to understand userland benchmarks!
  12372. TODO: would be amazing to have an automated guest instructions per second count, but I'm not sure how to do that nicely for QEMU: <<qemu-get-guest-instruction-count>>.
  12373. TODO: automate this further, produce the results table automatically, possibly by generalizing link:test-executables[].
  12374. For now we can just run on gem5 to estimate the instruction count per input size and extrapolate?
  12375. For example, the simplest scalable CPU content would be a busy loop: link:userland/gcc/busy_loop.c[], so let's focus on that for now.
  12376. Summary of manually collected results on <<p51>> at LKMC a18f28e263c91362519ef550150b5c9d75fa3679 + 1: xref:table-busy-loop-dmips[xrefstyle=full]. As expected, the less native / more detailed / more complex simulations are slower!
  12377. [[table-busy-loop-dmips]]
  12378. .Busy loop DMIPS for different simulator setups
  12379. [options="header"]
  12380. |===
  12381. |Simulator |Loops |Time (s) |Instruction count| Approximate MIPS
  12382. |`qemu --arch aarch64`
  12383. |10^10
  12384. |68
  12385. |1.1 * 10^11 (approx)
  12386. |2000
  12387. |`gem5 --arch aarch64`
  12388. |10^7
  12389. |100
  12390. |1.10018162 * 10^8
  12391. |1
  12392. |`+gem5 --arch aarch64 -- --cpu-type MinorCPU --caches+`
  12393. |10^6
  12394. |31
  12395. |1.1018152 * 10^7
  12396. |0.4
  12397. |`+gem5 --arch aarch64 -- --cpu-type DerivO3CPU --caches+`
  12398. |10^6
  12399. |52
  12400. |1.1018128 * 10^7
  12401. |0.2
  12402. |===
  12403. The first step is to determine a number of loops that will run long enough to have meaningful results, but not too long that we will get bored.
  12404. On our <<p51>> machine, we found 10^7 (10 million == 1000 times 10000) loops to be a good number:
  12405. ....
  12406. ./run --arch aarch64 --emulator gem5 --userland userland/gcc/busy_loop.c --userland-args '1000 10000' --static
  12407. ./get-stat sim_insts
  12408. ....
  12409. as it gives:
  12410. * time: 00:01:40
  12411. * instructions: 110018162 ~ 110 millions
  12412. so ~ 110 million instructions / 100 seconds makes ~ 1 MIPS (million instructions per second).
  12413. This experiment also suggests that each loop is about 11 instructions long (110M instructions / 10M loops), so we look at the disassembly:
  12414. ....
  12415. ./run-toolchain --arch aarch64 gdb -- -batch -ex 'disas busy_loop' "$(./getvar --arch aarch64 userland_build_dir)/gcc/busy_loop.out"
  12416. ....
  12417. which contains:
  12418. ....
  12419. 8 ) {
  12420. 0x0000000000400698 <+0>: ff 83 00 d1 sub sp, sp, #0x20
  12421. 0x000000000040069c <+4>: e0 07 00 f9 str x0, [sp, #8]
  12422. 0x00000000004006a0 <+8>: e1 03 00 f9 str x1, [sp]
  12423. 9 for (unsigned i = 0; i < max; i++) {
  12424. 0x00000000004006a4 <+12>: ff 1f 00 b9 str wzr, [sp, #28]
  12425. 0x00000000004006a8 <+16>: 11 00 00 14 b 0x4006ec <busy_loop+84>
  12426. 10 for (unsigned j = 0; j < max2; j++) {
  12427. 0x00000000004006ac <+20>: ff 1b 00 b9 str wzr, [sp, #24]
  12428. 0x00000000004006b0 <+24>: 08 00 00 14 b 0x4006d0 <busy_loop+56>
  12429. 11 __asm__ __volatile__ ("" : "+g" (j), "+g" (j) : :);
  12430. 0x00000000004006b4 <+28>: e1 1b 40 b9 ldr w1, [sp, #24]
  12431. 0x00000000004006b8 <+32>: e0 1b 40 b9 ldr w0, [sp, #24]
  12432. 0x00000000004006bc <+36>: e1 1b 00 b9 str w1, [sp, #24]
  12433. 0x00000000004006c0 <+40>: e0 17 00 b9 str w0, [sp, #20]
  12434. 10 for (unsigned j = 0; j < max2; j++) {
  12435. 0x00000000004006c4 <+44>: e0 17 40 b9 ldr w0, [sp, #20]
  12436. 0x00000000004006c8 <+48>: 00 04 00 11 add w0, w0, #0x1
  12437. 0x00000000004006cc <+52>: e0 1b 00 b9 str w0, [sp, #24]
  12438. 0x00000000004006d0 <+56>: e0 1b 40 b9 ldr w0, [sp, #24]
  12439. 0x00000000004006d4 <+60>: e1 03 40 f9 ldr x1, [sp]
  12440. 0x00000000004006d8 <+64>: 3f 00 00 eb cmp x1, x0
  12441. 0x00000000004006dc <+68>: c8 fe ff 54 b.hi 0x4006b4 <busy_loop+28> // b.pmore
  12442. 9 for (unsigned i = 0; i < max; i++) {
  12443. 0x00000000004006e0 <+72>: e0 1f 40 b9 ldr w0, [sp, #28]
  12444. 0x00000000004006e4 <+76>: 00 04 00 11 add w0, w0, #0x1
  12445. 0x00000000004006e8 <+80>: e0 1f 00 b9 str w0, [sp, #28]
  12446. 0x00000000004006ec <+84>: e0 1f 40 b9 ldr w0, [sp, #28]
  12447. 0x00000000004006f0 <+88>: e1 07 40 f9 ldr x1, [sp, #8]
  12448. 0x00000000004006f4 <+92>: 3f 00 00 eb cmp x1, x0
  12449. 0x00000000004006f8 <+96>: a8 fd ff 54 b.hi 0x4006ac <busy_loop+20> // b.pmore
  12450. 12 }
  12451. 13 }
  12452. 14 }
  12453. 0x00000000004006fc <+100>: 1f 20 03 d5 nop
  12454. 0x0000000000400700 <+104>: ff 83 00 91 add sp, sp, #0x20
  12455. 0x0000000000400704 <+108>: c0 03 5f d6 ret
  12456. ....
  12457. We look for the internal backwards jumps, and we find two:
  12458. ....
  12459. 0x00000000004006dc <+68>: c8 fe ff 54 b.hi 0x4006b4 <busy_loop+28> // b.pmore
  12460. 0x00000000004006f8 <+96>: a8 fd ff 54 b.hi 0x4006ac <busy_loop+20> // b.pmore
  12461. ....
  12462. and so clearly the one at 0x4006dc happens first and jumps to a larger address than the other one, so the internal loop must be between 4006dc and 4006b4, which contains exactly 11 instructions! Bingo!
  12463. Oh my God, unoptimized code is so horrendously inefficient, even I can't stand all those useless loads and stores to memory variables!!!
  12464. Then for QEMU, we experimentally turn the number of loops up to 10^10 loops (`100000 100000`), which contains an expected 11 * 10^10 instructions, and the runtime is 00:01:08, so we have 1.1 * 10^11 instruction / 68 seconds ~ 2 * 10^9 = 2000 MIPS!
  12465. We can then repeat the experiment for other gem5 CPUs to see how they compare.
  12466. ===== User mode vs full system benchmark
  12467. Let's see if user mode runs considerably faster than full system or not, ignoring the kernel boot.
  12468. First we build <<dhrystone>> manually statically since dynamic linking is broken in gem5 as explained at: xref:gem5-syscall-emulation-mode[xrefstyle=full].
  12469. TODO: move this section to our new custom dhrystone setup: xref:dhrystone[xrefstyle=full].
  12470. gem5 user mode:
  12471. ....
  12472. ./build-buildroot --arch arm --config 'BR2_PACKAGE_DHRYSTONE=y'
  12473. make \
  12474. -B \
  12475. -C "$(./getvar --arch arm buildroot_build_build_dir)/dhrystone-2" \
  12476. CC="$(./run-toolchain --arch arm --print-tool gcc)" \
  12477. CFLAGS=-static \
  12478. ;
  12479. time \
  12480. ./run \
  12481. --arch arm \
  12482. --emulator gem5 \
  12483. --userland "$(./getvar --arch arm buildroot_build_build_dir)/dhrystone-2/dhrystone" \
  12484. --userland-args 'asdf qwer' \
  12485. ;
  12486. ....
  12487. gem5 full system:
  12488. ....
  12489. time \
  12490. ./run \
  12491. --arch arm \
  12492. --eval-after './gem5.sh' \
  12493. --emulator gem5
  12494. --gem5-readfile 'dhrystone 100000' \
  12495. ;
  12496. ....
  12497. QEMU user mode:
  12498. ....
  12499. time qemu-arm "$(./getvar --arch arm buildroot_build_build_dir)/dhrystone-2/dhrystone" 100000000
  12500. ....
  12501. QEMU full system:
  12502. ....
  12503. time \
  12504. ./run \
  12505. --arch arm \
  12506. --eval-after 'time dhrystone 100000000;./linux/poweroff.out' \
  12507. ;
  12508. ....
  12509. Result on <<p51>> at bad30f513c46c1b0995d3a10c0d9bc2a33dc4fa0:
  12510. * gem5 user: 33 seconds
  12511. * gem5 full system: 51 seconds
  12512. * QEMU user: 45 seconds
  12513. * QEMU full system: 223 seconds
  12514. ==== Benchmark builds
  12515. The build times are calculated after doing `./configure` and https://buildroot.org/downloads/manual/manual.html#_offline_builds[`make source`], which downloads the sources, and basically benchmarks the <<benchmark-internets,Internet>>.
  12516. Sample build time at 2c12b21b304178a81c9912817b782ead0286d282: 28 minutes, 15 with full ccache hits. Breakdown: 19% GCC, 13% Linux kernel, 7% uclibc, 6% host-python, 5% host-qemu, 5% host-gdb, 2% host-binutils
  12517. Buildroot automatically stores build timestamps as milliseconds since Epoch. Convert to minutes:
  12518. ....
  12519. awk -F: 'NR==1{start=$1}; END{print ($1 - start)/(60000.0)}' "$(./getvar buildroot_build_build_dir)/build-time.log"
  12520. ....
  12521. Or to conveniently do a clean build without affecting your current one:
  12522. ....
  12523. ./bench-all -b
  12524. cat ../linux-kernel-module-cheat-regression/*/build-time.log
  12525. ....
  12526. ===== Find which Buildroot packages are making the build slow and big
  12527. ....
  12528. ./build-buildroot -- graph-build graph-size graph-depends
  12529. cd "$(./getvar buildroot_build_dir)/graphs"
  12530. xdg-open build.pie-packages.pdf
  12531. xdg-open graph-depends.pdf
  12532. xdg-open graph-size.pdf
  12533. ....
  12534. [[prebuilt-toolchain]]
  12535. ====== Buildroot use prebuilt host toolchain
  12536. The biggest build time hog is always GCC, and it does not look like we can use a precompiled one: https://stackoverflow.com/questions/10833672/buildroot-environment-with-host-toolchain
  12537. ===== Benchmark Buildroot build baseline
  12538. This is the minimal build we could expect to get away with.
  12539. We will run this whenever the Buildroot submodule is updated.
  12540. On the upstream Buildroot repo at :
  12541. ....
  12542. ./bench-all -B
  12543. ....
  12544. Sample time on 2017.08: 11 minutes, 7 with full ccache hits. Breakdown: 47% GCC, 15% Linux kernel, 9% uclibc, 5% host-binutils. Conclusions:
  12545. * we have bloated our kernel build 3x with all those delicious features :-)
  12546. * GCC time increased 1.5x by our bloat, but its percentage of the total was greatly reduced, due to new packages being introduced.
  12547. +
  12548. `make graph-depends` shows that most new dependencies come from QEMU and GDB, which we can't get rid of anyways.
  12549. A quick look at the system monitor reveals that the build switches between times when:
  12550. * CPUs are at a max, memory is fine. So we must be CPU / memory speed bound. I bet that this happens during heavy compilation.
  12551. * CPUs are not at a max, and memory is fine. So we are likely disk bound. I bet that this happens during configuration steps.
  12552. This is consistent with the fact that ccache reduces the build time only partially, since ccache should only overcome the CPU bound compilation steps, but not the disk bound ones.
  12553. The instructions counts varied very little between the baseline and LKMC, so runtime overhead is not a big deal apparently.
  12554. Size:
  12555. * `bzImage`: 4.4M
  12556. * `rootfs.cpio`: 1.6M
  12557. Zipped: 4.9M, `rootfs.cpio` deflates 50%, `bzImage` almost nothing.
  12558. ===== Benchmark gem5 build
  12559. How long it takes to build gem5 itself.
  12560. We will update this whenever the gem5 submodule is updated.
  12561. Sample results at gem5 2a9573f5942b5416fb0570cf5cb6cdecba733392: 10 to 12 minutes.
  12562. Get results with:
  12563. ....
  12564. ./bench-all --emulator gem5
  12565. tail -n+1 ../linux-kernel-module-cheat-regression/*/gem5-bench-build-*.txt
  12566. ....
  12567. ====== Benchmark gem5 single file change rebuild time
  12568. This is the critical development parameter, and is dominated by the link time of huge binaries.
  12569. In order to benchmark it better, make a comment only change to:
  12570. ....
  12571. vim submodules/gem5/src/sim/main.cc
  12572. ....
  12573. then rebuild with:
  12574. ....
  12575. ./build-gem5 --arch aarch64 --verbose
  12576. ....
  12577. and then copy the link command to a separate Bash file. Then you can time and modify it easily.
  12578. Some approximate reference values on <<p51>>:
  12579. * `opt`
  12580. ** unmodified: 10 seconds
  12581. ** hack with `-fuse-ld=gold`: 6 seconds. Huge improvement!
  12582. * `debug`
  12583. ** unmodified: 14 seconds. Why two times slower than unmodified?
  12584. ** hack with `-fuse-ld=gold`: `internal error in read_cie, at ../../gold/ehframe.cc:919` on Ubuntu 18.04 all GCC. TODO report.
  12585. * `fast`
  12586. ** `--force-lto`: 1 minute. Slower as expected, since more optimizations are done at link time. `--force-lto` is only used for `fast`, and it adds `-flto` to the build.
  12587. ramfs made no difference, the kernel must be caching files in memory very efficiently already.
  12588. Tested at: d4b3e064adeeace3c3e7d106801f95c14637c12f + 1.
  12589. === Benchmark machines
  12590. ==== P51
  12591. Lenovo ThinkPad https://www3.lenovo.com/gb/en/laptops/thinkpad/p-series/P51/p/22TP2WPWP51[P51 laptop]:
  12592. * 2500 USD in 2018 (high end)
  12593. * Intel Core i7-7820HQ Processor (8MB Cache, up to 3.90GHz) (4 cores 8 threads)
  12594. * 32GB(16+16) DDR4 2400MHz SODIMM
  12595. * 512GB SSD PCIe TLC OPAL2
  12596. * NVIDIA Quadro M1200 Mobile, latest Ubuntu supported proprietary driver
  12597. * Latest Ubuntu
  12598. === Benchmark Internets
  12599. ==== 38Mbps internet
  12600. 2c12b21b304178a81c9912817b782ead0286d282:
  12601. * shallow clone of all submodules: 4 minutes.
  12602. * `make source`: 2 minutes
  12603. Google M-lab speed test: 36.4Mbps
  12604. === Benchmark this repo bibliography
  12605. gem5:
  12606. * https://www.mail-archive.com/gem5-users@gem5.org/msg15262.html[] which parts of the gem5 code make it slow
  12607. * what are the minimum system requirements:
  12608. ** https://stackoverflow.com/questions/47997565/gem5-system-requirements-for-decent-performance/48941793#48941793
  12609. ** https://github.com/gem5/gem5/issues/25
  12610. == Xephyr
  12611. Xephyr is an RTOS that has <<posix>> support. I think it works much like our <<baremetal-setup>> which uses Newlib and generates individual ELF files that contain both our C program's code, and the Xephyr libraries.
  12612. TODO get a hello world working, and then consider further integration in this repo, e.g. being able to run all C userland content on it.
  12613. TODO: Cortex-A CPUs are not currently supported, there are some `qemu_cortex_m0` boards, but can't find a QEMU Cortex-A. There is an x86_64 qemu board, but we don't currently have an <<about-the-baremetal-setup,x86 baremetal toolchain>>. For this reason, we won't touch this further for now.
  12614. However, unlike Newlib, Xephyr must be setting up a simple pre-main runtime to be able to handle threads.
  12615. Failed attempt:
  12616. ....
  12617. # https://askubuntu.com/questions/952429/is-there-a-good-ppa-for-cmake-backports
  12618. wget -O - https://apt.kitware.com/keys/kitware-archive-latest.asc 2>/dev/null | sudo apt-key add -
  12619. sudo apt-add-repository 'deb https://apt.kitware.com/ubuntu/ bionic-rc main'
  12620. sudo apt-get update
  12621. sudo apt-get install cmake
  12622. git clone https://github.com/zephyrproject-rtos/zephyr
  12623. pip3 install --user -U west packaging
  12624. cd zephyr
  12625. git checkout v1.14.1
  12626. west init zephyrproject
  12627. west update
  12628. export ZEPHYR_TOOLCHAIN_VARIANT=xtools
  12629. export XTOOLS_TOOLCHAIN_PATH="$(pwd)/out/crosstool-ng/build/default/install/aarch64/bin/"
  12630. source zephyr-env.sh
  12631. west build -b qemu_aarch64 samples/hello_world
  12632. ....
  12633. The build system of that project is a bit excessive / wonky. You need an edge CMake not present in Ubuntu 18.04, which I don't want to install right now, and it uses the weird custom `west` build tool frontend.
  12634. == Compilers
  12635. Argh, compilers are boring, let's learn a bit about them.
  12636. * link:userland/gcc/busy_loop.c[]: https://stackoverflow.com/questions/7083482/how-to-prevent-gcc-from-optimizing-out-a-busy-wait-loop/58758133#58758133
  12637. * link:userland/gcc/prevent_reorder.cpp[]: https://stackoverflow.com/questions/37786547/enforcing-statement-order-in-c/56865717#56865717
  12638. == Computer architecture
  12639. === Cache coherence
  12640. https://en.wikipedia.org/wiki/Cache_coherence
  12641. Algorithms to keep the caches of different cores of a system coherent.
  12642. E.g.: if one processors writes to the cache, other processors have to know about it before they read from that address.
  12643. ==== MSI protocol
  12644. https://en.wikipedia.org/wiki/MSI_protocol
  12645. This is the most basic non-trivial coherency protocol, and therefore the first one you should learn.
  12646. Helpful video: https://www.youtube.com/watch?v=gAUVAel-2Fg "MSI Coherence - Georgia Tech - HPCA: Part 5" by Udacity.
  12647. Let's focus on a single cache line representing a given memory address.
  12648. The system looks like this:
  12649. ....
  12650. +----+
  12651. |DRAM|
  12652. +----+
  12653. ^
  12654. |
  12655. v
  12656. +--------+
  12657. | BUS |
  12658. +--------+
  12659. ^ ^
  12660. | |
  12661. v v
  12662. +------+ +------+
  12663. |CACHE1| |CACHE2|
  12664. +------+ +------+
  12665. ^ ^
  12666. | |
  12667. | |
  12668. +----+ +----+
  12669. |CPU1| |CPU2|
  12670. +----+ +----+
  12671. ....
  12672. MSI stands for which states each cache can be in for a given cache line. The states are:
  12673. * Modified: a single cache has the valid data and it has been modified from DRAM.
  12674. +
  12675. Both reads and writes are free, because we don't have to worry about other processors.
  12676. * Shared: the data is synchronized with DRAM, and may be present in multiple caches.
  12677. +
  12678. Reads are free, but writes need to do extra work.
  12679. +
  12680. This is the "most interesting" state of the protocol, as it allows for those free reads, even when multiple processors are using some address.
  12681. * Invalid: the cache does not have the data, CPU reads and writes need to do extra work
  12682. The above allowed states can be summarized in the following table:
  12683. ....
  12684. CACHE1
  12685. MSI
  12686. M nny
  12687. CACHE2 S nyy
  12688. I yyy
  12689. ....
  12690. The whole goal of the protocol is to maintain that state at all times, so that we can get those free reads when in shared state!
  12691. To do so, the caches have to pass messages between themselves! This means generating bus traffic, which has a cost and must be kept to a minimum.
  12692. The system components can receive and send the following messages:
  12693. * CPUn can send to CACHEn:
  12694. ** "Local read": CPU reads from cache
  12695. ** "Local write": CPU writes to cache
  12696. * CACHEn to itself:
  12697. ** "Evict": the cache is running out of space due to another request
  12698. * CACHEn can send the following message to the bus.
  12699. ** "Bus read": the cache needs to get the data. The reply will contain the full data line. It can come either from another cache that has the data, or from DRAM if none do.
  12700. ** "Bus write": the cache wants to modify some data, and it does not have the line.
  12701. +
  12702. The reply must contain the full data line, because maybe the processor just wants to change one byte, but the line is much larger.
  12703. +
  12704. That's why this request can also be called "Read Exclusive", as it is basically a "Bus Read" + "Invalidate" in one
  12705. ** "Invalidate": the cache wants to modify some data, but it knows that all other caches are up to date, because it is in shared state.
  12706. +
  12707. Therefore, it does not need to fetch the data, which saves bus traffic compared to "Bus write" since the data itself does not need to be sent.
  12708. ** "Write back": send the data on the bus and tell someone to pick it up: either DRAM or another cache
  12709. When a message is sent to the bus:
  12710. * all other caches and the DRAM will see it, this is called "snooping"
  12711. * either caches or DRAM can reply if a reply is needed, but other caches get priority to reply earlier if they can, e.g. to serve a cache request from other caches rather than going all the way to DRAM
  12712. When a cache receives a message, it do one or both of:
  12713. * change to another MSI state
  12714. * send a message to the bus
  12715. And finally, the transitions are:
  12716. * Modified:
  12717. ** "Local read": don't need to do anything because only the current cache holds the data
  12718. ** "Local write": don't need to do anything because only the current cache holds the data
  12719. ** "Evict": have to save data to DRAM so that our local modifications won't be lost
  12720. *** Move to: Invalid
  12721. *** Send message: "Write back"
  12722. ** "Bus read": another cache is trying to read the address which we owned exclusively.
  12723. +
  12724. Since we know what the latest data is, we can move to "Shared" rather than "Invalid" to possibly save time on future reads.
  12725. +
  12726. But to do that, we need to write the data back to DRAM to maintain the shared state consistent. The <<mesi-protocol>> prevents that extra read in some cases.
  12727. +
  12728. And it has to be either: before the other cache gets its data from DRAM, or better, the other cache can get its data from our write back itself just like the DRAM.
  12729. +
  12730. *** Move to: Shared
  12731. *** Send message: "Write back"
  12732. ** "Bus write": someone else will write to our address.
  12733. +
  12734. We don't know what they will write, so the best bet is to move to invalid.
  12735. +
  12736. Since the writer will become the new sole data owner, the writer can get the cache from us without going to DRAM at all! This is fine, because the writer will be the new sole owner of the line, so DRAM can remain dirty without problems.
  12737. +
  12738. *** Move to: Invalid
  12739. *** Send message: "Write back"
  12740. * Shared: TODO
  12741. ** "Local read":
  12742. ** "Local write":
  12743. ** "Evict":
  12744. ** "Bus read":
  12745. ** "Bus write":
  12746. * Invalid: TODO
  12747. ** "Local read":
  12748. ** "Local write":
  12749. ** "Evict":
  12750. ** "Bus read":
  12751. ** "Bus write":
  12752. TODO gem5 concrete example.
  12753. ==== MESI protocol
  12754. https://en.wikipedia.org/wiki/MESI_protocol
  12755. Splits the Shared of <<msi-protocol>> into a new Exclusive state:
  12756. * MESI Exclusive: clean but only present in one cache
  12757. * MESI Shared: clean but may be present in more that one cache
  12758. TODO advantage: I think the advantages over MSI are:
  12759. * when we move from Exclusive to Shared, no DRAM write back is needed, because we know that the cache is clean
  12760. * when we move from Exclusive to Modified, no invalidate message is required, reducing bus traffic
  12761. Exclusive is entered from Invalid after a "Local read", but only if the reply came from DRAM! If the reply came from another cache, we go directly to shared instead.
  12762. ==== MOSI protocol
  12763. https://en.wikipedia.org/wiki/MOSI_protocol
  12764. TODO compare to MSI and understand advantages. From Wikipedia it seems that MOSI can get data from the Owned cache while MSI cannot get data from Shared caches and must go to memory, but why not? Why do we need that Owned? Is it because there are multiple Shared caches and them all replying at the same time would lead to problems?
  12765. ==== MOESI protocol
  12766. https://en.wikipedia.org/wiki/MOESI_protocol
  12767. <<mesi-protocol>> + <<mosi-protocol>>, not much else to it!
  12768. == About this repo
  12769. === Supported hosts
  12770. The host requirements depend a lot on which examples you want to run.
  12771. Some setups of this repository are very portable, notably setups under <<userland-setup>>, e.g. <<c>>, and will likely work on any host system with minimal modification.
  12772. The least portable setups are those that require Buildroot and crosstool-NG.
  12773. We tend to test this repo the most on the latest Ubuntu and on the latest https://askubuntu.com/questions/16366/whats-the-difference-between-a-long-term-support-release-and-a-normal-release[Ubuntu LTS].
  12774. For other Linux distros, everything will likely also just work if you install the analogous required packages for your distro.
  12775. Find out the packages that we install with:
  12776. ....
  12777. ./build --download-dependencies --dry-run <some-target> | less
  12778. ....
  12779. and then just look for the `apt-get` commands shown on the log.
  12780. After installing the missing packages for your distro, do the build with:
  12781. ....
  12782. ./build --download-dependencies --no-apt <some-target>
  12783. ....
  12784. which does everything as normal, except that it skips any `apt` commands.
  12785. If something does not work however, <<docker>> should just work on any Linux distro.
  12786. Native Windows is unlikely feasible for Buildroot setups because Buildroot is a huge set of GNU Make scripts + host tools, just do everything from inside an Ubuntu in VirtualBox instance in that case.
  12787. Pull requests with ports to new host systems and reports on issues that things work or don't work on your host are welcome.
  12788. === Common build issues
  12789. [[put-source-uris-in-sources]]
  12790. ==== You must put some 'source' URIs in your sources.list
  12791. If `./build --download-dependencies` fails with:
  12792. ....
  12793. E: You must put some 'source' URIs in your sources.list
  12794. ....
  12795. see this: https://askubuntu.com/questions/496549/error-you-must-put-some-source-uris-in-your-sources-list/857433#857433 I don't know how to automate this step. Why, Ubuntu, why.
  12796. ==== Build from downloaded source zip files
  12797. It does not work if you just download the `.zip` with the sources for this repository from GitHub because we use link:.gitmodules[Git submodules], you must clone this repo.
  12798. `./build --download-dependencies` then fetches only the required submodules for you.
  12799. === Run command after boot
  12800. If you just want to run a command after boot ends without thinking much about it, just use the `--eval-after` option, e.g.:
  12801. ....
  12802. ./run --eval-after 'echo hello'
  12803. ....
  12804. This option passes the command to our init scripts through <<kernel-command-line-parameters>>, and uses a few clever tricks along the way to make it just work.
  12805. See <<init>> for the gory details.
  12806. === Default command line arguments
  12807. It gets annoying to retype `--arch aarch64` for every single command, or to remember `--config` setups.
  12808. So simplify that, do:
  12809. ....
  12810. cp config.py data/
  12811. ....
  12812. and then edit the `data/config` file to your needs.
  12813. Source: link:config.py[]
  12814. You can also choose a different configuration file explicitly with:
  12815. ....
  12816. ./run --config data/config2.py
  12817. ....
  12818. Almost all options names are automatically deduced from their command line `--help` name: just replace `-` with `_`.
  12819. More precisely, we use the `dest=` value of Python's https://docs.python.org/3/library/argparse.html[argparse module].
  12820. To get a list of all global options that you can use, try:
  12821. ....
  12822. ./getvar --type input
  12823. ....
  12824. but note that this does not include script specific options.
  12825. === Documentation
  12826. To learn how to build the documentation see: xref:build-the-documentation[xrefstyle=full].
  12827. ==== Documentation verification
  12828. When running link:build-doc[], we do the following checks:
  12829. * `<<>>` inner links are not broken
  12830. * `+link:somefile[]+` links point to paths that exist via <<asciidoctor-extract-link-targets>>. Upstream wontfix at: https://github.com/asciidoctor/asciidoctor/issues/3210
  12831. * all links in non-README files to README IDs exist via `git grep` + <<asciidoctor-extract-header-ids>>
  12832. The scripts prints what you have to fix and exits with an error status if there are any errors.
  12833. [[asciidoctor-extract-link-targets]]
  12834. ===== asciidoctor/extract-link-targets
  12835. Documentation for link:asciidoctor/extract-link-targets[]
  12836. Extract link targets from Asciidoctor document.
  12837. Usage:
  12838. ....
  12839. ./asciidoctor/extract-link-targets README.adoc
  12840. ....
  12841. Output: one link target per line.
  12842. Hastily hacked from: https://asciidoctor.org/docs/user-manual/#inline-macro-processor-example
  12843. [[asciidoctor-extract-header-ids]]
  12844. ===== asciidoctor/extract-header-ids
  12845. Documentation for link:asciidoctor/extract-header-ids[]
  12846. Extract header IDs, both auto-generated and manually given.
  12847. E.g., for the document `test.adoc`:
  12848. ....
  12849. = Auto generated
  12850. [[explicitly-given]]
  12851. == La la
  12852. ....
  12853. the script:
  12854. ....
  12855. ./asciidoctor/extract-header-ids test.adoc
  12856. ....
  12857. produces:
  12858. ....
  12859. auto-generated
  12860. explicitly-given
  12861. ....
  12862. One application we have in mind for this is that as of 2.0.10 Asciidoctor does not warn on header ID collisions between auto-generated IDs: https://github.com/asciidoctor/asciidoctor/issues/3147 But this script doesn't solve that yet as it would require generating the section IDs without the `-N` suffix. Section generation happens at `Section.generate_id` in Asciidoctor code.
  12863. Hastily hacked from: https://asciidoctor.org/docs/user-manual/#https://asciidoctor.org/docs/user-manual/#tree-processor-example until I noticed that that example had a bug at the time and so fixed it here: https://github.com/asciidoctor/asciidoctor/issues/3363
  12864. [[asciidoctor-link-target-up-rb]]
  12865. === asciidoctor/link-target-up.rb
  12866. The Asciidoctor extension scripts:
  12867. * link:asciidoctor-link-up.rb
  12868. * link:asciidoctor-link-github.rb
  12869. hack the README `link:` targets to make them work from:
  12870. * inside the `out/` directory with `../`
  12871. * <<github-pages>>, with explicit GitHub blob URLs
  12872. ==== GitHub pages
  12873. As mentioned before the TOC, we have to push this README to GitHub pages due to: https://github.com/isaacs/github/issues/1610
  12874. For now, instead of pushing with `git push`, I just remember to always push with:
  12875. ....
  12876. ./publish-gh-pages
  12877. ....
  12878. Source: link:publish-gh-pages[]
  12879. I'm going this way for now because:
  12880. * the Jekyll Asciidoctor plugin is not enabled by default on GitHub: https://webapps.stackexchange.com/questions/114606/can-github-pages-render-asciidoc
  12881. * https://stackoverflow.com/questions/1797074/local-executing-hook-after-a-git-push[post-push hooks don't exist]
  12882. * I'm lazy to setup a proper Travis CI push
  12883. * I'm the only contributor essentially, so no problems with pull requests
  12884. The only files used by the GitHub pages are:
  12885. * link:Gemfile[]
  12886. * link:_config.yml[]
  12887. === Clean the build
  12888. You did something crazy, and nothing seems to work anymore?
  12889. All our build outputs are stored under `out/`, so the coarsest and most effective thing you can do is:
  12890. ....
  12891. rm -rf out
  12892. ....
  12893. This implies a full rebuild for all archs however, so you might first want to explore finer grained cleans first.
  12894. All our individual `build-*` scripts have a `--clean` option to completely nuke their builds:
  12895. ....
  12896. ./build-gem5 --clean
  12897. ./build-qemu --clean
  12898. ./build-buildroot --clean
  12899. ....
  12900. Verify with:
  12901. ....
  12902. ls "$(./getvar qemu_build_dir)"
  12903. ls "$(./getvar gem5_build_dir)"
  12904. ls "$(./getvar buildroot_build_dir)"
  12905. ....
  12906. Note that host tools like QEMU and gem5 store all archs in a single directory to factor out build objects, so cleaning one arch will clean all of them.
  12907. To only nuke only one Buildroot package, we can use the https://buildroot.org/downloads/manual/manual.html#pkg-build-steps[`-dirclean`] Buildroot target:
  12908. ....
  12909. ./build-buildroot --no-all -- <package-name>-dirclean
  12910. ....
  12911. e.g.:
  12912. ....
  12913. ./build-buildroot --no-all -- sample_package-dirclean
  12914. ....
  12915. Verify with:
  12916. ....
  12917. ls "$(./getvar buildroot_build_build_dir)"
  12918. ....
  12919. === ccache
  12920. https://en.wikipedia.org/wiki/Ccache[ccache] <<benchmark-builds,might>> save you a lot of re-build when you decide to <<clean-the-build>> or create a new <<build-variants,build variant>>.
  12921. We have ccache enabled for everything we build by default.
  12922. However, you likely want to add the following to your `.bashrc` to take better advantage of `ccache`:
  12923. ....
  12924. export CCACHE_DIR=~/.ccache
  12925. export CCACHE_MAXSIZE="20G"
  12926. ....
  12927. We cannot automate this because you have to decide:
  12928. * should I store my cache on my HD or SSD?
  12929. * how big is my build, and how many build configurations do I need to keep around at a time?
  12930. If you don't those variables it, the default is to use `~/.buildroot-ccache` with `5G`, which is a bit small for us.
  12931. To check if `ccache` is working, run this command while a build is running on another shell:
  12932. ....
  12933. watch -n1 'make -C "$(./getvar buildroot_build_dir)" ccache-stats'
  12934. ....
  12935. or if you have it installed on host and the environment variables exported simply with:
  12936. ....
  12937. watch -n1 'ccache -s'
  12938. ....
  12939. and then watch the miss or hit counts go up.
  12940. We have https://buildroot.org/downloads/manual/manual.html#ccache[enabled ccached] builds by default.
  12941. `BR2_CCACHE_USE_BASEDIR=n` is used for Buildroot, which means that:
  12942. * absolute paths are used and GDB can find source files
  12943. * but builds are not reused across separated LKMC directories
  12944. === Rebuild Buildroot while running
  12945. It is not possible to rebuild the root filesystem while running QEMU because QEMU holds the file qcow2 file:
  12946. ....
  12947. error while converting qcow2: Failed to get "write" lock
  12948. ....
  12949. === Simultaneous runs
  12950. When doing long simulations sweeping across multiple system parameters, it becomes fundamental to do multiple simulations in parallel.
  12951. This is specially true for gem5, which runs much slower than QEMU, and cannot use multiple host cores to speed up the simulation: https://github.com/cirosantilli-work/gem5-issues/issues/15[], so the only way to parallelize is to run multiple instances in parallel.
  12952. This also has a good synergy with <<build-variants>>.
  12953. First shell:
  12954. ....
  12955. ./run
  12956. ....
  12957. Another shell:
  12958. ....
  12959. ./run --run-id 1
  12960. ....
  12961. and now you have two QEMU instances running in parallel.
  12962. The default run id is `0`.
  12963. Our scripts solve two difficulties with simultaneous runs:
  12964. * port conflicts, e.g. GDB and link:gem5-shell[]
  12965. * output directory conflicts, e.g. traces and gem5 stats overwriting one another
  12966. Each run gets a separate output directory. For example:
  12967. ....
  12968. ./run --arch aarch64 --emulator gem5 --run-id 0 &>/dev/null &
  12969. ./run --arch aarch64 --emulator gem5 --run-id 1 &>/dev/null &
  12970. ....
  12971. produces two separate <<m5out-directory,`m5out` directories>>:
  12972. ....
  12973. echo "$(./getvar --arch aarch64 --emulator gem5 --run-id 0 m5out_dir)"
  12974. echo "$(./getvar --arch aarch64 --emulator gem5 --run-id 1 m5out_dir)"
  12975. ....
  12976. and the gem5 host executable stdout and stderr can be found at:
  12977. ....
  12978. less "$(./getvar --arch aarch64 --emulator gem5 --run-id 0 termout_file)"
  12979. less "$(./getvar --arch aarch64 --emulator gem5 --run-id 1 termout_file)"
  12980. ....
  12981. Each line is prepended with the timestamp in seconds since the start of the program when it appeared.
  12982. To have more semantic output directories names for later inspection, you can use a non numeric string for the run ID, and indicate the port offset explicitly:
  12983. ....
  12984. ./run --arch aarch64 --emulator gem5 --run-id some-experiment --port-offset 1
  12985. ....
  12986. `--port-offset` defaults to the run ID when that is a number.
  12987. Like <<cpu-architecture>>, you will need to pass the `-n` option to anything that needs to know runtime information, e.g. <<gdb>>:
  12988. ....
  12989. ./run --run-id 1
  12990. ./run-gdb --run-id 1
  12991. ....
  12992. To run multiple gem5 checkouts, see: xref:gem5-worktree[xrefstyle=full].
  12993. Implementation note: we create multiple namespaces for two things:
  12994. * run output directory
  12995. * ports
  12996. ** QEMU allows setting all ports explicitly.
  12997. +
  12998. If a port is not free, it just crashes.
  12999. +
  13000. We assign a contiguous port range for each run ID.
  13001. ** gem5 automatically increments ports until it finds a free one.
  13002. +
  13003. gem5 60600f09c25255b3c8f72da7fb49100e2682093a does not seem to expose a way to set the terminal and VNC ports from `fs.py`, so we just let gem5 assign the ports itself, and use `-n` only to match what it assigned. Those ports both appear on <<gem5-config-ini>>.
  13004. +
  13005. The GDB port can be assigned on `gem5.opt --remote-gdb-port`, but it does not appear on `config.ini`.
  13006. === Build variants
  13007. It often happens that you are comparing two versions of the build, a good and a bad one, and trying to figure out why the bad one is bad.
  13008. Our build variants system allows you to keep multiple built versions of all major components, so that you can easily switching between running one or the other.
  13009. ==== Linux kernel build variants
  13010. If you want to keep two builds around, one for the latest Linux version, and the other for Linux `v4.16`:
  13011. ....
  13012. # Build master.
  13013. ./build-linux
  13014. # Build another branch.
  13015. git -C "$(./getvar linux_source_dir)" fetch --tags --unshallow
  13016. git -C "$(./getvar linux_source_dir)" checkout v4.16
  13017. ./build-linux --linux-build-id v4.16
  13018. # Restore master.
  13019. git -C "$(./getvar linux_source_dir)" checkout -
  13020. # Run master.
  13021. ./run
  13022. # Run another branch.
  13023. ./run --linux-build-id v4.16
  13024. ....
  13025. The `git fetch --unshallow` is needed the first time because `./build --download-dependencies` only does a shallow clone of the Linux kernel to save space and time, see also: https://stackoverflow.com/questions/6802145/how-to-convert-a-git-shallow-clone-to-a-full-clone
  13026. The `--linux-build-id` option should be passed to all scripts that support it, much like `--arch` for the <<cpu-architecture>>, e.g. to step debug:
  13027. .....
  13028. ./run-gdb --linux-build-id v4.16
  13029. .....
  13030. To run both kernels simultaneously, one on each QEMU instance, see: xref:simultaneous-runs[xrefstyle=full].
  13031. ==== QEMU build variants
  13032. Analogous to the <<linux-kernel-build-variants>> but with the `--qemu-build-id` option instead:
  13033. ....
  13034. ./build-qemu
  13035. git -C "$(./getvar qemu_source_dir)" checkout v2.12.0
  13036. ./build-qemu --qemu-build-id v2.12.0
  13037. git -C "$(./getvar qemu_source_dir)" checkout -
  13038. ./run
  13039. ./run --qemu-build-id v2.12.0
  13040. ....
  13041. ==== gem5 build variants
  13042. Analogous to the <<linux-kernel-build-variants>> but with the `--gem5-build-id` option instead:
  13043. ....
  13044. # Build master.
  13045. ./build-gem5
  13046. # Build another branch.
  13047. git -C "$(./getvar gem5_source_dir)" checkout some-branch
  13048. ./build-gem5 --gem5-build-id some-branch
  13049. # Restore master.
  13050. git -C "$(./getvar gem5_source_dir)" checkout -
  13051. # Run master.
  13052. ./run --emulator gem5
  13053. # Run another branch.
  13054. git -C "$(./getvar gem5_source_dir)" checkout some-branch
  13055. ./run --gem5-build-id some-branch --emulator gem5
  13056. ....
  13057. Don't forget however that gem5 has Python scripts in its source code tree, and that those must match the source code of a given build.
  13058. Therefore, you can't forget to checkout to the sources to that of the corresponding build before running, unless you explicitly tell gem5 to use a non-default source tree with <<gem5-worktree>>. This becomes inevitable when you want to launch multiple simultaneous runs at different checkouts.
  13059. ===== gem5 worktree
  13060. <<gem5-build-variants,`--gem5-build-id`>> goes a long way, but if you want to seamlessly switch between two gem5 tress without checking out multiple times, then `--gem5-worktree` is for you.
  13061. ....
  13062. # Build gem5 at the revision in the gem5 submodule.
  13063. ./build-gem5
  13064. # Create a branch at the same revision as the gem5 submodule.
  13065. ./build-gem5 --gem5-worktree my-new-feature
  13066. cd "$(./getvar --gem5-worktree my-new-feature)"
  13067. vim create-bugs
  13068. git add .
  13069. git commit -m 'Created a bug'
  13070. cd -
  13071. ./build-gem5 --gem5-worktree my-new-feature
  13072. # Run the submodule.
  13073. ./run --emulator gem5 --run-id 0 &>/dev/null &
  13074. # Run the branch the need to check out anything.
  13075. # With --gem5-worktree, we can do both runs at the same time!
  13076. ./run --emulator gem5 --gem5-worktree my-new-feature --run-id 1 &>/dev/null &
  13077. ....
  13078. `--gem5-worktree <worktree-id>` automatically creates:
  13079. * a https://git-scm.com/docs/git-worktree[Git worktree] of gem5 if one didn't exit yet for `<worktree-id>`
  13080. * a separate build directory, exactly like `--gem5-build-id my-new-feature` would
  13081. We promise that the scripts sill never touch that worktree again once it has been created: it is now up to you to manage the code manually.
  13082. `--gem5-worktree` is required if you want to do multiple simultaneous runs of different gem5 versions, because each gem5 build needs to use the matching Python scripts inside the source tree.
  13083. The difference between `--gem5-build-id` and `--gem5-worktree` is that `--gem5-build-id` specifies only the gem5 build output directory, while `--gem5-worktree` specifies the source input directory.
  13084. Each Git worktree needs a branch name, and we append the `wt/` prefix to the `--gem5-worktree` value, where `wt` stands for `WorkTree`. This is done to allow us to checkout to a test `some-branch` branch under `submodules/gem5` and still use `--gem5-worktree some-branch`, without conflict for the worktree branch, which can only be checked out once.
  13085. ===== gem5 private source trees
  13086. Suppose that you are working on a private fork of gem5, but you want to use this repository to develop it as well.
  13087. Simply adding your private repository as a remote to `submodules/gem5` is dangerous, as you might forget and push your private work by mistake one day.
  13088. Even removing remotes is not safe enough, since `git submodule update` and other submodule commands can restore the old public remote.
  13089. Instead, we provide the following safer process.
  13090. First do a separate private clone of you private repository outside of this repository:
  13091. ....
  13092. git clone https://my.private.repo.com/my-fork/gem5.git gem5-internal
  13093. gem5_internal="$(pwd)/gem5-internal"
  13094. ....
  13095. Next, when you want to build with the private repository, use the `--gem5-build-dir` and `--gem5-source-dir` argument to override our default gem5 source and build locations:
  13096. ....
  13097. cd linux-kernel-module-cheat
  13098. ./build-gem5 \
  13099. --gem5-build-dir "${gem5_internal}/build" \
  13100. --gem5-source-dir "$gem5_internal" \
  13101. ;
  13102. ./run-gem5 \
  13103. --gem5-build-dir "${gem5_internal}/build" \
  13104. --gem5-source-dir "$gem5_internal" \
  13105. ;
  13106. ....
  13107. With this setup, both your private gem5 source and build are safely kept outside of this public repository.
  13108. ==== Buildroot build variants
  13109. Allows you to have multiple versions of the GCC toolchain or root filesystem.
  13110. Analogous to the <<linux-kernel-build-variants>> but with the `--build-id` option instead:
  13111. ....
  13112. ./build-buildroot
  13113. git -C "$(./getvar buildroot_source_dir)" checkout 2018.05
  13114. ./build-buildroot --buildroot-build-id 2018.05
  13115. git -C "$(./getvar buildroot_source_dir)" checkout -
  13116. ./run
  13117. ./run --buildroot-build-id 2018.05
  13118. ....
  13119. === Directory structure
  13120. ==== lkmc directory
  13121. link:lkmc/[] contains sources and headers that are shared across kernel modules, userland and baremetal examples.
  13122. We chose this awkward name so that our includes will have an `lkmc/` prefix.
  13123. Another option would have been to name it as `includes/lkmc`, but that would make paths longer, and we might want to store source code in that directory as well in the future.
  13124. ===== Userland objects vs header-only
  13125. When factoring out functionality across userland examples, there are two main options:
  13126. * use header-only implementations
  13127. * use separate C files and link to separate objects.
  13128. The downsides of the header-only implementation are:
  13129. * slower compilation time, especially for C++
  13130. * cannot call C implementations from assembly files
  13131. The advantages of header-only implementations are:
  13132. * easier to use, just `#include` and you are done, no need to modify build metadata.
  13133. As a result, we are currently using the following rule:
  13134. * if something is only going to be used from C and not assembly, define it in a header which is easier to use
  13135. +
  13136. The slower compilation should be OK as long as split functionality amongst different headers and only include the required ones.
  13137. +
  13138. Also we don't have a choice in the case of C++ template, which must stay in headers.
  13139. * if the functionality will be called from assembly, then we don't have a choice, and must add it to a separate source file and link against it.
  13140. ==== buildroot_packages directory
  13141. Source: link:buildroot_packages/[].
  13142. Every directory inside it is a Buildroot package.
  13143. Those packages get automatically added to Buildroot's `BR2_EXTERNAL`, so all you need to do is to turn them on during build, e.g.:
  13144. ....
  13145. ./build-buildroot --config 'BR2_PACKAGE_SAMPLE_PACKAGE=y'
  13146. ....
  13147. then test it out with:
  13148. ....
  13149. ./run --eval-after '/sample_package.out'
  13150. ....
  13151. and you should see:
  13152. ....
  13153. hello sample_package
  13154. ....
  13155. Source: link:buildroot_packages/sample_package/sample_package.c[]
  13156. You can force a rebuild with:
  13157. ....
  13158. ./build-buildroot --config 'BR2_PACKAGE_SAMPLE_PACKAGE=y' -- sample_package-reconfigure
  13159. ....
  13160. Buildroot packages are convenient, but in general, if a package if very important to you, but not really mergeable back to Buildroot, you might want to just use a custom build script for it, and point it to the Buildroot toolchain, and then use `BR2_ROOTFS_OVERLAY`, much like we do for <<userland-setup>>.
  13161. A custom build script can give you more flexibility: e.g. the package can be made work with other root filesystems more easily, have better <<9p>> support, and rebuild faster as it evades some Buildroot boilerplate.
  13162. ===== kernel_modules buildroot package
  13163. Source: link:buildroot_packages/kernel_modules/[]
  13164. An example of how to use kernel modules in Buildroot.
  13165. Usage:
  13166. ....
  13167. ./build-buildroot \
  13168. --build-linux \
  13169. --config 'BR2_PACKAGE_KERNEL_MODULES=y' \
  13170. --no-overlay \
  13171. -- \
  13172. kernel_modules-reconfigure \
  13173. ;
  13174. ....
  13175. Then test one of the modules with:
  13176. ....
  13177. ./run --buildroot-linux --eval-after 'modprobe buildroot_hello'
  13178. ....
  13179. Source: link:buildroot_packages/kernel_modules/buildroot_hello.c[]
  13180. As you have just seen, this sets up everything so that <<modprobe>> can correctly find the module.
  13181. `./build-buildroot --build-linux` and `./run --buildroot-linux` are needed because the Buildroot kernel modules must use the Buildroot Linux kernel at build and run time.
  13182. The `--no-overlay` is required otherwise our `modules.order` generated by `./build-linux` and installed with `BR2_ROOTFS_OVERLAY` overwrites the Buildroot generated one.
  13183. Implementattion described at: https://stackoverflow.com/questions/40307328/how-to-add-a-linux-kernel-driver-module-as-a-buildroot-package/43874273#43874273
  13184. ==== patches directory
  13185. [[patches-global-directory]]
  13186. ===== patches/global directory
  13187. Has the following structure:
  13188. ....
  13189. package-name/00001-do-something.patch
  13190. ....
  13191. The patches are then applied to the corresponding packages before build.
  13192. Uses `BR2_GLOBAL_PATCH_DIR`.
  13193. [[patches-manual-directory]]
  13194. ===== patches/manual directory
  13195. Patches in this directory are never applied automatically: it is up to users to manually apply them before usage following the instructions in this documentation.
  13196. These are typically patches that don't contain fundamental functionality, so we don't feel like forking the target repos.
  13197. ==== rootfs_overlay
  13198. Source: link:rootfs_overlay[].
  13199. We use this directory for:
  13200. * customized configuration files
  13201. * userland module test scripts that don't need to be compiled.
  13202. +
  13203. Contrast this with <<userland-content,C examples>> that need compilation.
  13204. This directory is copied into the target filesystem by:
  13205. ....
  13206. ./copy-overlay
  13207. ./build-buildroot
  13208. ....
  13209. Source: link:copy-overlay[]
  13210. Build Buildroot is required for the same reason as described at: xref:your-first-kernel-module-hack[xrefstyle=full].
  13211. However, since the link:rootfs_overlay[] directory does not require compilation, unlike say <<your-first-kernel-module-hack,kernel modules>>, we also make it <<9p>> available to the guest directly even without `./copy-overlay` at:
  13212. ....
  13213. ls /mnt/9p/rootfs_overlay
  13214. ....
  13215. This way you can just hack away the scripts and try them out immediately without any further operations.
  13216. ===== out_rootfs_overlay_dir
  13217. This path can be found with:
  13218. ....
  13219. ./getvar out_rootfs_overlay_dir
  13220. ....
  13221. This output directory contains all the files that LKMC will put inside the final image, including for example:
  13222. * <<userland-content>> that needs to be compiled
  13223. * <<rootfs_overlay>> content that gets put inside the image as is
  13224. LKMC first collects all the files that it will dump into the guest there, and then in the very last step dumps everything into the final image.
  13225. In Buildroot, this is done by pointing `BR2_ROOTFS_OVERLAY` to that directory.
  13226. This does not include native image modification mechanisms such as <<buildroot_packages-directory,Buildroot packages>>, which we let Buildroot itself manage.
  13227. ==== lkmc.c
  13228. The files:
  13229. * link:lkmc.c[]
  13230. * link:lkmc.h[]
  13231. contain common C function helpers that can be used both in userland and baremetal. Oh, the infinite <<about-the-baremetal-setup,joys of Newlib>>.
  13232. Those files also contain arch specific helpers under ifdefs like:
  13233. ....
  13234. #if defined(__aarch64__)
  13235. ....
  13236. We try to keep as much as possible in those files. It bloats builds a little, but just makes everything simpler to understand.
  13237. ==== rand_check.out
  13238. Print out several parameters that normally change randomly from boot to boot:
  13239. ....
  13240. ./run --eval-after './linux/rand_check.out;./linux/poweroff.out'
  13241. ....
  13242. Source: link:userland/linux/rand_check.c[]
  13243. This can be used to check the determinism of:
  13244. * <<norandmaps>>
  13245. * <<qemu-record-and-replay>>
  13246. ==== lkmc_home
  13247. `lkmc_home` refers to the target base directory in which we put all our custom built stuff, such as <<userland-setup,userland executables>> and <<your-first-kernel-module-hack,kernel modules>>.
  13248. The current value can be found with:
  13249. ....
  13250. ./getvar guest_lkmc_home
  13251. ....
  13252. In the past, we used to dump everything into the root filesystem, but as the userland structure got more complex with subfolders, we decided that the risk of conflicting with important root files was becoming too great.
  13253. To save you from typing that path every time, we have made our most common commands `cd` into that directory by default for you, e.g.:
  13254. * interactive shells `cd` there through <<busybox-shell-initrc-files>>
  13255. * `--eval` and `--eval-after` through <<replace-init>> and <<init-busybox>>
  13256. Whenever a relative path is used inside a guest sample command, e.g. `insmod hello.ko` or `./hello.out`, it means that the path lives in `lkmc_home` unless stated otherwise.
  13257. === Test this repo
  13258. ==== Automated tests
  13259. Run almost all tests:
  13260. ....
  13261. ./build-test --all-archs --all-emulators --size 3 && \
  13262. ./test --size 3
  13263. echo $?
  13264. ....
  13265. should output 0.
  13266. Sources:
  13267. * link:build-test[]
  13268. * link:test[]
  13269. The link:test[] script runs several different types of tests, which can also be run separately as explained at:
  13270. * link:test-boot[]
  13271. * <<test-userland-in-full-system>>
  13272. * <<user-mode-tests>>
  13273. * <<baremetal-tests>>
  13274. * <<gdb-tests>>
  13275. * <<gem5-unit-tests>>
  13276. link:test[] does not all possible tests, because there are too many possible variations and that would take forever. The rationale is the same as for `./build all` and is explained in `./build --help`.
  13277. ===== Test arch and emulator selection
  13278. You can select multiple archs and emulators of interest, as for an other command, with:
  13279. ....
  13280. ./test-executables \
  13281. --arch x86_64 \
  13282. --arch aarch64 \
  13283. --emulator gem5 \
  13284. --emulator qemu \
  13285. ;
  13286. ....
  13287. You can also test all supported archs and emulators with:
  13288. ....
  13289. ./test-executables \
  13290. --all-archs \
  13291. --all-emulators \
  13292. ;
  13293. ....
  13294. This command would run the test four times, using `x86_64` and `aarch64` with both gem5 and QEMU.
  13295. Without those flags, it defaults to just running the default arch and emulator once: `x86_64` and `qemu`.
  13296. ===== Quit on fail
  13297. By default, continue running even after the first failure happens, and they show a summary at the end.
  13298. You can make them exit immediately with the `--no-quit-on-fail` option, e.g.:
  13299. ....
  13300. ./test-executables --quit-on-fail
  13301. ....
  13302. ===== Test userland in full system
  13303. TODO: we really need a mechanism to automatically generate the test list automatically e.g. based on <<path-properties>>, currently there are many tests missing, and we have to add everything manually which is very annoying.
  13304. We could just generate it on the fly on the host, and forward it to guest through CLI arguments.
  13305. Run all userland tests from inside full system simulation (i.e. not <<user-mode-simulation>>):
  13306. ....
  13307. ./test-userland-full-system
  13308. ....
  13309. This includes, in particular, userland programs that test the kernel modules, which cannot be tested in user mode simulation.
  13310. Basically just boots and runs: link:rootfs_overlay/lkmc/test_all.sh[]
  13311. Failure is detected by looking for the <<magic-failure-string>>
  13312. Most userland programs that don't rely on kernel modules can also be tested in user mode simulation as explained at: xref:user-mode-tests[xrefstyle=full].
  13313. ===== GDB tests
  13314. We have some https://github.com/pexpect/pexpect[pexpect] automated tests for GDB for both userland and baremetal programs!
  13315. Run the userland tests:
  13316. ....
  13317. ./build --all-archs test-gdb && \
  13318. ./test-gdb --all-archs --all-emulators
  13319. ....
  13320. Run the baremetal tests instead:
  13321. ....
  13322. ./test-gdb --all-archs --all-emulators --mode baremetal
  13323. ....
  13324. Sources:
  13325. * link:test-gdb[]
  13326. * link:userland/gdb_tests/[]
  13327. * link:userland/arch/arm/gdb_tests/[]
  13328. * link:userland/arch/aarch64/gdb_tests/[]
  13329. If a test fails, re-run the test commands manually and use `--verbose` to understand what happened:
  13330. ....
  13331. ./run --arch arm --background --baremetal baremetal/c/add.c --gdb-wait &
  13332. ./run-gdb --arch arm --baremetal baremetal/c/add.c --verbose -- main
  13333. ....
  13334. and possibly repeat the GDB steps manually with the usual:
  13335. ....
  13336. ./run-gdb --arch arm --baremetal baremetal/c/add.c --no-continue --verbose
  13337. ....
  13338. To debug GDB problems on gem5, you might want to enable the following <<gem5-tracing,tracing>> options:
  13339. ....
  13340. ./run \
  13341. --arch arm \
  13342. --baremetal baremetal/c/add.c \
  13343. --gdb-wait \
  13344. --trace GDBRecv,GDBSend \
  13345. --trace-stdout \
  13346. ;
  13347. ....
  13348. ===== Magic failure string
  13349. We do not know of any way to set the emulator exit status in QEMU arm full system.
  13350. For other arch / emulator combinations, we know how to do it:
  13351. * aarch64: aarch64 semihosting supports exit status
  13352. * gem5: <<m5-fail>> works on all archs
  13353. * user mode: QEMU forwards exit status, for gem5 we do some log parsing as described at: xref:gem5-syscall-emulation-exit-status[xrefstyle=full]
  13354. Since we can't do it for QEMU arm, the only reliable solution is to just parse the guest serial output for a magic failure string to check if tests failed.
  13355. Our run scripts parse the serial output looking for a line line containing only exactly the magic regular expression:
  13356. ....
  13357. lkmc_exit_status_(\d+)
  13358. ....
  13359. and then exit with the given regular expression, e.g.:
  13360. ....
  13361. ./run --arch aarch64 baremetal/return2.c
  13362. echo $?
  13363. ....
  13364. should output:
  13365. ....
  13366. 2
  13367. ....
  13368. This magic output string is notably generated by:
  13369. * link:rootfs_overlay/lkmc/test_fail.sh[], which is used by <<test-userland-in-full-system>>
  13370. * the `exit()` baremetal function when `status != 1`.
  13371. +
  13372. Unfortunately the only way we found to set this up was with `on_exit`: https://github.com/cirosantilli/linux-kernel-module-cheat/issues/59[].
  13373. +
  13374. Trying to patch `_exit` directly fails since at that point some de-initialization has already happened which prevents the print.
  13375. +
  13376. So setup this `on_exit` automatically from all our <<baremetal-bootloaders>>, so it just works automatically for the examples that use the bootloaders: https://stackoverflow.com/questions/44097610/pass-parameter-to-atexit/49659697#49659697
  13377. +
  13378. The following examples end up testing that our setup is working:
  13379. +
  13380. * link:userland/c/assert_fail.c[]
  13381. * link:userland/c/return0.c[]
  13382. * link:userland/c/return1.c[]
  13383. * link:userland/c/return2.c[]
  13384. * link:userland/c/exit0.c[]
  13385. * link:userland/c/exit1.c[]
  13386. * link:userland/c/exit2.c[]
  13387. * link:userland/posix/kill.c[]
  13388. Beware that on Linux kernel simulations, you cannot even echo that string from userland, since userland stdout shows up on the serial.
  13389. ==== Non-automated tests
  13390. ===== Test GDB Linux kernel
  13391. For the Linux kernel, do the following manual tests for now.
  13392. Shell 1:
  13393. ....
  13394. ./run --gdb-wait
  13395. ....
  13396. Shell 2:
  13397. ....
  13398. ./run-gdb start_kernel
  13399. ....
  13400. Should break GDB at `start_kernel`.
  13401. Then proceed to do the following tests:
  13402. * `./count.sh` and `break __x64_sys_write`
  13403. * `insmod timer.ko` and `break lkmc_timer_callback`
  13404. ===== Test the Internet
  13405. You should also test that the Internet works:
  13406. ....
  13407. ./run --arch x86_64 --kernel-cli '- lkmc_eval="ifup -a;wget -S google.com;poweroff;"'
  13408. ....
  13409. ===== CLI script tests
  13410. `build-userland` and `test-executables` have a wide variety of target selection modes, and it was hard to keep them all working without some tests:
  13411. * link:test-build-userland[]
  13412. * link:test-test-executables[]
  13413. === Bisection
  13414. When updating the Linux kernel, QEMU and gem5, things sometimes break.
  13415. However, for many types of crashes, it is trivial to bisect down to the offending commit, in particular because we can make QEMU and gem5 exit with status 1 on kernel panic as mentioned at: xref:exit-emulator-on-panic[xrefstyle=full].
  13416. For example, when updating from QEMU `v2.12.0` to `v3.0.0-rc3`, the Linux kernel boot started to panic for `arm`.
  13417. We then bisected it as explained at: https://stackoverflow.com/questions/4713088/how-to-use-git-bisect/22592593#22592593 with the link:bisect-qemu-linux-boot[] script:
  13418. ....
  13419. root_dir="$(pwd)"
  13420. cd "$(./getvar qemu_source_dir)"
  13421. git bisect start
  13422. # Check that our test script fails on v3.0.0-rc3 as expected, and mark it as bad.
  13423. "${root_dir}/bisect-qemu-linux-boot"
  13424. # Should output 1.
  13425. echo #?
  13426. git bisect bad
  13427. # Same for the good end.
  13428. git checkout v2.12.0
  13429. "${root_dir}/bisect-qemu-linux-boot"
  13430. # Should output 0.
  13431. echo #?
  13432. git bisect good
  13433. # This leaves us at the offending commit.
  13434. git bisect run "${root_dir}/bisect-qemu-linux-boot"
  13435. # Clean up after the bisection.
  13436. git bisect reset
  13437. git submodule update
  13438. "${root_dir}/build-qemu" --clean --qemu-build-id bisect
  13439. ....
  13440. Other bisection helpers include:
  13441. * link:bisect-linux-boot-gem5[]
  13442. * link:bisect-gem5-linux-boot[]
  13443. [[path-properties]]
  13444. === path_properties
  13445. In order to build and run each userland and <<baremetal-setup,baremetal>> example properly, we need per-file metadata such as compiler flags and required number of cores.
  13446. This data is stored is stored in link:path_properties.py[] at `path_properties_tuples`.
  13447. Maybe we should embed it magically into source files directories to make it easier to see? But one big Python dict was easier to implement so we started like this. And it allows factoring chunks out easily.
  13448. The format is as follows:
  13449. ....
  13450. 'path_component': (
  13451. {'property': value},
  13452. {
  13453. 'child_path_component':
  13454. {
  13455. {'child_property': },
  13456. {}
  13457. }
  13458. }
  13459. )
  13460. ....
  13461. and as a shortcut, paths that don't have any children can be written directly as:
  13462. .....
  13463. 'path_component': {'property': value}
  13464. .....
  13465. Properties of parent directories apply to all children.
  13466. Lists coming from parent directories are extended instead of overwritten by children, this is especially useful for C compiler flags.
  13467. === Update a forked submodule
  13468. This is a template update procedure for submodules for which we have some patches on on top of mainline.
  13469. This example is based on the Linux kernel, for which we used to have patches, but have since moved to mainline:
  13470. ....
  13471. # Last point before out patches.
  13472. last_mainline_revision=v4.15
  13473. next_mainline_revision=v4.16
  13474. cd "$(./getvar linux_source_dir)"
  13475. # Create a branch before the rebase in case things go wrong.
  13476. git checkout -b "lkmc-${last_mainline_revision}"
  13477. git remote set-url origin git@github.com:cirosantilli/linux.git
  13478. git push
  13479. git checkout master
  13480. git fetch up
  13481. git rebase --onto "$next_mainline_revision" "$last_mainline_revision"
  13482. # And update the README to show off.
  13483. git commit -m "linux: update to ${next_mainline_revision}"
  13484. ....
  13485. === Release
  13486. ==== Release procedure
  13487. Ensure that the <<automated-tests>> are passing on a clean build:
  13488. ....
  13489. mv out out.bak
  13490. ./build-test --size 3 && ./test --size 3
  13491. ....
  13492. The `./build-test` command builds a superset of what will be downloaded which also tests other things we would like to be working on the release. For the minimal build to generate the files to be uploaded, see: xref:release-zip[xrefstyle=full]
  13493. The clean build is necessary as it generates clean images since <<remove-buildroot-packages,it is not possible to remove Buildroot packages>>
  13494. Run all tests in <<non-automated-tests>> just QEMU x86_64 and QEMU aarch64.
  13495. TODO: not working currently, so skipped: Ensure that the <<benchmark-this-repo,benchmarks>> look fine:
  13496. ....
  13497. ./bench-all -A
  13498. ....
  13499. Create a release candidate and upload it:
  13500. ....
  13501. git tag -a -m '' v3.0-rc1
  13502. git push --follow-tags
  13503. ./release-zip --all-archs
  13504. # export LKMC_GITHUB_TOKEN=<your-token>
  13505. ./release-upload
  13506. ....
  13507. Now let's do an out-of-box testing for the release candidate:
  13508. ....
  13509. cd ..
  13510. git clone https://github.com/cirosantilli/linux-kernel-module-cheat linux-kernel-module-cheat-release
  13511. cd linux-kernel-module-cheat-release
  13512. ....
  13513. Test <<prebuilt>>.
  13514. Clean up, and re-start from scratch:
  13515. ....
  13516. cd ..
  13517. rm -rf linux-kernel-module-cheat-release
  13518. git clone https://github.com/cirosantilli/linux-kernel-module-cheat linux-kernel-module-cheat-release
  13519. cd linux-kernel-module-cheat-release
  13520. ....
  13521. Go through all the other <<getting-started>> sections in order.
  13522. Once everything looks fine, publish the release with:
  13523. ....
  13524. git tag -a v3.0
  13525. # Describe the release int the tag message.
  13526. git push --follow-tags
  13527. ./release-zip --all-archs
  13528. # export LKMC_GITHUB_TOKEN=<your-token>
  13529. ./release-upload
  13530. ....
  13531. ==== release-zip
  13532. Create a zip containing all files required for <<prebuilt>>:
  13533. ....
  13534. ./build --all-archs release && ./release-zip --all-archs
  13535. ....
  13536. Source: link:release-zip[]
  13537. This generates a zip file:
  13538. ....
  13539. echo "$(./getvar release_zip_file)"
  13540. ....
  13541. which you can then upload somewhere.
  13542. ==== release-upload
  13543. After:
  13544. * running <<release-zip>>
  13545. * creating and pushing a tag to GitHub
  13546. you can upload the release to GitHub automatically with:
  13547. ....
  13548. # export LKMC_GITHUB_TOKEN=<your-token>
  13549. ./release-upload
  13550. ....
  13551. Source: link:release-upload[]
  13552. The HEAD of the local repository must be on top of a tag that has been pushed for this to work.
  13553. Create `LKMC_GITHUB_TOKEN` under: https://github.com/settings/tokens/new and save it to your `.bashrc`.
  13554. The implementation of this script is described at:
  13555. * https://stackoverflow.com/questions/5207269/how-to-release-a-build-artifact-asset-on-github-with-a-script/52354732#52354732
  13556. * https://stackoverflow.com/questions/38153418/can-someone-give-a-python-requests-example-of-uploading-a-release-asset-in-githu/52354681#52354681
  13557. === Design rationale
  13558. ==== Design goals
  13559. This project was created to help me understand, modify and test low level system components by using system simulators.
  13560. System simulators are cool compared to real hardware because they are:
  13561. * free
  13562. * make experiments highly reproducible
  13563. * give full visibility to the system: you can inspect any byte in memory, or the state of any hardware register. The laws of physics sometimes get in the way when doing that for real hardware.
  13564. The current components we focus the most on are:
  13565. * <<linux-kernel>> and Linux kernel modules
  13566. * full systems emulators, currently <<qemu-buildroot-setup,qemu>> and <<gem5-buildroot-setup,gem5>>
  13567. * <<buildroot>>. We use and therefore document, a large part of its feature set.
  13568. The following components are not covered, but they would also benefit from this setup, and it shouldn't be hard to add them:
  13569. * C standard libraries
  13570. * compilers. Project idea: add a new instruction to x86, then hack up GCC to actually use it, and make a C program that generates it.
  13571. The design goals are to provide setups that are:
  13572. * highly automated: "just works"
  13573. * thoroughly documented: you know what "just works" means
  13574. * can be fully built from source: to give visibility and allow modifications
  13575. * can also use <<prebuilt, prebuilt binaries>> as much as possible: in case you are lazy or unable to build from source
  13576. We aim to make a documentation that contains a very high runnable example / theory bullshit ratio.
  13577. Having at least one example per section is ideal, and it should be the very first thing in the section if possible.
  13578. ==== Setup trade-offs
  13579. The trade-offs between the different <<getting-started,setups>> are basically a balance between:
  13580. * speed ans size: how long and how much disk space do the build and run take?
  13581. * visibility: can you GDB step debug everything and read source code?
  13582. * modifiability: can you modify the source code and rebuild a modified version?
  13583. * portability: does it work on a Windows host? Could it ever?
  13584. * accuracy: how accurate does the simulation represent real hardware?
  13585. * compatibility: how likely is is that all the components will work well together: emulator, compiler, kernel, standard library, ...
  13586. * guest software availability: how wide is your choice of easily installed guest software packages? See also: xref:linux-distro-choice[xrefstyle=full]
  13587. ==== Resource tradeoff guidelines
  13588. Choosing which features go into our default builds means making tradeoffs, here are our guidelines:
  13589. * keep the root filesystem as tiny as possible to make <<prebuilt>> small: only add BusyBox to have a small interactive system.
  13590. +
  13591. It is easy to add new packages once you have the toolchain, and if you don't there are infinitely many packages to cover and we can't cover them all.
  13592. * enable every feature possible on the toolchain (GCC, Binutils), because changes imply Buildroot rebuilds
  13593. * runtime is sacred. Faster systems are:
  13594. +
  13595. --
  13596. ** easier to understand
  13597. ** run faster, which is specially for <<gem5>> which is slow
  13598. --
  13599. +
  13600. Runtime basically just comes down to how we configure the Linux kernel, since in the root filesystem all that matters is `init=`, and that is easy to control.
  13601. +
  13602. One possibility we could play with is to build loadable modules instead of built-in modules to reduce runtime, but make it easier to get started with the modules.
  13603. In order to learn how to measure some of those aspects, see: xref:benchmark-this-repo[xrefstyle=full].
  13604. ==== Linux distro choice
  13605. We haven't found the ultimate distro yet, here is a summary table of trade-offs that we care about: xref:table-lkmc-linux-distro-comparison[xrefstyle=full].
  13606. [[table-lkmc-linux-distro-comparison]]
  13607. .Comparison of Linux distros for usage in this repository
  13608. [options="header"]
  13609. |===
  13610. |Distro |Packages in single Git tree |Git tracked docs |Cross build without QEMU |Prebuilt downloads |Number of packages
  13611. |Buildroot 2018.05
  13612. |y
  13613. |y
  13614. |y
  13615. |n
  13616. |2k (1)
  13617. |Ubuntu 18.04
  13618. |n
  13619. |n
  13620. |n
  13621. |y
  13622. |50k (3)
  13623. |Yocto 2.5 (8)
  13624. |?
  13625. |y (5)
  13626. |?
  13627. |y (6)
  13628. |400 (7)
  13629. |Alpine Linux 3.8.0
  13630. |y
  13631. |n (1)
  13632. |?
  13633. |y
  13634. |2000 (4)
  13635. |===
  13636. * (1): Wiki... https://wiki.alpinelinux.org/wiki/Main_Page
  13637. * (2): `ls packages | wc`
  13638. * (3): https://askubuntu.com/questions/120630/how-many-packages-are-in-the-main-repository
  13639. * (4): `ls main community non-free | wc`
  13640. * (5): yes, but on a separate Git tree... https://git.yoctoproject.org/cgit/cgit.cgi/yocto-docs/
  13641. * (6): yes, but the initial Poky build / download still took 5 hours on <<38mbps-internet>>, and QEMU failed to boot at the end... https://bugzilla.yoctoproject.org/show_bug.cgi?id=12953
  13642. * (7): `ls recipes-* | wc`
  13643. * (8): Poky reference system: http://git.yoctoproject.org/cgit/cgit.cgi/poky
  13644. Other interesting possibilities that I haven't evaluated well:
  13645. * NixOS https://nixos.org/ Seems to support full build from source well. Not much cross compilation information however.
  13646. * Gentoo https://en.wikipedia.org/wiki/Gentoo_Linux Seems to support full build from source well.
  13647. === Soft topics
  13648. ==== Fairy tale
  13649. ____
  13650. Once upon a time, there was a boy called Linus.
  13651. Linus made a super fun toy, and since he was not very humble, decided to call it Linux.
  13652. Linux was an awesome toy, but it had one big problem: it was very difficult to learn how to play with it!
  13653. As a result, only some weird kids who were very bored ended up playing with Linux, and everyone thought those kids were very cool, in their own weird way.
  13654. One day, a mysterious new kid called Ciro tried to play with Linux, and like many before him, got very frustrated, and gave up.
  13655. A few years later, Ciro had grown up a bit, and by chance came across a very cool toy made by the boy Petazzoni and his gang: it was called Buildroot.
  13656. Ciro noticed that if you used Buildroot together with Linux, and Linux suddenly became very fun to play with!
  13657. So Ciro decided to explain to as many kids as possible how to use Buildroot to play with Linux.
  13658. And so everyone was happy. Except some of the old weird kernel hackers who wanted to keep their mystique, but so be it.
  13659. THE END
  13660. ____
  13661. ==== Should you waste your life with systems programming?
  13662. Being the hardcore person who fully understands an important complex system such as a computer, it does have a nice ring to it doesn't it?
  13663. But before you dedicate your life to this nonsense, do consider the following points:
  13664. * almost all contributions to the kernel are done by large companies, and if you are not an employee in one of them, you are likely not going to be able to do much.
  13665. +
  13666. This can be inferred by the fact that the `devices/` directory is by far the largest in the kernel.
  13667. +
  13668. The kernel is of course just an interface to hardware, and the hardware developers start developing their kernel stuff even before specs are publicly released, both to help with hardware development and to have things working when the announcement is made.
  13669. +
  13670. Furthermore, I believe that there are in-tree devices which have never been properly publicly documented. Linus is of course fine with this, since code == documentation for him, but it is not as easy for mere mortals.
  13671. +
  13672. There are some less hardware bound higher level layers in the kernel which might not require being in a hardware company, and a few people must be living off it.
  13673. +
  13674. But of course, those are heavily motivated by the underlying hardware characteristics, and it is very likely that most of the people working there were previously at a hardware company.
  13675. +
  13676. In that sense, therefore, the kernel is not as open as one might want to believe.
  13677. * it is impossible to become rich with this knowledge.
  13678. +
  13679. This is partly implied by the fact that you need to be in a big company to make useful low level things, and therefore you will only be a tiny cog in the engine.
  13680. +
  13681. The key problem is that the entry cost of hardware design is just too insanely high for startups in general.
  13682. * Is learning this the most useful thing that you think can do for society?
  13683. +
  13684. Or are you just learning it for job security and having a nice sounding title?
  13685. +
  13686. I'm not a huge fan of the person, but I think Jobs said it right: https://www.youtube.com/watch?v=FF-tKLISfPE
  13687. +
  13688. First determine the useful goal, and then backtrack down to the most efficient thing you can do to reach it.
  13689. * there are two things that sadden me compared to physics-based engineering:
  13690. +
  13691. --
  13692. ** you will never become eternally famous. All tech disappears sooner or later, while laws of nature, at least as useful approximations, stay unchanged.
  13693. ** every problem that you face is caused by imperfections introduced by other humans.
  13694. +
  13695. It is much easier to accept limitations of physics, and even natural selection in biology, which is are produced by a sentient being (?).
  13696. --
  13697. +
  13698. Physics-based engineering, just like low level hardware, is of course completely closed source however, since wrestling against the laws of physics is about the most expensive thing humans can do.
  13699. Are you fine with those points, and ready to continue wasting your life?
  13700. Good. In that case, read on, and let's have some fun together ;-)
  13701. === Bibliography
  13702. Runnable stuff:
  13703. * https://lwn.net/Kernel/LDD3/ the best book, but outdated. Updated source: https://github.com/martinezjavier/ldd3 But examples non-minimal and take too much brain power to understand.
  13704. * https://github.com/satoru-takeuchi/elkdat manual build process without Buildroot, very few and simple kernel modules. But it seem ktest + QEMU working, which is awesome. `./test` there patches ktest config dynamically based on CLI! Maybe we should just steal it since GPL licensed.
  13705. * https://github.com/tinyclub/linux-lab Buildroot based, no kernel modules?
  13706. * https://github.com/agelastic/eudyptula
  13707. * https://github.com/linux-kernel-labs Yocto based, source inside a kernel fork subdir: https://github.com/linux-kernel-labs/linux/tree/f08b9e4238dfc612a9d019e3705bd906930057fc/tools/labs which the author would like to upstream https://www.reddit.com/r/programming/comments/79w2q9/linux_device_driver_labs_the_linux_kernel/dp6of43/
  13708. * Android AOSP: https://stackoverflow.com/questions/1809774/how-to-compile-the-android-aosp-kernel-and-test-it-with-the-android-emulator/48310014#48310014 AOSP is basically a uber bloated Buildroot (2 hours build vs 30 minutes), Android is Linux based, and QEMU is the emulator backend. These instructions might work for debugging the kernel: https://github.com/Fuzion24/AndroidKernelExploitationPlayground
  13709. * https://github.com/s-matyukevich/raspberry-pi-os Does both an OS from scratch, and annotates the corresponding kernel source code. For RPI3, no QEMU support: https://github.com/s-matyukevich/raspberry-pi-os/issues/8
  13710. * https://github.com/pw4ever/linux-kernel-hacking-helper as of bd9952127e7eda643cbb6cb4c51ad7b5b224f438, Bash, Arch Linux rootfs
  13711. * https://github.com/MichielDerhaeg/build-linux untested. Manually builds musl and BusyBox, no Buildroot. Seems to use host packaged toolchain and tested on x86_64 only. Might contain a minimized kernel config.
  13712. Theory:
  13713. * http://nairobi-embedded.org you will fall here a lot when you start popping the hard QEMU Google queries. They have covered everything we do here basically, but with a more manual approach, while this repo automates everything.
  13714. +
  13715. I couldn't find the markup source code for the tutorials, and as a result when the domain went down in May 2018, you have to use http://web.archive.org/ to see the pages...
  13716. * https://balau82.wordpress.com awesome low level resource
  13717. * https://rwmj.wordpress.com/ awesome red hatter
  13718. * https://lwn.net
  13719. * http://www.makelinux.net
  13720. * https://notes.shichao.io/lkd/
  13721. Awesome lists:
  13722. * https://github.com/gurugio/lowlevelprogramming-university
  13723. * https://github.com/uhub/awesome-c