README.adoc 488 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645
  1. = Linux Kernel Module Cheat
  2. :idprefix:
  3. :idseparator: -
  4. :sectanchors:
  5. :sectlinks:
  6. :sectnumlevels: 6
  7. :sectnums:
  8. :toc: macro
  9. :toclevels: 6
  10. :toc-title:
  11. The perfect emulation setup to study and develop the <<linux-kernel>> v5.0, kernel modules, <<qemu-buildroot-setup,QEMU>>, <<gem5-buildroot-setup,gem5>> and x86_64, ARMv7 and ARMv8 <<userland-assembly,userland>> and <<baremetal-setup,baremetal>> assembly. <<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.
  12. TL;DR: <<qemu-buildroot-setup-getting-started>>
  13. toc::[]
  14. == Getting started
  15. Each child section describes a possible different setup for this repo.
  16. If you don't know which one to go for, start with <<qemu-buildroot-setup-getting-started>>.
  17. Design goals of this project are documented at: <<design-goals>>.
  18. === QEMU Buildroot setup
  19. ==== QEMU Buildroot setup getting started
  20. This setup has been mostly tested on Ubuntu. For other host operating systems see: <<supported-hosts>>. For greater stability, consider using the <<release-procedure,latest release>> instead of master: https://github.com/cirosantilli/linux-kernel-module-cheat/releases
  21. Reserve 12Gb of disk and run:
  22. ....
  23. git clone https://github.com/cirosantilli/linux-kernel-module-cheat
  24. cd linux-kernel-module-cheat
  25. ./build --download-dependencies qemu-buildroot
  26. ./run
  27. ....
  28. 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.
  29. If something goes wrong, see: <<common-build-issues>> and use our issue tracker: https://github.com/cirosantilli/linux-kernel-module-cheat/issues
  30. The initial build will take a while (30 minutes to 2 hours) to clone and build, see <<benchmark-builds>> for more details.
  31. If you don't want to wait, you could also try the following faster but much more limited methods:
  32. * <<prebuilt>>
  33. * <<host>>
  34. but you will soon find that they are simply not enough if you anywhere near serious about systems programming.
  35. 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:
  36. ....
  37. insmod hello.ko
  38. insmod hello2.ko
  39. rmmod hello
  40. rmmod hello2
  41. ....
  42. This should print to the screen:
  43. ....
  44. hello init
  45. hello2 init
  46. hello cleanup
  47. hello2 cleanup
  48. ....
  49. which are `printk` messages from `init` and `cleanup` methods of those modules.
  50. Sources:
  51. * link:kernel_modules/hello.c[]
  52. * link:kernel_modules/hello2.c[]
  53. Quit QEMU with:
  54. ....
  55. Ctrl-A X
  56. ....
  57. See also: <<quit-qemu-from-text-mode>>.
  58. All available modules can be found in the link:kernel_modules[] directory.
  59. It is super easy to build for different <<cpu-architecture,CPU architectures>>, just use the `--arch` option:
  60. ....
  61. ./build --arch aarch64 --download-dependencies qemu-buildroot
  62. ./run --arch aarch64
  63. ....
  64. To avoid typing `--arch aarch64` many times, you can set the default arch as explained at: <<default-command-line-arguments>>
  65. I now urge you to read the following sections which contain widely applicable information:
  66. * <<run-command-after-boot>>
  67. * <<clean-the-build>>
  68. * <<build-the-documentation>>
  69. * Linux kernel
  70. ** <<printk>>
  71. ** <<kernel-command-line-parameters>>
  72. Once you use <<gdb>> and <<tmux>>, your terminal will look a bit like this:
  73. ....
  74. [ 1.451857] input: AT Translated Set 2 keyboard as /devices/platform/i8042/s1│loading @0xffffffffc0000000: ../kernel_modules-1.0//timer.ko
  75. [ 1.454310] ledtrig-cpu: registered to indicate activity on CPUs │(gdb) b lkmc_timer_callback
  76. [ 1.455621] usbcore: registered new interface driver usbhid │Breakpoint 1 at 0xffffffffc0000000: file /home/ciro/bak/git/linux-kernel-module
  77. [ 1.455811] usbhid: USB HID core driver │-cheat/out/x86_64/buildroot/build/kernel_modules-1.0/./timer.c, line 28.
  78. [ 1.462044] NET: Registered protocol family 10 │(gdb) c
  79. [ 1.467911] Segment Routing with IPv6 │Continuing.
  80. [ 1.468407] sit: IPv6, IPv4 and MPLS over IPv4 tunneling driver │
  81. [ 1.470859] NET: Registered protocol family 17 │Breakpoint 1, lkmc_timer_callback (data=0xffffffffc0002000 <mytimer>)
  82. [ 1.472017] 9pnet: Installing 9P2000 support │ at /linux-kernel-module-cheat//out/x86_64/buildroot/build/
  83. [ 1.475461] sched_clock: Marking stable (1473574872, 0)->(1554017593, -80442)│kernel_modules-1.0/./timer.c:28
  84. [ 1.479419] ALSA device list: │28 {
  85. [ 1.479567] No soundcards found. │(gdb) c
  86. [ 1.619187] ata2.00: ATAPI: QEMU DVD-ROM, 2.5+, max UDMA/100 │Continuing.
  87. [ 1.622954] ata2.00: configured for MWDMA2 │
  88. [ 1.644048] scsi 1:0:0:0: CD-ROM QEMU QEMU DVD-ROM 2.5+ P5│Breakpoint 1, lkmc_timer_callback (data=0xffffffffc0002000 <mytimer>)
  89. [ 1.741966] tsc: Refined TSC clocksource calibration: 2904.010 MHz │ at /linux-kernel-module-cheat//out/x86_64/buildroot/build/
  90. [ 1.742796] clocksource: tsc: mask: 0xffffffffffffffff max_cycles: 0x29dc0f4s│kernel_modules-1.0/./timer.c:28
  91. [ 1.743648] clocksource: Switched to clocksource tsc │28 {
  92. [ 2.072945] input: ImExPS/2 Generic Explorer Mouse as /devices/platform/i8043│(gdb) bt
  93. [ 2.078641] EXT4-fs (vda): couldn't mount as ext3 due to feature incompatibis│#0 lkmc_timer_callback (data=0xffffffffc0002000 <mytimer>)
  94. [ 2.080350] EXT4-fs (vda): mounting ext2 file system using the ext4 subsystem│ at /linux-kernel-module-cheat//out/x86_64/buildroot/build/
  95. [ 2.088978] EXT4-fs (vda): mounted filesystem without journal. Opts: (null) │kernel_modules-1.0/./timer.c:28
  96. [ 2.089872] VFS: Mounted root (ext2 filesystem) readonly on device 254:0. │#1 0xffffffff810ab494 in call_timer_fn (timer=0xffffffffc0002000 <mytimer>,
  97. [ 2.097168] devtmpfs: mounted │ fn=0xffffffffc0000000 <lkmc_timer_callback>) at kernel/time/timer.c:1326
  98. [ 2.126472] Freeing unused kernel memory: 1264K │#2 0xffffffff810ab71f in expire_timers (head=<optimized out>,
  99. [ 2.126706] Write protecting the kernel read-only data: 16384k │ base=<optimized out>) at kernel/time/timer.c:1363
  100. [ 2.129388] Freeing unused kernel memory: 2024K │#3 __run_timers (base=<optimized out>) at kernel/time/timer.c:1666
  101. [ 2.139370] Freeing unused kernel memory: 1284K │#4 run_timer_softirq (h=<optimized out>) at kernel/time/timer.c:1692
  102. [ 2.246231] EXT4-fs (vda): warning: mounting unchecked fs, running e2fsck isd│#5 0xffffffff81a000cc in __do_softirq () at kernel/softirq.c:285
  103. [ 2.259574] EXT4-fs (vda): re-mounted. Opts: block_validity,barrier,user_xatr│#6 0xffffffff810577cc in invoke_softirq () at kernel/softirq.c:365
  104. hello S98 │#7 irq_exit () at kernel/softirq.c:405
  105. │#8 0xffffffff818021ba in exiting_irq () at ./arch/x86/include/asm/apic.h:541
  106. Apr 15 23:59:23 login[49]: root login on 'console' │#9 smp_apic_timer_interrupt (regs=<optimized out>)
  107. hello /root/.profile │ at arch/x86/kernel/apic/apic.c:1052
  108. # insmod /timer.ko │#10 0xffffffff8180190f in apic_timer_interrupt ()
  109. [ 6.791945] timer: loading out-of-tree module taints kernel. │ at arch/x86/entry/entry_64.S:857
  110. # [ 7.821621] 4294894248 │#11 0xffffffff82003df8 in init_thread_union ()
  111. [ 8.851385] 4294894504 │#12 0x0000000000000000 in ?? ()
  112. │(gdb)
  113. ....
  114. ==== How to hack stuff
  115. 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.
  116. ===== Your first Linux kernel hack
  117. Let's hack up the <<linux-kernel-entry-point, Linux kernel entry point>>, which is an easy place to start.
  118. Open the file:
  119. ....
  120. vim submodules/linux/init/main.c
  121. ....
  122. and find the `start_kernel` function, then add there a:
  123. ....
  124. pr_info("I'VE HACKED THE LINUX KERNEL!!!");
  125. ....
  126. Then rebuild the Linux kernel, quit QEMU and reboot the modified kernel:
  127. ....
  128. ./build-linux
  129. ./run
  130. ....
  131. and, surely enough, your message has appeared at the beginning of the boot:
  132. ....
  133. <6>[ 0.000000] I'VE HACKED THE LINUX KERNEL!!!
  134. ....
  135. So you are now officially a Linux kernel hacker, way to go!
  136. 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:
  137. * saves a few seconds from parsing Make scripts and reading timestamps
  138. * makes it easier to understand what is being done in more detail
  139. * allows passing more specific options to customize the build
  140. The link:build[] script is just a lightweight wrapper that calls the smaller build scripts, and you can see what `./build` does with:
  141. ....
  142. ./build --dry-run
  143. ....
  144. When you reach difficulties, QEMU makes it possible to easily GDB step debug the Linux kernel source code, see: <<gdb>>.
  145. ===== Your first kernel module hack
  146. Edit link:kernel_modules/hello.c[] to contain:
  147. ....
  148. pr_info("hello init hacked\n");
  149. ....
  150. and rebuild with:
  151. ....
  152. ./build-modules
  153. ....
  154. Now there are two ways to test it out: the fast way, and the safe way.
  155. The fast way is, without quitting or rebooting QEMU, just directly re-insert the module with:
  156. ....
  157. insmod /mnt/9p/out_rootfs_overlay/lkmc/hello.ko
  158. ....
  159. and the new `pr_info` message should now show on the terminal at the end of the boot.
  160. 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:
  161. ....
  162. ls "$(./getvar out_rootfs_overlay_dir)"
  163. ....
  164. 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.
  165. Such failures are however unlikely, and you should be fine if you don't see anything weird happening.
  166. The safe way, is to fist <<rebuild-buildroot-while-running,quit QEMU>>, rebuild the modules, put them in the root filesystem, and then reboot:
  167. ....
  168. ./build-modules
  169. ./build-buildroot
  170. ./run --eval-after 'insmod hello.ko'
  171. ....
  172. `./build-buildroot` is required after `./build-modules` because it re-generates the root filesystem with the modules that we compiled at `./build-modules`.
  173. You can see that `./build` does that as well, by running:
  174. ....
  175. ./build --dry-run
  176. ....
  177. `--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.
  178. If the guest and host are the same arch, typically x86_64, you can speed up boot further with <<kvm>>:
  179. ....
  180. ./run --kvm
  181. ....
  182. All of this put together makes the safe procedure acceptably fast for regular development as well.
  183. It is also easy to GDB step debug kernel modules with our setup, see: <<gdb-step-debug-kernel-module>>.
  184. ===== Your first QEMU hack
  185. Not satisfied with mere software? OK then, let's hack up the QEMU x86 CPU identification:
  186. ....
  187. vim submodules/qemu/target/i386/cpu.c
  188. ....
  189. and modify:
  190. ....
  191. .model_id = "QEMU Virtual CPU version " QEMU_HW_VERSION,
  192. ....
  193. to contain:
  194. ....
  195. .model_id = "QEMU Virtual CPU version HACKED " QEMU_HW_VERSION,
  196. ....
  197. then as usual rebuild and re-run:
  198. .....
  199. ./build-qemu
  200. ./run --eval-after 'grep "model name" /proc/cpuinfo'
  201. .....
  202. and once again, there is your message: QEMU communicated it to the Linux kernel, which printed it out.
  203. You have now gone from newb to hardware hacker in a mere 15 minutes, your rate of progress is truly astounding!!!
  204. 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:
  205. * link:https://en.wikipedia.org/wiki/Semiconductor_fabrication_plant[Silicon fabs] don't publish reveal their link:https://en.wikipedia.org/wiki/Design_rule_checking[design rules]
  206. * which implies that there are no decent link: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
  207. * which implies that people can't develop open source link:https://en.wikipedia.org/wiki/Electronic_design_automation[EDA tools]
  208. * which implies that you can't get decent link:https://community.cadence.com/cadence_blogs_8/b/di/posts/hls-ppa-is-it-all-you-need-to-know[power, performance and area] estimates
  209. The only thing you can do with open source is purely functional designs with link:https://en.wikipedia.org/wiki/Verilator[Verilator], but you will never know if it can be actually produced and how efficient it can be.
  210. If you really want to develop semiconductors, your only choice is to join an university or a semiconductor company that has the EDA licenses.
  211. See also: <<should-you-waste-your-life-with-systems-programming>>.
  212. 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: <<debug-the-emulator>>.
  213. ===== Your first glibc hack
  214. 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: link:https://github.com/buildroot/buildroot/blob/2018.05/package/glibc/glibc.mk#L13[package/glibc/glibc.mk]. Buildroot 2018.05 applies no patches.
  215. Let's hack up the `puts` function:
  216. ....
  217. ./build-buildroot -- glibc-reconfigure
  218. ....
  219. with the patch:
  220. ....
  221. diff --git a/libio/ioputs.c b/libio/ioputs.c
  222. index 706b20b492..23185948f3 100644
  223. --- a/libio/ioputs.c
  224. +++ b/libio/ioputs.c
  225. @@ -38,8 +38,9 @@ _IO_puts (const char *str)
  226. if ((_IO_vtable_offset (_IO_stdout) != 0
  227. || _IO_fwide (_IO_stdout, -1) == -1)
  228. && _IO_sputn (_IO_stdout, str, len) == len
  229. + && _IO_sputn (_IO_stdout, " hacked", 7) == 7
  230. && _IO_putc_unlocked ('\n', _IO_stdout) != EOF)
  231. - result = MIN (INT_MAX, len + 1);
  232. + result = MIN (INT_MAX, len + 1 + 7);
  233. _IO_release_lock (_IO_stdout);
  234. return result;
  235. ....
  236. And then:
  237. ....
  238. ./run --eval-after './c/hello.out'
  239. ....
  240. outputs:
  241. ....
  242. hello hacked
  243. ....
  244. Lol!
  245. We can also test our hacked glibc on <<user-mode-simulation>> with:
  246. ....
  247. ./run --userland userland/c/hello.c
  248. ....
  249. I just noticed that this is actually a good way to develop glibc for other archs.
  250. 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
  251. 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:
  252. * https://stackoverflow.com/questions/10412684/how-to-compile-my-own-glibc-c-standard-library-from-source-and-use-it/52454710#52454710
  253. * https://stackoverflow.com/questions/847179/multiple-glibc-libraries-on-a-single-host/52454603#52454603
  254. * 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
  255. Tested on a30ed0f047523ff2368d421ee2cce0800682c44e + 1.
  256. ===== Your first Binutils hack
  257. Have you ever felt that a single `inc` instruction was not enough? Really? Me too!
  258. So let's hack the <<gnu-gas-assembler>>, which is part of link:https://en.wikipedia.org/wiki/GNU_Binutils[GNU Binutils], to add a new shiny version of `inc` called... `myinc`!
  259. 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/asm_hello.c[] but with `myinc` instead of `inc`.
  260. The inline assembly is disabled with an `#ifdef`, so first modify the source to enable that.
  261. Then, try to build userland:
  262. ....
  263. ./build-userland
  264. ....
  265. and watch it fail with:
  266. ....
  267. binutils_hack.c:8: Error: no such instruction: `myinc %rax'
  268. ....
  269. Now, edit the file
  270. ....
  271. vim submodules/binutils-gdb/opcodes/i386-tbl.h
  272. ....
  273. and add a copy of the `"inc"` instruction just next to it, but with the new name `"myinc"`:
  274. ....
  275. diff --git a/opcodes/i386-tbl.h b/opcodes/i386-tbl.h
  276. index af583ce578..3cc341f303 100644
  277. --- a/opcodes/i386-tbl.h
  278. +++ b/opcodes/i386-tbl.h
  279. @@ -1502,6 +1502,19 @@ const insn_template i386_optab[] =
  280. { { { 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  281. 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0,
  282. 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 } } } },
  283. + { "myinc", 1, 0xfe, 0x0, 1,
  284. + { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  285. + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  286. + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  287. + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  288. + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
  289. + { 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  290. + 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 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 },
  293. + { { { 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  294. + 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0,
  295. + 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 } } } },
  296. { "sub", 2, 0x28, None, 1,
  297. { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  299. ....
  300. Finally, rebuild Binutils, userland and test our program with <<user-mode-simulation>>:
  301. ....
  302. ./build-buildroot -- host-binutils-rebuild
  303. ./build-userland --static
  304. ./run --static --userland userland/arch/x86_64/binutils_hack.c
  305. ....
  306. and we se that `myinc` worked since the assert did not fail!
  307. Tested on b60784d59bee993bf0de5cde6c6380dd69420dda + 1.
  308. ===== Your first GCC hack
  309. OK, now time to hack GCC.
  310. For convenience, let's use the <<user-mode-simulation>>.
  311. If we run the program link:userland/c/gcc_hack.c[]:
  312. ....
  313. ./build-userland --static
  314. ./run --static --userland userland/c/gcc_hack.c
  315. ....
  316. it produces the normal boring output:
  317. ....
  318. i = 2
  319. j = 0
  320. ....
  321. So how about we swap `++` and `--` to make things more fun?
  322. Open the file:
  323. ....
  324. vim submodules/gcc/gcc/c/c-parser.c
  325. ....
  326. and find the function `c_parser_postfix_expression_after_primary`.
  327. In that function, swap `case CPP_PLUS_PLUS` and `case CPP_MINUS_MINUS`:
  328. ....
  329. diff --git a/gcc/c/c-parser.c b/gcc/c/c-parser.c
  330. index 101afb8e35f..89535d1759a 100644
  331. --- a/gcc/c/c-parser.c
  332. +++ b/gcc/c/c-parser.c
  333. @@ -8529,7 +8529,7 @@ c_parser_postfix_expression_after_primary (c_parser *parser,
  334. expr.original_type = DECL_BIT_FIELD_TYPE (field);
  335. }
  336. break;
  337. - case CPP_PLUS_PLUS:
  338. + case CPP_MINUS_MINUS:
  339. /* Postincrement. */
  340. start = expr.get_start ();
  341. finish = c_parser_peek_token (parser)->get_finish ();
  342. @@ -8548,7 +8548,7 @@ c_parser_postfix_expression_after_primary (c_parser *parser,
  343. expr.original_code = ERROR_MARK;
  344. expr.original_type = NULL;
  345. break;
  346. - case CPP_MINUS_MINUS:
  347. + case CPP_PLUS_PLUS:
  348. /* Postdecrement. */
  349. start = expr.get_start ();
  350. finish = c_parser_peek_token (parser)->get_finish ();
  351. ....
  352. Now rebuild GCC, the program and re-run it:
  353. ....
  354. ./build-buildroot -- host-gcc-final-rebuild
  355. ./build-userland --static
  356. ./run --static --userland userland/c/gcc_hack.c
  357. ....
  358. and the new ouptut is now:
  359. ....
  360. i = 2
  361. j = 0
  362. ....
  363. 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:
  364. * https://stackoverflow.com/questions/39883865/why-multiple-passes-for-building-linux-from-scratch-lfs
  365. * https://stackoverflow.com/questions/27457835/why-do-cross-compilers-have-a-two-stage-compilation
  366. ==== About the QEMU Buildroot setup
  367. This is our reference setup, and the best supported one, use it unless you have good reason not to.
  368. It was historically the first one we did, and all sections have been tested with this setup unless explicitly noted.
  369. Read the following sections for further introductory material:
  370. * <<introduction-to-qemu>>
  371. * <<introduction-to-buildroot>>
  372. === gem5 Buildroot setup
  373. ==== About the gem5 Buildroot setup
  374. This setup is like the <<qemu-buildroot-setup>>, but it uses link:http://gem5.org/[gem5] instead of QEMU as a system simulator.
  375. 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.
  376. 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.
  377. gem5 on the other hand, can simulate the system in more detail than QEMU, including:
  378. * simplified CPU pipeline
  379. * caches
  380. * DRAM timing
  381. and can therefore be used to estimate system performance, see: <<gem5-run-benchmark>> for an example.
  382. The downside of gem5 much slower than QEMU because of the greater simulation detail.
  383. See <<gem5-vs-qemu>> for a more thorough comparison.
  384. ==== gem5 Buildroot setup getting started
  385. For the most part, if you just add the `--emulator gem5` option or `*-gem5` suffix to all commands and everything should magically work.
  386. If you haven't built Buildroot yet for <<qemu-buildroot-setup>>, you can build from the beginning with:
  387. ....
  388. ./build --download-dependencies gem5-buildroot
  389. ./run --emulator gem5
  390. ....
  391. 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.
  392. Remember that the gem5 boot is <<benchmark-linux-kernel-boot,considerably slower>> than QEMU since the simulation is more detailed.
  393. To get a terminal, either open a new shell and run:
  394. ....
  395. ./gem5-shell
  396. ....
  397. You can quit the shell without killing gem5 by typing tilde followed by a period:
  398. ....
  399. ~.
  400. ....
  401. 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:
  402. ....
  403. ./run --emulator gem5 --tmux
  404. ....
  405. See also: <<tmux-gem5>>.
  406. 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:
  407. ....
  408. # <6>[ 1.215329] clocksource: tsc: mask: 0xffffffffffffffff max_cycles: 0x1cd486fa865, max_idle_ns: 440795259574 ns
  409. <6>[ 1.215351] clocksource: Switched to clocksource tsc
  410. ....
  411. but if you look closely, the `PS1` prompt marker `#` is there already, just hit enter and a clear prompt line will appear.
  412. If you forgot to open the shell and gem5 exit, you can inspect the terminal output post-mortem at:
  413. ....
  414. less "$(./getvar --emulator gem5 m5out_dir)/system.pc.com_1.device"
  415. ....
  416. More gem5 information is present at: <<gem5>>
  417. Good next steps are:
  418. * <<gem5-run-benchmark>>
  419. * <<m5out-directory>>
  420. * <<m5ops>>
  421. [[docker]]
  422. === Docker host setup
  423. This repository has been tested inside clean link:https://en.wikipedia.org/wiki/Docker_(software)[Docker] containers.
  424. 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: <<supported-hosts>>.
  425. For example, to do a <<qemu-buildroot-setup>> inside Docker, run:
  426. ....
  427. sudo apt-get install docker
  428. ./run-docker create && \
  429. ./run-docker sh -- ./build --download-dependencies qemu-buildroot
  430. ./run-docker sh
  431. ....
  432. You are now left inside a shell in the Docker! From there, just run as usual:
  433. ....
  434. ./run
  435. ....
  436. The host git top level directory is mounted inside the guest with a link: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!
  437. Command breakdown:
  438. * `./run-docker create`: create the image and container.
  439. +
  440. 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.
  441. +
  442. The image and container name is `lkmc`. The container shows under:
  443. +
  444. ....
  445. docker ps -a
  446. ....
  447. +
  448. and the image shows under:
  449. +
  450. ....
  451. docker images
  452. ....
  453. * `./run-docker sh`: open a shell on the container.
  454. +
  455. If it has not been started previously, start it. This can also be done explicitly with:
  456. +
  457. ....
  458. ./run-docker start
  459. ....
  460. +
  461. Quit the shell as usual with `Ctrl-D`
  462. +
  463. This can be called multiple times from different host terminals to open multiple shells.
  464. * `./run-docker stop`: stop the container.
  465. +
  466. This might save a bit of CPU and RAM once you stop working on this project, but it should not be a lot.
  467. * `./run-docker DESTROY`: delete the container and image.
  468. +
  469. 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.
  470. +
  471. To actually delete the Docker build, run on host:
  472. +
  473. ....
  474. # sudo rm -rf out.docker
  475. ....
  476. To use <<gdb>> from inside Docker, you need a second shell inside the container. You can either do that from another shell with:
  477. ....
  478. ./run-docker sh
  479. ....
  480. or even better, by starting a <<tmux>> session inside the container. We install `tmux` by default in the container.
  481. You can also start a second shell and run a command in it at the same time with:
  482. ....
  483. ./run-docker sh -- ./run-gdb start_kernel
  484. ....
  485. To use <<qemu-graphic-mode>> from Docker, run:
  486. ....
  487. ./run --graphic --vnc
  488. ....
  489. and then on host:
  490. ....
  491. sudo apt-get install vinagre
  492. ./vnc
  493. ....
  494. TODO make files created inside Docker be owned by the current user in host instead of `root`:
  495. * https://stackoverflow.com/questions/33681396/how-do-i-write-to-a-volume-container-as-non-root-in-docker
  496. * https://stackoverflow.com/questions/23544282/what-is-the-best-way-to-manage-permissions-for-docker-shared-volumes
  497. * https://stackoverflow.com/questions/31779802/shared-volume-file-permissions-ownership-docker
  498. [[prebuilt]]
  499. === Prebuilt setup
  500. ==== About the prebuilt setup
  501. This setup uses prebuilt binaries that we upload to GitHub from time to time.
  502. We don't currently provide a full prebuilt because it would be too big to host freely, notably because of the cross toolchain.
  503. Our prebuilts currently include:
  504. * <<qemu-buildroot-setup>> binaries
  505. ** Linux kernel
  506. ** root filesystem
  507. * <<baremetal-setup>> binaries for QEMU
  508. For more details, see our our <<release,release procedure>>.
  509. Advantage of this setup: saves time and disk space on the initial install, which is expensive in largely due to building the toolchain.
  510. The limitations are severe however:
  511. * 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: <<prebuilt-toolchain>>.
  512. +
  513. 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.
  514. * 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.
  515. * <<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: <<vmlinux-vs-bzimage-vs-zimage-vs-image>>.
  516. 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? :-)
  517. ==== Prebuilt setup getting started
  518. Checkout to the latest tag and use the Ubuntu packaged QEMU to boot Linux:
  519. ....
  520. sudo apt-get install qemu-system-x86
  521. git clone https://github.com/cirosantilli/linux-kernel-module-cheat
  522. cd linux-kernel-module-cheat
  523. git checkout "$(git rev-list --tags --max-count=1)"
  524. ./release-download-latest
  525. unzip lkmc-*.zip
  526. ./run --qemu-which host
  527. ....
  528. 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
  529. 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.
  530. Or to run a baremetal example instead:
  531. ....
  532. ./run \
  533. --arch aarch64 \
  534. --baremetal baremetal/hello.c \
  535. --qemu-which host \
  536. ;
  537. ....
  538. Be saner and use our custom built QEMU instead:
  539. ....
  540. ./build --download-dependencies qemu
  541. ./run
  542. ....
  543. This also allows you to <<your-first-qemu-hack,modify QEMU>> if you're into that sort of thing.
  544. To build the kernel modules as in <<your-first-kernel-module-hack>> do:
  545. ....
  546. git submodule update --depth 1 --init --recursive "$(./getvar linux_source_dir)"
  547. ./build-linux --no-modules-install -- modules_prepare
  548. ./build-modules --gcc-which host
  549. ./run
  550. ....
  551. 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.
  552. Command explanation:
  553. * `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.
  554. * `--gcc-which host` selects your host Ubuntu packaged GCC, since you don't have the Buildroot toolchain
  555. * `--no-modules-install` is required otherwise the `make modules_install` target we run by default fails, since the kernel wasn't built
  556. To modify the Linux kernel, build and use it as usual:
  557. ....
  558. git submodule update --depth 1 --init --recursive "$(./getvar linux_source_dir)"
  559. ./build-linux
  560. ./run
  561. ....
  562. ////
  563. For gem5, do:
  564. ....
  565. git submodule update --init --depth 1 "$(./getvar linux_source_dir)"
  566. sudo apt-get install qemu-utils
  567. ./build-gem5
  568. ./run --emulator gem5 --qemu-which host
  569. ....
  570. `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.
  571. 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
  572. ////
  573. ////
  574. [[ubuntu]]
  575. === Ubuntu guest setup
  576. ==== About the Ubuntu guest setup
  577. 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.
  578. The rationale for choice of Ubuntu as a second distribution in addition to Buildroot can be found at: <<linux-distro-choice>>
  579. Advantages over Buildroot:
  580. * saves build time
  581. * you get to play with a huge selection of Debian packages out of the box
  582. * more representative of most non-embedded production systems than BusyBox
  583. Disadvantages:
  584. * 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
  585. * 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
  586. 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:
  587. * 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
  588. * the default Ubuntu image has a large collection of software, and is large. The docker version is much more minimal.
  589. One alternative would be to use link: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`.
  590. ==== Ubuntu guest setup getting started
  591. TODO
  592. ....
  593. sudo ./build-docker
  594. ./run --docker
  595. ....
  596. `sudo` is required for Docker operations: https://askubuntu.com/questions/477551/how-can-i-use-docker-without-sudo
  597. ////
  598. [[host]]
  599. === Host kernel module setup
  600. **THIS IS DANGEROUS (AND FUN), YOU HAVE BEEN WARNED**
  601. 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.
  602. It has however severe limitations:
  603. * 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].
  604. * bugs can easily break you system. E.g.:
  605. ** segfaults can trivially lead to a kernel crash, and require a reboot
  606. ** 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`.
  607. ** 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]
  608. * can't control which hardware is used, notably the CPU architecture
  609. * can't step debug it with <<gdb,GDB>> easily. The alternatives are link:https://en.wikipedia.org/wiki/JTAG[JTAG] or <<kgdb>>, but those are less reliable, and require extra hardware.
  610. Still interested?
  611. ....
  612. ./build-modules --gcc-which host --host
  613. ....
  614. Compilation will likely fail for some modules because of kernel or toolchain differences that we can't control on the host.
  615. The best workaround is to compile just your modules with:
  616. ....
  617. ./build-modules --gcc-which host --host -- hello hello2
  618. ....
  619. which is equivalent to:
  620. ....
  621. ./build-modules \
  622. --gcc-which host \
  623. --host \
  624. -- \
  625. kernel_modules/hello.c \
  626. kernel_modules/hello2.c \
  627. ;
  628. ....
  629. Or just remove the `.c` extension from the failing files and try again:
  630. ....
  631. cd "$(./getvar kernel_modules_source_dir)"
  632. mv broken.c broken.c~
  633. ....
  634. Once you manage to compile, and have come to terms with the fact that this may blow up your host, try it out with:
  635. ....
  636. cd "$(./getvar kernel_modules_build_host_subdir)"
  637. sudo insmod hello.ko
  638. # Our module is there.
  639. sudo lsmod | grep hello
  640. # Last message should be: hello init
  641. dmesg -T
  642. sudo rmmod hello
  643. # Last message should be: hello exit
  644. dmesg -T
  645. # Not present anymore
  646. sudo lsmod | grep hello
  647. ....
  648. ==== Hello host
  649. Minimal host build system example:
  650. ....
  651. cd hello_host_kernel_module
  652. make
  653. sudo insmod hello.ko
  654. dmesg
  655. sudo rmmod hello.ko
  656. dmesg
  657. ....
  658. === Userland setup
  659. ==== About the userland setup
  660. 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:
  661. * link:userland/[]
  662. * <<rootfs_overlay>>
  663. * <<add-new-buildroot-packages>>
  664. When we started this repository, it only contained content that interacted very closely with the kernel, or that had required performance analysis.
  665. 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.
  666. Therefore, we decided to consolidate other userland tutorials that we had scattered around into this repository.
  667. Notable userland content included / moving into this repository includes:
  668. * <<userland-assembly>>
  669. * <<c>>
  670. * <<cpp>>
  671. * <<posix>>
  672. * https://github.com/cirosantilli/algorithm-cheat TODO will be good to move here for performance analysis <<gem5-run-benchmark,with gem5>>
  673. ==== Userland setup getting started
  674. There are several ways to run our userland content, notably:
  675. * natively on the host as shown at: <<userland-setup-getting-started-natively>>
  676. +
  677. Can only run examples compatible with your host CPU architecture and OS, but has the fastest setup and runtimes.
  678. * from user mode simulation with:
  679. +
  680. --
  681. ** the host prebuilt toolchain: <<userland-setup-getting-started-with-prebuilt-toolchain-and-qemu-user-mode>>
  682. ** the Buildroot toolchain you built yourself: <<qemu-user-mode-getting-started>>
  683. --
  684. +
  685. This setup:
  686. +
  687. --
  688. ** can run most examples, including those for other CPU architectures, with the notable exception of examples that rely on kernel modules
  689. ** can run reproducible approximate performance experiments with gem5, see e.g. <<bst-vs-heap>>
  690. --
  691. * from full system simulation as shown at: <<qemu-buildroot-setup-getting-started>>.
  692. +
  693. This is the most reproducible and controlled environment, and all examples work there. But also the slower one to setup.
  694. ===== Userland setup getting started natively
  695. With this setup, we will use the host toolchain and execute executables directly on the host.
  696. No installation or toolchain build is required, so you can just jump straight into it.
  697. Build, run and example, and clean it in-tree with:
  698. ....
  699. sudo apt-get install gcc
  700. cd userland
  701. ./build c/hello
  702. ./c/hello.out
  703. ./build --clean
  704. ....
  705. Source: link:userland/c/hello.c[].
  706. Build an entire directory and test it:
  707. ....
  708. cd userland
  709. ./build c
  710. ./test c
  711. ....
  712. Build the current directory and test it:
  713. ....
  714. cd userland/c
  715. ./build
  716. ./test
  717. ....
  718. 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.
  719. You can install those libraries with:
  720. ....
  721. cd linux-kernel-module-cheat
  722. ./build --download-dependencies userland-host
  723. ....
  724. and then build the examples and test with:
  725. ....
  726. ./build --package-all
  727. ./test --package-all
  728. ....
  729. Pass custom compiler options:
  730. ....
  731. ./build --ccflags='-foptimize-sibling-calls -foptimize-strlen' --force-rebuild
  732. ....
  733. Here we used `--force-rebuild` to force rebuild since the sources weren't modified since the last build.
  734. Some CLI options have more specialized flags, e.g. `-O` optimization level:
  735. ....
  736. ./build --optimization-level 3 --force-rebuild
  737. ....
  738. See also <<user-mode-static-executables>> for `--static`.
  739. The `build` scripts inside link:userland/[] are just symlinks to link:build-userland-in-tree[] which you can also use from toplevel as:
  740. ....
  741. ./build-userland-in-tree
  742. ./build-userland-in-tree userland/c
  743. ./build-userland-in-tree userland/c/hello.c
  744. ....
  745. `build-userland-in-tre` is in turn just a thin wrapper around link:build-userland[]:
  746. ....
  747. ./build-userland --gcc-which host --in-tree userland/c
  748. ....
  749. So you can use any option supported by `build-userland` script freely with `build-userland-in-tree` and `build`.
  750. The situation is analogous for link:userland/test[], link:test-user-mode-in-tree[] and link:test-user-mode[], which are further documented at: <<user-mode-tests>>.
  751. Do a more clean out-of-tree build instead and run the program:
  752. ....
  753. ./build-userland --gcc-which host --userland-build-id host
  754. ./run --emulator native --userland userland/c/hello.c --userland-build-id host
  755. ....
  756. Here we:
  757. * put the host executables in a separate <<build-variants,build-variant>> to avoid conflict with Buildroot builds.
  758. * ran with the `--emulator native` option to run the program natively
  759. In this case you can debub the program with:
  760. ....
  761. ./run --debug-vm --emulator native --userland userland/c/hello.c --userland-build-id host
  762. ....
  763. as shown at: <<debug-the-emulator>>, although direct GDB host usage works as well of course.
  764. ===== Userland setup getting started with prebuilt toolchain and QEMU user mode
  765. 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:
  766. ....
  767. sudo apt-get install gcc-aarch64-linux-gnu qemu-system-aarch64
  768. ./build-userland \
  769. --arch aarch64 \
  770. --gcc-which host \
  771. --userland-build-id host \
  772. ;
  773. ./run \
  774. --arch aarch64 \
  775. --qemu-which host \
  776. --userland-build-id host \
  777. --userland userland/c/print_argv.c \
  778. --userland-args 'asdf "qw er"' \
  779. ;
  780. ....
  781. where:
  782. * `--gcc-which host`: use the host toolchain.
  783. +
  784. We must pass this to `./run` as well because QEMU must know which dynamic libraries to use. See also: <<user-mode-static-executables>>.
  785. * `--userland-build-id host`: put the host built into a <<build-variants>>
  786. This present the usual trade-offs of using prebuilts as mentioned at: <<prebuilt>>.
  787. Other functionality are analogous, e.g. testing:
  788. ....
  789. ./test-user-mode \
  790. --arch aarch64 \
  791. --gcc-which host \
  792. --qemu-which host \
  793. --userland-build-id host \
  794. ;
  795. ....
  796. and <<user-mode-gdb>>:
  797. ....
  798. ./run \
  799. --arch aarch64 \
  800. --gdb \
  801. --gcc-which host \
  802. --qemu-which host \
  803. --userland-build-id host \
  804. --userland userland/c/print_argv.c \
  805. --userland-args 'asdf "qw er"' \
  806. ;
  807. ....
  808. ===== Userland setup getting started full system
  809. First ensure that <<qemu-buildroot-setup>> is working.
  810. 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.
  811. And the answer is exactly analogous to what is shown at: <<your-first-kernel-module-hack>>
  812. For example, if we modify link:userland/c/hello.c[] to print out something different, we can just rebuild it with:
  813. ....
  814. ./build-userland
  815. ....
  816. Source: link:build-userland[]. `./build` calls that script automatically for us when doing the initial full build.
  817. Now, run the program either without rebooting use the <<9p>> mount:
  818. ....
  819. /mnt/9p/out_rootfs_overlay/c/hello.out
  820. ....
  821. or shutdown QEMU, add the executable to the root filesystem:
  822. ....
  823. ./build-buildroot
  824. ....
  825. reboot and use the root filesystem as usual:
  826. ....
  827. ./hello.out
  828. ....
  829. === Baremetal setup
  830. ==== About the baremetal setup
  831. This setup does not use the Linux kernel nor Buildroot at all: it just runs your very own minimal OS.
  832. `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.
  833. 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.
  834. 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.
  835. You can also use C and a subset of the C standard library because we enable link: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
  836. Our C bare-metal compiler is built with link: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
  837. ==== Baremetal setup getting started
  838. Every `.c` file inside link:baremetal/[] and `.S` file inside `baremetal/arch/<arch>/` generates a separate baremetal image.
  839. For example, to run link:baremetal/hello.c[] in QEMU do:
  840. ....
  841. ./build --arch aarch64 --download-dependencies qemu-baremetal
  842. ./run --arch aarch64 --baremetal baremetal/hello.c
  843. ....
  844. The terminal prints:
  845. ....
  846. hello
  847. ....
  848. Now let's run link:baremetal/arch/aarch64/add.S[]:
  849. ....
  850. ./run --arch aarch64 --baremetal baremetal/arch/aarch64/add.S
  851. ....
  852. This time, the terminal does not print anything, which indicates success.
  853. If you look into the source, you will see that we just have an assertion there.
  854. You can see a sample assertion fail in link:baremetal/interactive/assert_fail.c[]:
  855. ....
  856. ./run --arch aarch64 --baremetal baremetal/interactive/assert_fail.c
  857. ....
  858. and the terminal contains:
  859. ....
  860. lkmc_test_fail
  861. error: simulation error detected by parsing logs
  862. ....
  863. and the exit status of our script is 1:
  864. ....
  865. echo $?
  866. ....
  867. To modify a baremetal program, simply edit the file, e.g.
  868. ....
  869. vim baremetal/hello.c
  870. ....
  871. and rebuild:
  872. ....
  873. ./build-baremetal --arch aarch64
  874. ./run --arch aarch64 --baremetal baremetal/hello.c
  875. ....
  876. `./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.
  877. `./build-baremetal` uses crosstool-NG, and so it must be preceded by link:build-crosstool-ng[], which `./build qemu-baremetal` also calls.
  878. Alternatively, for the sake of tab completion, we also accept relative paths inside `baremetal/`, for example the following also work:
  879. ....
  880. ./run --arch aarch64 --baremetal baremetal/hello.c
  881. ./run --arch aarch64 --baremetal baremetal/arch/aarch64/add.S
  882. ....
  883. Absolute paths however are used as is and must point to the actual executable:
  884. ....
  885. ./run --arch aarch64 --baremetal "$(./getvar --arch aarch64 baremetal_build_dir)/hello.elf"
  886. ....
  887. To use gem5 instead of QEMU do:
  888. ....
  889. ./build --download-dependencies gem5-baremetal
  890. ./run --arch aarch64 --baremetal baremetal/hello.c --emulator gem5
  891. ....
  892. and then <<qemu-buildroot-setup,as usual>> open a shell with:
  893. ....
  894. ./gem5-shell
  895. ....
  896. Or as usual, <<tmux>> users can do both in one go with:
  897. ....
  898. ./run --arch aarch64 --baremetal baremetal/hello.c --emulator gem5 --tmux
  899. ....
  900. TODO: the carriage returns are a bit different than in QEMU, see: <<gem5-baremetal-carriage-return>>.
  901. Note that `./build-baremetal` requires the `--emulator gem5` option, and generates separate executable images for both, as can be seen from:
  902. ....
  903. echo "$(./getvar --arch aarch64 --baremetal baremetal/hello.c --emulator qemu image)"
  904. echo "$(./getvar --arch aarch64 --baremetal baremetal/hello.c --emulator gem5 image)"
  905. ....
  906. This is unlike the Linux kernel that has a single image for both QEMU and gem5:
  907. ....
  908. echo "$(./getvar --arch aarch64 --emulator qemu image)"
  909. echo "$(./getvar --arch aarch64 --emulator gem5 image)"
  910. ....
  911. 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.
  912. `gem5` also supports the `RealViewPBX` machine, which represents an older hardware compared to the default `VExpress_GEM5_V1`:
  913. ....
  914. ./build-baremetal --arch aarch64 --emulator gem5 --machine RealViewPBX
  915. ./run --arch aarch64 --baremetal baremetal/hello.c --emulator gem5 --machine RealViewPBX
  916. ....
  917. This generates yet new separate images with new magic constants:
  918. ....
  919. echo "$(./getvar --arch aarch64 --baremetal baremetal/hello.c --emulator gem5 --machine VExpress_GEM5_V1 image)"
  920. echo "$(./getvar --arch aarch64 --baremetal baremetal/hello.c --emulator gem5 --machine RealViewPBX image)"
  921. ....
  922. But just stick to newer and better `VExpress_GEM5_V1` unless you have a good reason to use `RealViewPBX`.
  923. When doing baremetal programming, it is likely that you will want to learn userland assembly first, see: <<userland-assembly>>.
  924. For more information on baremetal, see the section: <<baremetal>>.
  925. The following subjects are particularly important:
  926. * <<tracing>>
  927. * <<baremetal-gdb-step-debug>>
  928. [[gdb]]
  929. == GDB step debug
  930. === GDB step debug kernel boot
  931. `--gdb-wait` makes QEMU and gem5 wait for a GDB connection, otherwise we could accidentally go past the point we want to break at:
  932. ....
  933. ./run --gdb-wait
  934. ....
  935. Say you want to break at `start_kernel`. So on another shell:
  936. ....
  937. ./run-gdb start_kernel
  938. ....
  939. or at a given line:
  940. ....
  941. ./run-gdb init/main.c:1088
  942. ....
  943. Now QEMU will stop there, and you can use the normal GDB commands:
  944. ....
  945. list
  946. next
  947. continue
  948. ....
  949. See also:
  950. * http://stackoverflow.com/questions/11408041/how-to-debug-the-linux-kernel-with-gdb-and-qemu/33203642#33203642
  951. * http://stackoverflow.com/questions/4943857/linux-kernel-live-debugging-how-its-done-and-what-tools-are-used/42316607#42316607
  952. ==== GDB step debug kernel boot other archs
  953. Just don't forget to pass `--arch` to `./run-gdb`, e.g.:
  954. ....
  955. ./run --arch aarch64 --gdb-wait
  956. ....
  957. and:
  958. ....
  959. ./run-gdb --arch aarch64 start_kernel
  960. ....
  961. [[kernel-o0]]
  962. ==== Disable kernel compiler optimizations
  963. https://stackoverflow.com/questions/29151235/how-to-de-optimize-the-linux-kernel-to-and-compile-it-with-o0
  964. `O=0` is an impossible dream, `O=2` being the default.
  965. So get ready for some weird jumps, and `<value optimized out>` fun. Why, Linux, why.
  966. === GDB step debug kernel post-boot
  967. Let's observe the kernel `write` system call as it reacts to some userland actions.
  968. Start QEMU with just:
  969. ....
  970. ./run
  971. ....
  972. and after boot inside a shell run:
  973. ....
  974. ./count.sh
  975. ....
  976. which counts to infinity to stdout. Source: link:rootfs_overlay/lkmc/count.sh[].
  977. Then in another shell, run:
  978. ....
  979. ./run-gdb
  980. ....
  981. and then hit:
  982. ....
  983. Ctrl-C
  984. break __x64_sys_write
  985. continue
  986. continue
  987. continue
  988. ....
  989. And you now control the counting on the first shell from GDB!
  990. Before v4.17, the symbol name was just `sys_write`, the change happened at link: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:
  991. ....
  992. rbreak .*sys_write
  993. ....
  994. or just have a quick look at the sources!
  995. 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.
  996. === tmux
  997. tmux just makes things even more fun by allowing us to see both the terminal for:
  998. * emulator stdout
  999. * <<gdb>>
  1000. at once without dragging windows around!
  1001. First start `tmux` with:
  1002. ....
  1003. tmux
  1004. ....
  1005. Now that you are inside a shell inside tmux, you can start GDB simply with:
  1006. ....
  1007. ./run --gdb
  1008. ....
  1009. which is just a convenient shortcut for:
  1010. ....
  1011. ./run --gdb-wait --tmux --tmux-args start_kernel
  1012. ....
  1013. This splits the terminal into two panes:
  1014. * left: usual QEMU with terminal
  1015. * right: GDB
  1016. and focuses on the GDB pane.
  1017. Now you can navigate with the usual tmux shortcuts:
  1018. * switch between the two panes with: `Ctrl-B O`
  1019. * close either pane by killing its terminal with `Ctrl-D` as usual
  1020. See the tmux manual for further details:
  1021. ....
  1022. man tmux
  1023. ....
  1024. To start again, switch back to the QEMU pane with `Ctrl-O`, kill the emulator, and re-run:
  1025. ....
  1026. ./run --gdb
  1027. ....
  1028. This automatically clears the GDB pane, and starts a new one.
  1029. The option `--tmux-args` determines which options will be passed to the program running on the second tmux pane, and is equivalent to:
  1030. This is equivalent to:
  1031. ....
  1032. ./run --gdb-wait
  1033. ./run-gdb start_kernel
  1034. ....
  1035. 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>>:
  1036. ....
  1037. ./run --gdb --tmux-args=--no-continue
  1038. ....
  1039. 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
  1040. ==== tmux gem5
  1041. If you are using gem5 instead of QEMU, `--tmux` has a different effect by default: it opens the gem5 terminal instead of the debugger:
  1042. ....
  1043. ./run --emulator gem5 --tmux
  1044. ....
  1045. To open a new pane with GDB instead of the terminal, use:
  1046. ....
  1047. ./run --gdb
  1048. ....
  1049. which is equivalent to:
  1050. ....
  1051. ./run --emulator gem5 --gdb-wait --tmux --tmux-args start_kernel --tmux-program gdb
  1052. ....
  1053. `--tmux-program` implies `--tmux`, so we can just write:
  1054. ....
  1055. ./run --emulator gem5 --gdb-wait --tmux-program gdb
  1056. ....
  1057. 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`.
  1058. 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 "`.
  1059. === GDB step debug kernel module
  1060. http://stackoverflow.com/questions/28607538/how-to-debug-linux-kernel-modules-with-qemu/44095831#44095831
  1061. Loadable kernel modules are a bit trickier since the kernel can place them at different memory locations depending on load order.
  1062. So we cannot set the breakpoints before `insmod`.
  1063. However, the Linux kernel GDB scripts offer the `lx-symbols` command, which takes care of that beautifully for us.
  1064. Shell 1:
  1065. ....
  1066. ./run
  1067. ....
  1068. Wait for the boot to end and run:
  1069. ....
  1070. insmod timer.ko
  1071. ....
  1072. Source: link:kernel_modules/timer.c[].
  1073. This prints a message to dmesg every second.
  1074. Shell 2:
  1075. ....
  1076. ./run-gdb
  1077. ....
  1078. In GDB, hit `Ctrl-C`, and note how it says:
  1079. ....
  1080. scanning for modules in /root/linux-kernel-module-cheat/out/kernel_modules/x86_64/kernel_modules
  1081. loading @0xffffffffc0000000: /root/linux-kernel-module-cheat/out/kernel_modules/x86_64/kernel_modules/timer.ko
  1082. ....
  1083. That's `lx-symbols` working! Now simply:
  1084. ....
  1085. break lkmc_timer_callback
  1086. continue
  1087. continue
  1088. continue
  1089. ....
  1090. and we now control the callback from GDB!
  1091. Just don't forget to remove your breakpoints after `rmmod`, or they will point to stale memory locations.
  1092. TODO: why does `break work_func` for `insmod kthread.ko` not very well? Sometimes it breaks but not others.
  1093. [[gdb-step-debug-kernel-module-arm]]
  1094. ==== GDB step debug kernel module insmodded by init on ARM
  1095. TODO on `arm` 51e31cdc2933a774c2a0dc62664ad8acec1d2dbe it does not always work, and `lx-symbols` fails with the message:
  1096. ....
  1097. loading vmlinux
  1098. Traceback (most recent call last):
  1099. File "/linux-kernel-module-cheat//out/arm/buildroot/build/linux-custom/scripts/gdb/linux/symbols.py", line 163, in invoke
  1100. self.load_all_symbols()
  1101. File "/linux-kernel-module-cheat//out/arm/buildroot/build/linux-custom/scripts/gdb/linux/symbols.py", line 150, in load_all_symbols
  1102. [self.load_module_symbols(module) for module in module_list]
  1103. File "/linux-kernel-module-cheat//out/arm/buildroot/build/linux-custom/scripts/gdb/linux/symbols.py", line 110, in load_module_symbols
  1104. module_name = module['name'].string()
  1105. gdb.MemoryError: Cannot access memory at address 0xbf0000cc
  1106. Error occurred in Python command: Cannot access memory at address 0xbf0000cc
  1107. ....
  1108. Can't reproduce on `x86_64` and `aarch64` are fine.
  1109. It is kind of random: if you just `insmod` manually and then immediately `./run-gdb --arch arm`, then it usually works.
  1110. But this fails most of the time: shell 1:
  1111. ....
  1112. ./run --arch arm --eval-after 'insmod hello.ko'
  1113. ....
  1114. shell 2:
  1115. ....
  1116. ./run-gdb --arch arm
  1117. ....
  1118. then hit `Ctrl-C` on shell 2, and voila.
  1119. Then:
  1120. ....
  1121. cat /proc/modules
  1122. ....
  1123. says that the load address is:
  1124. ....
  1125. 0xbf000000
  1126. ....
  1127. so it is close to the failing `0xbf0000cc`.
  1128. `readelf`:
  1129. ....
  1130. ./run-toolchain readelf -- -s "$(./getvar kernel_modules_build_subdir)/hello.ko"
  1131. ....
  1132. does not give any interesting hits at `cc`, no symbol was placed that far.
  1133. ==== GDB module_init
  1134. TODO find a more convenient method. We have working methods, but they are not ideal.
  1135. 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!
  1136. Possibly asked at:
  1137. * https://stackoverflow.com/questions/37059320/debug-a-kernel-module-being-loaded
  1138. * https://stackoverflow.com/questions/11888412/debug-the-init-module-call-of-a-linux-kernel-module
  1139. ===== GDB module_init step into it
  1140. This is the best method we've found so far.
  1141. The kernel calls `module_init` synchronously, therefore it is not hard to step into that call.
  1142. As of 4.16, the call happens in `do_one_initcall`, so we can do in shell 1:
  1143. ....
  1144. ./run
  1145. ....
  1146. shell 2 after boot finishes (because there are other calls to `do_init_module` at boot, presumably for the built-in modules):
  1147. ....
  1148. ./run-gdb do_one_initcall
  1149. ....
  1150. then step until the line:
  1151. ....
  1152. 833 ret = fn();
  1153. ....
  1154. which does the actual call, and then step into it.
  1155. For the next time, you can also put a breakpoint there directly:
  1156. ....
  1157. ./run-gdb init/main.c:833
  1158. ....
  1159. How we found this out: first we got <<gdb-module_init-calculate-entry-address>> working, and then we did a `bt`. AKA cheating :-)
  1160. ===== GDB module_init calculate entry address
  1161. This works, but is a bit annoying.
  1162. 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.
  1163. So once we find the address the first time, we can just reuse it afterwards, as long as we don't modify the module.
  1164. Do a fresh boot and get the module:
  1165. ....
  1166. ./run --eval-after './pr_debug.sh;insmod fops.ko;./linux/poweroff.out'
  1167. ....
  1168. The boot must be fresh, because the load address changes every time we insert, even after removing previous modules.
  1169. The base address shows on terminal:
  1170. ....
  1171. 0xffffffffc0000000 .text
  1172. ....
  1173. Now let's find the offset of `myinit`:
  1174. ....
  1175. ./run-toolchain readelf -- \
  1176. -s "$(./getvar kernel_modules_build_subdir)/fops.ko" | \
  1177. grep myinit
  1178. ....
  1179. which gives:
  1180. ....
  1181. 30: 0000000000000240 43 FUNC LOCAL DEFAULT 2 myinit
  1182. ....
  1183. so the offset address is `0x240` and we deduce that the function will be placed at:
  1184. ....
  1185. 0xffffffffc0000000 + 0x240 = 0xffffffffc0000240
  1186. ....
  1187. Now we can just do a fresh boot on shell 1:
  1188. ....
  1189. ./run --eval 'insmod fops.ko;./linux/poweroff.out' --gdb-wait
  1190. ....
  1191. and on shell 2:
  1192. ....
  1193. ./run-gdb '*0xffffffffc0000240'
  1194. ....
  1195. GDB then breaks, and `lx-symbols` works.
  1196. ===== GDB module_init break at the end of sys_init_module
  1197. TODO not working. This could be potentially very convenient.
  1198. 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.
  1199. Beware that there are both `sys_init_module` and `sys_finit_module` syscalls, and `insmod` uses `fmodule_init` by default.
  1200. Both call `do_module_init` however, which is what `lx-symbols` hooks to.
  1201. If we try:
  1202. ....
  1203. b sys_finit_module
  1204. ....
  1205. then hitting:
  1206. ....
  1207. n
  1208. ....
  1209. does not break, and insertion happens, likely because of optimizations? <<kernel-o0>>
  1210. Then we try:
  1211. ....
  1212. b do_init_module
  1213. ....
  1214. A naive:
  1215. ....
  1216. fin
  1217. ....
  1218. also fails to break!
  1219. Finally, in despair we notice that <<pr_debug>> prints the kernel load address as explained at <<bypass-lx-symbols>>.
  1220. 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.
  1221. ===== GDB module_init add trap instruction
  1222. This is another possibility: we could modify the module source by adding a trap instruction of some kind.
  1223. This appears to be described at: https://www.linuxjournal.com/article/4525
  1224. But it refers to a `gdbstart` script which is not in the tree anymore and beyond my `git log` capabilities.
  1225. And just adding:
  1226. ....
  1227. asm( " int $3");
  1228. ....
  1229. directly gives an <<oops,oops>> as I'd expect.
  1230. ==== Bypass lx-symbols
  1231. Useless, but a good way to show how hardcore you are. Disable `lx-symbols` with:
  1232. ....
  1233. ./run-gdb --no-lxsymbols
  1234. ....
  1235. From inside guest:
  1236. ....
  1237. insmod timer.ko
  1238. cat /proc/modules
  1239. ....
  1240. as mentioned at:
  1241. * https://stackoverflow.com/questions/6384605/how-to-get-address-of-a-kernel-module-loaded-using-insmod/6385818
  1242. * https://unix.stackexchange.com/questions/194405/get-base-address-and-size-of-a-loaded-kernel-module
  1243. This will give a line of form:
  1244. ....
  1245. fops 2327 0 - Live 0xfffffffa00000000
  1246. ....
  1247. And then tell GDB where the module was loaded with:
  1248. ....
  1249. Ctrl-C
  1250. add-symbol-file ../../../rootfs_overlay/x86_64/timer.ko 0xffffffffc0000000
  1251. 0xffffffffc0000000
  1252. ....
  1253. Alternatively, if the module panics before you can read `/proc/modules`, there is a <<pr_debug>> which shows the load address:
  1254. ....
  1255. echo 8 > /proc/sys/kernel/printk
  1256. echo 'file kernel/module.c +p' > /sys/kernel/debug/dynamic_debug/control
  1257. ./linux/myinsmod.out hello.ko
  1258. ....
  1259. And then search for a line of type:
  1260. ....
  1261. [ 84.877482] 0xfffffffa00000000 .text
  1262. ....
  1263. Tested on 4f4749148273c282e80b58c59db1b47049e190bf + 1.
  1264. === GDB step debug early boot
  1265. TODO successfully debug the very first instruction that the Linux kernel runs, before `start_kernel`!
  1266. Break at the very first instruction executed by QEMU:
  1267. ....
  1268. ./run-gdb --no-continue
  1269. ....
  1270. TODO why can't we break at early startup stuff such as:
  1271. ....
  1272. ./run-gdb extract_kernel
  1273. ./run-gdb main
  1274. ....
  1275. 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?
  1276. See also: https://stackoverflow.com/questions/2589845/what-are-the-first-operations-that-the-linux-kernel-executes-on-boot
  1277. <<gem5-tracing>> with `--debug-flags=Exec` does show the right symbols however! So in the worst case, we can just read their source. Amazing.
  1278. 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: <<vmlinux-vs-bzimage-vs-zimage-vs-image>>.
  1279. ==== GDB step debug early boot by address
  1280. One possibility is to run:
  1281. ....
  1282. ./trace-boot --arch arm
  1283. ....
  1284. and then find the second address (the first one does not work, already too late maybe):
  1285. ....
  1286. less "$(./getvar --arch arm trace_txt_file)"
  1287. ....
  1288. and break there:
  1289. ....
  1290. ./run --arch arm --gdb-wait
  1291. ./run-gdb --arch arm '*0x1000'
  1292. ....
  1293. 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
  1294. I also tried to hack `run-gdb` with:
  1295. ....
  1296. @@ -81,7 +81,7 @@ else
  1297. ${gdb} \
  1298. -q \\
  1299. -ex 'add-auto-load-safe-path $(pwd)' \\
  1300. --ex 'file vmlinux' \\
  1301. +-ex 'file arch/arm/boot/compressed/vmlinux' \\
  1302. -ex 'target remote localhost:${port}' \\
  1303. ${brk} \
  1304. -ex 'continue' \\
  1305. ....
  1306. and no I do have the symbols from `arch/arm/boot/compressed/vmlinux'`, but the breaks still don't work.
  1307. === GDB step debug userland processes
  1308. QEMU's `-gdb` GDB breakpoints are set on virtual addresses, so you can in theory debug userland processes as well.
  1309. * https://stackoverflow.com/questions/26271901/is-it-possible-to-use-gdb-and-qemu-to-debug-linux-user-space-programs-and-kernel
  1310. * https://stackoverflow.com/questions/16273614/debug-init-on-qemu-using-gdb
  1311. You will generally want to use <<gdbserver>> for this as it is more reliable, but this method can overcome the following limitations of `gdbserver`:
  1312. * the emulator does not support host to guest networking. This seems to be the case for gem5: <<gem5-host-to-guest-networking>>
  1313. * cannot see the start of the `init` process easily
  1314. * `gdbserver` alters the working of the kernel, and makes your run less representative
  1315. Known limitations of direct userland debugging:
  1316. * 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.
  1317. * TODO step into shared libraries. If I attempt to load them explicitly:
  1318. +
  1319. ....
  1320. (gdb) sharedlibrary ../../staging/lib/libc.so.0
  1321. No loaded shared libraries match the pattern `../../staging/lib/libc.so.0'.
  1322. ....
  1323. +
  1324. since GDB does not know that libc is loaded.
  1325. ==== GDB step debug userland custom init
  1326. This is the userland debug setup most likely to work, since at init time there is only one userland executable running.
  1327. For executables from the link:userland/[] directory such as link:userland/posix/count.c[]:
  1328. * Shell 1:
  1329. +
  1330. ....
  1331. ./run --gdb-wait --kernel-cli 'init=/lkmc/posix/count.out'
  1332. ....
  1333. * Shell 2:
  1334. +
  1335. ....
  1336. ./run-gdb-user userland/posix/count.c main
  1337. ....
  1338. +
  1339. Alternatively, we could also pass the full path to the executable:
  1340. +
  1341. ....
  1342. ./run-gdb-user "$(./getvar userland_build_dir)/posix/count.out" main
  1343. ....
  1344. +
  1345. Path resolution is analogous to <<baremetal-setup-getting-started,that of `./run --baremetal`>>.
  1346. Then, as soon as boot ends, we are left inside a debug session that looks just like what `gdbserver` would produce.
  1347. ==== GDB step debug userland BusyBox init
  1348. BusyBox custom init process:
  1349. * Shell 1:
  1350. +
  1351. ....
  1352. ./run --gdb-wait --kernel-cli 'init=/bin/ls'
  1353. ....
  1354. * Shell 2:
  1355. +
  1356. ....
  1357. ./run-gdb-user "$(./getvar buildroot_build_build_dir)"/busybox-*/busybox ls_main
  1358. ....
  1359. This follows BusyBox' convention of calling the main for each executable as `<exec>_main` since the `busybox` executable has many "mains".
  1360. BusyBox default init process:
  1361. * Shell 1:
  1362. +
  1363. ....
  1364. ./run --gdb-wait
  1365. ....
  1366. * Shell 2:
  1367. +
  1368. ....
  1369. ./run-gdb-user "$(./getvar buildroot_build_build_dir)"/busybox-*/busybox init_main
  1370. ....
  1371. `init` cannot be debugged with <<gdbserver>> without modifying the source, or else `/sbin/init` exits early with:
  1372. ....
  1373. "must be run as PID 1"
  1374. ....
  1375. ==== GDB step debug userland non-init
  1376. Non-init process:
  1377. * Shell 1:
  1378. +
  1379. ....
  1380. ./run --gdb-wait
  1381. ....
  1382. * Shell 2:
  1383. +
  1384. ....
  1385. ./run-gdb-user userland/linux/myinsmod.c main
  1386. ....
  1387. * Shell 1 after the boot finishes:
  1388. +
  1389. ....
  1390. ./linux/myinsmod.out hello.ko
  1391. ....
  1392. This is the least reliable setup as there might be other processes that use the given virtual address.
  1393. ===== GDB step debug userland non-init without --gdb-wait
  1394. TODO: without `--gdb-wait` and the `break main` that we do inside `./run-gdb-user` says:
  1395. ....
  1396. Cannot access memory at address 0x10604
  1397. ....
  1398. and then GDB never breaks. Tested at ac8663a44a450c3eadafe14031186813f90c21e4 + 1.
  1399. The exact behaviour seems to depend on the architecture:
  1400. * `arm`: happens always
  1401. * `x86_64`: appears to happen only if you try to connect GDB as fast as possible, before init has been reached.
  1402. * `aarch64`: could not observe the problem
  1403. We have also double checked the address with:
  1404. ....
  1405. ./run-toolchain --arch arm readelf -- \
  1406. -s "$(./getvar --arch arm userland_build_dir)/linux/myinsmod.out" | \
  1407. grep main
  1408. ....
  1409. and from GDB:
  1410. ....
  1411. info line main
  1412. ....
  1413. and both give:
  1414. ....
  1415. 000105fc
  1416. ....
  1417. which is just 8 bytes before `0x10604`.
  1418. `gdbserver` also says `0x10604`.
  1419. However, if do a `Ctrl-C` in GDB, and then a direct:
  1420. ....
  1421. b *0x000105fc
  1422. ....
  1423. it works. Why?!
  1424. 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.
  1425. === GDB call
  1426. GDB can call functions as explained at: https://stackoverflow.com/questions/1354731/how-to-evaluate-functions-in-gdb
  1427. However this is failing for us:
  1428. * some symbols are not visible to `call` even though `b` sees them
  1429. * for those that are, `call` fails with an E14 error
  1430. E.g.: if we break on `__x64_sys_write` on `count.sh`:
  1431. ....
  1432. >>> call printk(0, "asdf")
  1433. Could not fetch register "orig_rax"; remote failure reply 'E14'
  1434. >>> b printk
  1435. Breakpoint 2 at 0xffffffff81091bca: file kernel/printk/printk.c, line 1824.
  1436. >>> call fdget_pos(fd)
  1437. No symbol "fdget_pos" in current context.
  1438. >>> b fdget_pos
  1439. Breakpoint 3 at 0xffffffff811615e3: fdget_pos. (9 locations)
  1440. >>>
  1441. ....
  1442. even though `fdget_pos` is the first thing `__x64_sys_write` does:
  1443. ....
  1444. 581 SYSCALL_DEFINE3(write, unsigned int, fd, const char __user *, buf,
  1445. 582 size_t, count)
  1446. 583 {
  1447. 584 struct fd f = fdget_pos(fd);
  1448. ....
  1449. I also noticed that I get the same error:
  1450. ....
  1451. Could not fetch register "orig_rax"; remote failure reply 'E14'
  1452. ....
  1453. when trying to use:
  1454. ....
  1455. fin
  1456. ....
  1457. on many (all?) functions.
  1458. See also: https://github.com/cirosantilli/linux-kernel-module-cheat/issues/19
  1459. === GDB view ARM system registers
  1460. `info all-registers` shows some of them.
  1461. The implementation is described at: https://stackoverflow.com/questions/46415059/how-to-observe-aarch64-system-registers-in-qemu/53043044#53043044
  1462. === GDB step debug multicore userland
  1463. For a more minimal baremetal multicore setup, see: <<arm-multicore>>.
  1464. We can set and get which cores the Linux kernel allows a program to run on with `sched_getaffinity` and `sched_setaffinity`:
  1465. ....
  1466. ./run --cpus 2 --eval-after './linux/sched_getaffinity.out'
  1467. ....
  1468. Source: link:userland/linux/sched_getaffinity.c[]
  1469. Sample output:
  1470. ....
  1471. sched_getaffinity = 1 1
  1472. sched_getcpu = 1
  1473. sched_getaffinity = 1 0
  1474. sched_getcpu = 0
  1475. ....
  1476. Which shows us that:
  1477. * initially:
  1478. ** all 2 cores were enabled as shown by `sched_getaffinity = 1 1`
  1479. ** 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.
  1480. * then we restrict the affinity to just core 0, and we see that the program was actually moved to core 0
  1481. The number of cores is modified as explained at: <<number-of-cores>>
  1482. `taskset` from the util-linux package sets the initial core affinity of a program:
  1483. ....
  1484. ./build-buildroot \
  1485. --config 'BR2_PACKAGE_UTIL_LINUX=y' \
  1486. --config 'BR2_PACKAGE_UTIL_LINUX_SCHEDUTILS=y' \
  1487. ;
  1488. ./run --eval-after 'taskset -c 1,1 ./linux/sched_getaffinity.out'
  1489. ....
  1490. output:
  1491. ....
  1492. sched_getaffinity = 0 1
  1493. sched_getcpu = 1
  1494. sched_getaffinity = 1 0
  1495. sched_getcpu = 0
  1496. ....
  1497. so we see that the affinity was restricted to the second core from the start.
  1498. Let's do a QEMU observation to justify this example being in the repository with <<gdb-step-debug-userland-non-init,userland breakpoints>>.
  1499. We will run our `./linux/sched_getaffinity.out` infinitely many time, on core 0 and core 1 alternatively:
  1500. ....
  1501. ./run \
  1502. --cpus 2 \
  1503. --eval-after 'i=0; while true; do taskset -c $i,$i ./linux/sched_getaffinity.out; i=$((! $i)); done' \
  1504. --gdb-wait \
  1505. ;
  1506. ....
  1507. on another shell:
  1508. ....
  1509. ./run-gdb-user "$(./getvar userland_build_dir)/linux/sched_getaffinity.out" main
  1510. ....
  1511. Then, inside GDB:
  1512. ....
  1513. (gdb) info threads
  1514. Id Target Id Frame
  1515. * 1 Thread 1 (CPU#0 [running]) main () at sched_getaffinity.c:30
  1516. 2 Thread 2 (CPU#1 [halted ]) native_safe_halt () at ./arch/x86/include/asm/irqflags.h:55
  1517. (gdb) c
  1518. (gdb) info threads
  1519. Id Target Id Frame
  1520. 1 Thread 1 (CPU#0 [halted ]) native_safe_halt () at ./arch/x86/include/asm/irqflags.h:55
  1521. * 2 Thread 2 (CPU#1 [running]) main () at sched_getaffinity.c:30
  1522. (gdb) c
  1523. ....
  1524. and we observe that `info threads` shows the actual correct core on which the process was restricted to run by `taskset`!
  1525. We should also try it out with kernel modules: https://stackoverflow.com/questions/28347876/set-cpu-affinity-on-a-loadable-linux-kernel-module
  1526. TODO we then tried:
  1527. ....
  1528. ./run --cpus 2 --eval-after './linux/sched_getaffinity_threads.out'
  1529. ....
  1530. and:
  1531. ....
  1532. ./run-gdb-user "$(./getvar userland_build_dir)/linux/sched_getaffinity_threads.out"
  1533. ....
  1534. to switch between two simultaneous live threads with different affinities, it just didn't break on our threads:
  1535. ....
  1536. b main_thread_0
  1537. ....
  1538. Bibliography:
  1539. * https://stackoverflow.com/questions/10490756/how-to-use-sched-getaffinity-and-sched-setaffinity-in-linux-from-c/50117787#50117787
  1540. * https://stackoverflow.com/questions/42800801/how-to-use-gdb-to-debug-qemu-with-smp-symmetric-multiple-processors
  1541. === Linux kernel GDB scripts
  1542. We source the Linux kernel GDB scripts by default for `lx-symbols`, but they also contains some other goodies worth looking into.
  1543. Those scripts basically parse some in-kernel data structures to offer greater visibility with GDB.
  1544. All defined commands are prefixed by `lx-`, so to get a full list just try to tab complete that.
  1545. 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.
  1546. Show dmesg:
  1547. ....
  1548. lx-dmesg
  1549. ....
  1550. Show the <<kernel-command-line-parameters>>:
  1551. ....
  1552. lx-cmdline
  1553. ....
  1554. Dump the device tree to a `fdtdump.dtb` file in the current directory:
  1555. ....
  1556. lx-fdtdump
  1557. pwd
  1558. ....
  1559. List inserted kernel modules:
  1560. ....
  1561. lx-lsmod
  1562. ....
  1563. Sample output:
  1564. ....
  1565. Address Module Size Used by
  1566. 0xffffff80006d0000 hello 16384 0
  1567. ....
  1568. Bibliography:
  1569. * https://events.static.linuxfound.org/sites/events/files/slides/Debugging%20the%20Linux%20Kernel%20with%20GDB.pdf
  1570. * https://wiki.linaro.org/LandingTeams/ST/GDB
  1571. ==== lx-ps
  1572. List all processes:
  1573. ....
  1574. lx-ps
  1575. ....
  1576. Sample output:
  1577. ....
  1578. 0xffff88000ed08000 1 init
  1579. 0xffff88000ed08ac0 2 kthreadd
  1580. ....
  1581. The second and third fields are obviously PID and process name.
  1582. The first one is more interesting, and contains the address of the `task_struct` in memory.
  1583. This can be confirmed with:
  1584. ....
  1585. p ((struct task_struct)*0xffff88000ed08000
  1586. ....
  1587. which contains the correct PID for all threads I've tried:
  1588. ....
  1589. pid = 1,
  1590. ....
  1591. 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!
  1592. On ARM, I tried:
  1593. ....
  1594. task_pt_regs((struct thread_info *)((struct task_struct)*0xffffffc00e8f8000))->uregs[ARM_pc]
  1595. ....
  1596. 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?
  1597. Bibliography:
  1598. * https://stackoverflow.com/questions/9561546/thread-aware-gdb-for-kernel
  1599. * https://wiki.linaro.org/LandingTeams/ST/GDB
  1600. * https://events.static.linuxfound.org/sites/events/files/slides/Debugging%20the%20Linux%20Kernel%20with%20GDB.pdf presentation: https://www.youtube.com/watch?v=pqn5hIrz3A8
  1601. === Debug the GDB remote protocol
  1602. For when it breaks again, or you want to add a new feature!
  1603. ....
  1604. ./run --debug
  1605. ./run-gdb --before '-ex "set remotetimeout 99999" -ex "set debug remote 1"' start_kernel
  1606. ....
  1607. See also: https://stackoverflow.com/questions/13496389/gdb-remote-protocol-how-to-analyse-packets
  1608. [[remote-g-packet]]
  1609. ==== Remote 'g' packet reply is too long
  1610. This error means that the GDB server, e.g. in QEMU, sent more registers than the GDB client expected.
  1611. This can happen for the following reasons:
  1612. * 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
  1613. * there is a bug in the GDB server and the XML description does not match the number of registers actually sent
  1614. * 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
  1615. 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
  1616. == KGDB
  1617. KGDB is kernel dark magic that allows you to GDB the kernel on real hardware without any extra hardware support.
  1618. 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.
  1619. 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.
  1620. First run the kernel with:
  1621. ....
  1622. ./run --kgdb
  1623. ....
  1624. this passes the following options on the kernel CLI:
  1625. ....
  1626. kgdbwait kgdboc=ttyS1,115200
  1627. ....
  1628. `kgdbwait` tells the kernel to wait for KGDB to connect.
  1629. So the kernel sets things up enough for KGDB to start working, and then boot pauses waiting for connection:
  1630. ....
  1631. <6>[ 4.866050] Serial: 8250/16550 driver, 4 ports, IRQ sharing disabled
  1632. <6>[ 4.893205] 00:05: ttyS0 at I/O 0x3f8 (irq = 4, base_baud = 115200) is a 16550A
  1633. <6>[ 4.916271] 00:06: ttyS1 at I/O 0x2f8 (irq = 3, base_baud = 115200) is a 16550A
  1634. <6>[ 4.987771] KGDB: Registered I/O driver kgdboc
  1635. <2>[ 4.996053] KGDB: Waiting for connection from remote gdb...
  1636. Entering kdb (current=0x(____ptrval____), pid 1) on processor 0 due to Keyboard Entry
  1637. [0]kdb>
  1638. ....
  1639. KGDB expects the connection at `ttyS1`, our second serial port after `ttyS0` which contains the terminal.
  1640. The last line is the KDB prompt, and is covered at: <<kdb>>. Typing now shows nothing because that prompt is expecting input from `ttyS1`.
  1641. Instead, we connect to the serial port `ttyS1` with GDB:
  1642. ....
  1643. ./run-gdb --kgdb --no-continue
  1644. ....
  1645. Once GDB connects, it is left inside the function `kgdb_breakpoint`.
  1646. So now we can set breakpoints and continue as usual.
  1647. For example, in GDB:
  1648. ....
  1649. continue
  1650. ....
  1651. Then in QEMU:
  1652. ....
  1653. ./count.sh &
  1654. ./kgdb.sh
  1655. ....
  1656. link:rootfs_overlay/lkmc/kgdb.sh[] pauses the kernel for KGDB, and gives control back to GDB.
  1657. And now in GDB we do the usual:
  1658. ....
  1659. break __x64_sys_write
  1660. continue
  1661. continue
  1662. continue
  1663. continue
  1664. ....
  1665. And now you can count from KGDB!
  1666. 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.
  1667. See also:
  1668. * https://github.com/torvalds/linux/blob/v4.9/Documentation/DocBook/kgdb.tmpl
  1669. * https://stackoverflow.com/questions/22004616/qemu-kernel-debugging-with-kgdb/44197715#44197715
  1670. === KGDB ARM
  1671. 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
  1672. One possible workaround for this would be to use <<kdb-arm>>.
  1673. Main more generic question: https://stackoverflow.com/questions/14155577/how-to-use-kgdb-on-arm
  1674. === KGDB kernel modules
  1675. Just works as you would expect:
  1676. ....
  1677. insmod timer.ko
  1678. ./kgdb.sh
  1679. ....
  1680. In GDB:
  1681. ....
  1682. break lkmc_timer_callback
  1683. continue
  1684. continue
  1685. continue
  1686. ....
  1687. and you now control the count.
  1688. === KDB
  1689. KDB is a way to use KDB directly in your main console, without GDB.
  1690. 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 .
  1691. 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).
  1692. Run QEMU as:
  1693. ....
  1694. ./run --kdb
  1695. ....
  1696. This passes `kgdboc=ttyS0` to the Linux CLI, therefore using our main console. Then QEMU:
  1697. ....
  1698. [0]kdb> go
  1699. ....
  1700. And now the `kdb>` prompt is responsive because it is listening to the main console.
  1701. After boot finishes, run the usual:
  1702. ....
  1703. ./count.sh &
  1704. ./kgdb.sh
  1705. ....
  1706. And you are back in KDB. Now you can count with:
  1707. ....
  1708. [0]kdb> bp __x64_sys_write
  1709. [0]kdb> go
  1710. [0]kdb> go
  1711. [0]kdb> go
  1712. [0]kdb> go
  1713. ....
  1714. And you will break whenever `__x64_sys_write` is hit.
  1715. You can get see further commands with:
  1716. ....
  1717. [0]kdb> help
  1718. ....
  1719. 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.
  1720. ==== KDB graphic
  1721. You can also use KDB directly from the <<graphics,graphic>> window with:
  1722. ....
  1723. ./run --graphic --kdb
  1724. ....
  1725. This setup could be used to debug the kernel on machines without serial, such as modern desktops.
  1726. This works because `--graphics` adds `kbd` (which stands for `KeyBoarD`!) to `kgdboc`.
  1727. ==== KDB ARM
  1728. TODO neither `arm` and `aarch64` are working as of 1cd1e58b023791606498ca509256cc48e95e4f5b + 1.
  1729. `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.
  1730. `aarch64` seems to place the breakpoint correctly, but after the first `go` the kernel oopses with warning:
  1731. ....
  1732. WARNING: CPU: 0 PID: 46 at /root/linux-kernel-module-cheat/submodules/linux/kernel/smp.c:416 smp_call_function_many+0xdc/0x358
  1733. ....
  1734. and stack trace:
  1735. ....
  1736. smp_call_function_many+0xdc/0x358
  1737. kick_all_cpus_sync+0x30/0x38
  1738. kgdb_flush_swbreak_addr+0x3c/0x48
  1739. dbg_deactivate_sw_breakpoints+0x7c/0xb8
  1740. kgdb_cpu_enter+0x284/0x6a8
  1741. kgdb_handle_exception+0x138/0x240
  1742. kgdb_brk_fn+0x2c/0x40
  1743. brk_handler+0x7c/0xc8
  1744. do_debug_exception+0xa4/0x1c0
  1745. el1_dbg+0x18/0x78
  1746. __arm64_sys_write+0x0/0x30
  1747. el0_svc_handler+0x74/0x90
  1748. el0_svc+0x8/0xc
  1749. ....
  1750. My theory is that every serious ARM developer has JTAG, and no one ever tests this, and the kernel code is just broken.
  1751. == gdbserver
  1752. Step debug userland processes to understand how they are talking to the kernel.
  1753. First build `gdbserver` into the root filesystem:
  1754. ....
  1755. ./build-buildroot --config 'BR2_PACKAGE_GDB=y'
  1756. ....
  1757. Then on guest, to debug link:userland/linux/myinsmod.c[]:
  1758. ....
  1759. ./gdbserver.sh ./linux/myinsmod.out hello.ko
  1760. ....
  1761. Source: link:rootfs_overlay/lkmc/gdbserver.sh[].
  1762. And on host:
  1763. ....
  1764. ./run-gdbserver userland/linux/myinsmod.c
  1765. ....
  1766. or alternatively with the path to the executable itself:
  1767. ....
  1768. ./run-gdbserver "$(./getvar userland_build_dir)/linux/myinsmod.out"
  1769. ....
  1770. Bibliography: https://reverseengineering.stackexchange.com/questions/8829/cross-debugging-for-arm-mips-elf-with-qemu-toolchain/16214#16214
  1771. === gdbserver BusyBox
  1772. Analogous to <<gdb-step-debug-userland-processes>>:
  1773. ....
  1774. ./gdbserver.sh ls
  1775. ....
  1776. on host you need:
  1777. ....
  1778. ./run-gdbserver "$(./getvar buildroot_build_build_dir)"/busybox-*/busybox ls_main
  1779. ....
  1780. === gdbserver libc
  1781. Our setup gives you the rare opportunity to step debug libc and other system libraries.
  1782. For example in the guest:
  1783. ....
  1784. ./gdbserver.sh ./count.out
  1785. ....
  1786. Then on host:
  1787. ....
  1788. ./run-gdbserver count
  1789. ....
  1790. and inside GDB:
  1791. ....
  1792. break sleep
  1793. continue
  1794. ....
  1795. And you are now left inside the `sleep` function of our default libc implementation uclibc link:https://cgit.uclibc-ng.org/cgi/cgit/uclibc-ng.git/tree/libc/unistd/sleep.c?h=v1.0.30#n91[`libc/unistd/sleep.c`]!
  1796. You can also step into the `sleep` call:
  1797. ....
  1798. step
  1799. ....
  1800. This is made possible by the GDB command that we use by default:
  1801. ....
  1802. set sysroot ${common_buildroot_build_dir}/staging
  1803. ....
  1804. which automatically finds unstripped shared libraries on the host for us.
  1805. See also: https://stackoverflow.com/questions/8611194/debugging-shared-libraries-with-gdbserver/45252113#45252113
  1806. === gdbserver dynamic loader
  1807. 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
  1808. Bibliography: https://stackoverflow.com/questions/20114565/gdb-step-into-dynamic-linkerld-so-code
  1809. == CPU architecture
  1810. The portability of the kernel and toolchains is amazing: change an option and most things magically work on completely different hardware.
  1811. To use `arm` instead of x86 for example:
  1812. ....
  1813. ./build-buildroot --arch arm
  1814. ./run --arch arm
  1815. ....
  1816. Debug:
  1817. ....
  1818. ./run --arch arm --gdb-wait
  1819. # On another terminal.
  1820. ./run-gdb --arch arm
  1821. ....
  1822. We also have one letter shorthand names for the architectures and `--arch` option:
  1823. ....
  1824. # aarch64
  1825. ./run -a A
  1826. # arm
  1827. ./run -a a
  1828. # x86_64
  1829. ./run -a x
  1830. ....
  1831. Known quirks of the supported architectures are documented in this section.
  1832. === x86_64
  1833. ==== ring0
  1834. This example illustrates how reading from the x86 control registers with `mov crX, rax` can only be done from kernel land on ring0.
  1835. From kernel land:
  1836. ....
  1837. insmod ring0.ko
  1838. ....
  1839. works and output the registers, for example:
  1840. ....
  1841. cr0 = 0xFFFF880080050033
  1842. cr2 = 0xFFFFFFFF006A0008
  1843. cr3 = 0xFFFFF0DCDC000
  1844. ....
  1845. However if we try to do it from userland:
  1846. ....
  1847. ./ring0.out
  1848. ....
  1849. stdout gives:
  1850. ....
  1851. Segmentation fault
  1852. ....
  1853. and dmesg outputs:
  1854. ....
  1855. traps: ring0.out[55] general protection ip:40054c sp:7fffffffec20 error:0 in ring0.out[400000+1000]
  1856. ....
  1857. Sources:
  1858. * link:kernel_modules/ring0.c[]
  1859. * link:lkmc/ring0.h[]
  1860. * link:userland/ring0.c[]
  1861. In both cases, we attempt to run the exact same code which is shared on the `ring0.h` header file.
  1862. Bibliography:
  1863. * https://stackoverflow.com/questions/7415515/how-to-access-the-control-registers-cr0-cr2-cr3-from-a-program-getting-segmenta/7419306#7419306
  1864. * https://stackoverflow.com/questions/18717016/what-are-ring-0-and-ring-3-in-the-context-of-operating-systems/44483439#44483439
  1865. === arm
  1866. ==== Run arm executable in aarch64
  1867. 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
  1868. I've tried:
  1869. ....
  1870. ./run-toolchain --arch aarch64 gcc -- -static ~/test/hello_world.c -o "$(./getvar p9_dir)/a.out"
  1871. ./run --arch aarch64 --eval-after '/mnt/9p/data/a.out'
  1872. ....
  1873. but it fails with:
  1874. ....
  1875. a.out: line 1: syntax error: unexpected word (expecting ")")
  1876. ....
  1877. === MIPS
  1878. We used to "support" it until f8c0502bb2680f2dbe7c1f3d7958f60265347005 (it booted) but dropped since one was testing it often.
  1879. If you want to revive and maintain it, send a pull request.
  1880. === Other architectures
  1881. It should not be too hard to port this repository to any architecture that Buildroot supports. Pull requests are welcome.
  1882. == init
  1883. When the Linux kernel finishes booting, it runs an executable as the first and only userland process. This executable is called the `init` program.
  1884. The init process is then responsible for setting up the entire userland (or destroying everything when you want to have fun).
  1885. 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.
  1886. systemd provides a "popular" init implementation for desktop distros as of 2017.
  1887. BusyBox provides its own minimalistic init implementation which Buildroot, and therefore this repo, uses by default.
  1888. 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
  1889. 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: <<path-to-init>>
  1890. === Replace init
  1891. To have more control over the system, you can replace BusyBox's init with your own.
  1892. The most direct way to replace `init` with our own is to just use the `init=` <<kernel-command-line-parameters,command line parameter>> directly:
  1893. ....
  1894. ./run --kernel-cli 'init=/lkmc/count.sh'
  1895. ....
  1896. This just counts every second forever and does not give you a shell.
  1897. 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: <<init-environment>>.
  1898. For this reason, we have created a more robust helper method with the `--eval` option:
  1899. ....
  1900. ./run --eval 'echo "asdf qwer";insmod hello.ko;./linux/poweroff.out'
  1901. ....
  1902. It is basically a shortcut for:
  1903. ....
  1904. ./run --kernel-cli 'init=/lkmc/eval_base64.sh - lkmc_eval="insmod hello.ko;./linux/poweroff.out"'
  1905. ....
  1906. Source: link:rootfs_overlay/lkmc/eval_base64.sh[].
  1907. This allows quoting and newlines by base64 encoding on host, and decoding on guest, see: <<kernel-command-line-parameters-escaping>>.
  1908. It also automatically chooses between `init=` and `rcinit=` for you, see: <<path-to-init>>
  1909. `--eval` replaces BusyBox' init completely, which makes things more minimal, but also has has the following consequences:
  1910. * `/etc/fstab` mounts are not done, notably `/proc` and `/sys`, test it out with:
  1911. +
  1912. ....
  1913. ./run --eval 'echo asdf;ls /proc;ls /sys;echo qwer'
  1914. ....
  1915. * 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:
  1916. +
  1917. ....
  1918. ./run --eval 'echo hello;sh'
  1919. ....
  1920. The best way to overcome those limitations is to use: <<init-busybox>>
  1921. If the script is large, you can add it to a gitignored file and pass that to `--eval` as in:
  1922. ....
  1923. echo '
  1924. cd /lkmc
  1925. insmod hello.ko
  1926. ./linux/poweroff.out
  1927. ' > data/gitignore.sh
  1928. ./run --eval "$(cat data/gitignore.sh)"
  1929. ....
  1930. or add it to a file to the root filesystem guest and rebuild:
  1931. ....
  1932. echo '#!/bin/sh
  1933. cd /lkmc
  1934. insmod hello.ko
  1935. ./linux/poweroff.out
  1936. ' > rootfs_overlay/lkmc/gitignore.sh
  1937. chmod +x rootfs_overlay/lkmc/gitignore.sh
  1938. ./build-buildroot
  1939. ./run --kernel-cli 'init=/lkmc/gitignore.sh'
  1940. ....
  1941. Remember that if your init returns, the kernel will panic, there are just two non-panic possibilities:
  1942. * run forever in a loop or long sleep
  1943. * `poweroff` the machine
  1944. ==== poweroff.out
  1945. Just using BusyBox' `poweroff` at the end of the `init` does not work and the kernel panics:
  1946. ....
  1947. ./run --eval poweroff
  1948. ....
  1949. because BusyBox' `poweroff` tries to do some fancy stuff like killing init, likely to allow userland to shutdown nicely.
  1950. But this fails when we are `init` itself!
  1951. BusyBox' `poweroff` works more brutally and effectively if you add `-f`:
  1952. ....
  1953. ./run --eval 'poweroff -f'
  1954. ....
  1955. but why not just use our minimal `./linux/poweroff.out` and be done with it?
  1956. ....
  1957. ./run --eval './linux/poweroff.out'
  1958. ....
  1959. Source: link:userland/linux/poweroff.c[]
  1960. 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
  1961. ==== sleep_forever.out
  1962. I dare you to guess what this does:
  1963. ....
  1964. ./run --eval './posix/sleep_forever.out'
  1965. ....
  1966. Source: link:userland/posix/sleep_forever.c[]
  1967. This executable is a convenient simple init that does not panic and sleeps instead.
  1968. ==== time_boot.out
  1969. Get a reasonable answer to "how long does boot take in guest time?":
  1970. ....
  1971. ./run --eval-after './linux/time_boot.c'
  1972. ....
  1973. Source: link:userland/linux/time_boot.out[]
  1974. That executable writes to `dmesg` directly through `/dev/kmsg` a message of type:
  1975. ....
  1976. [ 2.188242] /path/to/linux-kernel-module-cheat/userland/linux/time_boot.c
  1977. ....
  1978. which tells us that boot took `2.188242` seconds based on the dmesg timestamp.
  1979. Bibliography: https://stackoverflow.com/questions/12683169/measure-time-taken-for-linux-kernel-from-bootup-to-userpace/46517014#46517014
  1980. [[init-busybox]]
  1981. === Run command at the end of BusyBox init
  1982. Use the `--eval-after` option is for you rely on something that BusyBox' init set up for you like `/etc/fstab`:
  1983. ....
  1984. ./run --eval-after 'echo asdf;ls /proc;ls /sys;echo qwer'
  1985. ....
  1986. After the commands run, you are left on an interactive shell.
  1987. The above command is basically equivalent to:
  1988. ....
  1989. ./run --kernel-cli-after-dash 'lkmc_eval="insmod hello.ko;./linux/poweroff.out;"'
  1990. ....
  1991. where the `lkmc_eval` option gets evaled by our default link:rootfs_overlay/etc/init.d/S98[] startup script.
  1992. Except that `--eval-after` is smarter and uses `base64` encoding.
  1993. Alternatively, you can also add the comamdns to run to a new `init.d` entry to run at the end o the BusyBox init:
  1994. ....
  1995. cp rootfs_overlay/etc/init.d/S98 rootfs_overlay/etc/init.d/S99.gitignore
  1996. vim rootfs_overlay/etc/init.d/S99.gitignore
  1997. ./build-buildroot
  1998. ./run
  1999. ....
  2000. and they will be run automatically before the login prompt.
  2001. 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`].
  2002. === Path to init
  2003. The init is selected at:
  2004. * initrd or initramfs system: `/init`, a custom one can be set with the `rdinit=` <<kernel-command-line-parameters,kernel command line parameter>>
  2005. * otherwise: default is `/sbin/init`, followed by some other paths, a custom one can be set with `init=`
  2006. 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
  2007. === Init environment
  2008. Documented at link:https://www.kernel.org/doc/html/v4.14/admin-guide/kernel-parameters.html[]:
  2009. ____
  2010. 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.
  2011. ____
  2012. And you can try it out with:
  2013. ....
  2014. ./run --kernel-cli 'init=/lkmc/linux/init_env_poweroff.out - asdf=qwer zxcv'
  2015. ....
  2016. Output:
  2017. ....
  2018. args:
  2019. /lkmc/linux/init_env_poweroff.out
  2020. -
  2021. zxcv
  2022. env:
  2023. HOME=/
  2024. TERM=linux
  2025. asdf=qwer
  2026. ....
  2027. Source: link:userland/linux/init_env_poweroff.c[].
  2028. ==== init arguments
  2029. The annoying dash `-` gets passed as a parameter to `init`, which makes it impossible to use this method for most non custom executables.
  2030. Arguments with dots that come after `-` are still treated specially (of the form `subsystem.somevalue`) and disappear, from args, e.g.:
  2031. ....
  2032. ./run --kernel-cli 'init=/lkmc/linux/init_env_poweroff.out - /lkmc/linux/poweroff.out'
  2033. ....
  2034. outputs:
  2035. ....
  2036. args
  2037. /lkmc/linux/init_env_poweroff.out
  2038. -
  2039. ab
  2040. ....
  2041. so see how `a.b` is gone.
  2042. 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[].
  2043. ==== init environment env
  2044. 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
  2045. ....
  2046. const char *envp_init[MAX_INIT_ENVS+2] = { "HOME=/", "TERM=linux", NULL, };
  2047. ....
  2048. ==== BusyBox shell init environment
  2049. On top of the Linux kernel, the BusyBox `/bin/sh` shell will also define other variables.
  2050. We can explore the shenanigans that the shell adds on top of the Linux kernel with:
  2051. ....
  2052. ./run --kernel-cli 'init=/bin/sh'
  2053. ....
  2054. From there we observe that:
  2055. ....
  2056. env
  2057. ....
  2058. gives:
  2059. ....
  2060. SHLVL=1
  2061. HOME=/
  2062. TERM=linux
  2063. PWD=/
  2064. ....
  2065. therefore adding `SHLVL` and `PWD` to the default kernel exported variables.
  2066. 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:
  2067. ....
  2068. set
  2069. ....
  2070. then it shows more variables, notably:
  2071. ....
  2072. PATH='/sbin:/usr/sbin:/bin:/usr/bin'
  2073. ....
  2074. ===== BusyBox shell initrc files
  2075. Login shells source some default files, notably:
  2076. ....
  2077. /etc/profile
  2078. $HOME/.profile
  2079. ....
  2080. In our case, `HOME` is set to `/` presumably by `init` at: https://git.busybox.net/busybox/tree/init/init.c?id=5059653882dbd86e3bbf48389f9f81b0fac8cd0a#n1114
  2081. We provide `/.profile` from link:rootfs_overlay/.profile[], and use the default BusyBox `/etc/profile`.
  2082. 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
  2083. When we use just `init=/bin/sh`, the Linux kernel sets `argv[0]` to `/bin/sh`, which does not start with `-`.
  2084. 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:
  2085. ....
  2086. cat /proc/$$/cmdline
  2087. ....
  2088. where `$$` is the PID of the shell itself: https://stackoverflow.com/questions/21063765/get-pid-in-shell-bash
  2089. Bibliography: https://unix.stackexchange.com/questions/176027/ash-profile-configuration-file
  2090. == initrd
  2091. 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
  2092. 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.
  2093. This is very similar to the kernel image itself, which already gets put into memory by the QEMU `-kernel` option.
  2094. 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.
  2095. To enable initrd instead of the default ext2 disk image, do:
  2096. ....
  2097. ./build-buildroot --initrd
  2098. ./run --initrd
  2099. ....
  2100. By looking at the QEMU run command generated, you can see that we didn't give the `-drive` option at all:
  2101. ....
  2102. cat "$(./getvar run_dir)/run.sh"
  2103. ....
  2104. Instead, we used the QEMU `-initrd` option to point to the `.cpio` filesystem that Buildroot generated for us.
  2105. Try removing that `-initrd` option to watch the kernel panic without rootfs at the end of boot.
  2106. When using `.cpio`, there can be no <<disk-persistency,filesystem persistency>> across boots, since all file operations happen in memory in a tmpfs:
  2107. ....
  2108. date >f
  2109. poweroff
  2110. cat f
  2111. # can't open 'f': No such file or directory
  2112. ....
  2113. which can be good for automated tests, as it ensures that you are using a pristine unmodified system image every time.
  2114. Not however that we already disable disk persistency by default on ext2 filesystems even without `--initrd`: <<disk-persistency>>.
  2115. One downside of this method is that it has to put the entire filesystem into memory, and could lead to a panic:
  2116. ....
  2117. end Kernel panic - not syncing: Out of memory and no killable processes...
  2118. ....
  2119. This can be solved by increasing the memory with:
  2120. ....
  2121. ./run --initrd --memory 256M
  2122. ....
  2123. The main ingredients to get initrd working are:
  2124. * `BR2_TARGET_ROOTFS_CPIO=y`: make Buildroot generate `images/rootfs.cpio` in addition to the other images.
  2125. +
  2126. It is also possible to compress that image with other options.
  2127. * `qemu -initrd`: make QEMU put the image into memory and tell the kernel about it.
  2128. * `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
  2129. +
  2130. Buildroot forces that option when `BR2_TARGET_ROOTFS_CPIO=y` is given
  2131. 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
  2132. === initrd in desktop distros
  2133. Most modern desktop distributions have an initrd in their root disk to do early setup.
  2134. The rationale for this is described at: https://en.wikipedia.org/wiki/Initial_ramdisk
  2135. One obvious use case is having an encrypted root filesystem: you keep the initrd in an unencrypted partition, and then setup decryption from there.
  2136. 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:
  2137. ....
  2138. initrd /initrd.img-4.4.0-108-generic
  2139. ....
  2140. Related: https://stackoverflow.com/questions/6405083/initrd-and-booting-the-linux-kernel
  2141. === initramfs
  2142. initramfs is just like <<initrd>>, but you also glue the image directly to the kernel image itself using the kernel's build system.
  2143. Try it out with:
  2144. ....
  2145. ./build-buildroot --initramfs
  2146. ./build-linux --initramfs
  2147. ./run --initramfs
  2148. ....
  2149. 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.
  2150. 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:
  2151. ....
  2152. cat "$(./getvar run_dir)/run.sh"
  2153. ....
  2154. It is also interesting to observe how this increases the size of the kernel image if you do a:
  2155. ....
  2156. ls -lh "$(./getvar linux_image)"
  2157. ....
  2158. before and after using initramfs, since the `.cpio` is now glued to the kernel image.
  2159. Don't forget that to stop using initramfs, you must rebuild the kernel without `--initramfs` to get rid of the attached CPIO image:
  2160. ....
  2161. ./build-linux
  2162. ./run
  2163. ....
  2164. Alternatively, consider using <<linux-kernel-build-variants>> if you need to switch between initramfs and non initramfs often:
  2165. ....
  2166. ./build-buildroot --initramfs
  2167. ./build-linux --initramfs --linux-build-id initramfs
  2168. ./run --initramfs --linux-build-id
  2169. ....
  2170. Setting up initramfs is very easy: our scripts just set `CONFIG_INITRAMFS_SOURCE` to point to the CPIO path.
  2171. http://nairobi-embedded.org/initramfs_tutorial.html shows a full manual setup.
  2172. === rootfs
  2173. This is how `/proc/mounts` shows the root filesystem:
  2174. * hard disk: `/dev/root on / type ext2 (rw,relatime,block_validity,barrier,user_xattr)`. That file does not exist however.
  2175. * initrd: `rootfs on / type rootfs (rw)`
  2176. * initramfs: `rootfs on / type rootfs (rw)`
  2177. TODO: understand `/dev/root` better:
  2178. * https://unix.stackexchange.com/questions/295060/why-on-some-linux-systems-does-the-root-filesystem-appear-as-dev-root-instead
  2179. * https://superuser.com/questions/1213770/how-do-you-determine-the-root-device-if-dev-root-is-missing
  2180. ==== /dev/root
  2181. See: <<rootfs>>
  2182. === gem5 initrd
  2183. 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
  2184. This would require gem5 to load the CPIO into memory, just like QEMU. Grepping `initrd` shows some ARM hits under:
  2185. ....
  2186. src/arch/arm/linux/atag.hh
  2187. ....
  2188. but they are commented out.
  2189. === gem5 initramfs
  2190. This could in theory be easier to make work than initrd since the emulator does not have to do anything special.
  2191. 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:
  2192. ....
  2193. VFS: Cannot open root device "sda" or unknown-block(8,0): error -5
  2194. ....
  2195. 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: <<vmlinux-vs-bzimage-vs-zimage-vs-image>>.
  2196. 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>>.
  2197. 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.
  2198. == Device tree
  2199. The device tree is a Linux kernel defined data structure that serves to inform the kernel how the hardware is setup.
  2200. <<platform_device>> contains a minimal runnable example of device tree manipulation.
  2201. 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.
  2202. x86 does not use it device trees, but many other archs to, notably ARM.
  2203. This is notably because ARM boards:
  2204. * typically don't have discoverable hardware extensions like PCI, but rather just put everything on an SoC with magic register addresses
  2205. * are made by a wide variety of vendors due to ARM's licensing business model, which increases variability
  2206. 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
  2207. === DTB files
  2208. Files that contain device trees have the `.dtb` extension when compiled, and `.dts` when in text form.
  2209. You can convert between those formats with:
  2210. ....
  2211. "$(./getvar buildroot_host_dir)"/bin/dtc -I dtb -O dts -o a.dts a.dtb
  2212. "$(./getvar buildroot_host_dir)"/bin/dtc -I dts -O dtb -o a.dtb a.dts
  2213. ....
  2214. Buildroot builds the tool due to `BR2_PACKAGE_HOST_DTC=y`.
  2215. On Ubuntu 18.04, the package is named:
  2216. ....
  2217. sudo apt-get install device-tree-compiler
  2218. ....
  2219. See also: https://stackoverflow.com/questions/14000736/tool-to-visualize-the-device-tree-file-dtb-used-by-the-linux-kernel/39931834#39931834
  2220. Device tree files are provided to the emulator just like the root filesystem and the Linux kernel image.
  2221. In real hardware, those components are also often provided separately. For example, on the Raspberry Pi 2, the SD card must contain two partitions:
  2222. * the first contains all magic files, including the Linux kernel and the device tree
  2223. * the second contains the root filesystem
  2224. See also: https://stackoverflow.com/questions/29837892/how-to-run-a-c-program-with-no-os-on-the-raspberry-pi/40063032#40063032
  2225. === Device tree syntax
  2226. Good format descriptions:
  2227. * https://www.raspberrypi.org/documentation/configuration/device-tree.md
  2228. Minimal example
  2229. ....
  2230. /dts-v1/;
  2231. / {
  2232. a;
  2233. };
  2234. ....
  2235. Check correctness with:
  2236. ....
  2237. dtc a.dts
  2238. ....
  2239. Separate nodes are simply merged by node path, e.g.:
  2240. ....
  2241. /dts-v1/;
  2242. / {
  2243. a;
  2244. };
  2245. / {
  2246. b;
  2247. };
  2248. ....
  2249. then `dtc a.dts` gives:
  2250. ....
  2251. /dts-v1/;
  2252. / {
  2253. a;
  2254. b;
  2255. };
  2256. ....
  2257. === Get device tree from a running kernel
  2258. https://unix.stackexchange.com/questions/265890/is-it-possible-to-get-the-information-for-a-device-tree-using-sys-of-a-running/330926#330926
  2259. 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.
  2260. So observing the device tree from the guest allows to easily see what the emulator has generated.
  2261. Compile the `dtc` tool into the root filesystem:
  2262. ....
  2263. ./build-buildroot \
  2264. --arch aarch64 \
  2265. --config 'BR2_PACKAGE_DTC=y' \
  2266. --config 'BR2_PACKAGE_DTC_PROGRAMS=y' \
  2267. ;
  2268. ....
  2269. `-M virt` for example, which we use by default for `aarch64`, boots just fine without the `-dtb` option:
  2270. ....
  2271. ./run --arch aarch64
  2272. ....
  2273. Then, from inside the guest:
  2274. ....
  2275. dtc -I fs -O dts /sys/firmware/devicetree/base
  2276. ....
  2277. contains:
  2278. ....
  2279. cpus {
  2280. #address-cells = <0x1>;
  2281. #size-cells = <0x0>;
  2282. cpu@0 {
  2283. compatible = "arm,cortex-a57";
  2284. device_type = "cpu";
  2285. reg = <0x0>;
  2286. };
  2287. };
  2288. ....
  2289. === Device tree emulator generation
  2290. Since emulators know everything about the hardware, they can automatically generate device trees for us, which is very convenient.
  2291. This is the case for both QEMU and gem5.
  2292. For example, if we increase the <<number-of-cores,number of cores>> to 2:
  2293. ....
  2294. ./run --arch aarch64 --cpus 2
  2295. ....
  2296. QEMU automatically adds a second CPU to the DTB!
  2297. ....
  2298. cpu@0 {
  2299. cpu@1 {
  2300. ....
  2301. The action seems to be happening at: `hw/arm/virt.c`.
  2302. You can dump the DTB QEMU generated with:
  2303. ....
  2304. ./run --arch aarch64 -- -machine dumpdtb=dtb.dtb
  2305. ....
  2306. as mentioned at: https://lists.gnu.org/archive/html/qemu-discuss/2017-02/msg00051.html
  2307. <<gem5-fs_biglittle>> 2a9573f5942b5416fb0570cf5cb6cdecba733392 can also generate its own DTB.
  2308. gem5 can generate DTBs on ARM with `--generate-dtb`. The generated DTB is placed in the <<m5out-directory>> named as `system.dtb`.
  2309. == KVM
  2310. link: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.
  2311. You can make QEMU or gem5 by passing enabling KVM with:
  2312. ....
  2313. ./run --kvm
  2314. ....
  2315. but it was broken in gem5 with pending patches: https://www.mail-archive.com/gem5-users@gem5.org/msg15046.html It fails immediately on:
  2316. ....
  2317. panic: KVM: Failed to enter virtualized mode (hw reason: 0x80000021)
  2318. ....
  2319. KVM works by running userland instructions natively directly on the real hardware instead of running a software simulation of those instructions.
  2320. 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 link:https://www.youtube.com/watch?v=8ItXpmLsINs[running an ARM desktop for some weird reason] :-)
  2321. We don't enable KVM by default because:
  2322. * it limits visibility, since more things are running natively:
  2323. ** can't use <<gdb,GDB>>
  2324. ** can't do <<tracing,instruction tracing>>
  2325. ** on gem5, you lose <<gem5-run-benchmark,cycle counts>> and therefor any notion of performance
  2326. * QEMU kernel boots are already <<benchmark-linux-kernel-boot,fast enough>> for most purposes without it
  2327. 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
  2328. === KVM arm
  2329. 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.
  2330. We can test KVM on arm by running this repository inside an Ubuntu arm QEMU VM.
  2331. This produces no speedup of course, since the VM is already slow since it cannot use KVM on the x86 host.
  2332. 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
  2333. Then, from inside that image:
  2334. ....
  2335. sudo apt-get install git
  2336. git clone https://github.com/cirosantilli/linux-kernel-module-cheat
  2337. cd linux-kernel-module-cheat
  2338. sudo ./setup -y
  2339. ....
  2340. and then proceed exactly as in <<prebuilt>>.
  2341. 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.
  2342. 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
  2343. == User mode simulation
  2344. Both QEMU and gem5 have an user mode simulation mode in addition to full system simulation that we consider elsewhere in this project.
  2345. 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>>.
  2346. In both, the basic idea is the same.
  2347. User mode simulation takes regular userland executables of any arch as input and executes them directly, without booting a kernel.
  2348. Instead of simulating the full system, it translates normal instructions like in full system mode, but magically forwards system calls to the host OS.
  2349. Advantages over full system simulation:
  2350. * 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
  2351. * 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.
  2352. Disadvantages:
  2353. * lower guest to host portability:
  2354. ** TODO confirm: host OS == guest OS?
  2355. ** TODO confirm: the host Linux kernel should be newer than the kernel the executable was built for.
  2356. +
  2357. It may still work even if that is not the case, but could fail is a missing system call is reached.
  2358. +
  2359. The target Linux kernel of the executable is a GCC toolchain build-time configuration.
  2360. ** emulator implementers have to keep up with libc changes, some of which break even a C hello world due setup code executed before main.
  2361. +
  2362. See also: <<user-mode-simulation-with-glibc>>
  2363. * 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
  2364. === QEMU user mode getting started
  2365. Let's run link:userland/c/print_argv.c[] built with the Buildroot toolchain on QEMU user mode:
  2366. ....
  2367. ./build user-mode-qemu
  2368. ./run \
  2369. --userland userland/c/print_argv.c \
  2370. --userland-args='asdf "qw er"' \
  2371. ;
  2372. ....
  2373. Output:
  2374. ....
  2375. /path/to/linux-kernel-module-cheat/out/userland/default/x86_64/c/print_argv.out
  2376. asdf
  2377. qw er
  2378. ....
  2379. `./run --userland` path resolution is analogous to <<baremetal-setup-getting-started,that of `./run --baremetal`>>.
  2380. `./build user-mode-qemu` first builds Buildroot, and then runs `./build-userland`, which is further documented at: <<userland-setup>>. It also builds QEMU. If you ahve already done a <<qemu-buildroot-setup>> previously, this will be very fast.
  2381. If you modify the userland programs, rebuild simply with:
  2382. ....
  2383. ./build-userland
  2384. ....
  2385. ==== User mode GDB
  2386. It's nice when <<gdb,the obvious>> just works, right?
  2387. ....
  2388. ./run \
  2389. --arch aarch64 \
  2390. --gdb-wait \
  2391. --userland userland/c/print_argv.c \
  2392. --userland-args 'asdf "qw er"' \
  2393. ;
  2394. ....
  2395. and on another shell:
  2396. ....
  2397. ./run-gdb \
  2398. --arch aarch64 \
  2399. --userland userland/c/print_argv.c \
  2400. main \
  2401. ;
  2402. ....
  2403. Or alternatively, if you are using <<tmux>>, do everything in one go with:
  2404. ....
  2405. ./run \
  2406. --arch aarch64 \
  2407. --gdb \
  2408. --userland userland/c/print_argv.c \
  2409. --userland-args 'asdf "qw er"' \
  2410. ;
  2411. ....
  2412. To stop at the very first instruction of a freestanding program, just use `--no-continue` TODO example.
  2413. === User mode tests
  2414. Automatically run all userland tests that can be run in user mode simulation, and check that they exit with status 0:
  2415. ....
  2416. ./build --all-archs test-user-mode
  2417. ./test-user-mode --all-archs --all-emulators
  2418. ....
  2419. Or just for QEMU:
  2420. ....
  2421. ./build --all-archs test-user-mode-qemu
  2422. ./test-user-mode --all-archs --emulator qemu
  2423. ....
  2424. Source: link:test-user-mode[]
  2425. This script skips a manually configured list of tests, notably:
  2426. * tests that depend on a full running kernel and cannot be run in user mode simulation, e.g. those that rely on kernel modules
  2427. * tests that require user interaction
  2428. * tests that take perceptible ammounts of time
  2429. * known bugs we didn't have time to fix ;-)
  2430. Tests under link:userland/libs/[] depend on certain libraries being available on the target, e.g. <<blas>> for link:userland/libs/blas[]. They are not run by default, but can be enabled with `--package` and `--package-all`.
  2431. The gem5 tests require building statically with build id `static`, see also: <<gem5-syscall-emulation-mode>>. TODO automate this better.
  2432. See: <<test-this-repo>> for more useful testing tips.
  2433. === User mode Buildroot executables
  2434. If you followed <<qemu-buildroot-setup>>, you can now run the executables created by Buildroot directly as:
  2435. ....
  2436. ./run \
  2437. --userland "$(./getvar buildroot_target_dir)/bin/echo" \
  2438. --userland-args='asdf' \
  2439. ;
  2440. ....
  2441. Here is an interesting examples of this: <<linux-test-project>>
  2442. === User mode simulation with glibc
  2443. At 125d14805f769104f93c510bedaa685a52ec025d we <<libc-choice,moved Buildroot from uClibc to glibc>>, and caused some user mode pain, which we document here.
  2444. ==== FATAL: kernel too old
  2445. Happens on all gem5 <<user-mode-simulation>> setups, but not on QEMU on Ubuntu 18.04 host.
  2446. glibc has a check for kernel version, likely obtained from the `uname` syscall, and if the kernel is not new enough, it quits.
  2447. Determining the right number to put there is of course highly non-trivial and would require an extensive userland test suite, which most emulator don't have.
  2448. We don't have this failure for QEMU on an 18.04 host, only gem5.
  2449. QEMU by default copies the host `uname` value. However, our scripts set it by default to our the latest Buildroot kernel version with QEMU's `-r` option, which is exposed as `--kernel-version`:
  2450. ....
  2451. ./run --arch aarch64 --kernel-version 4.18 --userland userland/posix/uname.c
  2452. ....
  2453. Source: link:userland/posix/uname.c[].
  2454. gem5 does not have such runtime configuration, but the error can be worked around for now by patching the hardcoded Linux version as mentioned at: https://stackoverflow.com/questions/48959349/how-to-solve-fatal-kernel-too-old-when-running-gem5-in-syscall-emulation-se-m to be a recent Linux version such as `v4.17.0`.
  2455. We override the default QEMU uname because otherwise all executables fail with "kernel too old" on older Ubuntu hosts. The downside is that you might hit syscalls which your host does not have for QEMU to forward to, but we'll let you be the judge of that.
  2456. The QEMU source that does this is at: https://github.com/qemu/qemu/blob/v3.1.0/linux-user/syscall.c#L8931
  2457. In gem5, there are tons of missing syscalls, and that number currently just gets bumped up randomly from time to time when someone gets fed up:
  2458. * https://stackoverflow.com/questions/53085048/how-to-compile-and-run-an-executable-in-gem5-syscall-emulation-mode-with-se-py/53085049#53085049
  2459. * https://gem5-review.googlesource.com/c/public/gem5/+/15855
  2460. The ID is just hardcoded on the source:
  2461. ==== stack smashing detected
  2462. For some reason QEMU / glibc x86_64 picks up the host libc, which breaks things.
  2463. Other archs work as they different host libc is skipped. <<user-mode-static-executables>> also work.
  2464. 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`.
  2465. Reproduction:
  2466. ....
  2467. rm -f "$(./getvar buildroot_target_dir)/etc/ld.so.cache"
  2468. ./run --userland userland/c/hello.c
  2469. ./run --userland userland/c/hello.c --qemu-which host
  2470. ....
  2471. Outcome:
  2472. ....
  2473. *** stack smashing detected ***: <unknown> terminated
  2474. qemu: uncaught target signal 6 (Aborted) - core dumped
  2475. ....
  2476. To get things working again, restore `ld.so.cache` with:
  2477. ....
  2478. ./build-buildroot
  2479. ....
  2480. I've also tested on an Ubuntu 16.04 guest and the failure is different one:
  2481. ....
  2482. qemu: uncaught target signal 4 (Illegal instruction) - core dumped
  2483. ....
  2484. A non-QEMU-specific example of stack smashing is shown at: https://stackoverflow.com/questions/1345670/stack-smashing-detected/51897264#51897264
  2485. Tested at: 2e32389ebf1bedd89c682aa7b8fe42c3c0cf96e5 + 1.
  2486. === User mode static executables
  2487. Example:
  2488. ....
  2489. ./build-userland \
  2490. --arch aarch64 \
  2491. --static \
  2492. ;
  2493. ./run \
  2494. --arch aarch64 \
  2495. --static \
  2496. --userland userland/c/print_argv.c \
  2497. --userland-args 'asdf "qw er"' \
  2498. ;
  2499. ....
  2500. 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.
  2501. We pass `-L` by default, so everything just works.
  2502. 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:
  2503. * gem5 user mode currently only supports static executables: <<gem5-syscall-emulation-mode>>
  2504. * QEMU x86_64 guest on x86_64 host was failing with <<stack-smashing-detected>>, but we found a workaround
  2505. ==== User mode static executables with dynamic libraries
  2506. One limitation of static executables is that Buildroot mostly only builds dynamic versions of libraries (the libc is an exception).
  2507. So programs that rely on those libraries might not compile as GCC can't find the `.a` version of the library.
  2508. For example, if we try to build <<blas>> statically:
  2509. ....
  2510. ./build-userland --package openblas --static -- userland/libs/openblas/hello.c
  2511. ....
  2512. it fails with:
  2513. ....
  2514. ld: cannot find -lopenblas
  2515. ....
  2516. === gem5 syscall emulation mode
  2517. Less robust than QEMU's, but still usable:
  2518. * https://stackoverflow.com/questions/48986597/when-should-you-use-full-system-fs-vs-syscall-emulation-se-with-userland-program
  2519. * https://stackoverflow.com/questions/48959349/how-to-solve-fatal-kernel-too-old-when-running-gem5-in-syscall-emulation-se-m
  2520. There are much more unimplemented syscalls in gem5 than in QEMU. Many of those are trivial to implement however.
  2521. As of 185c2730cc78d5adda683d76c0e3b35e7cb534f0, dynamically linked executables only work on x86, and they can only use the host libraries, which is ugly:
  2522. * https://stackoverflow.com/questions/50542222/how-to-run-a-dynamically-linked-executable-syscall-emulation-mode-se-py-in-gem5
  2523. * https://www.mail-archive.com/gem5-users@gem5.org/msg15585.html
  2524. If you try dynamically linked executables on ARM, they fail with:
  2525. ....
  2526. fatal: Unable to open dynamic executable's interpreter.
  2527. ....
  2528. So let's just play with some static ones:
  2529. ....
  2530. ./build-userland \
  2531. --arch aarch64 \
  2532. --static \
  2533. ;
  2534. ./run \
  2535. --arch aarch64 \
  2536. --emulator gem5 \
  2537. --userland userland/c/print_argv.c \
  2538. --userland-args 'asdf "qw er"' \
  2539. ;
  2540. ....
  2541. TODO: how to escape spaces on the command line arguments?
  2542. <<user-mode-gdb,GDB step debug>> also works normally on gem5:
  2543. ....
  2544. ./run \
  2545. --arch aarch64 \
  2546. --emulator gem5 \
  2547. --gdb-wait \
  2548. --static \
  2549. --userland userland/c/print_argv.c \
  2550. --userland-args 'asdf "qw er"' \
  2551. ;
  2552. ./run-gdb \
  2553. --arch aarch64 \
  2554. --emulator gem5 \
  2555. --static \
  2556. --userland userland/c/print_argv.c \
  2557. main \
  2558. ;
  2559. ....
  2560. ==== gem5 syscall emulation exit status
  2561. As of gem5 7fa4c946386e7207ad5859e8ade0bbfc14000d91, the crappy `se.py` script does not forward the exit status of syscall emulation mode, you can test it with:
  2562. ....
  2563. ./run --dry-run --emulator gem5 --static --userland userland/c/false.c
  2564. ....
  2565. Source: link:userland/c/false.c[].
  2566. Then manually run the generated gem5 CLI, and do:
  2567. ....
  2568. echo $?
  2569. ....
  2570. and the output is always `0`.
  2571. Instead, it just outputs a message to stdout just like for <<m5-fail>>:
  2572. ....
  2573. Simulated exit code not 0! Exit code is 1
  2574. ....
  2575. which we parse in link:run[] and then exit with the correct result ourselves...
  2576. Related thread: https://stackoverflow.com/questions/56032347/is-there-a-way-to-identify-if-gem5-run-got-over-successfully
  2577. ==== gem5 syscall emulation mode program stdin
  2578. gem5 shows its own stdout to terminal, and does not allow you to type stdin to programs.
  2579. Instead, you must pass stdin non-interactively with the through a file with the `--se.py --input` option, e.g.:
  2580. ....
  2581. printf a > f
  2582. ./run --emulator gem5 --userland userland/c/getchar.c --static -- --input f
  2583. ....
  2584. leads to gem5 output:
  2585. ....
  2586. enter a character: you entered: a
  2587. ....
  2588. Source: link:userland/c/getchar.c[]
  2589. ==== User mode vs full system benchmark
  2590. Let's see if user mode runs considerably faster than full system or not.
  2591. First we build Dhrystone manually statically since dynamic linking is broken in gem5: <<gem5-syscall-emulation-mode>>.
  2592. gem5 user mode:
  2593. ....
  2594. ./build-buildroot --arch arm --config 'BR2_PACKAGE_DHRYSTONE=y'
  2595. make \
  2596. -B \
  2597. -C "$(./getvar --arch arm buildroot_build_build_dir)/dhrystone-2" \
  2598. CC="$(./run-toolchain --arch arm --print-tool gcc)" \
  2599. CFLAGS=-static \
  2600. ;
  2601. time \
  2602. ./run \
  2603. --arch arm \
  2604. --emulator gem5 \
  2605. --userland "$(./getvar --arch arm buildroot_build_build_dir)/dhrystone-2/dhrystone" \
  2606. --userland-args 'asdf qwer' \
  2607. ;
  2608. ....
  2609. gem5 full system:
  2610. ....
  2611. time \
  2612. ./run \
  2613. --arch arm \
  2614. --eval-after './gem5.sh' \
  2615. --emulator gem5
  2616. --gem5-readfile 'dhrystone 100000' \
  2617. ;
  2618. ....
  2619. QEMU user mode:
  2620. ....
  2621. time qemu-arm "$(./getvar --arch arm buildroot_build_build_dir)/dhrystone-2/dhrystone" 100000000
  2622. ....
  2623. QEMU full system:
  2624. ....
  2625. time \
  2626. ./run \
  2627. --arch arm \
  2628. --eval-after 'time dhrystone 100000000;./linux/poweroff.out' \
  2629. ;
  2630. ....
  2631. Result on <<p51>> at bad30f513c46c1b0995d3a10c0d9bc2a33dc4fa0:
  2632. * gem5 user: 33 seconds
  2633. * gem5 full system: 51 seconds
  2634. * QEMU user: 45 seconds
  2635. * QEMU full system: 223 seconds
  2636. === QEMU user mode quirks
  2637. ==== QEMU user mode does not show stdout immediately
  2638. At 8d8307ac0710164701f6e14c99a69ee172ccbb70 + 1, I noticed that if you run link:userland/posix/count.c[]:
  2639. ....
  2640. ./run --userland userland/posix/count.c --userland-args 3
  2641. ....
  2642. it first waits for 3 seconds, and then dumps all the output at once, instead of counting once every second as expected.
  2643. 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:
  2644. ....
  2645. /path/to/linux-kernel-module-cheat/out/qemu/default/x86_64-linux-user/qemu-x86_64 \
  2646. -L /path/to/linux-kernel-module-cheat/out/buildroot/build/default/x86_64/target \
  2647. /path/to/linux-kernel-module-cheat/out/userland/default/x86_64/posix/count.out \
  2648. 3 \
  2649. | tee
  2650. ....
  2651. TODO: investigate further and then possibly post on QEMU mailing list.
  2652. ===== QEMU user mode does not show errors
  2653. Similarly to <<qemu-user-mode-does-not-show-stdout-immediately>>, QEMU error messages do not show at all through pipes.
  2654. In particular, it does not say anything if you pass it a non-existing executable:
  2655. ....
  2656. qemu-x86_64 asdf | cat
  2657. ....
  2658. So we just check ourselves manually
  2659. == Kernel module utilities
  2660. === insmod
  2661. link:https://git.busybox.net/busybox/tree/modutils/insmod.c?h=1_29_3[Provided by BusyBox]:
  2662. ....
  2663. ./run --eval-after 'insmod hello.ko'
  2664. ....
  2665. === myinsmod
  2666. If you are feeling raw, you can insert and remove modules with our own minimal module inserter and remover!
  2667. ....
  2668. # init_module
  2669. ./linux/myinsmod.out hello.ko
  2670. # finit_module
  2671. ./linux/myinsmod.out hello.ko "" 1
  2672. ./linux/myrmmod.out hello
  2673. ....
  2674. which teaches you how it is done from C code.
  2675. Source:
  2676. * link:userland/linux/myinsmod.c[]
  2677. * link:userland/linux/myrmmod.c[]
  2678. The Linux kernel offers two system calls for module insertion:
  2679. * `init_module`
  2680. * `finit_module`
  2681. and:
  2682. ....
  2683. man init_module
  2684. ....
  2685. documents that:
  2686. ____
  2687. 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().
  2688. ____
  2689. `finit` is newer and was added only in v3.8. More rationale: https://lwn.net/Articles/519010/
  2690. Bibliography: https://stackoverflow.com/questions/5947286/how-to-load-linux-kernel-modules-from-c-code
  2691. === modprobe
  2692. Implemented as a BusyBox applet by default: https://git.busybox.net/busybox/tree/modutils/modprobe.c?h=1_29_stable
  2693. `modprobe` searches for modules installed under:
  2694. ....
  2695. ls /lib/modules/<kernel_version>
  2696. ....
  2697. and specified in the `modules.order` file.
  2698. 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.
  2699. Currently, there are only two kinds of kernel modules that you can try out with `modprobe`:
  2700. * modules built with Buildroot, see: <<kernel_modules-package>>
  2701. * modules built from the kernel tree itself, see: <<dummy-irq>>
  2702. We are not installing out custom `./build-modules` modules there, because:
  2703. * we don't know the right way. Why is there no `install` or `install_modules` target for kernel modules?
  2704. +
  2705. 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
  2706. * 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: <<your-first-kernel-module-hack>>
  2707. === kmod
  2708. The more "reference" kernel.org implementation of `lsmod`, `insmod`, `rmmod`, etc.: https://git.kernel.org/pub/scm/utils/kernel/kmod/kmod.git
  2709. Default implementation on desktop distros such as Ubuntu 16.04, where e.g.:
  2710. ....
  2711. ls -l /bin/lsmod
  2712. ....
  2713. gives:
  2714. ....
  2715. lrwxrwxrwx 1 root root 4 Jul 25 15:35 /bin/lsmod -> kmod
  2716. ....
  2717. and:
  2718. ....
  2719. dpkg -l | grep -Ei
  2720. ....
  2721. contains:
  2722. ....
  2723. ii kmod 22-1ubuntu5 amd64 tools for managing Linux kernel modules
  2724. ....
  2725. 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.
  2726. ==== module-init-tools
  2727. Name of a predecessor set of tools.
  2728. ==== kmod modprobe
  2729. kmod's `modprobe` can also load modules under different names to avoid conflicts, e.g.:
  2730. ....
  2731. sudo modprobe vmhgfs -o vm_hgfs
  2732. ....
  2733. == Filesystems
  2734. === OverlayFS
  2735. link:https://en.wikipedia.org/wiki/OverlayFS[OverlayFS] is a filesystem merged in the Linux kernel in 3.18.
  2736. 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:
  2737. * https://askubuntu.com/questions/109413/how-do-i-use-overlayfs/1075564#1075564
  2738. * https://stackoverflow.com/questions/31044982/how-to-use-multiple-lower-layers-in-overlayfs/52792397#52792397
  2739. 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.
  2740. This would have several advantages:
  2741. * makes it faster to test modified guest programs
  2742. ** not rebooting is fundamental for <<gem5>>, where the reboot is very costly.
  2743. ** no need to regenerate the root filesystem at all and reboot
  2744. ** overcomes the `check_bin_arch` problem: <<rpath>>
  2745. * we could keep the base root filesystem very small, which implies:
  2746. ** less host disk usage, no need to copy the entire `./getvar out_rootfs_overlay_dir` to the image again
  2747. ** no need to worry about <<br2_target_rootfs_ext2_size>>
  2748. We can already make host files appear on the guest with <<9p>>, but they appear on a subdirectory instead of the root.
  2749. 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.
  2750. For example, we wouldn't have to mess around with variables such as `PATH` and `LD_LIBRARY_PATH`.
  2751. The idea is to:
  2752. * 9P mount our overlay directory `./getvar out_rootfs_overlay_dir` on the guest, which we already do at `/mnt/9p/out_rootfs_overlay`
  2753. * then create an overlay with that directory and the root, and `chroot` into it.
  2754. +
  2755. I was unable to mount directly to `/` avoid the `chroot`:
  2756. ** https://stackoverflow.com/questions/41119656/how-can-i-overlayfs-the-root-filesystem-on-linux
  2757. ** https://unix.stackexchange.com/questions/316018/how-to-use-overlayfs-to-protect-the-root-filesystem
  2758. ** https://unix.stackexchange.com/questions/420646/mount-root-as-overlayfs
  2759. We already have a prototype of this running from `fstab` on guest at `/mnt/overlay`, but it has the following shortcomings:
  2760. * changes to underlying filesystems are not visible on the overlay unless you remount with `mount -r remount /mnt/overlay`, as mentioned link:https://github.com/torvalds/linux/blob/v4.18/Documentation/filesystems/overlayfs.txt#L332[on the kernel docs]:
  2761. +
  2762. ....
  2763. Changes to the underlying filesystems while part of a mounted overlay
  2764. filesystem are not allowed. If the underlying filesystem is changed,
  2765. the behavior of the overlay is undefined, though it will not result in
  2766. a crash or deadlock.
  2767. ....
  2768. +
  2769. This makes everything very inconvenient if you are inside `chroot` action. You would have to leave `chroot`, remount, then come back.
  2770. * the overlay does not contain sub-filesystems, e.g. `/proc`. We would have to re-mount them. But should be doable with some automation.
  2771. Even more awesome than `chroot` would be to `pivot_root`, but I couldn't get that working either:
  2772. * https://stackoverflow.com/questions/28015688/pivot-root-device-or-resource-busy
  2773. * https://unix.stackexchange.com/questions/179788/pivot-root-device-or-resource-busy
  2774. === Secondary disk
  2775. A simpler and possibly less overhead alternative to <<9P>> would be to generate a secondary disk image with the benchmark you want to rebuild.
  2776. Then you can `umount` and re-mount on guest without reboot.
  2777. 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[].
  2778. 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
  2779. == Graphics
  2780. Both QEMU and gem5 are capable of outputting graphics to the screen, and taking mouse and keyboard input.
  2781. https://unix.stackexchange.com/questions/307390/what-is-the-difference-between-ttys0-ttyusb0-and-ttyama0-in-linux
  2782. === QEMU text mode
  2783. Text mode is the default mode for QEMU.
  2784. The opposite of text mode is <<qemu-graphic-mode>>
  2785. In text mode, we just show the serial console directly on the current terminal, without opening a QEMU GUI window.
  2786. You cannot see any graphics from text mode, but text operations in this mode, including:
  2787. * scrolling up: <<scroll-up-in-graphic-mode>>
  2788. * copy paste to and from the terminal
  2789. making this a good default, unless you really need to use with graphics.
  2790. Text mode works by sending the terminal character by character to a serial device.
  2791. 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.
  2792. For more details, see:
  2793. * https://unix.stackexchange.com/questions/307390/what-is-the-difference-between-ttys0-ttyusb0-and-ttyama0-in-linux
  2794. * <<tty>>
  2795. Note that you can still see an image even in text mode with the VNC:
  2796. ....
  2797. ./run --vnc
  2798. ....
  2799. and on another terminal:
  2800. ....
  2801. ./vnc
  2802. ....
  2803. but there is not terminal on the VNC window, just the <<config_logo>> penguin.
  2804. ==== Quit QEMU from text mode
  2805. https://superuser.com/questions/1087859/how-to-quit-the-qemu-monitor-when-not-using-a-gui
  2806. 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.
  2807. The simplest way to quit QEMU, is to do:
  2808. ....
  2809. Ctrl-A X
  2810. ....
  2811. Alternative methods include:
  2812. * `quit` command on the <<qemu-monitor>>
  2813. * `pkill qemu`
  2814. === QEMU graphic mode
  2815. Enable graphic mode with:
  2816. ....
  2817. ./run --graphic
  2818. ....
  2819. Outcome: you see a penguin due to <<config_logo>>.
  2820. For a more exciting GUI experience, see: <<x11>>
  2821. Text mode is the default due to the following considerable advantages:
  2822. * copy and paste commands and stdout output to / from host
  2823. * 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
  2824. * have a large scroll buffer, and be able to search it, e.g. by using tmux on host
  2825. * one less window floating around to think about in addition to your shell :-)
  2826. * graphics mode has only been properly tested on `x86_64`.
  2827. Text mode has the following limitations over graphics mode:
  2828. * you can't see graphics such as those produced by <<x11>>
  2829. * 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.
  2830. `x86_64` has a VGA device enabled by default, as can be seen as:
  2831. ....
  2832. ./qemu-monitor info qtree
  2833. ....
  2834. and the Linux kernel picks it up through the link:https://en.wikipedia.org/wiki/Linux_framebuffer[fbdev] graphics system as can be seen from:
  2835. ....
  2836. cat /dev/urandom > /dev/fb0
  2837. ....
  2838. flooding the screen with colors. See also: https://superuser.com/questions/223094/how-do-i-know-if-i-have-kms-enabled
  2839. ==== Scroll up in graphic mode
  2840. Scroll up in <<qemu-graphic-mode>>:
  2841. ....
  2842. Shift-PgUp
  2843. ....
  2844. but I never managed to increase that buffer:
  2845. * https://askubuntu.com/questions/709697/how-to-increase-scrollback-lines-in-ubuntu14-04-2-server-edition
  2846. * https://unix.stackexchange.com/questions/346018/how-to-increase-the-scrollback-buffer-size-for-tty
  2847. The superior alternative is to use text mode and GNU screen or <<tmux>>.
  2848. ==== QEMU Graphic mode arm
  2849. ===== QEMU graphic mode arm terminal
  2850. TODO: on arm, we see the penguin and some boot messages, but don't get a shell at then end:
  2851. ....
  2852. ./run --arch aarch64 --graphic
  2853. ....
  2854. I think it does not work because the graphic window is <<drm>> only, i.e.:
  2855. ....
  2856. cat /dev/urandom > /dev/fb0
  2857. ....
  2858. fails with:
  2859. ....
  2860. cat: write error: No space left on device
  2861. ....
  2862. 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>>.
  2863. There is however one out-of-tree implementation: <<kmscon>>.
  2864. ===== QEMU graphic mode arm terminal implementation
  2865. `arm` and `aarch64` rely on the QEMU CLI option:
  2866. ....
  2867. -device virtio-gpu-pci
  2868. ....
  2869. and the kernel config options:
  2870. ....
  2871. CONFIG_DRM=y
  2872. CONFIG_DRM_VIRTIO_GPU=y
  2873. ....
  2874. Unlike x86, `arm` and `aarch64` don't have a display device attached by default, thus the need for `virtio-gpu-pci`.
  2875. See also https://wiki.qemu.org/Documentation/Platforms/ARM (recently edited and corrected by yours truly... :-)).
  2876. ===== QEMU graphic mode arm VGA
  2877. TODO: how to use VGA on ARM? https://stackoverflow.com/questions/20811203/how-can-i-output-to-vga-through-qemu-arm Tried:
  2878. ....
  2879. -device VGA
  2880. ....
  2881. But https://github.com/qemu/qemu/blob/v2.12.0/docs/config/mach-virt-graphical.cfg#L264 says:
  2882. ....
  2883. # We use virtio-gpu because the legacy VGA framebuffer is
  2884. # very troublesome on aarch64, and virtio-gpu is the only
  2885. # video device that doesn't implement it.
  2886. ....
  2887. so maybe it is not possible?
  2888. === gem5 graphic mode
  2889. 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`.
  2890. TODO could not get it working on `x86_64`, only ARM.
  2891. Overview: https://stackoverflow.com/questions/50364863/how-to-get-graphical-gui-output-and-user-touch-keyboard-mouse-input-in-a-ful/50364864#50364864
  2892. More concretely, first build the kernel with the <<gem5-arm-linux-kernel-patches>>, and then run:
  2893. ....
  2894. ./build-linux \
  2895. --arch arm \
  2896. --custom-config-file-gem5 \
  2897. --linux-build-id gem5-v4.15 \
  2898. ;
  2899. ./run --arch arm --emulator gem5 --linux-build-id gem5-v4.15
  2900. ....
  2901. and then on another shell:
  2902. ....
  2903. vinagre localhost:5900
  2904. ....
  2905. The <<config_logo>> penguin only appears after several seconds, together with kernel messages of type:
  2906. ....
  2907. [ 0.152755] [drm] found ARM HDLCD version r0p0
  2908. [ 0.152790] hdlcd 2b000000.hdlcd: bound virt-encoder (ops 0x80935f94)
  2909. [ 0.152795] [drm] Supports vblank timestamp caching Rev 2 (21.10.2013).
  2910. [ 0.152799] [drm] No driver support for vblank timestamp query.
  2911. [ 0.215179] Console: switching to colour frame buffer device 240x67
  2912. [ 0.230389] hdlcd 2b000000.hdlcd: fb0: frame buffer device
  2913. [ 0.230509] [drm] Initialized hdlcd 1.0.0 20151021 for 2b000000.hdlcd on minor 0
  2914. ....
  2915. 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:
  2916. ....
  2917. system.vncserver: Listening for connections on port 5900
  2918. ....
  2919. and when we connect it shows a message:
  2920. ....
  2921. info: VNC client attached
  2922. ....
  2923. Alternatively, you can also dump each new frame to an image file with `--frame-capture`:
  2924. ....
  2925. ./run \
  2926. --arch arm \
  2927. --emulator gem5 \
  2928. --linux-build-id gem5-v4.15 \
  2929. -- --frame-capture \
  2930. ;
  2931. ....
  2932. This creates on compressed PNG whenever the screen image changes inside the <<m5out-directory>> with filename of type:
  2933. ....
  2934. frames_system.vncserver/fb.<frame-index>.<timestamp>.png.gz
  2935. ....
  2936. It is fun to see how we get one new frame whenever the white underscore cursor appears and reappears under the penguin!
  2937. The last frame is always available uncompressed at: `system.framebuffer.png`.
  2938. TODO <<kmscube>> failed on `aarch64` with:
  2939. ....
  2940. kmscube[706]: unhandled level 2 translation fault (11) at 0x00000000, esr 0x92000006, in libgbm.so.1.0.0[7fbf6a6000+e000]
  2941. ....
  2942. Tested on: link:http://github.com/cirosantilli/linux-kernel-module-cheat/commit/38fd6153d965ba20145f53dc1bb3ba34b336bde9[38fd6153d965ba20145f53dc1bb3ba34b336bde9]
  2943. ==== Graphic mode gem5 aarch64
  2944. For `aarch64` we also need to configure the kernel with link:linux_config/display[]:
  2945. ....
  2946. git -C "$(./getvar linux_source_dir)" fetch https://gem5.googlesource.com/arm/linux gem5/v4.15:gem5/v4.15
  2947. git -C "$(./getvar linux_source_dir)" checkout gem5/v4.15
  2948. ./build-linux \
  2949. --arch aarch64 \
  2950. --config-fragment linux_config/display \
  2951. --custom-config-file-gem5 \
  2952. --linux-build-id gem5-v4.15 \
  2953. ;
  2954. git -C "$(./getvar linux_source_dir)" checkout -
  2955. ./run --arch aarch64 --emulator gem5 --linux-build-id gem5-v4.15
  2956. ....
  2957. This is because the gem5 `aarch64` defconfig does not enable HDLCD like the 32 bit one `arm` one for some reason.
  2958. ==== gem5 graphic mode DP650
  2959. TODO get working. There is an unmerged patchset at: https://gem5-review.googlesource.com/c/public/gem5/+/11036/1
  2960. The DP650 is a newer display hardware than HDLCD. TODO is its interface publicly documented anywhere? Since it has a gem5 model and link:https://github.com/torvalds/linux/blob/v4.19/drivers/gpu/drm/arm/Kconfig#L39[in-tree Linux kernel support], that information cannot be secret?
  2961. The key option to enable support in Linux is `DRM_MALI_DISPLAY=y` which we enable at link:linux_config/display[].
  2962. Build the kernel exactly as for <<graphic-mode-gem5-aarch64>> and then run with:
  2963. ....
  2964. ./run --arch aarch64 --dp650 --emulator gem5 --linux-build-id gem5-v4.15
  2965. ....
  2966. ==== Graphic mode gem5 internals
  2967. We cannot use mainline Linux because the <<gem5-arm-linux-kernel-patches>> are required at least to provide the `CONFIG_DRM_VIRT_ENCODER` option.
  2968. gem5 emulates the link:http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0541c/CHDBAIDI.html[HDLCD] ARM Holdings hardware for `arm` and `aarch64`.
  2969. The kernel uses HDLCD to implement the <<drm>> interface, the required kernel config options are present at: link:linux_config/display[].
  2970. TODO: minimize out the `--custom-config-file`. If we just remove it on `arm`: it does not work with a failing dmesg:
  2971. ....
  2972. [ 0.066208] [drm] found ARM HDLCD version r0p0
  2973. [ 0.066241] hdlcd 2b000000.hdlcd: bound virt-encoder (ops drm_vencoder_ops)
  2974. [ 0.066247] [drm] Supports vblank timestamp caching Rev 2 (21.10.2013).
  2975. [ 0.066252] [drm] No driver support for vblank timestamp query.
  2976. [ 0.066276] hdlcd 2b000000.hdlcd: Cannot do DMA to address 0x0000000000000000
  2977. [ 0.066281] swiotlb: coherent allocation failed for device 2b000000.hdlcd size=8294400
  2978. [ 0.066288] CPU: 0 PID: 1 Comm: swapper/0 Not tainted 4.15.0 #1
  2979. [ 0.066293] Hardware name: V2P-AARCH64 (DT)
  2980. [ 0.066296] Call trace:
  2981. [ 0.066301] dump_backtrace+0x0/0x1b0
  2982. [ 0.066306] show_stack+0x24/0x30
  2983. [ 0.066311] dump_stack+0xb8/0xf0
  2984. [ 0.066316] swiotlb_alloc_coherent+0x17c/0x190
  2985. [ 0.066321] __dma_alloc+0x68/0x160
  2986. [ 0.066325] drm_gem_cma_create+0x98/0x120
  2987. [ 0.066330] drm_fbdev_cma_create+0x74/0x2e0
  2988. [ 0.066335] __drm_fb_helper_initial_config_and_unlock+0x1d8/0x3a0
  2989. [ 0.066341] drm_fb_helper_initial_config+0x4c/0x58
  2990. [ 0.066347] drm_fbdev_cma_init_with_funcs+0x98/0x148
  2991. [ 0.066352] drm_fbdev_cma_init+0x40/0x50
  2992. [ 0.066357] hdlcd_drm_bind+0x220/0x428
  2993. [ 0.066362] try_to_bring_up_master+0x21c/0x2b8
  2994. [ 0.066367] component_master_add_with_match+0xa8/0xf0
  2995. [ 0.066372] hdlcd_probe+0x60/0x78
  2996. [ 0.066377] platform_drv_probe+0x60/0xc8
  2997. [ 0.066382] driver_probe_device+0x30c/0x478
  2998. [ 0.066388] __driver_attach+0x10c/0x128
  2999. [ 0.066393] bus_for_each_dev+0x70/0xb0
  3000. [ 0.066398] driver_attach+0x30/0x40
  3001. [ 0.066402] bus_add_driver+0x1d0/0x298
  3002. [ 0.066408] driver_register+0x68/0x100
  3003. [ 0.066413] __platform_driver_register+0x54/0x60
  3004. [ 0.066418] hdlcd_platform_driver_init+0x20/0x28
  3005. [ 0.066424] do_one_initcall+0x44/0x130
  3006. [ 0.066428] kernel_init_freeable+0x13c/0x1d8
  3007. [ 0.066433] kernel_init+0x18/0x108
  3008. [ 0.066438] ret_from_fork+0x10/0x1c
  3009. [ 0.066444] hdlcd 2b000000.hdlcd: Failed to set initial hw configuration.
  3010. [ 0.066470] hdlcd 2b000000.hdlcd: master bind failed: -12
  3011. [ 0.066477] hdlcd: probe of 2b000000.hdlcd failed with error -12
  3012. [
  3013. ....
  3014. So what other options are missing from `gem5_defconfig`? It would be cool to minimize it out to better understand the options.
  3015. [[x11]]
  3016. === X11 Buildroot
  3017. Once you've seen the `CONFIG_LOGO` penguin as a sanity check, you can try to go for a cooler X11 Buildroot setup.
  3018. Build and run:
  3019. ....
  3020. ./build-buildroot --config-fragment buildroot_config/x11
  3021. ./run --graphic
  3022. ....
  3023. Inside QEMU:
  3024. ....
  3025. startx
  3026. ....
  3027. And then from the GUI you can start exciting graphical programs such as:
  3028. ....
  3029. xcalc
  3030. xeyes
  3031. ....
  3032. Outcome:
  3033. image:x11.png[image]
  3034. 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.
  3035. More details: https://unix.stackexchange.com/questions/70931/how-to-install-x11-on-my-own-linux-buildroot-system/306116#306116
  3036. 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.
  3037. To x11 packages have an `xserver` prefix as in:
  3038. ....
  3039. ./build-buildroot --config-fragment buildroot_config/x11 -- xserver_xorg-server-reconfigure
  3040. ....
  3041. the easiest way to find them out is to just list `"$(./getvar buildroot_build_build_dir)/x*`.
  3042. TODO as of: c2696c978d6ca88e8b8599c92b1beeda80eb62b2 I noticed that `startx` leads to a <<bug_on>>:
  3043. ....
  3044. [ 2.809104] WARNING: CPU: 0 PID: 51 at drivers/gpu/drm/ttm/ttm_bo_vm.c:304 ttm_bo_vm_open+0x37/0x40
  3045. ....
  3046. ==== X11 Buildroot mouse not moving
  3047. 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.
  3048. * https://askubuntu.com/questions/730891/how-can-i-get-a-mouse-cursor-in-qemu
  3049. * https://stackoverflow.com/questions/19665412/mouse-and-keyboard-not-working-in-qemu-emulator
  3050. `-show-cursor` did not help, I just get to see the host cursor, but the guest cursor still does not move.
  3051. Doing:
  3052. ....
  3053. watch -n 1 grep i8042 /proc/interrupts
  3054. ....
  3055. shows that interrupts do happen when mouse and keyboard presses are done, so I expect that it is some wrong either with:
  3056. * QEMU. Same behaviour if I try the host's QEMU 2.10.1 however.
  3057. * X11 configuration. We do have `BR2_PACKAGE_XDRIVER_XF86_INPUT_MOUSE=y`.
  3058. `/var/log/Xorg.0.log` contains the following interesting lines:
  3059. ....
  3060. [ 27.549] (II) LoadModule: "mouse"
  3061. [ 27.549] (II) Loading /usr/lib/xorg/modules/input/mouse_drv.so
  3062. [ 27.590] (EE) <default pointer>: Cannot find which device to use.
  3063. [ 27.590] (EE) <default pointer>: cannot open input device
  3064. [ 27.590] (EE) PreInit returned 2 for "<default pointer>"
  3065. [ 27.590] (II) UnloadModule: "mouse"
  3066. ....
  3067. The file `/dev/inputs/mice` does not exist.
  3068. Note that our current link:kernel_confi_fragment sets:
  3069. ....
  3070. # CONFIG_INPUT_MOUSE is not set
  3071. # CONFIG_INPUT_MOUSEDEV_PSAUX is not set
  3072. ....
  3073. for gem5, so you might want to remove those lines to debug this.
  3074. ==== X11 Buildroot ARM
  3075. On ARM, `startx` hangs at a message:
  3076. ....
  3077. vgaarb: this pci device is not a vga device
  3078. ....
  3079. and nothing shows on the screen, and:
  3080. ....
  3081. grep EE /var/log/Xorg.0.log
  3082. ....
  3083. says:
  3084. ....
  3085. (EE) Failed to load module "modesetting" (module does not exist, 0)
  3086. ....
  3087. A friend told me this but I haven't tried it yet:
  3088. * `xf86-video-modesetting` is likely the missing ingredient, but it does not seem possible to activate it from Buildroot currently without patching things.
  3089. * `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`
  3090. == Networking
  3091. === Enable networking
  3092. 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: <<resource-tradeoff-guidelines>>
  3093. To enable networking on Buildroot, simply run:
  3094. ....
  3095. ifup -a
  3096. ....
  3097. That command goes over all (`-a`) the interfaces in `/etc/network/interfaces` and brings them up.
  3098. Then test it with:
  3099. ....
  3100. wget google.com
  3101. cat index.html
  3102. ....
  3103. Disable networking with:
  3104. ....
  3105. ifdown -a
  3106. ....
  3107. To enable networking by default after boot, use the methods documented at <<init-busybox>>.
  3108. === ping
  3109. `ping` does not work within QEMU by default, e.g.:
  3110. ....
  3111. ping google.com
  3112. ....
  3113. hangs after printing the header:
  3114. ....
  3115. PING google.com (216.58.204.46): 56 data bytes
  3116. ....
  3117. https://unix.stackexchange.com/questions/473448/how-to-ping-from-the-qemu-guest-to-an-external-url
  3118. === Guest host networking
  3119. In this section we discuss how to interact between the guest and the host through networking.
  3120. First ensure that you can access the external network since that is easier to get working: <<networking>>.
  3121. ==== Host to guest networking
  3122. ===== nc host to guest
  3123. With `nc` we can create the most minimal example possible as a sanity check.
  3124. On guest run:
  3125. ....
  3126. nc -l -p 45455
  3127. ....
  3128. Then on host run:
  3129. ....
  3130. echo asdf | nc localhost 45455
  3131. ....
  3132. `asdf` appears on the guest.
  3133. This uses:
  3134. * BusyBox' `nc` utility, which is enabled with `CONFIG_NC=y`
  3135. * `nc` from the `netcat-openbsd` package on an Ubuntu 18.04 host
  3136. Only this specific port works by default since we have forwarded it on the QEMU command line.
  3137. We us this exact procedure to connect to <<gdbserver>>.
  3138. ===== ssh into guest
  3139. Not enabled by default due to the build / runtime overhead. To enable, build with:
  3140. ....
  3141. ./build-buildroot --config 'BR2_PACKAGE_OPENSSH=y'
  3142. ....
  3143. Then inside the guest turn on sshd:
  3144. ....
  3145. ./sshd.sh
  3146. ....
  3147. Source: link:rootfs_overlay/lkmc/sshd.sh[]
  3148. And finally on host:
  3149. ....
  3150. ssh root@localhost -p 45456
  3151. ....
  3152. Bibliography: https://unix.stackexchange.com/questions/124681/how-to-ssh-from-host-to-guest-using-qemu/307557#307557
  3153. ===== gem5 host to guest networking
  3154. 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
  3155. ==== Guest to host networking
  3156. First <<enable-networking>>.
  3157. Then in the host, start a server:
  3158. ....
  3159. python -m SimpleHTTPServer 8000
  3160. ....
  3161. And then in the guest, find the IP we need to hit with:
  3162. ....
  3163. ip rounte
  3164. ....
  3165. which gives:
  3166. .....
  3167. default via 10.0.2.2 dev eth0
  3168. 10.0.2.0/24 dev eth0 scope link src 10.0.2.15
  3169. .....
  3170. so we use in the guest:
  3171. ....
  3172. wget 10.0.2.2:8000
  3173. ....
  3174. Bibliography: https://serverfault.com/questions/769874/how-to-forward-a-port-from-guest-to-host-in-qemu-kvm/951835#951835
  3175. === 9P
  3176. The link:https://en.wikipedia.org/wiki/9P_(protocol)[9p protocol] allows the guest to mount a host directory.
  3177. Both QEMU and <<9p-gem5>> support 9P.
  3178. ==== 9P vs NFS
  3179. All of 9P and NFS (and sshfs) allow sharing directories between guest and host.
  3180. Advantages of 9P
  3181. * requires `sudo` on the host to mount
  3182. * 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>>
  3183. +
  3184. 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.
  3185. * 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.
  3186. +
  3187. This is not the case for gem5 7bfb7f3a43f382eb49853f47b140bfd6caad0fb8 unfortunately, which relies on the link:https://github.com/chaos/diod[diod] host daemon, although it is not unfeasible that future versions could implement it natively as well.
  3188. Advantages of NFS:
  3189. * way more widely used and therefore stable and available, not to mention that it also works on real hardware.
  3190. * 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!
  3191. ==== 9P getting started
  3192. As usual, we have already set everything up for you. On host:
  3193. ....
  3194. cd "$(./getvar p9_dir)"
  3195. uname -a > host
  3196. ....
  3197. Guest:
  3198. ....
  3199. cd /mnt/9p/data
  3200. cat host
  3201. uname -a > guest
  3202. ....
  3203. Host:
  3204. ....
  3205. cat guest
  3206. ....
  3207. The main ingredients for this are:
  3208. * `9P` settings in our <<kernel-configs-about,kernel configs>>
  3209. * `9p` entry on our link:rootfs_overlay/etc/fstab[]
  3210. +
  3211. Alternatively, you could also mount your own with:
  3212. +
  3213. ....
  3214. mkdir /mnt/my9p
  3215. mount -t 9p -o trans=virtio,version=9p2000.L host0 /mnt/my9p
  3216. ....
  3217. * Launch QEMU with `-virtfs` as in your link:run[] script
  3218. +
  3219. When we tried:
  3220. +
  3221. ....
  3222. security_model=mapped
  3223. ....
  3224. +
  3225. writes from guest failed due to user mismatch problems: https://serverfault.com/questions/342801/read-write-access-for-passthrough-9p-filesystems-with-libvirt-qemu
  3226. Bibliography:
  3227. * https://superuser.com/questions/628169/how-to-share-a-directory-with-the-host-without-networking-in-qemu
  3228. * https://wiki.qemu.org/Documentation/9psetup
  3229. ==== 9P gem5
  3230. TODO seems possible! Lets do it:
  3231. * http://gem5.org/wiki/images/b/b8/Summit2017_wa_devlib.pdf
  3232. * http://gem5.org/WA-gem5
  3233. ==== NFS
  3234. TODO: get working.
  3235. <<9p>> is better with emulation, but let's just get this working for fun.
  3236. First make sure that this works: <<guest-to-host-networking>>.
  3237. Then, build the kernel with NFS support:
  3238. ....
  3239. ./build-linux --config-fragment linux_config/nfs
  3240. ....
  3241. Now on host:
  3242. ....
  3243. sudo apt-get install nfs-kernel-server
  3244. ....
  3245. Now edit `/etc/exports` to contain:
  3246. ....
  3247. /tmp *(rw,sync,no_root_squash,no_subtree_check)
  3248. ....
  3249. and restart the server:
  3250. ....
  3251. sudo systemctl restart nfs-kernel-server
  3252. ....
  3253. Now on guest:
  3254. ....
  3255. mkdir /mnt/nfs
  3256. mount -t nfs 10.0.2.2:/tmp /mnt/nfs
  3257. ....
  3258. TODO: failing with:
  3259. ....
  3260. mount: mounting 10.0.2.2:/tmp on /mnt/nfs failed: No such device
  3261. ....
  3262. And now the `/tmp` directory from host is not mounted on guest!
  3263. If you don't want to start the NFS server after the next boot automatically so save resources, link:https://askubuntu.com/questions/19320/how-to-enable-or-disable-services[do]:
  3264. ....
  3265. systemctl disable nfs-kernel-server
  3266. ....
  3267. == Linux kernel
  3268. === Linux kernel configuration
  3269. ==== Modify kernel config
  3270. To modify a single option on top of our <<kernel-configs-about,default kernel configs>>, do:
  3271. ....
  3272. ./build-linux --config 'CONFIG_FORTIFY_SOURCE=y'
  3273. ....
  3274. 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:
  3275. ....
  3276. ./build-modules --clean
  3277. ./build-modules
  3278. ....
  3279. and then proceed as in <<your-first-kernel-module-hack>>.
  3280. You might often get way without rebuilding the kernel modules however.
  3281. To use an extra kernel config fragment file on top of our defaults, do:
  3282. ....
  3283. printf '
  3284. CONFIG_IKCONFIG=y
  3285. CONFIG_IKCONFIG_PROC=y
  3286. ' > data/myconfig
  3287. ./build-linux --config-fragment 'data/myconfig'
  3288. ....
  3289. To use just your own exact `.config` instead of our defaults ones, use:
  3290. ....
  3291. ./build-linux --custom-config-file data/myconfig
  3292. ....
  3293. There is also a shortcut `--custom-config-file` to use the <<gem5-arm-linux-kernel-patches>>.
  3294. The following options can all be used together, sorted by decreasing config setting power precedence:
  3295. * `--config`
  3296. * `--config-fragment`
  3297. * `--custom-config-file`
  3298. To do a clean menu config yourself and use that for the build, do:
  3299. ....
  3300. ./build-linux --clean
  3301. ./build-linux --custom-config-target menuconfig
  3302. ....
  3303. 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:
  3304. ....
  3305. ./build-linux --no-configure
  3306. ....
  3307. So what you likely want to do instead is to save that as a new `defconfig` and use it later as:
  3308. ....
  3309. ./build-linux --no-configure --no-modules-install savedefconfig
  3310. cp "$(./getvar linux_build_dir)/defconfig" data/myconfig
  3311. ./build-linux --custom-config-file data/myconfig
  3312. ....
  3313. You can also use other config generating targets such as `defconfig` with the same method as shown at: <<linux-kernel-defconfig>>.
  3314. ==== Find the kernel config
  3315. Get the build config in guest:
  3316. ....
  3317. zcat /proc/config.gz
  3318. ....
  3319. or with our shortcut:
  3320. ....
  3321. ./conf.sh
  3322. ....
  3323. or to conveniently grep for a specific option case insensitively:
  3324. ....
  3325. ./conf.sh ikconfig
  3326. ....
  3327. Source: link:rootfs_overlay/lkmc/conf.sh[].
  3328. This is enabled by:
  3329. ....
  3330. CONFIG_IKCONFIG=y
  3331. CONFIG_IKCONFIG_PROC=y
  3332. ....
  3333. From host:
  3334. ....
  3335. cat "$(./getvar linux_config)"
  3336. ....
  3337. Just for fun link:https://stackoverflow.com/questions/14958192/how-to-get-the-config-from-a-linux-kernel-image/14958263#14958263[]:
  3338. ....
  3339. ./linux/scripts/extract-ikconfig "$(./getvar vmlinux)"
  3340. ....
  3341. although this can be useful when someone gives you a random image.
  3342. [[kernel-configs-about]]
  3343. ==== About our Linux kernel configs
  3344. By default, link:build-linux[] generates a `.config` that is a mixture of:
  3345. * a base config extracted from Buildroot's minimal per machine `.config`, which has the minimal options needed to boot: <<buildroot-kernel-config>>.
  3346. * small overlays put top of that
  3347. To find out which kernel configs are being used exactly, simply run:
  3348. ....
  3349. ./build-linux --dry-run
  3350. ....
  3351. 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
  3352. For each arch, the base of our configs are named as:
  3353. ....
  3354. linux_config/buildroot-<arch>
  3355. ....
  3356. e.g.: link:linux_config/buildroot-x86_64[].
  3357. These configs are extracted directly from a Buildroot build with link:update-buildroot-kernel-config[].
  3358. 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
  3359. On top of those, we add the following by default:
  3360. * link:linux_config/min[]: see: <<linux-kernel-min-config>>
  3361. * 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
  3362. +
  3363. We have since observed that the kernel size itself is very bloated compared to `defconfig`: <<linux-kernel-defconfig>>.
  3364. [[buildroot-kernel-config]]
  3365. ===== About Buildroot's kernel configs
  3366. To see Buildroot's base configs, start from link:https://github.com/buildroot/buildroot/blob/2018.05/configs/qemu_x86_64_defconfig[`buildroot/configs/qemu_x86_64_defconfig`].
  3367. 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: link:https://github.com/buildroot/buildroot/blob/2018.05/board/qemu/x86_64/linux-4.15.config[board/qemu/x86_64/linux-4.15.config].
  3368. `arm`, on the other hand, uses link: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.
  3369. ====== Linux kernel defconfig
  3370. To boot link: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:
  3371. ....
  3372. ./build-linux \
  3373. --linux-build-id defconfig \
  3374. --custom-config-target defconfig \
  3375. --config CONFIG_VIRTIO_PCI=y \
  3376. --config CONFIG_VIRTIO_BLK=y \
  3377. ;
  3378. ./run --linux-build-id defconfig
  3379. ....
  3380. Oh, and check this out:
  3381. ....
  3382. du -h \
  3383. "$(./getvar vmlinux)" \
  3384. "$(./getvar --linux-build-id defconfig vmlinux)" \
  3385. ;
  3386. ....
  3387. Output:
  3388. ....
  3389. 360M /path/to/linux-kernel-module-cheat/out/linux/default/x86_64/vmlinux
  3390. 47M /path/to/linux-kernel-module-cheat/out/linux/defconfig/x86_64/vmlinux
  3391. ....
  3392. Brutal. Where did we go wrong?
  3393. The extra virtio options are not needed if we use <<initrd>>:
  3394. ....
  3395. ./build-linux \
  3396. --linux-build-id defconfig \
  3397. --custom-config-target defconfig \
  3398. ;
  3399. ./run --initrd --linux-build-id defconfig
  3400. ....
  3401. On aarch64, we can boot from initrd with:
  3402. ....
  3403. ./build-linux \
  3404. --arch aarch64 \
  3405. --linux-build-id defconfig \
  3406. --custom-config-target defconfig \
  3407. ;
  3408. ./run \
  3409. --arch aarch64 \
  3410. --initrd \
  3411. --linux-build-id defconfig \
  3412. --memory 2G \
  3413. ;
  3414. ....
  3415. We need the 2G of memory because the CPIO is 600MiB due to a humongous amount of loadable kernel modules!
  3416. In aarch64, the size situation is inverted from x86_64, and this can be seen on the vmlinux size as well:
  3417. ....
  3418. 118M /path/to/linux-kernel-module-cheat/out/linux/default/aarch64/vmlinux
  3419. 240M /path/to/linux-kernel-module-cheat/out/linux/defconfig/aarch64/vmlinux
  3420. ....
  3421. 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!
  3422. Bibliography: https://unix.stackexchange.com/questions/29439/compiling-the-kernel-with-default-configurations/204512#204512
  3423. Tested on 1e2b7f1e5e9e3073863dc17e25b2455c8ebdeadd + 1.
  3424. ====== Linux kernel min config
  3425. 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.
  3426. It is one of the default config fragments we use, as explained at: <<kernel-configs-about>>>.
  3427. 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.
  3428. We can build just with `min` on top of the base config with:
  3429. ....
  3430. ./build-linux \
  3431. --arch aarch64 \
  3432. --config-fragment linux_config/min \
  3433. --custom-config-file linux_config/buildroot-aarch64 \
  3434. --linux-build-id min \
  3435. ;
  3436. ....
  3437. 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?
  3438. Tested on 649d06d6758cefd080d04dc47fd6a5a26a620874 + 1.
  3439. ===== Notable alternate gem5 kernel configs
  3440. Other configs which we had previously tested at 4e0d9af81fcce2ce4e777cb82a1990d7c2ca7c1e are:
  3441. * `arm` and `aarch64` configs present in the official ARM gem5 Linux kernel fork: <<gem5-arm-linux-kernel-patches>>. Some of the configs present there are added by the patches.
  3442. * Jason's magic `x86_64` config: http://web.archive.org/web/20171229121642/http://www.lowepower.com/jason/files/config which is referenced at: link: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`.
  3443. === Kernel version
  3444. ==== Find the kernel version
  3445. We try to use the latest possible kernel major release version.
  3446. In QEMU:
  3447. ....
  3448. cat /proc/version
  3449. ....
  3450. or in the source:
  3451. ....
  3452. cd "$(./getvar linux_source_dir)"
  3453. git log | grep -E ' Linux [0-9]+\.' | head
  3454. ....
  3455. ==== Update the Linux kernel
  3456. During update all you kernel modules may break since the kernel API is not stable.
  3457. They are usually trivial breaks of things moving around headers or to sub-structs.
  3458. The userland, however, should simply not break, as Linus enforces strict backwards compatibility of userland interfaces.
  3459. This backwards compatibility is just awesome, it makes getting and running the latest master painless.
  3460. This also makes this repo the perfect setup to develop the Linux kernel.
  3461. In case something breaks while updating the Linux kernel, you can try to bisect it to understand the root cause: <<bisection>>.
  3462. ==== Downgrade the Linux kernel
  3463. 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.
  3464. The default Linux kernel version is bumped in Buildroot with commit messages of type:
  3465. ....
  3466. linux: bump default to version 4.9.6
  3467. ....
  3468. So you can try:
  3469. ....
  3470. git log --grep 'linux: bump default to version'
  3471. ....
  3472. Those commits change `BR2_LINUX_KERNEL_LATEST_VERSION` in `/linux/Config.in`.
  3473. 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.
  3474. 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.
  3475. We don't expect those changes to be very difficult. A good way to approach the task is to:
  3476. * do a dry run build to get the equivalent Bash commands used:
  3477. +
  3478. ....
  3479. ./build-buildroot --dry-run
  3480. ....
  3481. * build the Buildroot documentation for the version you are going to use, and check if all Buildroot build commands make sense there
  3482. 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.
  3483. 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:
  3484. * `git log master -- packages/<pkg>`
  3485. * Google the error message for mailing list hits
  3486. Successful port reports:
  3487. * v3.18: https://github.com/cirosantilli/linux-kernel-module-cheat/issues/39#issuecomment-438525481
  3488. === Kernel command line parameters
  3489. 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.
  3490. This allows us to control the behaviour of the kernel without rebuilding anything.
  3491. With QEMU, QEMU itself acts as the bootloader, and provides the `-append` option and we expose it through `./run --kernel-cli`, e.g.:
  3492. ....
  3493. ./run --kernel-cli 'foo bar'
  3494. ....
  3495. Then inside the host, you can check which options were given with:
  3496. ....
  3497. cat /proc/cmdline
  3498. ....
  3499. They are also printed at the beginning of the boot message:
  3500. ....
  3501. dmesg | grep "Command line"
  3502. ....
  3503. See also:
  3504. * https://unix.stackexchange.com/questions/48601/how-to-display-the-linux-kernel-command-line-parameters-given-for-the-current-bo
  3505. * https://askubuntu.com/questions/32654/how-do-i-find-the-boot-parameters-used-by-the-running-kernel
  3506. The arguments are documented in the kernel documentation: https://www.kernel.org/doc/html/v4.14/admin-guide/kernel-parameters.html
  3507. When dealing with real boards, extra command line options are provided on some magic bootloader configuration file, e.g.:
  3508. * GRUB configuration files: https://askubuntu.com/questions/19486/how-do-i-add-a-kernel-boot-parameter
  3509. * 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
  3510. ==== Kernel command line parameters escaping
  3511. 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"`
  3512. This even lead us to use base64 encoding with `--eval`!
  3513. ==== Kernel command line parameters definition points
  3514. There are two methods:
  3515. * `__setup` as in:
  3516. +
  3517. ....
  3518. __setup("console=", console_setup);
  3519. ....
  3520. * `core_param` as in:
  3521. +
  3522. ....
  3523. core_param(panic, panic_timeout, int, 0644);
  3524. ....
  3525. `core_param` suggests how they are different:
  3526. ....
  3527. /**
  3528. * core_param - define a historical core kernel parameter.
  3529. ...
  3530. * core_param is just like module_param(), but cannot be modular and
  3531. * doesn't add a prefix (such as "printk."). This is for compatibility
  3532. * with __setup(), and it makes sense as truly core parameters aren't
  3533. * tied to the particular file they're in.
  3534. */
  3535. ....
  3536. ==== rw
  3537. By default, the Linux kernel mounts the root filesystem as readonly. TODO rationale?
  3538. This cannot be observed in the default BusyBox init, because by default our link:rootfs_overlay/etc/inittab[] does:
  3539. ....
  3540. /bin/mount -o remount,rw /
  3541. ....
  3542. Analogously, Ubuntu 18.04 does in its fstab something like:
  3543. ....
  3544. UUID=/dev/sda1 / ext4 errors=remount-ro 0 1
  3545. ....
  3546. which uses default mount `rw` flags.
  3547. 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.
  3548. To observe the default readonly behaviour, hack the link:run[] script to remove <<replace-init,replace init>>, and then run on a raw shell:
  3549. ....
  3550. ./run --kernel-cli 'init=/bin/sh'
  3551. ....
  3552. Now try to do:
  3553. ....
  3554. touch a
  3555. ....
  3556. which fails with:
  3557. ....
  3558. touch: a: Read-only file system
  3559. ....
  3560. We can also observe the read-onlyness with:
  3561. ....
  3562. mount -t proc /proc
  3563. mount
  3564. ....
  3565. which contains:
  3566. ....
  3567. /dev/root on / type ext2 (ro,relatime,block_validity,barrier,user_xattr)
  3568. ....
  3569. and so it is Read Only as shown by `ro`.
  3570. ==== norandmaps
  3571. Disable userland address space randomization. Test it out by running <<rand_check-out>> twice:
  3572. ....
  3573. ./run --eval-after './linux/rand_check.out;./linux/poweroff.out'
  3574. ./run --eval-after './linux/rand_check.out;./linux/poweroff.out'
  3575. ....
  3576. If we remove it from our link:run[] script by hacking it up, the addresses shown by `linux/rand_check.out` vary across boots.
  3577. Equivalent to:
  3578. ....
  3579. echo 0 > /proc/sys/kernel/randomize_va_space
  3580. ....
  3581. === printk
  3582. `printk` is the most simple and widely used way of getting information from the kernel, so you should familiarize yourself with its basic configuration.
  3583. We use `printk` a lot in our kernel modules, and it shows on the terminal by default, along with stdout and what you type.
  3584. Hide all `printk` messages:
  3585. ....
  3586. dmesg -n 1
  3587. ....
  3588. or equivalently:
  3589. ....
  3590. echo 1 > /proc/sys/kernel/printk
  3591. ....
  3592. See also: https://superuser.com/questions/351387/how-to-stop-kernel-messages-from-flooding-my-console
  3593. Do it with a <<kernel-command-line-parameters>> to affect the boot itself:
  3594. ....
  3595. ./run --kernel-cli 'loglevel=5'
  3596. ....
  3597. and now only boot warning messages or worse show, which is useful to identify problems.
  3598. Our default `printk` format is:
  3599. ....
  3600. <LEVEL>[TIMESTAMP] MESSAGE
  3601. ....
  3602. e.g.:
  3603. ....
  3604. <6>[ 2.979121] Freeing unused kernel memory: 2024K
  3605. ....
  3606. where:
  3607. * `LEVEL`: higher means less serious
  3608. * `TIMESTAMP`: seconds since boot
  3609. This format is selected by the following boot options:
  3610. * `console_msg_format=syslog`: add the `<LEVEL>` part. Added in v4.16.
  3611. * `printk.time=y`: add the `[TIMESTAMP]` part
  3612. The debug highest level is a bit more magic, see: <<pr_debug>> for more info.
  3613. ==== ignore_loglevel
  3614. ....
  3615. ./run --kernel-cli 'ignore_loglevel'
  3616. ....
  3617. enables all log levels, and is basically the same as:
  3618. ....
  3619. ./run --kernel-cli 'loglevel=8'
  3620. ....
  3621. except that you don't need to know what is the maximum level.
  3622. ==== pr_debug
  3623. https://stackoverflow.com/questions/28936199/why-is-pr-debug-of-the-linux-kernel-not-giving-any-output/49835405#49835405
  3624. Debug messages are not printable by default without recompiling.
  3625. But the awesome `CONFIG_DYNAMIC_DEBUG=y` option which we enable by default allows us to do:
  3626. ....
  3627. echo 8 > /proc/sys/kernel/printk
  3628. echo 'file kernel/module.c +p' > /sys/kernel/debug/dynamic_debug/control
  3629. ./linux/myinsmod.out hello.ko
  3630. ....
  3631. and we have a shortcut at:
  3632. ....
  3633. ./pr_debug.sh
  3634. ....
  3635. Source: link:rootfs_overlay/lkmc/pr_debug.sh[].
  3636. Syntax: https://www.kernel.org/doc/html/v4.11/admin-guide/dynamic-debug-howto.html
  3637. Wildcards are also accepted, e.g. enable all messages from all files:
  3638. ....
  3639. echo 'file * +p' > /sys/kernel/debug/dynamic_debug/control
  3640. ....
  3641. TODO: why is this not working:
  3642. ....
  3643. echo 'func sys_init_module +p' > /sys/kernel/debug/dynamic_debug/control
  3644. ....
  3645. Enable messages in specific modules:
  3646. ....
  3647. echo 8 > /proc/sys/kernel/printk
  3648. echo 'module myprintk +p' > /sys/kernel/debug/dynamic_debug/control
  3649. insmod myprintk.ko
  3650. ....
  3651. Source: link:kernel_modules/myprintk.c[]
  3652. This outputs the `pr_debug` message:
  3653. ....
  3654. printk debug
  3655. ....
  3656. but TODO: it also shows debug messages even without enabling them explicitly:
  3657. ....
  3658. echo 8 > /proc/sys/kernel/printk
  3659. insmod myprintk.ko
  3660. ....
  3661. and it shows as enabled:
  3662. ....
  3663. # grep myprintk /sys/kernel/debug/dynamic_debug/control
  3664. /root/linux-kernel-module-cheat/out/kernel_modules/x86_64/kernel_modules/panic.c:12 [myprintk]myinit =p "pr_debug\012"
  3665. ....
  3666. Enable `pr_debug` for boot messages as well, before we can reach userland and write to `/proc`:
  3667. ....
  3668. ./run --kernel-cli 'dyndbg="file * +p" loglevel=8'
  3669. ....
  3670. Get ready for the noisiest boot ever, I think it overflows the `printk` buffer and funny things happen.
  3671. ===== pr_debug != printk(KERN_DEBUG
  3672. 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:
  3673. ....
  3674. ./run --kernel-cli 'initcall_debug logleve=8'
  3675. ....
  3676. which outputs lines of type:
  3677. ....
  3678. <7>[ 1.756680] calling clk_disable_unused+0x0/0x130 @ 1
  3679. <7>[ 1.757003] initcall clk_disable_unused+0x0/0x130 returned 0 after 111 usecs
  3680. ....
  3681. which are `printk(KERN_DEBUG` inside `init/main.c` in v4.16.
  3682. Mentioned at: https://stackoverflow.com/questions/37272109/how-to-get-details-of-all-modules-drivers-got-initialized-probed-during-kernel-b
  3683. This likely comes from the ifdef split at `init/main.c`:
  3684. ....
  3685. /* If you are writing a driver, please use dev_dbg instead */
  3686. #if defined(CONFIG_DYNAMIC_DEBUG)
  3687. #include <linux/dynamic_debug.h>
  3688. /* dynamic_pr_debug() uses pr_fmt() internally so we don't need it here */
  3689. #define pr_debug(fmt, ...) \
  3690. dynamic_pr_debug(fmt, ##__VA_ARGS__)
  3691. #elif defined(DEBUG)
  3692. #define pr_debug(fmt, ...) \
  3693. printk(KERN_DEBUG pr_fmt(fmt), ##__VA_ARGS__)
  3694. #else
  3695. #define pr_debug(fmt, ...) \
  3696. no_printk(KERN_DEBUG pr_fmt(fmt), ##__VA_ARGS__)
  3697. #endif
  3698. ....
  3699. === Linux kernel entry point
  3700. `start_kernel` is a good definition of it: https://stackoverflow.com/questions/18266063/does-kernel-have-main-function/33422401#33422401
  3701. === Kernel module APIs
  3702. ==== Kernel module parameters
  3703. The Linux kernel allows passing module parameters at insertion time <<myinsmod,through the `init_module` and `finit_module` system calls>>:
  3704. ....
  3705. ./params.sh
  3706. echo $?
  3707. ....
  3708. Outcome: the test passes:
  3709. ....
  3710. 0
  3711. ....
  3712. Sources:
  3713. * link:kernel_modules/params.c[]
  3714. * link:rootfs_overlay/lkmc/params.sh[]
  3715. As shown in the example, module parameters can also be read and modified at runtime from <<sysfs>>.
  3716. We can obtain the help text of the parameters with:
  3717. ....
  3718. modinfo params.ko
  3719. ....
  3720. The output contains:
  3721. ....
  3722. parm: j:my second favorite int
  3723. parm: i:my favorite int
  3724. ....
  3725. ===== modprobe.conf
  3726. <<modprobe>> insertion can also set default parameters via the link:rootfs_overlay/etc/modprobe.conf[`/etc/modprobe.conf`] file:
  3727. ....
  3728. modprobe params
  3729. cat /sys/kernel/debug/lkmc_params
  3730. ....
  3731. Output:
  3732. ....
  3733. 12 34
  3734. ....
  3735. This is specially important when loading modules with <<kernel-module-dependencies>> or else we would have no opportunity of passing those.
  3736. `modprobe.conf` doesn't actually insmod anything for us: https://superuser.com/questions/397842/automatically-load-kernel-module-at-boot-angstrom/1267464#1267464
  3737. ==== Kernel module dependencies
  3738. One module can depend on symbols of another module that are exported with `EXPORT_SYMBOL`:
  3739. ....
  3740. ./dep.sh
  3741. echo $?
  3742. ....
  3743. Outcome: the test passes:
  3744. ....
  3745. 0
  3746. ....
  3747. Sources:
  3748. * link:kernel_modules/dep.c[]
  3749. * link:kernel_modules/dep2.c[]
  3750. * link:rootfs_overlay/lkmc/dep.sh[]
  3751. The kernel deduces dependencies based on the `EXPORT_SYMBOL` that each module uses.
  3752. Symbols exported by `EXPORT_SYMBOL` can be seen with:
  3753. ....
  3754. insmod dep.ko
  3755. grep lkmc_dep /proc/kallsyms
  3756. ....
  3757. sample output:
  3758. ....
  3759. ffffffffc0001030 r __ksymtab_lkmc_dep [dep]
  3760. ffffffffc000104d r __kstrtab_lkmc_dep [dep]
  3761. ffffffffc0002300 B lkmc_dep [dep]
  3762. ....
  3763. This requires `CONFIG_KALLSYMS_ALL=y`.
  3764. Dependency information is stored by the kernel module build system in the `.ko` files' <<module_info>>, e.g.:
  3765. ....
  3766. modinfo dep2.ko
  3767. ....
  3768. contains:
  3769. ....
  3770. depends: dep
  3771. ....
  3772. We can double check with:
  3773. ....
  3774. strings 3 dep2.ko | grep -E 'depends'
  3775. ....
  3776. The output contains:
  3777. ....
  3778. depends=dep
  3779. ....
  3780. Module dependencies are also stored at:
  3781. ....
  3782. cd /lib/module/*
  3783. grep dep modules.dep
  3784. ....
  3785. Output:
  3786. ....
  3787. extra/dep2.ko: extra/dep.ko
  3788. extra/dep.ko:
  3789. ....
  3790. TODO: what for, and at which point point does Buildroot / BusyBox generate that file?
  3791. ===== Kernel module dependencies with modprobe
  3792. Unlike `insmod`, <<modprobe>> deals with kernel module dependencies for us.
  3793. First get <<kernel_modules-package>> working.
  3794. Then, for example:
  3795. ....
  3796. modprobe buildroot_dep2
  3797. ....
  3798. outputs to dmesg:
  3799. ....
  3800. 42
  3801. ....
  3802. and then:
  3803. ....
  3804. lsmod
  3805. ....
  3806. outputs:
  3807. ....
  3808. Module Size Used by Tainted: G
  3809. buildroot_dep2 16384 0
  3810. buildroot_dep 16384 1 buildroot_dep2
  3811. ....
  3812. Sources:
  3813. * link:buildroot_packages/kernel_modules/buildroot_dep.c[]
  3814. * link:buildroot_packages/kernel_modules/buildroot_dep2.c[]
  3815. Removal also removes required modules that have zero usage count:
  3816. ....
  3817. modprobe -r buildroot_dep2
  3818. ....
  3819. `modprobe` uses information from the `modules.dep` file to decide the required dependencies. That file contains:
  3820. ....
  3821. extra/buildroot_dep2.ko: extra/buildroot_dep.ko
  3822. ....
  3823. Bibliography:
  3824. * https://askubuntu.com/questions/20070/whats-the-difference-between-insmod-and-modprobe
  3825. * https://stackoverflow.com/questions/22891705/whats-the-difference-between-insmod-and-modprobe
  3826. ==== MODULE_INFO
  3827. Module metadata is stored on module files at compile time. Some of the fields can be retrieved through the `THIS_MODULE` `struct module`:
  3828. ....
  3829. insmod module_info.ko
  3830. ....
  3831. Dmesg output:
  3832. ....
  3833. name = module_info
  3834. version = 1.0
  3835. ....
  3836. Source: link:kernel_modules/module_info.c[]
  3837. Some of those are also present on sysfs:
  3838. ....
  3839. cat /sys/module/module_info/version
  3840. ....
  3841. Output:
  3842. ....
  3843. 1.0
  3844. ....
  3845. And we can also observe them with the `modinfo` command line utility:
  3846. ....
  3847. modinfo module_info.ko
  3848. ....
  3849. sample output:
  3850. ....
  3851. filename: module_info.ko
  3852. license: GPL
  3853. version: 1.0
  3854. srcversion: AF3DE8A8CFCDEB6B00E35B6
  3855. depends:
  3856. vermagic: 4.17.0 SMP mod_unload modversions
  3857. ....
  3858. Module information is stored in a special `.modinfo` section of the ELF file:
  3859. ....
  3860. ./run-toolchain readelf -- -SW "$(./getvar kernel_modules_build_subdir)/module_info.ko"
  3861. ....
  3862. contains:
  3863. ....
  3864. [ 5] .modinfo PROGBITS 0000000000000000 0000d8 000096 00 A 0 0 8
  3865. ....
  3866. and:
  3867. ....
  3868. ./run-toolchain readelf -- -x .modinfo "$(./getvar kernel_modules_build_subdir)/module_info.ko"
  3869. ....
  3870. gives:
  3871. ....
  3872. 0x00000000 6c696365 6e73653d 47504c00 76657273 license=GPL.vers
  3873. 0x00000010 696f6e3d 312e3000 61736466 3d717765 ion=1.0.asdf=qwe
  3874. 0x00000020 72000000 00000000 73726376 65727369 r.......srcversi
  3875. 0x00000030 6f6e3d41 46334445 38413843 46434445 on=AF3DE8A8CFCDE
  3876. 0x00000040 42364230 30453335 42360000 00000000 B6B00E35B6......
  3877. 0x00000050 64657065 6e64733d 006e616d 653d6d6f depends=.name=mo
  3878. 0x00000060 64756c65 5f696e66 6f007665 726d6167 dule_info.vermag
  3879. 0x00000070 69633d34 2e31372e 3020534d 50206d6f ic=4.17.0 SMP mo
  3880. 0x00000080 645f756e 6c6f6164 206d6f64 76657273 d_unload modvers
  3881. 0x00000090 696f6e73 2000 ions .
  3882. ....
  3883. 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`.
  3884. Bibliography:
  3885. * https://stackoverflow.com/questions/19467150/significance-of-this-module-in-linux-driver/49812248#49812248
  3886. * https://stackoverflow.com/questions/4839024/how-to-find-the-version-of-a-compiled-kernel-module/42556565#42556565
  3887. * https://unix.stackexchange.com/questions/238167/how-to-understand-the-modinfo-output
  3888. ==== vermagic
  3889. 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:
  3890. ....
  3891. insmod vermagic.ko
  3892. ....
  3893. Possible dmesg output:
  3894. ....
  3895. VERMAGIC_STRING = 4.17.0 SMP mod_unload modversions
  3896. ....
  3897. Source: link:kernel_modules/vermagic.c[]
  3898. If we artificially create a mismatch with `MODULE_INFO(vermagic`, the insmod fails with:
  3899. ....
  3900. insmod: can't insert 'vermagic_fail.ko': invalid module format
  3901. ....
  3902. and `dmesg` says the expected and found vermagic found:
  3903. ....
  3904. vermagic_fail: version magic 'asdfqwer' should be '4.17.0 SMP mod_unload modversions '
  3905. ....
  3906. Source: link:kernel_modules/vermagic_fail.c[]
  3907. The kernel's vermagic is defined based on compile time configurations at link:https://github.com/torvalds/linux/blob/v4.17/include/linux/vermagic.h#L35[include/linux/vermagic.h]:
  3908. ....
  3909. #define VERMAGIC_STRING \
  3910. UTS_RELEASE " " \
  3911. MODULE_VERMAGIC_SMP MODULE_VERMAGIC_PREEMPT \
  3912. MODULE_VERMAGIC_MODULE_UNLOAD MODULE_VERMAGIC_MODVERSIONS \
  3913. MODULE_ARCH_VERMAGIC \
  3914. MODULE_RANDSTRUCT_PLUGIN
  3915. ....
  3916. The `SMP` part of the string for example is defined on the same file based on the value of `CONFIG_SMP`:
  3917. ....
  3918. #ifdef CONFIG_SMP
  3919. #define MODULE_VERMAGIC_SMP "SMP "
  3920. #else
  3921. #define MODULE_VERMAGIC_SMP ""
  3922. ....
  3923. TODO how to get the vermagic from running kernel from userland? https://lists.kernelnewbies.org/pipermail/kernelnewbies/2012-October/006306.html
  3924. <<kmod-modprobe>> has a flag to skip the vermagic check:
  3925. ....
  3926. --force-modversion
  3927. ....
  3928. This option just strips `modversion` information from the module before loading, so it is not a kernel feature.
  3929. ==== module_init
  3930. `init_module` and `cleantup_module` are an older alternative to the `module_init` and `module_exit` macros:
  3931. ....
  3932. insmod init_module.ko
  3933. rmmod init_module
  3934. ....
  3935. Dmesg output:
  3936. ....
  3937. init_module
  3938. cleanup_module
  3939. ....
  3940. Source: link:kernel_modules/module_init.c[]
  3941. 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
  3942. === Kernel panic and oops
  3943. To test out kernel panics and oops in controlled circumstances, try out the modules:
  3944. ....
  3945. insmod panic.ko
  3946. insmod oops.ko
  3947. ....
  3948. Source:
  3949. * link:kernel_modules/panic.c[]
  3950. * link:kernel_modules/oops.c[]
  3951. A panic can also be generated with:
  3952. ....
  3953. echo c > /proc/sysrq-trigger
  3954. ....
  3955. Panic vs oops: https://unix.stackexchange.com/questions/91854/whats-the-difference-between-a-kernel-oops-and-a-kernel-panic
  3956. How to generate them:
  3957. * https://unix.stackexchange.com/questions/66197/how-to-cause-kernel-panic-with-a-single-command
  3958. * https://stackoverflow.com/questions/23484147/generate-kernel-oops-or-crash-in-the-code
  3959. 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>>:
  3960. * https://superuser.com/questions/848412/scrolling-up-the-failed-screen-with-kernel-panic
  3961. * https://superuser.com/questions/269228/write-qemu-booting-virtual-machine-output-to-a-file
  3962. * http://www.reactos.org/wiki/QEMU#Redirect_to_a_file
  3963. ==== Kernel panic
  3964. On panic, the kernel dies, and so does our terminal.
  3965. The panic trace looks like:
  3966. ....
  3967. panic: loading out-of-tree module taints kernel.
  3968. panic myinit
  3969. Kernel panic - not syncing: hello panic
  3970. CPU: 0 PID: 53 Comm: insmod Tainted: G O 4.16.0 #6
  3971. Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS rel-1.11.0-0-g63451fca13-prebuilt.qemu-project.org 04/01/2014
  3972. Call Trace:
  3973. dump_stack+0x7d/0xba
  3974. ? 0xffffffffc0000000
  3975. panic+0xda/0x213
  3976. ? printk+0x43/0x4b
  3977. ? 0xffffffffc0000000
  3978. myinit+0x1d/0x20 [panic]
  3979. do_one_initcall+0x3e/0x170
  3980. do_init_module+0x5b/0x210
  3981. load_module+0x2035/0x29d0
  3982. ? kernel_read_file+0x7d/0x140
  3983. ? SyS_finit_module+0xa8/0xb0
  3984. SyS_finit_module+0xa8/0xb0
  3985. do_syscall_64+0x6f/0x310
  3986. ? trace_hardirqs_off_thunk+0x1a/0x32
  3987. entry_SYSCALL_64_after_hwframe+0x42/0xb7
  3988. RIP: 0033:0x7ffff7b36206
  3989. RSP: 002b:00007fffffffeb78 EFLAGS: 00000206 ORIG_RAX: 0000000000000139
  3990. RAX: ffffffffffffffda RBX: 000000000000005c RCX: 00007ffff7b36206
  3991. RDX: 0000000000000000 RSI: 000000000069e010 RDI: 0000000000000003
  3992. RBP: 000000000069e010 R08: 00007ffff7ddd320 R09: 0000000000000000
  3993. R10: 00007ffff7ddd320 R11: 0000000000000206 R12: 0000000000000003
  3994. R13: 00007fffffffef4a R14: 0000000000000000 R15: 0000000000000000
  3995. Kernel Offset: disabled
  3996. ---[ end Kernel panic - not syncing: hello panic
  3997. ....
  3998. Notice how our panic message `hello panic` is visible at:
  3999. ....
  4000. Kernel panic - not syncing: hello panic
  4001. ....
  4002. ===== Kernel module stack trace to source line
  4003. The log shows which module each symbol belongs to if any, e.g.:
  4004. ....
  4005. myinit+0x1d/0x20 [panic]
  4006. ....
  4007. says that the function `myinit` is in the module `panic`.
  4008. To find the line that panicked, do:
  4009. ....
  4010. ./run-gdb
  4011. ....
  4012. and then:
  4013. ....
  4014. info line *(myinit+0x1d)
  4015. ....
  4016. which gives us the correct line:
  4017. ....
  4018. 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>.
  4019. ....
  4020. as explained at: https://stackoverflow.com/questions/8545931/using-gdb-to-convert-addresses-to-lines/27576029#27576029
  4021. The exact same thing can be done post mortem with:
  4022. ....
  4023. ./run-toolchain gdb -- \
  4024. -batch \
  4025. -ex 'info line *(myinit+0x1d)' \
  4026. "$(./getvar kernel_modules_build_subdir)/panic.ko" \
  4027. ;
  4028. ....
  4029. Related:
  4030. * https://stackoverflow.com/questions/6151538/addr2line-on-kernel-module
  4031. * https://stackoverflow.com/questions/13468286/how-to-read-understand-analyze-and-debug-a-linux-kernel-panic
  4032. ===== BUG_ON
  4033. Basically just calls `panic("BUG!")` for most archs.
  4034. ===== Exit emulator on panic
  4035. 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.
  4036. ====== Exit QEMU on panic
  4037. Enabled by default with:
  4038. * `panic=-1` command line option which reboots the kernel immediately on panic, see: <<reboot-on-panic>>
  4039. * QEMU `-no-reboot`, which makes QEMU exit when the guest tries to reboot
  4040. 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.
  4041. TODO neither method exits with exit status different from 0, so for now we are just grepping the logs for panic messages, which sucks.
  4042. 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.
  4043. ====== Exit gem5 on panic
  4044. gem5 9048ef0ffbf21bedb803b785fb68f83e95c04db8 (January 2019) can detect panics automatically if the option `system.panic_on_panic` is on.
  4045. It parses kernel symbols and detecting when the PC reaches the address of the `panic` function. gem5 then prints to stdout:
  4046. ....
  4047. Kernel panic in simulated kernel
  4048. ....
  4049. and exits with status -6.
  4050. 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.
  4051. 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!
  4052. If we don't set `system.panic_on_panic`, then gem5 just hangs on an infinite guest loop.
  4053. TODO: why doesn't gem5 x86 ff52563a214c71fcd1e21e9f00ad839612032e3b support `system.panic_on_panic` as well? Trying to set `system.panic_on_panic` there fails with:
  4054. ....
  4055. tried to set or access non-existentobject parameter: panic_on_panic
  4056. ....
  4057. However, at that commit panic on x86 makes gem5 crash with:
  4058. ....
  4059. panic: i8042 "System reset" command not implemented.
  4060. ....
  4061. which is a good side effect of an unimplemented hardware feature, since the simulation actually stops.
  4062. The implementation of panic detection happens at: https://github.com/gem5/gem5/blob/1da285dfcc31b904afc27e440544d006aae25b38/src/arch/arm/linux/system.cc#L73
  4063. ....
  4064. kernelPanicEvent = addKernelFuncEventOrPanic<Linux::KernelPanicEvent>(
  4065. "panic", "Kernel panic in simulated kernel", dmesg_output);
  4066. ....
  4067. Here we see that the symbol `"panic"` for the `panic()` function is the one being tracked.
  4068. Related thread: https://stackoverflow.com/questions/56032347/is-there-a-way-to-identify-if-gem5-run-got-over-successfully
  4069. ===== Reboot on panic
  4070. Make the kernel reboot after n seconds after panic:
  4071. ....
  4072. echo 1 > /proc/sys/kernel/panic
  4073. ....
  4074. Can also be controlled with the `panic=` kernel boot parameter.
  4075. `0` to disable, `-1` to reboot immediately.
  4076. Bibliography:
  4077. * https://github.com/torvalds/linux/blob/v4.17/Documentation/admin-guide/kernel-parameters.txt#L2931
  4078. * https://unix.stackexchange.com/questions/29567/how-to-configure-the-linux-kernel-to-reboot-on-panic/29569#29569
  4079. ===== Panic trace show addresses instead of symbols
  4080. If `CONFIG_KALLSYMS=n`, then addresses are shown on traces instead of symbol plus offset.
  4081. In v4.16 it does not seem possible to configure that at runtime. GDB step debugging with:
  4082. ....
  4083. ./run --eval-after 'insmod dump_stack.ko' --gdb-wait --tmux-args dump_stack
  4084. ....
  4085. shows that traces are printed at `arch/x86/kernel/dumpstack.c`:
  4086. ....
  4087. static void printk_stack_address(unsigned long address, int reliable,
  4088. char *log_lvl)
  4089. {
  4090. touch_nmi_watchdog();
  4091. printk("%s %s%pB\n", log_lvl, reliable ? "" : "? ", (void *)address);
  4092. }
  4093. ....
  4094. and `%pB` is documented at `Documentation/core-api/printk-formats.rst`:
  4095. ....
  4096. If KALLSYMS are disabled then the symbol address is printed instead.
  4097. ....
  4098. 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...
  4099. [[oops]]
  4100. ==== Kernel oops
  4101. On oops, the shell still lives after.
  4102. However we:
  4103. * leave the normal control flow, and `oops after` never gets printed: an interrupt is serviced
  4104. * cannot `rmmod oops` afterwards
  4105. It is possible to make `oops` lead to panics always with:
  4106. ....
  4107. echo 1 > /proc/sys/kernel/panic_on_oops
  4108. insmod oops.ko
  4109. ....
  4110. An oops stack trace looks like:
  4111. ....
  4112. BUG: unable to handle kernel NULL pointer dereference at 0000000000000000
  4113. IP: myinit+0x18/0x30 [oops]
  4114. PGD dccf067 P4D dccf067 PUD dcc1067 PMD 0
  4115. Oops: 0002 [#1] SMP NOPTI
  4116. Modules linked in: oops(O+)
  4117. CPU: 0 PID: 53 Comm: insmod Tainted: G O 4.16.0 #6
  4118. Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS rel-1.11.0-0-g63451fca13-prebuilt.qemu-project.org 04/01/2014
  4119. RIP: 0010:myinit+0x18/0x30 [oops]
  4120. RSP: 0018:ffffc900000d3cb0 EFLAGS: 00000282
  4121. RAX: 000000000000000b RBX: ffffffffc0000000 RCX: ffffffff81e3e3a8
  4122. RDX: 0000000000000001 RSI: 0000000000000086 RDI: ffffffffc0001033
  4123. RBP: ffffc900000d3e30 R08: 69796d2073706f6f R09: 000000000000013b
  4124. R10: ffffea0000373280 R11: ffffffff822d8b2d R12: 0000000000000000
  4125. R13: ffffffffc0002050 R14: ffffffffc0002000 R15: ffff88000dc934c8
  4126. FS: 00007ffff7ff66a0(0000) GS:ffff88000fc00000(0000) knlGS:0000000000000000
  4127. CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033
  4128. CR2: 0000000000000000 CR3: 000000000dcd2000 CR4: 00000000000006f0
  4129. Call Trace:
  4130. do_one_initcall+0x3e/0x170
  4131. do_init_module+0x5b/0x210
  4132. load_module+0x2035/0x29d0
  4133. ? SyS_finit_module+0xa8/0xb0
  4134. SyS_finit_module+0xa8/0xb0
  4135. do_syscall_64+0x6f/0x310
  4136. ? trace_hardirqs_off_thunk+0x1a/0x32
  4137. entry_SYSCALL_64_after_hwframe+0x42/0xb7
  4138. RIP: 0033:0x7ffff7b36206
  4139. RSP: 002b:00007fffffffeb78 EFLAGS: 00000206 ORIG_RAX: 0000000000000139
  4140. RAX: ffffffffffffffda RBX: 000000000000005c RCX: 00007ffff7b36206
  4141. RDX: 0000000000000000 RSI: 000000000069e010 RDI: 0000000000000003
  4142. RBP: 000000000069e010 R08: 00007ffff7ddd320 R09: 0000000000000000
  4143. R10: 00007ffff7ddd320 R11: 0000000000000206 R12: 0000000000000003
  4144. R13: 00007fffffffef4b R14: 0000000000000000 R15: 0000000000000000
  4145. Code: <c7> 04 25 00 00 00 00 00 00 00 00 e8 b2 33 09 c1 31 c0 c3 0f 1f 44
  4146. RIP: myinit+0x18/0x30 [oops] RSP: ffffc900000d3cb0
  4147. CR2: 0000000000000000
  4148. ---[ end trace 3cdb4e9d9842b503 ]---
  4149. ....
  4150. To find the line that oopsed, look at the `RIP` register:
  4151. ....
  4152. RIP: 0010:myinit+0x18/0x30 [oops]
  4153. ....
  4154. and then on GDB:
  4155. ....
  4156. ./run-gdb
  4157. ....
  4158. run
  4159. ....
  4160. info line *(myinit+0x18)
  4161. ....
  4162. which gives us the correct line:
  4163. ....
  4164. 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>.
  4165. ....
  4166. This-did not work on `arm` due to <<gdb-step-debug-kernel-module-arm>> so we need to either:
  4167. * <<gdb-module_init>>
  4168. * <<kernel-module-stack-trace-to-source-line>> post-mortem method
  4169. ==== dump_stack
  4170. 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:
  4171. ....
  4172. insmod dump_stack.ko
  4173. ....
  4174. Source: link:kernel_modules/dump_stack.c[]
  4175. ==== WARN_ON
  4176. The `WARN_ON` macro basically just calls <<dump_stack,dump_stack>>.
  4177. One extra side effect is that we can make it also panic with:
  4178. ....
  4179. echo 1 > /proc/sys/kernel/panic_on_warn
  4180. insmod warn_on.ko
  4181. ....
  4182. Source: link:kernel_modules/warn_on.c[]
  4183. Can also be activated with the `panic_on_warn` boot parameter.
  4184. === Pseudo filesystems
  4185. 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.
  4186. What each pseudo-file does for each related system call does is defined by its <<file-operations>>.
  4187. Bibliography:
  4188. * https://superuser.com/questions/1198292/what-is-a-pseudo-file-system-in-linux
  4189. * https://en.wikipedia.org/wiki/Synthetic_file_system
  4190. ==== debugfs
  4191. Debugfs is the simplest pseudo filesystem to play around with:
  4192. ....
  4193. ./debugfs.sh
  4194. echo $?
  4195. ....
  4196. Outcome: the test passes:
  4197. ....
  4198. 0
  4199. ....
  4200. Sources:
  4201. * link:kernel_modules/debugfs.c[]
  4202. * link:rootfs_overlay/lkmc/debugfs.sh[]
  4203. Debugfs is made specifically to help test kernel stuff. Just mount, set <<file-operations>>, and we are done.
  4204. For this reason, it is the filesystem that we use whenever possible in our tests.
  4205. `debugfs.sh` explicitly mounts a debugfs at a custom location, but the most common mount point is `/sys/kernel/debug`.
  4206. 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].
  4207. Debugfs support requires the kernel to be compiled with `CONFIG_DEBUG_FS=y`.
  4208. Only the more basic file operations can be implemented in debugfs, e.g. `mmap` never gets called:
  4209. * https://patchwork.kernel.org/patch/9252557/
  4210. * https://github.com/torvalds/linux/blob/v4.9/fs/debugfs/file.c#L212
  4211. Bibliography: https://github.com/chadversary/debugfs-tutorial
  4212. ==== procfs
  4213. Procfs is just another fops entry point:
  4214. ....
  4215. ./procfs.sh
  4216. echo $?
  4217. ....
  4218. Outcome: the test passes:
  4219. ....
  4220. 0
  4221. ....
  4222. Procfs is a little less convenient than <<debugfs>>, but is more used in serious applications.
  4223. Procfs can run all system calls, including ones that debugfs can't, e.g. <<mmap>>.
  4224. Sources:
  4225. * link:kernel_modules/procfs.c[]
  4226. * link:rootfs_overlay/lkmc/procfs.sh[]
  4227. Bibliography: https://stackoverflow.com/questions/8516021/proc-create-example-for-kernel-module/18924359#18924359
  4228. ===== /proc/version
  4229. Its data is shared with `uname()`, which is a <<posix,POSIX C>> function and has a Linux syscall to back it up.
  4230. Where the data comes from and how to modify it:
  4231. * https://unix.stackexchange.com/questions/136959/where-does-uname-get-its-information-from/485962#485962
  4232. * https://stackoverflow.com/questions/23424174/how-to-customize-or-remove-extra-linux-kernel-version-details-shown-at-boot
  4233. In this repo, leaking host information, and to make builds more reproducible, we are setting:
  4234. - user and date to dummy values with `KBUILD_BUILD_USER` and `KBUILD_BUILD_TIMESTAMP`
  4235. - hostname to the kernel git commit with `KBUILD_BUILD_HOST` and `KBUILD_BUILD_VERSION`
  4236. A sample result is:
  4237. ....
  4238. 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
  4239. ....
  4240. ==== sysfs
  4241. Sysfs is more restricted than <<procfs>>, as it does not take an arbitrary `file_operations`:
  4242. ....
  4243. ./sysfs.sh
  4244. echo $?
  4245. ....
  4246. Outcome: the test passes:
  4247. ....
  4248. 0
  4249. ....
  4250. Sources:
  4251. * link:kernel_modules/sysfs.c[]
  4252. * link:rootfs_overlay/lkmc/sysfs.sh[]
  4253. Vs procfs:
  4254. * https://unix.stackexchange.com/questions/4884/what-is-the-difference-between-procfs-and-sysfs
  4255. * https://stackoverflow.com/questions/37237835/how-to-attach-file-operations-to-sysfs-attribute-in-platform-driver
  4256. You basically can only do `open`, `close`, `read`, `write`, and `lseek` on sysfs files.
  4257. It is similar to a <<seq_file>> file operation, except that write is also implemented.
  4258. TODO: what are those `kobject` structs? Make a more complex example that shows what they can do.
  4259. Bibliography:
  4260. * https://github.com/t3rm1n4l/kern-dev-tutorial/blob/1f036ef40fc4378f5c8d2842e55bcea7c6f8894a/05-sysfs/sysfs.c
  4261. * https://www.kernel.org/doc/Documentation/kobject.txt
  4262. * https://www.quora.com/What-are-kernel-objects-Kobj
  4263. * http://www.makelinux.net/ldd3/chp-14-sect-1
  4264. * https://www.win.tue.nl/~aeb/linux/lk/lk-13.html
  4265. ==== Character devices
  4266. Character devices can have arbitrary <<file-operations>> associated to them:
  4267. ....
  4268. ./character_device.sh
  4269. echo $?
  4270. ....
  4271. Outcome: the test passes:
  4272. ....
  4273. 0
  4274. ....
  4275. Sources:
  4276. * link:rootfs_overlay/lkmc/character_device.sh[]
  4277. * link:rootfs_overlay/lkmc/mknoddev.sh[]
  4278. * link:kernel_modules/character_device.c[]
  4279. Unlike <<procfs>> entires, character device files are created with userland `mknod` or `mknodat` syscalls:
  4280. ....
  4281. mknod </dev/path_to_dev> c <major> <minor>
  4282. ....
  4283. Intuitively, for physical devices like keyboards, the major number maps to which driver, and the minor number maps to which device it is.
  4284. A single driver can drive multiple compatible devices.
  4285. The major and minor numbers can be observed with:
  4286. ....
  4287. ls -l /dev/urandom
  4288. ....
  4289. Output:
  4290. ....
  4291. crw-rw-rw- 1 root root 1, 9 Jun 29 05:45 /dev/urandom
  4292. ....
  4293. which means:
  4294. * `c` (first letter): this is a character device. Would be `b` for a block device.
  4295. * `1, 9`: the major number is `1`, and the minor `9`
  4296. To avoid device number conflicts when registering the driver we:
  4297. * ask the kernel to allocate a free major number for us with: `register_chrdev(0`
  4298. * find ouf which number was assigned by grepping `/proc/devices` for the kernel module name
  4299. Bibliography: https://unix.stackexchange.com/questions/37829/understanding-character-device-or-character-special-files/371758#371758
  4300. ===== Automatically create character device file on insmod
  4301. And also destroy it on `rmmod`:
  4302. ....
  4303. ./character_device_create.sh
  4304. echo $?
  4305. ....
  4306. Outcome: the test passes:
  4307. ....
  4308. 0
  4309. ....
  4310. Sources:
  4311. * link:kernel_modules/character_device_create.c[]
  4312. * link:rootfs_overlay/lkmc/character_device_create.sh[]
  4313. Bibliography: https://stackoverflow.com/questions/5970595/how-to-create-a-device-node-from-the-init-module-code-of-a-linux-kernel-module/45531867#45531867
  4314. === Pseudo files
  4315. ==== File operations
  4316. 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>>.
  4317. This example illustrates the most basic system calls: `open`, `read`, `write`, `close` and `lseek`:
  4318. ....
  4319. ./fops.sh
  4320. echo $?
  4321. ....
  4322. Outcome: the test passes:
  4323. ....
  4324. 0
  4325. ....
  4326. Sources:
  4327. * link:kernel_modules/fops.c[]
  4328. * link:rootfs_overlay/lkmc/fops.sh[]
  4329. Then give this a try:
  4330. ....
  4331. sh -x ./fops.sh
  4332. ....
  4333. We have put printks on each fop, so this allows you to see which system calls are being made for each command.
  4334. No, there no official documentation: http://stackoverflow.com/questions/15213932/what-are-the-struct-file-operations-arguments
  4335. ==== seq_file
  4336. Writing trivial read <<file-operations>> is repetitive and error prone. The `seq_file` API makes the process much easier for those trivial cases:
  4337. ....
  4338. ./seq_file.sh
  4339. echo $?
  4340. ....
  4341. Outcome: the test passes:
  4342. ....
  4343. 0
  4344. ....
  4345. Sources:
  4346. * link:kernel_modules/seq_file.c[]
  4347. * link:rootfs_overlay/lkmc/seq_file.sh[]
  4348. In this example we create a debugfs file that behaves just like a file that contains:
  4349. ....
  4350. 0
  4351. 1
  4352. 2
  4353. ....
  4354. However, we only store a single integer in memory and calculate the file on the fly in an iterator fashion.
  4355. `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
  4356. Bibliography:
  4357. * link:https://github.com/torvalds/linux/blob/v4.17/Documentation/filesystems/seq_file.txt[Documentation/filesystems/seq_file.txt]
  4358. * https://stackoverflow.com/questions/25399112/how-to-use-a-seq-file-in-linux-modules
  4359. ===== seq_file single_open
  4360. If you have the entire read output upfront, `single_open` is an even more convenient version of <<seq_file>>:
  4361. ....
  4362. ./seq_file.sh
  4363. echo $?
  4364. ....
  4365. Outcome: the test passes:
  4366. ....
  4367. 0
  4368. ....
  4369. Sources:
  4370. * link:kernel_modules/seq_file_single_open.c[]
  4371. * link:rootfs_overlay/lkmc/seq_file_single_open.sh[]
  4372. This example produces a debugfs file that behaves like a file that contains:
  4373. ....
  4374. ab
  4375. cd
  4376. ....
  4377. ==== poll
  4378. The poll system call allows an user process to do a non-busy wait on a kernel event:
  4379. ....
  4380. ./poll.sh
  4381. ....
  4382. Outcome: `jiffies` gets printed to stdout every second from userland.
  4383. Sources:
  4384. * link:kernel_modules/poll.c[]
  4385. * link:include/poll.h[]
  4386. * link:rootfs_overlay/lkmc/poll.sh[]
  4387. Typically, we are waiting for some hardware to make some piece of data available available to the kernel.
  4388. The hardware notifies the kernel that the data is ready with an interrupt.
  4389. To simplify this example, we just fake the hardware interrupts with a <<kthread>> that sleeps for a second in an infinite loop.
  4390. Bibliography: https://stackoverflow.com/questions/30035776/how-to-add-poll-function-to-the-kernel-module-code/44645336#44645336
  4391. ==== ioctl
  4392. The `ioctl` system call is the best way to pass an arbitrary number of parameters to the kernel in a single go:
  4393. ....
  4394. ./ioctl.sh
  4395. echo $?
  4396. ....
  4397. Outcome: the test passes:
  4398. ....
  4399. 0
  4400. ....
  4401. Sources:
  4402. * link:kernel_modules/ioctl.c[]
  4403. * link:lkmc/ioctl.h[]
  4404. * link:userland/kernel_modules/ioctl.c[]
  4405. * link:rootfs_overlay/lkmc/ioctl.sh[]
  4406. `ioctl` is one of the most important methods of communication with real device drivers, which often take several fields as input.
  4407. `ioctl` takes as input:
  4408. * an integer `request` : it usually identifies what type of operation we want to do on this call
  4409. * an untyped pointer to memory: can be anything, but is typically a pointer to a `struct`
  4410. +
  4411. The type of the `struct` often depends on the `request` input
  4412. +
  4413. This `struct` is defined on a uapi-style C header that is used both to compile the kernel module and the userland executable.
  4414. +
  4415. The fields of this `struct` can be thought of as arbitrary input parameters.
  4416. And the output is:
  4417. * an integer return value. `man ioctl` documents:
  4418. +
  4419. ____
  4420. 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.
  4421. ____
  4422. * the input pointer data may be overwritten to contain arbitrary output
  4423. Bibliography:
  4424. * https://stackoverflow.com/questions/2264384/how-do-i-use-ioctl-to-manipulate-my-kernel-module/44613896#44613896
  4425. * https://askubuntu.com/questions/54239/problem-with-ioctl-in-a-simple-kernel-module/926675#926675
  4426. ==== mmap
  4427. The `mmap` system call allows us to share memory between user and kernel space without copying:
  4428. ....
  4429. ./mmap.sh
  4430. echo $?
  4431. ....
  4432. Outcome: the test passes:
  4433. ....
  4434. 0
  4435. ....
  4436. Sources:
  4437. * link:kernel_modules/mmap.c[]
  4438. * link:userland/kernel_modules/mmap.c[]
  4439. * link:rootfs_overlay/lkmc/mmap.sh[]
  4440. 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.
  4441. `mmap`, like most more complex <<file-operations>>, does not work with <<debugfs>> as of 4.9, so we use a <<procfs>> file for it.
  4442. Example adapted from: https://coherentmusings.wordpress.com/2014/06/10/implementing-mmap-for-transferring-data-from-user-space-to-kernel-space/
  4443. Bibliography:
  4444. * https://stackoverflow.com/questions/10760479/mmap-kernel-buffer-to-user-space/10770582#10770582
  4445. * https://stackoverflow.com/questions/1623008/allocating-memory-for-user-space-from-kernel-thread
  4446. * https://stackoverflow.com/questions/6967933/mmap-mapping-in-user-space-a-kernel-buffer-allocated-with-kmalloc
  4447. * https://github.com/jeremytrimble/ezdma
  4448. * https://github.com/simonjhall/dma
  4449. * https://github.com/ikwzm/udmabuf
  4450. ==== Anonymous inode
  4451. Anonymous inodes allow getting multiple file descriptors from a single filesystem entry, which reduces namespace pollution compared to creating multiple device files:
  4452. ....
  4453. ./anonymous_inode.sh
  4454. echo $?
  4455. ....
  4456. Outcome: the test passes:
  4457. ....
  4458. 0
  4459. ....
  4460. Sources:
  4461. * link:kernel_modules/anonymous_inode.c[]
  4462. * link:lkmc/anonymous_inode.h[]
  4463. * link:userland/kernel_modules/anonymous_inode.c[]
  4464. * link:rootfs_overlay/lkmc/anonymous_inode.sh[]
  4465. This example gets an anonymous inode via <<ioctl>> from a debugfs entry by using `anon_inode_getfd`.
  4466. Reads to that inode return the sequence: `1`, `10`, `100`, ... `10000000`, `1`, `100`, ...
  4467. Bibliography: https://stackoverflow.com/questions/4508998/what-is-an-anonymous-inode-in-linux/44388030#44388030
  4468. ==== netlink sockets
  4469. Netlink sockets offer a socket API for kernel / userland communication:
  4470. ....
  4471. ./netlink.sh
  4472. echo $?
  4473. ....
  4474. Outcome: the test passes:
  4475. ....
  4476. 0
  4477. ....
  4478. Sources:
  4479. * link:kernel_modules/netlink.c[]
  4480. * link:lkmc/netlink.h[]
  4481. * link:userland/kernel_modules/netlink.c[]
  4482. * link:rootfs_overlay/lkmc/netlink.sh[]
  4483. Launch multiple user requests in parallel to stress our socket:
  4484. ....
  4485. insmod netlink.ko sleep=1
  4486. for i in `seq 16`; do ./netlink.out & done
  4487. ....
  4488. 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
  4489. Bibliography:
  4490. * https://stackoverflow.com/questions/3299386/how-to-use-netlink-socket-to-communicate-with-a-kernel-module
  4491. * https://en.wikipedia.org/wiki/Netlink
  4492. === kthread
  4493. Kernel threads are managed exactly like userland threads; they also have a backing `task_struct`, and are scheduled with the same mechanism:
  4494. ....
  4495. insmod kthread.ko
  4496. ....
  4497. Source: link:kernel_modules/kthread.c[]
  4498. Outcome: dmesg counts from `0` to `9` once every second infinitely many times:
  4499. ....
  4500. 0
  4501. 1
  4502. 2
  4503. ...
  4504. 8
  4505. 9
  4506. 0
  4507. 1
  4508. 2
  4509. ...
  4510. ....
  4511. The count stops when we `rmmod`:
  4512. ....
  4513. rmmod kthread
  4514. ....
  4515. The sleep is done with `usleep_range`, see: <<sleep>>.
  4516. Bibliography:
  4517. * http://stackoverflow.com/questions/10177641/proper-way-of-handling-threads-in-kernel
  4518. * http://stackoverflow.com/questions/4084708/how-to-wait-for-a-linux-kernel-thread-kthreadto-exit
  4519. ==== kthreads
  4520. Let's launch two threads and see if they actually run in parallel:
  4521. ....
  4522. insmod kthreads.ko
  4523. ....
  4524. Source: link:kernel_modules/kthreads.c[]
  4525. Outcome: two threads count to dmesg from `0` to `9` in parallel.
  4526. Each line has output of form:
  4527. ....
  4528. <thread_id> <count>
  4529. ....
  4530. Possible very likely outcome:
  4531. ....
  4532. 1 0
  4533. 2 0
  4534. 1 1
  4535. 2 1
  4536. 1 2
  4537. 2 2
  4538. 1 3
  4539. 2 3
  4540. ....
  4541. The threads almost always interleaved nicely, thus confirming that they are actually running in parallel.
  4542. ==== sleep
  4543. Count to dmesg every one second from `0` up to `n - 1`:
  4544. ....
  4545. insmod sleep.ko n=5
  4546. ....
  4547. Source: link:kernel_modules/sleep.c[]
  4548. The sleep is done with a call to link:https://github.com/torvalds/linux/blob/v4.17/kernel/time/timer.c#L1984[`usleep_range`] directly inside `module_init` for simplicity.
  4549. Bibliography:
  4550. * https://stackoverflow.com/questions/15994603/how-to-sleep-in-the-linux-kernel/44153288#44153288
  4551. * https://github.com/torvalds/linux/blob/v4.17/Documentation/timers/timers-howto.txt
  4552. ==== Workqueues
  4553. A more convenient front-end for <<kthread>>:
  4554. ....
  4555. insmod workqueue_cheat.ko
  4556. ....
  4557. Outcome: count from `0` to `9` infinitely many times
  4558. Stop counting:
  4559. ....
  4560. rmmod workqueue_cheat
  4561. ....
  4562. Source: link:kernel_modules/workqueue_cheat.c[]
  4563. The workqueue thread is killed after the worker function returns.
  4564. 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
  4565. Bibliography: https://github.com/torvalds/linux/blob/v4.17/Documentation/core-api/workqueue.rst
  4566. ===== Workqueue from workqueue
  4567. Count from `0` to `9` every second infinitely many times by scheduling a new work item from a work item:
  4568. ....
  4569. insmod work_from_work.ko
  4570. ....
  4571. Stop:
  4572. ....
  4573. rmmod work_from_work
  4574. ....
  4575. The sleep is done indirectly through: link: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.
  4576. Source: link:kernel_modules/work_from_work.c[]
  4577. ==== schedule
  4578. Let's block the entire kernel! Yay:
  4579. .....
  4580. ./run --eval-after 'dmesg -n 1;insmod schedule.ko schedule=0'
  4581. .....
  4582. Outcome: the system hangs, the only way out is to kill the VM.
  4583. Source: link:kernel_modules/schedule.c[]
  4584. kthreads only allow interrupting if you call `schedule()`, and the `schedule=0` <<kernel-module-parameters,kernel module parameter>> turns it off.
  4585. Sleep functions like `usleep_range` also end up calling schedule.
  4586. If we allow `schedule()` to be called, then the system becomes responsive:
  4587. .....
  4588. ./run --eval-after 'dmesg -n 1;insmod schedule.ko schedule=1'
  4589. .....
  4590. and we can observe the counting with:
  4591. ....
  4592. dmesg -w
  4593. ....
  4594. The system also responds if we <<number-of-cores,add another core>>:
  4595. ....
  4596. ./run --cpus 2 --eval-after 'dmesg -n 1;insmod schedule.ko schedule=0'
  4597. ....
  4598. ==== Wait queues
  4599. Wait queues are a way to make a thread sleep until an event happens on the queue:
  4600. ....
  4601. insmod wait_queue.c
  4602. ....
  4603. Dmesg output:
  4604. ....
  4605. 0 0
  4606. 1 0
  4607. 2 0
  4608. # Wait one second.
  4609. 0 1
  4610. 1 1
  4611. 2 1
  4612. # Wait one second.
  4613. 0 2
  4614. 1 2
  4615. 2 2
  4616. ...
  4617. ....
  4618. Stop the count:
  4619. ....
  4620. rmmod wait_queue
  4621. ....
  4622. Source: link:kernel_modules/wait_queue.c[]
  4623. This example launches three threads:
  4624. * one thread generates events every with link:https://github.com/torvalds/linux/blob/v4.17/include/linux/wait.h#L195[`wake_up`]
  4625. * the other two threads wait for that with link:https://github.com/torvalds/linux/blob/v4.17/include/linux/wait.h#L286[`wait_event`], and print a dmesg when it happens.
  4626. +
  4627. The `wait_event` macro works a bit like:
  4628. +
  4629. ....
  4630. while (!cond)
  4631. sleep_until_event
  4632. ....
  4633. === Timers
  4634. Count from `0` to `9` infinitely many times in 1 second intervals using timers:
  4635. ....
  4636. insmod timer.ko
  4637. ....
  4638. Stop counting:
  4639. ....
  4640. rmmod timer
  4641. ....
  4642. Source: link:kernel_modules/timer.c[]
  4643. Timers are callbacks that run when an interrupt happens, from the interrupt context itself.
  4644. Therefore they produce more accurate timing than thread scheduling, which is more complex, but you can't do too much work inside of them.
  4645. Bibliography:
  4646. * http://stackoverflow.com/questions/10812858/timers-in-linux-device-drivers
  4647. * https://gist.github.com/yagihiro/310149
  4648. === IRQ
  4649. ==== irq.ko
  4650. Brute force monitor every shared interrupt that will accept us:
  4651. ....
  4652. ./run --eval-after 'insmod irq.ko' --graphic
  4653. ....
  4654. Source: link:kernel_modules/irq.c[].
  4655. Now try the following:
  4656. * press a keyboard key and then release it after a few seconds
  4657. * press a mouse key, and release it after a few seconds
  4658. * move the mouse around
  4659. Outcome: dmesg shows which IRQ was fired for each action through messages of type:
  4660. ....
  4661. handler irq = 1 dev = 250
  4662. ....
  4663. `dev` is the character device for the module and never changes, as can be confirmed by:
  4664. ....
  4665. grep lkmc_irq /proc/devices
  4666. ....
  4667. The IRQs that we observe are:
  4668. * `1` for keyboard press and release.
  4669. +
  4670. If you hold the key down for a while, it starts firing at a constant rate. So this happens at the hardware level!
  4671. * `12` mouse actions
  4672. This only works if for IRQs for which the other handlers are registered as `IRQF_SHARED`.
  4673. We can see which ones are those, either via dmesg messages of type:
  4674. ....
  4675. genirq: Flags mismatch irq 0. 00000080 (myirqhandler0) vs. 00015a00 (timer)
  4676. request_irq irq = 0 ret = -16
  4677. request_irq irq = 1 ret = 0
  4678. ....
  4679. which indicate that `0` is not, but `1` is, or with:
  4680. ....
  4681. cat /proc/interrupts
  4682. ....
  4683. which shows:
  4684. ....
  4685. 0: 31 IO-APIC 2-edge timer
  4686. 1: 9 IO-APIC 1-edge i8042, myirqhandler0
  4687. ....
  4688. so only `1` has `myirqhandler0` attached but not `0`.
  4689. The <<qemu-monitor>> also has some interrupt statistics for x86_64:
  4690. ....
  4691. ./qemu-monitor info irq
  4692. ....
  4693. TODO: properly understand how each IRQ maps to what number.
  4694. ==== dummy-irq
  4695. The Linux kernel v4.16 mainline also has a `dummy-irq` module at `drivers/misc/dummy-irq.c` for monitoring a single IRQ.
  4696. We build it by default with:
  4697. ....
  4698. CONFIG_DUMMY_IRQ=m
  4699. ....
  4700. And then you can do
  4701. ....
  4702. ./run --graphic
  4703. ....
  4704. and in guest:
  4705. ....
  4706. modprobe dummy-irq irq=1
  4707. ....
  4708. Outcome: when you click a key on the keyboard, dmesg shows:
  4709. ....
  4710. dummy-irq: interrupt occurred on IRQ 1
  4711. ....
  4712. However, this module is intended to fire only once as can be seen from its source:
  4713. ....
  4714. static int count = 0;
  4715. if (count == 0) {
  4716. printk(KERN_INFO "dummy-irq: interrupt occurred on IRQ %d\n",
  4717. irq);
  4718. count++;
  4719. }
  4720. ....
  4721. and furthermore interrupt `1` and `12` happen immediately TODO why, were they somehow pending?
  4722. So so see something interesting, you need to monitor an interrupt that is more rare than the keyboard, e.g. <<platform_device>>.
  4723. ==== /proc/interrupts
  4724. In the guest with <<qemu-graphic-mode>>:
  4725. ....
  4726. watch -n 1 cat /proc/interrupts
  4727. ....
  4728. Then see how clicking the mouse and keyboard affect the interrupt counts.
  4729. This confirms that:
  4730. * 1: keyboard
  4731. * 12: mouse click and drags
  4732. The module also shows which handlers are registered for each IRQ, as we have observed at <<irq-ko>>
  4733. When in text mode, we can also observe interrupt line 4 with handler `ttyS0` increase continuously as IO goes through the UART.
  4734. === Kernel utility functions
  4735. https://github.com/torvalds/linux/blob/v4.17/Documentation/core-api/kernel-api.rst
  4736. ==== kstrto
  4737. Convert a string to an integer:
  4738. ....
  4739. ./kstrto.sh
  4740. echo $?
  4741. ....
  4742. Outcome: the test passes:
  4743. ....
  4744. 0
  4745. ....
  4746. Sources:
  4747. * link:kernel_modules/kstrto.c[]
  4748. * link:rootfs_overlay/lkmc/kstrto.sh[]
  4749. Bibliography: https://stackoverflow.com/questions/6139493/how-convert-char-to-int-in-linux-kernel/49811658#49811658
  4750. ==== virt_to_phys
  4751. Convert a virtual address to physical:
  4752. ....
  4753. insmod virt_to_phys.ko
  4754. cat /sys/kernel/debug/lkmc_virt_to_phys
  4755. ....
  4756. Source: link:kernel_modules/virt_to_phys.c[]
  4757. Sample output:
  4758. ....
  4759. *kmalloc_ptr = 0x12345678
  4760. kmalloc_ptr = ffff88000e169ae8
  4761. virt_to_phys(kmalloc_ptr) = 0xe169ae8
  4762. static_var = 0x12345678
  4763. &static_var = ffffffffc0002308
  4764. virt_to_phys(&static_var) = 0x40002308
  4765. ....
  4766. We can confirm that the `kmalloc_ptr` translation worked with:
  4767. ....
  4768. ./qemu-monitor 'xp 0xe169ae8'
  4769. ....
  4770. which reads four bytes from a given physical address, and gives the expected:
  4771. ....
  4772. 000000000e169ae8: 0x12345678
  4773. ....
  4774. TODO it only works for kmalloc however, for the static variable:
  4775. ....
  4776. ./qemu-monitor 'xp 0x40002308'
  4777. ....
  4778. it gave a wrong value of `00000000`.
  4779. Bibliography:
  4780. * https://stackoverflow.com/questions/5748492/is-there-any-api-for-determining-the-physical-address-from-virtual-address-in-li/45128487#45128487
  4781. * https://stackoverflow.com/questions/39134990/mmap-of-dev-mem-fails-with-invalid-argument-for-virt-to-phys-address-but-addre/45127582#45127582
  4782. * https://stackoverflow.com/questions/43325205/can-we-use-virt-to-phys-for-user-space-memory-in-kernel-module
  4783. ===== Userland physical address experiments
  4784. Only tested in x86_64.
  4785. The Linux kernel exposes physical addresses to userland through:
  4786. * `/proc/<pid>/maps`
  4787. * `/proc/<pid>/pagemap`
  4788. * `/dev/mem`
  4789. In this section we will play with them.
  4790. First get a virtual address to play with:
  4791. ....
  4792. ./posix/virt_to_phys_test.out &
  4793. ....
  4794. Source: link:userland/posix/virt_to_phys_test.c[]
  4795. Sample output:
  4796. ....
  4797. vaddr 0x600800
  4798. pid 110
  4799. ....
  4800. The program:
  4801. * allocates a `volatile` variable and sets is value to `0x12345678`
  4802. * prints the virtual address of the variable, and the program PID
  4803. * runs a while loop until until the value of the variable gets mysteriously changed somehow, e.g. by nasty tinkerers like us
  4804. Then, translate the virtual address to physical using `/proc/<pid>/maps` and `/proc/<pid>/pagemap`:
  4805. ....
  4806. ./linux/virt_to_phys_user.out 110 0x600800
  4807. ....
  4808. Sample output physical address:
  4809. ....
  4810. 0x7c7b800
  4811. ....
  4812. Source: link:userland/linux/virt_to_phys_user.c[]
  4813. Now we can verify that `linux/virt_to_phys_user.out` gave the correct physical address in the following ways:
  4814. * <<qemu-xp>>
  4815. * <<dev-mem>>
  4816. Bibliography:
  4817. * https://stackoverflow.com/questions/17021214/decode-proc-pid-pagemap-entry/45126141#45126141
  4818. * https://stackoverflow.com/questions/6284810/proc-pid-pagemaps-and-proc-pid-maps-linux/45500208#45500208
  4819. ====== QEMU xp
  4820. The `xp` <<qemu-monitor>> command reads memory at a given physical address.
  4821. First launch `linux/virt_to_phys_user.out` as described at <<userland-physical-address-experiments>>.
  4822. On a second terminal, use QEMU to read the physical address:
  4823. ....
  4824. ./qemu-monitor 'xp 0x7c7b800'
  4825. ....
  4826. Output:
  4827. ....
  4828. 0000000007c7b800: 0x12345678
  4829. ....
  4830. Yes!!! We read the correct value from the physical address.
  4831. We could not find however to write to memory from the QEMU monitor, boring.
  4832. [[dev-mem]]
  4833. ====== /dev/mem
  4834. `/dev/mem` exposes access to physical addresses, and we use it through the convenient `devmem` BusyBox utility.
  4835. First launch `linux/virt_to_phys_user.out` as described at <<userland-physical-address-experiments>>.
  4836. Next, read from the physical address:
  4837. ....
  4838. devmem 0x7c7b800
  4839. ....
  4840. Possible output:
  4841. ....
  4842. Memory mapped at address 0x7ff7dbe01000.
  4843. Value at address 0X7C7B800 (0x7ff7dbe01800): 0x12345678
  4844. ....
  4845. which shows that the physical memory contains the expected value `0x12345678`.
  4846. `0x7ff7dbe01000` is a new virtual address that `devmem` maps to the physical address to be able to read from it.
  4847. Modify the physical memory:
  4848. ....
  4849. devmem 0x7c7b800 w 0x9abcdef0
  4850. ....
  4851. After one second, we see on the screen:
  4852. ....
  4853. i 9abcdef0
  4854. [1]+ Done ./posix/virt_to_phys_test.out
  4855. ....
  4856. so the value changed, and the `while` loop exited!
  4857. This example requires:
  4858. * `CONFIG_STRICT_DEVMEM=n`, otherwise `devmem` fails with:
  4859. +
  4860. ....
  4861. devmem: mmap: Operation not permitted
  4862. ....
  4863. * `nopat` kernel parameter
  4864. which we set by default.
  4865. Bibliography: https://stackoverflow.com/questions/11891979/how-to-access-mmaped-dev-mem-without-crashing-the-linux-kernel
  4866. ====== pagemap_dump.out
  4867. Dump the physical address of all pages mapped to a given process using `/proc/<pid>/maps` and `/proc/<pid>/pagemap`.
  4868. First launch `linux/virt_to_phys_user.out` as described at <<userland-physical-address-experiments>>. Suppose that the output was:
  4869. ....
  4870. # ./posix/virt_to_phys_test.out &
  4871. vaddr 0x601048
  4872. pid 63
  4873. # ./linux/virt_to_phys_user.out 63 0x601048
  4874. 0x1a61048
  4875. ....
  4876. Now obtain the page map for the process:
  4877. ....
  4878. ./linux/pagemap_dump.out 63
  4879. ....
  4880. Sample output excerpt:
  4881. ....
  4882. vaddr pfn soft-dirty file/shared swapped present library
  4883. 400000 1ede 0 1 0 1 ./posix/virt_to_phys_test.out
  4884. 600000 1a6f 0 0 0 1 ./posix/virt_to_phys_test.out
  4885. 601000 1a61 0 0 0 1 ./posix/virt_to_phys_test.out
  4886. 602000 2208 0 0 0 1 [heap]
  4887. 603000 220b 0 0 0 1 [heap]
  4888. 7ffff78ec000 1fd4 0 1 0 1 /lib/libuClibc-1.0.30.so
  4889. ....
  4890. Source: link:userland/linux/pagemap_dump.c[]
  4891. Adapted from: https://github.com/dwks/pagemap/blob/8a25747bc79d6080c8b94eac80807a4dceeda57a/pagemap2.c
  4892. Meaning of the flags:
  4893. * `vaddr`: first virtual address of a page the belongs to the process. Notably:
  4894. +
  4895. ....
  4896. ./run-toolchain readelf -- -l "$(./getvar userland_build_dir)/posix/virt_to_phys_test.out"
  4897. ....
  4898. +
  4899. contains:
  4900. +
  4901. ....
  4902. Type Offset VirtAddr PhysAddr
  4903. FileSiz MemSiz Flags Align
  4904. ...
  4905. LOAD 0x0000000000000000 0x0000000000400000 0x0000000000400000
  4906. 0x000000000000075c 0x000000000000075c R E 0x200000
  4907. LOAD 0x0000000000000e98 0x0000000000600e98 0x0000000000600e98
  4908. 0x00000000000001b4 0x0000000000000218 RW 0x200000
  4909. Section to Segment mapping:
  4910. Segment Sections...
  4911. ...
  4912. 02 .interp .hash .dynsym .dynstr .rela.plt .init .plt .text .fini .rodata .eh_frame_hdr .eh_frame
  4913. 03 .ctors .dtors .jcr .dynamic .got.plt .data .bss
  4914. ....
  4915. +
  4916. from which we deduce that:
  4917. +
  4918. ** `400000` is the text segment
  4919. ** `600000` is the data segment
  4920. * `pfn`: add three zeroes to it, and you have the physical address.
  4921. +
  4922. Three zeroes is 12 bits which is 4kB, which is the size of a page.
  4923. +
  4924. For example, the virtual address `0x601000` has `pfn` of `0x1a61`, which means that its physical address is `0x1a61000`
  4925. +
  4926. This is consistent with what `linux/virt_to_phys_user.out` told us: the virtual address `0x601048` has physical address `0x1a61048`.
  4927. +
  4928. `048` corresponds to the three last zeroes, and is the offset within the page.
  4929. +
  4930. 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.
  4931. * `soft-dirty`: TODO
  4932. * `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`.
  4933. * `swapped`: TODO swapped to disk?
  4934. * `present`: TODO vs swapped?
  4935. * `library`: which executable owns that page
  4936. This program works in two steps:
  4937. * parse the human readable lines lines from `/proc/<pid>/maps`. This files contains lines of form:
  4938. +
  4939. ....
  4940. 7ffff7b6d000-7ffff7bdd000 r-xp 00000000 fe:00 658 /lib/libuClibc-1.0.22.so
  4941. ....
  4942. +
  4943. which tells us that:
  4944. +
  4945. ** `7f8af99f8000-7f8af99ff000` is a virtual address range that belong to the process, possibly containing multiple pages.
  4946. ** `/lib/libuClibc-1.0.22.so` is the name of the library that owns that memory
  4947. * loop over each page of each address range, and ask `/proc/<pid>/pagemap` for more information about that page, including the physical address
  4948. === Linux kernel tracing
  4949. Good overviews:
  4950. * 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
  4951. * https://jvns.ca/blog/2017/07/05/linux-tracing-systems/
  4952. I hope to have examples of all methods some day, since I'm obsessed with visibility.
  4953. ==== CONFIG_PROC_EVENTS
  4954. Logs proc events such as process creation to a link:kernel_modules/netlink.c[netlink socket].
  4955. We then have a userland program that listens to the events and prints them out:
  4956. ....
  4957. # ./linux/proc_events.out &
  4958. # set mcast listen ok
  4959. # sleep 2 & sleep 1
  4960. fork: parent tid=48 pid=48 -> child tid=79 pid=79
  4961. fork: parent tid=48 pid=48 -> child tid=80 pid=80
  4962. exec: tid=80 pid=80
  4963. exec: tid=79 pid=79
  4964. # exit: tid=80 pid=80 exit_code=0
  4965. exit: tid=79 pid=79 exit_code=0
  4966. echo a
  4967. a
  4968. #
  4969. ....
  4970. Source: link:userland/linux/proc_events.c[]
  4971. TODO: why `exit: tid=79` shows after `exit: tid=80`?
  4972. Note how `echo a` is a Bash built-in, and therefore does not spawn a new process.
  4973. TODO: why does this produce no output?
  4974. ....
  4975. ./linux/proc_events.out >f &
  4976. ....
  4977. * https://stackoverflow.com/questions/6075013/detect-launching-of-programs-on-linux-platform/8255487#8255487
  4978. * https://serverfault.com/questions/199654/does-anyone-know-a-simple-way-to-monitor-root-process-spawn
  4979. * https://unix.stackexchange.com/questions/260162/how-to-track-newly-created-processes
  4980. 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.
  4981. * https://unix.stackexchange.com/questions/163681/print-pids-and-names-of-processes-as-they-are-created/163689 requests process name
  4982. * https://serverfault.com/questions/199654/does-anyone-know-a-simple-way-to-monitor-root-process-spawn requests UID
  4983. ===== CONFIG_PROC_EVENTS aarch64
  4984. 0111ca406bdfa6fd65a2605d353583b4c4051781 was failing with:
  4985. ....
  4986. >>> kernel_modules 1.0 Building
  4987. /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"
  4988. /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'
  4989. In file included from /linux-kernel-module-cheat//out/aarch64/buildroot/host/aarch64-buildroot-linux-uclibc/sysroot/usr/include/signal.h:329:0,
  4990. from proc_events.c:12:
  4991. /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
  4992. mcontext_t uc_mcontext;
  4993. ^~~~~~~~~~~
  4994. ....
  4995. so we commented it out.
  4996. Related threads:
  4997. * https://mailman.uclibc-ng.org/pipermail/devel/2018-January/001624.html
  4998. * https://github.com/DynamoRIO/dynamorio/issues/2356
  4999. 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:
  5000. ....
  5001. ../utils/ldd.c: In function 'elf_find_dynamic':
  5002. ../utils/ldd.c:238:12: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
  5003. return (void *)byteswap_to_host(dynp->d_un.d_val);
  5004. ^
  5005. /tmp/user/20321/cciGScKB.o: In function `process_line_callback':
  5006. msgmerge.c:(.text+0x22): undefined reference to `escape'
  5007. /tmp/user/20321/cciGScKB.o: In function `process':
  5008. msgmerge.c:(.text+0xf6): undefined reference to `poparser_init'
  5009. msgmerge.c:(.text+0x11e): undefined reference to `poparser_feed_line'
  5010. msgmerge.c:(.text+0x128): undefined reference to `poparser_finish'
  5011. collect2: error: ld returned 1 exit status
  5012. Makefile.in:120: recipe for target '../utils/msgmerge.host' failed
  5013. make[2]: *** [../utils/msgmerge.host] Error 1
  5014. make[2]: *** Waiting for unfinished jobs....
  5015. /tmp/user/20321/ccF8V8jF.o: In function `process':
  5016. msgfmt.c:(.text+0xbf3): undefined reference to `poparser_init'
  5017. msgfmt.c:(.text+0xc1f): undefined reference to `poparser_feed_line'
  5018. msgfmt.c:(.text+0xc2b): undefined reference to `poparser_finish'
  5019. collect2: error: ld returned 1 exit status
  5020. Makefile.in:120: recipe for target '../utils/msgfmt.host' failed
  5021. make[2]: *** [../utils/msgfmt.host] Error 1
  5022. package/pkg-generic.mk:227: recipe for target '/data/git/linux-kernel-module-cheat/out/aarch64/buildroot/build/uclibc-custom/.stamp_built' failed
  5023. make[1]: *** [/data/git/linux-kernel-module-cheat/out/aarch64/buildroot/build/uclibc-custom/.stamp_built] Error 2
  5024. Makefile:79: recipe for target '_all' failed
  5025. make: *** [_all] Error 2
  5026. ....
  5027. 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.
  5028. ==== ftrace
  5029. Trace a single function:
  5030. ....
  5031. cd /sys/kernel/debug/tracing/
  5032. # Stop tracing.
  5033. echo 0 > tracing_on
  5034. # Clear previous trace.
  5035. echo > trace
  5036. # List the available tracers, and pick one.
  5037. cat available_tracers
  5038. echo function > current_tracer
  5039. # List all functions that can be traced
  5040. # cat available_filter_functions
  5041. # Choose one.
  5042. echo __kmalloc > set_ftrace_filter
  5043. # Confirm that only __kmalloc is enabled.
  5044. cat enabled_functions
  5045. echo 1 > tracing_on
  5046. # Latest events.
  5047. head trace
  5048. # Observe trace continuously, and drain seen events out.
  5049. cat trace_pipe &
  5050. ....
  5051. Sample output:
  5052. ....
  5053. # tracer: function
  5054. #
  5055. # entries-in-buffer/entries-written: 97/97 #P:1
  5056. #
  5057. # _-----=> irqs-off
  5058. # / _----=> need-resched
  5059. # | / _---=> hardirq/softirq
  5060. # || / _--=> preempt-depth
  5061. # ||| / delay
  5062. # TASK-PID CPU# |||| TIMESTAMP FUNCTION
  5063. # | | | |||| | |
  5064. head-228 [000] .... 825.534637: __kmalloc <-load_elf_phdrs
  5065. head-228 [000] .... 825.534692: __kmalloc <-load_elf_binary
  5066. head-228 [000] .... 825.534815: __kmalloc <-load_elf_phdrs
  5067. head-228 [000] .... 825.550917: __kmalloc <-__seq_open_private
  5068. head-228 [000] .... 825.550953: __kmalloc <-tracing_open
  5069. head-229 [000] .... 826.756585: __kmalloc <-load_elf_phdrs
  5070. head-229 [000] .... 826.756627: __kmalloc <-load_elf_binary
  5071. head-229 [000] .... 826.756719: __kmalloc <-load_elf_phdrs
  5072. head-229 [000] .... 826.773796: __kmalloc <-__seq_open_private
  5073. head-229 [000] .... 826.773835: __kmalloc <-tracing_open
  5074. head-230 [000] .... 827.174988: __kmalloc <-load_elf_phdrs
  5075. head-230 [000] .... 827.175046: __kmalloc <-load_elf_binary
  5076. head-230 [000] .... 827.175171: __kmalloc <-load_elf_phdrs
  5077. ....
  5078. Trace all possible functions, and draw a call graph:
  5079. ....
  5080. echo 1 > max_graph_depth
  5081. echo 1 > events/enable
  5082. echo function_graph > current_tracer
  5083. ....
  5084. Sample output:
  5085. ....
  5086. # CPU DURATION FUNCTION CALLS
  5087. # | | | | | | |
  5088. 0) 2.173 us | } /* ntp_tick_length */
  5089. 0) | timekeeping_update() {
  5090. 0) 4.176 us | ntp_get_next_leap();
  5091. 0) 5.016 us | update_vsyscall();
  5092. 0) | raw_notifier_call_chain() {
  5093. 0) 2.241 us | notifier_call_chain();
  5094. 0) + 19.879 us | }
  5095. 0) 3.144 us | update_fast_timekeeper();
  5096. 0) 2.738 us | update_fast_timekeeper();
  5097. 0) ! 117.147 us | }
  5098. 0) | _raw_spin_unlock_irqrestore() {
  5099. 0) 4.045 us | _raw_write_unlock_irqrestore();
  5100. 0) + 22.066 us | }
  5101. 0) ! 265.278 us | } /* update_wall_time */
  5102. ....
  5103. TODO: what do `+` and `!` mean?
  5104. Each `enable` under the `events/` tree enables a certain set of functions, the higher the `enable` more functions are enabled.
  5105. 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
  5106. ===== ftrace system calls
  5107. https://stackoverflow.com/questions/29840213/how-do-i-trace-a-system-call-in-linux/51856306#51856306
  5108. ===== trace-cmd
  5109. TODO example:
  5110. ....
  5111. ./build-buildroot --config 'BR2_PACKAGE_TRACE_CMD=y'
  5112. ....
  5113. ==== Kprobes
  5114. 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. :-)
  5115. ....
  5116. ./build-linux --config 'CONFIG_KPROBES=y'
  5117. ....
  5118. Then on guest:
  5119. ....
  5120. insmod kprobe_example.ko
  5121. sleep 4 & sleep 4 &'
  5122. ....
  5123. Outcome: dmesg outputs on every fork:
  5124. ....
  5125. <_do_fork> pre_handler: p->addr = 0x00000000e1360063, ip = ffffffff810531d1, flags = 0x246
  5126. <_do_fork> post_handler: p->addr = 0x00000000e1360063, flags = 0x246
  5127. <_do_fork> pre_handler: p->addr = 0x00000000e1360063, ip = ffffffff810531d1, flags = 0x246
  5128. <_do_fork> post_handler: p->addr = 0x00000000e1360063, flags = 0x246
  5129. ....
  5130. Source: link:kernel_modules/kprobe_example.c[]
  5131. TODO: it does not work if I try to immediately launch `sleep`, why?
  5132. ....
  5133. insmod kprobe_example.ko
  5134. sleep 4 & sleep 4 &
  5135. ....
  5136. I don't think your code can refer to the surrounding kernel code however: the only visible thing is the value of the registers.
  5137. You can then hack it up to read the stack and read argument values, but do you really want to?
  5138. 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
  5139. Bibliography:
  5140. * https://github.com/torvalds/linux/blob/v4.16/Documentation/kprobes.txt
  5141. * https://github.com/torvalds/linux/blob/v4.17/samples/kprobes/kprobe_example.c
  5142. ==== Count boot instructions
  5143. TODO: didn't port during refactor after 3b0a343647bed577586989fb702b760bd280844a. Reimplementing should not be hard.
  5144. * https://www.quora.com/How-many-instructions-does-a-typical-Linux-kernel-boot-take
  5145. * https://github.com/cirosantilli/chat/issues/31
  5146. * https://rwmj.wordpress.com/2016/03/17/tracing-qemu-guest-execution/
  5147. * `qemu/docs/tracing.txt` and `qemu/docs/replay.txt`
  5148. * https://stackoverflow.com/questions/39149446/how-to-use-qemus-simple-trace-backend/46497873#46497873
  5149. Results (boot not excluded):
  5150. [options="header"]
  5151. |===
  5152. |Commit |Arch |Simulator |Instruction count
  5153. |7228f75ac74c896417fb8c5ba3d375a14ed4d36b
  5154. |arm
  5155. |QEMU
  5156. |680k
  5157. |7228f75ac74c896417fb8c5ba3d375a14ed4d36b
  5158. |arm
  5159. |gem5 AtomicSimpleCPU
  5160. |160M
  5161. |7228f75ac74c896417fb8c5ba3d375a14ed4d36b
  5162. |arm
  5163. |gem5 HPI
  5164. |155M
  5165. |7228f75ac74c896417fb8c5ba3d375a14ed4d36b
  5166. |x86_64
  5167. |QEMU
  5168. |3M
  5169. |7228f75ac74c896417fb8c5ba3d375a14ed4d36b
  5170. |x86_64
  5171. |gem5 AtomicSimpleCPU
  5172. |528M
  5173. |===
  5174. QEMU:
  5175. ....
  5176. ./trace-boot --arch x86_64
  5177. ....
  5178. sample output:
  5179. ....
  5180. instructions 1833863
  5181. entry_address 0x1000000
  5182. instructions_firmware 20708
  5183. ....
  5184. gem5:
  5185. ....
  5186. ./run --arch aarch64 --emulator gem5 --eval 'm5 exit'
  5187. # Or:
  5188. # ./run --arch aarch64 --emulator gem5 --eval 'm5 exit' -- --cpu-type=HPI --caches
  5189. ./gem5-stat --arch aarch64 sim_insts
  5190. ....
  5191. Notes:
  5192. * `0x1000000` is the address where QEMU puts the Linux kernel at with `-kernel` in x86.
  5193. +
  5194. It can be found from:
  5195. +
  5196. ....
  5197. ./run-toolchain readelf -- -e "$(./getvar vmlinux)" | grep Entry
  5198. ....
  5199. +
  5200. TODO confirm further. If I try to break there with:
  5201. +
  5202. ....
  5203. ./run-gdb *0x1000000
  5204. ....
  5205. +
  5206. 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:
  5207. +
  5208. ....
  5209. ./run-gdb extract_kernel
  5210. ....
  5211. +
  5212. It only appears once on every log I've seen so far, checked with `grep 0x1000000 trace.txt`
  5213. +
  5214. 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.
  5215. +
  5216. 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 link:http://github.com/cirosantilli/linux-kernel-module-cheat/commit/f8c0502bb2680f2dbe7c1f3d7958f60265347005[f8c0502bb2680f2dbe7c1f3d7958f60265347005].
  5217. * 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:
  5218. +
  5219. ....
  5220. ./run-gdb-user "$(./getvar userland_build_dir)/linux/poweroff.out" main
  5221. ....
  5222. +
  5223. And get that from the traces, e.g. if the address is `4003a0`, then we search:
  5224. +
  5225. ....
  5226. grep -n 4003a0 trace.txt
  5227. ....
  5228. +
  5229. 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.
  5230. * to disable networking. Is replacing `init` enough?
  5231. +
  5232. --
  5233. ** https://superuser.com/questions/181254/how-do-you-boot-linux-with-networking-disabled
  5234. ** https://superuser.com/questions/684005/how-does-one-permanently-disable-gnu-linux-networking/1255015#1255015
  5235. --
  5236. +
  5237. `CONFIG_NET=n` did not significantly reduce instruction counts, so maybe replacing `init` is enough.
  5238. * gem5 simulates memory latencies. So I think that the CPU loops idle while waiting for memory, and counts will be higher.
  5239. === Linux kernel hardening
  5240. Make it harder to get hacked and easier to notice that you were, at the cost of some (small?) runtime overhead.
  5241. ==== CONFIG_FORTIFY_SOURCE
  5242. Detects buffer overflows for us:
  5243. ....
  5244. ./build-linux --config 'CONFIG_FORTIFY_SOURCE=y' --linux-build-id fortify
  5245. ./build-modules --clean
  5246. ./build-modules
  5247. ./build-buildroot
  5248. ./run --eval-after 'insmod strlen_overflow.ko' --linux-build-id fortify
  5249. ....
  5250. Possible dmesg output:
  5251. ....
  5252. strlen_overflow: loading out-of-tree module taints kernel.
  5253. detected buffer overflow in strlen
  5254. ------------[ cut here ]------------
  5255. ....
  5256. followed by a trace.
  5257. 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.
  5258. TODO not always reproducible. Find a more reproducible failure. I could not observe it on:
  5259. ....
  5260. insmod memcpy_overflow.ko
  5261. ....
  5262. Source: link:kernel_modules/strlen_overflow.c[]
  5263. Bibliography: https://www.reddit.com/r/hacking/comments/8h4qxk/what_a_buffer_overflow_in_the_linux_kernel_looks/
  5264. ==== Linux security modules
  5265. https://en.wikipedia.org/wiki/Linux_Security_Modules
  5266. ===== SELinux
  5267. TODO get a hello world permission control working:
  5268. ....
  5269. ./build-linux \
  5270. --config-fragment linux_config/selinux \
  5271. --linux-build-id selinux \
  5272. ;
  5273. ./build-buildroot --config 'BR2_PACKAGE_REFPOLICY=y'
  5274. ./run --enable-kvm --linux-build-id selinux
  5275. ....
  5276. Source: link:linux_config/selinux[]
  5277. This builds:
  5278. * `BR2_PACKAGE_REFPOLICY`, which includes a reference `/etc/selinux/config` policy: https://github.com/SELinuxProject/refpolicy
  5279. +
  5280. refpolicy in turn depends on:
  5281. * `BR2_PACKAGE_SETOOLS`, which contains tools such as `getenforced`: https://github.com/SELinuxProject/setools
  5282. +
  5283. setools depends on:
  5284. * `BR2_PACKAGE_LIBSELINUX`, which is the backing userland library
  5285. After boot finishes, we see:
  5286. ....
  5287. Starting auditd: mkdir: invalid option -- 'Z'
  5288. ....
  5289. which comes from `/etc/init.d/S01auditd`, because BusyBox' `mkdir` does not have the crazy `-Z` option like Ubuntu. That's amazing!
  5290. The kernel logs contain:
  5291. ....
  5292. SELinux: Initializing.
  5293. ....
  5294. Inside the guest we now have:
  5295. ....
  5296. getenforce
  5297. ....
  5298. which initially says:
  5299. ....
  5300. Disabled
  5301. ....
  5302. TODO: if we try to enforce:
  5303. ....
  5304. setenforce 1
  5305. ....
  5306. it does not work and outputs:
  5307. ....
  5308. setenforce: SELinux is disabled
  5309. ....
  5310. SELinux requires glibc: <<libc-choice>>.
  5311. === User mode Linux
  5312. I once got link: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
  5313. 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.
  5314. Maybe some brave soul will send a pull request one day.
  5315. === UIO
  5316. UIO is a kernel subsystem that allows to do certain types of driver operations from userland.
  5317. This would be awesome to improve debuggability and safety of kernel modules.
  5318. 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
  5319. TODO get something interesting working. I currently don't understand the behaviour very well.
  5320. TODO how to ACK interrupts? How to ensure that every interrupt gets handled separately?
  5321. TODO how to write to registers. Currently using `/dev/mem` and `lspci`.
  5322. This example should handle interrupts from userland and print a message to stdout:
  5323. ....
  5324. ./uio_read.sh
  5325. ....
  5326. 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 :-)
  5327. UIO interface in a nutshell:
  5328. * blocking read / poll: waits until interrupts
  5329. * `write`: call `irqcontrol` callback. Default: 0 or 1 to enable / disable interrupts.
  5330. * `mmap`: access device memory
  5331. Sources:
  5332. * link:userland/kernel_modules/uio_read.c[]
  5333. * link:rootfs_overlay/lkmc/uio_read.sh[]
  5334. Bibliography:
  5335. * https://stackoverflow.com/questions/15286772/userspace-vs-kernel-space-driver
  5336. * https://01.org/linuxgraphics/gfx-docs/drm/driver-api/uio-howto.html
  5337. * https://stackoverflow.com/questions/7986260/linux-interrupt-handling-in-user-space
  5338. * https://yurovsky.github.io/2014/10/10/linux-uio-gpio-interrupt/
  5339. * https://github.com/bmartini/zynq-axis/blob/65a3a448fda1f0ea4977adfba899eb487201853d/dev/axis.c
  5340. * https://yurovsky.github.io/2014/10/10/linux-uio-gpio-interrupt/
  5341. * 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.
  5342. * https://stackoverflow.com/questions/49309162/interfacing-with-qemu-edu-device-via-userspace-i-o-uio-linux-driver
  5343. * userland driver stability questions:
  5344. ** https://stackoverflow.com/questions/8030758/getting-kernel-version-from-linux-kernel-module-at-runtime/45430233#45430233
  5345. ** https://stackoverflow.com/questions/37098482/how-to-build-a-linux-kernel-module-so-that-it-is-compatible-with-all-kernel-rele/45429681#45429681
  5346. ** https://liquidat.wordpress.com/2007/07/21/linux-kernel-2623-to-have-stable-userspace-driver-api/
  5347. === Linux kernel interactive stuff
  5348. [[fbcon]]
  5349. ==== Linux kernel console fun
  5350. Requires <<graphics>>.
  5351. You can also try those on the `Ctrl-Alt-F3` of your Ubuntu host, but it is much more fun inside a VM!
  5352. Stop the cursor from blinking:
  5353. ....
  5354. echo 0 > /sys/class/graphics/fbcon/cursor_blink
  5355. ....
  5356. Rotate the console 90 degrees! https://askubuntu.com/questions/237963/how-do-i-rotate-my-display-when-not-using-an-x-server
  5357. ....
  5358. echo 1 > /sys/class/graphics/fbcon/rotate
  5359. ....
  5360. Relies on: `CONFIG_FRAMEBUFFER_CONSOLE_ROTATION=y`.
  5361. Documented under: `Documentation/fb/`.
  5362. 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:
  5363. * https://unix.stackexchange.com/questions/177024/remap-keyboard-on-the-linux-console
  5364. * https://superuser.com/questions/194202/remapping-keys-system-wide-in-linux-not-just-in-x
  5365. ==== Linux kernel magic keys
  5366. Requires <<graphics>>.
  5367. Let's have some fun.
  5368. I think most are implemented under:
  5369. ....
  5370. drivers/tty
  5371. ....
  5372. TODO find all.
  5373. Scroll up / down the terminal:
  5374. ....
  5375. Shift-PgDown
  5376. Shift-PgUp
  5377. ....
  5378. Or inside `./qemu-monitor`:
  5379. ....
  5380. sendkey shift-pgup
  5381. sendkey shift-pgdown
  5382. ....
  5383. ===== Ctrl Alt Del
  5384. Run `/sbin/reboot` on guest:
  5385. ....
  5386. Ctrl-Alt-Del
  5387. ....
  5388. Enabled from our link:rootfs_overlay/etc/inittab[]:
  5389. ....
  5390. ::ctrlaltdel:/sbin/reboot
  5391. ....
  5392. Linux tries to reboot, and QEMU shutdowns due to the `-no-reboot` option which we set by default for: <<exit-emulator-on-panic>>.
  5393. Under the hood, behaviour is controlled by the `reboot` syscall:
  5394. ....
  5395. man 2 reboot
  5396. ....
  5397. `reboot` calls can set either of the these behaviours for `Ctrl-Alt-Del`:
  5398. * do a hard shutdown syscall. Set in ublibc C code with:
  5399. +
  5400. ....
  5401. reboot(RB_ENABLE_CAD)
  5402. ....
  5403. +
  5404. or from procfs with:
  5405. +
  5406. ....
  5407. echo 1 > /proc/sys/kernel/ctrl-alt-del
  5408. ....
  5409. * send a SIGINT to the init process. This is what BusyBox' init does, and it then execs the string set in `inittab`.
  5410. +
  5411. Set in uclibc C code with:
  5412. +
  5413. ....
  5414. reboot(RB_DISABLE_CAD)
  5415. ....
  5416. +
  5417. or from procfs with:
  5418. +
  5419. ....
  5420. echo 0 > /proc/sys/kernel/ctrl-alt-del
  5421. ....
  5422. Minimal example:
  5423. ....
  5424. ./run --kernel-cli 'init=/lkmc/linux/ctrl_alt_del.out' --graphic
  5425. ....
  5426. Source: link:userland/linux/ctrl_alt_del.c[]
  5427. When you hit `Ctrl-Alt-Del` in the guest, our tiny init handles a `SIGINT` sent by the kernel and outputs to stdout:
  5428. ....
  5429. cad
  5430. ....
  5431. To map between `man 2 reboot` and the uClibc `RB_*` magic constants see:
  5432. ....
  5433. less "$(./getvar buildroot_build_build_dir)"/uclibc-*/include/sys/reboot.h"
  5434. ....
  5435. The procfs mechanism is documented at:
  5436. ....
  5437. less linux/Documentation/sysctl/kernel.txt
  5438. ....
  5439. which says:
  5440. ....
  5441. When the value in this file is 0, ctrl-alt-del is trapped and
  5442. sent to the init(1) program to handle a graceful restart.
  5443. When, however, the value is > 0, Linux's reaction to a Vulcan
  5444. Nerve Pinch (tm) will be an immediate reboot, without even
  5445. syncing its dirty buffers.
  5446. Note: when a program (like dosemu) has the keyboard in 'raw'
  5447. mode, the ctrl-alt-del is intercepted by the program before it
  5448. ever reaches the kernel tty layer, and it's up to the program
  5449. to decide what to do with it.
  5450. ....
  5451. Bibliography:
  5452. * https://superuser.com/questions/193652/does-linux-have-a-ctrlaltdel-equivalent/1324415#1324415
  5453. * https://unix.stackexchange.com/questions/42573/meaning-and-commands-for-ctrlaltdel/444969#444969
  5454. ===== SysRq
  5455. We cannot test these actual shortcuts on QEMU since the host captures them at a lower level, but from:
  5456. ....
  5457. ./qemu-monitor
  5458. ....
  5459. we can for example crash the system with:
  5460. ....
  5461. sendkey alt-sysrq-c
  5462. ....
  5463. Same but boring because no magic key:
  5464. ....
  5465. echo c > /proc/sysrq-trigger
  5466. ....
  5467. Implemented in:
  5468. ....
  5469. drivers/tty/sysrq.c
  5470. ....
  5471. On your host, on modern systems that don't have the `SysRq` key you can do:
  5472. ....
  5473. Alt-PrtSc-space
  5474. ....
  5475. which prints a message to `dmesg` of type:
  5476. ....
  5477. 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)
  5478. ....
  5479. Individual SysRq can be enabled or disabled with the bitmask:
  5480. ....
  5481. /proc/sys/kernel/sysrq
  5482. ....
  5483. The bitmask is documented at:
  5484. ....
  5485. less linux/Documentation/admin-guide/sysrq.rst
  5486. ....
  5487. Bibliography: https://en.wikipedia.org/wiki/Magic_SysRq_key
  5488. ==== TTY
  5489. In order to play with TTYs, do this:
  5490. ....
  5491. printf '
  5492. tty2::respawn:/sbin/getty -n -L -l /lkmc/loginroot.sh tty2 0 vt100
  5493. tty3::respawn:-/bin/sh
  5494. tty4::respawn:/sbin/getty 0 tty4
  5495. tty63::respawn:-/bin/sh
  5496. ::respawn:/sbin/getty -L ttyS0 0 vt100
  5497. ::respawn:/sbin/getty -L ttyS1 0 vt100
  5498. ::respawn:/sbin/getty -L ttyS2 0 vt100
  5499. # Leave one serial empty.
  5500. #::respawn:/sbin/getty -L ttyS3 0 vt100
  5501. ' >> rootfs_overlay/etc/inittab
  5502. ./build-buildroot
  5503. ./run --graphic -- \
  5504. -serial telnet::1235,server,nowait \
  5505. -serial vc:800x600 \
  5506. -serial telnet::1236,server,nowait \
  5507. ;
  5508. ....
  5509. and on a second shell:
  5510. ....
  5511. telnet localhost 1235
  5512. ....
  5513. We don't add more TTYs by default because it would spawn more processes, even if we use `askfirst` instead of `respawn`.
  5514. On the GUI, switch TTYs with:
  5515. * `Alt-Left` or `Alt-Right:` go to previous / next populated `/dev/ttyN` TTY. Skips over empty TTYs.
  5516. * `Alt-Fn`: go to the nth TTY. If it is not populated, don't go there.
  5517. * `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
  5518. 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.
  5519. Next, we also have the following shells running on the serial ports, hit enter to activate them:
  5520. * `/dev/ttyS0`: first shell that was used to run QEMU, corresponds to QEMU's `-serial mon:stdio`.
  5521. +
  5522. It would also work if we used `-serial stdio`, but:
  5523. +
  5524. --
  5525. ** `Ctrl-C` would kill QEMU instead of going to the guest
  5526. ** `Ctrl-A C` wouldn't open the QEMU console there
  5527. --
  5528. +
  5529. see also: https://stackoverflow.com/questions/49716931/how-to-run-qemu-with-nographic-and-monitor-but-still-be-able-to-send-ctrlc-to
  5530. * `/dev/ttyS1`: second shell running `telnet`
  5531. * `/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`.
  5532. although we cannot change between terminals from there.
  5533. Each populated TTY contains a "shell":
  5534. * `-/bin/sh`: goes directly into an `sh` without a login prompt.
  5535. +
  5536. 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
  5537. +
  5538. The `getty` executable however also does this operation and therefore dispenses the `-`.
  5539. * `/sbin/getty` asks for password, and then gives you an `sh`
  5540. +
  5541. 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.
  5542. Identify the current TTY with the command:
  5543. ....
  5544. tty
  5545. ....
  5546. Bibliography:
  5547. * https://unix.stackexchange.com/questions/270272/how-to-get-the-tty-in-which-bash-is-running/270372
  5548. * https://unix.stackexchange.com/questions/187319/how-to-get-the-real-name-of-the-controlling-terminal
  5549. * https://unix.stackexchange.com/questions/77796/how-to-get-the-current-terminal-name
  5550. * https://askubuntu.com/questions/902998/how-to-check-which-tty-am-i-using
  5551. This outputs:
  5552. * `/dev/console` for the initial GUI terminal. But I think it is the same as `/dev/tty1`, because if I try to do
  5553. +
  5554. ....
  5555. tty1::respawn:-/bin/sh
  5556. ....
  5557. +
  5558. it makes the terminal go crazy, as if multiple processes are randomly eating up the characters.
  5559. * `/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): link:https://superuser.com/questions/449781/why-is-there-so-many-linux-dev-tty[]. I think this is determined by:
  5560. +
  5561. ....
  5562. #define MAX_NR_CONSOLES 63
  5563. ....
  5564. +
  5565. in `linux/include/uapi/linux/vt.h`.
  5566. * `/dev/ttySN` for the text shells.
  5567. +
  5568. 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
  5569. +
  5570. There are only 4 serial ports, I think this is determined by QEMU. TODO check.
  5571. +
  5572. See also: https://stackoverflow.com/questions/16706423/two-instances-of-busybox-on-separate-serial-lines-ttysn
  5573. Get the TTY in bulk for all processes:
  5574. ....
  5575. ./psa.sh
  5576. ....
  5577. Source: link:rootfs_overlay/lkmc/psa.sh[].
  5578. The TTY appears under the `TT` section, which is enabled by `-o tty`. This shows the TTY device number, e.g.:
  5579. ....
  5580. 4,1
  5581. ....
  5582. and we can then confirm it with:
  5583. ....
  5584. ls -l /dev/tty1
  5585. ....
  5586. Next try:
  5587. ....
  5588. insmod kthread.ko
  5589. ....
  5590. 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.
  5591. Bibliography:
  5592. * https://serverfault.com/questions/119736/how-to-enable-multiple-virtual-consoles-on-linux
  5593. * https://github.com/mirror/busybox/blob/1_28_3/examples/inittab#L60
  5594. * http://web.archive.org/web/20180117124612/http://nairobi-embedded.org/qemu_serial_port_system_console.html
  5595. ===== Start a getty from outside of init
  5596. TODO: https://unix.stackexchange.com/questions/196704/getty-start-from-command-line
  5597. TODO: how to place an `sh` directly on a TTY as well without `getty`?
  5598. If I try the exact same command that the `inittab` is doing from a regular shell after boot:
  5599. ....
  5600. /sbin/getty 0 tty1
  5601. ....
  5602. it fails with:
  5603. ....
  5604. getty: setsid: Operation not permitted
  5605. ....
  5606. The following however works:
  5607. ....
  5608. ./run --eval 'getty 0 tty1 & getty 0 tty2 & getty 0 tty3 & sleep 99999999' --graphic
  5609. ....
  5610. presumably because it is being called from `init` directly?
  5611. Outcome: `Alt-Right` cycles between three TTYs, `tty1` being the default one that appears under the boot messages.
  5612. `man 2 setsid` says that there is only one failure possibility:
  5613. ____
  5614. 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.
  5615. ____
  5616. We can get some visibility into it to try and solve the problem with:
  5617. ....
  5618. ./psa.sh
  5619. ....
  5620. ===== console kernel boot parameter
  5621. Take the command described at <<tty>> and try adding the following:
  5622. * `-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.
  5623. +
  5624. Instead, the shell appears on `/dev/tty7`.
  5625. * `-e 'console=tty2'` like `/dev/tty7`, but `/dev/tty2` is broken, because we have two shells there:
  5626. ** one due to the `::respawn:-/bin/sh` entry which uses whatever `console` points to
  5627. ** another one due to the `tty2::respawn:/sbin/getty` entry we added
  5628. * `-e 'console=ttyS0'` much like `tty2`, but messages show only on serial, and the terminal is broken due to having multiple shells on it
  5629. * `-e 'console=tty1 console=ttyS0'`: boot messages show on both `tty1` and `ttyS0`, but only `S0` gets a shell because it came last
  5630. ==== CONFIG_LOGO
  5631. 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
  5632. This is due to the link:https://github.com/torvalds/linux/blob/v4.17/drivers/video/logo/Kconfig#L5[`CONFIG_LOGO=y`] option which we enable by default.
  5633. `reset` on the terminal then kills the poor penguins.
  5634. When `CONFIG_LOGO=y` is set, the logo can be disabled at boot with:
  5635. ....
  5636. ./run --kernel-cli 'logo.nologo'
  5637. ....
  5638. * https://stackoverflow.com/questions/39872463/how-can-i-disable-the-startup-penguins-and-boot-text-on-linaro-ubuntu
  5639. * https://unix.stackexchange.com/questions/332198/centos-remove-penguin-logo-at-startup
  5640. Looks like a recompile is needed to modify the image...
  5641. * https://superuser.com/questions/736423/changing-kernel-bootsplash-image
  5642. * https://unix.stackexchange.com/questions/153975/how-to-change-boot-logo-in-linux-mint
  5643. === DRM
  5644. DRM / DRI is the new interface that supersedes `fbdev`:
  5645. ....
  5646. ./build-buildroot --config 'BR2_PACKAGE_LIBDRM=y'
  5647. ./build-userland --package libdrm -- userland/libs/libdrm/modeset.c
  5648. ./run --eval-after './libs/libdrm/modeset.out' --graphic
  5649. ....
  5650. Source: link:userland/libs/libdrm_modeset.c[]
  5651. Outcome: for a few seconds, the screen that contains the terminal gets taken over by changing colors of the rainbow.
  5652. 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.
  5653. ....
  5654. ./build-buildroot --config 'BR2_PACKAGE_LIBDRM=y'
  5655. ./build-userland --package libdrm
  5656. ./build-buildroot
  5657. ./run --eval-after './libs/libdrm/modeset.out' --graphic
  5658. ....
  5659. <<kmscube>> however worked, which means that it must be a bug with this demo?
  5660. We set `CONFIG_DRM=y` on our default kernel configuration, and it creates one device file for each display:
  5661. ....
  5662. # ls -l /dev/dri
  5663. total 0
  5664. crw------- 1 root root 226, 0 May 28 09:41 card0
  5665. # grep 226 /proc/devices
  5666. 226 drm
  5667. # ls /sys/module/drm /sys/module/drm_kms_helper/
  5668. ....
  5669. Try creating new displays:
  5670. ....
  5671. ./run --arch aarch64 --graphic -- -device virtio-gpu-pci
  5672. ....
  5673. to see multiple `/dev/dri/cardN`, and then use a different display with:
  5674. ....
  5675. ./run --eval-after './libs/libdrm/modeset.out' --graphic
  5676. ....
  5677. Bibliography:
  5678. * https://dri.freedesktop.org/wiki/DRM/
  5679. * https://en.wikipedia.org/wiki/Direct_Rendering_Infrastructure
  5680. * https://en.wikipedia.org/wiki/Direct_Rendering_Manager
  5681. * https://en.wikipedia.org/wiki/Mode_setting KMS
  5682. Tested on: link:http://github.com/cirosantilli/linux-kernel-module-cheat/commit/93e383902ebcc03d8a7ac0d65961c0e62af9612b[93e383902ebcc03d8a7ac0d65961c0e62af9612b]
  5683. ==== kmscube
  5684. ....
  5685. ./build-buildroot --config-fragment buildroot_config/kmscube
  5686. ....
  5687. Outcome: a colored spinning cube coded in OpenGL + EGL takes over your display and spins forever: https://www.youtube.com/watch?v=CqgJMgfxjsk
  5688. 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
  5689. TODO: it is very slow, about 1FPS. I tried Buildroot master ad684c20d146b220dd04a85dbf2533c69ec8ee52 with:
  5690. ....
  5691. make qemu_x86_64_defconfig
  5692. printf "
  5693. BR2_CCACHE=y
  5694. BR2_PACKAGE_HOST_QEMU=y
  5695. BR2_PACKAGE_HOST_QEMU_LINUX_USER_MODE=n
  5696. BR2_PACKAGE_HOST_QEMU_SYSTEM_MODE=y
  5697. BR2_PACKAGE_HOST_QEMU_VDE2=y
  5698. BR2_PACKAGE_KMSCUBE=y
  5699. BR2_PACKAGE_MESA3D=y
  5700. BR2_PACKAGE_MESA3D_DRI_DRIVER_SWRAST=y
  5701. BR2_PACKAGE_MESA3D_OPENGL_EGL=y
  5702. BR2_PACKAGE_MESA3D_OPENGL_ES=y
  5703. BR2_TOOLCHAIN_BUILDROOT_CXX=y
  5704. " >> .config
  5705. ....
  5706. and the FPS was much better, I estimate something like 15FPS.
  5707. On Ubuntu 18.04 with NVIDIA proprietary drivers:
  5708. ....
  5709. sudo apt-get instll kmscube
  5710. kmscube
  5711. ....
  5712. fails with:
  5713. ....
  5714. drmModeGetResources failed: Invalid argument
  5715. failed to initialize legacy DRM
  5716. ....
  5717. See also: https://github.com/robclark/kmscube/issues/12 and https://stackoverflow.com/questions/26920835/can-egl-application-run-in-console-mode/26921287#26921287
  5718. Tested on: link:http://github.com/cirosantilli/linux-kernel-module-cheat/commit/2903771275372ccfecc2b025edbb0d04c4016930[2903771275372ccfecc2b025edbb0d04c4016930]
  5719. ==== kmscon
  5720. TODO get working.
  5721. Implements a console for <<drm>>.
  5722. The Linux kernel has a built-in fbdev console: <<fbcon,fbcon>> but not for <<drm>> it seems.
  5723. The upstream project seems dead with last commit in 2014: https://www.freedesktop.org/wiki/Software/kmscon/
  5724. 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
  5725. Haven't tested the fork on QEMU too much insanity.
  5726. ==== libdri2
  5727. TODO get working.
  5728. Looks like a more raw alternative to libdrm:
  5729. ....
  5730. ./build-buildroot --config 'BR2_PACKABE_LIBDRI2=y'
  5731. wget \
  5732. -O "$(./getvar userland_source_dir)/dri2test.c" \
  5733. https://raw.githubusercontent.com/robclark/libdri2/master/test/dri2test.c \
  5734. ;
  5735. ./build-userland
  5736. ....
  5737. but then I noticed that that example requires multiple files, and I don't feel like integrating it into our build.
  5738. When I build it on Ubuntu 18.04 host, it does not generate any executable, so I'm confused.
  5739. === Linux kernel testing
  5740. Bibliography: https://stackoverflow.com/questions/3177338/how-is-the-linux-kernel-tested
  5741. ==== Linux Test Project
  5742. https://github.com/linux-test-project/ltp
  5743. Tests a lot of Linux and POSIX userland visible interfaces.
  5744. Buildroot already has a package, so it is trivial to build it:
  5745. ....
  5746. ./build-buildroot --config 'BR2_PACKAGE_LTP_TESTSUITE=y'
  5747. ....
  5748. So now let's try and see if the `exit` system call is working:
  5749. ....
  5750. /usr/lib/ltp-testsuite/testcases/bin/exit01
  5751. ....
  5752. which gives successful output:
  5753. ....
  5754. exit01 1 TPASS : exit() test PASSED
  5755. ....
  5756. and has source code at: https://github.com/linux-test-project/ltp/blob/20190115/testcases/kernel/syscalls/exit/exit01.c
  5757. 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>>:
  5758. ....
  5759. ./run --userland "$(./getvar buildroot_target_dir)/usr/lib/ltp-testsuite/testcases/bin/exit01"
  5760. ....
  5761. Tested at: 287c83f3f99db8c1ff9bbc85a79576da6a78e986 + 1.
  5762. ==== stress
  5763. <<posix>> userland stress. Two versions:
  5764. ....
  5765. ./build-buildroot \
  5766. --config 'BR2_PACKAGE_STRESS=y' \
  5767. --config 'BR2_PACKAGE_STRESS_NG=y' \
  5768. ;
  5769. ....
  5770. `STRESS_NG` is likely the best, but it requires glibc: <<libc-choice>>.
  5771. Websites:
  5772. * https://people.seas.harvard.edu/~apw/stress/
  5773. * https://github.com/ColinIanKing/stress-ng
  5774. `stress` usage:
  5775. ....
  5776. stress --help
  5777. stress -c 16 &
  5778. ps
  5779. ....
  5780. and notice how 16 threads were created in addition to a parent worker thread.
  5781. It just runs forever, so kill it when you get tired:
  5782. ....
  5783. kill %1
  5784. ....
  5785. `stress -c 1 -t 1` makes gem5 irresponsive for a very long time.
  5786. == Linux kernel build system
  5787. === vmlinux vs bzImage vs zImage vs Image
  5788. Between all archs on QEMU and gem5 we touch all of those kernel built output files.
  5789. 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
  5790. QEMU does not seem able to boot ELF files like `vmlinux`, only `objdump` code: https://superuser.com/questions/1376944/can-qemu-boot-linux-from-vmlinux-instead-of-bzimage
  5791. Converting `arch/*` images to `vmlinux` is possible in x86 with link:https://github.com/torvalds/linux/blob/master/scripts/extract-vmlinux[`extract-vmlinux`]. But for arm it fails with:
  5792. ....
  5793. run-detectors: unable to find an interpreter for
  5794. ....
  5795. as mentioned at:
  5796. * https://unix.stackexchange.com/questions/352215/how-do-i-extract-vmlinux-from-an-arm-image
  5797. * https://raspberrypi.stackexchange.com/questions/88621/why-doesnt-extract-vmlinux-work-with-raspbians-boot-kernel-img
  5798. == QEMU
  5799. === Introduction to QEMU
  5800. link: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.
  5801. If you are familiar with link: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.
  5802. Also both can use very similar techniques: either link:lhttps://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
  5803. The huge advantage of QEMU over VirtualBox is that is supports cross arch simulation, e.g. simulate an ARM guest on an x86 host.
  5804. 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.
  5805. Another advantage of QEMU over virtual box is that it doesn't have Oracle' hands all all over it, more like RedHat + ARM.
  5806. 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.
  5807. 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!
  5808. All of this makes QEMU the natural choice of reference system simulator for this repo.
  5809. === Disk persistency
  5810. We disable disk persistency for both QEMU and gem5 by default, to prevent the emulator from putting the image in an unknown state.
  5811. For QEMU, this is done by passing the `snapshot` option to `-drive`, and for gem5 it is the default behaviour.
  5812. If you hack up our link:run[] script to remove that option, then:
  5813. ....
  5814. ./run --eval-after 'date >f;poweroff'
  5815. ....
  5816. followed by:
  5817. ....
  5818. ./run --eval-after 'cat f'
  5819. ....
  5820. gives the date, because `poweroff` without `-n` syncs before shutdown.
  5821. The `sync` command also saves the disk:
  5822. ....
  5823. sync
  5824. ....
  5825. When you do:
  5826. ....
  5827. ./build-buildroot
  5828. ....
  5829. the disk image gets overwritten by a fresh filesystem and you lose all changes.
  5830. 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.
  5831. Persistency is also turned off when booting from <<initrd>> with a CPIO instead of with a disk.
  5832. 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.
  5833. ==== gem5 disk persistency
  5834. TODO how to make gem5 disk writes persistent?
  5835. As of cadb92f2df916dbb47f428fd1ec4932a2e1f0f48 there are some `read_only` entries in the <<config-ini>> under cow sections, but hacking them to true did not work:
  5836. ....
  5837. diff --git a/configs/common/FSConfig.py b/configs/common/FSConfig.py
  5838. index 17498c42b..76b8b351d 100644
  5839. --- a/configs/common/FSConfig.py
  5840. +++ b/configs/common/FSConfig.py
  5841. @@ -60,7 +60,7 @@ os_types = { 'alpha' : [ 'linux' ],
  5842. }
  5843. class CowIdeDisk(IdeDisk):
  5844. - image = CowDiskImage(child=RawDiskImage(read_only=True),
  5845. + image = CowDiskImage(child=RawDiskImage(read_only=False),
  5846. read_only=False)
  5847. def childImage(self, ci):
  5848. ....
  5849. The directory of interest is `src/dev/storage`.
  5850. === gem5 qcow2
  5851. 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
  5852. This would be good to allow storing smaller sparse ext2 images locally on disk.
  5853. === Snapshot
  5854. QEMU allows us to take snapshots at any time through the monitor.
  5855. You can then restore CPU, memory and disk state back at any time.
  5856. qcow2 filesystems must be used for that to work.
  5857. To test it out, login into the VM with and run:
  5858. ....
  5859. ./run --eval-after 'umount /mnt/9p/*;./count.sh'
  5860. ....
  5861. On another shell, take a snapshot:
  5862. ....
  5863. ./qemu-monitor savevm my_snap_id
  5864. ....
  5865. The counting continues.
  5866. Restore the snapshot:
  5867. ....
  5868. ./qemu-monitor loadvm my_snap_id
  5869. ....
  5870. and the counting goes back to where we saved. This shows that CPU and memory states were reverted.
  5871. 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:
  5872. .....
  5873. 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'
  5874. .....
  5875. We can also verify that the disk state is also reversed. Guest:
  5876. ....
  5877. echo 0 >f
  5878. ....
  5879. Monitor:
  5880. ....
  5881. ./qemu-monitor savevm my_snap_id
  5882. ....
  5883. Guest:
  5884. ....
  5885. echo 1 >f
  5886. ....
  5887. Monitor:
  5888. ....
  5889. ./qemu-monitor loadvm my_snap_id
  5890. ....
  5891. Guest:
  5892. ....
  5893. cat f
  5894. ....
  5895. And the output is `0`.
  5896. Our setup does not allow for snapshotting while using <<initrd>>.
  5897. Bibliography: https://stackoverflow.com/questions/40227651/does-qemu-emulator-have-checkpoint-function/48724371#48724371
  5898. ==== Snapshot internals
  5899. Snapshots are stored inside the `.qcow2` images themselves.
  5900. They can be observed with:
  5901. ....
  5902. "$(./getvar buildroot_host_dir)/bin/qemu-img" info "$(./getvar qcow2_file)"
  5903. ....
  5904. which after `savevm my_snap_id` and `savevm asdf` contains an output of type:
  5905. ....
  5906. image: out/x86_64/buildroot/images/rootfs.ext2.qcow2
  5907. file format: qcow2
  5908. virtual size: 512M (536870912 bytes)
  5909. disk size: 180M
  5910. cluster_size: 65536
  5911. Snapshot list:
  5912. ID TAG VM SIZE DATE VM CLOCK
  5913. 1 my_snap_id 47M 2018-04-27 21:17:50 00:00:15.251
  5914. 2 asdf 47M 2018-04-27 21:20:39 00:00:18.583
  5915. Format specific information:
  5916. compat: 1.1
  5917. lazy refcounts: false
  5918. refcount bits: 16
  5919. corrupt: false
  5920. ....
  5921. As a consequence:
  5922. * it is possible to restore snapshots across boots, since they stay on the same image the entire time
  5923. * it is not possible to use snapshots with <<initrd>> in our setup, since we don't pass `-drive` at all when initrd is enabled
  5924. === Device models
  5925. This section documents:
  5926. * how to interact with peripheral hardware device models through device drivers
  5927. * 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
  5928. For the more complex interfaces, we focus on simplified educational devices, either:
  5929. * present in the QEMU upstream:
  5930. ** <<qemu-edu>>
  5931. * added in link:https://github.com/cirosantilli/qemu[our fork of QEMU]:
  5932. ** <<pci_min>>
  5933. ** <<platform_device>>
  5934. ==== PCI
  5935. Only tested in x86.
  5936. ===== pci_min
  5937. PCI driver for our minimal `pci_min.c` QEMU fork device:
  5938. ....
  5939. ./run -- -device lkmc_pci_min
  5940. ....
  5941. then:
  5942. ....
  5943. insmod pci_min.ko
  5944. ....
  5945. Sources:
  5946. * Kernel module: link:kernel_modules/pci_min.c[].
  5947. * QEMU device: https://github.com/cirosantilli/qemu/blob/lkmc/hw/misc/lkmc_pci_min.c
  5948. Outcome:
  5949. ....
  5950. <4>[ 10.608241] pci_min: loading out-of-tree module taints kernel.
  5951. <6>[ 10.609935] probe
  5952. <6>[ 10.651881] dev->irq = 11
  5953. lkmc_pci_min mmio_write addr = 0 val = 12345678 size = 4
  5954. <6>[ 10.668515] irq_handler irq = 11 dev = 251
  5955. lkmc_pci_min mmio_write addr = 4 val = 0 size = 4
  5956. ....
  5957. What happened:
  5958. * right at probe time, we write to a register
  5959. * our hardware model is coded such that it generates an interrupt when written to
  5960. * the Linux kernel interrupt handler write to another register, which tells the hardware to stop sending interrupts
  5961. Kernel messages and printks from inside QEMU are shown all together, to see that more clearly, run in <<qemu-graphic-mode>> instead.
  5962. 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.
  5963. Probe already does a MMIO write, which generates an IRQ and tests everything.
  5964. [[qemu-edu]]
  5965. ===== QEMU edu PCI device
  5966. Small upstream educational PCI device:
  5967. ....
  5968. ./qemu_edu.sh
  5969. ....
  5970. 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
  5971. Sources:
  5972. * kernel module: link:kernel_modules/qemu_edu.c[]
  5973. * QEMU device: https://github.com/qemu/qemu/blob/v2.12.0/hw/misc/edu.c
  5974. * test script: link:rootfs_overlay/lkmc/qemu_edu.sh[]
  5975. Works because we add to our default QEMU CLI:
  5976. ....
  5977. -device edu
  5978. ....
  5979. This example uses:
  5980. * the QEMU `edu` educational device, which is a minimal educational in-tree PCI example
  5981. * the `pci.ko` kernel module, which exercises the `edu` hardware.
  5982. +
  5983. I've contacted the awesome original author author of `edu` link: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. link: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.
  5984. TODO exercise DMA on the kernel module. The `edu` hardware model has that feature:
  5985. * https://stackoverflow.com/questions/32592734/are-there-any-dma-driver-example-pcie-and-fpga/44716747#44716747
  5986. * https://stackoverflow.com/questions/17913679/how-to-instantiate-and-use-a-dma-driver-linux-module
  5987. ===== Manipulate PCI registers directly
  5988. In this section we will try to interact with PCI devices directly from userland without kernel modules.
  5989. First identify the PCI device with:
  5990. ....
  5991. lspci
  5992. ....
  5993. In our case for example, we see:
  5994. ....
  5995. 00:06.0 Unclassified device [00ff]: Device 1234:11e8 (rev 10)
  5996. 00:07.0 Unclassified device [00ff]: Device 1234:11e9
  5997. ....
  5998. which we identify as being `edu` and `pci_min` respectively by the magic numbers: `1234:11e?`
  5999. Alternatively, we can also do use the QEMU monitor:
  6000. ....
  6001. ./qemu-monitor info qtree
  6002. ....
  6003. which gives:
  6004. ....
  6005. dev: lkmc_pci_min, id ""
  6006. addr = 07.0
  6007. romfile = ""
  6008. rombar = 1 (0x1)
  6009. multifunction = false
  6010. command_serr_enable = true
  6011. x-pcie-lnksta-dllla = true
  6012. x-pcie-extcap-init = true
  6013. class Class 00ff, addr 00:07.0, pci id 1234:11e9 (sub 1af4:1100)
  6014. bar 0: mem at 0xfeb54000 [0xfeb54007]
  6015. dev: edu, id ""
  6016. addr = 06.0
  6017. romfile = ""
  6018. rombar = 1 (0x1)
  6019. multifunction = false
  6020. command_serr_enable = true
  6021. x-pcie-lnksta-dllla = true
  6022. x-pcie-extcap-init = true
  6023. class Class 00ff, addr 00:06.0, pci id 1234:11e8 (sub 1af4:1100)
  6024. bar 0: mem at 0xfea00000 [0xfeafffff]
  6025. ....
  6026. See also: https://serverfault.com/questions/587189/list-all-devices-emulated-for-a-vm/913622#913622
  6027. Read the configuration registers as binary:
  6028. ....
  6029. hexdump /sys/bus/pci/devices/0000:00:06.0/config
  6030. ....
  6031. Get nice human readable names and offsets of the registers and some enums:
  6032. ....
  6033. setpci --dumpregs
  6034. ....
  6035. Get the values of a given config register from its human readable name, either with either bus or device id:
  6036. ....
  6037. setpci -s 0000:00:06.0 BASE_ADDRESS_0
  6038. setpci -d 1234:11e9 BASE_ADDRESS_0
  6039. ....
  6040. Note however that `BASE_ADDRESS_0` also appears when you do:
  6041. ....
  6042. lspci -v
  6043. ....
  6044. as:
  6045. ....
  6046. Memory at feb54000
  6047. ....
  6048. Then you can try messing with that address with <<dev-mem>>:
  6049. ....
  6050. devmem 0xfeb54000 w 0x12345678
  6051. ....
  6052. which writes to the first register of our <<pci_min>> device.
  6053. The device then fires an interrupt at irq 11, which is unhandled, which leads the kernel to say you are a bad boy:
  6054. ....
  6055. lkmc_pci_min mmio_write addr = 0 val = 12345678 size = 4
  6056. <5>[ 1064.042435] random: crng init done
  6057. <3>[ 1065.567742] irq 11: nobody cared (try booting with the "irqpoll" option)
  6058. ....
  6059. followed by a trace.
  6060. Next, also try using our <<irq-ko>> IRQ monitoring module before triggering the interrupt:
  6061. ....
  6062. insmod irq.ko
  6063. devmem 0xfeb54000 w 0x12345678
  6064. ....
  6065. 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:
  6066. ....
  6067. handler irq = 11 dev = 251
  6068. ....
  6069. ===== pciutils
  6070. There are two versions of `setpci` and `lspci`:
  6071. * a simple one from BusyBox
  6072. * a more complete one from link: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.
  6073. ===== Introduction to PCI
  6074. The PCI standard is non-free, obviously like everything in low level: https://pcisig.com/specifications but Google gives several illegal PDF hits :-)
  6075. And of course, the best documentation available is: http://wiki.osdev.org/PCI
  6076. Like every other hardware, we could interact with PCI on x86 using only IO instructions and memory operations.
  6077. But PCI is a complex communication protocol that the Linux kernel implements beautifully for us, so let's use the kernel API.
  6078. Bibliography:
  6079. * edu device source and spec in QEMU tree:
  6080. ** https://github.com/qemu/qemu/blob/v2.7.0/hw/misc/edu.c
  6081. ** https://github.com/qemu/qemu/blob/v2.7.0/docs/specs/edu.txt
  6082. * http://www.zarb.org/~trem/kernel/pci/pci-driver.c inb outb runnable example (no device)
  6083. * LDD3 PCI chapter
  6084. * another QEMU device + module, but using a custom QEMU device:
  6085. ** https://github.com/levex/kernel-qemu-pci/blob/31fc9355161b87cea8946b49857447ddd34c7aa6/module/levpci.c
  6086. ** https://github.com/levex/kernel-qemu-pci/blob/31fc9355161b87cea8946b49857447ddd34c7aa6/qemu/hw/char/lev-pci.c
  6087. * 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
  6088. * http://nairobi-embedded.org/linux_pci_device_driver.html
  6089. ===== PCI BFD
  6090. `lspci -k` shows something like:
  6091. ....
  6092. 00:04.0 Class 00ff: 1234:11e8 lkmc_pci
  6093. ....
  6094. Meaning of the first numbers:
  6095. ....
  6096. <8:bus>:<5:device>.<3:function>
  6097. ....
  6098. Often abbreviated to BDF.
  6099. * bus: groups PCI slots
  6100. * device: maps to one slot
  6101. * function: https://stackoverflow.com/questions/19223394/what-is-the-function-number-in-pci/44735372#44735372
  6102. Sometimes a fourth number is also added, e.g.:
  6103. ....
  6104. 0000:00:04.0
  6105. ....
  6106. TODO is that the domain?
  6107. 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:
  6108. ....
  6109. k->class_id = PCI_CLASS_OTHERS
  6110. ....
  6111. ===== PCI BAR
  6112. https://stackoverflow.com/questions/30190050/what-is-base-address-register-bar-in-pcie/44716618#44716618
  6113. Each PCI device has 6 BAR IOs (base address register) as per the PCI spec.
  6114. Each BAR corresponds to an address range that can be used to communicate with the PCI.
  6115. Each BAR is of one of the two types:
  6116. * `IORESOURCE_IO`: must be accessed with `inX` and `outX`
  6117. * `IORESOURCE_MEM`: must be accessed with `ioreadX` and `iowriteX`. This is the saner method apparently, and what the edu device uses.
  6118. The length of each region is defined by the hardware, and communicated to software via the configuration registers.
  6119. The Linux kernel automatically parses the 64 bytes of standardized configuration registers for us.
  6120. QEMU devices register those regions with:
  6121. ....
  6122. memory_region_init_io(&edu->mmio, OBJECT(edu), &edu_mmio_ops, edu,
  6123. "edu-mmio", 1 << 20);
  6124. pci_register_bar(pdev, 0, PCI_BASE_ADDRESS_SPACE_MEMORY, &edu->mmio);
  6125. ....
  6126. ==== GPIO
  6127. 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.
  6128. 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
  6129. The best you can do is to hack our link:build[] script to add:
  6130. ....
  6131. HOST_QEMU_OPTS='--extra-cflags=-DDEBUG_PL061=1'
  6132. ....
  6133. where link:http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.ddi0190b/index.html[PL061] is the dominating ARM Holdings hardware that handles GPIO.
  6134. Then compile with:
  6135. ....
  6136. ./build-buildroot --arch arm --config-fragment buildroot_config/gpio
  6137. ./build-linux --config-fragment linux_config/gpio
  6138. ....
  6139. then test it out with:
  6140. ....
  6141. ./gpio.sh
  6142. ....
  6143. Source: link:rootfs_overlay/lkmc/gpio.sh[]
  6144. Buildroot's Linux tools package provides some GPIO CLI tools: `lsgpio`, `gpio-event-mon`, `gpio-hammer`, TODO document them here.
  6145. ==== LEDs
  6146. TODO: broken when `arm` moved to `-M virt`, same as <<gpio>>.
  6147. Hack QEMU's `hw/misc/arm_sysctl.c` with a printf:
  6148. ....
  6149. static void arm_sysctl_write(void *opaque, hwaddr offset,
  6150. uint64_t val, unsigned size)
  6151. {
  6152. arm_sysctl_state *s = (arm_sysctl_state *)opaque;
  6153. switch (offset) {
  6154. case 0x08: /* LED */
  6155. printf("LED val = %llx\n", (unsigned long long)val);
  6156. ....
  6157. and then rebuild with:
  6158. ....
  6159. ./build-qemu --arch arm
  6160. ./build-linux --arch arm --config-fragment linux_config/leds
  6161. ....
  6162. But beware that one of the LEDs has a heartbeat trigger by default (specified on dts), so it will produce a lot of output.
  6163. And then activate it with:
  6164. ....
  6165. cd /sys/class/leds/versatile:0
  6166. cat max_brightness
  6167. echo 255 >brightness
  6168. ....
  6169. Relevant QEMU files:
  6170. * `hw/arm/versatilepb.c`
  6171. * `hw/misc/arm_sysctl.c`
  6172. Relevant kernel files:
  6173. * `arch/arm/boot/dts/versatile-pb.dts`
  6174. * `drivers/leds/led-class.c`
  6175. * `drivers/leds/leds-sysctl.c`
  6176. ==== platform_device
  6177. Minimal platform device example coded into the `-M versatilepb` SoC of our QEMU fork.
  6178. Using this device now requires checking out to the branch:
  6179. ....
  6180. git checkout platform-device
  6181. git submodule sync
  6182. ....
  6183. before building, it does not work on master.
  6184. 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`.
  6185. The module itself can be found at: https://github.com/cirosantilli/linux-kernel-module-cheat/blob/platform-device/kernel_modules/platform_device.c
  6186. Uses:
  6187. * `hw/misc/lkmc_platform_device.c` minimal device added in our QEMU fork to `-M versatilepb`
  6188. * 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
  6189. Expected outcome after insmod:
  6190. * QEMU reports MMIO with printfs
  6191. * IRQs are generated and handled by this module, which logs to dmesg
  6192. Without insmoding this module, try writing to the register with <<dev-mem>>:
  6193. ....
  6194. devmem 0x101e9000 w 0x12345678
  6195. ....
  6196. We can also observe the interrupt with <<dummy-irq>>:
  6197. ....
  6198. modprobe dummy-irq irq=34
  6199. insmod platform_device.ko
  6200. ....
  6201. The IRQ number `34` was found by on the dmesg after:
  6202. ....
  6203. insmod platform_device.ko
  6204. ....
  6205. Bibliography: https://stackoverflow.com/questions/28315265/how-to-add-a-new-device-in-qemu-source-code/44612957#44612957
  6206. ==== gem5 educational hardware models
  6207. TODO get some working!
  6208. http://gedare-csphd.blogspot.co.uk/2013/02/adding-simple-io-device-to-gem5.html
  6209. === QEMU monitor
  6210. 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
  6211. While QEMU is running, on another terminal, run:
  6212. ....
  6213. ./qemu-monitor
  6214. ....
  6215. or send one command such as `info qtree` and quit the monitor:
  6216. ....
  6217. ./qemu-monitor info qtree
  6218. ....
  6219. or equivalently:
  6220. ....
  6221. echo 'info qtree' | ./qemu-monitor
  6222. ....
  6223. Source: link:qemu-monitor[]
  6224. `qemu-monitor` uses the `-monitor` QEMU command line option, which makes the monitor listen from a socket.
  6225. Alternatively, we can also enter the QEMU monitor from inside `-nographics` <<qemu-text-mode>> with:
  6226. ....
  6227. Ctrl-A C
  6228. ....
  6229. and go back to the terminal with:
  6230. ....
  6231. Ctrl-A C
  6232. ....
  6233. * http://stackoverflow.com/questions/14165158/how-to-switch-to-qemu-monitor-console-when-running-with-curses
  6234. * https://superuser.com/questions/488263/how-to-switch-to-the-qemu-control-panel-with-nographics
  6235. When in graphic mode, we can do it from the GUI:
  6236. ....
  6237. Ctrl-Alt ?
  6238. ....
  6239. where `?` is a digit `1`, or `2`, or, `3`, etc. depending on what else is available on the GUI: serial, parallel and frame buffer.
  6240. Finally, we can also access QEMU monitor commands directly from <<gdb>> with the `monitor` command:
  6241. ....
  6242. ./run-gdb
  6243. ....
  6244. then inside that shell:
  6245. ....
  6246. monitor info qtree
  6247. ....
  6248. This way you can use both QEMU monitor and GDB commands to inspect the guest from inside a single shell! Pretty awesome.
  6249. In general, `./qemu-monitor` is the best option, as it:
  6250. * works on both modes
  6251. * allows to use the host Bash history to re-run one off commands
  6252. * allows you to search the output of commands on your host shell even when in graphic mode
  6253. Getting everything to work required careful choice of QEMU command line options:
  6254. * https://stackoverflow.com/questions/49716931/how-to-run-qemu-with-nographic-and-monitor-but-still-be-able-to-send-ctrlc-to/49751144#49751144
  6255. * https://unix.stackexchange.com/questions/167165/how-to-pass-ctrl-c-to-the-guest-when-running-qemu-with-nographic/436321#436321
  6256. ==== QEMU monitor from guest
  6257. 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
  6258. It is also worth looking into the QEMU Guest Agent tool `qemu-gq` that can be enabled with:
  6259. ....
  6260. ./build-buildroot --config 'BR2_PACKAGE_QEMU=y'
  6261. ....
  6262. See also: https://superuser.com/questions/930588/how-to-pass-commands-noninteractively-to-running-qemu-from-the-guest-qmp-via-te
  6263. ==== QEMU monitor from GDB
  6264. 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.
  6265. Try for example:
  6266. ....
  6267. monitor help
  6268. monitor info qtree
  6269. ....
  6270. === Debug the emulator
  6271. When you start hacking QEMU or gem5, it is useful to see what is going on inside the emulator themselves.
  6272. This is of course trivial since they are just regular userland programs on the host, but we make it a bit easier with:
  6273. ....
  6274. ./run --debug-vm
  6275. ....
  6276. Then you could:
  6277. ....
  6278. break edu_mmio_read
  6279. run
  6280. ....
  6281. And in QEMU:
  6282. ....
  6283. ./qemu_edu.sh
  6284. ....
  6285. Or for a faster development loop:
  6286. ....
  6287. ./run --debug-vm-args '-ex "break edu_mmio_read" -ex "run"'
  6288. ....
  6289. 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:
  6290. ....
  6291. sleep 10
  6292. ....
  6293. 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.
  6294. 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.
  6295. ==== Debug gem5 Python scripts
  6296. Start pdb at the first instruction:
  6297. ....
  6298. ./run --emulator gem5 --gem5-exe-args='--pdb' --terminal
  6299. ....
  6300. Requires `--terminal` as we must be on foreground.
  6301. Alternatively, you can add to the point of the code where you want to break the usual:
  6302. ....
  6303. import ipdb; ipdb.set_trace()
  6304. ....
  6305. and then run with:
  6306. ....
  6307. ./run --emulator gem5 --terminal
  6308. ....
  6309. TODO test PyCharm: https://stackoverflow.com/questions/51982735/writing-gem5-configuration-scripts-with-pycharm
  6310. === Tracing
  6311. QEMU can log several different events.
  6312. The most interesting are events which show instructions that QEMU ran, for which we have a helper:
  6313. ....
  6314. ./trace-boot --arch x86_64
  6315. ....
  6316. Under the hood, this uses QEMU's `-trace` option.
  6317. You can then inspect the address of each instruction run:
  6318. ....
  6319. less "$(./getvar --arch x86_64 run_dir)/trace.txt"
  6320. ....
  6321. Sample output excerpt:
  6322. ....
  6323. exec_tb 0.000 pid=10692 tb=0x7fb4f8000040 pc=0xfffffff0
  6324. exec_tb 35.391 pid=10692 tb=0x7fb4f8000180 pc=0xfe05b
  6325. exec_tb 21.047 pid=10692 tb=0x7fb4f8000340 pc=0xfe066
  6326. exec_tb 12.197 pid=10692 tb=0x7fb4f8000480 pc=0xfe06a
  6327. ....
  6328. Get the list of available trace events:
  6329. ....
  6330. ./run --trace help
  6331. ....
  6332. TODO: any way to show the actualy disassembled instruction executed directly from there? Possible with <<qemu-d-tracing>>.
  6333. Enable other specific trace events:
  6334. ....
  6335. ./run --trace trace1,trace2
  6336. ./qemu-trace2txt -a "$arch"
  6337. less "$(./getvar -a "$arch" run_dir)/trace.txt"
  6338. ....
  6339. This functionality relies on the following setup:
  6340. * `./configure --enable-trace-backends=simple`. This logs in a binary format to the trace file.
  6341. +
  6342. It makes 3x execution faster than the default trace backend which logs human readable data to stdout.
  6343. +
  6344. Logging with the default backend `log` greatly slows down the CPU, and in particular leads to this boot message:
  6345. +
  6346. ....
  6347. All QSes seen, last rcu_sched kthread activity 5252 (4294901421-4294896169), jiffies_till_next_fqs=1, root ->qsmask 0x0
  6348. swapper/0 R running task 0 1 0 0x00000008
  6349. ffff880007c03ef8 ffffffff8107aa5d ffff880007c16b40 ffffffff81a3b100
  6350. ffff880007c03f60 ffffffff810a41d1 0000000000000000 0000000007c03f20
  6351. fffffffffffffedc 0000000000000004 fffffffffffffedc ffffffff00000000
  6352. Call Trace:
  6353. <IRQ> [<ffffffff8107aa5d>] sched_show_task+0xcd/0x130
  6354. [<ffffffff810a41d1>] rcu_check_callbacks+0x871/0x880
  6355. [<ffffffff810a799f>] update_process_times+0x2f/0x60
  6356. ....
  6357. +
  6358. in which the boot appears to hang for a considerable time.
  6359. * 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/
  6360. ==== QEMU -d tracing
  6361. QEMU also has a second trace mechanism in addition to `-trace`, find out the events with:
  6362. ....
  6363. ./run -- -d help
  6364. ....
  6365. Let's pick the one that dumps executed instructions, `in_asm`:
  6366. ....
  6367. ./run --eval './linux/poweroff.out' -- -D out/trace.txt -d in_asm
  6368. less out/trace.txt
  6369. ....
  6370. Sample output excerpt:
  6371. ....
  6372. ----------------
  6373. IN:
  6374. 0xfffffff0: ea 5b e0 00 f0 ljmpw $0xf000:$0xe05b
  6375. ----------------
  6376. IN:
  6377. 0x000fe05b: 2e 66 83 3e 88 61 00 cmpl $0, %cs:0x6188
  6378. 0x000fe062: 0f 85 7b f0 jne 0xd0e1
  6379. ....
  6380. 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
  6381. 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.
  6382. ==== QEMU trace register values
  6383. TODO: is it possible to show the register values for each instruction?
  6384. This would include the memory values read into the registers.
  6385. Asked at: https://superuser.com/questions/1377764/how-to-trace-the-register-values-of-executed-instructions-in-qemu
  6386. Seems impossible due to optimizations that QEMU does:
  6387. * https://lists.gnu.org/archive/html/qemu-devel/2015-06/msg07479.html
  6388. * https://lists.gnu.org/archive/html/qemu-devel/2014-04/msg02856.html
  6389. * https://lists.gnu.org/archive/html/qemu-devel/2012-08/msg03057.html
  6390. 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
  6391. gem5 can do it: <<gem5-tracing>>.
  6392. ==== Trace source lines
  6393. We can further use Binutils' `addr2line` to get the line that corresponds to each address:
  6394. ....
  6395. ./trace-boot --arch x86_64
  6396. ./trace2line --arch x86_64
  6397. less "$(./getvar --arch x86_64 run_dir)/trace-lines.txt"
  6398. ....
  6399. The last commands takes several seconds.
  6400. The format is as follows:
  6401. ....
  6402. 39368 _static_cpu_has arch/x86/include/asm/cpufeature.h:148
  6403. ....
  6404. Where:
  6405. * `39368`: number of consecutive times that a line ran. Makes the output much shorter and more meaningful
  6406. * `_static_cpu_has`: name of the function that contains the line
  6407. * `arch/x86/include/asm/cpufeature.h:148`: file and line
  6408. This could of course all be done with GDB, but it would likely be too slow to be practical.
  6409. TODO do even more awesome offline post-mortem analysis things, such as:
  6410. * detect if we are in userspace or kernelspace. Should be a simple matter of reading the
  6411. * read kernel data structures, and determine the current thread. Maybe we can reuse / extend the kernel's GDB Python scripts??
  6412. ==== QEMU record and replay
  6413. 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.
  6414. This awesome feature allows you to examine a single run as many times as you would like until you understand everything:
  6415. ....
  6416. # Record a run.
  6417. ./run --eval-after './linux/rand_check.out;./linux/poweroff.out;' --record
  6418. # Replay the run.
  6419. ./run --eval-after './linux/rand_check.out;./linux/poweroff.out;' --replay
  6420. ....
  6421. A convenient shortcut to do both at once to test the feature is:
  6422. ....
  6423. ./qemu-rr --eval-after './linux/rand_check.out;./linux/poweroff.out;'
  6424. ....
  6425. By comparing the terminal output of both runs, we can see that they are the exact same, including things which normally differ across runs:
  6426. * timestamps of dmesg output
  6427. * <<rand_check-out>> output
  6428. 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.
  6429. Documented at: https://github.com/qemu/qemu/blob/v2.12.0/docs/replay.txt
  6430. TODO: using `-r` as above leads to a kernel warning:
  6431. ....
  6432. rcu_sched detected stalls on CPUs/tasks
  6433. ....
  6434. TODO: replay deadlocks intermittently at disk operations, last kernel message:
  6435. ....
  6436. EXT4-fs (sda): re-mounted. Opts: block_validity,barrier,user_xattr
  6437. ....
  6438. TODO replay with network gets stuck:
  6439. ....
  6440. ./qemu-rr --eval-after 'ifup -a;wget -S google.com;./linux/poweroff.out;'
  6441. ....
  6442. after the message:
  6443. ....
  6444. adding dns 10.0.2.3
  6445. ....
  6446. There is explicit network support on the QEMU patches, but either it is buggy or we are not using the correct magic options.
  6447. Solved on unmerged c42634d8e3428cfa60672c3ba89cabefc720cde9 from https://github.com/ispras/qemu/tree/rr-180725
  6448. 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
  6449. Then, when I tried with <<initrd>> and no disk:
  6450. ....
  6451. ./build-buildroot --arch aarch64 --initrd
  6452. ./qemu-rr --arch aarch64 --eval-after './linux/rand_check.out;./linux/poweroff.out;' --initrd
  6453. ....
  6454. QEMU crashes with:
  6455. ....
  6456. ERROR:replay/replay-time.c:49:replay_read_clock: assertion failed: (replay_file && replay_mutex_locked())
  6457. ....
  6458. 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`?
  6459. Solved on unmerged c42634d8e3428cfa60672c3ba89cabefc720cde9 from https://github.com/ispras/qemu/tree/rr-180725
  6460. ===== QEMU reverse debugging
  6461. TODO get working.
  6462. 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 link:https://github.com/ispras/qemu/tree/rr-180725[]:
  6463. ....
  6464. ./run --eval-after './linux/rand_check.out;./linux/poweroff.out;' --record
  6465. ./run --eval-after './linux/rand_check.out;./linux/poweroff.out;' --replay --gdb-wait
  6466. ....
  6467. On another shell:
  6468. ....
  6469. ./run-gdb start_kernel
  6470. ....
  6471. In GDB:
  6472. ....
  6473. n
  6474. n
  6475. n
  6476. n
  6477. reverse-continue
  6478. ....
  6479. and we are back at `start_kernel`
  6480. ==== QEMU trace multicore
  6481. TODO: is there any way to distinguish which instruction runs on each core? Doing:
  6482. ....
  6483. ./run --arch x86_64 --cpus 2 --eval './linux/poweroff.out' --trace exec_tb
  6484. ./qemu-trace2txt
  6485. ....
  6486. just appears to output both cores intertwined without any clear differentiation.
  6487. ==== gem5 tracing
  6488. gem5 provides also provides a tracing mechanism documented at: link:http://www.gem5.org/Trace_Based_Debugging[]:
  6489. ....
  6490. ./run --arch aarch64 --eval 'm5 exit' --emulator gem5 --trace Exec
  6491. less "$(./getvar --arch aarch64 run_dir)/trace.txt"
  6492. ....
  6493. Output the trace to stdout instead of a file:
  6494. ....
  6495. ./run \
  6496. --arch aarch64 \
  6497. --emulator gem5 \
  6498. --eval 'm5 exit' \
  6499. --trace ExecAll \
  6500. --trace-stdout \
  6501. ;
  6502. ....
  6503. We also have a shortcut for `--trace ExecAll -trace-stdout` with `--trace-insts-stdout`
  6504. ....
  6505. ./run \
  6506. --arch aarch64 \
  6507. --emulator gem5 \
  6508. --eval 'm5 exit' \
  6509. --trace-insts-stdout \
  6510. ;
  6511. ....
  6512. 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>>.
  6513. List all available debug flags:
  6514. ....
  6515. ./run --arch aarch64 --gem5-exe-args='--debug-help' --emulator gem5
  6516. ....
  6517. but to understand most of them you have to look at the source code:
  6518. ....
  6519. less "$(./getvar gem5_source_dir)/src/cpu/SConscript"
  6520. less "$(./getvar gem5_source_dir)/src/cpu/exetrace.cc"
  6521. ....
  6522. The traces are generated from `DPRINTF(<trace-id>` calls scattered throughout the code.
  6523. As can be seen on the `Sconstruct`, `Exec` is just an alias that enables a set of flags.
  6524. Be warned, the trace is humongous, at 16Gb.
  6525. 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.
  6526. Enabling tracing made the runtime about 4x slower on the <<p51>>, with or without `.gz` compression.
  6527. The output format is of type:
  6528. ....
  6529. 25007000: system.cpu T0 : @start_kernel : stp
  6530. 25007000: system.cpu T0 : @start_kernel.0 : addxi_uop ureg0, sp, #-112 : IntAlu : D=0xffffff8008913f90
  6531. 25007500: system.cpu T0 : @start_kernel.1 : strxi_uop x29, [ureg0] : MemWrite : D=0x0000000000000000 A=0xffffff8008913f90
  6532. 25008000: system.cpu T0 : @start_kernel.2 : strxi_uop x30, [ureg0, #8] : MemWrite : D=0x0000000000000000 A=0xffffff8008913f98
  6533. 25008500: system.cpu T0 : @start_kernel.3 : addxi_uop sp, ureg0, #0 : IntAlu : D=0xffffff8008913f90
  6534. ....
  6535. There are two types of lines:
  6536. * full instructions, as the first line. Only shown if the `ExecMacro` flag is given.
  6537. * micro ops that constitute the instruction, the lines that follow. Yes, `aarch64` also has microops: link:https://superuser.com/questions/934752/do-arm-processors-like-cortex-a9-use-microcode/934755#934755[]. Only shown if the `ExecMicro` flag is given.
  6538. Breakdown:
  6539. * `25007500`: time count in some unit. Note how the microops execute at further timestamps.
  6540. * `system.cpu`: distinguishes between CPUs when there are more than one
  6541. * `T0`: thread number. TODO: link:https://superuser.com/questions/133082/hyper-threading-and-dual-core-whats-the-difference/995858#995858[hyperthread]? How to play with it?
  6542. * `@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`.
  6543. * `.1` as in `@start_kernel.1`: index of the microop
  6544. * `stp`: instruction disassembly. Seems to use `.isa` files dispersed per arch, which is an in house format: http://gem5.org/ISA_description_system
  6545. * `strxi_uop x29, [ureg0]`: microop disassembly.
  6546. * `MemWrite : D=0x0000000000000000 A=0xffffff8008913f90`: a memory write microop:
  6547. ** `D` stands for data, and represents the value that was written to memory or to a register
  6548. ** `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.
  6549. The best way to verify all of this is to write some <<baremetal,baremetal code>>
  6550. Trace the source lines just like <<trace-source-lines,for QEMU>> with:
  6551. ....
  6552. ./trace-boot --arch aarch64 --emulator gem5
  6553. ./trace2line --arch aarch64 --emulator gem5
  6554. less "$(./getvar --arch aarch64 run_dir)/trace-lines.txt"
  6555. ....
  6556. 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?
  6557. === QEMU GUI is unresponsive
  6558. 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.
  6559. We have not managed to track this problem down yet, but the following workaround always works:
  6560. ....
  6561. Ctrl-Shift-U
  6562. Ctrl-C
  6563. root
  6564. ....
  6565. This started happening when we switched to building QEMU through Buildroot, and has not been observed on later Ubuntu.
  6566. Using text mode is another workaround if you don't need GUI features.
  6567. == gem5
  6568. Getting started at: <<gem5-buildroot-setup>>.
  6569. === gem5 vs QEMU
  6570. * advantages of gem5:
  6571. ** simulates a generic more realistic pipelined and optionally 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:
  6572. +
  6573. --
  6574. *** do much more realistic performance benchmarking with it, which makes absolutely no sense in QEMU, which is purely functional
  6575. *** make certain functional observations that are not possible in QEMU, e.g.:
  6576. **** 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.
  6577. **** spectre / meltdown:
  6578. ***** https://www.mail-archive.com/gem5-users@gem5.org/msg15319.html
  6579. ***** https://github.com/jlpresearch/gem5/tree/spectre-test
  6580. --
  6581. +
  6582. It is not of course truly cycle accurate, as that:
  6583. +
  6584. --
  6585. ** would require exposing proprietary information of the CPU designs: link:https://stackoverflow.com/questions/17454955/can-you-check-performance-of-a-program-running-with-qemu-simulator/33580850#33580850[]
  6586. ** would make the simulation even slower TODO confirm, by how much
  6587. --
  6588. +
  6589. but the approximation is reasonable.
  6590. +
  6591. 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.
  6592. ** 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
  6593. ** 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: <<arm-exception-level>>
  6594. * disadvantage of gem5: slower than QEMU, see: <<benchmark-linux-kernel-boot>>
  6595. +
  6596. This implies that the user base is much smaller, since no Android devs.
  6597. +
  6598. 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:
  6599. +
  6600. --
  6601. ** the documentation is more scarce
  6602. ** it takes longer to support new hardware features
  6603. --
  6604. +
  6605. Well, not that AOSP is that much better anyways.
  6606. * not sure: gem5 has BSD license while QEMU has GPL
  6607. +
  6608. This suits chip makers that want to distribute forks with secret IP to their customers.
  6609. +
  6610. On the other hand, the chip makers tend to upstream less, and the project becomes more crappy in average :-)
  6611. === gem5 run benchmark
  6612. OK, this is why we used gem5 in the first place, performance measurements!
  6613. Let's see how many cycles https://en.wikipedia.org/wiki/Dhrystone[Dhrystone], which Buildroot provides, takes for a few different input parameters.
  6614. First build Dhrystone into the root filesystem:
  6615. ....
  6616. ./build-buildroot --config 'BR2_PACKAGE_DHRYSTONE=y'
  6617. ....
  6618. Then, a flexible setup is demonstrated at:
  6619. ....
  6620. ./gem5-bench-dhrystone
  6621. cat out/gem5-bench-dhrystone.txt
  6622. ....
  6623. Source: link:gem5-bench-dhrystone[]
  6624. Sample output:
  6625. ....
  6626. n cycles
  6627. 1000 12898577
  6628. 10000 23441629
  6629. 100000 128428617
  6630. ....
  6631. so as expected, the Dhrystone run with a larger input parameter `100000` took more cycles than the ones with smaller input parameters.
  6632. The `gem5-stats` commands output the approximate number of CPU cycles it took Dhrystone to run.
  6633. Another interesting example can be found at: link:gem5-bench-cache[].
  6634. A more naive and simpler to understand approach would be a direct:
  6635. ....
  6636. ./run --arch aarch64 --emulator gem5 --eval 'm5 checkpoint;m5 resetstats;dhrystone 10000;m5 exit'
  6637. ....
  6638. but the problem is that this method does not allow to easily run a different script without running the boot again, see: <<gem5-restore-new-script>>.
  6639. Now you can play a fun little game with your friends:
  6640. * pick a computational problem
  6641. * make a program that solves the computation problem, and outputs output to stdout
  6642. * write the code that runs the correct computation in the smallest number of cycles possible
  6643. To find out why your program is slow, a good first step is to have a look at <<stats-txt>> file.
  6644. ==== Skip extra benchmark instructions
  6645. A few imperfections of our <<gem5-run-benchmark,benchmarking method>> are:
  6646. * 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
  6647. * 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?
  6648. Solutions to these problems include:
  6649. * modify benchmark code with instrumentation directly, see <<m5ops-instructions>> for an example.
  6650. * monitor known addresses TODO possible? Create an example.
  6651. 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
  6652. Those problems should be insignificant if the benchmark runs for long enough however.
  6653. ==== gem5 system parameters
  6654. Besides optimizing a program for a given CPU setup, chip developers can also do the inverse, and optimize the chip for a given benchmark!
  6655. The rabbit hole is likely deep, but let's scratch a bit of the surface.
  6656. ===== Number of cores
  6657. ....
  6658. ./run --arch arm --cpus 2 --emulator gem5
  6659. ....
  6660. Check with:
  6661. ....
  6662. cat /proc/cpuinfo
  6663. getconf _NPROCESSORS_CONF
  6664. ....
  6665. ====== gem5 arm more than 8 cores
  6666. https://stackoverflow.com/questions/50248067/how-to-run-a-gem5-arm-aarch64-full-system-simulation-with-fs-py-with-more-than-8
  6667. Build the kernel with the <<gem5-arm-linux-kernel-patches>>, and then run:
  6668. ....
  6669. ./run \
  6670. --arch aarch64 \
  6671. --linux-build-id gem5-v4.15 \
  6672. --emulator gem5 \
  6673. --cpus 16 \
  6674. -- \
  6675. --param 'system.realview.gic.gem5_extensions = True' \
  6676. ;
  6677. ....
  6678. ===== gem5 cache size
  6679. https://stackoverflow.com/questions/49624061/how-to-run-gem5-simulator-in-fs-mode-without-cache/49634544#49634544
  6680. A quick `+./run --emulator gem5 -- -h+` leads us to the options:
  6681. ....
  6682. --caches
  6683. --l1d_size=1024
  6684. --l1i_size=1024
  6685. --l2cache
  6686. --l2_size=1024
  6687. --l3_size=1024
  6688. ....
  6689. But keep in mind that it only affects benchmark performance of the most detailed CPU types:
  6690. [options="header"]
  6691. |===
  6692. |arch |CPU type |caches used
  6693. |X86
  6694. |`AtomicSimpleCPU`
  6695. |no
  6696. |X86
  6697. |`DerivO3CPU`
  6698. |?*
  6699. |ARM
  6700. |`AtomicSimpleCPU`
  6701. |no
  6702. |ARM
  6703. |`HPI`
  6704. |yes
  6705. |===
  6706. {empty}*: couldn't test because of:
  6707. * https://stackoverflow.com/questions/49011096/how-to-switch-cpu-models-in-gem5-after-restoring-a-checkpoint-and-then-observe-t
  6708. Cache sizes can in theory be checked with the methods described at: link:https://superuser.com/questions/55776/finding-l2-cache-size-in-linux[]:
  6709. ....
  6710. getconf -a | grep CACHE
  6711. lscpu
  6712. cat /sys/devices/system/cpu/cpu0/cache/index2/size
  6713. ....
  6714. but for some reason the Linux kernel is not seeing the cache sizes:
  6715. * https://stackoverflow.com/questions/49008792/why-doesnt-the-linux-kernel-see-the-cache-sizes-in-the-gem5-emulator-in-full-sy
  6716. * http://gem5-users.gem5.narkive.com/4xVBlf3c/verify-cache-configuration
  6717. Behaviour breakdown:
  6718. * arm QEMU and gem5 (both `AtomicSimpleCPU` or `HPI`), x86 gem5: `/sys` files don't exist, and `getconf` and `lscpu` value empty
  6719. * x86 QEMU: `/sys` files exist, but `getconf` and `lscpu` values still empty
  6720. So we take a performance measurement approach instead:
  6721. ....
  6722. ./gem5-bench-cache --arch aarch64
  6723. cat "$(./getvar --arch aarch64 run_dir)/bench-cache.txt"
  6724. ....
  6725. which gives:
  6726. ....
  6727. 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
  6728. time 23.82
  6729. exit_status 0
  6730. cycles 93284622
  6731. instructions 4393457
  6732. 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
  6733. time 14.91
  6734. exit_status 0
  6735. cycles 10128985
  6736. instructions 4211458
  6737. 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
  6738. time 51.87
  6739. exit_status 0
  6740. cycles 188803630
  6741. instructions 12401336
  6742. 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
  6743. time 35.35
  6744. exit_status 0
  6745. cycles 20715757
  6746. instructions 12192527
  6747. 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
  6748. time 339.07
  6749. exit_status 0
  6750. cycles 1176559936
  6751. instructions 94222791
  6752. 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
  6753. time 240.37
  6754. exit_status 0
  6755. cycles 125666679
  6756. instructions 91738770
  6757. ....
  6758. We make the following conclusions:
  6759. * 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?
  6760. * 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.
  6761. ===== gem5 memory latency
  6762. TODO These look promising:
  6763. ....
  6764. --list-mem-types
  6765. --mem-type=MEM_TYPE
  6766. --mem-channels=MEM_CHANNELS
  6767. --mem-ranks=MEM_RANKS
  6768. --mem-size=MEM_SIZE
  6769. ....
  6770. TODO: now to verify this with the Linux kernel? Besides raw performance benchmarks.
  6771. ===== Memory size
  6772. ....
  6773. ./run --arch arm --memory 512M
  6774. ....
  6775. and verify inside the guest with:
  6776. ....
  6777. free -m
  6778. ....
  6779. ===== gem5 disk and network latency
  6780. TODO These look promising:
  6781. ....
  6782. --ethernet-linkspeed
  6783. --ethernet-linkdelay
  6784. ....
  6785. and also: `gem5-dist`: https://publish.illinois.edu/icsl-pdgem5/
  6786. ===== gem5 clock frequency
  6787. Clock frequency: TODO how does it affect performance in benchmarks?
  6788. ....
  6789. ./run --arch aarch64 --emulator gem5 -- --cpu-clock 10000000
  6790. ....
  6791. Check with:
  6792. ....
  6793. m5 resetstats
  6794. sleep 10
  6795. m5 dumpstats
  6796. ....
  6797. and then:
  6798. ....
  6799. ./gem5-stat --arch aarch64
  6800. ....
  6801. TODO: why doesn't this exist:
  6802. ....
  6803. ls /sys/devices/system/cpu/cpu0/cpufreq
  6804. ....
  6805. ==== Interesting benchmarks
  6806. Buildroot built-in libraries, mostly under Libraries > Other:
  6807. * Armadillo `C++`: linear algebra
  6808. * fftw: Fourier transform
  6809. * Flann
  6810. * GSL: various
  6811. * liblinear
  6812. * libspacialindex
  6813. * libtommath
  6814. * qhull
  6815. There are not yet enabled, but it should be easy to so, see: <<add-new-buildroot-packages>>
  6816. ===== BST vs heap
  6817. https://stackoverflow.com/questions/6147242/heap-vs-binary-search-tree-bst/29548834#29548834
  6818. Usage:
  6819. ....
  6820. ./build-userland \
  6821. --arch aarch64 \
  6822. --ccflagg='-DLKMC_M5OPS_ENABLE=1' \
  6823. --force-build cpp/bst_vs_heap \
  6824. --static \
  6825. ;
  6826. ./run \
  6827. --arch aarch64 \
  6828. --emulator gem5 \
  6829. --static \
  6830. --userland userland/cpp/bst_vs_heap.cpp \
  6831. --userland-args='1000' \
  6832. ;
  6833. ./bst-vs-heap --arch aarch64 > bst_vs_heap.dat
  6834. ./bst-vs-heap.gnuplot
  6835. xdg-open bst-vs-heap.tmp.png
  6836. ....
  6837. Sources:
  6838. * link:userland/cpp/bst_vs_heap.cpp[]
  6839. * link:bst-vs-heap[]
  6840. * link:bst-vs-heap.gnuplot[]
  6841. Tested on e70103b9b32e6e33dbab9eaf2ff00c358f55d8db + 1 with the workaround patch mentioned at: <<fatal-kernel-too-old>>.
  6842. ===== BLAS
  6843. Buildroot supports it, which makes everything just trivial:
  6844. ....
  6845. ./build-buildroot --config 'BR2_PACKAGE_OPENBLAS=y'
  6846. ./build-userland --package openblas -- userland/libs/openblas/hello.c
  6847. ./run --eval-after './libs/openblas/hello.out; echo $?'
  6848. ....
  6849. Outcome: the test passes:
  6850. ....
  6851. 0
  6852. ....
  6853. Source: link:userland/libs/openblas/hello.c[]
  6854. The test performs a general matrix multiplication:
  6855. ....
  6856. | 1.0 -3.0 | | 1.0 2.0 1.0 | | 0.5 0.5 0.5 | | 11.0 - 9.0 5.0 |
  6857. 1 * | 2.0 4.0 | * | -3.0 4.0 -1.0 | + 2 * | 0.5 0.5 0.5 | = | - 9.0 21.0 -1.0 |
  6858. | 1.0 -1.0 | | 0.5 0.5 0.5 | | 5.0 - 1.0 3.0 |
  6859. ....
  6860. This can be deduced from the Fortran interfaces at
  6861. ....
  6862. less "$(./getvar buildroot_build_build_dir)"/openblas-*/reference/dgemmf.f
  6863. ....
  6864. which we can map to our call as:
  6865. ....
  6866. C := alpha*op( A )*op( B ) + beta*C,
  6867. SUBROUTINE DGEMMF( TRANA, TRANB, M,N,K, ALPHA,A,LDA,B,LDB,BETA,C,LDC)
  6868. cblas_dgemm( CblasColMajor, CblasNoTrans, CblasTrans,3,3,2 ,1, A,3, B,3, 2 ,C,3 );
  6869. ....
  6870. ===== Eigen
  6871. Header only linear algebra library with a mainline Buildroot package:
  6872. ....
  6873. ./build-buildroot --config 'BR2_PACKAGE_EIGEN=y'
  6874. ./build-userland --package eigen -- userland/libs/eigen/hello.cpp
  6875. ....
  6876. Just create an array and print it:
  6877. ....
  6878. ./run --eval-after './libs/eigen/hello.out'
  6879. ....
  6880. Output:
  6881. ....
  6882. 3 -1
  6883. 2.5 1.5
  6884. ....
  6885. Source: link:userland/libs/eigen/hello.cpp[]
  6886. This example just creates a matrix and prints it out.
  6887. Tested on: link:http://github.com/cirosantilli/linux-kernel-module-cheat/commit/a4bdcf102c068762bb1ef26c591fcf71e5907525[a4bdcf102c068762bb1ef26c591fcf71e5907525]
  6888. ===== PARSEC benchmark
  6889. We have ported parts of the link: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.
  6890. There are two ways to run PARSEC with this repo:
  6891. * <<parsec-benchmark-without-parsecmgmt,without `pasecmgmt`>>, most likely what you want
  6892. * <<parsec-benchmark-with-parsecmgmt,with `pasecmgmt`>>
  6893. ====== PARSEC benchmark without parsecmgmt
  6894. ....
  6895. ./build --arch arm --download-dependencies gem5-buildroot parsec-benchmark
  6896. ./build-buildroot --arch arm --config 'BR2_PACKAGE_PARSEC_BENCHMARK=y'
  6897. ./run --arch arm --emulator gem5
  6898. ....
  6899. Once inside the guest, launch one of the `test` input sized benchmarks manually as in:
  6900. ....
  6901. cd /parsec/ext/splash2x/apps/fmm/run
  6902. ../inst/arm-linux.gcc/bin/fmm 1 < input_1
  6903. ....
  6904. To find run out how to run many of the benchmarks, have a look at the `test.sh` script of the `parse-benchmark` repo.
  6905. From the guest, you can also run it as:
  6906. ....
  6907. cd /parsec
  6908. ./test.sh
  6909. ....
  6910. but this might be a bit time consuming in gem5.
  6911. ====== PARSEC change the input size
  6912. Running a benchmark of a size different than `test`, e.g. `simsmall`, requires a rebuild with:
  6913. ....
  6914. ./build-buildroot \
  6915. --arch arm \
  6916. --config 'BR2_PACKAGE_PARSEC_BENCHMARK=y' \
  6917. --config 'BR2_PACKAGE_PARSEC_BENCHMARK_INPUT_SIZE="simsmall"' \
  6918. -- parsec_benchmark-reconfigure \
  6919. ;
  6920. ....
  6921. Large input may also require tweaking:
  6922. * <<br2_target_rootfs_ext2_size>> if the unpacked inputs are large
  6923. * <<memory-size>>, unless you want to meet the OOM killer, which is admittedly kind of fun
  6924. `test.sh` only contains the run commands for the `test` size, and cannot be used for `simsmall`.
  6925. The easiest thing to do, is to link: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:
  6926. ....
  6927. 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
  6928. ....
  6929. and then tweak the command found in `test.sh` accordingly.
  6930. 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`).
  6931. The rebuild is required because we unpack input files on the host.
  6932. Separating input sizes also allows to create smaller images when only running the smaller benchmarks.
  6933. 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!
  6934. One option would be to do that inside the guest with QEMU.
  6935. Also, we can't generate all input sizes at once, because many of them have the same name and would overwrite one another...
  6936. PARSEC simply wasn't designed with non native machines in mind...
  6937. ====== PARSEC benchmark with parsecmgmt
  6938. Most users won't want to use this method because:
  6939. * running the `parsecmgmt` Bash scripts takes forever before it ever starts running the actual benchmarks on gem5
  6940. +
  6941. Running on QEMU is feasible, but not the main use case, since QEMU cannot be used for performance measurements
  6942. * 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)
  6943. It would be awesome if it were possible to use this method, since this is what Parsec supports officially, and so:
  6944. * you don't have to dig into what raw command to run
  6945. * there is an easy way to run all the benchmarks in one go to test them out
  6946. * you can just run any of the benchmarks that you want
  6947. but it simply is not feasible in gem5 because it takes too long.
  6948. If you still want to run this, try it out with:
  6949. ....
  6950. ./build-buildroot \
  6951. --arch aarch64 \
  6952. --config 'BR2_PACKAGE_PARSEC_BENCHMARK=y' \
  6953. --config 'BR2_PACKAGE_PARSEC_BENCHMARK_PARSECMGMT=y' \
  6954. --config 'BR2_TARGET_ROOTFS_EXT2_SIZE="3G"' \
  6955. -- parsec_benchmark-reconfigure \
  6956. ;
  6957. ....
  6958. And then you can run it just as you would on the host:
  6959. ....
  6960. cd /parsec/
  6961. bash
  6962. . env.sh
  6963. parsecmgmt -a run -p splash2x.fmm -i test
  6964. ....
  6965. ====== PARSEC uninstall
  6966. If you want to remove PARSEC later, Buildroot doesn't provide an automated package removal mechanism: <<remove-buildroot-packages>>, but the following procedure should be satisfactory:
  6967. ....
  6968. rm -rf \
  6969. "$(./getvar buildroot_download_dir)"/parsec-* \
  6970. "$(./getvar buildroot_build_dir)"/build/parsec-* \
  6971. "$(./getvar buildroot_build_dir)"/build/packages-file-list.txt \
  6972. "$(./getvar buildroot_build_dir)"/images/rootfs.* \
  6973. "$(./getvar buildroot_build_dir)"/target/parsec-* \
  6974. ;
  6975. ./build-buildroot --arch arm
  6976. ....
  6977. ====== PARSEC benchmark hacking
  6978. If you end up going inside link:submodules/parsec-benchmark[] to hack up the benchmark (you will!), these tips will be helpful.
  6979. 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.
  6980. A few workarounds are:
  6981. * develop in host first as much as you can. Our PARSEC fork supports it.
  6982. +
  6983. If you do this, don't forget to do a:
  6984. +
  6985. ....
  6986. cd "$(./getvar parsec_source_dir)"
  6987. git clean -xdf .
  6988. ....
  6989. before going for the cross compile build.
  6990. +
  6991. * patch Buildroot to work well, and keep cross compiling all the way. This should be totally viable, and we should do it.
  6992. +
  6993. Don't forget to explicitly rebuild PARSEC with:
  6994. +
  6995. ....
  6996. ./build-buildroot \
  6997. --arch arm \
  6998. --config 'BR2_PACKAGE_PARSEC_BENCHMARK=y' \
  6999. -- parsec_benchmark-reconfigure \
  7000. ;
  7001. ....
  7002. +
  7003. You may also want to test if your patches are still functionally correct inside of QEMU first, which is a faster emulator.
  7004. * 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
  7005. === gem5 kernel command line parameters
  7006. Analogous <<kernel-command-line-parameters,to QEMU>>:
  7007. ....
  7008. ./run --arch arm --kernel-cli 'init=/lkmc/linux/poweroff.out' --emulator gem5
  7009. ....
  7010. Internals: when we give `--command-line=` to gem5, it overrides default command lines, including some mandatory ones which are required to boot properly.
  7011. Our run script hardcodes the require options in the default `--command-line` and appends extra options given by `-e`.
  7012. To find the default options in the first place, we removed `--command-line` and ran:
  7013. ....
  7014. ./run --arch arm --emulator gem5
  7015. ....
  7016. and then looked at the line of the Linux kernel that starts with:
  7017. ....
  7018. Kernel command line:
  7019. ....
  7020. [[gem5-gdb]]
  7021. === gem5 GDB step debug
  7022. ==== gem5 GDB step debug kernel
  7023. Analogous <<gdb,to QEMU>>, on the first shell:
  7024. ....
  7025. ./run --arch arm --emulator gem5 --gdb-wait
  7026. ....
  7027. On the second shell:
  7028. ....
  7029. ./run-gdb --arch arm --emulator gem5
  7030. ....
  7031. On a third shell:
  7032. ....
  7033. ./gem5-shell
  7034. ....
  7035. When you want to break, just do a `Ctrl-C` on GDB shell, and then `continue`.
  7036. And we now see the boot messages, and then get a shell. Now try the `./count.sh` procedure described for QEMU: <<gdb-step-debug-kernel-post-boot>>.
  7037. ==== gem5 GDB step debug userland process
  7038. We are unable to use `gdbserver` because of networking: <<gem5-host-to-guest-networking>>
  7039. The alternative is to do as in <<gdb-step-debug-userland-processes>>.
  7040. Next, follow the exact same steps explained at <<gdb-step-debug-userland-non-init-without--d>>, but passing `-g` to every command as usual.
  7041. But then TODO (I'll still go crazy one of those days): for `arm`, while debugging `./linux/myinsmod.out hello.ko`, after then line:
  7042. ....
  7043. 23 if (argc < 3) {
  7044. 24 params = "";
  7045. ....
  7046. 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.
  7047. TODO:
  7048. ....
  7049. ./run-gdb-user --arch arm --emulator gem5 gem5-1.0/gem5/util/m5/m5 main
  7050. ....
  7051. breaks when `m5` is run on guest, but does not show the source code.
  7052. === gem5 checkpoint
  7053. 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.
  7054. Documentation: http://gem5.org/Checkpoints
  7055. ....
  7056. ./run --arch arm --emulator gem5
  7057. ....
  7058. In the guest, wait for the boot to end and run:
  7059. ....
  7060. m5 checkpoint
  7061. ....
  7062. where <<m5>> is a guest utility present inside the gem5 tree which we cross-compiled and installed into the guest.
  7063. To restore the checkpoint, kill the VM and run:
  7064. ....
  7065. ./run --arch arm --emulator gem5 --gem5-restore 1
  7066. ....
  7067. The `--gem5-restore` option restores the checkpoint that was created most recently.
  7068. Let's create a second checkpoint to see how it works, in guest:
  7069. ....
  7070. date >f
  7071. m5 checkpoint
  7072. ....
  7073. Kill the VM, and try it out:
  7074. ....
  7075. ./run --arch arm --emulator gem5 --gem5-restore 1
  7076. ....
  7077. Here we use `--gem5-restore 1` again, since the second snapshot we took is now the most recent one
  7078. Now in the guest:
  7079. ....
  7080. cat f
  7081. ....
  7082. 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.
  7083. If you automate things with <<kernel-command-line-parameters>> as in:
  7084. ....
  7085. ./run --arch arm --eval 'm5 checkpoint;m5 resetstats;dhrystone 1000;m5 exit' --emulator gem5
  7086. ....
  7087. Then there is no need to pass the kernel command line again to gem5 for replay:
  7088. ....
  7089. ./run --arch arm --emulator gem5 --gem5-restore 1
  7090. ....
  7091. since boot has already happened, and the parameters are already in the RAM of the snapshot.
  7092. ==== gem5 checkpoint internals
  7093. Checkpoints are stored inside the <<m5out-directory>> at:
  7094. ....
  7095. "$(./getvar --emulator gem5 m5out_dir)/cpt.<checkpoint-time>"
  7096. ....
  7097. where `<checkpoint-time>` is the cycle number at which the checkpoint was taken.
  7098. `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
  7099. 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.
  7100. Therefore, just use our superior `--gem5-restore` flag, which uses directory timestamps to determine which checkpoint you created most recently.
  7101. 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.
  7102. [[gem5-restore-new-script]]
  7103. ==== gem5 checkpoint restore and run a different script
  7104. You want to automate running several tests from a single pristine post-boot state.
  7105. The problem is that boot takes forever, and after the checkpoint, the memory and disk states are fixed, so you can't for example:
  7106. * hack up an existing rc script, since the disk is fixed
  7107. * inject new kernel boot command line options, since those have already been put into memory by the bootloader
  7108. There is however a few loopholes, <<m5-readfile>> being the simplest, as it reads whatever is present on the host.
  7109. So we can do it like:
  7110. ....
  7111. # Boot, checkpoint and exit.
  7112. printf 'echo "setup run";m5 exit' > "$(./getvar gem5_readfile)"
  7113. ./run --emulator gem5 --eval 'm5 checkpoint;m5 readfile > a.sh;sh a.sh'
  7114. # Restore and run the first benchmark.
  7115. printf 'echo "first benchmark";m5 exit' > "$(./getvar gem5_readfile)"
  7116. ./run --emulator gem5 --gem5-restore 1
  7117. # Restore and run the second benchmark.
  7118. printf 'echo "second benchmark";m5 exit' > "$(./getvar gem5_readfile)"
  7119. ./run --emulator gem5 --gem5-restore 1
  7120. # If something weird happened, create an interactive shell to examine the system.
  7121. printf 'sh' > "$(./getvar gem5_readfile)"
  7122. ./run --emulator gem5 --gem5-restore 1
  7123. ....
  7124. Since this is such a common setup, we provide some helpers for it as described at <<gem5-run-benchmark>>:
  7125. * link:rootfs_overlay/lkmc/gem5.sh[]. This script is analogous to gem5's in-tree link:https://github.com/gem5/gem5/blob/2b4b94d0556c2d03172ebff63f7fc502c3c26ff8/configs/boot/hack_back_ckpt.rcS[hack_back_ckpt.rcS], but with less noise.
  7126. * `./run --gem5-readfile` is a convenient way to set the `m5 readfile`
  7127. Other loophole possibilities include:
  7128. * <<9p>>
  7129. * <<secondary-disk>>
  7130. * `expect` as mentioned at: https://stackoverflow.com/questions/7013137/automating-telnet-session-using-bash-scripts
  7131. +
  7132. ....
  7133. #!/usr/bin/expect
  7134. spawn telnet localhost 3456
  7135. expect "# $"
  7136. send "pwd\r"
  7137. send "ls /\r"
  7138. send "m5 exit\r"
  7139. expect eof
  7140. ....
  7141. +
  7142. This is ugly however as it is not deterministic.
  7143. https://www.mail-archive.com/gem5-users@gem5.org/msg15233.html
  7144. ==== gem5 restore checkpoint with a different CPU
  7145. gem5 can switch to a different CPU model when restoring a checkpoint.
  7146. 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.
  7147. An illustrative interactive run:
  7148. ....
  7149. ./run --arch arm --emulator gem5
  7150. ....
  7151. In guest:
  7152. ....
  7153. m5 checkpoint
  7154. ....
  7155. And then restore the checkpoint with a different CPU:
  7156. ....
  7157. ./run --arch arm --emulator gem5 --gem5-restore 1 -- --caches --restore-with-cpu=HPI
  7158. ....
  7159. === Pass extra options to gem5
  7160. Pass options to the `fs.py` script:
  7161. * get help:
  7162. +
  7163. ....
  7164. ./run --emulator gem5 -- -h
  7165. ....
  7166. * boot with the more detailed and slow `HPI` CPU model:
  7167. +
  7168. ....
  7169. ./run --arch arm --emulator gem5 -- --caches --cpu-type=HPI
  7170. ....
  7171. Pass options to the `gem5` executable itself:
  7172. * get help:
  7173. +
  7174. ....
  7175. ./run --gem5-exe-args='-h' --emulator gem5
  7176. ....
  7177. === gem5 exit after a number of instructions
  7178. Quit the simulation after `1024` instructions:
  7179. ....
  7180. ./run --emulator gem5 -- -I 1024
  7181. ....
  7182. Can be nicely checked with <<gem5-tracing>>.
  7183. Cycles instead of instructions:
  7184. ....
  7185. ./run --emulator gem5 -- --memory 1024
  7186. ....
  7187. Otherwise the simulation runs forever by default.
  7188. === m5ops
  7189. m5ops are magic instructions which lead gem5 to do magic things, like quitting or dumping stats.
  7190. Documentation: http://gem5.org/M5ops
  7191. There are two main ways to use m5ops:
  7192. * <<m5>>
  7193. * <<m5ops-instructions>>
  7194. `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.
  7195. `m5` cannot should / should not be used however:
  7196. * in bare metal setups
  7197. * 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.
  7198. +
  7199. Why not just hardcode some <<m5ops-instructions>> as in our example instead, since you are going to modify the source of the benchmark anyways?
  7200. ==== m5
  7201. `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>>
  7202. Its source is present in the gem5 tree: https://github.com/gem5/gem5/blob/6925bf55005c118dc2580ba83e0fa10b31839ef9/util/m5/m5.c
  7203. It is possible to guess what most tools do from the corresponding <<m5ops>>, but let's at least document the less obvious ones here.
  7204. ===== m5 exit
  7205. End the simulation.
  7206. Sane Python scripts will exit gem5 with status 0, which is what `fs.py` does.
  7207. ===== m5 fail
  7208. End the simulation with a failure exit event:
  7209. ....
  7210. m5 fail 1
  7211. ....
  7212. 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:
  7213. ....
  7214. Simulated exit code not 0! Exit code is 1
  7215. ....
  7216. and exits with status 0.
  7217. We then parse that string ourselves in link:run[] and exit with the correct status...
  7218. 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
  7219. `m5 fail` is just a superset of `m5 exit`, which is just:
  7220. ....
  7221. m5 fail 0
  7222. ....
  7223. as can be seen from the source: https://github.com/gem5/gem5/blob/50a57c0376c02c912a978c4443dd58caebe0f173/src/sim/pseudo_inst.cc#L303
  7224. ===== m5 writefile
  7225. Send a guest file to the host. <<9p>> is a more advanced alternative.
  7226. Guest:
  7227. ....
  7228. echo mycontent > myfileguest
  7229. m5 writefile myfileguest myfilehost
  7230. ....
  7231. Host:
  7232. ....
  7233. cat "$(./getvar --arch aarch64 --emulator gem5 m5out_dir)/myfilehost"
  7234. ....
  7235. Does not work for subdirectories, gem5 crashes:
  7236. ....
  7237. m5 writefile myfileguest mydirhost/myfilehost
  7238. ....
  7239. ===== m5 readfile
  7240. Read a host file pointed to by the `fs.py --script` option to stdout.
  7241. https://stackoverflow.com/questions/49516399/how-to-use-m5-readfile-and-m5-execfile-in-gem5/49538051#49538051
  7242. Host:
  7243. ....
  7244. date > "$(./getvar gem5_readfile)"
  7245. ....
  7246. Guest:
  7247. ....
  7248. m5 readfile
  7249. ....
  7250. Outcome: date shows on guest.
  7251. ===== m5 initparam
  7252. Ermm, just another <<m5-readfile>> that only takes integers and only from CLI options? Is this software so redundant?
  7253. Host:
  7254. ....
  7255. ./run --emulator gem5 --gem5-restore 1 -- --initparam 13
  7256. ./run --emulator gem5 --gem5-restore 1 -- --initparam 42
  7257. ....
  7258. Guest:
  7259. ....
  7260. m5 initparm
  7261. ....
  7262. Outputs the given paramter.
  7263. ===== m5 execfile
  7264. Trivial combination of `m5 readfile` + execute the script.
  7265. Host:
  7266. ....
  7267. printf '#!/bin/sh
  7268. echo asdf
  7269. ' > "$(./getvar gem5_readfile)"
  7270. ....
  7271. Guest:
  7272. ....
  7273. touch /tmp/execfile
  7274. chmod +x /tmp/execfile
  7275. m5 execfile
  7276. ....
  7277. Outcome:
  7278. ....
  7279. adsf
  7280. ....
  7281. ==== m5ops instructions
  7282. gem5 allocates some magic instructions on unused instruction encodings for convenient guest instrumentation.
  7283. Those instructions are exposed through the <<m5>> in tree executable.
  7284. To make things simpler to understand, you can play around with our own minimized educational `m5` subset link:userland/c/m5ops.c[].
  7285. 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.
  7286. To use that file, first rebuild `m5ops.out` with the m5ops instructions enabled and install it on the root filesystem:
  7287. ....
  7288. ./build-userland \
  7289. --arch aarch64 \
  7290. --ccflags='-DLKMC_M5OPS_ENABLE=1' \
  7291. --force-build c/m5ops \
  7292. --static \
  7293. ;
  7294. ./build-buildroot --arch aarch64
  7295. ....
  7296. 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.
  7297. Then, from inside <<gem5-buildroot-setup>>, test it out with:
  7298. ....
  7299. # checkpoint
  7300. ./c/m5ops.out c
  7301. # dumpstats
  7302. ./c/m5ops.out d
  7303. # exit
  7304. ./c/m5ops.out e
  7305. # dump resetstats
  7306. ./c/m5ops.out r
  7307. ....
  7308. In theory, the cleanest way to add m5ops to your benchmarks would be to do exactly what the `m5` tool does:
  7309. * include link:https://github.com/gem5/gem5/blob/05c4c2b566ce351ab217b2bd7035562aa7a76570/include/gem5/asm/generic/m5ops.h[`include/gem5/asm/generic/m5ops.h`]
  7310. * link with the `.o` file under `util/m5` for the correct arch, e.g. `m5op_arm_A64.o` for aarch64.
  7311. 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`.
  7312. Related: https://www.mail-archive.com/gem5-users@gem5.org/msg15418.html
  7313. ===== m5ops instructions interface
  7314. Let's study how <<m5>> uses them:
  7315. * link: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
  7316. * link: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
  7317. * link: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.
  7318. We notice that there are two different implementations for each arch:
  7319. * magic instructions, which don't exist in the corresponding arch
  7320. * magic memory addresses on a given page
  7321. 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.
  7322. Then, in aarch64 magic instructions for example, the lines:
  7323. ....
  7324. .macro m5op_func, name, func, subfunc
  7325. .globl \name
  7326. \name:
  7327. .long 0xff000110 | (\func << 16) | (\subfunc << 12)
  7328. ret
  7329. ....
  7330. define a simple function function for each m5op. Here we see that:
  7331. * `0xff000110` is a base mask for the magic non-existing instruction
  7332. * `\func` and `\subfunc` are OR-applied on top of the base mask, and define m5op this is.
  7333. +
  7334. Those values will loop over the magic constants defined in `m5ops.h` with the deferred preprocessor idiom.
  7335. +
  7336. For example, `exit` is `0x21` due to:
  7337. +
  7338. ....
  7339. #define M5OP_EXIT 0x21
  7340. ....
  7341. Finally, `m5.c` calls the defined functions as in:
  7342. ....
  7343. m5_exit(ints[0]);
  7344. ....
  7345. 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 link:https://en.wikipedia.org/wiki/Calling_convention#ARM_(A64)[aarch64 calling convention].
  7346. Keep in mind that for all archs, `m5.c` does the calls with 64-bit integers:
  7347. ....
  7348. uint64_t ints[2] = {0,0};
  7349. parse_int_args(argc, argv, ints, argc);
  7350. m5_fail(ints[1], ints[0]);
  7351. ....
  7352. Therefore, for example:
  7353. * aarch64 uses `x0` for the first argument and `x1` for the second, since each is 64 bits log already
  7354. * arm uses `r0` and `r1` for the first argument, and `r2` and `r3` for the second, since each register is only 32 bits long
  7355. That convention specifies that `x0` to `x7` contain the function arguments, so `x0` contains the first argument, and `x1` the second.
  7356. In our `m5ops` example, we just hardcode everything in the assembly one-liners we are producing.
  7357. We ignore the `\subfunc` since it is always 0 on the ops that interest us.
  7358. ===== m5op annotations
  7359. `include/gem5/asm/generic/m5ops.h` also describes some annotation instructions.
  7360. What they mean: https://stackoverflow.com/questions/50583962/what-are-the-gem5-annotations-mops-magic-instructions-and-how-to-use-them
  7361. === gem5 arm Linux kernel patches
  7362. 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.
  7363. The patches are optional: the vanilla kernel does boot. But they add some interesting gem5-specific optimizations, instrumentations and device support.
  7364. The patches also <<notable-alternate-gem5-kernel-configs,add defconfigs>> that are known to work well with gem5.
  7365. E.g. for arm v4.9 there is: link:https://gem5.googlesource.com/arm/linux/+/917e007a4150d26a0aa95e4f5353ba72753669c7/arch/arm/configs/gem5_defconfig[].
  7366. In order to use those patches and their associated configs, and, we recommend using <<linux-kernel-build-variants>> as:
  7367. ....
  7368. git -C "$(./getvar linux_source_dir)" fetch https://gem5.googlesource.com/arm/linux gem5/v4.15:gem5/v4.15
  7369. git -C "$(./getvar linux_source_dir)" checkout gem5/v4.15
  7370. ./build-linux \
  7371. --arch aarch64 \
  7372. --custom-config-file-gem5 \
  7373. --linux-build-id gem5-v4.15 \
  7374. ;
  7375. git -C "$(./getvar linux_source_dir)" checkout -
  7376. ./run \
  7377. --arch aarch64 \
  7378. --emulator gem5 \
  7379. --linux-build-id gem5-v4.15 \
  7380. ;
  7381. ....
  7382. QEMU also boots that kernel successfully:
  7383. ....
  7384. ./run \
  7385. --arch aarch64 \
  7386. --linux-build-id gem5-v4.15 \
  7387. ;
  7388. ....
  7389. but glibc kernel version checks make init fail with:
  7390. ....
  7391. FATAL: kernel too old
  7392. ....
  7393. because that kernel version is too old.
  7394. 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:
  7395. * `drm: Add component-aware simple encoder` allows you to see images through VNC: <<gem5-graphic-mode>>
  7396. * `gem5: Add support for gem5's extended GIC mode` adds support for more than 8 cores: <<gem5-arm-more-than-8-cores>>
  7397. Tested on 649d06d6758cefd080d04dc47fd6a5a26a620874 + 1.
  7398. ==== gem5 arm Linux kernel patches boot speedup
  7399. We have observed that with the kernel patches, boot is 2x faster, falling from 1m40s to 50s.
  7400. With link: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:
  7401. ....
  7402. clocksource: Switched to clocksource arch_sys_counter
  7403. ....
  7404. 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.
  7405. === m5out directory
  7406. When you run gem5, it generates an `m5out` directory at:
  7407. ....
  7408. echo $(./getvar --arch arm --emulator gem5 m5out_dir)"
  7409. ....
  7410. The location of that directory can be set with `./gem5.opt -d`, and defaults to `./m5out`.
  7411. The files in that directory contains some very important information about the run, and you should become familiar with every one of them.
  7412. ==== system.terminal
  7413. Contains UART output, both from the Linux kernel or from the baremetal system.
  7414. Can also be seen live on <<m5term>>.
  7415. ==== stats.txt
  7416. This file contains important statistics about the run:
  7417. ....
  7418. cat "$(./getvar --arch aarch64 m5out_dir)/stats.txt"
  7419. ....
  7420. Whenever we run `m5 dumpstats` or `m5 exit`, a section with the following format is added to that file:
  7421. ....
  7422. ---------- Begin Simulation Statistics ----------
  7423. [the stats]
  7424. ---------- End Simulation Statistics ----------
  7425. ....
  7426. That file contains several important execution metrics, e.g. number of cycles and several types of cache misses:
  7427. ....
  7428. system.cpu.numCycles
  7429. system.cpu.dtb.inst_misses
  7430. system.cpu.dtb.inst_hits
  7431. ....
  7432. For x86, it is interesting to try and correlate `numCycles` with:
  7433. ==== config.ini
  7434. The `config.ini` file, contains a very good high level description of the system:
  7435. ....
  7436. less $(./getvar --arch arm --emulator gem5 m5out_dir)"
  7437. ....
  7438. That file contains a tree representation of the system, sample excerpt:
  7439. ....
  7440. [root]
  7441. type=Root
  7442. children=system
  7443. full_system=true
  7444. [system]
  7445. type=ArmSystem
  7446. children=cpu cpu_clk_domain
  7447. auto_reset_addr_64=false
  7448. semihosting=Null
  7449. [system.cpu]
  7450. type=AtomicSimpleCPU
  7451. children=dstage2_mmu dtb interrupts isa istage2_mmu itb tracer
  7452. branchPred=Null
  7453. [system.cpu_clk_domain]
  7454. type=SrcClockDomain
  7455. clock=500
  7456. ....
  7457. Each node has:
  7458. * a list of child nodes, e.g. `system` is a child of `root`, and both `cpu` and `cpu_clk_domain` are children of `system`
  7459. * a list of parameters, e.g. `system.semihosting` is `Null`, which means that <<semihosting>> was turned off
  7460. ** the `type` parameter shows is present on every node, and it maps to a `Python` object that inherits from `SimObject`.
  7461. +
  7462. For example, `AtomicSimpleCPU` maps is defined at link:https://github.com/gem5/gem5/blob/05c4c2b566ce351ab217b2bd7035562aa7a76570/src/cpu/simple/AtomicSimpleCPU.py#L45[src/cpu/simple/AtomicSimpleCPU.py].
  7463. You can also get a simplified graphical view of the tree with:
  7464. ....
  7465. xdg-open "$(./getvar --arch arm --emulator gem5 m5out_dir)/config.dot.pdf"
  7466. ....
  7467. Modifying the `config.ini` file manually does nothing since it gets overwritten every time.
  7468. Set custom configs with the `--param` option of `fs.py`, e.g. we can make gem5 wait for GDB to connect with:
  7469. ....
  7470. fs.py --param 'system.cpu[0].wait_for_remote_gdb = True'
  7471. ....
  7472. 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[].
  7473. === m5term
  7474. We use the `m5term` in-tree executable to connect to the terminal instead of a direct `telnet`.
  7475. If you use `telnet` directly, it mostly works, but certain interactive features don't, e.g.:
  7476. * up and down arrows for history navigation
  7477. * tab to complete paths
  7478. * `Ctrl-C` to kill processes
  7479. TODO understand in detail what `m5term` does differently than `telnet`.
  7480. === gem5 Python scripts without rebuild
  7481. We have made a crazy setup that allows you to just `cd` into `submodules/gem5`, and edit Python scripts directly there.
  7482. 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.
  7483. So if you modified the Python scripts with this setup, you would still need to `./build` to copy the modified files over.
  7484. For gem5 specifically however, we have hacked up the build so that we `cd` into the `submodules/gem5` tree, and then do an link:https://stackoverflow.com/questions/54343515/how-to-build-gem5-out-of-tree/54343516#54343516[out of tree] build to `out/common/gem5`.
  7485. 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.
  7486. Using Buildroot for gem5 is still convenient because we use it to:
  7487. * to cross build `m5` for us
  7488. * check timestamps and skip the gem5 build when it is not requested
  7489. 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.
  7490. === gem5 fs_bigLITTLE
  7491. By default, we use `configs/example/fs.py` script.
  7492. The `--gem5-script biglittle` option enables the alternative `configs/example/arm/fs_bigLITTLE.py` script instead.
  7493. First apply:
  7494. ....
  7495. patch -d "$(./getvar gem5_source_dir)" -p 1 < patches/manual/gem5-biglittle.patch
  7496. ....
  7497. then:
  7498. ....
  7499. ./run --arch aarch64 --emulator gem5 --gem5-script biglittle
  7500. ....
  7501. Advantages over `fs.py`:
  7502. * more representative of mobile ARM SoCs, which almost always have big little cluster
  7503. * simpler than `fs.py`, and therefore easier to understand and modify
  7504. Disadvantages over `fs.py`:
  7505. * only works for ARM, not other archs
  7506. * not as many configuration options as `fs.py`, many things are hardcoded
  7507. 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 <<config-ini>> does show that the two big ones are `DerivO3CPU` and the small ones are `MinorCPU`.
  7508. 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.
  7509. Tested on: link:http://github.com/cirosantilli/linux-kernel-module-cheat/commit/18c1c823feda65f8b54cd38e261c282eee01ed9f[18c1c823feda65f8b54cd38e261c282eee01ed9f]
  7510. === gem5 unit tests
  7511. https://stackoverflow.com/questions/52279971/how-to-run-the-gem5-unit-tests
  7512. These are just very small GTest tests that test a single class in isolation, they don't run any executables.
  7513. Build the unit tests and run them:
  7514. ....
  7515. ./build-gem5 --unit-tests
  7516. ....
  7517. 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.:
  7518. ....
  7519. /path/to/build/ARM/base/circlebuf.test.opt --gtest_output=xml:/path/to/build/ARM/unittests.opt/base/circlebuf.test.xml
  7520. [==========] Running 4 tests from 1 test case.
  7521. [----------] Global test environment set-up.
  7522. [----------] 4 tests from CircleBufTest
  7523. [ RUN ] CircleBufTest.BasicReadWriteNoOverflow
  7524. [ OK ] CircleBufTest.BasicReadWriteNoOverflow (0 ms)
  7525. [ RUN ] CircleBufTest.SingleWriteOverflow
  7526. [ OK ] CircleBufTest.SingleWriteOverflow (0 ms)
  7527. [ RUN ] CircleBufTest.MultiWriteOverflow
  7528. [ OK ] CircleBufTest.MultiWriteOverflow (0 ms)
  7529. [ RUN ] CircleBufTest.PointerWrapAround
  7530. [ OK ] CircleBufTest.PointerWrapAround (0 ms)
  7531. [----------] 4 tests from CircleBufTest (0 ms total)
  7532. [----------] Global test environment tear-down
  7533. [==========] 4 tests from 1 test case ran. (0 ms total)
  7534. [ PASSED ] 4 tests.
  7535. ....
  7536. so you can just copy paste the command.
  7537. Building individual tests is possible with:
  7538. ....
  7539. ./build-gem5 --unit-test base/circlebuf.test
  7540. ....
  7541. This does not run the test however.
  7542. 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`.
  7543. Running the larger regression tests is exposed with:
  7544. ....
  7545. ./build-gem5 --regression-test quick/fs
  7546. ....
  7547. but TODO: those require magic blobs on `M5_PATH` that we don't currently automate.
  7548. === gem5 clang build
  7549. TODO test properly, benchmark vs GCC.
  7550. ....
  7551. sudo apt-get install clang
  7552. ./build-gem5 --clang
  7553. ./run --clang --emulator gem5
  7554. ....
  7555. == Buildroot
  7556. === Introduction to Buildroot
  7557. link:https://en.wikipedia.org/wiki/Buildroot[Buildroot] is a set of Make scripts that download and compile from source compatible versions of:
  7558. * GCC
  7559. * Linux kernel
  7560. * C standard library: Buildroot supports several implementations, see: <<libc-choice>>
  7561. * link:https://en.wikipedia.org/wiki/BusyBox[BusyBox]: provides the shell and basic command line utilities
  7562. It therefore produces a pristine, blob-less, debuggable setup, where all moving parts are configured to work perfectly together.
  7563. Perhaps the awesomeness of Buildroot only sinks in once you notice that all it takes is 4 commands as explained at https://stackoverflow.com/questions/47557262/how-to-download-the-torvalds-linux-kernel-master-recompile-it-and-boot-it-wi/49349237#49349237
  7564. ....
  7565. git clone https://github.com/buildroot/buildroot
  7566. cd buildroot
  7567. git checkout 2018.02
  7568. make qemu_aarch64_virt_defconfig
  7569. make olddefconfig
  7570. time make BR2_JLEVEL="$(nproc)"
  7571. qemu-system-aarch64 -M virt -cpu cortex-a57 -nographic -smp 1 -kernel output/images/Image -append "root=/dev/vda console=ttyAMA0" -netdev user,id=eth0 -device virtio-net-device,netdev=eth0 -drive file=output/images/rootfs.ext4,if=none,format=raw,id=hd0 -device virtio-blk-device,drive=hd0
  7572. ....
  7573. This repo basically wraps around that, and tries to make everything even more awesome for kernel developers.
  7574. The downsides of Buildroot are:
  7575. * the first build takes a while, but it is well worth it
  7576. * 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.
  7577. +
  7578. In theory, any software can be packaged, and the Buildroot side is easy.
  7579. +
  7580. The hard part is dealing with crappy third party build systems and huge dependency chains.
  7581. === Custom Buildroot configs
  7582. We provide the following mechanisms:
  7583. * `./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[].
  7584. * `./build-buildroot --config 'BR2_SOME_OPTION="myval"'`: append a single option to a single build.
  7585. For example, if you decide to <<enable-buildroot-compiler-optimizations>> after an initial build is finished, you must <<clean-the-build>> and rebuild:
  7586. ....
  7587. ./build-buildroot \
  7588. --config 'BR2_OPTIMIZE_3=y' \
  7589. --config 'BR2_PACKAGE_SAMPLE_PACKAGE=y' \
  7590. --
  7591. sample_package-dirclean \
  7592. sample_package-reconfigure \
  7593. ;
  7594. ....
  7595. as explained at: https://buildroot.org/downloads/manual/manual.html#rebuild-pkg
  7596. The clean is necessary because the source files didn't change, so `make` would just check the timestamps and not build anything.
  7597. You will then likely want to make those more permanent with: <<default-command-line-arguments>>
  7598. ==== Enable Buildroot compiler optimizations
  7599. If you are benchmarking compiled programs instead of hand written assembly, remember that we configure Buildroot to disable optimizations by default with:
  7600. ....
  7601. BR2_OPTIMIZE_0=y
  7602. ....
  7603. to improve the debugging experience.
  7604. You will likely want to change that to:
  7605. ....
  7606. BR2_OPTIMIZE_3=y
  7607. ....
  7608. Our link:kernel_modules/user[] package correctly forwards the Buildroot options to the build with `$(TARGET_CONFIGURE_OPTS)`, so you don't have to do any extra work.
  7609. Don't forget to do that if you are <<add-new-buildroot-packages,adding a new package>> with your own build system.
  7610. Then, you have two choices:
  7611. * 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: <<custom-buildroot-configs>>
  7612. +
  7613. ....
  7614. ./build-buildroot \
  7615. --config 'BR2_OPTIMIZE_3=y' \
  7616. --config 'BR2_PACKAGE_SAMPLE_PACKAGE=y' \
  7617. -- \
  7618. sample_package-dirclean \
  7619. sample_package-reconfigure \
  7620. ;
  7621. ....
  7622. +
  7623. However, this approach might not be representative since calls to an unoptimized libc and other libraries will have a negative performance impact.
  7624. +
  7625. Maybe you can get away with rebuilding libc, but I'm not sure that it will work properly.
  7626. +
  7627. Kernel-wise it should be fine though due to: <<kernel-o0>>
  7628. * <<clean-the-build,clean the build>> and rebuild from scratch:
  7629. +
  7630. ....
  7631. mv out out~
  7632. ./build-buildroot --config 'BR2_OPTIMIZE_3=y'
  7633. ....
  7634. === Find Buildroot options with make menuconfig
  7635. `make menuconfig` is a convenient way to find Buildroot configurations:
  7636. ....
  7637. cd "$(./getvar buildroot_build_dir)"
  7638. make menuconfig
  7639. ....
  7640. Hit `/` and search for the settings.
  7641. Save and quit.
  7642. ....
  7643. diff -u .config.olg .config
  7644. ....
  7645. Then copy and paste the diff additions to link:buildroot_config/default[] to make them permanent.
  7646. === Change user
  7647. At startup, we login automatically as the `root` user.
  7648. 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:
  7649. ....
  7650. login user0
  7651. ....
  7652. and password:
  7653. ....
  7654. a
  7655. ....
  7656. Then test that the user changed with:
  7657. ....
  7658. id
  7659. ....
  7660. which gives:
  7661. ....
  7662. uid=1000(user0) gid=1000(user0) groups=1000(user0)
  7663. ....
  7664. ==== Login as a non-root user without password
  7665. Replace on `inittab`:
  7666. ....
  7667. ::respawn:-/bin/sh
  7668. ....
  7669. with:
  7670. ....
  7671. ::respawn:-/bin/login -f user0
  7672. ....
  7673. `-f` forces login without asking for the password.
  7674. === Add new Buildroot packages
  7675. First, see if you can't get away without actually adding a new package, for example:
  7676. * 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:kernel_modules/user[] and you are done
  7677. * 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: <<custom-buildroot-configs>>
  7678. 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.
  7679. For how to use that package, see: <<buildroot_packages-directory>>.
  7680. Then iterate trying to do what you want and reading the manual until it works: https://buildroot.org/downloads/manual/manual.html
  7681. === Remove Buildroot packages
  7682. Once you've built a package in to the image, there is no easy way to remove it.
  7683. Documented at: link:https://github.com/buildroot/buildroot/blob/2017.08/docs/manual/rebuilding-packages.txt#L90[]
  7684. Also mentioned at: https://stackoverflow.com/questions/47320800/how-to-clean-only-target-in-buildroot
  7685. See this for a sample manual workaround: <<parsec-uninstall>>.
  7686. === BR2_TARGET_ROOTFS_EXT2_SIZE
  7687. When adding new large package to the Buildroot root filesystem, it may fail with the message:
  7688. ....
  7689. Maybe you need to increase the filesystem size (BR2_TARGET_ROOTFS_EXT2_SIZE)
  7690. ....
  7691. The solution is to simply add:
  7692. ....
  7693. ./build-buildroot --config 'BR2_TARGET_ROOTFS_EXT2_SIZE="512M"'
  7694. ....
  7695. where 512Mb is "large enough".
  7696. Note that dots cannot be used as in `1.5G`, so just use Megs as in `1500M` instead.
  7697. Unfortunately, TODO we don't have a perfect way to find the right value for `BR2_TARGET_ROOTFS_EXT2_SIZE`. One good heuristic is:
  7698. ....
  7699. du -hsx "$(./getvar --arch arm buildroot_target_dir)"
  7700. ....
  7701. Some promising ways to overcome this problem include:
  7702. * <<squashfs>>
  7703. TODO benchmark: would gem5 suffer a considerable disk read performance hit due to decompressing SquashFS?
  7704. * libguestfs: link:https://serverfault.com/questions/246835/convert-directory-to-qemu-kvm-virtual-disk-image/916697#916697[], in particular link:http://libguestfs.org/guestfish.1.html#vfs-minimum-size[`vfs-minimum-size`]
  7705. * use methods described at: <<gem5-restore-new-script>> instead of putting builds on the root filesystem
  7706. Bibliography: https://stackoverflow.com/questions/49211241/is-there-a-way-to-automatically-detect-the-minimum-required-br2-target-rootfs-ex
  7707. ==== SquashFS
  7708. link: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.
  7709. But then we could mount link: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>>.
  7710. This is the exact unanswered question: https://unix.stackexchange.com/questions/343484/mounting-squashfs-image-with-read-write-overlay-for-rootfs
  7711. [[rpath]]
  7712. === Buildroot rebuild is slow when the root filesystem is large
  7713. Buildroot is not designed for large root filesystem images, and the rebuild becomes very slow when we add a large package to it.
  7714. 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`
  7715. We have applied link:https://github.com/cirosantilli/buildroot/commit/983fe7910a73923a4331e7d576a1e93841d53812[983fe7910a73923a4331e7d576a1e93841d53812] to out Buildroot fork which removes part of the pain by not running:
  7716. ....
  7717. >>> Sanitizing RPATH in target tree
  7718. ....
  7719. which contributed to a large part of the slowness.
  7720. Test how Buildroot deals with many files with:
  7721. ....
  7722. ./build-buildroot \
  7723. --config 'BR2_PACKAGE_LKMC_MANY_FILES=y' \
  7724. -- \
  7725. lkmc_many_files-reconfigure \
  7726. |& \
  7727. ts -i '%.s' \
  7728. ;
  7729. ./build-buildroot |& ts -i '%.s'
  7730. ....
  7731. 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.
  7732. === Report upstream bugs
  7733. 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.
  7734. For example, QEMU developers will only want to see the final QEMU command that you are running.
  7735. 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.
  7736. We make that easy by building commands as strings, and then echoing them before evaling.
  7737. So for example when you run:
  7738. ....
  7739. ./run --arch arm
  7740. ....
  7741. the very first stdout output of that script is the actual QEMU command that is being run.
  7742. The command is also saved to a file for convenience:
  7743. ....
  7744. cat "$(./getvar --arch arm run_cmd_file)"
  7745. ....
  7746. which you can manually modify and execute during your experiments later:
  7747. ....
  7748. vim "$(./getvar --arch arm run_cmd_file)"
  7749. ./"$(./getvar --arch arm run_cmd_file)"
  7750. ....
  7751. If you are not already on the master of the given component, you can do that neatly with <<build-variants>>.
  7752. E.g., to check if a QEMU bug is still present on `master`, you can do as explained at <<qemu-build-variants>>:
  7753. ....
  7754. git -C "$(./getvar qemu_source_dir)" checkout master
  7755. ./build-qemu --clean --qemu-build-id master
  7756. ./build-qemu --qemu-build-id master
  7757. git -C "$(./getvar qemu_source_dir)" checkout -
  7758. ./run --qemu-build-id master
  7759. ....
  7760. Then, you will also want to do a <<bisection>> to pinpoint the exact commit to blame, and CC that developer.
  7761. Finally, give the images you used save upstream developpers time: <<release-zip>>.
  7762. For Buildroot problems, you should wither provide the config you have:
  7763. ....
  7764. ./getvar buildroot_config_file
  7765. ....
  7766. or try to reproduce with a minimal config, see: https://github.com/cirosantilli/buildroot/tree/in-tree-package-master
  7767. === libc choice
  7768. Buildroot supports several libc implementations, including:
  7769. * link:https://en.wikipedia.org/wiki/GNU_C_Library[glibc]
  7770. * link:https://en.wikipedia.org/wiki/UClibc[uClibc]
  7771. We currently use glibc, which is selected by:
  7772. ....
  7773. BR2_TOOLCHAIN_BUILDROOT_GLIBC=y
  7774. ....
  7775. 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.:
  7776. * <<selinux>>. Trivial unmerged fix at: http://lists.busybox.net/pipermail/buildroot/2017-July/197793.html just missing the uClibc option to expose `fts.h`...
  7777. * <<stress>>
  7778. The full list of unsupported packages can be found by grepping the Buildroot source:
  7779. ....
  7780. git -C "$(./getvar buildroot_source_dir)" grep 'depends on BR2_TOOLCHAIN_USES_GLIBC'
  7781. ....
  7782. 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: <<user-mode-simulation-with-glibc>>. I quote "downside" because glibc is actually exposing emulator bugs which we should actually go and fix.
  7783. == Userland content
  7784. Getting started at: <<userland-setup>>
  7785. The quickest way to run the arch agnostic examples is natively with: <<userland-setup-getting-started-natively>>
  7786. This sectionwas were originally moved in here from: https://github.com/cirosantilli/cpp-cheat
  7787. === C
  7788. Programs under link:userland/c/[] are examples of link:https://en.wikipedia.org/wiki/ANSI_C[ANSI C] programming:
  7789. * Standard library
  7790. ** assert.h
  7791. *** link:userland/c/assert_fail.c[]
  7792. Userland assembly content is located at: <<userland-assembly>>. It was split from this section basically becase we were hitting the HTML `h6` limit, stupid web :-)
  7793. ==== GCC C extensions
  7794. ===== C empty struct
  7795. Example: link:userland/gcc/empty_struct.c[]
  7796. Documentation: https://gcc.gnu.org/onlinedocs/gcc-8.2.0/gcc/Empty-Structures.html#Empty-Structures
  7797. Question: https://stackoverflow.com/questions/24685399/c-empty-struct-what-does-this-mean-do
  7798. ===== OpenMP
  7799. GCC implements the <<OpenMP>> threading implementation: https://stackoverflow.com/questions/3949901/pthreads-vs-openmp
  7800. Example: link:userland/gcc/openmp.c[]
  7801. 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`.
  7802. It seems to be easier to use for compute parallelism and more language agnostic than POSIX threads.
  7803. pthreads are more versatile though and allow for a superset of OpenMP.
  7804. The implementation lives under `libgomp` in the GCC tree, and is documented at: https://gcc.gnu.org/onlinedocs/libgomp/
  7805. `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.
  7806. [[cpp]]
  7807. === C++
  7808. Programs under link:userland/cpp/[] are examples of link:https://en.wikipedia.org/wiki/C%2B%2B#Standardization[ISO C] programming.
  7809. === POSIX
  7810. Programs under link:userland/posix/[] are examples of POSIX C programming.
  7811. What is POSIX:
  7812. * https://stackoverflow.com/questions/1780599/what-is-the-meaning-of-posix/31865755#31865755
  7813. * https://unix.stackexchange.com/questions/11983/what-exactly-is-posix/220877#220877
  7814. == Userland assembly
  7815. Programs under `userland/arch/<arch>/` are examples of userland assembly programming.
  7816. This section will document ISA agnostic concepts.
  7817. ISA specifics are covered at:
  7818. * <<x86-userland-assembly>> under link:userland/arch/x86_64/[], originally migrated from: https://github.com/cirosantilli/x86-assembly-cheat
  7819. * <<arm-userland-assembly>> under originally migrated from https://github.com/cirosantilli/arm-assembly-cheat under:
  7820. ** link:userland/arch/arm/[]
  7821. ** link:userland/arch/aarch64/[]
  7822. Like other userland programs, these programs can be run as explained at: <<userland-setup>>.
  7823. As a quick reminder, the fastest setups to get started are:
  7824. * <<userland-setup-getting-started-natively>> if your host can run the examples, e.g. x86 example on an x86 host
  7825. * <<userland-setup-getting-started-with-prebuilt-toolchain-and-qemu-user-mode>> otherwise
  7826. However, as usual, it is saner to build your toolchain as explained at: <<qemu-user-mode-getting-started>>.
  7827. The first example that you want to run for each arch is:
  7828. ....
  7829. ./run --userland userland/arch/<arch>/add.S
  7830. ....
  7831. e.g.:
  7832. ....
  7833. ./run --userland userland/arch/x86_64/add.S
  7834. ....
  7835. Sources:
  7836. * link:userland/arch/x86_64/add.S[]
  7837. * link:userland/arch/arm/add.S[]
  7838. * link:userland/arch/aarch64/add.S[]
  7839. These examples use the venerable ADD instruction to:
  7840. * 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.
  7841. +
  7842. It is then a big copy paste for most other data instructions.
  7843. * verify that the venerable `add` instruction and our assertions are working
  7844. Then, modify that program to make the assertion fail:
  7845. ....
  7846. ASSERT_EQ(%rax, $4)
  7847. ....
  7848. because 1 + 2 tends to equal 3 instead of 4.
  7849. And then watch the assertion fail:
  7850. ....
  7851. ./build-userland
  7852. ./run --userland userland/arch/x86_64/add.S
  7853. ....
  7854. with error message:
  7855. ....
  7856. assert_eq_64 failed
  7857. val1 0x3
  7858. val2 0x4
  7859. error: asm_main returned 1 at line 8
  7860. ....
  7861. and notice how the error message gives both:
  7862. * the actual assembly source line number where the failing assert was
  7863. * the actual and expected values
  7864. Other infrastructure sanity checks that you might want to look into include:
  7865. * link:userland/arch/empty.S[]
  7866. * `FAIL` tests
  7867. ** link:userland/arch/fail.S[]
  7868. * `ASSERT_MEMCMP` tests
  7869. ** link:userland/arch/x86_64/lkmc_assert_memcmp_fail.S[]
  7870. === Assembly registers
  7871. After seeing an <<userland-assembly,ADD hello world>>, you need to learn the general registers:
  7872. * arm
  7873. ** link:userland/arch/arm/registers.S[]
  7874. * aarch64
  7875. ** link:userland/arch/aarch64/registers.S[]
  7876. ** link:userland/arch/aarch64/pc.S[]
  7877. Bibliography: <<armarm7>> A2.3 "ARM core registers".
  7878. ==== ARMv8 aarch64 x31 register
  7879. Example: link:userland/arch/aarch64/x31.S[]
  7880. There is no `x31` name, and the encoding can have two different names depending on the instruction:
  7881. * `xzr`: zero register:
  7882. ** https://stackoverflow.com/questions/42788696/why-might-one-use-the-xzr-register-instead-of-the-literal-0-on-armv8
  7883. ** https://community.arm.com/processors/f/discussions/3185/wzr-xzr-register-s-purpose
  7884. * `sp`: stack pointer
  7885. To make things more confusing, some aliases can take either name, which makes them alias to different things, e.g. `mov` accepts both:
  7886. ....
  7887. mov x0, sp
  7888. mov x0, xzr
  7889. ....
  7890. and the first one is an alias to `add` while the second an alias to `orr`.
  7891. The difference is documented on a per instruction basis. Instructions that encode 31 as SP say:
  7892. ....
  7893. if d == 31 then
  7894. SP[] = result;
  7895. else
  7896. X[d] = result;
  7897. ....
  7898. And then those that don't say that, B1.2.1 "Registers in AArch64 state" implies the zero register:
  7899. ____
  7900. In instruction encodings, the value 0b11111 (31) is used to indicate the ZR (zero register). This
  7901. indicates that the argument takes the value zero, but does not indicate that the ZR is implemented
  7902. as a physical register.
  7903. ____
  7904. This is also described on <<armarm8>> C1.2.5 "Register names":
  7905. ____
  7906. There is no register named W31 or X31.
  7907. The name SP represents the stack pointer for 64-bit operands where an encoding of the value 31 in the
  7908. corresponding register field is interpreted as a read or write of the current stack pointer. When instructions
  7909. do not interpret this operand encoding as the stack pointer, use of the name SP is an error.
  7910. The name XZR represents the zero register for 64-bit operands where an encoding of the value 31 in the
  7911. corresponding register field is interpreted as returning zero when read or discarding the result when written.
  7912. When instructions do not interpret this operand encoding as the zero register, use of the name XZR is an error
  7913. ____
  7914. === Floating point assembly
  7915. 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.
  7916. For this reason, there are sometimes multiple ways to do floating point operations in each ISA.
  7917. Let's start as usual with floating point addition + register file:
  7918. * arm
  7919. ** <<arm-vadd-instruction>>
  7920. ** <<arm-vfp-registers>>
  7921. * aarch64
  7922. ** <<armv8-aarch64-fadd-instruction>>
  7923. ** <<armv8-aarch64-floating-point-registers>>
  7924. === SIMD assembly
  7925. Much like ADD for non-SIMD, start learning SIMD instructions by looking at the integer and floating point SIMD ADD instructions of each ISA:
  7926. * x86
  7927. ** <<x86-addpd-instruction>>
  7928. ** <<x86-paddq-instruction>>
  7929. * arm
  7930. ** <<arm-vadd-instruction>>
  7931. * aarch64
  7932. ** <<armv8-aarch64-add-vector-instruction>>
  7933. ** <<armv8-aarch64-fadd-instruction>>
  7934. Then it is just a huge copy paste of infinite boring details:
  7935. * <<x86-simd>>
  7936. * <<arm-simd>>
  7937. === User vs system assembly
  7938. By "userland assembly", we mean "the parts of the ISA which can be freely used from userland".
  7939. Most ISAs are divided into a system and userland part, and to running the system part requires elevated privileges such as <<ring0>> in x86.
  7940. One big difference between both is that we can run userland assembly on <<userland-setup>>, which is easier to get running and debug.
  7941. In particular, most userland assembly examples link to the C standard library: <<userland-assembly-c-standard-library>>.
  7942. Userland assembly is generally simpler, and a pre-requisite for <<baremetal-setup>>.
  7943. System-land assembly cheats will be put under: <<baremetal-setup>>.
  7944. === Userland assembly C standard library
  7945. All examples except the <<freestanding-programs>> link to the C standard library.
  7946. This allows using the C standard library for IO, which is very convenient and portable across host OSes.
  7947. It also exposes other non-IO functionality that is very convenient such as `memcmp`.
  7948. The C standard library infrastructure is implemented in the following files:
  7949. * link:userland/arch/main.c[]
  7950. * link:userland/arch/common.h[]
  7951. * link:userland/arch/x86_64/common_arch.h[]
  7952. * link:userland/arch/arm/common_arch.h[]
  7953. * link:userland/arch/aarch64/common_arch.h[]
  7954. ==== Freestanding programs
  7955. 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.
  7956. 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: <<linux-system-calls>>.
  7957. Such executables are called freestanding because they don't execute the glibc initialization code, but rather start directly on our custom hand written assembly.
  7958. In order to GDB step debug those executables, you will want to use `--no-continue`, e.g.:
  7959. ....
  7960. ./run --arch aarch64 --userland userland/arch/aarch64/freestanding/linux/hello.S --gdb-wait
  7961. ./run-gdb --arch aarch64 --no-continue --userland userland/arch/aarch64/freestanding/linux/hello.S
  7962. ....
  7963. You are now left on the very first instruction of our tiny executable!
  7964. === GCC inline assembly
  7965. Examples under `arch/<arch>/c/` directories show to how use inline assembly from higher level languages such as C:
  7966. * x86_64
  7967. ** link:userland/arch/x86_64/c/inc.c[]
  7968. ** link:userland/arch/x86_64/c/add.c[]
  7969. * arm
  7970. ** link:userland/arch/arm/c/inc.c[]
  7971. ** link:userland/arch/arm/c/inc_memory.c[]
  7972. ** link:userland/arch/arm/c/inc_memory_global.c[]
  7973. ** link:userland/arch/arm/c/add.c[]
  7974. * aarch64
  7975. ** link:userland/arch/aarch64/c/earlyclobber.c[]
  7976. ** link:userland/arch/aarch64/c/inc.c[]
  7977. ** link:userland/arch/aarch64/c/multiline.cpp[]
  7978. ==== GCC inline assembly register variables
  7979. Used notably in some of the <<linux-system-calls>> setups:
  7980. * link:userland/arch/arm/reg_var.c[]
  7981. * link:userland/arch/aarch64/reg_var.c[]
  7982. * link:userland/arch/aarch64/reg_var_float.c[]
  7983. In x86, makes it possible to access variables not exposed with the one letter register constraints.
  7984. 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
  7985. This feature notably useful for making system calls from C, see: <<linux-system-calls>>.
  7986. Documentation: https://gcc.gnu.org/onlinedocs/gcc-4.4.2/gcc/Explicit-Reg-Vars.html
  7987. ==== GCC inline assembly scratch registers
  7988. How to use temporary registers in inline assembly:
  7989. * x86_64
  7990. ** link:userland/arch/x86_64/c/scratch.c[]
  7991. ** link:userland/arch/x86_64/c/scratch_hardcode.c[]
  7992. Bibliography: https://stackoverflow.com/questions/6682733/gcc-prohibit-use-of-some-registers/54963829#54963829
  7993. ==== GCC inline assembly early-clobbers
  7994. An example of using the `&` early-clobber modifier: link:userland/arch/aarch64/earlyclobber.c
  7995. More details at: https://stackoverflow.com/questions/15819794/when-to-use-earlyclobber-constraint-in-extended-gcc-inline-assembly/54853663#54853663
  7996. The assertion may fail without it. It actually does fail in GCC 8.2.0.
  7997. ==== GCC inline assembly floating point ARM
  7998. Not documented as of GCC 8.2, but possible: https://stackoverflow.com/questions/53960240/armv8-floating-point-output-inline-assembly
  7999. * link:userland/arch/arm/c/inc_float.c[]
  8000. * link:userland/arch/aarch64/c/inc_float.c[]
  8001. === Linux system calls
  8002. The following <<userland-setup>> programs illustrate how to make system calls:
  8003. * x86_64
  8004. ** link:userland/arch/x86_64/freestanding/linux/hello.S[]
  8005. ** link:userland/arch/x86_64/c/freestanding/linux/hello.c[]
  8006. ** link:userland/arch/x86_64/c/freestanding/linux/hello_regvar.c[]
  8007. * arm
  8008. ** link:userland/arch/arm/freestanding/linux/hello.S[]
  8009. ** link:userland/arch/arm/c/freestanding/linux/hello.c[]
  8010. * aarch64
  8011. ** link:userland/arch/aarch64/freestanding/linux/hello.S[]
  8012. ** link:userland/arch/aarch64/c/freestanding/linux/hello.c[]
  8013. ** link:userland/arch/aarch64/c/freestanding/linux/hello_clobbers.c[]
  8014. Determining the ARM syscall numbers:
  8015. * https://reverseengineering.stackexchange.com/questions/16917/arm64-syscalls-table
  8016. * arm: https://github.com/torvalds/linux/blob/v4.17/arch/arm/tools/syscall.tbl
  8017. * aarch64: https://github.com/torvalds/linux/blob/v4.17/include/uapi/asm-generic/unistd.h
  8018. Determining the ARM syscall interface:
  8019. * https://stackoverflow.com/questions/12946958/what-is-the-interface-for-arm-system-calls-and-where-is-it-defined-in-the-linux
  8020. * https://stackoverflow.com/questions/45742869/linux-syscall-conventions-for-armv8
  8021. Questions about the C inline assembly examples:
  8022. * x86_64: https://stackoverflow.com/questions/9506353/how-to-invoke-a-system-call-via-sysenter-in-inline-assembly/54956854#54956854
  8023. * ARM: https://stackoverflow.com/questions/21729497/doing-a-syscall-without-libc-using-arm-inline-assembly
  8024. === Calling conventions
  8025. ==== x86_64 calling convention
  8026. Examples:
  8027. * link:userland/arch/x86_64/common_arch.h[] `ENTRY` and `EXIT`
  8028. ==== ARM calling convention
  8029. Call C standard library functions from assembly and vice versa.
  8030. * arm
  8031. ** link:userland/arch/arm/common_arch.h[] `ENTRY` and `EXIT`
  8032. ** link:userland/arch/arm/linux/c_from_asm.S[]
  8033. * aarch64
  8034. ** link:userland/arch/aarch64/common_arch.h[] `ENTRY` and `EXIT`
  8035. ** link:userland/arch/aarch64/c/linux/asm_from_c.c[]
  8036. ARM Architecture Procedure Call Standard (AAPCS) is the name that ARM Holdings gives to the calling convention.
  8037. Official specification: http://infocenter.arm.com/help/topic/com.arm.doc.ihi0042f/IHI0042F_aapcs.pdf
  8038. Bibliography:
  8039. * https://en.wikipedia.org/wiki/Calling_convention#ARM_(A32) Wiki contains the master list as usual.
  8040. * http://stackoverflow.com/questions/8422287/calling-c-functions-from-arm-assembly
  8041. * http://stackoverflow.com/questions/261419/arm-to-c-calling-convention-registers-to-save
  8042. * https://stackoverflow.com/questions/10494848/arm-whats-the-difference-between-apcs-and-aapcs-abi
  8043. === GNU GAS assembler
  8044. link:https://en.wikipedia.org/wiki/GNU_Assembler[GNU GAS] is the default assembler used by GDB, and therefore it completely dominates in Linux.
  8045. The Linux kernel in particular uses GNU GAS assembly extensively for the arch specific parts under `arch/`.
  8046. ==== GNU GAS assembler comments
  8047. In this tutorial, we use exclusively C Preprocessor `/**/` comments because:
  8048. * they are the same for all archs
  8049. * we are already stuck to the C Preprocessor because GNU GAS macros are unusable so we need `#define`
  8050. * mixing `#` GNU GAS comments and `#define` is a bad idea ;-)
  8051. 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
  8052. Examples:
  8053. * link:userland/arch/arm/comments.S[]
  8054. * link:userland/arch/aarch64/comments.S[]
  8055. ==== GNU GAS assembler immediates
  8056. Summary:
  8057. * x86 always dollar `$` everywhere.
  8058. * ARM: can use either `#`, `$` or nothing depending on v7 vs v8 and <<gnu-gas-assembler-arm-unified-syntax,`.syntax unified`>>.
  8059. +
  8060. Fuller explanation at: https://stackoverflow.com/questions/21652884/is-the-hash-required-for-immediate-values-in-arm-assembly/51987780#51987780
  8061. Examples:
  8062. * link:userland/arch/arm/immediates.S[]
  8063. * link:userland/arch/aarch64/immediates.S[]
  8064. ==== GNU GAS assembler data sizes
  8065. Let's see how many bytes go into each data type:
  8066. * link:userland/arch/x86_64/gas_data_sizes.S[]
  8067. * link:userland/arch/arm/gas_data_sizes.S[]
  8068. * link:userland/arch/aarch64/gas_data_sizes.S[]
  8069. Conclusion:
  8070. [options="header"]
  8071. |===
  8072. |.byte |.word |.long |.quad |.octa
  8073. |x86
  8074. |1
  8075. |2
  8076. |4
  8077. |8
  8078. |16
  8079. |arm
  8080. |1
  8081. |4
  8082. |4
  8083. |8
  8084. |16
  8085. |aarch64
  8086. |1
  8087. |4
  8088. |4
  8089. |8
  8090. |16
  8091. |===
  8092. and also keep in mind that according to the manual:
  8093. * `.int` is the same as `.long`
  8094. * `.hword` is the same as `.short` which is usually the same as `.word`
  8095. Bibliography:
  8096. * https://sourceware.org/binutils/docs-2.32/as/Pseudo-Ops.html#Pseudo-Ops
  8097. * https://stackoverflow.com/questions/43005411/how-does-the-quad-directive-work-in-assembly/43006616
  8098. * https://gist.github.com/steakknife/d47d0b19a24817f48027
  8099. ===== GNU GAS assembler ARM specifics
  8100. ====== GNU GAS assembler ARM unified syntax
  8101. There are two types of ARMv7 assemblies:
  8102. * `.syntax divided`
  8103. * `.syntax unified`
  8104. They are very similar, but unified is the new and better one, which we use in this tutorial.
  8105. Unfortunately, for backwards compatibility, GNU AS 2.31.1 and GCC 8.2.0 still use `.syntax divided` by default.
  8106. 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).
  8107. Some of the differences include:
  8108. * `#` is optional in unified syntax int literals, see <<gnu-gas-assembler-immediates>>
  8109. * many mnemonics changed:
  8110. ** 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
  8111. ** but there are some more drastic ones, e.g. `swi` vs `svc`: https://stackoverflow.com/questions/8459279/are-arm-instructuons-swi-and-svc-exactly-same-thing/54078731#54078731
  8112. * cannot have implicit destination with shift, see: <<arm-shift-suffixes>>
  8113. ===== GNU GAS assembler ARM .n and .w suffixes
  8114. When reading disassembly, many instructions have either a `.n` or `.w` suffix.
  8115. `.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.
  8116. Bibliography: https://stackoverflow.com/questions/27147043/n-suffix-to-branch-instruction
  8117. == x86 userland assembly
  8118. Arch agnostic infrastructure getting started at: <<userland-assembly>>.
  8119. === x86 userland assembly getting started
  8120. These are the main concepts and instructions that you should learn to be able to understand what is going on.
  8121. Once those are done, everything else left on userland is just to learn a huge list of instructions: <<x86-userland-assembly-instructions>>
  8122. === x86 userland assembly instructions
  8123. ==== x86 SIMD
  8124. History:
  8125. * link:https://en.wikipedia.org/wiki/MMX_(instruction_set)[MMX]: 1997
  8126. * link:https://en.wikipedia.org/wiki/Streaming_SIMD_Extensions[SSE]: Streaming SIMD Extensions. 1999. 128-bit XMM registers.
  8127. * link:https://en.wikipedia.org/wiki/SSE2[SSE2]: 2004
  8128. * link:https://en.wikipedia.org/wiki/SSE3[SSE3]: 2006
  8129. * link:https://en.wikipedia.org/wiki/SSE4[SSE4]: 2006
  8130. * link:https://en.wikipedia.org/wiki/Advanced_Vector_Extensions[AVX]: Advanced Vector Extensions. 2011. 256-bit YMM registers. Extension of XMM.
  8131. * AVX2:2013
  8132. * AVX-512: 2016. 512-bit ZMM registers. Extension of YMM.
  8133. ===== x86 SSE2
  8134. ====== x86 addpd instruction
  8135. link:userland/arch/x86_64/addpd.S[]: `addps`, `addpd`
  8136. Good first instruction to learn SIMD: <<simd-assembly>>
  8137. ====== x86 paddq instruction
  8138. link:userland/arch/x86_64/paddq.S[]: `paddq`, `paddl`, `paddw`, `paddb`
  8139. Good first instruction to learn SIMD: <<simd-assembly>>
  8140. === x86 rdtsc instruction
  8141. TODO: review this section, make a more controlled userland experiment with <<m5ops>> instrumentation.
  8142. Let's have some fun and try to correlate the gem5 <<stats-txt>> `system.cpu.numCycles` cycle count with the link:https://en.wikipedia.org/wiki/Time_Stamp_Counter[x86 `rdtsc` instruction] that is supposed to do the same thing:
  8143. ....
  8144. ./build-userland --static userland/arch/x86_64/c/rdtsc.c
  8145. ./run --eval './arch/x86_64/c/rdtsc.out;m5 exit;' --emulator gem5
  8146. ./gem5-stat
  8147. ....
  8148. Source: link:userland/rdtsc.c[]
  8149. `rdtsc` outputs a cycle count which we compare with gem5's `gem5-stat`:
  8150. * `3828578153`: `rdtsc`
  8151. * `3830832635`: `gem5-stat`
  8152. which gives pretty close results, and serve as a nice sanity check that the cycle counter is coherent.
  8153. 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`.
  8154. Bibliography:
  8155. * https://en.wikipedia.org/wiki/Time_Stamp_Counter
  8156. * https://stackoverflow.com/questions/9887839/clock-cycle-count-wth-gcc/9887979
  8157. ==== ARM pmccntr
  8158. 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:
  8159. * https://stackoverflow.com/questions/40454157/is-there-an-equivalent-instruction-to-rdtsc-in-arm
  8160. * https://stackoverflow.com/questions/31620375/arm-cortex-a7-returning-pmccntr-0-in-kernel-mode-and-illegal-instruction-in-u/31649809#31649809
  8161. * https://blog.regehr.org/archives/794
  8162. == ARM userland assembly
  8163. Arch general getting started at: <<userland-assembly>>.
  8164. Instructions here loosely grouped based on that of the <<armarm7>> Chapter A4 "The Instruction Sets".
  8165. We cover here mostly ARMv7, and then treat aarch64 differentially, since much of the ARMv7 userland is the same in aarch32.
  8166. === Introduction to the ARM architecture
  8167. The link: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.
  8168. 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.
  8169. ARM is generally considered a RISC instruction set, although there are some more complex instructions which would not generally be classified as purely RISC.
  8170. 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.
  8171. ARM Holdings was bought by the Japanese giant SoftBank in 2016.
  8172. ==== ARMv8 vs ARMv7 vs AArch64 vs AArch32
  8173. ARMv7 is the older architecture described at: <<armarm7>>.
  8174. ARMv8 is the newer architecture ISA link:https://developer.arm.com/docs/den0024/latest/preface[released in 2013] and described at: <<armarm8>>. It can be in either of two states:
  8175. * <<aarch32>>
  8176. * aarch64
  8177. In the lose terminology of this repository:
  8178. * `arm` means basically AArch32
  8179. * `aarch64` means ARMv8 AArch64
  8180. ARMv8 has link:https://en.wikipedia.org/wiki/ARM_architecture#ARMv8-A[had several updates] since its release:
  8181. * v8.1: 2014
  8182. * v8.2: 2016
  8183. * v8.3: 2016
  8184. * v8.4: TODO
  8185. * v8.5: 2018
  8186. They are described at: <<armarm8>> A1.7 "ARMv8 architecture extensions".
  8187. ===== AArch32
  8188. 32-bit mode of operation of ARMv8.
  8189. Userland is highly / fully backwards compatible with ARMv7:
  8190. * https://stackoverflow.com/questions/42972096/armv8-backward-compatibility-with-armv7-snapdragon-820-vs-cortex-a15
  8191. * https://stackoverflow.com/questions/31848185/does-armv8-aarch32-mode-has-backward-compatible-with-armv4-armv5-or-armv6
  8192. For this reason, QEMU and GAS seems to enable both AArch32 and ARMv7 under `arm` rather than `aarch64`.
  8193. 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.:
  8194. * <<armv8-aarch32-vcvta-instruction>>
  8195. ===== AArch32 vs AArch64
  8196. A great summary of differences can be found at: https://en.wikipedia.org/wiki/ARM_architecture#AArch64_features
  8197. Some random ones:
  8198. * aarch32 has two encodings: Thumb and ARM: <<arm-instruction-encodings>>
  8199. * in ARMv8, the stack has to 16-byte aligned. Therefore, the main way to push things to stack is with 8-byte pair pushes with the <<armv8-aarch64-ldp-and-stp-instructions>>
  8200. ==== Free ARM implementations
  8201. 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.
  8202. ARM has already sued people in the past for implementing ARM ISA: http://www.eetimes.com/author.asp?section_id=36&doc_id=1287452
  8203. http://semiengineering.com/an-alternative-to-x86-arm-architectures/ mentions that:
  8204. ____
  8205. 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.
  8206. ____
  8207. 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.
  8208. 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?
  8209. Generally, it is mostly large companies that implement the CPUs themselves. For example, the link:https://en.wikipedia.org/wiki/Apple_A12[Apple A12 chip], which is used in iPhones, has verilog designs:
  8210. ____
  8211. 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.
  8212. ____
  8213. 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.
  8214. 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
  8215. ==== ARM instruction encodings
  8216. 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>>.
  8217. aarch32 has two "instruction sets", which to look just like encodings.
  8218. Some control bit must determine which one we are currently on, and userland can switch between them with the <<arm-bx-instruction>> TODO: details.
  8219. The encodings are:
  8220. * A32: every instruction is 4 bytes long. Can encode every instruction.
  8221. * T32: most common instructions are 2 bytes long. Many others less common ones are 4 bytes long.
  8222. +
  8223. T stands for "Thumb", which is the original name for the technology. The word "Thumb" does not appear on <<armarm8>> however. It does appear on <<armarm7>> though.
  8224. +
  8225. Example: link:userland/arch/arm/thumb.S[]
  8226. +
  8227. See also: <<armarm8>> F2.1.3 "Instruction encodings".
  8228. Within each instruction set, there can be multiple encodings for a given function, and they are noted simply as:
  8229. * A1, A2, ...: A32 encodings
  8230. * T1, T2, ..m: T32 encodings
  8231. 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.
  8232. This design can be contrasted with x86, which has widely variable instruction length.
  8233. Bibliography:
  8234. * https://stackoverflow.com/questions/28669905/what-is-the-difference-between-the-arm-thumb-and-thumb-2-instruction-encodings
  8235. * https://reverseengineering.stackexchange.com/questions/6080/how-to-detect-thumb-mode-in-arm-disassembly
  8236. === ARM branch instructions
  8237. ==== ARM b instruction
  8238. Unconditional branch.
  8239. Example: link:userland/arch/arm/b.S[]
  8240. 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.
  8241. This allows for 26 bit long jumps, which is 64 MiB.
  8242. TODO: what to do if we want to jump longer than that?
  8243. ==== ARM beq instruction
  8244. Branch if equal based on the status registers.
  8245. Examples:
  8246. * link:userland/arch/arm/beq.S[].
  8247. * link:userland/arch/aarch64/beq.S[].
  8248. The family of instructions includes:
  8249. * `beq`: branch if equal
  8250. * `bne`: branch if not equal
  8251. * `ble`: less or equal
  8252. * `bge`: greater or equal
  8253. * `blt`: less than
  8254. * `bgt`: greater than
  8255. ==== ARM bl instruction
  8256. Branch with link, i.e. branch and store the return address on the `rl` register.
  8257. Example: link:userland/arch/arm/bl.S[]
  8258. This is the major way to make function calls.
  8259. The current ARM / Thumb mode is encoded in the least significant bit of lr.
  8260. ===== ARM bx instruction
  8261. `bx`: branch and switch between ARM / Thumb mode, encoded in the least significant bit of the given register.
  8262. `bx lr` is the main way to return from function calls after a `bl` call.
  8263. Since `bl` encodes the current ARM / Thumb in the register, `bx` keeps the mode unchanged by default.
  8264. ===== ARMv8 aarch64 ret instruction
  8265. Example: link:userland/arch/aarch64/ret.S[]
  8266. ARMv8 AArch64 only:
  8267. * there is no `bx` in AArch64 since no Thumb to worry about, so it is called just `br`
  8268. * the `ret` instruction was added in addition to `br`, with the following differences:
  8269. ** provides a hint that this is a function call return
  8270. ** has a default argument `x30` if none is given. This is where `bl` puts the return value.
  8271. See also: https://stackoverflow.com/questions/32304646/arm-assembly-branch-to-address-inside-register-or-memory/54145818#54145818
  8272. ==== ARM cbz instruction
  8273. Compare and branch if zero.
  8274. Example: link:userland/arch/aarch64/cbz.S[]
  8275. Only in ARMv8 and ARMv7 Thumb mode, not in armv7 ARM mode.
  8276. Very handy!
  8277. ==== ARM conditional execution
  8278. 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`.
  8279. Example: link:userland/arch/arm/cond.S[]
  8280. Just add the usual `eq`, `ne`, etc. suffixes just as for `b`.
  8281. The list of all extensions is documented at <<armarm7>> "A8.3 Conditional execution".
  8282. === ARM load and store instructions
  8283. In ARM, there are only two instruction families that do memory access: <<arm-ldr-instruction>> to load and <<arm-str-instruction>> to store.
  8284. Everything else works on register and immediates.
  8285. 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.
  8286. This kind of architecture is called a link:https://en.wikipedia.org/wiki/Load/store_architecture[Load/store architecture].
  8287. ==== ARM ldr instruction
  8288. ===== ARM ldr pseudo-instruction
  8289. `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
  8290. The pseudo instruction version is when an equal sign appears on one of the operators.
  8291. 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.
  8292. Example: link:userland/arch/arm/ldr_pseudo.S[]
  8293. This is done basically because all instructions are 32-bit wide, and there is not enough space to encode 32-bit addresses in them.
  8294. Bibliography:
  8295. * https://stackoverflow.com/questions/37840754/what-does-an-equals-sign-on-the-right-side-of-a-ldr-instruction-in-arm-mean
  8296. * https://stackoverflow.com/questions/17214962/what-is-the-difference-between-label-equals-sign-and-label-brackets-in-ar
  8297. * https://stackoverflow.com/questions/14046686/why-use-ldr-over-mov-or-vice-versa-in-arm-assembly
  8298. ===== ARM addressing modes
  8299. Example: link:userland/arch/arm/address_modes.S[]
  8300. Load and store instructions can update the source register with the following modes:
  8301. * offset: add an offset, don't change the address register. Notation:
  8302. +
  8303. ....
  8304. ldr r1, [r0, 4]
  8305. ....
  8306. * pre-indexed: change the address register, and then use it modified. Notation:
  8307. +
  8308. ....
  8309. ldr r1, [r0, 4]!
  8310. ....
  8311. * post-indexed: use the address register unmodified, and then modify it. Notation:
  8312. +
  8313. ....
  8314. ldr r1, [r0], 4
  8315. ....
  8316. The offset itself can come from the following sources:
  8317. * immediate
  8318. * register
  8319. * scaled register: left shift the register and use that as an offset
  8320. The indexed modes are convenient to loop over arrays.
  8321. Bibliography: <<armarm7>>:
  8322. * A4.6.5 "Addressing modes"
  8323. * A8.5 "Memory accesses"
  8324. ====== ARM loop over array
  8325. As an application of the post-indexed addressing mode, let's increment an array.
  8326. Example: link:userland/arch/arm/inc_array.S[]
  8327. ===== ARM ldrh and ldrb instructions
  8328. There are `ldr` variants that load less than full 4 bytes:
  8329. * link:userland/arch/arm/ldrb.S[]: load byte
  8330. * link:userland/arch/arm/ldrh.S[]: load half word
  8331. ==== ARM str instruction
  8332. Store from memory into registers.
  8333. Example: link:userland/arch/arm/str.S[]
  8334. Basically everything that applies to <<arm-ldr-instruction>> also applies here so we won't go into much detail.
  8335. ===== ARMv8 aarch64 str instruction
  8336. PC-relative `str` is not possible in aarch64.
  8337. For `ldr` it works <<arm-ldr-instruction,as in aarch32>>.
  8338. As a result, it is not possible to load from the literal pool for `str`.
  8339. Example: link:userland/arch/aarch64/str.S[]
  8340. This can be seen from <<armarm8>> C3.2.1 "Load/Store register": `ldr` simply has on extra PC encoding that `str` does not.
  8341. ===== ARMv8 aarch64 ldp and stp instructions
  8342. Push a pair of registers to the stack.
  8343. TODO minimal example. Currently used on link:v8/commmon_arch.h[] since it is the main way to restore register state.
  8344. ==== ARM ldmia instruction
  8345. Pop values form stack into the register and optionally update the address register.
  8346. `stmdb` is the push version.
  8347. Example: link:userland/arch/arm/ldmia.S[]
  8348. The mnemonics stand for:
  8349. * `stmdb`: STore Multiple Decrement Before
  8350. * `ldmia`: LoaD Multiple Increment After
  8351. Example: link:userland/arch/arm/push.S[]
  8352. `push` and `pop` are just mnemonics `stdmdb` and `ldmia` using the stack pointer `sp` as address register:
  8353. ....
  8354. stmdb sp!, reglist
  8355. ldmia sp!, reglist
  8356. ....
  8357. The `!` indicates that we want to update the register.
  8358. The registers are encoded as single bits inside the instruction: each bit represents one register.
  8359. 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.
  8360. AArch64 loses those instructions, likely because it was not possible anymore to encode all registers: http://stackoverflow.com/questions/27941220/push-lr-and-pop-lr-in-arm-arch64 and replaces them with the <<armv8-aarch64-ldp-and-stp-instructions>>
  8361. === ARM data processing instructions
  8362. Arithmetic:
  8363. * link:userland/arch/arm/mul.S[]: multiply
  8364. * link:userland/arch/arm/sub.S[]: subtract
  8365. * link:userland/arch/arm/rbit.S[]: reverse bit order
  8366. * link:userland/arch/arm/rev.S[]: reverse byte order
  8367. * link:userland/arch/arm/tst.S[]
  8368. ==== ARM cset instruction
  8369. Example: link:userland/arch/aarch64/cset.S[]
  8370. Set a register conditionally depending on the condition flags:
  8371. ARMv8-only, likely because in ARMv8 you can't have conditional suffixes for every instruction.
  8372. ==== ARM bitwise instructions
  8373. * link:userland/arch/arm/and.S[]
  8374. * `eor`: exclusive OR
  8375. * `orr`: OR
  8376. * link:userland/arch/arm/clz.S[]: count leading zeroes
  8377. ===== ARM bic instruction
  8378. Bitwise Bit Clear: clear some bits.
  8379. ....
  8380. dest = `left & ~right`
  8381. ....
  8382. Example: link:userland/arch/arm/bic.S[]
  8383. ===== ARM ubfm instruction
  8384. Unsigned Bitfield Move.
  8385. ____
  8386. 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.
  8387. ____
  8388. Example: link:userland/arch/aarch64/ubfm.S[]
  8389. TODO: explain full behaviour. Very complicated. Has several simpler to understand aliases.
  8390. ====== ARM ubfx instruction
  8391. Alias for:
  8392. ....
  8393. UBFM <Wd>, <Wn>, #<lsb>, #(<lsb>+<width>-1)
  8394. ....
  8395. Example: link:userland/arch/aarch64/ubfx.S[]
  8396. The operation:
  8397. ....
  8398. UBFX dest, src, lsb, width
  8399. ....
  8400. does:
  8401. ....
  8402. dest = (src & ((1 << width) - 1)) >> lsb;
  8403. ....
  8404. Bibliography: https://stackoverflow.com/questions/8366625/arm-bit-field-extract
  8405. ===== ARM bfm instruction
  8406. TODO: explain. Similar to <<arm-ubfm-instruction,`ubfm`>> but leave untouched bits unmodified.
  8407. ====== ARM bfi instruction
  8408. Examples:
  8409. * link:userland/arch/arm/bfi.S[]
  8410. * link:userland/arch/aarch64/bfi.S[]
  8411. Move the lower bits of source register into any position in the destination:
  8412. * ARMv8: an alias for <<arm-bfm-instruction,`bfm`>>
  8413. * ARMv7: a real instruction
  8414. ==== ARM mov instruction
  8415. Move an immediate to a register, or a register to another register.
  8416. Cannot load from or to memory, since only the `ldr` and `str` instruction families can do that in ARM: <<arm-load-and-store-instructions>>
  8417. Example: link:userland/arch/arm/mov.S[]
  8418. 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.
  8419. The solutions to this problem are mentioned at:
  8420. * https://stackoverflow.com/questions/38689886/loading-32-bit-values-to-a-register-in-arm-assembly
  8421. * https://community.arm.com/processors/b/blog/posts/how-to-load-constants-in-assembly-for-arm-architecture
  8422. Summary of solutions:
  8423. * <<arm-movw-and-movt-instructions>>
  8424. * place it in memory. But then how to load the address, which is also a 32-bit value?
  8425. ** use pc-relative addressing if the memory is close enough
  8426. ** use `orr` encodable shifted immediates
  8427. The blog article summarizes nicely which immediates can be encoded and the design rationale:
  8428. ____
  8429. 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).
  8430. 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.
  8431. ____
  8432. 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.
  8433. ===== ARM movw and movt instructions
  8434. Set the higher or lower 16 bits of a register to an immediate in one go.
  8435. Example: link:userland/arch/arm/movw.S[]
  8436. The armv8 version analogue is <<armv8-aarch64-movk-instruction>>.
  8437. ===== ARMv8 aarch64 movk instruction
  8438. Fill a 64 bit register with 4 16-bit instructions one at a time.
  8439. Similar to <<arm-movw-and-movt-instructions>> in v7.
  8440. Example: link:userland/arch/aarch64/movk.S[]
  8441. Bibliography: https://stackoverflow.com/questions/27938768/moving-a-32-bit-constant-in-arm-arch64-register
  8442. ===== ARMv8 aarch64 movn instruction
  8443. Set 16-bits negated and the rest to `1`.
  8444. Example: link:userland/arch/aarch64/movn.S[]
  8445. ==== ARM data processing instruction suffixes
  8446. ===== ARM shift suffixes
  8447. Most data processing instructions can also optionally shift the second register operand.
  8448. Example: link:userland/arch/arm/shift.S[]
  8449. The shift types are:
  8450. * `lsr` and `lfl`: Logical Shift Right / Left. Insert zeroes.
  8451. * `ror`: Rotate Right / Left. Wrap bits around.
  8452. * `asr`: Arithmetic Shift Right. Keep sign.
  8453. Documented at: <<armarm7>> "A4.4.1 Standard data-processing instructions"
  8454. ===== ARM S suffix
  8455. Example: link:userland/arch/arm/s_suffix.S[]
  8456. The `S` suffix, present on most <<arm-data-processing-instructions>>, makes the instruction also set the Status register flags that control conditional jumps.
  8457. If the result of the operation is `0`, then it triggers `beq`, since comparison is a subtraction, with success on 0.
  8458. `cmp` sets the flags by default of course.
  8459. ==== ARM adr instruction
  8460. 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.
  8461. Examples:
  8462. * link:userland/arch/arm/adr.S[]
  8463. * link:userland/arch/aarch64/adr.S[]
  8464. * link:userland/arch/aarch64/adrp.S[]
  8465. More details: https://stackoverflow.com/questions/41906688/what-are-the-semantics-of-adrp-and-adrl-instructions-in-arm-assembly/54042899#54042899
  8466. ===== ARM adrl instruction
  8467. See: <<arm-adr-instruction>>.
  8468. === ARM miscellaneous instructions
  8469. ==== ARM nop instruction
  8470. There are a few different ways to encode `nop`, notably `mov` a register into itself, and a dedicated miscellaneous instruction.
  8471. Example: link:userland/arch/arm/nop.S[]
  8472. Try disassembling the executable to see what the assembler is emitting:
  8473. ....
  8474. gdb-multiarch -batch -ex 'arch arm' -ex "file v7/nop.out" -ex "disassemble/rs asm_main_after_prologue"
  8475. ....
  8476. Bibliography: https://stackoverflow.com/questions/1875491/nop-for-iphone-binaries
  8477. === ARM SIMD
  8478. ==== ARM VFP
  8479. The name for the ARMv7 and AArch32 floating point and SIMD instructions / registers.
  8480. Vector Floating Point extension.
  8481. TODO I think it was optional in ARMv7, find quote.
  8482. VFP has several revisions, named as VFPv1, VFPv2, etc. TODO: announcement dates.
  8483. 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:
  8484. * https://github.com/torvalds/linux/blob/v4.18/arch/arm/kernel/setup.c#L1199
  8485. * https://github.com/torvalds/linux/blob/v4.18/arch/arm64/kernel/cpuinfo.c#L95
  8486. 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.
  8487. Bibliography:
  8488. * <<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?
  8489. * https://mindplusplus.wordpress.com/2013/06/25/arm-vfp-vector-programming-part-1-introduction/
  8490. * https://en.wikipedia.org/wiki/ARM_architecture#Floating-point_(VFP)
  8491. ===== ARM VFP registers
  8492. TODO example
  8493. <<armarm8>> E1.3.1 "The SIMD and floating-point register file" Figure E1-1 "SIMD and floating-point register file, AArch32 operation":
  8494. ....
  8495. +-----+-----+-----+
  8496. | S0 | | |
  8497. +-----+ D0 + |
  8498. | S1 | | |
  8499. +-----+-----+ Q0 |
  8500. | S2 | | |
  8501. +-----+ D1 + |
  8502. | S3 | | |
  8503. +-----+-----+-----+
  8504. | S4 | | |
  8505. +-----+ D2 + |
  8506. | S5 | | |
  8507. +-----+-----+ Q1 |
  8508. | S6 | | |
  8509. +-----+ D3 + |
  8510. | S7 | | |
  8511. +-----+-----+-----+
  8512. ....
  8513. Note how Sn is weirdly packed inside Dn, and Dn weirdly packed inside Qn, likely for historical reasons.
  8514. And you can't access the higher bytes at D16 or greater with Sn.
  8515. ===== ARM vadd instruction
  8516. * link:userland/arch/arm/vadd_scalar.S[]: see also: <<floating-point-assembly>>
  8517. * link:userland/arch/arm/vadd_vector.S[]: see also: <<simd-assembly>>
  8518. ===== ARM vcvt instruction
  8519. Example: link:userland/arch/arm/vcvt.S[]
  8520. Convert between integers and floating point.
  8521. <<armarm7>> on rounding:
  8522. ____
  8523. 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.
  8524. ____
  8525. Notice how the opcode takes two types.
  8526. E.g., in our 32-bit float to 32-bit unsigned example we use:
  8527. ....
  8528. vld1.32.f32
  8529. ....
  8530. ====== ARM vcvtr instruction
  8531. Example: link:userland/arch/arm/vcvtr.S[]
  8532. Like <<arm-vcvt-instruction>>, but the rounding mode is selected by the FPSCR.RMode field.
  8533. 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>>.
  8534. Rounding mode selection is exposed in the ANSI C standard through link:https://en.cppreference.com/w/c/numeric/fenv/feround[`fesetround`].
  8535. TODO: is the initial rounding mode specified by the ELF standard? Could not find a reference.
  8536. ====== ARMv8 AArch32 vcvta instruction
  8537. Example: link:userland/arch/arm/vcvt.S[]
  8538. Added in ARMv8 <<aarch32>> only, not present in ARMv7.
  8539. 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>>.
  8540. Now in AArch32 it is possible to do it explicitly per-instruction.
  8541. Also there was no ties to away mode in ARMv7. This mode does not exist in C99 either.
  8542. ==== ARMv8 Advanced SIMD and floating-point support
  8543. The <<armarm8>> specifies floating point and SIMD support in the main architecture at A1.5 "Advanced SIMD and floating-point support".
  8544. The feature is often refered to simply as "SIMD&FP" throughout the manual.
  8545. The Linux kernel shows `/proc/cpuinfo` compatibility as `neon`, which is yet another intermediate name that came up at some point: <<arm-neon>>
  8546. Vs <<arm-vfp>>: https://stackoverflow.com/questions/4097034/arm-cortex-a8-whats-the-difference-between-vfp-and-neon
  8547. ===== ARMv8 floating point availability
  8548. Support is semi-mandatory. <<armarm8>> A1.5 "Advanced SIMD and floating-point support":
  8549. ____
  8550. ARMv8 can support the following levels of support for Advanced SIMD and floating-point instructions:
  8551. - Full SIMD and floating-point support without exception trapping.
  8552. - Full SIMD and floating-point support with exception trapping.
  8553. - No floating-point or SIMD support. This option is licensed only for implementations targeting specialized markets.
  8554. Note: All systems that support standard operating systems with rich application environments provide hardware
  8555. support for Advanced SIMD and floating-point. It is a requirement of the ARM Procedure Call Standard for
  8556. AArch64, see Procedure Call Standard for the ARM 64-bit Architecture.
  8557. ____
  8558. Therefore it is in theory optional, but highly available.
  8559. This is unlike ARMv7, where floating point is completely optional through <<arm-vfp>>.
  8560. ===== ARM NEON
  8561. Just an informal name for the "Advanced SIMD instructions"? Very confusing.
  8562. <<armarm8>> F2.9 "Additional information about Advanced SIMD and floating-point instructions" says:
  8563. ____
  8564. The Advanced SIMD architecture, its associated implementations, and supporting software, are commonly referred to as NEON technology.
  8565. ____
  8566. https://developer.arm.com/technologies/neon mentions that is is present on both ARMv7 and ARMv8:
  8567. ____
  8568. 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.
  8569. ____
  8570. ==== ARMv8 AArch64 floating point registers
  8571. TODO example.
  8572. <<armarm8>> B1.2.1 "Registers in AArch64 state" describes the registers:
  8573. ____
  8574. 32 SIMD&FP registers, `V0` to `V31`. Each register can be accessed as:
  8575. * A 128-bit register named `Q0` to `Q31`.
  8576. * A 64-bit register named `D0` to `D31`.
  8577. * A 32-bit register named `S0` to `S31`.
  8578. * A 16-bit register named `H0` to `H31`.
  8579. * An 8-bit register named `B0` to `B31`.
  8580. ____
  8581. Notice how Sn is very different between v7 and v8! In v7 it goes across Dn, and in v8 inside each Dn.
  8582. ===== ARMv8 aarch64 add vector instruction
  8583. link:userland/arch/aarch64/add_vector.S[]
  8584. Good first instruction to learn SIMD: <<simd-assembly>>
  8585. ===== ARMv8 aarch64 fadd instruction
  8586. * link:userland/arch/aarch64/fadd_vector.S[]: see also: <<simd-assembly>>
  8587. * link:userland/arch/aarch64/fadd_scalar.S[]: see also: <<floating-point-assembly>>
  8588. ====== ARM fadd vs vadd
  8589. 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: <<arm-vadd-instruction>>
  8590. The same goes for most ARMv7 mnemonics: `f*` is old, and `v*` is the newer better syntax.
  8591. But then, in ARMv8, they decided to use <<armv8-aarch64-fadd-instruction>> as the main floating point add name, and get rid of `vadd`!
  8592. Also keep in mind that fused multiply add is `fmadd`.
  8593. Examples at: <<simd-assembly>>
  8594. ===== ARMv8 aarch64 ld2 instruction
  8595. Example: link:userland/arch/aarch64/ld2.S[]
  8596. We can load multiple vectors interleaved from memory in one single instruction!
  8597. This is why the `ldN` instructions take an argument list denoted by `{}` for the registers, much like armv7 <<arm-ldmia-instruction>>.
  8598. There are analogous `ld3` and `ld4` instruction.
  8599. ==== ARM SIMD bibliography
  8600. * GNU GAS tests under link:https://sourceware.org/git/gitweb.cgi?p=binutils-gdb.git;a=tree;f=gas/testsuite/gas/aarch64;hb=00f223631fa9803b783515a2f667f86997e2cdbe[`gas/testsuite/gas/aarch64`]
  8601. * https://stackoverflow.com/questions/2851421/is-there-a-good-reference-for-arm-neon-intrinsics
  8602. * assembly optimized libraries:
  8603. ** https://github.com/projectNe10/Ne10
  8604. === ARM assembly bibliography
  8605. ==== ARM non-official bibliography
  8606. Good getting started tutorials:
  8607. * http://www.davespace.co.uk/arm/introduction-to-arm/
  8608. * https://azeria-labs.com/writing-arm-assembly-part-1/
  8609. * https://thinkingeek.com/arm-assembler-raspberry-pi/
  8610. * http://bob.cs.sonoma.edu/IntroCompOrg-RPi/app-make.html
  8611. ==== ARM official bibliography
  8612. The official manuals were stored in http://infocenter.arm.com but as of 2017 they started to slowly move to link:https://developer.arm.com[].
  8613. Each revision of a document has a "ARM DDI" unique document identifier.
  8614. The "ARM Architecture Reference Manuals" are the official canonical ISA documentation document. In this repository, we always reference the following revisions:
  8615. Bibliography: https://www.quora.com/Where-can-I-find-the-official-documentation-of-ARM-instruction-set-architectures-ISAs
  8616. [[armarm7]]
  8617. ===== ARMv7 architecture reference manual
  8618. https://developer.arm.com/products/architecture/a-profile/docs/ddi0406/latest/arm-architecture-reference-manual-armv7-a-and-armv7-r-edition
  8619. The official comprehensive ARMv7 reference.
  8620. We use by default: DDI 0406C.d: https://static.docs.arm.com/ddi0406/cd/DDI0406C_d_armv7ar_arm.pdf
  8621. [[armarm8]]
  8622. ===== ARMv8 architecture reference manual
  8623. https://static.docs.arm.com/ddi0487/ca/DDI0487C_a_armv8_arm.pdf
  8624. Latest version: https://developer.arm.com/docs/ddi0487/latest/arm-architecture-reference-manual-armv8-for-armv8-a-architecture-profile
  8625. The official comprehensive ARMv8 reference.
  8626. ISA quick references can be found in some places:
  8627. * https://web.archive.org/web/20161009122630/http://infocenter.arm.com/help/topic/com.arm.doc.qrc0001m/QRC0001_UAL.pdf
  8628. [[armv8-programmers-guide]]
  8629. ===== Programmer's Guide for ARMv8-A
  8630. https://static.docs.arm.com/den0024/a/DEN0024A_v8_architecture_PG.pdf
  8631. A more terse human readable introduction to the ARM architecture than the reference manuals.
  8632. Does not have as many assembly code examples as you'd hope however...
  8633. Latest version at: https://developer.arm.com/docs/den0024/latest/preface
  8634. == Baremetal
  8635. Getting started at: <<baremetal-setup>>
  8636. === Baremetal GDB step debug
  8637. GDB step debug works on baremetal exactly as it does on the Linux kernel: <<gdb>>.
  8638. Except that is is even cooler here since we can easily control and understand every single instruction that is being run!
  8639. For example, on the first shell:
  8640. ....
  8641. ./run --arch arm --baremetal baremetal/hello.c --gdb-wait
  8642. ....
  8643. then on the second shell:
  8644. ....
  8645. ./run-gdb --arch arm --baremetal baremetal/hello.c -- main
  8646. ....
  8647. Or if you are a <<tmux,tmux pro>>, do everything in one go with:
  8648. ....
  8649. ./run --arch arm --baremetal baremetal/hello.c --gdb
  8650. ....
  8651. Alternatively, to start from the very first executed instruction of our tiny <<baremetal-bootloaders>>:
  8652. ....
  8653. ./run \
  8654. --arch arm \
  8655. --baremetal baremetal/hello.c \
  8656. --gdb-wait \
  8657. --tmux-args=--no-continue \
  8658. ;
  8659. ....
  8660. Now you can just `stepi` to when jumping into main to go to the C code in link:baremetal/hello.c[].
  8661. This is specially interesting for the executables that don't use the bootloader from under `baremetal/arch/<arch>/no_bootloader/*.S`, e.g.:
  8662. ....
  8663. ./run \
  8664. --arch arm \
  8665. --baremetal baremetal/arch/arm/no_bootloader/semihost_exit.S \
  8666. --gdb-wait \
  8667. --tmux-args=--no-continue \
  8668. ;
  8669. ....
  8670. The cool thing about those examples is that you start at the very first instruction of your program, which gives more control.
  8671. === Baremetal bootloaders
  8672. 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:
  8673. * link:baremetal/lib/arm.S[]
  8674. * link:baremetal/lib/aarch64.S[]
  8675. Out simplistic bootloaders basically setup up just enough system state to allow calling:
  8676. * C functions such as `exit` from the assembly examples
  8677. * the `main` of C examples itself
  8678. The most important things that we setup in the bootloaders are:
  8679. * the stack pointer
  8680. * NEON: <<aarch64-baremetal-neon-setup>>
  8681. * TODO: we don't do this currently but maybe we should setup BSS
  8682. The C functions that become available as a result are:
  8683. * Newlib functions implemented at link:baremetal/lib/syscalls.c[]
  8684. * non-Newlib functions implemented at link:kwargs['c'][]
  8685. It is not possible to call those C functions from the examples that don't use a bootloader.
  8686. For this reason, we tend to create examples with bootloaders, as it is easier to write them portably.
  8687. === Semihosting
  8688. Semihosting is a publicly documented interface specified by ARM Holdings that allows us to do some magic operations very useful in development.
  8689. Semihosting is implemented both on some real devices and on simulators such as QEMU and <<gem5-semihosting>>.
  8690. It is documented at: https://developer.arm.com/docs/100863/latest/introduction
  8691. For example, the following code makes QEMU exit:
  8692. ....
  8693. ./run --arch arm --baremetal baremetal/arch/arm/semihost_exit.S
  8694. ....
  8695. Source: link:baremetal/arch/arm/no_bootloader/semihost_exit.S[]
  8696. That program program contains the code:
  8697. ....
  8698. mov r0, #0x18
  8699. ldr r1, =#0x20026
  8700. svc 0x00123456
  8701. ....
  8702. and we can see from the docs that `0x18` stands for the `SYS_EXIT` command.
  8703. This is also how we implement the `exit(0)` system call in C for QEMU for link:baremetal/exit0.c[] through the Newlib via the function `_exit` at link:baremetal/lib/kwargs['c'][].
  8704. Other magic operations we can do with semihosting besides exiting the on the host include:
  8705. * read and write to host stdin and stdout
  8706. * read and write to host files
  8707. Alternatives exist for some semihosting operations, e.g.:
  8708. * UART IO for host stdin and stdout in both emulators and real hardware
  8709. * <<m5ops>> for <<gem5>>, e.g. `m5 exit` makes the emulator quit
  8710. 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.
  8711. The downside of semihosting is that it is ARM specific. TODO is it an open standard that other vendors can implement?
  8712. In QEMU, we enable semihosting with:
  8713. ....
  8714. -semihosting
  8715. ....
  8716. Newlib 9c84bfd47922aad4881f80243320422b621c95dc already has a semi-hosting implementation at:
  8717. ....
  8718. newlib/libc/sys/arm/syscalls.c
  8719. ....
  8720. TODO: how to use it? Possible through crosstool-NG? In the worst case we could just copy it.
  8721. Bibliography:
  8722. * https://stackoverflow.com/questions/31990487/how-to-cleanly-exit-qemu-after-executing-bare-metal-program-without-user-interve/40957928#40957928
  8723. * https://balau82.wordpress.com/2010/11/04/qemu-arm-semihosting/
  8724. ==== gem5 semihosting
  8725. For gem5, you need:
  8726. ....
  8727. patch -d "$(./getvar gem5_source_dir)" -p 1 < patches/manual/gem5-semihost.patch
  8728. ....
  8729. https://stackoverflow.com/questions/52475268/how-to-enable-arm-semihosting-in-gem5/52475269#52475269
  8730. === gem5 baremetal carriage return
  8731. TODO: our example is printing newlines without automatic carriage return `\r` as in:
  8732. ....
  8733. enter a character
  8734. got: a
  8735. ....
  8736. We use `m5term` by default, and if we try `telnet` instead:
  8737. ....
  8738. telnet localhost 3456
  8739. ....
  8740. it does add the carriage returns automatically.
  8741. === Baremetal host packaged toolchain
  8742. For `arm`, some baremetal examples compile fine with:
  8743. ....
  8744. sudo apt-get install gcc-arm-none-eabi qemu-system-arm
  8745. ./build-baremetal --arch arm --gcc-which host-baremetal
  8746. ./run --arch arm --baremetal baremetal/hello.c --qemu-which host
  8747. ....
  8748. However, there are as usual limitations to using prebuilts:
  8749. * certain examples fail to build with the Ubuntu packaged toolchain. E.g.: link:baremetal/exit0.c[] fails with:
  8750. +
  8751. ....
  8752. /usr/lib/gcc/arm-none-eabi/6.3.1/../../../arm-none-eabi/lib/libg.a(lib_a-fini.o): In function `__libc_fini_array':
  8753. /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'
  8754. collect2: error: ld returned 1 exit status
  8755. ....
  8756. +
  8757. with the prebuilt toolchain, and I'm lazy to debug.
  8758. * 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
  8759. === C++ baremetal
  8760. TODO I tried by there was an error. Not yet properly reported. 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
  8761. === GDB builtin CPU simulator
  8762. 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
  8763. TODO: any advantage over QEMU? I doubt it, mostly using it as as toy for now:
  8764. Without running `./run`, do directly:
  8765. ....
  8766. ./run-gdb --arch arm --baremetal baremetal/hello.c --sim
  8767. ....
  8768. Then inside GDB:
  8769. ....
  8770. load
  8771. starti
  8772. ....
  8773. and now you can debug normally.
  8774. Enabled with the crosstool-NG configuration:
  8775. ....
  8776. CT_GDB_CROSS_SIM=y
  8777. ....
  8778. which by grepping crosstool-NG we can see does on GDB:
  8779. ....
  8780. ./configure --enable-sim
  8781. ....
  8782. Those are not set by default on `gdb-multiarch` in Ubuntu 16.04.
  8783. Bibliography:
  8784. * https://stackoverflow.com/questions/49470659/arm-none-eabi-gdb-undefined-target-command-sim
  8785. * http://cs107e.github.io/guides/gdb/
  8786. ==== GDB builtin CPU simulator userland
  8787. Since I had this compiled, I also decided to try it out on userland.
  8788. 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
  8789. It just ignores the `swi` however, and does not forward syscalls to the host like QEMU does.
  8790. Then I tried a glibc example: https://github.com/cirosantilli/arm-assembly-cheat/blob/cd232dcaf32c0ba6399b407e0b143d19b6ec15f4/v7/mov.S
  8791. First it wouldn't break, so I added `-static` to the `Makefile`, and then it started failing with:
  8792. ....
  8793. Unhandled v6 thumb insn
  8794. ....
  8795. Doing:
  8796. ....
  8797. help architecture
  8798. ....
  8799. shows ARM version up to `armv6`, so maybe `armv6` is not implemented?
  8800. === ARM baremetal
  8801. In this section we will focus on learning ARM architecture concepts that can only learnt on baremetal setups.
  8802. Userland information can be found at: https://github.com/cirosantilli/arm-assembly-cheat
  8803. ==== ARM exception level
  8804. ARM exception levels are analogous to x86 <<ring0,rings>>.
  8805. Print the EL at the beginning of a baremetal simulation:
  8806. ....
  8807. ./run --arch arm --baremetal baremetal/arch/arm/el.c
  8808. ./run --arch aarch64 --baremetal baremetal/arch/aarch64/el.c
  8809. ....
  8810. Sources:
  8811. * link:baremetal/arch/arm/el.c[]
  8812. * link:baremetal/arch/aarch64/el.c[]
  8813. The instructions that find the ARM EL are explained at: https://stackoverflow.com/questions/31787617/what-is-the-current-execution-mode-exception-level-etc
  8814. The lower ELs are not mandated by the architecture, and can be controlled through command line options in QEMU and gem5.
  8815. 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
  8816. ....
  8817. ./run --arch arm --baremetal baremetal/arch/arm/el.c
  8818. ./run --arch arm --baremetal baremetal/arch/arm/el.c -- -machine virtualization=on
  8819. ./run --arch arm --baremetal baremetal/arch/arm/el.c -- -machine secure=on
  8820. ./run --arch aarch64 --baremetal baremetal/arch/aarch64/el.c
  8821. ./run --arch aarch64 --baremetal baremetal/arch/aarch64/el.c -- -machine virtualization=on
  8822. ./run --arch aarch64 --baremetal baremetal/arch/aarch64/el.c -- -machine secure=on
  8823. ....
  8824. outputs respectively:
  8825. ....
  8826. 19
  8827. 19
  8828. 19
  8829. 1
  8830. 2
  8831. 3
  8832. ....
  8833. TODO: why is `arm` stuck at `19` which equals Supervisor mode?
  8834. In gem5, you can configure the lowest EL with:
  8835. ....
  8836. ./run --arch arm --baremetal baremeta/arch/arm/el.c --emulator gem5
  8837. cat "$(./getvar --arch arm --emulator gem5 gem5_guest_terminal_file)"
  8838. ./run --arch arm --baremetal baremetal/arch/arm/el.c --emulator gem5 -- --param 'system.have_virtualization = True'
  8839. cat "$(./getvar --arch arm --emulator gem5 gem5_guest_terminal_file)"
  8840. ./run --arch arm --baremetal baremetal/arch/arm/el.c --emulator gem5 -- --param 'system.have_security = True'
  8841. cat "$(./getvar --arch arm --emulator gem5 gem5_guest_terminal_file)"
  8842. ./run --arch aarch64 --baremetal baremetal/arch/aarch64/el.c --emulator gem5
  8843. cat "$(./getvar --arch aarch64 --emulator gem5 gem5_guest_terminal_file)"
  8844. ./run --arch aarch64 --baremetal baremetal/arch/aarch64/el.c --emulator gem5 -- --param 'system.have_virtualization = True'
  8845. cat "$(./getvar --arch aarch64 --emulator gem5 gem5_guest_terminal_file)"
  8846. ./run --arch aarch64 --baremetal baremetal/arch/aarch64/el.c --emulator gem5 -- --param 'system.have_security = True'
  8847. cat "$(./getvar --arch aarch64 --emulator gem5 gem5_guest_terminal_file)"
  8848. ....
  8849. output:
  8850. ....
  8851. 19
  8852. 26
  8853. 19
  8854. 1
  8855. 2
  8856. 3
  8857. ....
  8858. ==== svc
  8859. This is the most basic example of exception handling we have.
  8860. We a handler for `svc`, do an `svc`, and observe that the handler got called and returned from C and assembly:
  8861. ....
  8862. ./run --arch aarch64 --baremetal baremetal/arch/aarch64/svc.c
  8863. ./run --arch aarch64 --baremetal baremetal/arch/aarch64/svc_asm.S
  8864. ....
  8865. Sources:
  8866. * link:baremetal/arch/aarch64/svc.c[]
  8867. * link:baremetal/arch/aarch64/svc_asm.S[]
  8868. Sample output for the C one:
  8869. ....
  8870. daif 0x3c0
  8871. spsel 0x1
  8872. vbar_el1 0x40000800
  8873. lkmc_vector_trap_handler
  8874. exc_type 0x11
  8875. exc_type is LKMC_VECTOR_SYNC_SPX
  8876. ESR 0x56000042
  8877. SP 0x4200bba8
  8878. ELR 0x40002470
  8879. SPSR 0x600003c5
  8880. x0 0x0
  8881. x1 0x1
  8882. x2 0x14
  8883. x3 0x14
  8884. x4 0x40008390
  8885. x5 0xfffffff8
  8886. x6 0x4200ba28
  8887. x7 0x0
  8888. x8 0x0
  8889. x9 0x13
  8890. x10 0x0
  8891. x11 0x0
  8892. x12 0x0
  8893. x13 0x0
  8894. x14 0x0
  8895. x15 0x0
  8896. x16 0x0
  8897. x17 0x0
  8898. x18 0x0
  8899. x19 0x0
  8900. x20 0x0
  8901. x21 0x0
  8902. x22 0x0
  8903. x23 0x0
  8904. x24 0x0
  8905. x25 0x0
  8906. x26 0x0
  8907. x27 0x0
  8908. x28 0x0
  8909. x29 0x4200bba8
  8910. x30 0x4000246c
  8911. ....
  8912. 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:
  8913. ....
  8914. ./run \
  8915. --arch aarch64 \
  8916. --baremetal baremetal/arch/aarch64/svc_asm.S
  8917. -- -d in_asm,int \
  8918. ;
  8919. ....
  8920. contains:
  8921. ....
  8922. ----------------
  8923. IN:
  8924. 0x40002060: d4000001 svc #0
  8925. Taking exception 2 [SVC]
  8926. ...from EL1 to EL1
  8927. ...with ESR 0x15/0x56000000
  8928. ...with ELR 0x40002064
  8929. ...to EL1 PC 0x40000a00 PSTATE 0x3c5
  8930. ----------------
  8931. IN:
  8932. 0x40000a00: 14000225 b #0x40001294
  8933. ....
  8934. and:
  8935. ....
  8936. ./run \
  8937. --arch aarch64 \
  8938. --baremetal baremetal/arch/aarch64/svc_asm.S \
  8939. --trace ExecAll,Faults \
  8940. --trace-stdout \
  8941. ;
  8942. ....
  8943. contains:
  8944. ....
  8945. 4000: system.cpu A0 T0 : @main+8 : svc #0x0 : IntAlu : flags=(IsSerializeAfter|IsNonSpeculative|IsSyscall)
  8946. 4000: Supervisor Call: Invoking Fault (AArch64 target EL):Supervisor Call cpsr:0x3c5 PC:0x80000808 elr:0x8000080c newVec: 0x80001200
  8947. 4500: system.cpu A0 T0 : @vector_table+512 : b <_curr_el_spx_sync> : IntAlu : flags=(IsControl|IsDirectControl|IsUncondControl)
  8948. ....
  8949. So we see in both cases that the `svc` is done, then an exception happens, and then we just continue running from the exception handler address.
  8950. The vector table format is described on <<armarm8>> Table D1-7 "Vector offsets from vector table base address".
  8951. 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".
  8952. The first part of the table contains:
  8953. [options="header"]
  8954. |===
  8955. |Address |Exception type |Description
  8956. |VBAR_ELn + 0x000
  8957. |Synchronous
  8958. |Current EL with SP0
  8959. |VBAR_ELn + 0x080
  8960. |IRQ/vIRQ + 0x100
  8961. |Current EL with SP0
  8962. |VBAR_ELn + 0x100
  8963. |FIQ/vFIQ
  8964. |Current EL with SP0
  8965. |VBAR_ELn + 0x180
  8966. |SError/vSError
  8967. |Current EL with SP0
  8968. |===
  8969. and the following other parts are analogous, but referring to `SPx` and lower ELs.
  8970. We are going to do everything in <<arm-exception-level,EL1>> for now.
  8971. On the terminal output, we observe the initial values of:
  8972. * `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.
  8973. +
  8974. This reset value is defined by <<armarm8>> C5.2.2 "DAIF, Interrupt Mask Bits".
  8975. * `SPSel`: `0x1`, which means: use `SPx` instead of `SP0`.
  8976. +
  8977. This reset value is defined by <<armarm8>> C5.2.16 "SPSel, Stack Pointer Select".
  8978. * `VBAR_EL1`: `0x0` holds the base address of the vector table
  8979. +
  8980. 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.
  8981. Bibliography:
  8982. * https://github.com/torvalds/linux/blob/v4.20/arch/arm64/kernel/entry.S#L430 this is where the kernel defines the vector table
  8983. * https://github.com/dwelch67/qemu_arm_samples/tree/07162ba087111e0df3f44fd857d1b4e82458a56d/swi01
  8984. * https://github.com/NienfengYao/armv8-bare-metal/blob/572c6f95880e70aa92fe9fed4b8ad7697082a764/vector.S#L168
  8985. * https://stackoverflow.com/questions/51094092/how-to-make-timer-irq-work-on-qemu-machine-virt-cpu-cortex-a57
  8986. * https://stackoverflow.com/questions/44991264/armv8-exception-vectors-and-handling
  8987. * https://stackoverflow.com/questions/44198483/arm-timers-and-interrupts
  8988. ==== ARM multicore
  8989. ....
  8990. ./run --arch aarch64 --baremetal baremetal/arch/aarch64/multicore.S --cpus 2
  8991. ./run --arch aarch64 --baremetal baremetal/arch/aarch64/multicore.S --cpus 2 --emulator gem5
  8992. ./run --arch arm --baremetal baremetal/arch/aarch64/multicore.S --cpus 2
  8993. ./run --arch arm --baremetal baremetal/arch/aarch64/multicore.S --cpus 2 --emulator gem5
  8994. ....
  8995. Sources:
  8996. * link:baremetal/arch/aarch64/multicore.S[]
  8997. * link:baremetal/arch/arm/multicore.S[]
  8998. CPU 0 of this program enters a spinlock loop: it repeatedly checks if a given memory address is `1`.
  8999. 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!
  9000. Don't believe me? Then try:
  9001. ....
  9002. ./run --arch aarch64 --baremetal baremetal/arch/aarch64/multicore.S --cpus 1
  9003. ....
  9004. and watch it hang forever.
  9005. Note that if you try the same thing on gem5:
  9006. ....
  9007. ./run --arch aarch64 --baremetal baremetal/arch/aarch64/multicore.S --cpus 1 --emulator gem5
  9008. ....
  9009. then the gem5 actually exits, but with a different message:
  9010. ....
  9011. Exiting @ tick 18446744073709551615 because simulate() limit reached
  9012. ....
  9013. as opposed to the expected:
  9014. ....
  9015. Exiting @ tick 36500 because m5_exit instruction encountered
  9016. ....
  9017. since gem5 is able to detect when nothing will ever happen, and exits.
  9018. When GDB step debugging, switch between cores with the usual `thread` commands, see also: <<gdb-step-debug-multicore-userland>>.
  9019. Bibliography: https://stackoverflow.com/questions/980999/what-does-multicore-assembly-language-look-like/33651438#33651438
  9020. ===== WFE and SEV
  9021. The `WFE` and `SEV` instructions are just hints: a compliant implementation can treat them as NOPs.
  9022. However, likely no implementation likely does (TODO confirm), since:
  9023. * `WFE` puts the core in a low power mode
  9024. * `SEV` wakes up cores from a low power mode
  9025. and power consumption is key in ARM applications.
  9026. 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
  9027. ....
  9028. case 2: /* WFE */
  9029. if (!(tb_cflags(s->base.tb) & CF_PARALLEL)) {
  9030. s->base.is_jmp = DISAS_WFE;
  9031. }
  9032. return;
  9033. case 4: /* SEV */
  9034. case 5: /* SEVL */
  9035. /* we treat all as NOP at least for now */
  9036. return;
  9037. ....
  9038. 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% ;-)):
  9039. ....
  9040. * For WFI we will halt the vCPU until an IRQ. For WFE and YIELD we
  9041. * only call the helper when running single threaded TCG code to ensure
  9042. * the next round-robin scheduled vCPU gets a crack. In MTTCG mode we
  9043. * just skip this instruction. Currently the SEV/SEVL instructions
  9044. * which are *one* of many ways to wake the CPU from WFE are not
  9045. * implemented so we can't sleep like WFI does.
  9046. */
  9047. ....
  9048. 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.
  9049. The following Raspberry Pi bibliography helped us get this sample up and running:
  9050. * https://github.com/bztsrc/raspi3-tutorial/tree/a3f069b794aeebef633dbe1af3610784d55a0efa/02_multicorec
  9051. * https://github.com/dwelch67/raspberrypi/tree/a09771a1d5a0b53d8e7a461948dc226c5467aeec/multi00
  9052. * https://github.com/LdB-ECM/Raspberry-Pi/blob/3b628a2c113b3997ffdb408db03093b2953e4961/Multicore/SmartStart64.S
  9053. * https://github.com/LdB-ECM/Raspberry-Pi/blob/3b628a2c113b3997ffdb408db03093b2953e4961/Multicore/SmartStart32.S
  9054. ===== PSCI
  9055. In QEMU, CPU 1 starts in a halted state. This can be observed from GDB, where:
  9056. ....
  9057. info threads
  9058. ....
  9059. shows something like:
  9060. ....
  9061. * 1 Thread 1 (CPU#0 [running]) mystart
  9062. 2 Thread 2 (CPU#1 [halted ]) mystart
  9063. ....
  9064. To wake up CPU 1 on QEMU, we must use the Power State Coordination Interface (PSCI) which is documented at: link:https://developer.arm.com/docs/den0022/latest/arm-power-state-coordination-interface-platform-design-document[].
  9065. This interface uses `HVC` calls, and the calling convention is documented at "SMC CALLING CONVENTION" link:https://developer.arm.com/docs/den0028/latest[].
  9066. 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:
  9067. ....
  9068. psci {
  9069. method = "hvc";
  9070. compatible = "arm,psci-0.2", "arm,psci";
  9071. cpu_on = <0xc4000003>;
  9072. migrate = <0xc4000005>;
  9073. cpu_suspend = <0xc4000001>;
  9074. cpu_off = <0x84000002>;
  9075. };
  9076. ....
  9077. 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 :-)
  9078. 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.
  9079. Bibliography: https://stackoverflow.com/questions/20055754/arm-start-wakeup-bringup-the-other-cpu-cores-aps-and-pass-execution-start-addre/53473447#53473447
  9080. ===== DMB
  9081. 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
  9082. ==== ARM baremetal bibliography
  9083. First, also consider the userland bibliography: <<arm-assembly-bibliography>>.
  9084. The most useful ARM baremetal example sets we've seen so far are:
  9085. * https://github.com/dwelch67/raspberrypi real hardware
  9086. * https://github.com/dwelch67/qemu_arm_samples QEMU `-m vexpress`
  9087. * https://github.com/bztsrc/raspi3-tutorial real hardware + QEMU `-m raspi`
  9088. * https://github.com/LdB-ECM/Raspberry-Pi real hardware
  9089. ===== armv8-bare-metal
  9090. https://github.com/NienfengYao/armv8-bare-metal
  9091. The only QEMU `-m virt` aarch64 example set that I can find on the web. Awesome.
  9092. 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.
  9093. I needed the following minor patches: https://github.com/NienfengYao/armv8-bare-metal/pull/1
  9094. === How we got some baremetal stuff to work
  9095. It is nice when thing just work.
  9096. But you can also learn a thing or two from how I actually made them work in the first place.
  9097. ==== Find the UART address
  9098. Enter the QEMU console:
  9099. ....
  9100. Ctrl-X C
  9101. ....
  9102. Then do:
  9103. ....
  9104. info mtree
  9105. ....
  9106. And look for `pl011`:
  9107. ....
  9108. 0000000009000000-0000000009000fff (prio 0, i/o): pl011
  9109. ....
  9110. 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
  9111. ....
  9112. class RealViewPBX(RealView):
  9113. uart = Pl011(pio_addr=0x10009000, int_num=44)
  9114. ....
  9115. ==== aarch64 baremetal NEON setup
  9116. Inside link:baremetal/lib/aarch64.S[] there is a chunk of code called "NEON setup".
  9117. Without that, the `printf`:
  9118. ....
  9119. printf("got: %c\n", c);
  9120. ....
  9121. compiled to a:
  9122. ....
  9123. str q0, [sp, #80]
  9124. ....
  9125. which uses NEON registers, and goes into an exception loop.
  9126. It was a bit confusing because there was a previous `printf`:
  9127. ....
  9128. printf("enter a character\n");
  9129. ....
  9130. which did not blow up because GCC compiles it into `puts` directly since it has no arguments, and that does not generate NEON instructions.
  9131. The last instructions ran was found with:
  9132. ....
  9133. while(1)
  9134. stepi
  9135. end
  9136. ....
  9137. or by hacking the QEMU CLI to contain:
  9138. .....
  9139. -D log.log -d in_asm
  9140. .....
  9141. I could not find any previous NEON instruction executed so this led me to suspect that some NEON initialization was required:
  9142. * 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"
  9143. * https://community.arm.com/processors/f/discussions/5409/how-to-enable-neon-in-cortex-a8
  9144. * https://stackoverflow.com/questions/19231197/enable-neon-on-arm-cortex-a-series
  9145. We then tried to copy the code from the "Bare-metal Boot Code for ARMv8-A Processors" document:
  9146. ....
  9147. // Disable trapping of accessing in EL3 and EL2.
  9148. MSR CPTR_EL3, XZR
  9149. MSR CPTR_EL3, XZR
  9150. // Disable access trapping in EL1 and EL0.
  9151. MOV X1, #(0x3 << 20) // FPEN disables trapping to EL1.
  9152. MSR CPACR_EL1, X1
  9153. ISB
  9154. ....
  9155. but it entered an exception loop at `MSR CPTR_EL3, XZR`.
  9156. We then found out that QEMU starts in EL1, and so we kept just the EL1 part, and it worked. Related:
  9157. * https://stackoverflow.com/questions/42824706/qemu-system-aarch64-entering-el1-when-emulating-a53-power-up
  9158. * https://stackoverflow.com/questions/37299524/neon-support-in-armv8-system-mode-qemu
  9159. === Baremetal tests
  9160. Automatically run all non-interactive baremetal tests:
  9161. ....
  9162. ./test-baremetal --arch aarch64
  9163. ....
  9164. Source: link:test-baremetal[]
  9165. Analogously to <<user-mode-tests>>, we can select individual tests or directories with:
  9166. ....
  9167. ./test-baremetal --arch aarch64 baremetal/hello.c baremetal/arch/aarch64/no_bootloader/
  9168. ....
  9169. which would run all of:
  9170. * link:baremetal/hello.c[]
  9171. * all tests under the directory: link:baremetal/arch/aarch64/no_bootloader/[]
  9172. We detect if tests failed by parsing logs for the <<magic-failure-string>>.
  9173. We also skip tests that cannot work on certain conditions based on their basenames, e.g.:
  9174. * tests that start with `gem5_` only run in `gem5`
  9175. * tests that start with `semihost_` only run in QEMU, until we find a better way to automate <<gem5-semihosting>>
  9176. See: <<test-this-repo>> for more useful testing tips.
  9177. === Baremetal bibliography
  9178. https://stackoverflow.com/questions/43682311/uart-communication-in-gem5-with-arm-bare-metal
  9179. https://github.com/tukl-msd/gem5.bare-metal contains an alternative working baremetal setup. Our setup has more features at the time of writing however. Usage:
  9180. ....
  9181. # Build gem5.
  9182. git clone https://gem5.googlesource.com/public/gem5
  9183. cd gem5
  9184. git checkout 60600f09c25255b3c8f72da7fb49100e2682093a
  9185. scons --ignore-style -j`nproc` build/ARM/gem5.opt
  9186. cd ..
  9187. # Build example.
  9188. sudo apt-get install gcc-arm-none-eabi
  9189. git clone https://github.com/tukl-msd/gem5.bare-metal
  9190. cd gem5.bare-metal
  9191. git checkout 6ad1069d4299b775b5491e9252739166bfac9bfe
  9192. cd Simple
  9193. make CROSS_COMPILE_DIR=/usr/bin
  9194. # Run example.
  9195. ../../gem5/default/build/ARM/gem5.opt' \
  9196. ../../gem5/configs/example/fs.py' \
  9197. --bare-metal \
  9198. --disk-image="$(pwd)/../common/fake.iso" \
  9199. --kernel="$(pwd)/main.elf" \
  9200. --machine-type=RealView_PBX \
  9201. --mem-size=256MB \
  9202. ;
  9203. ....
  9204. == Android
  9205. Remember: Android AOSP is a huge undocumented piece of bloatware. It's integration into this repo will likely never be super good.
  9206. Verbose setup description: https://stackoverflow.com/questions/1809774/how-to-compile-the-android-aosp-kernel-and-test-it-with-the-android-emulator/48310014#48310014
  9207. Download, build and run with the prebuilt AOSP QEMU emulator and the AOSP kernel:
  9208. ....
  9209. ./build-android \
  9210. --android-base-dir /path/to/your/hd \
  9211. --android-version 8.1.0_r60 \
  9212. download \
  9213. build \
  9214. ;
  9215. ./run-android \
  9216. --android-base-dir /path/to/your/hd \
  9217. --android-version 8.1.0_r60 \
  9218. ;
  9219. ....
  9220. Sources:
  9221. * link:build-android[]
  9222. * link:run-android[]
  9223. TODO how to hack the AOSP kernel, userland and emulator?
  9224. Other archs work as well as usual with `--arch` parameter. However, running in non-x86 is very slow due to the lack of KVM.
  9225. Tested on: `8.1.0_r60`.
  9226. === Android image structure
  9227. https://source.android.com/devices/bootloader/partitions-images
  9228. The messy AOSP generates a ton of images instead of just one.
  9229. When the emulator launches, we can see them through QEMU `-drive` arguments:
  9230. ....
  9231. emulator: argv[21] = "-initrd"
  9232. emulator: argv[22] = "/data/aosp/8.1.0_r60/out/target/product/generic_x86_64/ramdisk.img"
  9233. emulator: argv[23] = "-drive"
  9234. 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"
  9235. emulator: argv[25] = "-device"
  9236. emulator: argv[26] = "virtio-blk-pci,drive=system,iothread=disk-iothread,modern-pio-notify"
  9237. emulator: argv[27] = "-drive"
  9238. 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"
  9239. emulator: argv[29] = "-device"
  9240. emulator: argv[30] = "virtio-blk-pci,drive=cache,iothread=disk-iothread,modern-pio-notify"
  9241. emulator: argv[31] = "-drive"
  9242. 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"
  9243. emulator: argv[33] = "-device"
  9244. emulator: argv[34] = "virtio-blk-pci,drive=userdata,iothread=disk-iothread,modern-pio-notify"
  9245. emulator: argv[35] = "-drive"
  9246. 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"
  9247. emulator: argv[37] = "-device"
  9248. emulator: argv[38] = "virtio-blk-pci,drive=encrypt,iothread=disk-iothread,modern-pio-notify"
  9249. emulator: argv[39] = "-drive"
  9250. 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"
  9251. emulator: argv[41] = "-device"
  9252. emulator: argv[42] = "virtio-blk-pci,drive=vendor,iothread=disk-iothread,modern-pio-notify"
  9253. ....
  9254. The root directory is the <<initrd>> given on the QEMU CLI, which `/proc/mounts` reports at:
  9255. ....
  9256. rootfs on / type rootfs (ro,seclabel,size=886392k,nr_inodes=221598)
  9257. ....
  9258. This contains the <<android-init>>, which through `.rc` must be mounting mounts the drives int o the right places TODO find exact point.
  9259. The drive order is:
  9260. ....
  9261. system
  9262. cache
  9263. userdata
  9264. encryptionkey
  9265. vendor-qemu
  9266. ....
  9267. Then, on the terminal:
  9268. ....
  9269. mount | grep vd
  9270. ....
  9271. gives:
  9272. ....
  9273. /dev/block/vda1 on /system type ext4 (ro,seclabel,relatime,data=ordered)
  9274. /dev/block/vde1 on /vendor type ext4 (ro,seclabel,relatime,data=ordered)
  9275. /dev/block/vdb on /cache type ext4 (rw,seclabel,nosuid,nodev,noatime,errors=panic,data=ordered)
  9276. ....
  9277. and we see that the order of `vda`, `vdb`, etc. matches that in which `-drive` were given to QEMU.
  9278. Tested on: `8.1.0_r60`.
  9279. ==== Android images read-only
  9280. From `mount`, we can see that some of the mounted images are `ro`.
  9281. Basically, every image that was given to QEMU as qcow2 is writable, and that qcow2 is an overlay over the actual original image.
  9282. In order to make `/system` and `/vendor` writable by using qcow2 for them as well, we must use the `-writable-system` option:
  9283. ....
  9284. ./run-android -- -writable-system
  9285. ....
  9286. * https://android.stackexchange.com/questions/110927/how-to-mount-system-rewritable-or-read-only-rw-ro/207200#207200
  9287. * https://stackoverflow.com/questions/13089694/adb-remount-permission-denied-but-able-to-access-super-user-in-shell-android/43163693#43163693
  9288. then:
  9289. ....
  9290. su
  9291. mount -o rw,remount /system
  9292. date >/system/a
  9293. ....
  9294. Now reboot, and relaunch with `-writable-system` once again to pick up the modified qcow2 images:
  9295. ....
  9296. ./run-android -- -writable-system
  9297. ....
  9298. and the newly created file is still there:
  9299. ....
  9300. date >/system/a
  9301. ....
  9302. `/system` and `/vendor` can be nuked quickly with:
  9303. ....
  9304. ./build-android --extra-args snod
  9305. ./build-android --extra-args vnod
  9306. ....
  9307. as mentioned at: https://stackoverflow.com/questions/29023406/how-to-just-build-android-system-image and on:
  9308. ....
  9309. ./build-android --extra-args help
  9310. ....
  9311. Tested on: `8.1.0_r60`.
  9312. ==== Android /data partition
  9313. When I install an app like F-Droid, it goes under `/data` according to:
  9314. ....
  9315. find / -iname '*fdroid*'
  9316. ....
  9317. and it <<disk-persistency,persists across boots>>.
  9318. `/data` is behind a RW LVM device:
  9319. ....
  9320. /dev/block/dm-0 on /data type ext4 (rw,seclabel,nosuid,nodev,noatime,errors=panic,data=ordered)
  9321. ....
  9322. but TODO I can't find where it comes from since I don't have the CLI tools mentioned at:
  9323. * https://superuser.com/questions/131519/what-is-this-dm-0-device
  9324. * https://unix.stackexchange.com/questions/185057/where-does-lvm-store-its-configuration
  9325. However, by looking at:
  9326. ....
  9327. ./run-android -- -help
  9328. ....
  9329. we see:
  9330. ....
  9331. -data <file> data image (default <datadir>/userdata-qemu.img
  9332. ....
  9333. which confirms the suspicion that this data goes in `userdata-qemu.img`.
  9334. 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
  9335. Tested on: `8.1.0_r60`.
  9336. === Install Android apps
  9337. 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`:
  9338. * https://android.stackexchange.com/questions/6984/how-to-download-files-from-the-web-in-the-android-browser
  9339. * https://stackoverflow.com/questions/26775079/wget-in-android-terminal
  9340. Installing with `adb install` does however work: https://stackoverflow.com/questions/7076240/install-an-apk-file-from-command-prompt
  9341. link: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/
  9342. And the `Settings` app crashes so I can't change it, logcat contains:
  9343. ....
  9344. No service published for: wifip2p
  9345. ....
  9346. which is mentioned at: https://stackoverflow.com/questions/47839955/android-8-settings-app-crashes-on-emulator-with-clean-aosp-build
  9347. We also tried to enable it from the command line with:
  9348. ....
  9349. settings put secure install_non_market_apps 1
  9350. ....
  9351. 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.
  9352. No person alive seems to know how to pre-install apps on AOSP: https://stackoverflow.com/questions/6249458/pre-installing-android-application
  9353. Tested on: `8.1.0_r60`.
  9354. === Android init
  9355. For Linux in general, see: <<init>>.
  9356. 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
  9357. The top of that file then sources other `.rc` files present on the root directory:
  9358. ....
  9359. import /init.environ.rc
  9360. import /init.usb.rc
  9361. import /init.${ro.hardware}.rc
  9362. import /vendor/etc/init/hw/init.${ro.hardware}.rc
  9363. import /init.usb.configfs.rc
  9364. import /init.${ro.zygote}.rc
  9365. ....
  9366. 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:
  9367. ....
  9368. getprop ro.hardware
  9369. ....
  9370. This gives:
  9371. ....
  9372. ranchu
  9373. ....
  9374. 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
  9375. 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
  9376. Tested on: `8.1.0_r60`.
  9377. == Benchmark this repo
  9378. TODO: didn't fully port during refactor after 3b0a343647bed577586989fb702b760bd280844a. Reimplementing should not be hard.
  9379. In this section document how benchmark builds and runs of this repo, and how to investigate what the bottleneck is.
  9380. Ideally, we should setup an automated build server that benchmarks those things continuously for us, but our <<travis>> attempt failed.
  9381. So currently, we are running benchmarks manually when it seems reasonable and uploading them to: https://github.com/cirosantilli/linux-kernel-module-cheat-regression
  9382. All benchmarks were run on the <<p51>> machine, unless stated otherwise.
  9383. Run all benchmarks and upload the results:
  9384. ....
  9385. cd ..
  9386. git clone https://github.com/cirosantilli/linux-kernel-module-cheat-regression
  9387. cd -
  9388. ./bench-all -A
  9389. ....
  9390. === Travis
  9391. 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.
  9392. === Benchmark this repo benchmarks
  9393. ==== Benchmark Linux kernel boot
  9394. Run all kernel boot benchmarks for one arch:
  9395. ....
  9396. ./build-test-boot --size 3 && ./test-boot --size 3
  9397. cat "$(./getvar test_boot_benchmark_file)"
  9398. ....
  9399. Sample results at 8fb9db39316d43a6dbd571e04dd46ae73915027f:
  9400. ....
  9401. cmd ./run --arch x86_64 --eval './linux/poweroff.out'
  9402. time 8.25
  9403. exit_status 0
  9404. cmd ./run --arch x86_64 --eval './linux/poweroff.out' --kvm
  9405. time 1.22
  9406. exit_status 0
  9407. cmd ./run --arch x86_64 --eval './linux/poweroff.out' --trace exec_tb
  9408. time 8.83
  9409. exit_status 0
  9410. instructions 2244297
  9411. cmd ./run --arch x86_64 --eval 'm5 exit' --emulator gem5
  9412. time 213.39
  9413. exit_status 0
  9414. instructions 318486337
  9415. cmd ./run --arch arm --eval './linux/poweroff.out'
  9416. time 6.62
  9417. exit_status 0
  9418. cmd ./run --arch arm --eval './linux/poweroff.out' --trace exec_tb
  9419. time 6.90
  9420. exit_status 0
  9421. instructions 776374
  9422. cmd ./run --arch arm --eval 'm5 exit' --emulator gem5
  9423. time 118.46
  9424. exit_status 0
  9425. instructions 153023392
  9426. 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
  9427. time 2250.40
  9428. exit_status 0
  9429. instructions 151981914
  9430. cmd ./run --arch aarch64 --eval './linux/poweroff.out'
  9431. time 4.94
  9432. exit_status 0
  9433. cmd ./run --arch aarch64 --eval './linux/poweroff.out' --trace exec_tb
  9434. time 5.04
  9435. exit_status 0
  9436. instructions 233162
  9437. cmd ./run --arch aarch64 --eval 'm5 exit' --emulator gem5
  9438. time 70.89
  9439. exit_status 0
  9440. instructions 124346081
  9441. 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
  9442. time 381.86
  9443. exit_status 0
  9444. instructions 124564620
  9445. cmd ./run --arch aarch64 --eval 'm5 exit' --emulator gem5 --gem5-build-type fast
  9446. time 58.00
  9447. exit_status 0
  9448. instructions 124346081
  9449. cmd ./run --arch aarch64 --eval 'm5 exit' --emulator gem5 --gem5-build-type debug
  9450. time 1022.03
  9451. exit_status 0
  9452. instructions 124346081
  9453. ....
  9454. TODO: aarch64 gem5 and QEMU use the same kernel, so why is the gem5 instruction count so much much higher?
  9455. ===== gem5 arm HPI boot takes much longer than aarch64
  9456. TODO 62f6870e4e0b384c4bd2d514116247e81b241251 takes 33 minutes to finish at 62f6870e4e0b384c4bd2d514116247e81b241251:
  9457. ....
  9458. cmd ./run --arch arm --eval 'm5 exit' --emulator gem5 -- --caches --cpu-type=HPI
  9459. ....
  9460. while aarch64 only 7 minutes.
  9461. 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?
  9462. Logs of the runs can be found at: https://github.com/cirosantilli-work/gem5-issues/tree/0df13e862b50ae20fcd10bae1a9a53e55d01caac/arm-hpi-slow
  9463. The cycle count is higher for `arm`, 350M vs 250M for `aarch64`, not nowhere near the 5x runtime time increase.
  9464. 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.
  9465. ===== gem5 x86_64 DerivO3CPU boot panics
  9466. https://github.com/cirosantilli-work/gem5-issues/issues/2
  9467. ....
  9468. Kernel panic - not syncing: Attempted to kill the idle task!
  9469. ....
  9470. ==== Benchmark builds
  9471. The build times are calculated after doing `./configure` and link:https://buildroot.org/downloads/manual/manual.html#_offline_builds[`make source`], which downloads the sources, and basically benchmarks the <<benchmark-internets,Internet>>.
  9472. 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
  9473. Buildroot automatically stores build timestamps as milliseconds since Epoch. Convert to minutes:
  9474. ....
  9475. awk -F: 'NR==1{start=$1}; END{print ($1 - start)/(60000.0)}' "$(./getvar buildroot_build_build_dir)/build-time.log"
  9476. ....
  9477. Or to conveniently do a clean build without affecting your current one:
  9478. ....
  9479. ./bench-all -b
  9480. cat ../linux-kernel-module-cheat-regression/*/build-time.log
  9481. ....
  9482. ===== Find which packages are making the build slow and big
  9483. ....
  9484. ./build-buildroot -- graph-build graph-size graph-depends
  9485. cd "$(./getvar buildroot_build_dir)/graphs"
  9486. xdg-open build.pie-packages.pdf
  9487. xdg-open graph-depends.pdf
  9488. xdg-open graph-size.pdf
  9489. ....
  9490. [[prebuilt-toolchain]]
  9491. ====== Buildroot use prebuilt host toolchain
  9492. 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
  9493. ===== Benchmark Buildroot build baseline
  9494. This is the minimal build we could expect to get away with.
  9495. We will run this whenever the Buildroot submodule is updated.
  9496. On the upstream Buildroot repo at :
  9497. ....
  9498. ./bench-all -B
  9499. ....
  9500. Sample time on 2017.08: 11 minutes, 7 with full ccache hits. Breakdown: 47% GCC, 15% Linux kernel, 9% uclibc, 5% host-binutils. Conclusions:
  9501. * we have bloated our kernel build 3x with all those delicious features :-)
  9502. * GCC time increased 1.5x by our bloat, but its percentage of the total was greatly reduced, due to new packages being introduced.
  9503. +
  9504. `make graph-depends` shows that most new dependencies come from QEMU and GDB, which we can't get rid of anyways.
  9505. A quick look at the system monitor reveals that the build switches between times when:
  9506. * CPUs are at a max, memory is fine. So we must be CPU / memory speed bound. I bet that this happens during heavy compilation.
  9507. * CPUs are not at a max, and memory is fine. So we are likely disk bound. I bet that this happens during configuration steps.
  9508. 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.
  9509. The instructions counts varied very little between the baseline and LKMC, so runtime overhead is not a big deal apparently.
  9510. Size:
  9511. * `bzImage`: 4.4M
  9512. * `rootfs.cpio`: 1.6M
  9513. Zipped: 4.9M, `rootfs.cpio` deflates 50%, `bzImage` almost nothing.
  9514. ===== Benchmark gem5 build
  9515. How long it takes to build gem5 itself.
  9516. We will update this whenever the gem5 submoule is updated.
  9517. Sample results at gem5 2a9573f5942b5416fb0570cf5cb6cdecba733392: 10 to 12 minutes.
  9518. Get results with:
  9519. ....
  9520. ./bench-all --emulator gem5
  9521. tail -n+1 ../linux-kernel-module-cheat-regression/*/gem5-bench-build-*.txt
  9522. ....
  9523. ====== Benchmark gem5 single file change rebuild time
  9524. This is the critical development parameter, and is dominated by the link time of huge binaries.
  9525. In order to benchmark it better, make a comment only change to:
  9526. ....
  9527. vim submodules/gem5/src/sim/main.cc
  9528. ....
  9529. then rebuild with:
  9530. ....
  9531. ./build-gem5 --arch aarch64 --verbose
  9532. ....
  9533. and then copy the link command to a separate Bash file. Then you can time and modify it easily.
  9534. Some approximate reference values on <<p51>>:
  9535. * `opt`
  9536. ** unmodified: 10 seconds
  9537. ** hack with `-fuse-ld=gold`: 6 seconds. Huge improvement!
  9538. * `debug`
  9539. ** unmodified: 14 seconds. Why two times slower than unmodified?
  9540. ** hack with `-fuse-ld=gold`: `internal error in read_cie, at ../../gold/ehframe.cc:919` on Ubuntu 18.04 all GCC. TODO report.
  9541. * `fast`
  9542. ** `--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.
  9543. ramfs made no difference, the kernel must be caching files in memory very efficiently already.
  9544. Tested at: d4b3e064adeeace3c3e7d106801f95c14637c12f + 1.
  9545. === Benchmark machines
  9546. ==== P51
  9547. Lenovo ThinkPad link:https://www3.lenovo.com/gb/en/laptops/thinkpad/p-series/P51/p/22TP2WPWP51[P51 laptop]:
  9548. * 2500 USD in 2018 (high end)
  9549. * Intel Core i7-7820HQ Processor (8MB Cache, up to 3.90GHz) (4 cores 8 threads)
  9550. * 32GB(16+16) DDR4 2400MHz SODIMM
  9551. * 512GB SSD PCIe TLC OPAL2
  9552. * NVIDIA Quadro M1200 Mobile, latest Ubuntu supported proprietary driver
  9553. * Latest Ubuntu
  9554. === Benchmark Internets
  9555. ==== 38Mbps internet
  9556. 2c12b21b304178a81c9912817b782ead0286d282:
  9557. * shallow clone of all submodules: 4 minutes.
  9558. * `make source`: 2 minutes
  9559. Google M-lab speed test: 36.4Mbps
  9560. === Benchmark this repo bibliography
  9561. gem5:
  9562. * link:https://www.mail-archive.com/gem5-users@gem5.org/msg15262.html[] which parts of the gem5 code make it slow
  9563. * what are the minimum system requirements:
  9564. ** https://stackoverflow.com/questions/47997565/gem5-system-requirements-for-decent-performance/48941793#48941793
  9565. ** https://github.com/gem5/gem5/issues/25
  9566. == About this repo
  9567. === Supported hosts
  9568. We tend to test this repo the most on the latest Ubuntu and on the latest link:https://askubuntu.com/questions/16366/whats-the-difference-between-a-long-term-support-release-and-a-normal-release[Ubuntu LTS].
  9569. For other Linux distros, everything will likely also just work if you install the analogous required packages for your distro.
  9570. Find out the packages that we install with:
  9571. ....
  9572. ./build --download-dependencies --dry-run <some-target> | less
  9573. ....
  9574. and then just look for the `apt-get` commands shown on the log.
  9575. After installing the missing packages for your distro, do the build with:
  9576. ....
  9577. ./build --download-dependencies --no-apt <some-target>
  9578. ....
  9579. which does everything as normal, except that it skips any `apt` commands.
  9580. Ports to new host systems are welcome and will be merged.
  9581. If something does not work however, <<docker>> should just work on any Linux distro.
  9582. Native Windows is unlikely feasible for Buildroot setups becuase Buildroot is a huge set of GNU Make scripts + host tools, just do everything from inside an Ubuntu in VirtualBox instance in that case.
  9583. Some setups of this repository are however very portable, notably setups under <<userland-setup>>, e.g. <<c>>.
  9584. === Common build issues
  9585. [[put-source-uris-in-sources]]
  9586. ==== You must put some 'source' URIs in your sources.list
  9587. If `./build --download-dependencies` fails with:
  9588. ....
  9589. E: You must put some 'source' URIs in your sources.list
  9590. ....
  9591. 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.
  9592. ==== Build from downloaded source zip files
  9593. 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.
  9594. `./build --download-dependencies` then fetches only the required submodules for you.
  9595. === Run command after boot
  9596. If you just want to run a command after boot ends without thinking much about it, just use the `--eval-after` option, e.g.:
  9597. ....
  9598. ./run --eval-after 'echo hello'
  9599. ....
  9600. 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.
  9601. See <<init>> for the gory details.
  9602. === Default command line arguments
  9603. It gets annoying to retype `--arch aarch64` for every single command, or to remember `--config` setups.
  9604. So simplify that, do:
  9605. ....
  9606. cp config.py data/
  9607. ....
  9608. and then edit the `data/config` file to your needs.
  9609. Source: link:config.py[]
  9610. You can also choose a different configuration file explicitly with:
  9611. ....
  9612. ./run --config data/config2.py
  9613. ....
  9614. Almost all options names are automatically deduced from their command line `--help` name: just replace `-` with `_`.
  9615. More precisely, we use the `dest=` value of Python's link:https://docs.python.org/3/library/argparse.html[argparse module].
  9616. To get a list of all global options that you can use, try:
  9617. ....
  9618. ./getvar --type input
  9619. ....
  9620. but note that this does not include script specific options.
  9621. === Build the documentation
  9622. You don't need to depend on GitHub:
  9623. ....
  9624. sudo apt install asciidoctor
  9625. ./build-doc
  9626. xdg-open out/README.html
  9627. ....
  9628. Source: link:build-doc[]
  9629. === Clean the build
  9630. You did something crazy, and nothing seems to work anymore?
  9631. All our build outputs are stored under `out/`, so the coarsest and most effective thing you can do is:
  9632. ....
  9633. rm -rf out
  9634. ....
  9635. This implies a full rebuild for all archs however, so you might first want to explore finer grained cleans first.
  9636. All our individual `build-*` scripts have a `--clean` option to completely nuke their builds:
  9637. ....
  9638. ./build-gem5 --clean
  9639. ./build-qemu --clean
  9640. ./build-buildroot --clean
  9641. ....
  9642. Verify with:
  9643. ....
  9644. ls "$(./getvar qemu_build_dir)"
  9645. ls "$(./getvar gem5_build_dir)"
  9646. ls "$(./getvar buildroot_build_dir)"
  9647. ....
  9648. 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.
  9649. To only nuke only one Buildroot package, we can use the link:https://buildroot.org/downloads/manual/manual.html#pkg-build-steps[]`-dirclean`] Buildroot target:
  9650. ....
  9651. ./build-buildroot --no-all -- <package-name>-dirclean
  9652. ....
  9653. e.g.:
  9654. ....
  9655. ./build-buildroot --no-all -- sample_package-dirclean
  9656. ....
  9657. Verify with:
  9658. ....
  9659. ls "$(./getvar buildroot_build_build_dir)"
  9660. ....
  9661. === ccache
  9662. link: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>>.
  9663. We have ccache enabled for everything we build by default.
  9664. However, you likely want to add the following to your `.bashrc` to take better advantage of `ccache`:
  9665. ....
  9666. export CCACHE_DIR=~/.ccache
  9667. export CCACHE_MAXSIZE="20G"
  9668. ....
  9669. We cannot automate this because you have to decide:
  9670. * should I store my cache on my HD or SSD?
  9671. * how big is my build, and how many build configurations do I need to keep around at a time?
  9672. If you don't those variables it, the default is to use `~/.buildroot-ccache` with `5G`, which is a bit small for us.
  9673. To check if `ccache` is working, run this command while a build is running on another shell:
  9674. ....
  9675. watch -n1 'make -C "$(./getvar buildroot_build_dir)" ccache-stats'
  9676. ....
  9677. or if you have it installed on host and the environment variables exported simply with:
  9678. ....
  9679. watch -n1 'ccache -s'
  9680. ....
  9681. and then watch the miss or hit counts go up.
  9682. We have link:https://buildroot.org/downloads/manual/manual.html#ccache[enabled ccached] builds by default.
  9683. `BR2_CCACHE_USE_BASEDIR=n` is used for Buildroot, which means that:
  9684. * absolute paths are used and GDB can find source files
  9685. * but builds are not reused across separated LKMC directories
  9686. === Rebuild Buildroot while running
  9687. It is not possible to rebuild the root filesystem while running QEMU because QEMU holds the file qcow2 file:
  9688. ....
  9689. error while converting qcow2: Failed to get "write" lock
  9690. ....
  9691. === Simultaneous runs
  9692. When doing long simulations sweeping across multiple system parameters, it becomes fundamental to do multiple simulations in parallel.
  9693. This is specially true for gem5, which runs much slower than QEMU, and cannot use multiple host cores to speed up the simulation: link:https://github.com/cirosantilli-work/gem5-issues/issues/15[], so the only way to parallelize is to run multiple instances in parallel.
  9694. This also has a good synergy with <<build-variants>>.
  9695. First shell:
  9696. ....
  9697. ./run
  9698. ....
  9699. Another shell:
  9700. ....
  9701. ./run --run-id 1
  9702. ....
  9703. and now you have two QEMU instances running in parallel.
  9704. The default run id is `0`.
  9705. Our scripts solve two difficulties with simultaneous runs:
  9706. * port conflicts, e.g. GDB and link:gem5-shell[]
  9707. * output directory conflicts, e.g. traces and gem5 stats overwriting one another
  9708. Each run gets a separate output directory. For example:
  9709. ....
  9710. ./run --arch aarch64 --emulator gem5 --run-id 0 &>/dev/null &
  9711. ./run --arch aarch64 --emulator gem5 --run-id 1 &>/dev/null &
  9712. ....
  9713. produces two separate <<m5out-directory,`m5out` directories>>:
  9714. ....
  9715. echo "$(./getvar --arch aarch64 --emulator gem5 --run-id 0 m5out_dir)"
  9716. echo "$(./getvar --arch aarch64 --emulator gem5 --run-id 1 m5out_dir)"
  9717. ....
  9718. and the gem5 host executable stdout and stderr can be found at:
  9719. ....
  9720. less "$(./getvar --arch aarch64 --emulator gem5 --run-id 0 termout_file)"
  9721. less "$(./getvar --arch aarch64 --emulator gem5 --run-id 1 termout_file)"
  9722. ....
  9723. Each line is prepended with the timestamp in seconds since the start of the program when it appeared.
  9724. 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:
  9725. ....
  9726. ./run --arch aarch64 --emulator gem5 --run-id some-experiment --port-offset 1
  9727. ....
  9728. `--port-offset` defaults to the run ID when that is a number.
  9729. Like <<cpu-architecture>>, you will need to pass the `-n` option to anything that needs to know runtime information, e.g. <<gdb>>:
  9730. ....
  9731. ./run --run-id 1
  9732. ./run-gdb --run-id 1
  9733. ....
  9734. To run multiple gem5 checkouts, see: <<gem5-worktree>>.
  9735. Implementation note: we create multiple namespaces for two things:
  9736. * run output directory
  9737. * ports
  9738. ** QEMU allows setting all ports explicitly.
  9739. +
  9740. If a port is not free, it just crashes.
  9741. +
  9742. We assign a contiguous port range for each run ID.
  9743. ** gem5 automatically increments ports until it finds a free one.
  9744. +
  9745. 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 <<config-ini>>.
  9746. +
  9747. The GDB port can be assigned on `gem5.opt --remote-gdb-port`, but it does not appear on `config.ini`.
  9748. === Build variants
  9749. 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.
  9750. 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.
  9751. ==== Linux kernel build variants
  9752. If you want to keep two builds around, one for the latest Linux version, and the other for Linux `v4.16`:
  9753. ....
  9754. # Build master.
  9755. ./build-linux
  9756. # Build another branch.
  9757. git -C "$(./getvar linux_source_dir)" fetch --tags --unshallow
  9758. git -C "$(./getvar linux_source_dir)" checkout v4.16
  9759. ./build-linux --linux-build-id v4.16
  9760. # Restore master.
  9761. git -C "$(./getvar linux_source_dir)" checkout -
  9762. # Run master.
  9763. ./run
  9764. # Run another branch.
  9765. ./run --linux-build-id v4.16
  9766. ....
  9767. 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
  9768. 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:
  9769. .....
  9770. ./run-gdb --linux-build-id v4.16
  9771. .....
  9772. To run both kernels simultaneously, one on each QEMU instance, see: <<simultaneous-runs>>.
  9773. ==== QEMU build variants
  9774. Analogous to the <<linux-kernel-build-variants>> but with the `--qemu-build-id` option instead:
  9775. ....
  9776. ./build-qemu
  9777. git -C "$(./getvar qemu_source_dir)" checkout v2.12.0
  9778. ./build-qemu --qemu-build-id v2.12.0
  9779. git -C "$(./getvar qemu_source_dir)" checkout -
  9780. ./run
  9781. ./run --qemu-build-id v2.12.0
  9782. ....
  9783. ==== gem5 build variants
  9784. Analogous to the <<linux-kernel-build-variants>> but with the `--gem5-build-id` option instead:
  9785. ....
  9786. # Build master.
  9787. ./build-gem5
  9788. # Build another branch.
  9789. git -C "$(./getvar gem5_source_dir)" checkout some-branch
  9790. ./build-gem5 --gem5-build-id some-branch
  9791. # Restore master.
  9792. git -C "$(./getvar gem5_source_dir)" checkout -
  9793. # Run master.
  9794. ./run --emulator gem5
  9795. # Run another branch.
  9796. git -C "$(./getvar gem5_source_dir)" checkout some-branch
  9797. ./run --gem5-build-id some-branch --emulator gem5
  9798. ....
  9799. 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.
  9800. 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.
  9801. ===== gem5 worktree
  9802. <<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.
  9803. ....
  9804. # Build gem5 at the revision in the gem5 submodule.
  9805. ./build-gem5
  9806. # Create a branch at the same revision as the gem5 submodule.
  9807. ./build-gem5 --gem5-worktree my-new-feature
  9808. cd "$(./getvar --gem5-worktree my-new-feature)"
  9809. vim create-bugs
  9810. git add .
  9811. git commit -m 'Created a bug'
  9812. cd -
  9813. ./build-gem5 --gem5-worktree my-new-feature
  9814. # Run the submodule.
  9815. ./run --emulator gem5 --run-id 0 &>/dev/null &
  9816. # Run the branch the need to check out anything.
  9817. # With --gem5-worktree, we can do both runs at the same time!
  9818. ./run --emulator gem5 --gem5-worktree my-new-feature --run-id 1 &>/dev/null &
  9819. ....
  9820. `--gem5-worktree <worktree-id>` automatically creates:
  9821. * a link:https://git-scm.com/docs/git-worktree[Git worktree] of gem5 if one didn't exit yet for `<worktree-id>`
  9822. * a separate build directory, exactly like `--gem5-build-id my-new-feature` would
  9823. 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.
  9824. `--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.
  9825. 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.
  9826. 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.
  9827. ===== gem5 private source trees
  9828. Suppose that you are working on a private fork of gem5, but you want to use this repository to develop it as well.
  9829. 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.
  9830. Even removing remotes is not safe enough, since `git submodule update` and other submodule commands can restore the old public remote.
  9831. Instead, we provide the following safer process.
  9832. First do a separate private clone of you private repository outside of this repository:
  9833. ....
  9834. git clone https://my.private.repo.com/my-fork/gem5.git gem5-internal
  9835. gem5_internal="$(pwd)/gem5-internal"
  9836. ....
  9837. 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:
  9838. ....
  9839. cd linux-kernel-module-cheat
  9840. ./build-gem5 \
  9841. --gem5-build-dir "${gem5_internal}/build" \
  9842. --gem5-source-dir "$gem5_internal" \
  9843. ;
  9844. ./run-gem5 \
  9845. --gem5-build-dir "${gem5_internal}/build" \
  9846. --gem5-source-dir "$gem5_internal" \
  9847. ;
  9848. ....
  9849. With this setup, both your private gem5 source and build are safely kept outside of this public repository.
  9850. ===== gem5 debug build
  9851. The `gem5.debug` executable has optimizations turned off unlike the default `gem5.opt`, and provides a much better <<debug-the-emulator,debug experience>>:
  9852. ....
  9853. ./build-gem5 --arch aarch64 --gem5-build-type debug
  9854. ./run --arch aarch64 --debug-vm --emulator gem5 --gem5-build-type debug
  9855. ....
  9856. The build outputs are automatically stored in a different directory from other build types such as `.opt` build, which prevents `.debug` files from overwriting `.opt` ones.
  9857. Therefore, `--gem5-build-id` is not required.
  9858. The price to pay for debuggability is high however: a Linux kernel boot was about 14 times slower than opt at 71e927e63bda6507d5a528f22c78d65099bdf36f between the commands:
  9859. ....
  9860. ./run --arch aarch64 --eval 'm5 exit' --emulator gem5 --linux-build-id v4.16
  9861. ./run --arch aarch64 --eval 'm5 exit' --emulator gem5 --linux-build-id v4.16 --gem5-build-type debug
  9862. ....
  9863. so you will likely only use this when it is unavoidable.
  9864. ==== Buildroot build variants
  9865. Allows you to have multiple versions of the GCC toolchain or root filesystem.
  9866. Analogous to the <<linux-kernel-build-variants>> but with the `--build-id` option instead:
  9867. ....
  9868. ./build-buildroot
  9869. git -C "$(./getvar buildroot_source_dir)" checkout 2018.05
  9870. ./build-buildroot --buildroot-build-id 2018.05
  9871. git -C "$(./getvar buildroot_source_dir)" checkout -
  9872. ./run
  9873. ./run --buildroot-build-id 2018.05
  9874. ....
  9875. === Directory structure
  9876. ==== lkmc directory
  9877. link:lkmc/[] contains sources and headers that are shared across kernel modules, userland and baremetal examples.
  9878. We chose this awkward name so that our includes will have an `lkmc/` prefix.
  9879. 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.
  9880. ===== Userland objects vs header-only
  9881. When factoring out functionality across userland examples, there are two main options:
  9882. * use header-only implementations
  9883. * use separate C files and link to separate objects.
  9884. The downsides of the header-only implementation are:
  9885. * slower compilation time, especially for C++
  9886. * cannot call C implementations from assembly files
  9887. The advantages of header-only implementations are:
  9888. * easier to use, just `#include` and you are done, no need to modify build metadata.
  9889. As a result, we are currently using the following rule:
  9890. * if something is only going to be used from C and not assembly, define it in a header which is easier to use
  9891. +
  9892. The slower compilation should be OK as long as split functionality amongst different headers and only include the required ones.
  9893. +
  9894. Also we don't have a choice in the case of C++ template, which must stay in headers.
  9895. * 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.
  9896. ==== buildroot_packages directory
  9897. Source: link:buildroot_packages/[]
  9898. Every directory inside it is a Buildroot package.
  9899. 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.:
  9900. ....
  9901. ./build-buildroot --config 'BR2_PACKAGE_SAMPLE_PACKAGE=y'
  9902. ....
  9903. then test it out with:
  9904. ....
  9905. ./run --eval-after './sample_package.out'
  9906. ....
  9907. and you should see:
  9908. ....
  9909. hello sample_package
  9910. ....
  9911. Source: link:buildroot_packages/sample_package/sample_package.c[]
  9912. You can force a rebuild with:
  9913. ....
  9914. ./build-buildroot --config 'BR2_PACKAGE_SAMPLE_PACKAGE=y' -- sample_package-reconfigure
  9915. ....
  9916. 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>>.
  9917. 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.
  9918. ===== kernel_modules package
  9919. Source: link:buildroot_packages/kernel_modules/[]
  9920. An example of how to use kernel modules in Buildroot.
  9921. Usage:
  9922. ....
  9923. ./build-buildroot \
  9924. --build-linux \
  9925. --config 'BR2_PACKAGE_KERNEL_MODULES=y' \
  9926. --no-overlay \
  9927. -- \
  9928. kernel_modules-reconfigure \
  9929. ;
  9930. ....
  9931. Then test one of the modules with:
  9932. ....
  9933. ./run --buildroot-linux --eval-after 'modprobe buildroot_hello'
  9934. ....
  9935. Source: link:buildroot_packages/kernel_modules/buildroot_hello.c[]
  9936. As you have just seen, this sets up everything so that <<modprobe>> can conrrectly find the module.
  9937. `./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.
  9938. The `--no-overlay` is required otherwise our `modules.order` generated by `./build-linux` and installed with `BR2_ROOTFS_OVERLAY` overwrites the Buildroot generated one.
  9939. Implementattion described at: https://stackoverflow.com/questions/40307328/how-to-add-a-linux-kernel-driver-module-as-a-buildroot-package/43874273#43874273
  9940. ==== patches directory
  9941. ===== patches/global
  9942. Has the following structure:
  9943. ....
  9944. package-name/00001-do-something.patch
  9945. ....
  9946. The patches are then applied to the corresponding packages before build.
  9947. Uses `BR2_GLOBAL_PATCH_DIR`.
  9948. ===== patches/manual
  9949. 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.
  9950. These are typically patches that don't contain fundamental functionality, so we don't feel like forking the target repos.
  9951. ==== rootfs_overlay
  9952. We use this directory for:
  9953. * customized configuration files
  9954. * userland module test scripts that don't need to be compiled.
  9955. +
  9956. C files for example need compilation, and must go through the regular package system, e.g. through link:kernel_modules/user[].
  9957. This directory is copied into the target filesystem by:
  9958. ....
  9959. ./copy-overlay
  9960. ./build-buildroot
  9961. ....
  9962. Source: link:copy-overlay[]
  9963. Build Buildroot is required for the same reason as described at: <<your-first-kernel-module-hack>>.
  9964. 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:
  9965. ....
  9966. ls /mnt/9p/rootfs_overlay
  9967. ....
  9968. This way you can just hack away the scripts and try them out immediately without any further operations.
  9969. ==== lkmc.c
  9970. The files:
  9971. * link:lkmc.c[]
  9972. * link:lkmc.h[]
  9973. contain common C function helpers that can be used both in userland and baremetal. Oh, the infinite <<about-the-baremetal-setup,joys of Newlib>>.
  9974. Those files also contain arch specific helpers under ifdefs like:
  9975. ....
  9976. #if defined(__aarch64__)
  9977. ....
  9978. We try to keep as much as possible in those files. It bloats builds a little, but just makes everything simpler to understand.
  9979. ==== rand_check.out
  9980. Print out several parameters that normally change randomly from boot to boot:
  9981. ....
  9982. ./run --eval-after './linux/rand_check.out;./linux/poweroff.out'
  9983. ....
  9984. Source: link:userland/linux/rand_check.c[]
  9985. This can be used to check the determinism of:
  9986. * <<norandmaps>>
  9987. * <<qemu-record-and-replay>>
  9988. ==== lkmc_home
  9989. `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>>.
  9990. The current value can be found with:
  9991. ....
  9992. ./getvar guest_lkmc_home
  9993. ....
  9994. 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.
  9995. 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.:
  9996. * interactive shells `cd` there through <<busybox-shell-initrc-files>>
  9997. * `--eval` and `--eval-after` through <<replace-init>> and <<init-busybox>>
  9998. 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.
  9999. === Test this repo
  10000. ==== Automated tests
  10001. Run almost all tests:
  10002. ....
  10003. ./build-test --size 3 && \
  10004. ./test --size 3
  10005. echo $?
  10006. ....
  10007. should output 0.
  10008. Sources:
  10009. * link:build-test[]
  10010. * link:test[]
  10011. The link:test[] script runs several different types of tests, which can also be run separately as explained at:
  10012. * link:test-boot[]
  10013. * <<test-userland-in-full-system>>
  10014. * <<user-mode-tests>>
  10015. * <<baremetal-tests>>
  10016. * <<test-gdb>>
  10017. * <<gem5-unit-tests>>
  10018. 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`.
  10019. ===== Test arch and emulator selection
  10020. You can select multiple archs and emulators of interest, as for an other command, with:
  10021. ....
  10022. ./test-user-mode \
  10023. --arch x86_64 \
  10024. --arch aarch64 \
  10025. --emulator gem5 \
  10026. --emulator qemu \
  10027. ;
  10028. ....
  10029. You can also test all supported archs and emulators with:
  10030. ....
  10031. ./test-user-mode \
  10032. --all-archs \
  10033. --all-emulators \
  10034. ;
  10035. ....
  10036. This command would run the test four times, using `x86_64` and `aarch64` with both gem5 and QEMU.
  10037. Without those flags, it defaults to just running the default arch and emulator once: `x86_64` and `qemu`.
  10038. ===== Quit on fail
  10039. By default, tests stop running as soon as the first failure happens.
  10040. You can prevent this with the `--no-quit-on-fail option, e.g.:
  10041. ....
  10042. ./test-user-mode --no-quit-on-fail
  10043. ....
  10044. You can then see which tests failed on the test summary report at the end.
  10045. ===== Test userland in full system
  10046. 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.
  10047. We could just generate it on the fly on the host, and forward it to guest through CLI arguments.
  10048. Run all userland tests from inside full system simulation (i.e. not <<user-mode-simulation>>):
  10049. ....
  10050. ./test-userland-full-system
  10051. ....
  10052. This includes, in particular, userland programs that test the kernel modules, which cannot be tested in user mode simulation.
  10053. Basically just boots and runs: link:rootfs_overlay/lkmc/test_all.sh[]
  10054. Failure is detected by looking for the <<magic-failure-string>>
  10055. Most userland programs that don't rely on kernel modules can also be tested in user mode simulation as explained at: <<user-mode-tests>>.
  10056. ===== Test GDB
  10057. We have some link:https://github.com/pexpect/pexpect[pexpect] automated tests for the baremetal programs!
  10058. ....
  10059. ./build --all-archs test-gdb && \
  10060. ./test-gdb --all-archs --all-emulators
  10061. ....
  10062. Sources:
  10063. * link:build-test-gdb[]
  10064. * link:test-gdb[]
  10065. If a test fails, re-run the test commands manually and use `--verbose` to understand what happened:
  10066. ....
  10067. ./run --arch arm --background --baremetal baremetal/add.c --gdb-wait &
  10068. ./run-gdb --arch arm --baremetal baremetal/add.c --verbose -- main
  10069. ....
  10070. and possibly repeat the GDB steps manually with the usual:
  10071. ....
  10072. ./run-gdb --arch arm --baremetal baremetal/add.c --no-continue --verbose
  10073. ....
  10074. To debug GDB problems on gem5, you might want to enable the following <<gem5-tracing,tracing>> options:
  10075. ....
  10076. ./run \
  10077. --arch arm \
  10078. --baremetal baremetal/add.c \
  10079. --gdb-wait \
  10080. --trace GDBRecv,GDBSend \
  10081. --trace-stdout \
  10082. ;
  10083. ....
  10084. ===== Magic failure string
  10085. We do not know of any way to set the emulator exit status in QEMU arm full system.
  10086. For other arch / emulator combinations, we know how to do it:
  10087. * aarch64: aarch64 semihosting supports exit status
  10088. * gem5: <<m5-fail>> works on all archs
  10089. * user mode: QEMU forwards exit status, gem5 we do some log parsing: <<gem5-syscall-emulation-exit-status>>
  10090. 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.
  10091. Our run scripts parse the serial output looking for a line line containing only exactly the magic regular expression:
  10092. ....
  10093. lkmc_exit_status_(\d+)
  10094. ....
  10095. and then exit with the given regular expression, e.g.:
  10096. ....
  10097. ./run --arch aarch64 baremetal/return2.c
  10098. echo $?
  10099. ....
  10100. should output:
  10101. ....
  10102. 2
  10103. ....
  10104. This magic output string is notably generated by:
  10105. * link:rootfs_overlay/lkmc/test_fail.sh[], which is used by <<test-userland-in-full-system>>
  10106. * the `exit()` baremetal function when `status != 1`.
  10107. +
  10108. Unfortunately the only way we found to set this up was with `on_exit`: link:https://github.com/cirosantilli/linux-kernel-module-cheat/issues/59[].
  10109. +
  10110. Trying to patch `_exit` directly fails since at that point some de-initialization has already happened which prevents the print.
  10111. +
  10112. 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
  10113. +
  10114. The following examples end up testing that our setup is working:
  10115. +
  10116. * link:baremetal/assert_fail.c[]
  10117. * link:baremetal/lkmc_assert_fail.c[]
  10118. * link:baremetal/return1.c[]
  10119. * link:baremetal/return2.c[]
  10120. * link:baremetal/exit0.c[]
  10121. * link:baremetal/exit1.c[]
  10122. * link:baremetal/arch/arm/return1.S[]
  10123. * link:baremetal/arch/aarch64/return1.S[]
  10124. Beware that on Linux kernel simulations, you cannot even echo that string from userland, since userland stdout shows up on the serial.
  10125. ====== baremetal assert
  10126. TODO: implement enough syscalls for it, so we can get the error line:
  10127. ....
  10128. cd baremetal
  10129. ln -s ../lkmc/assert_fail.c
  10130. cd ..
  10131. ./build --arch aarch64
  10132. ....
  10133. fails with:
  10134. ....
  10135. /path/to/linux-kernel-module-cheat/out/crosstool-ng/build/default/install/aarch64/lib/gcc/aarch64-unknown-elf/8.1.0/../../../../aarch64-unknown-elf/lib/libg.a(lib_a-signalr.o): In function `_kill_r':
  10136. /path/to/linux-kernel-module-cheat/out/crosstool-ng/build/default/build/aarch64-unknown-elf/src/newlib/newlib/libc/reent/signalr.c:53: undefined reference to `_kill'
  10137. /path/to/linux-kernel-module-cheat/out/crosstool-ng/build/default/build/aarch64-unknown-elf/src/newlib/newlib/libc/reent/signalr.c:53:(.text+0x20): relocation truncated to fit: R_AARCH64_CALL26 against undefined symbol `_kill'
  10138. /path/to/linux-kernel-module-cheat/out/crosstool-ng/build/default/install/aarch64/lib/gcc/aarch64-unknown-elf/8.1.0/../../../../aarch64-unknown-elf/lib/libg.a(lib_a-signalr.o): In function `_getpid_r':
  10139. /path/to/linux-kernel-module-cheat/out/crosstool-ng/build/default/build/aarch64-unknown-elf/src/newlib/newlib/libc/reent/signalr.c:83: undefined reference to `_getpid'
  10140. /path/to/linux-kernel-module-cheat/out/crosstool-ng/build/default/build/aarch64-unknown-elf/src/newlib/newlib/libc/reent/signalr.c:83:(.text+0x44): relocation truncated to fit: R_AARCH64_JUMP26 against undefined symbol `_getpid'
  10141. ....
  10142. at 406ee82cf33a6e3df0067b219b0414c59d7018b3 + 1.
  10143. ==== Non-automated tests
  10144. ===== Test GDB Linux kernel
  10145. For the Linux kernel, do the following manual tests for now.
  10146. Shell 1:
  10147. ....
  10148. ./run --gdb-wait
  10149. ....
  10150. Shell 2:
  10151. ....
  10152. ./run-gdb start_kernel
  10153. ....
  10154. Should break GDB at `start_kernel`.
  10155. Then proceed to do the following tests:
  10156. * `./count.sh` and `break __x64_sys_write`
  10157. * `insmod timer.ko` and `break lkmc_timer_callback`
  10158. ===== Test the Internet
  10159. You should also test that the Internet works:
  10160. ....
  10161. ./run --arch x86_64 --kernel-cli '- lkmc_eval="ifup -a;wget -S google.com;poweroff;"'
  10162. ....
  10163. ===== CLI script tests
  10164. `build-userland` and `test-user-mode` have a wide variety of target selection modes, and it was hard to keep them all working without some tests:
  10165. * link:test-build-userland[]
  10166. * link:test-test-user-mode[]
  10167. === Bisection
  10168. When updating the Linux kernel, QEMU and gem5, things sometimes break.
  10169. 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: <<exit-emulator-on-panic>>.
  10170. For example, when updating from QEMU `v2.12.0` to `v3.0.0-rc3`, the Linux kernel boot started to panic for `arm`.
  10171. We then bisected it as explained at: https://stackoverflow.com/questions/4713088/how-to-use-git-bisect/22592593#22592593 with the link:qemu-bisect-boot[] script:
  10172. ....
  10173. root_dir="$(pwd)"
  10174. cd "$(./getvar qemu_source_dir)"
  10175. git bisect start
  10176. # Check that our test script fails on v3.0.0-rc3 as expected, and mark it as bad.
  10177. "${root_dir}/qemu-bisect-boot"
  10178. # Should output 1.
  10179. echo #?
  10180. git bisect bad
  10181. # Same for the good end.
  10182. git checkout v2.12.0
  10183. "${root_dir}/qemu-bisect-boot"
  10184. # Should output 0.
  10185. echo #?
  10186. git bisect good
  10187. # This leaves us at the offending commit.
  10188. git bisect run ../bisect-qemu-linux-boot
  10189. # Clean up after the bisection.
  10190. git bisect reset
  10191. git submodule update
  10192. "${root_dir}/build-qemu" --clean --qemu-build-id bisect
  10193. ....
  10194. TODO broken, fix: An example of Linux kernel commit bisection on gem5 boots can be found at: link:bisect-linux-boot-gem5[].
  10195. [[path-properties]]
  10196. === path_properties
  10197. 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.
  10198. This data is stored is stored in link:path_properties.py[] at `path_properties_tuples`.
  10199. 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.
  10200. The format is as follows:
  10201. ....
  10202. 'path_component': (
  10203. {'property': value},
  10204. {
  10205. 'child_path_component':
  10206. {
  10207. {'child_property': },
  10208. {}
  10209. }
  10210. }
  10211. )
  10212. ....
  10213. and as a shortcut, paths that don't have any children can be written directly as:
  10214. .....
  10215. 'path_component': {'property': value}
  10216. .....
  10217. Properties of parent directories apply to all children.
  10218. Lists coming from parent directories are extended instead of overwritten by children, this is especially useful for C compiler flags.
  10219. === Update a forked submodule
  10220. This is a template update procedure for submodules for which we have some patches on on top of mainline.
  10221. This example is based on the Linux kernel, for which we used to have patches, but have since moved to mainline:
  10222. ....
  10223. # Last point before out patches.
  10224. last_mainline_revision=v4.15
  10225. next_mainline_revision=v4.16
  10226. cd "$(./getvar linux_source_dir)"
  10227. # Create a branch before the rebase in case things go wrong.
  10228. git checkout -b "lkmc-${last_mainline_revision}"
  10229. git remote set-url origin git@github.com:cirosantilli/linux.git
  10230. git push
  10231. git checkout master
  10232. git remote add up git://git.kernel.org/pub/scm/linux/kernel/git/stable/linux-stable.git
  10233. git fetch up
  10234. git rebase --onto "$next_mainline_revision" "$last_mainline_revision"
  10235. # And update the README to show off.
  10236. git commit -m "linux: update to ${next_mainline_revision}"
  10237. ....
  10238. === Release
  10239. ==== Release procedure
  10240. Ensure that the <<automated-tests>> are passing on a clean build:
  10241. ....
  10242. mv out out.bak
  10243. ./build-test --size 3 && ./test --size 3
  10244. ....
  10245. The clean build is necessary as it generates clean images since <<remove-buildroot-packages,it is not possible to remove Buildroot packages>>
  10246. Run all tests in <<non-automated-tests>> just QEMU x86_64 and QEMU aarch64.
  10247. TODO: not working currently, so skipped: Ensure that the <<benchmark-this-repo,benchmarks>> look fine:
  10248. ....
  10249. ./bench-all -A
  10250. ....
  10251. Create a release candidate and upload it:
  10252. ....
  10253. git tag -a -m '' v3.0-rc1
  10254. git push --follow-tags
  10255. ./release-zip --all-archs
  10256. # export LKMC_GITHUB_TOKEN=<your-token>
  10257. ./release-upload
  10258. ....
  10259. Now let's do an out-of-box testing for the release candidate:
  10260. ....
  10261. cd ..
  10262. git clone https://github.com/cirosantilli/linux-kernel-module-cheat linux-kernel-module-cheat-release
  10263. cd linux-kernel-module-cheat-release
  10264. ....
  10265. Test <<prebuilt>>.
  10266. Clean up, and re-start from scratch:
  10267. ....
  10268. cd ..
  10269. rm -rf linux-kernel-module-cheat-release
  10270. git clone https://github.com/cirosantilli/linux-kernel-module-cheat linux-kernel-module-cheat-release
  10271. cd linux-kernel-module-cheat-release
  10272. ....
  10273. Go through all the other <<getting-started>> sections in order.
  10274. Once everything looks fine, publish the release with:
  10275. ....
  10276. git tag -a v3.0
  10277. # Describe the release int the tag message.
  10278. git push --follow-tags
  10279. ./release-zip --all-archs
  10280. # export LKMC_GITHUB_TOKEN=<your-token>
  10281. ./release-upload
  10282. ....
  10283. ==== release-zip
  10284. Create a zip containing all files required for <<prebuilt>>:
  10285. ....
  10286. ./build --all-archs release && ./release-zip --all-archs
  10287. ....
  10288. Source: link:release-zip[]
  10289. This generates a zip file:
  10290. ....
  10291. echo "$(./getvar release_zip_file)"
  10292. ....
  10293. which you can then upload somewhere.
  10294. ==== release-upload
  10295. After:
  10296. * running <<release-zip>>
  10297. * creating and pushing a tag to GitHub
  10298. you can upload the release to GitHub automatically with:
  10299. ....
  10300. # export LKMC_GITHUB_TOKEN=<your-token>
  10301. ./release-upload
  10302. ....
  10303. Source: link:release-upload[]
  10304. The HEAD of the local repository must be on top of a tag that has been pushed for this to work.
  10305. Create `LKMC_GITHUB_TOKEN` under: https://github.com/settings/tokens/new and save it to your `.bashrc`.
  10306. The implementation of this script is described at:
  10307. * https://stackoverflow.com/questions/5207269/how-to-release-a-build-artifact-asset-on-github-with-a-script/52354732#52354732
  10308. * https://stackoverflow.com/questions/38153418/can-someone-give-a-python-requests-example-of-uploading-a-release-asset-in-githu/52354681#52354681
  10309. === Design rationale
  10310. ==== Design goals
  10311. This project was created to help me understand, modify and test low level system components by using system simulators.
  10312. System simulators are cool compared to real hardware because they are:
  10313. * free
  10314. * make experiments highly reproducible
  10315. * 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.
  10316. The current components we focus the most on are:
  10317. * <<linux-kernel>> and Linux kernel modules
  10318. * full systems emulators, currently <<qemu-buildroot-setup,qemu>> and <<gem5-buildroot-setup,gem5>>
  10319. * <<buildroot>>. We use and therefore document, a large part of its feature set.
  10320. The following components are not covered, but they would also benefit from this setup, and it shouldn't be hard to add them:
  10321. * C standard libraries
  10322. * 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.
  10323. The design goals are to provide setups that are:
  10324. * highly automated: "just works"
  10325. * thoroughly documented: you know what "just works" means
  10326. * can be fully built from source: to give visibility and allow modifications
  10327. * can also use <<prebuilt, prebuilt binaries>> as much as possible: in case you are lazy or unable to build from source
  10328. We aim to make a documentation that contains a very high runnable example / theory bullshit ratio.
  10329. Having at least one example per section is ideal, and it should be the very first thing in the section if possible.
  10330. ==== Setup trade-offs
  10331. The trade-offs between the different <<getting-started,setups>> are basically a balance between:
  10332. * speed ans size: how long and how much disk space do the build and run take?
  10333. * visibility: can you GDB step debug everything and read source code?
  10334. * modifiability: can you modify the source code and rebuild a modified version?
  10335. * portability: does it work on a Windows host? Could it ever?
  10336. * accuracy: how accurate does the simulation represent real hardware?
  10337. * compatibility: how likely is is that all the components will work well together: emulator, compiler, kernel, standard library, ...
  10338. * guest software availability: how wide is your choice of easily installed guest software packages? See also: <<linux-distro-choice>>
  10339. ==== Resource tradeoff guidelines
  10340. Choosing which features go into our default builds means making tradeoffs, here are our guidelines:
  10341. * keep the root filesystem as tiny as possible to make <<prebuilt>> small: only add BusyBox to have a small interactive system.
  10342. +
  10343. 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.
  10344. * enable every feature possible on the toolchain (GCC, Binutils), because changes imply Buildroot rebuilds
  10345. * runtime is sacred. Faster systems are:
  10346. +
  10347. --
  10348. ** easier to understand
  10349. ** run faster, which is specially for <<gem5>> which is slow
  10350. --
  10351. +
  10352. 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.
  10353. +
  10354. 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.
  10355. In order to learn how to measure some of those aspects, see: <<benchmark-this-repo>>
  10356. ==== Linux distro choice
  10357. We haven't found the ultimate distro yet, here is a summary table of trade-offs that we care about:
  10358. [options="header"]
  10359. |===
  10360. |Distro |Packages in single Git tree |Git tracked docs |Cross build without QEMU |Prebuilt downloads |Number of packages
  10361. |Buildroot 2018.05
  10362. |y
  10363. |y
  10364. |y
  10365. |n
  10366. |2k (1)
  10367. |Ubuntu 18.04
  10368. |n
  10369. |n
  10370. |n
  10371. |y
  10372. |50k (3)
  10373. |Yocto 2.5 (8)
  10374. |?
  10375. |y (5)
  10376. |?
  10377. |y (6)
  10378. |400 (7)
  10379. |Alpine Linux 3.8.0
  10380. |y
  10381. |n (1)
  10382. |?
  10383. |y
  10384. |2000 (4)
  10385. |===
  10386. * (1): Wiki... https://wiki.alpinelinux.org/wiki/Main_Page
  10387. * (2): `ls packages | wc`
  10388. * (3): https://askubuntu.com/questions/120630/how-many-packages-are-in-the-main-repository
  10389. * (4): `ls main community non-free | wc`
  10390. * (5): yes, but on a separate Git tree... https://git.yoctoproject.org/cgit/cgit.cgi/yocto-docs/
  10391. * (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
  10392. * (7): `ls recipes-* | wc`
  10393. * (8): Poky reference system: http://git.yoctoproject.org/cgit/cgit.cgi/poky
  10394. Other interesting possibilities that I haven't evaluated well:
  10395. * NixOS https://nixos.org/ Seems to support full build from source well. Not much cross compilation information however.
  10396. * Gentoo https://en.wikipedia.org/wiki/Gentoo_Linux Seems to support full build from source well.
  10397. === Soft topics
  10398. ==== Fairy tale
  10399. ____
  10400. Once upon a time, there was a boy called Linus.
  10401. Linus made a super fun toy, and since he was not very humble, decided to call it Linux.
  10402. Linux was an awesome toy, but it had one big problem: it was very difficult to learn how to play with it!
  10403. 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.
  10404. One day, a mysterious new kid called Ciro tried to play with Linux, and like many before him, got very frustrated, and gave up.
  10405. 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.
  10406. Ciro noticed that if you used Buildroot together with Linux, and Linux suddenly became very fun to play with!
  10407. So Ciro decided to explain to as many kids as possible how to use Buildroot to play with Linux.
  10408. And so everyone was happy. Except some of the old weird kernel hackers who wanted to keep their mystique, but so be it.
  10409. THE END
  10410. ____
  10411. ==== Should you waste your life with systems programming?
  10412. 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?
  10413. But before you dedicate your life to this nonsense, do consider the following points:
  10414. * 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.
  10415. +
  10416. This can be inferred by the fact that the `devices/` directory is by far the largest in the kernel.
  10417. +
  10418. 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.
  10419. +
  10420. 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.
  10421. +
  10422. 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.
  10423. +
  10424. 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.
  10425. +
  10426. In that sense, therefore, the kernel is not as open as one might want to believe.
  10427. * it is impossible to become rich with this knowledge.
  10428. +
  10429. 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.
  10430. +
  10431. The key problem is that the entry cost of hardware design is just too insanely high for startups in general.
  10432. * Is learning this the most useful thing that you think can do for society?
  10433. +
  10434. Or are you just learning it for job security and having a nice sounding title?
  10435. +
  10436. I'm not a huge fan of the person, but I think Jobs said it right: https://www.youtube.com/watch?v=FF-tKLISfPE
  10437. +
  10438. First determine the useful goal, and then backtrack down to the most efficient thing you can do to reach it.
  10439. * there are two things that sadden me compared to physics-based engineering:
  10440. +
  10441. --
  10442. ** you will never become eternally famous. All tech disappears sooner or later, while laws of nature, at least as useful approximations, stay unchanged.
  10443. ** every problem that you face is caused by imperfections introduced by other humans.
  10444. +
  10445. It is much easier to accept limitations of physics, and even natural selection in biology, which is are produced by a sentient being (?).
  10446. --
  10447. +
  10448. 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.
  10449. Are you fine with those points, and ready to continue wasting your life?
  10450. Good. In that case, read on, and let's have some fun together ;-)
  10451. === Bibliography
  10452. Runnable stuff:
  10453. * 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.
  10454. * 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.
  10455. * https://github.com/tinyclub/linux-lab Buildroot based, no kernel modules?
  10456. * https://github.com/agelastic/eudyptula
  10457. * 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/
  10458. * 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
  10459. * 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
  10460. * https://github.com/pw4ever/linux-kernel-hacking-helper as of bd9952127e7eda643cbb6cb4c51ad7b5b224f438, Bash, Arch Linux rootfs
  10461. * 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.
  10462. Theory:
  10463. * 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.
  10464. +
  10465. 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...
  10466. * https://balau82.wordpress.com awesome low level resource
  10467. * https://rwmj.wordpress.com/ awesome red hatter
  10468. * https://lwn.net
  10469. * http://www.makelinux.net
  10470. * https://notes.shichao.io/lkd/
  10471. Awesome lists:
  10472. * https://github.com/gurugio/lowlevelprogramming-university
  10473. * https://github.com/uhub/awesome-c