README.adoc 352 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668
  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 modify the <<linux-kernel>>, kernel modules, <<qemu-buildroot-setup,QEMU>> and <<gem5-buildroot-setup,gem5>>. Highly automated. Thoroughly documented. <<gdb>> and <<kgdb>> just work. Powered by <<about-the-qemu-buildroot-setup,Buildroot>>. "Tested" in Ubuntu 18.04 host, x86 and ARM guests with kernel v4.19.
  12. TL;DR: <<qemu-buildroot-setup-getting-started>>
  13. toc::[]
  14. == Getting started
  15. Each child section describes a possible different setups for this repo.
  16. If you don't know which one to go for, start with <<qemu-buildroot-setup-getting-started>>.
  17. === QEMU Buildroot setup
  18. ==== QEMU Buildroot setup getting started
  19. This setup has been mostly tested on Ubuntu. For other host operating systems see: <<supported-hosts>>.
  20. Reserve 12Gb of disk and run:
  21. ....
  22. git clone https://github.com/cirosantilli/linux-kernel-module-cheat
  23. cd linux-kernel-module-cheat
  24. ./download-dependencies && ./build
  25. ./run
  26. ....
  27. 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.
  28. If something goes wrong, see: <<common-build-issues>> and use our issue tracker: https://github.com/cirosantilli/linux-kernel-module-cheat/issues
  29. The initial build will take a while (30 minutes to 2 hours) to clone and build, see <<benchmark-builds>> for more details.
  30. If you don't want to wait, you could also try the following faster but much more limited methods:
  31. * <<prebuilt>>
  32. * <<host>>
  33. but you will soon find that they are simply not enough if you anywhere near serious about systems programming.
  34. After `./run`, QEMU opens up and you can start playing with the kernel modules inside the simulated system:
  35. ....
  36. insmod /hello.ko
  37. insmod /hello2.ko
  38. rmmod hello
  39. rmmod hello2
  40. ....
  41. This should print to the screen:
  42. ....
  43. hello init
  44. hello2 init
  45. hello cleanup
  46. hello2 cleanup
  47. ....
  48. which are `printk` messages from `init` and `cleanup` methods of those modules.
  49. Sources:
  50. * link:kernel_modules/hello.c[]
  51. * link:kernel_modules/hello2.c[]
  52. Quit QEMU with:
  53. ....
  54. Ctrl-A X
  55. ....
  56. See also: <<quit-qemu-from-text-mode>>.
  57. All available modules can be found in the link:kernel_modules[] directory.
  58. It is super easy to build for different CPU architectures, just use the `--arch` option:
  59. ....
  60. ./build --arch aarch64
  61. ./run --arch aarch64
  62. ....
  63. To avoid typing `--arch aarch64` so many times, set the default arch as explained at: <<default-command-line-arguments>>
  64. See also: <<cpu-architecture,CPU architectures>>.
  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. While developing individual components, you will most often want to use specific build commands such as `./build-linux` instead of the more generic `./build` helper.
  117. You can see what `./build` does with:
  118. ....
  119. ./build --dry-run
  120. ....
  121. ===== Your first Linux kernel hack
  122. Let's hack up the <<linux-kernel-entry-point, Linux kernel entry point>>, which is an easy place to start.
  123. Open the file:
  124. ....
  125. vim submodules/linux/init/main.c
  126. ....
  127. and find the `start_kernel` function, then add there a:
  128. ....
  129. pr_info("I'VE HACKED THE LINUX KERNEL!!!");
  130. ....
  131. Then rebuild the Linux kernel, quit QEMU and reboot the modified kernel:
  132. ....
  133. ./build-linux
  134. ./run
  135. ....
  136. and, surely enough, your message has appeared at the beginning of the boot.
  137. We could have used just `./build` as in the initial build, but doing just `./build-linux` will save us a bit of time.
  138. The link:build[`./build`] script is just a lightweight wrapper, but when you start modifying components such as the Linux kernel, it is better to run individual steps directly.
  139. So you are now officially a Linux kernel hacker, way to go!
  140. ===== Your first kernel module hack
  141. Edit link:kernel_modules/hello.c[] to contain:
  142. ....
  143. pr_info("hello init hacked\n");
  144. ....
  145. and rebuild with:
  146. ....
  147. ./build-modules
  148. ....
  149. Now there are two way to test it out, the fast way, and the safe way.
  150. The fast way is, without quitting or rebooting QEMU, just directly re-insert the module with:
  151. ....
  152. insmod /mnt/9p/out_rootfs_overlay/hello.ko
  153. ....
  154. and the new `pr_info` message should now show on the terminal at the end of the boot.
  155. This works because we have a <<9p>> mount there setup by default, which makes a host directory available on the guest.
  156. The fast is slightly risky because your kernel module might have corrupted the kernel memory, which could affect future runs.
  157. Such failures are however unlikely, and you should be fine if you don't see anything weird happening.
  158. The safe way, is to fist quit QEMU, then rebuild the modules, root filesystem, and then reboot:
  159. ....
  160. ./build-modules
  161. ./build-buildroot
  162. ./run --eval-busybox 'insmod /hello.ko'
  163. ....
  164. `./build-buildroot` is required after `./build-modules` because it generates the root filesystem with the modules that we compiled at `./build-modules`.
  165. You can see that `./build` does that as well, by running:
  166. ....
  167. ./build --dry-run
  168. ....
  169. `--eval-busybox` 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.
  170. If the guest and host are the same arch, typically x86_64, you can speed up boot further with <<kvm>>:
  171. ....
  172. ./run --kvm
  173. ....
  174. All of this put together makes the safe procedure acceptably fast for regular development as well.
  175. ===== Your first QEMU hack
  176. Not satisfied with mere software? OK then, let's hack up the QEMU x86 CPU identification:
  177. ....
  178. vim submodules/qemu/target/i386/cpu.c
  179. ....
  180. and modify:
  181. ....
  182. .model_id = "QEMU Virtual CPU version " QEMU_HW_VERSION,
  183. ....
  184. to contain:
  185. ....
  186. .model_id = "QEMU Virtual CPU version HACKED " QEMU_HW_VERSION,
  187. ....
  188. then as usual rebuild and re-run:
  189. .....
  190. ./build-qemu
  191. ./run --eval-busybox 'grep "model name" /proc/cpuinfo'
  192. .....
  193. and once again, there is your message: QEMU communicated it to the Linux kernel, which printed it out.
  194. You have now gone from newb to hardware hacker in a mere 15 minutes, your rate of progress is truly astounding!!!
  195. 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:
  196. * 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]
  197. * 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
  198. * which implies that people can't develop open source link:https://en.wikipedia.org/wiki/Electronic_design_automation[EDA tools]
  199. * 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
  200. 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.
  201. If you really want to develop semiconductors, your only choice is to join an university or a semiconductor company that has the EDA licenses.
  202. ==== About the QEMU Buildroot setup
  203. This is our reference setup, and the best supported one, use it unless you have good reason not to.
  204. It was historically the first one we did, and all sections have been tested with this setup unless explicitly noted.
  205. link:https://en.wikipedia.org/wiki/Buildroot[Buildroot] is a set of Make scripts that download and compile from source compatible versions of:
  206. * GCC
  207. * Linux kernel
  208. * C standard library: Buildroot supports several implementations, we use link:https://en.wikipedia.org/wiki/GNU_C_Library[glibc] by default
  209. * link:https://en.wikipedia.org/wiki/BusyBox[BusyBox]: provides the shell and basic command line utilities
  210. It therefore produces a pristine, blob-less, debuggable setup, where all moving parts are configured to work perfectly together.
  211. The downsides of Buildroot are:
  212. * the first build takes a while, but it is well worth it
  213. * 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.
  214. +
  215. In theory, any software can be packaged, and the Buildroot side is easy.
  216. +
  217. The hard part is dealing with crappy third party build systems and huge dependency chains.
  218. 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.
  219. QEMU is 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.
  220. 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!
  221. All of this makes QEMU the natural choice of default system simulator.
  222. === gem5 Buildroot setup
  223. ==== About the gem5 Buildroot setup
  224. This setup is like the <<qemu-buildroot-setup>>, but it uses link:http://gem5.org/[gem5] instead of QEMU as a system simulator.
  225. 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, and this cannot be used to estimate system performance. This is known as a functional simulation.
  226. gem5 on the other hand, can simulate the system in more detail than QEMU, including:
  227. * simplified CPU pipeline
  228. * caches
  229. * DRAM timing
  230. and can therefore be used to estimate system performance, see: <<gem5-run-benchmark>> for an example.
  231. The downside of gem5 much slower than QEMU because of the greater simulation detail.
  232. See <<gem5-vs-qemu>> for a more thorough comparison.
  233. ==== gem5 Buildroot setup getting started
  234. For the most part, if you just add the `--gem5` option or `*-gem5` suffix to all commands and everything should magically work.
  235. If you haven't built Buildroot yet for <<qemu-buildroot-setup>>, you can build from the beginning with:
  236. ....
  237. ./download-dependencies --gem5 && ./build gem5-buildroot
  238. ./run --gem5
  239. ....
  240. 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.
  241. Remember that the gem5 boot is <<benchmark-linux-kernel-boot,considerably slower>> than QEMU since the simulation is more detailed.
  242. To get a terminal, either open a new shell and run:
  243. ....
  244. ./gem5-shell
  245. ....
  246. You can quit the shell without killing gem5 by typing tilde followed by a period:
  247. ....
  248. ~.
  249. ....
  250. If you are inside <<tmux>>, which I highly recommend, just run gem5 with:
  251. ....
  252. ./run --gem5 --tmux
  253. ....
  254. This will open up a split terminal by default so that you can see both the gem5 stdout and the terminal. See also: <<tmux-gem5>>.
  255. 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:
  256. ....
  257. # <6>[ 1.215329] clocksource: tsc: mask: 0xffffffffffffffff max_cycles: 0x1cd486fa865, max_idle_ns: 440795259574 ns
  258. <6>[ 1.215351] clocksource: Switched to clocksource tsc
  259. ....
  260. but if you look closely, the `PS1` prompt marker `#` is there already, just hit enter and a clear prompt line will appear.
  261. If you forgot to open the shell and gem5 exit, you can inspect the terminal output post-mortem at:
  262. ....
  263. less "$(./getvar --gem5 m5out_dir)/system.pc.com_1.device"
  264. ....
  265. More gem5 information is present at: <<gem5>>
  266. Good next steps are:
  267. * <<gem5-run-benchmark>>
  268. * <<m5out-directory>>
  269. * <<m5ops>>
  270. [[docker]]
  271. === Docker host setup
  272. This repository has been tested inside clean link:https://en.wikipedia.org/wiki/Docker_(software)[Docker] containers.
  273. 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.
  274. Buildroot is the most complex thing we build, and therefore the most likely to break, so running inside Docker is specially relevant to run:
  275. * <<qemu-buildroot-setup>>
  276. * <<gem5-buildroot-setup>>
  277. Before anything, you must get rid of any host build files on `out/` if you have any. A simple way to do this it to:
  278. ....
  279. mv out out.host
  280. ....
  281. A cleaner option is to make a separate clone of this repository just for Docker, although this will require another submodule update.
  282. Then install Docker, e.g. on Ubuntu:
  283. ....
  284. sudo apt-get install docker
  285. ....
  286. The very first time you launch Docker, create the container with:
  287. ....
  288. ./run-docker setup
  289. ....
  290. You are now left inside a shell in the Docker guest.
  291. From there, run the exact same commands that you would on a native install.
  292. The host git top level directory is mounted inside the guest, which means for example that you can use your host's GUI text editor directly on the files.
  293. Just don't forget that if you nuke that directory on the guest, then it gets nuked on the host as well!
  294. Trying to run the output from Docker from host won't however, I think the main reason is that the absolute paths inside Docker are different than the host ones, but even if we fix that there will likely be other problems.
  295. TODO make files created inside Docker be owned by the current user in host instead of `root`: https://stackoverflow.com/questions/23544282/what-is-the-best-way-to-manage-permissions-for-docker-shared-volumes
  296. Quit and stop the container:
  297. ....
  298. Ctrl-D
  299. ....
  300. Restart the container:
  301. ....
  302. ./run-docker
  303. ....
  304. In order to use functionality such as <<gdb>>, you need a second shell inside the container. You can either do that with:
  305. ....
  306. ./run-docker sh
  307. ....
  308. or even better, by starting a <<tmux>> session inside the container. We install `tmux` by default in the container.
  309. You can start a second shell and run a command in it at the same time with:
  310. ....
  311. ./run-docker sh ./run-gdb start_kernel
  312. ....
  313. Docker stops if and only if you quit the initial shell, you can quit this one without consequences.
  314. If you mistakenly run `./run-docker` twice, it opens two mirrored terminals. To quit one of them do link:https://stackoverflow.com/questions/19688314/how-do-you-attach-and-detach-from-dockers-process[]:
  315. ....
  316. Ctrl-P Ctrl-Q
  317. ....
  318. To use <<qemu-graphic-mode>> from Docker:
  319. ....
  320. ./run --graphic --vnc
  321. ....
  322. and then on host:
  323. ....
  324. sudo apt-get install vinagre
  325. ./vnc
  326. ....
  327. Destroy the docker container:
  328. ....
  329. ./run-docker DELETE
  330. ....
  331. Since we mount the guest's working directory on the host git top-level, you will likely not lose data from doing this, just the `apt-get` installs.
  332. To get back to a host build, don't forget to clean up `out/` again:
  333. ....
  334. mv out out.docker
  335. mv out.host out
  336. ....
  337. After this, to start using Docker again will you need another:
  338. ....
  339. ./run-docker setup
  340. ....
  341. Tested on: a760cb1196161e913a94684e03cfeaebf71f0cdd
  342. [[prebuilt]]
  343. === Prebuilt Buildroot setup
  344. ==== About the prebuilt Buildroot setup
  345. This setup uses prebuilt binaries of the <<qemu-buildroot-setup>> that we upload to GitHub from time to time.
  346. We don't currently provide a full prebuilt because it would be too big to host freely, notably because of the cross toolchain.
  347. Our prebuilts currently include:
  348. * Linux kernel
  349. * root filesystem
  350. Advantage: saves time and disk space on the initial install, which is expensive in largely due to building the toolchain.
  351. The limitations are severe however:
  352. * 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>>.
  353. +
  354. 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.
  355. * 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.
  356. * <<gem5>> is not currently supported, although it should not be too hard to do. Annoyances:
  357. +
  358. ** there is no Debian package for it, so you have to compile your own, so you might as well just build the image itself
  359. ** it does not handle <<gem5-qcow2,qcow2>>, and we haven't gotten <<squashfs>> to work yet, therefore we would have to either distribute large ext2 images, or constantly fight with <<br2_target_rootfs_ext2_size>>
  360. ** QEMU uses `bzImage` and gem5 the raw `vmlinux`, and we don't want to distribute the same thing twice...
  361. +
  362. And our attempt at using link:https://github.com/torvalds/linux/blob/master/scripts/extract-vmlinux[`extract-vmlinux`] failed for `aarch64` with:
  363. +
  364. ....
  365. run-detectors: unable to find an interpreter for
  366. ....
  367. 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? :-)
  368. ==== Prebuilt Buildroot setup getting started
  369. Some times it works with the host QEMU:
  370. ....
  371. sudo apt-get install qemu-system-x86
  372. git clone https://github.com/cirosantilli/linux-kernel-module-cheat
  373. cd linux-kernel-module-cheat
  374. ./release-download-latest
  375. unzip lkmc-*.zip
  376. ./run --prebuilt
  377. ....
  378. but to be sure, build your own at a tested revision:
  379. ....
  380. git submodule update --init --recursive "$(./getvar qemu_src_dir)"
  381. ./build-qemu
  382. ./run
  383. ....
  384. This also allows you to <<your-first-qemu-hack,modify QEMU>> if you're into that sort of thing.
  385. To try an older prebuilt:
  386. * download it from: link:https://github.com/cirosantilli/linux-kernel-module-cheat/releases[]
  387. * checkout this repo to match the SHA of the release
  388. then do whatever that checked out README says.
  389. If you are curious to see what the releases contain in detail, have a look at our <<release,release procedure>>.
  390. To build the kernel modules, simply do:
  391. ....
  392. ./build-linux -- modules_prepare
  393. ./build-modules
  394. ./run
  395. ....
  396. `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.
  397. To modify the Linux kernel, build and use it as usual:
  398. ....
  399. ./build-linux
  400. ./run
  401. ....
  402. ////
  403. For gem5, do:
  404. ....
  405. git submodule update --init --depth 1 "$(./getvar linux_src_dir)"
  406. sudo apt-get install qemu-utils
  407. ./build-gem5
  408. ./run --gem5 --prebuilt
  409. ....
  410. `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.
  411. 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
  412. ////
  413. ////
  414. [[ubuntu]]
  415. === Ubuntu guest setup
  416. ==== About the Ubuntu guest setup
  417. 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.
  418. The rationale for choice of Ubuntu as a second distribution in addition to Buildroot can be found at: <<linux-distro-choice>>
  419. Advantages over Buildroot:
  420. * saves build time
  421. * you get to play with a huge selection of Debian packages out of the box
  422. * more representative of most non-embedded production systems than BusyBox
  423. Disadvantages:
  424. * 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
  425. * 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
  426. 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:
  427. * 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
  428. * the default Ubuntu image has a large collection of software, and is large. The docker version is much more minimal.
  429. 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`.
  430. ==== Ubuntu guest setup getting started
  431. TODO
  432. ....
  433. sudo ./build-docker
  434. ./run --docker
  435. ....
  436. `sudo` is required for Docker operations: https://askubuntu.com/questions/477551/how-can-i-use-docker-without-sudo
  437. ////
  438. [[host]]
  439. === Host kernel module setup
  440. **THIS IS DANGEROUS (AND FUN), YOU HAVE BEEN WARNED**
  441. 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.
  442. It has however severe limitations:
  443. * 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].
  444. * bugs can easily break you system. E.g.:
  445. ** segfaults can trivially lead to a kernel crash, and require a reboot
  446. ** 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`.
  447. ** 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]
  448. * can't control which hardware is used, notably the CPU architecture
  449. * 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.
  450. Still interested?
  451. ....
  452. ./build-modules --host
  453. ....
  454. Compilation will likely fail for some modules because of kernel or toolchain differences that we can't control on the host.
  455. The best solution is to compile just your modules with:
  456. ....
  457. ./build-modules --host -- hello hello2
  458. ....
  459. which is equivalent to:
  460. ....
  461. ./build-modules --host -- packages/kernel/modules/hello.c packages/kernel/modules/hello2.c
  462. ....
  463. Or just remove the `.c` extension from the failing files and try again:
  464. ....
  465. cd "$(./getvar kernel_modules_src_dir)"
  466. mv broken.c broken.c~
  467. ....
  468. Once you manage to compile, and have come to terms with the fact that this may blow up your host, try it out with:
  469. ....
  470. cd "$(./getvar kernel_modules_build_host_subdir)"
  471. sudo insmod hello.ko
  472. # Our module is there.
  473. sudo lsmod | grep hello
  474. # Last message should be: hello init
  475. dmesg -T
  476. sudo rmmod hello
  477. # Last message should be: hello exit
  478. dmesg -T
  479. # Not present anymore
  480. sudo lsmod | grep hello
  481. ....
  482. ==== Hello host
  483. Minimal host build system example:
  484. ....
  485. cd hello_host_kernel_module
  486. make
  487. sudo insmod hello.ko
  488. dmesg
  489. sudo rmmod hello.ko
  490. dmesg
  491. ....
  492. === Baremetal setup
  493. ==== About the baremetal setup
  494. This setup does not use the Linux kernel nor Buildroot at all: it just runs your very own minimal OS.
  495. `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.
  496. 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.
  497. 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.
  498. 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
  499. 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
  500. ==== Baremetal setup getting started
  501. QEMU:
  502. ....
  503. ./download-dependencies --baremetal --qemu && \
  504. ./build-qemu --arch arm && \
  505. ./build-crosstool-ng --arch arm && \
  506. ./build-baremetal --arch arm && \
  507. ./run --arch arm --baremetal prompt
  508. ....
  509. You are now left inside QEMU running the tiny baremetal system link:baremetal/prompt.c[], which uses the UART to:
  510. * print characters to the terminal
  511. * read characters from your keyboard
  512. A session looks like this after typing `abc`:
  513. ....
  514. enter a character
  515. got: a
  516. new alloc of 1 bytes at address 0x0x4000a2c8
  517. enter a character
  518. got: b
  519. new alloc of 2 bytes at address 0x0x4000a2c8
  520. enter a character
  521. got: c
  522. new alloc of 4 bytes at address 0x0x4000a2c8
  523. ....
  524. `./build-baremetal` is the command that actually builds the baremetal system for us. It uses crosstool-NG, so that command must be preceded by `./build-crosstool-ng`.
  525. Every `.c` file inside link:baremetal/[] and `.S` file inside `baremetal/arch/<arch>/` generates a separate baremetal image. You can run a different image with commands such as:
  526. ....
  527. ./run --arch arm --baremetal exit
  528. ./run --arch arm --baremetal arch/arm/semihost_exit
  529. ....
  530. which will run respectively:
  531. * link:baremetal/exit.c[]
  532. * link:baremetal/arch/arm/m5exit.S[]
  533. which just make the emulator quit via <<semihosting>>.
  534. Alternatively, for the sake of tab completion, we also accept relative paths inside `baremetal/`:
  535. ....
  536. ./run --arch arm --baremetal baremetal/exit.c
  537. ./run --arch arm --baremetal baremetal/arch/arm/semihost_exit.c
  538. ....
  539. Absolute paths however as used as is an must point to the actual executable:
  540. ....
  541. ./run --arch arm --baremetal "$(./getvar --arch arm baremetal_build_dir)/exit.elf"
  542. ....
  543. To use gem5 instead of QEMU do:
  544. ....
  545. patch -d "$(./getvar gem5_src_dir)" -p 1 < patches/manual/gem5-semihost.patch
  546. ./download-dependencies --baremetal --gem5
  547. ./build-gem5 --arch arm
  548. ./build-crosstool-ng --arch arm
  549. ./build-baremetal --arch arm --gem5
  550. ./run --arch arm --baremetal prompt --gem5
  551. ....
  552. and then <<qemu-buildroot-setup,as usual>> open a shell with:
  553. ....
  554. ./gem5-shell
  555. ....
  556. TODO: the carriage returns are a bit different than in QEMU, see: <<gem5-baremetal-carriage-return>>.
  557. The semihosting patch is required to enable <<semihosting>>, on which base functionality such as `exit()` depends, see also: https://stackoverflow.com/questions/52475268/how-to-enable-arm-semihosting-in-gem5/52475269#52475269
  558. Note that `./build-baremetal` requires the `--gem5` option, and generates separate executable images for both, as can be seen from:
  559. ....
  560. echo "$(./getvar --arch aarch64 --baremetal prompt image)"
  561. echo "$(./getvar --arch aarch64 --baremetal prompt --gem5 image)"
  562. ....
  563. This is unlike the Linux kernel that has a single image for both QEMU and gem5:
  564. ....
  565. echo "$(./getvar --arch aarch64 image)"
  566. echo "$(./getvar --arch aarch64 --gem5 image)"
  567. ....
  568. 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.
  569. `gem5` also supports the `RealViewPBX` machine, which represents an older hardware compared to the default `VExpress_GEM5_V1`:
  570. ....
  571. ./build-baremetal --arch arm --gem5 --machine RealViewPBX
  572. ./run --arch arm --baremetal prompt --gem5 --machine RealViewPBX
  573. ....
  574. This generates yet new separate images with new magic constants:
  575. ....
  576. echo "$(./getvar --arch arm --baremetal prompt --gem5 --machine VExpress_GEM5_V1 image)"
  577. echo "$(./getvar --arch arm --baremetal prompt --gem5 --machine RealViewPBX image)"
  578. ....
  579. But just stick to newer and better `VExpress_GEM5_V1` unless you have a good reason to use `RealViewPBX`.
  580. When doing bare metal programming, it is likely that you will want to learn assembly language basics. Have a look at these tutorials for the userland part:
  581. * https://github.com/cirosantilli/x86-assembly-cheat
  582. * https://github.com/cirosantilli/arm-assembly-cheat
  583. For more information on baremetal, see the section: <<baremetal>>. The following subjects are particularly important:
  584. * <<tracing>>
  585. * <<baremetal-gdb-step-debug>>
  586. [[gdb]]
  587. == GDB step debug
  588. === GDB step debug kernel boot
  589. `--debug-guest` makes QEMU wait for a GDB connection, otherwise we could accidentally go past the point we want to break at:
  590. ....
  591. ./run --debug-guest
  592. ....
  593. Say you want to break at `start_kernel`. So on another shell:
  594. ....
  595. ./run-gdb start_kernel
  596. ....
  597. or at a given line:
  598. ....
  599. ./run-gdb init/main.c:1088
  600. ....
  601. Now QEMU will stop there, and you can use the normal GDB commands:
  602. ....
  603. list
  604. next
  605. continue
  606. ....
  607. See also:
  608. * http://stackoverflow.com/questions/11408041/how-to-debug-the-linux-kernel-with-gdb-and-qemu/33203642#33203642
  609. * http://stackoverflow.com/questions/4943857/linux-kernel-live-debugging-how-its-done-and-what-tools-are-used/42316607#42316607
  610. [[kernel-o0]]
  611. ==== Disable kernel compiler optimizations
  612. https://stackoverflow.com/questions/29151235/how-to-de-optimize-the-linux-kernel-to-and-compile-it-with-o0
  613. `O=0` is an impossible dream, `O=2` being the default.
  614. So get ready for some weird jumps, and `<value optimized out>` fun. Why, Linux, why.
  615. === GDB step debug kernel post-boot
  616. Let's observe the kernel as it reacts to some userland actions.
  617. Start QEMU with just:
  618. ....
  619. ./run
  620. ....
  621. and after boot inside a shell run:
  622. ....
  623. /count.sh
  624. ....
  625. which counts to infinity to stdout. Source: link:rootfs_overlay/count.sh[].
  626. Then in another shell, run:
  627. ....
  628. ./run-gdb
  629. ....
  630. and then hit:
  631. ....
  632. Ctrl-C
  633. break __x64_sys_write
  634. continue
  635. continue
  636. continue
  637. ....
  638. And you now control the counting on the first shell from GDB!
  639. Before v4.17, the symbol name was just `sys_write`, the change happened at link:https://github.com/torvalds/linux/commit/d5a00528b58cdb2c71206e18bd021e34c4eab878[d5a00528b58cdb2c71206e18bd021e34c4eab878]. aarch64 still uses just `sys_write`.
  640. 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.
  641. === tmux
  642. tmux just makes things even more fun by allowing us to see both terminals at once without dragging windows around!
  643. First start `tmux` with:
  644. ....
  645. tmux
  646. ....
  647. Now that you are inside a shell inside tmux, run:
  648. ....
  649. ./run --debug-guest --tmux
  650. ....
  651. Gives splits the terminal into two panes:
  652. * left: usual QEMU
  653. * right: gdb
  654. and focuses on the GDB pane.
  655. Now you can navigate with the usual tmux shortcuts:
  656. * switch between the two panes with: `Ctrl-B O`
  657. * close either pane by killing its terminal with `Ctrl-D` as usual
  658. To start again, switch back to the QEMU pane, kill the emulator, and re-run:
  659. ....
  660. ./run --debug-guest --tmux
  661. ....
  662. This automatically clears the GDB pane, and starts a new one.
  663. Pass extra GDB arguments with:
  664. ....
  665. ./run --debug-guest --tmux=start_kernel
  666. ....
  667. See the tmux manual for further details:
  668. ....
  669. man tmux
  670. ....
  671. 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
  672. ==== tmux gem5
  673. If you are using gem5 instead of QEMU, `--tmux` has a different effect: it opens the gem5 terminal instead of the debugger:
  674. ....
  675. ./run --gem5 --tmux
  676. ....
  677. If you also want to use the debugger with gem5, you will need to create new terminals as usual.
  678. From inside tmux, you can do that with `Ctrl-B C` or `Ctrl-B %`.
  679. To see the debugger by default instead of the terminal, run:
  680. ....
  681. ./tmu ./run-gdb
  682. ./run --debug-guest --gem5
  683. ....
  684. === GDB step debug kernel module
  685. http://stackoverflow.com/questions/28607538/how-to-debug-linux-kernel-modules-with-qemu/44095831#44095831
  686. Loadable kernel modules are a bit trickier since the kernel can place them at different memory locations depending on load order.
  687. So we cannot set the breakpoints before `insmod`.
  688. However, the Linux kernel GDB scripts offer the `lx-symbols` command, which takes care of that beautifully for us.
  689. Shell 1:
  690. ....
  691. ./run
  692. ....
  693. Wait for the boot to end and run:
  694. ....
  695. insmod /timer.ko
  696. ....
  697. Source: link:kernel_modules/timer.c[].
  698. This prints a message to dmesg every second.
  699. Shell 2:
  700. ....
  701. ./run-gdb
  702. ....
  703. In GDB, hit `Ctrl-C`, and note how it says:
  704. ....
  705. scanning for modules in /root/linux-kernel-module-cheat/out/kernel_modules/x86_64/kernel_modules
  706. loading @0xffffffffc0000000: /root/linux-kernel-module-cheat/out/kernel_modules/x86_64/kernel_modules/timer.ko
  707. ....
  708. That's `lx-symbols` working! Now simply:
  709. ....
  710. break lkmc_timer_callback
  711. continue
  712. continue
  713. continue
  714. ....
  715. and we now control the callback from GDB!
  716. Just don't forget to remove your breakpoints after `rmmod`, or they will point to stale memory locations.
  717. TODO: why does `break work_func` for `insmod kthread.ko` not very well? Sometimes it breaks but not others.
  718. [[gdb-step-debug-kernel-module-arm]]
  719. ==== GDB step debug kernel module insmodded by init on ARM
  720. TODO on `arm` 51e31cdc2933a774c2a0dc62664ad8acec1d2dbe it does not always work, and `lx-symbols` fails with the message:
  721. ....
  722. loading vmlinux
  723. Traceback (most recent call last):
  724. File "/linux-kernel-module-cheat//out/arm/buildroot/build/linux-custom/scripts/gdb/linux/symbols.py", line 163, in invoke
  725. self.load_all_symbols()
  726. File "/linux-kernel-module-cheat//out/arm/buildroot/build/linux-custom/scripts/gdb/linux/symbols.py", line 150, in load_all_symbols
  727. [self.load_module_symbols(module) for module in module_list]
  728. File "/linux-kernel-module-cheat//out/arm/buildroot/build/linux-custom/scripts/gdb/linux/symbols.py", line 110, in load_module_symbols
  729. module_name = module['name'].string()
  730. gdb.MemoryError: Cannot access memory at address 0xbf0000cc
  731. Error occurred in Python command: Cannot access memory at address 0xbf0000cc
  732. ....
  733. Can't reproduce on `x86_64` and `aarch64` are fine.
  734. It is kind of random: if you just `insmod` manually and then immediately `./run-gdb --arch arm`, then it usually works.
  735. But this fails most of the time: shell 1:
  736. ....
  737. ./run --arch arm --eval-busybox 'insmod /hello.ko'
  738. ....
  739. shell 2:
  740. ....
  741. ./run-gdb --arch arm
  742. ....
  743. then hit `Ctrl-C` on shell 2, and voila.
  744. Then:
  745. ....
  746. cat /proc/modules
  747. ....
  748. says that the load address is:
  749. ....
  750. 0xbf000000
  751. ....
  752. so it is close to the failing `0xbf0000cc`.
  753. `readelf`:
  754. ....
  755. ./run-toolchain readelf -- -s "$(./getvar kernel_modules_build_subdir)/hello.ko"
  756. ....
  757. does not give any interesting hits at `cc`, no symbol was placed that far.
  758. ==== GDB module_init
  759. TODO find a more convenient method. We have working methods, but they are not ideal.
  760. 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!
  761. Possibly asked at:
  762. * https://stackoverflow.com/questions/37059320/debug-a-kernel-module-being-loaded
  763. * https://stackoverflow.com/questions/11888412/debug-the-init-module-call-of-a-linux-kernel-module
  764. ===== GDB module_init step into it
  765. This is the best method we've found so far.
  766. The kernel calls `module_init` synchronously, therefore it is not hard to step into that call.
  767. As of 4.16, the call happens in `do_one_initcall`, so we can do in shell 1:
  768. ....
  769. ./run
  770. ....
  771. shell 2 after boot finishes (because there are other calls to `do_init_module` at boot, presumably for the built-in modules):
  772. ....
  773. ./run-gdb do_one_initcall
  774. ....
  775. then step until the line:
  776. ....
  777. 833 ret = fn();
  778. ....
  779. which does the actual call, and then step into it.
  780. For the next time, you can also put a breakpoint there directly:
  781. ....
  782. ./run-gdb init/main.c:833
  783. ....
  784. How we found this out: first we got <<gdb-module_init-calculate-entry-address>> working, and then we did a `bt`. AKA cheating :-)
  785. ===== GDB module_init calculate entry address
  786. This works, but is a bit annoying.
  787. 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.
  788. So once we find the address the first time, we can just reuse it afterwards, as long as we don't modify the module.
  789. Do a fresh boot and get the module:
  790. ....
  791. ./run --eval-busybox '/pr_debug.sh;insmod /fops.ko;/poweroff.out'
  792. ....
  793. The boot must be fresh, because the load address changes every time we insert, even after removing previous modules.
  794. The base address shows on terminal:
  795. ....
  796. 0xffffffffc0000000 .text
  797. ....
  798. Now let's find the offset of `myinit`:
  799. ....
  800. ./run-toolchain readelf -- \
  801. -s "$(./getvar kernel_modules_build_subdir)/fops.ko" | \
  802. grep myinit
  803. ....
  804. which gives:
  805. ....
  806. 30: 0000000000000240 43 FUNC LOCAL DEFAULT 2 myinit
  807. ....
  808. so the offset address is `0x240` and we deduce that the function will be placed at:
  809. ....
  810. 0xffffffffc0000000 + 0x240 = 0xffffffffc0000240
  811. ....
  812. Now we can just do a fresh boot on shell 1:
  813. ....
  814. ./run --eval 'insmod /fops.ko;/poweroff.out' --debug-guest
  815. ....
  816. and on shell 2:
  817. ....
  818. ./run-gdb '*0xffffffffc0000240'
  819. ....
  820. GDB then breaks, and `lx-symbols` works.
  821. ===== GDB module_init break at the end of sys_init_module
  822. TODO not working. This could be potentially very convenient.
  823. 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.
  824. Beware that there are both `sys_init_module` and `sys_finit_module` syscalls, and `insmod` uses `fmodule_init` by default.
  825. Both call `do_module_init` however, which is what `lx-symbols` hooks to.
  826. If we try:
  827. ....
  828. b sys_finit_module
  829. ....
  830. then hitting:
  831. ....
  832. n
  833. ....
  834. does not break, and insertion happens, likely because of optimizations? <<kernel-o0>>
  835. Then we try:
  836. ....
  837. b do_init_module
  838. ....
  839. A naive:
  840. ....
  841. fin
  842. ....
  843. also fails to break!
  844. Finally, in despair we notice that <<pr_debug>> prints the kernel load address as explained at <<bypass-lx-symbols>>.
  845. 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.
  846. ===== GDB module_init add trap instruction
  847. This is another possibility: we could modify the module source by adding a trap instruction of some kind.
  848. This appears to be described at: https://www.linuxjournal.com/article/4525
  849. But it refers to a `gdbstart` script which is not in the tree anymore and beyond my `git log` capabilities.
  850. And just adding:
  851. ....
  852. asm( " int $3");
  853. ....
  854. directly gives an <<oops,oops>> as I'd expect.
  855. ==== Bypass lx-symbols
  856. Useless, but a good way to show how hardcore you are. Disable `lx-symbols` with:
  857. ....
  858. ./run-gdb --no-lxsymbols
  859. ....
  860. From inside guest:
  861. ....
  862. insmod /timer.ko
  863. cat /proc/modules
  864. ....
  865. as mentioned at:
  866. * https://stackoverflow.com/questions/6384605/how-to-get-address-of-a-kernel-module-loaded-using-insmod/6385818
  867. * https://unix.stackexchange.com/questions/194405/get-base-address-and-size-of-a-loaded-kernel-module
  868. This will give a line of form:
  869. ....
  870. fops 2327 0 - Live 0xfffffffa00000000
  871. ....
  872. And then tell GDB where the module was loaded with:
  873. ....
  874. Ctrl-C
  875. add-symbol-file ../../../rootfs_overlay/x86_64/timer.ko 0xffffffffc0000000
  876. 0xffffffffc0000000
  877. ....
  878. Alternatively, if the module panics before you can read `/proc/modules`, there is a <<pr_debug>> which shows the load address:
  879. ....
  880. echo 8 > /proc/sys/kernel/printk
  881. echo 'file kernel/module.c +p' > /sys/kernel/debug/dynamic_debug/control
  882. /myinsmod.out /hello.ko
  883. ....
  884. And then search for a line of type:
  885. ....
  886. [ 84.877482] 0xfffffffa00000000 .text
  887. ....
  888. Tested on 4f4749148273c282e80b58c59db1b47049e190bf + 1.
  889. === GDB step debug early boot
  890. TODO sucessfully debu the very first instruction that the Linux kernel runs, before `start_kernel`!
  891. Break at the very first instruction executed by QEMU:
  892. ....
  893. ./run-gdb --no-continue
  894. ....
  895. TODO why can't we break at early startup stuff such as:
  896. ....
  897. ./run-gdb extract_kernel
  898. ./run-gdb main
  899. ....
  900. 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?
  901. See also: https://stackoverflow.com/questions/2589845/what-are-the-first-operations-that-the-linux-kernel-executes-on-boot
  902. <<gem5-tracing>> with `--debug-flags=Exec` does show the right symbols however! So in the worst case, we can just read their source. Amazing.
  903. TODO: try out `CONFIG_HAVE_KERNEL_UNCOMPRESSED=y` from Linux v4.19 and see if it gives us any extra visibility.
  904. ==== GDB step debug early boot by address
  905. One possibility is to run:
  906. ....
  907. ./trace-boot --arch arm
  908. ....
  909. and then find the second address (the first one does not work, already too late maybe):
  910. ....
  911. less "$(./getvar --arch arm trace_txt_file)"
  912. ....
  913. and break there:
  914. ....
  915. ./run --arch arm --debug-guest
  916. ./run-gdb --arch arm '*0x1000'
  917. ....
  918. 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
  919. I also tried to hack `run-gdb` with:
  920. ....
  921. @@ -81,7 +81,7 @@ else
  922. ${gdb} \
  923. -q \\
  924. -ex 'add-auto-load-safe-path $(pwd)' \\
  925. --ex 'file vmlinux' \\
  926. +-ex 'file arch/arm/boot/compressed/vmlinux' \\
  927. -ex 'target remote localhost:${port}' \\
  928. ${brk} \
  929. -ex 'continue' \\
  930. ....
  931. and no I do have the symbols from `arch/arm/boot/compressed/vmlinux'`, but the breaks still don't work.
  932. === GDB step debug userland processes
  933. QEMU's `-gdb` GDB breakpoints are set on virtual addresses, so you can in theory debug userland processes as well.
  934. * https://stackoverflow.com/questions/26271901/is-it-possible-to-use-gdb-and-qemu-to-debug-linux-user-space-programs-and-kernel
  935. * https://stackoverflow.com/questions/16273614/debug-init-on-qemu-using-gdb
  936. You will generally want to use <<gdbserver>> for this as it is more reliable, but this method can overcome the following limitations of `gdbserver`:
  937. * the emulator does not support host to guest networking. This seems to be the case for gem5: <<gem5-host-to-guest-networking>>
  938. * cannot see the start of the `init` process easily
  939. * `gdbserver` alters the working of the kernel, and makes your run less representative
  940. Known limitations of direct userland debugging:
  941. * 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.
  942. * TODO step into shared libraries. If I attempt to load them explicitly:
  943. +
  944. ....
  945. (gdb) sharedlibrary ../../staging/lib/libc.so.0
  946. No loaded shared libraries match the pattern `../../staging/lib/libc.so.0'.
  947. ....
  948. +
  949. since GDB does not know that libc is loaded.
  950. ==== GDB step debug userland custom init
  951. * Shell 1:
  952. +
  953. ....
  954. ./run --debug-guest --kernel-cli 'init=/sleep_forever.out'
  955. ....
  956. * Shell 2:
  957. +
  958. ....
  959. ./run-gdb-user "$(./getvar userland_build_dir)/sleep_forever.out" main
  960. ....
  961. TODO not working as of f8c0502bb2680f2dbe7c1f3d7958f60265347005, does not break. Bisect on recent QEMU and kernel. Debug by creating an executable that prints the address of `main`.
  962. ==== GDB step debug userland BusyBox init
  963. BusyBox custom init process:
  964. * Shell 1:
  965. +
  966. ....
  967. ./run --debug-guest --kernel-cli 'init=/bin/ls'
  968. ....
  969. * Shell 2:
  970. +
  971. ....
  972. ./run-gdb-user busybox-1.26.2/busybox ls_main
  973. ....
  974. This follows BusyBox' convention of calling the main for each executable as `<exec>_main` since the `busybox` executable has many "mains".
  975. BusyBox default init process:
  976. * Shell 1:
  977. +
  978. ....
  979. ./run --debug-guest
  980. ....
  981. * Shell 2:
  982. +
  983. ....
  984. ./run-gdb-user busybox-1.26.2/busybox init_main
  985. ....
  986. This cannot be debugged in another way without modifying the source, or `/sbin/init` exits early with:
  987. ....
  988. "must be run as PID 1"
  989. ....
  990. ==== GDB step debug userland non-init
  991. Non-init process:
  992. * Shell 1:
  993. +
  994. ....
  995. ./run --debug-guest
  996. ....
  997. * Shell 2:
  998. +
  999. ....
  1000. ./run-gdb-user "$(./getvar userland_build_dir)/myinsmod.out" main
  1001. ....
  1002. * Shell 1 after the boot finishes:
  1003. +
  1004. ....
  1005. /myinsmod.out /hello.ko
  1006. ....
  1007. This is the least reliable setup as there might be other processes that use the given virtual address.
  1008. ===== GDB step debug userland non-init without --debug-guest
  1009. TODO: on QEMU bfba11afddae2f7b2c1335b4e23133e9cd3c9126, it works on `x86_64` and `aarch64` but fails on arm as follows:
  1010. * Shell 1:
  1011. +
  1012. ....
  1013. ./run --arch arm
  1014. ....
  1015. * Shell 2: wait for boot to finish, and run:
  1016. +
  1017. ....
  1018. ./run-gdb-user --arch arm "$(./getvar userland_build_dir)/hello.out" main
  1019. ....
  1020. * Shell 1:
  1021. +
  1022. ....
  1023. /hello.out
  1024. ....
  1025. The problem is that the `b main` that we do inside `./run-gdb-user` says:
  1026. ....
  1027. Cannot access memory at address 0x10604
  1028. ....
  1029. We have also double checked the address with:
  1030. ....
  1031. ./run-toolchain --arch arm readelf -- \
  1032. -s "$(./getvar --arch arm kernel_modules_build_subdir)/fops.ko" | \
  1033. grep main
  1034. ....
  1035. and from GDB:
  1036. ....
  1037. info line main
  1038. ....
  1039. and both give:
  1040. ....
  1041. 000105fc
  1042. ....
  1043. which is just 8 bytes before `0x10604`.
  1044. `gdbserver` also says `0x10604`.
  1045. However, if do a `Ctrl-C` in GDB, and then a direct:
  1046. ....
  1047. b *0x000105fc
  1048. ....
  1049. it works. Why?!
  1050. 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.
  1051. === GDB call
  1052. GDB can call functions as explained at: https://stackoverflow.com/questions/1354731/how-to-evaluate-functions-in-gdb
  1053. However this is failing for us:
  1054. * some symbols are not visible to `call` even though `b` sees them
  1055. * for those that are, `call` fails with an E14 error
  1056. E.g.: if we break on `__x64_sys_write` on `/count.sh`:
  1057. ....
  1058. >>> call printk(0, "asdf")
  1059. Could not fetch register "orig_rax"; remote failure reply 'E14'
  1060. >>> b printk
  1061. Breakpoint 2 at 0xffffffff81091bca: file kernel/printk/printk.c, line 1824.
  1062. >>> call fdget_pos(fd)
  1063. No symbol "fdget_pos" in current context.
  1064. >>> b fdget_pos
  1065. Breakpoint 3 at 0xffffffff811615e3: fdget_pos. (9 locations)
  1066. >>>
  1067. ....
  1068. even though `fdget_pos` is the first thing `__x64_sys_write` does:
  1069. ....
  1070. 581 SYSCALL_DEFINE3(write, unsigned int, fd, const char __user *, buf,
  1071. 582 size_t, count)
  1072. 583 {
  1073. 584 struct fd f = fdget_pos(fd);
  1074. ....
  1075. I also noticed that I get the same error:
  1076. ....
  1077. Could not fetch register "orig_rax"; remote failure reply 'E14'
  1078. ....
  1079. when trying to use:
  1080. ....
  1081. fin
  1082. ....
  1083. on many (all?) functions.
  1084. See also: https://github.com/cirosantilli/linux-kernel-module-cheat/issues/19
  1085. === GDB view ARM system registers
  1086. `info all-registers` shows some of them.
  1087. The implementation is described at: https://stackoverflow.com/questions/46415059/how-to-observe-aarch64-system-registers-in-qemu/53043044#53043044
  1088. === GDB step debug multicore
  1089. We can set and get which cores the Linux kernel allows a program to run on with `sched_getaffinity` and `sched_setaffinity`:
  1090. ....
  1091. ./run --cpus 2 --eval-busybox '/sched_getaffinity.out'
  1092. ....
  1093. Source: link:userland/sched_getaffinity.c[]
  1094. Sample output:
  1095. ....
  1096. sched_getaffinity = 1 1
  1097. sched_getcpu = 1
  1098. sched_getaffinity = 1 0
  1099. sched_getcpu = 0
  1100. ....
  1101. Which shows us that:
  1102. * initially:
  1103. ** all 2 cores were enabled as shown by `sched_getaffinity = 1 1`
  1104. ** 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.
  1105. * then we restrict the affinity to just core 0, and we see that the program was actually moved to core 0
  1106. The number of cores is modified as explained at: <<number-of-cores>>
  1107. `taskset` from the util-linux package sets the initial core affinity of a program:
  1108. ....
  1109. ./build-buildroot \
  1110. --config 'BR2_PACKAGE_UTIL_LINUX=y' \
  1111. --config 'BR2_PACKAGE_UTIL_LINUX_SCHEDUTILS=y' \
  1112. ;
  1113. ./run --eval-busybox 'taskset -c 1,1 /sched_getaffinity.out'
  1114. ....
  1115. output:
  1116. ....
  1117. sched_getaffinity = 0 1
  1118. sched_getcpu = 1
  1119. sched_getaffinity = 1 0
  1120. sched_getcpu = 0
  1121. ....
  1122. so we see that the affinity was restricted to the second core from the start.
  1123. Let's do a QEMU observation to justify this example being in the repository with <<gdb-step-debug-userland-non-init,userland breakpoints>>.
  1124. We will run our `/sched_getaffinity.out` infinitely many time, on core 0 and core 1 alternatively:
  1125. ....
  1126. ./run \
  1127. --cpus 2 \
  1128. --debug-guest \
  1129. --eval-busybox 'i=0; while true; do taskset -c $i,$i /sched_getaffinity.out; i=$((! $i)); done' \
  1130. ;
  1131. ....
  1132. on another shell:
  1133. ....
  1134. ./run-gdb-user "$(./getvar userland_build_dir)/sched_getaffinity.out" main
  1135. ....
  1136. Then, inside GDB:
  1137. ....
  1138. (gdb) info threads
  1139. Id Target Id Frame
  1140. * 1 Thread 1 (CPU#0 [running]) main () at sched_getaffinity.c:30
  1141. 2 Thread 2 (CPU#1 [halted ]) native_safe_halt () at ./arch/x86/include/asm/irqflags.h:55
  1142. (gdb) c
  1143. (gdb) info threads
  1144. Id Target Id Frame
  1145. 1 Thread 1 (CPU#0 [halted ]) native_safe_halt () at ./arch/x86/include/asm/irqflags.h:55
  1146. * 2 Thread 2 (CPU#1 [running]) main () at sched_getaffinity.c:30
  1147. (gdb) c
  1148. ....
  1149. and we observe that `info threads` shows the actual correct core on which the process was restricted to run by `taskset`!
  1150. We should also try it out with kernel modules: https://stackoverflow.com/questions/28347876/set-cpu-affinity-on-a-loadable-linux-kernel-module
  1151. TODO we then tried:
  1152. ....
  1153. ./run --cpus 2 --eval-busybox '/sched_getaffinity_threads.out'
  1154. ....
  1155. and:
  1156. ....
  1157. ./run-gdb-user "$(./getvar userland_build_dir)/sched_getaffinity_threads.out"
  1158. ....
  1159. to switch between two simultaneous live threads with different affinities, it just didn't break on our threads:
  1160. ....
  1161. b main_thread_0
  1162. ....
  1163. Bibliography:
  1164. * https://stackoverflow.com/questions/10490756/how-to-use-sched-getaffinity-and-sched-setaffinity-in-linux-from-c/50117787#50117787
  1165. * https://stackoverflow.com/questions/42800801/how-to-use-gdb-to-debug-qemu-with-smp-symmetric-multiple-processors
  1166. === Linux kernel GDB scripts
  1167. We source the Linux kernel GDB scripts by default for `lx-symbols`, but they also contains some other goodies worth looking into.
  1168. Those scripts basically parse some in-kernel datastructures to offer greater visibility with GDB.
  1169. All defined commands are prefixed by `lx-`, so to get a full list just try to tab complete that.
  1170. 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.
  1171. Show dmesg:
  1172. ....
  1173. lx-dmesg
  1174. ....
  1175. Show the <<kernel-command-line-parameters>>:
  1176. ....
  1177. lx-cmdline
  1178. ....
  1179. Dump the device tree to a `fdtdump.dtb` file in the current directory:
  1180. ....
  1181. lx-fdtdump
  1182. pwd
  1183. ....
  1184. List inserted kernel modules:
  1185. ....
  1186. lx-lsmod
  1187. ....
  1188. Sample output:
  1189. ....
  1190. Address Module Size Used by
  1191. 0xffffff80006d0000 hello 16384 0
  1192. ....
  1193. Bibliography:
  1194. * https://events.static.linuxfound.org/sites/events/files/slides/Debugging%20the%20Linux%20Kernel%20with%20GDB.pdf
  1195. * https://wiki.linaro.org/LandingTeams/ST/GDB
  1196. ==== lx-ps
  1197. List all processes:
  1198. ....
  1199. lx-ps
  1200. ....
  1201. Sample output:
  1202. ....
  1203. 0xffff88000ed08000 1 init
  1204. 0xffff88000ed08ac0 2 kthreadd
  1205. ....
  1206. The second and third fields are obviously PID and process name.
  1207. The first one is more interesting, and contains the address of the `task_struct` in memory.
  1208. This can be confirmed with:
  1209. ....
  1210. p ((struct task_struct)*0xffff88000ed08000
  1211. ....
  1212. which contains the correct PID for all threads I've tried:
  1213. ....
  1214. pid = 1,
  1215. ....
  1216. 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!
  1217. On ARM, I tried:
  1218. ....
  1219. task_pt_regs((struct thread_info *)((struct task_struct)*0xffffffc00e8f8000))->uregs[ARM_pc]
  1220. ....
  1221. 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?
  1222. Bibliography:
  1223. * https://stackoverflow.com/questions/9561546/thread-aware-gdb-for-kernel
  1224. * https://wiki.linaro.org/LandingTeams/ST/GDB
  1225. * https://events.static.linuxfound.org/sites/events/files/slides/Debugging%20the%20Linux%20Kernel%20with%20GDB.pdf presentation: https://www.youtube.com/watch?v=pqn5hIrz3A8
  1226. === Debug the GDB remote protocol
  1227. For when it breaks again, or you want to add a new feature!
  1228. ....
  1229. ./run --debug
  1230. ./run-gdb --before '-ex "set remotetimeout 99999" -ex "set debug remote 1"' start_kernel
  1231. ....
  1232. See also: https://stackoverflow.com/questions/13496389/gdb-remote-protocol-how-to-analyse-packets
  1233. ==== Remote 'g' packet reply is too long
  1234. This error means that the GDB server, e.g. in QEMU, sent more registers than the GDB client expected.
  1235. This can happen for the following reasons:
  1236. * 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
  1237. * there is a bug in the GDB server and the XML description does not match the number of registers actually sent
  1238. * 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
  1239. 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
  1240. == KGDB
  1241. KGDB is kernel dark magic that allows you to GDB the kernel on real hardware without any extra hardware support.
  1242. 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.
  1243. 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.
  1244. First run the kernel with:
  1245. ....
  1246. ./run --kgdb
  1247. ....
  1248. this passes the following options on the kernel CLI:
  1249. ....
  1250. kgdbwait kgdboc=ttyS1,115200
  1251. ....
  1252. `kgdbwait` tells the kernel to wait for KGDB to connect.
  1253. So the kernel sets things up enough for KGDB to start working, and then boot pauses waiting for connection:
  1254. ....
  1255. <6>[ 4.866050] Serial: 8250/16550 driver, 4 ports, IRQ sharing disabled
  1256. <6>[ 4.893205] 00:05: ttyS0 at I/O 0x3f8 (irq = 4, base_baud = 115200) is a 16550A
  1257. <6>[ 4.916271] 00:06: ttyS1 at I/O 0x2f8 (irq = 3, base_baud = 115200) is a 16550A
  1258. <6>[ 4.987771] KGDB: Registered I/O driver kgdboc
  1259. <2>[ 4.996053] KGDB: Waiting for connection from remote gdb...
  1260. Entering kdb (current=0x(____ptrval____), pid 1) on processor 0 due to Keyboard Entry
  1261. [0]kdb>
  1262. ....
  1263. KGDB expects the connection at `ttyS1`, our second serial port after `ttyS0` which contains the terminal.
  1264. The last line is the KDB prompt, and is covered at: <<kdb>>. Typing now shows nothing because that prompt is expecting input from `ttyS1`.
  1265. Instad, we connect to the serial port `ttyS1` with GDB:
  1266. ....
  1267. ./run-gdb --kgdb --no-continue
  1268. ....
  1269. Once GDB connects, it is left inside the function `kgdb_breakpoint`.
  1270. So now we can set breakpoints and continue as usual.
  1271. For example, in GDB:
  1272. ....
  1273. continue
  1274. ....
  1275. Then in QEMU:
  1276. ....
  1277. /count.sh &
  1278. /kgdb.sh
  1279. ....
  1280. link:rootfs_overlay:kgdb.sh[] pauses the kernel for KGDB, and gives control back to GDB.
  1281. And now in GDB we do the usual:
  1282. ....
  1283. break __x64_sys_write
  1284. continue
  1285. continue
  1286. continue
  1287. continue
  1288. ....
  1289. 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 as it recently did is to try:
  1290. ....
  1291. rbreak .*sys_write
  1292. ....
  1293. And now you can count from GDB!
  1294. 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.
  1295. See also:
  1296. * https://github.com/torvalds/linux/blob/v4.9/Documentation/DocBook/kgdb.tmpl
  1297. * https://stackoverflow.com/questions/22004616/qemu-kernel-debugging-with-kgdb/44197715#44197715
  1298. === KGDB ARM
  1299. 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
  1300. One possible workaround for this would be to use <<kdb-arm>>.
  1301. Main more generic question: https://stackoverflow.com/questions/14155577/how-to-use-kgdb-on-arm
  1302. === KGDB kernel modules
  1303. In QEMU:
  1304. ....
  1305. insmod /timer.ko
  1306. ....
  1307. Source: link:rootfs_overlay/kgdb-mod.sh[].
  1308. In GDB:
  1309. ....
  1310. lx-symbols ../kernel_modules-1.0/
  1311. break lkmc_timer_callback
  1312. continue
  1313. continue
  1314. continue
  1315. ....
  1316. and you now control the count.
  1317. TODO: if I `-ex lx-symbols` to the `gdb` command, just like done for QEMU `-gdb`, the kernel <<oops,oops>>. How to automate this step?
  1318. === KDB
  1319. KDB is a way to use KDB directly in your main console, without GDB.
  1320. 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 .
  1321. 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).
  1322. Run QEMU as:
  1323. ....
  1324. ./run --kdb
  1325. ....
  1326. This passes `kgdboc=ttyS0` to the Linux CLI, therefore using our main console. Then QEMU:
  1327. ....
  1328. [0]kdb> go
  1329. ....
  1330. And now the `kdb>` prompt is responsive because it is listening to the main console.
  1331. After boot finishes, run the usual:
  1332. ....
  1333. /count.sh &
  1334. /kgdb.sh
  1335. ....
  1336. And you are back in KDB. Now you can count with:
  1337. ....
  1338. [0]kdb> bp __x64_sys_write
  1339. [0]kdb> go
  1340. [0]kdb> go
  1341. [0]kdb> go
  1342. [0]kdb> go
  1343. ....
  1344. And you will break whenever `__x64_sys_write` is hit.
  1345. You can get see further commands with:
  1346. ....
  1347. [0]kdb> help
  1348. ....
  1349. The other KDB commands allow you to instruction steps, view memory, registers and some higher level kernel runtime data.
  1350. ==== KDB graphic
  1351. You can also use KDB directly from the <<graphics,graphic>> window with:
  1352. ....
  1353. ./run --graphic --kdb
  1354. ....
  1355. This setup could be used to debug the kernel on machines without serial, such as modern desktops.
  1356. This works because `--graphics` This adds `kbd` (which stands for `KeyBoarD`!) to `kgdboc`.
  1357. ==== KDB ARM
  1358. TODO neither `arm` and `aarch64` are working as of 1cd1e58b023791606498ca509256cc48e95e4f5b + 1.
  1359. `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.
  1360. `aarch64` seems to place the breakpoint correctly, but after the first `go` the kernel oopses with warning:
  1361. ....
  1362. WARNING: CPU: 0 PID: 46 at /root/linux-kernel-module-cheat/submodules/linux/kernel/smp.c:416 smp_call_function_many+0xdc/0x358
  1363. ....
  1364. and stack trace:
  1365. ....
  1366. smp_call_function_many+0xdc/0x358
  1367. kick_all_cpus_sync+0x30/0x38
  1368. kgdb_flush_swbreak_addr+0x3c/0x48
  1369. dbg_deactivate_sw_breakpoints+0x7c/0xb8
  1370. kgdb_cpu_enter+0x284/0x6a8
  1371. kgdb_handle_exception+0x138/0x240
  1372. kgdb_brk_fn+0x2c/0x40
  1373. brk_handler+0x7c/0xc8
  1374. do_debug_exception+0xa4/0x1c0
  1375. el1_dbg+0x18/0x78
  1376. __arm64_sys_write+0x0/0x30
  1377. el0_svc_handler+0x74/0x90
  1378. el0_svc+0x8/0xc
  1379. ....
  1380. My theory is that every serious ARM developer has either serial or JTAG, and no one ever tests this, and the kernel code is just broken.
  1381. == gdbserver
  1382. Step debug userland processes to understand how they are talking to the kernel.
  1383. First build `gdbserver` into the root filesystem:
  1384. ....
  1385. ./build-buildroot --config 'BR2_PACKAGE_GDB=y'
  1386. ....
  1387. Then on guest:
  1388. ....
  1389. /gdbserver.sh /myinsmod.out /hello.ko
  1390. ....
  1391. Source: link:rootfs_overlay/gdbserver.sh[].
  1392. Host:
  1393. ....
  1394. ./run-gdbserver "$(./getvar userland_build_dir)/myinsmod.out"
  1395. ....
  1396. You can find the executable with:
  1397. ....
  1398. find "$(./getvar build_dir)" -name myinsmod.out
  1399. ....
  1400. TODO: automate the path finding:
  1401. * using the executable from under `$(./getvar target_dir)` would be easier as the path is the same as in guest, but unfortunately those executables are stripped to make the guest smaller. `BR2_STRIP_none=y` should disable stripping, but make the image way larger.
  1402. * `$(./getvar staging_dir)` would be even better than the target dir as Buildroot docs say that this directory contains binaries before they were stripped. However, only a few binaries are pre-installed there by default, and it seems to be a manual per package thing.
  1403. +
  1404. E.g. `pciutils` has for `lspci`:
  1405. +
  1406. ....
  1407. define PCIUTILS_INSTALL_STAGING_CMDS
  1408. $(TARGET_MAKE_ENV) $(MAKE1) -C $(@D) $(PCIUTILS_MAKE_OPTS) \
  1409. PREFIX=$(STAGING_DIR)/usr SBINDIR=$(STAGING_DIR)/usr/bin \
  1410. install install-lib install-pcilib
  1411. endef
  1412. ....
  1413. +
  1414. and the docs describe the `*_INSTALL_STAGING` per package config, which is normally set for shared library packages.
  1415. +
  1416. Feature request: https://bugs.busybox.net/show_bug.cgi?id=10386
  1417. An implementation overview can be found at: https://reverseengineering.stackexchange.com/questions/8829/cross-debugging-for-mips-elf-with-qemu-toolchain/16214#16214
  1418. === gdbserver different archs
  1419. As usual, different archs work with:
  1420. ....
  1421. ./run-gdbserver --arch arm "$(./getvar userland_build_dir)/myinsmod.out"
  1422. ....
  1423. === gdbserver BusyBox
  1424. BusyBox executables are all symlinks, so if you do on guest:
  1425. ....
  1426. /gdbserver.sh ls
  1427. ....
  1428. on host you need:
  1429. ....
  1430. ./run-gdbserver busybox-1.26.2/busybox
  1431. ....
  1432. === gdbserver shared libraries
  1433. Our setup gives you the rare opportunity to step debug libc and other system libraries e.g. with:
  1434. ....
  1435. b open
  1436. c
  1437. ....
  1438. Or simply by stepping into calls:
  1439. ....
  1440. s
  1441. ....
  1442. This is made possible by the GDB command:
  1443. ....
  1444. set sysroot ${common_buildroot_build_dir}/staging
  1445. ....
  1446. which automatically finds unstripped shared libraries on the host for us.
  1447. See also: https://stackoverflow.com/questions/8611194/debugging-shared-libraries-with-gdbserver/45252113#45252113
  1448. === gdbserver dynamic loader
  1449. 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
  1450. Bibliography: https://stackoverflow.com/questions/20114565/gdb-step-into-dynamic-linkerld-so-code
  1451. == CPU architecture
  1452. The portability of the kernel and toolchains is amazing: change an option and most things magically work on completely different hardware.
  1453. To use `arm` instead of x86 for example:
  1454. ....
  1455. ./build-buildroot --arch arm
  1456. ./run --arch arm
  1457. ....
  1458. Debug:
  1459. ....
  1460. ./run --arch arm --debug-guest
  1461. # On another terminal.
  1462. ./run-gdb --arch arm
  1463. ....
  1464. We also have one letter shorthand names for the architectures and `--arch` option:
  1465. ....
  1466. # aarch64
  1467. ./run -a A
  1468. # arm
  1469. ./run -a a
  1470. # x86_64
  1471. ./run -a x
  1472. ....
  1473. Known quirks of the supported architectures are documented in this section.
  1474. === x86_64
  1475. ==== ring0
  1476. This example illustrates how reading from the x86 control registers with `mov crX, rax` can only be done from kernel land on ring0.
  1477. From kernel land:
  1478. ....
  1479. insmod ring0.ko
  1480. ....
  1481. works and output the registers, for example:
  1482. ....
  1483. cr0 = 0xFFFF880080050033
  1484. cr2 = 0xFFFFFFFF006A0008
  1485. cr3 = 0xFFFFF0DCDC000
  1486. ....
  1487. However if we try to do it from userland:
  1488. ....
  1489. /ring0.out
  1490. ....
  1491. stdout gives:
  1492. ....
  1493. Segmentation fault
  1494. ....
  1495. and dmesg outputs:
  1496. ....
  1497. traps: ring0.out[55] general protection ip:40054c sp:7fffffffec20 error:0 in ring0.out[400000+1000]
  1498. ....
  1499. Sources:
  1500. * link:kernel_modules/ring0.c[]
  1501. * link:kernel_modules/ring0.h[]
  1502. * link:userland/ring0.c[]
  1503. In both cases, we attempt to run the exact same code which is shared on the `ring0.h` header file.
  1504. Bibliography:
  1505. * https://stackoverflow.com/questions/7415515/how-to-access-the-control-registers-cr0-cr2-cr3-from-a-program-getting-segmenta/7419306#7419306
  1506. * https://stackoverflow.com/questions/18717016/what-are-ring-0-and-ring-3-in-the-context-of-operating-systems/44483439#44483439
  1507. === arm
  1508. ==== Run arm executable in aarch64
  1509. 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
  1510. I've tried:
  1511. ....
  1512. ./run-toolchain --arch aarch64 gcc -- -static ~/test/hello_world.c -o "$(./getvar p9_dir)/a.out"
  1513. ./run --arch aarch64 --eval-busybox '/mnt/9p/data/a.out'
  1514. ....
  1515. but it fails with:
  1516. ....
  1517. a.out: line 1: syntax error: unexpected word (expecting ")")
  1518. ....
  1519. === MIPS
  1520. We used to "support" it until f8c0502bb2680f2dbe7c1f3d7958f60265347005 (it booted) but dropped since one was testing it often.
  1521. If you want to revive and maintain it, send a pull request.
  1522. === Other architectures
  1523. It should not be too hard to port this repository to any architecture that Buildroot supports. Pull requests are welcome.
  1524. == init
  1525. When the Linux kernel finishes booting, it runs an executable as the first and only userland process. This executable is called the `init` program.
  1526. The init process is then responsible for setting up the entire userland (or destroying everything when you want to have fun).
  1527. 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.
  1528. systemd provides a "popular" init implementation for desktop distros as of 2017.
  1529. BusyBox provides its own minimalistic init implementation which Buildroot, and therefore this repo, uses by default.
  1530. 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
  1531. 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>>
  1532. === Replace init
  1533. To have more control over the system, you can replace BusyBox's init with your own.
  1534. The most direct way to replace `init` with our own is to just use the `init=` <<kernel-command-line-parameters,command line parameter>> directly:
  1535. ....
  1536. ./run --kernel-cli 'init=/count.sh'
  1537. ....
  1538. This just counts every second forever and does not give you a shell.
  1539. 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>>.
  1540. For this reason, we have created a more robust helper method with the `--eval` option:
  1541. ....
  1542. ./run --eval 'echo "asdf qwer";insmod /hello.ko;/poweroff.out'
  1543. ....
  1544. The `--eval` option replaces init with a shell script that just evals the given command.
  1545. It is basically a shortcut for:
  1546. ....
  1547. ./run --kernel-cli 'init=/eval_base64.sh - lkmc_eval="insmod /hello.ko;/poweroff.out"'
  1548. ....
  1549. Source: link:rootfs_overlay/eval_base64.sh[].
  1550. This allows quoting and newlines by base64 encoding on host, and decoding on guest, see: <<kernel-command-line-parameters-escaping>>.
  1551. It also automatically chooses between `init=` and `rcinit=` for you, see: <<path-to-init>>
  1552. `--eval` replaces BusyBox' init completely, which makes things more minimal, but also has has the following consequences:
  1553. * `/etc/fstab` mounts are not done, notably `/proc` and `/sys`, test it out with:
  1554. +
  1555. ....
  1556. ./run --eval 'echo asdf;ls /proc;ls /sys;echo qwer'
  1557. ....
  1558. * 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:
  1559. +
  1560. ....
  1561. ./run --eval 'echo hello;sh'
  1562. ....
  1563. The best way to overcome those limitations is to use: <<init-busybox>>
  1564. If the script is large, you can add it to a gitignored file and pass that to `-E` as in:
  1565. ....
  1566. echo '
  1567. insmod /hello.ko
  1568. /poweroff.out
  1569. ' > gitignore.sh
  1570. ./run --eval "$(cat gitignore.sh)"
  1571. ....
  1572. or add it to a file to the root filesystem guest and rebuild:
  1573. ....
  1574. echo '#!/bin/sh
  1575. insmod /hello.ko
  1576. /poweroff.out
  1577. ' > rootfs_overlay/gitignore.sh
  1578. chmod +x rootfs_overlay/gitignore.sh
  1579. ./build-buildroot
  1580. ./run --kernel-cli 'init=/gitignore.sh'
  1581. ....
  1582. Remember that if your init returns, the kernel will panic, there are just two non-panic possibilities:
  1583. * run forever in a loop or long sleep
  1584. * `poweroff` the machine
  1585. ==== poweroff.out
  1586. Just using BusyBox' `poweroff` at the end of the `init` does not work and the kernel panics:
  1587. ....
  1588. ./run --eval poweroff
  1589. ....
  1590. because BusyBox' `poweroff` tries to do some fancy stuff like killing init, likely to allow userland to shutdown nicely.
  1591. But this fails when we are `init` itself!
  1592. `poweroff` works more brutally and effectively if you add `-f`:
  1593. ....
  1594. ./run --eval 'poweroff -f'
  1595. ....
  1596. but why not just use our minimal `/poweroff.out` and be done with it?
  1597. ....
  1598. ./run --eval '/poweroff.out'
  1599. ....
  1600. Source: link:userland/poweroff.c[]
  1601. 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
  1602. ==== sleep_forever.out
  1603. I dare you to guess what this does:
  1604. ....
  1605. ./run --eval '/sleep_forever.out'
  1606. ....
  1607. Source: link:userland/sleep_forever.c[]
  1608. This executable is a convenient simple init that does not panic and sleeps instead.
  1609. ==== time_boot.out
  1610. Get a reasonable answer to "how long does boot take?":
  1611. ....
  1612. ./run --eval-busybox '/time_boot.out'
  1613. ....
  1614. Dmesg contains a message of type:
  1615. ....
  1616. [ 2.188242] time_boot.c
  1617. ....
  1618. which tells us that boot took `2.188242` seconds.
  1619. Bibliography: https://stackoverflow.com/questions/12683169/measure-time-taken-for-linux-kernel-from-bootup-to-userpace/46517014#46517014
  1620. [[init-busybox]]
  1621. === Run command at the end of BusyBox init
  1622. Use the `--eval-busybox` option is for you rely on something that BusyBox' init set up for you like `/etc/fstab`:
  1623. ....
  1624. ./run --eval-busybox 'echo asdf;ls /proc;ls /sys;echo qwer'
  1625. ....
  1626. After the commands run, you are left on an interactive shell.
  1627. The above command is basically equivalent to:
  1628. ....
  1629. ./run --kernel-cli-after-dash 'lkmc_eval="insmod /hello.ko;poweroff.out;"'
  1630. ....
  1631. where the `lkmc_eval` option gets evaled by our default link:rootfs_overlay/etc/init.d/S98[S98] startup script.
  1632. Except that `--eval-busybox` is smarter and uses `base64` encoding.
  1633. Alternatively, you can also add the comamdns to run to a new `init.d` entry to run at the end o the BusyBox init:
  1634. ....
  1635. cp rootfs_overlay/etc/init.d/S98 rootfs_overlay/etc/init.d/S99.gitignore
  1636. vim rootfs_overlay/etc/init.d/S99.gitignore
  1637. ./build-buildroot
  1638. ./run
  1639. ....
  1640. and they will be run automatically before the login prompt.
  1641. 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`].
  1642. === Path to init
  1643. The init is selected at:
  1644. * initrd or initramfs system: `/init`, a custom one can be set with the `rdinit=` <<kernel-command-line-parameters,kernel command line parameter>>
  1645. * otherwise: default is `/sbin/init`, followed by some other paths, a custom one can be set with `init=`
  1646. 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
  1647. === Init environment
  1648. Documented at link:https://www.kernel.org/doc/html/v4.14/admin-guide/kernel-parameters.html[]:
  1649. ____
  1650. 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.
  1651. ____
  1652. And you can try it out with:
  1653. ....
  1654. ./run --kernel-cli 'init=/init_env_poweroff.out - asdf=qwer zxcv'
  1655. ....
  1656. Output:
  1657. ....
  1658. args:
  1659. /init_env_poweroff.out
  1660. -
  1661. zxcv
  1662. env:
  1663. HOME=/
  1664. TERM=linux
  1665. asdf=qwer
  1666. ....
  1667. Source: link:userland/init_env_poweroff.c[].
  1668. ==== init environment args
  1669. The annoying dash `-` gets passed as a parameter to `init`, which makes it impossible to use this method for most non custom executables.
  1670. Arguments with dots that come after `-` are still treated specially (of the form `subsystem.somevalue`) and disappear, from args, e.g.:
  1671. ....
  1672. ./run --kernel-cli 'init=/init_env_poweroff.out - /poweroff.out'
  1673. ....
  1674. outputs:
  1675. ....
  1676. args
  1677. /init_env_poweroff.out
  1678. -
  1679. ab
  1680. ....
  1681. so see how `a.b` is gone.
  1682. ==== init environment env
  1683. 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
  1684. ....
  1685. const char *envp_init[MAX_INIT_ENVS+2] = { "HOME=/", "TERM=linux", NULL, };
  1686. ....
  1687. ==== BusyBox shell init environment
  1688. On top of the Linux kernel, the BusyBox `/bin/sh` shell will also define other variables.
  1689. We can explore the shenanigans that the shell adds on top of the Linux kernel with:
  1690. ....
  1691. ./run --kernel-cli 'init=/bin/sh'
  1692. ....
  1693. From there we observe that:
  1694. ....
  1695. env
  1696. ....
  1697. gives:
  1698. ....
  1699. SHLVL=1
  1700. HOME=/
  1701. TERM=linux
  1702. PWD=/
  1703. ....
  1704. therefore adding `SHLVL` and `PWD` to the default kernel exported variables.
  1705. 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:
  1706. ....
  1707. set
  1708. ....
  1709. then it shows more variables, notably:
  1710. ....
  1711. PATH='/sbin:/usr/sbin:/bin:/usr/bin'
  1712. ....
  1713. Finally, login shells will source some default files, notably:
  1714. ....
  1715. /etc/profile
  1716. /root/.profile
  1717. ....
  1718. We currently control `/root/.profile` at link:rootfs_overlay/root/.profile[], and use the default BusyBox `/etc/profile`.
  1719. 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
  1720. When we use just `init=/bin/sh`, the Linux kernel sets `argv[0]` to `/bin/sh`, which does not start with `-`.
  1721. However, if you use `::respawn:-/bin/sh` on inttab described at <<tty>>, BusyBox' init sets `argv[0]` to `-`, and so does `getty`. This can be observed with:
  1722. ....
  1723. cat /proc/$$/cmdline
  1724. ....
  1725. where `$$` is the PID of the shell itself: https://stackoverflow.com/questions/21063765/get-pid-in-shell-bash
  1726. == initrd
  1727. TODO: broken when we started building the Linux manually with `./build-linux` instead of Buildroot. Was working before, see e.g. 56738a1c70e50bf7b6d5fbe02372c5d277a8286f.
  1728. 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
  1729. The bootloader, which for us is QEMU itself, is then configured to put that CPIO into memory, and tell the kernel that it is there.
  1730. 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.
  1731. To enable initrd instead of the default ext2 disk image, do:
  1732. ....
  1733. ./build-buildroot --initrd
  1734. ./run --initrd
  1735. ....
  1736. Notice how it boots fine, even though this leads to not giving QEMU the `-drive` option, as can be verified with:
  1737. ....
  1738. cat "$(./getvar run_dir)/run.sh"
  1739. ....
  1740. Also as expected, there is no filesystem persistency, since we are doing everything in memory:
  1741. ....
  1742. date >f
  1743. poweroff
  1744. cat f
  1745. # can't open 'f': No such file or directory
  1746. ....
  1747. which can be good for automated tests, as it ensures that you are using a pristine unmodified system image every time.
  1748. One downside of this method is that it has to put the entire filesystem into memory, and could lead to a panic:
  1749. ....
  1750. end Kernel panic - not syncing: Out of memory and no killable processes...
  1751. ....
  1752. This can be solved by increasing the memory with:
  1753. ....
  1754. ./run --initrd --memory 256M
  1755. ....
  1756. The main ingredients to get initrd working are:
  1757. * `BR2_TARGET_ROOTFS_CPIO=y`: make Buildroot generate `images/rootfs.cpio` in addition to the other images.
  1758. +
  1759. It is also possible to compress that image with other options.
  1760. * `qemu -initrd`: make QEMU put the image into memory and tell the kernel about it.
  1761. * `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
  1762. +
  1763. Buildroot forces that option when `BR2_TARGET_ROOTFS_CPIO=y` is given
  1764. https://unix.stackexchange.com/questions/89923/how-does-linux-load-the-initrd-image asks how the mechanism works in more detail.
  1765. === initrd in desktop distros
  1766. Most modern desktop distributions have an initrd in their root disk to do early setup.
  1767. The rationale for this is described at: https://en.wikipedia.org/wiki/Initial_ramdisk
  1768. One obvious use case is having an encrypted root filesystem: you keep the initrd in an unencrypted partition, and then setup decryption from there.
  1769. 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:
  1770. ....
  1771. initrd /initrd.img-4.4.0-108-generic
  1772. ....
  1773. Related: https://stackoverflow.com/questions/6405083/initrd-and-booting-the-linux-kernel
  1774. === initramfs
  1775. initramfs is just like <<initrd>>, but you also glue the image directly to the kernel image itself.
  1776. So the only argument that QEMU needs is the `-kernel`, no `-drive` not even `-initrd`! Pretty cool.
  1777. Try it out with:
  1778. ....
  1779. ./build-buildroot --initramfs -l
  1780. ./run --initramfs
  1781. ....
  1782. The `-l` (ell) should only be used the first time you move to / from a different root filesystem method (ext2 or cpio) to initramfs to overcome: https://stackoverflow.com/questions/49260466/why-when-i-change-br2-linux-kernel-custom-config-file-and-run-make-linux-reconfi
  1783. ....
  1784. ./build-buildroot --initramfs
  1785. ./run --initramfs
  1786. ....
  1787. It is interesting to see how this increases the size of the kernel image if you do a:
  1788. ....
  1789. ls -lh "$(./getvar linux_image)"
  1790. ....
  1791. before and after using initramfs, since the `.cpio` is now glued to the kernel image.
  1792. In the background, it uses `BR2_TARGET_ROOTFS_INITRAMFS`, and this makes the kernel config option `CONFIG_INITRAMFS_SOURCE` point to the CPIO that will be embedded in the kernel image.
  1793. http://nairobi-embedded.org/initramfs_tutorial.html shows a full manual setup.
  1794. === gem5 initrd
  1795. 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
  1796. == Device tree
  1797. The device tree is a Linux kernel defined data structure that serves to inform the kernel how the hardware is setup.
  1798. <<platform_device>> contains a minimal runnable example of device tree manipulation.
  1799. 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.
  1800. x86 does not use it device trees, but many other archs to, notably ARM.
  1801. This is notably because ARM boards:
  1802. * typically don't have discoverable hardware extensions like PCI, but rather just put everything on an SoC with magic register addresses
  1803. * are made by a wide variety of vendors due to ARM's licensing business model, which increases variability
  1804. 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
  1805. === DTB files
  1806. Files that contain device trees have the `.dtb` extension when compiled, and `.dts` when in text form.
  1807. You can convert between those formats with:
  1808. ....
  1809. "$(./getvar host_dir)"/bin/dtc -I dtb -O dts -o a.dts a.dtb
  1810. "$(./getvar host_dir)"/bin/dtc -I dts -O dtb -o a.dtb a.dts
  1811. ....
  1812. Buildroot builds the tool due to `BR2_PACKAGE_HOST_DTC=y`.
  1813. On Ubuntu 18.04, the package is named:
  1814. ....
  1815. sudo apt-get install device-tree-compiler
  1816. ....
  1817. See also: https://stackoverflow.com/questions/14000736/tool-to-visualize-the-device-tree-file-dtb-used-by-the-linux-kernel/39931834#39931834
  1818. Device tree files are provided to the emulator just like the root filesystem and the Linux kernel image.
  1819. In real hardware, those components are also often provided separately. For example, on the Raspberry Pi 2, the SD card must contain two partitions:
  1820. * the first contains all magic files, including the Linux kernel and the device tree
  1821. * the second contains the root filesystem
  1822. See also: https://stackoverflow.com/questions/29837892/how-to-run-a-c-program-with-no-os-on-the-raspberry-pi/40063032#40063032
  1823. === Device tree syntax
  1824. Good format descriptions:
  1825. * https://www.raspberrypi.org/documentation/configuration/device-tree.md
  1826. Minimal example
  1827. ....
  1828. /dts-v1/;
  1829. / {
  1830. a;
  1831. };
  1832. ....
  1833. Check correctness with:
  1834. ....
  1835. dtc a.dts
  1836. ....
  1837. Separate nodes are simply merged by node path, e.g.:
  1838. ....
  1839. /dts-v1/;
  1840. / {
  1841. a;
  1842. };
  1843. / {
  1844. b;
  1845. };
  1846. ....
  1847. then `dtc a.dts` gives:
  1848. ....
  1849. /dts-v1/;
  1850. / {
  1851. a;
  1852. b;
  1853. };
  1854. ....
  1855. === Get device tree from a running kernel
  1856. https://unix.stackexchange.com/questions/265890/is-it-possible-to-get-the-information-for-a-device-tree-using-sys-of-a-running/330926#330926
  1857. 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.
  1858. So observing the device tree from the guest allows to easily see what the emulator has generated.
  1859. Compile the `dtc` tool into the root filesystem:
  1860. ....
  1861. ./build-buildroot \
  1862. --arch aarch64 \
  1863. --config 'BR2_PACKAGE_DTC=y' \
  1864. --config 'BR2_PACKAGE_DTC_PROGRAMS=y' \
  1865. ;
  1866. ....
  1867. `-M virt` for example, which we use by default for `aarch64`, boots just fine without the `-dtb` option:
  1868. ....
  1869. ./run --arch aarch64
  1870. ....
  1871. Then, from inside the guest:
  1872. ....
  1873. dtc -I fs -O dts /sys/firmware/devicetree/base
  1874. ....
  1875. contains:
  1876. ....
  1877. cpus {
  1878. #address-cells = <0x1>;
  1879. #size-cells = <0x0>;
  1880. cpu@0 {
  1881. compatible = "arm,cortex-a57";
  1882. device_type = "cpu";
  1883. reg = <0x0>;
  1884. };
  1885. };
  1886. ....
  1887. === Device tree emulator generation
  1888. Since emulators know everything about the hardware, they can automatically generate device trees for us, which is very convenient.
  1889. This is the case for both QEMU and gem5.
  1890. For example, if we increase the <<number-of-cores,number of cores>> to 2:
  1891. ....
  1892. ./run --arch aarch64 --cpus 2
  1893. ....
  1894. QEMU automatically adds a second CPU to the DTB!
  1895. ....
  1896. cpu@0 {
  1897. cpu@1 {
  1898. ....
  1899. The action seems to be happening at: `hw/arm/virt.c`.
  1900. <<gem5-fs_biglittle>> 2a9573f5942b5416fb0570cf5cb6cdecba733392 can also generate its own DTB.
  1901. gem5 can generate DTBs on ARM with `--generate-dtb`, but we don't use that feature as of f8c0502bb2680f2dbe7c1f3d7958f60265347005 because it was buggy.
  1902. == KVM
  1903. You can make QEMU or gem5 <<benchmark-linux-kernel-boot,run faster>> by passing enabling KVM with:
  1904. ....
  1905. ./run --kvm
  1906. ....
  1907. but it was broken in gem5 with pending patches: https://www.mail-archive.com/gem5-users@gem5.org/msg15046.html It fails immediately on:
  1908. ....
  1909. panic: KVM: Failed to enter virtualized mode (hw reason: 0x80000021)
  1910. ....
  1911. KVM uses the link:https://en.wikipedia.org/wiki/Kernel-based_Virtual_Machine[KVM Linux kernel feature] of the host to run most instructions natively.
  1912. We don't enable KVM by default because:
  1913. * only works if the architecture of the guest equals that of the host.
  1914. +
  1915. We have only tested / supported it on x86, but it is rumoured that QEMU and gem5 also have ARM KVM support if you are link:https://www.youtube.com/watch?v=8ItXpmLsINs[running an ARM desktop for some weird reason] :-)
  1916. * limits visibility, since more things are running natively:
  1917. ** can't use GDB
  1918. ** can't do instruction tracing
  1919. * kernel boots are already fast enough without `-enable-kvm`
  1920. The main use case for `-enable-kvm` in this repository is to test if something that takes a long time to run is functionally correct.
  1921. For example, when porting a benchmark to Buildroot, you can first use QEMU's KVM to test that benchmarks is producing the correct results, before analysing them more deeply in gem5, which runs much slower.
  1922. == User mode simulation
  1923. Both QEMU and gem5 have an user mode simulation mode in addition to full system simulation that we consider elsewhere in this project.
  1924. In QEMU, it is called just <<qemu-user-mode,"user mode">>, and in gem5 it is called <<gem5-syscall-emulation-mode,syscall emulation mode>>.
  1925. In both, the basic idea is the same.
  1926. User mode simulation takes regular userland executables of any arch as input and executes them directly, without booting a kernel.
  1927. Instead of simulating the full system, it translates normal instructions like in full system mode, but magically forwards system calls to the host OS.
  1928. Advantages over full system simulation:
  1929. * 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
  1930. * 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.
  1931. Disadvantages:
  1932. * lower guest to host portability:
  1933. ** TODO confirm: host OS == guest OS?
  1934. ** TODO confirm: the host Linux kernel should be newer than the kernel the executable was built for.
  1935. +
  1936. It may still work even if that is not the case, but could fail is a missing system call is reached.
  1937. +
  1938. The target Linux kernel of the executable is a GCC toolchain build-time configuration.
  1939. * cannot be used to test the Linux kernel, and results are less representative of a real system since we are faking more
  1940. === QEMU user mode
  1941. First let's run a dynamically linked executable built with the Buildroot toolchain:
  1942. ....
  1943. ./build-qemu --arch arm --userland
  1944. ./build-userland --arch arm
  1945. ./build-buildroot --arch arm
  1946. ./run \
  1947. --arch arm \
  1948. --userland print_argv \
  1949. -- \
  1950. asdf qwer \
  1951. ;
  1952. ....
  1953. This runs link:userland/print_argv.c[]. `--userland` path resolution is analogous to <<baremetal-setup-getting-started,that of `--baremetal`>>.
  1954. `./build-userland` is further documented at: <<userland-directory>>.
  1955. 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.
  1956. We pass `-L` by default, so everything just works:
  1957. You can also try statically linked executables with:
  1958. ....
  1959. ./build-userland \
  1960. --arch arm \
  1961. --make-args='CCFLAGS_EXTRA=-static' \
  1962. --userland-build-id static \
  1963. ;
  1964. ./run \
  1965. --arch arm \
  1966. --userland-build-id static \
  1967. --userland print_argv \
  1968. -- \
  1969. asdf qwer \
  1970. ;
  1971. ....
  1972. Or you can run statically linked built by the host packaged toolchain with:
  1973. ....
  1974. ./build-userland \
  1975. --arch arm \
  1976. --host \
  1977. --make-args='-B CFLAGS_EXTRA=-static' \
  1978. --userland-build-id host-static \
  1979. ;
  1980. ./run \
  1981. --arch arm \
  1982. --userland-build-id host-static \
  1983. --userland print_argv \
  1984. -- \
  1985. asdf qwer \
  1986. ;
  1987. ....
  1988. TODO expose dynamically linked executables built by the host toolchain. It also works, we just have to use e.g. `-L /usr/aarch64-linux-gnu`, so it's not really hard, I'm just lazy.
  1989. ==== QEMU user mode GDB
  1990. It's nice when <<gdb,the obvious>> just works, right?
  1991. ....
  1992. ./run \
  1993. --arch arm \
  1994. --debug-guest \
  1995. --userland print_argv \
  1996. -- \
  1997. asdf qwer \
  1998. ;
  1999. ....
  2000. and on another shell:
  2001. ....
  2002. ./run-gdb \
  2003. --arch arm \
  2004. --userland print_argv \
  2005. main \
  2006. ;
  2007. ....
  2008. or to stop at the very first instruction of a freestanding program, just use `--no-continue` TODO example.
  2009. === gem5 syscall emulation mode
  2010. Less robust than QEMU's, but still usable:
  2011. * https://stackoverflow.com/questions/48986597/when-should-you-use-full-system-fs-vs-syscall-emulation-se-with-userland-program
  2012. * https://stackoverflow.com/questions/48959349/how-to-solve-fatal-kernel-too-old-when-running-gem5-in-syscall-emulation-se-m
  2013. There are much more unimplemented syscalls in gem5 than in QEMU. Many of those are trivial to implement however.
  2014. As of 185c2730cc78d5adda683d76c0e3b35e7cb534f0, dynamically linked executables only work on x86, and they can only use the host libraries, which is ugly:
  2015. * https://stackoverflow.com/questions/50542222/how-to-run-a-dynamically-linked-executable-syscall-emulation-mode-se-py-in-gem5
  2016. * https://www.mail-archive.com/gem5-users@gem5.org/msg15585.html
  2017. If you try dynamically linked executables on ARM, they fail with:
  2018. ....
  2019. fatal: Unable to open dynamic executable's interpreter.
  2020. ....
  2021. So let's just play with some static ones:
  2022. ....
  2023. ./build-userland \
  2024. --arch aarch64 \
  2025. --userland-build-id static \
  2026. --make-args='CCFLAGS_EXTRA=-static' \
  2027. ;
  2028. ./run \
  2029. --arch aarch64 \
  2030. --gem5 \
  2031. --userland print_argv \
  2032. --userland-build-id static \
  2033. -- \
  2034. --options 'asdf "qw er"' \
  2035. ;
  2036. ....
  2037. TODO: how to escape spaces?
  2038. Step debug also works:
  2039. ....
  2040. ./run \
  2041. --arch arm \
  2042. --debug-guest \
  2043. --gem5 \
  2044. --userland print_argv \
  2045. --userland-build-id static \
  2046. -- \
  2047. --options 'asdf "qw er"' \
  2048. ;
  2049. ./run-gdb \
  2050. --arch arm \
  2051. --gem5 \
  2052. --userland print_argv \
  2053. --userland-build-id static \
  2054. main \
  2055. ;
  2056. ....
  2057. ==== User mode vs full system benchmark
  2058. Let's see if user mode runs considerably faster than full system or not.
  2059. gem5 user mode:
  2060. ....
  2061. ./build-buildroot --config 'BR2_PACKAGE_DHRYSTONE=y' --arch arm
  2062. make \
  2063. -B \
  2064. -C "$(./getvar --arch arm build_dir)/dhrystone-2" \
  2065. CC="$(./run-toolchain --arch arm --dry gcc)" \
  2066. CFLAGS=-static \
  2067. ;
  2068. time \
  2069. ./run \
  2070. --arch arm \
  2071. --gem5 \
  2072. --userland \
  2073. "$(./getvar --arch arm build_dir)/dhrystone-2/dhrystone" \
  2074. -- \
  2075. --options 100000 \
  2076. ;
  2077. ....
  2078. gem5 full system:
  2079. ....
  2080. time \
  2081. ./run \
  2082. --arch arm \
  2083. --eval-busybox '/gem5.sh' \
  2084. --gem5
  2085. --gem5-readfile 'dhrystone 100000' \
  2086. ;
  2087. ....
  2088. QEMU user mode:
  2089. ....
  2090. time qemu-arm "$(./getvar --arch arm build_dir)/dhrystone-2/dhrystone" 100000000
  2091. ....
  2092. QEMU full system:
  2093. ....
  2094. time \
  2095. ./run \
  2096. --arch arm \
  2097. --eval-busybox 'time dhrystone 100000000;/poweroff.out' \
  2098. ;
  2099. ....
  2100. Result on <<p51>> at bad30f513c46c1b0995d3a10c0d9bc2a33dc4fa0:
  2101. * gem5 user: 33 seconds
  2102. * gem5 full system: 51 seconds
  2103. * QEMU user: 45 seconds
  2104. * QEMU full system: 223 seconds
  2105. == Kernel module utilities
  2106. === insmod
  2107. link:https://git.busybox.net/busybox/tree/modutils/insmod.c?h=1_29_3[Provided by BusyBox]:
  2108. ....
  2109. ./run --eval-busybox 'insmod /hello.ko'
  2110. ....
  2111. === modprobe
  2112. If you are feeling fancy, you can also insert modules with:
  2113. ....
  2114. modprobe hello
  2115. ....
  2116. which insmods link:kernel_modules/hello.c[].
  2117. `modprobe` searches for modules under:
  2118. ....
  2119. ls /lib/modules/*/extra/
  2120. ....
  2121. Kernel modules built from the Linux mainline tree with `CONFIG_SOME_MOD=m`, are automatically available with `modprobe`, e.g.:
  2122. ....
  2123. modprobe dummy-irq irq=1
  2124. ....
  2125. === myinsmod
  2126. If you are feeling raw, you can insert and remove modules with our own minimal module inserter and remover!
  2127. ....
  2128. # init_module
  2129. /myinsmod.out /hello.ko
  2130. # finit_module
  2131. /myinsmod.out /hello.ko "" 1
  2132. /myrmmod.out hello
  2133. ....
  2134. which teaches you how it is done from C code.
  2135. Source:
  2136. * link:userland/myinsmod.c[]
  2137. * link:userland/myrmmod.c[]
  2138. The Linux kernel offers two system calls for module insertion:
  2139. * `init_module`
  2140. * `finit_module`
  2141. and:
  2142. ....
  2143. man init_module
  2144. ....
  2145. documents that:
  2146. ____
  2147. 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().
  2148. ____
  2149. `finit` is newer and was added only in v3.8. More rationale: https://lwn.net/Articles/519010/
  2150. Bibliography: https://stackoverflow.com/questions/5947286/how-to-load-linux-kernel-modules-from-c-code
  2151. === kmod
  2152. https://git.kernel.org/pub/scm/utils/kernel/kmod/kmod.git
  2153. Multi-call executable that implements: `lsmod`, `insmod`, `rmmod`, and other tools on desktop distros such as Ubuntu 16.04, where e.g.:
  2154. ....
  2155. ls -l /bin/lsmod
  2156. ....
  2157. gives:
  2158. ....
  2159. lrwxrwxrwx 1 root root 4 Jul 25 15:35 /bin/lsmod -> kmod
  2160. ....
  2161. and:
  2162. ....
  2163. dpkg -l | grep -Ei
  2164. ....
  2165. contains:
  2166. ....
  2167. ii kmod 22-1ubuntu5 amd64 tools for managing Linux kernel modules
  2168. ....
  2169. BusyBox also implements its own version of those executables. There are some differences.
  2170. Buildroot also has a kmod package, but we are not using it since BusyBox' version is good enough so far.
  2171. This page will only describe features that differ from kmod to the BusyBox implementation.
  2172. ==== module-init-tools
  2173. Name of a predecessor set of tools.
  2174. ==== kmod modprobe
  2175. kmod's `modprobe` can also load modules under different names to avoid conflicts, e.g.:
  2176. ....
  2177. sudo modprobe vmhgfs -o vm_hgfs
  2178. ....
  2179. == Filesystems
  2180. === OverlayFS
  2181. link:https://en.wikipedia.org/wiki/OverlayFS[OverlayFS] is a filesystem merged in the Linux kernel in 3.18.
  2182. 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:
  2183. * https://askubuntu.com/questions/109413/how-do-i-use-overlayfs/1075564#1075564
  2184. * https://stackoverflow.com/questions/31044982/how-to-use-multiple-lower-layers-in-overlayfs/52792397#52792397
  2185. 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.
  2186. This would have several advantages:
  2187. * makes it faster to test modified guest programs
  2188. ** not rebooting is fundamental for <<gem5>>, where the reboot is very costly.
  2189. ** no need to regenerate the root filesystem at all and reboot
  2190. ** overcomes the `check_bin_arch` problem: <<rpath>>
  2191. * we could keep the base root filesystem very small, which implies:
  2192. ** less host disk usage, no need to copy the entire `out_rootfs_overlay_dir` to the image again
  2193. ** no need to worry about <<br2_target_rootfs_ext2_size>>
  2194. We can already make host files appear on the guest with <<9p>>, but they appear on a subdirectory instead of the root.
  2195. 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.
  2196. For example, we wouldn't have to mess around with variables such as `PATH` and `LD_LIBRARY_PATH`.
  2197. The idea is to:
  2198. * 9P mount our overlay directory `./getvar out_rootfs_overlay_dir` on the guest, which we already do at `/mnt/9p/out_rootfs_overlay`
  2199. * then create an overlay with that directory and the root, and `chroot` into it.
  2200. +
  2201. I was unable to mount directly to `/` avoid the `chroot`:
  2202. ** https://stackoverflow.com/questions/41119656/how-can-i-overlayfs-the-root-filesystem-on-linux
  2203. ** https://unix.stackexchange.com/questions/316018/how-to-use-overlayfs-to-protect-the-root-filesystem
  2204. ** https://unix.stackexchange.com/questions/420646/mount-root-as-overlayfs
  2205. We already have a prototype of this running from `fstab` on guest at `/mnt/overlay`, but it has the following shortcomings:
  2206. * 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]:
  2207. +
  2208. ....
  2209. Changes to the underlying filesystems while part of a mounted overlay
  2210. filesystem are not allowed. If the underlying filesystem is changed,
  2211. the behavior of the overlay is undefined, though it will not result in
  2212. a crash or deadlock.
  2213. ....
  2214. +
  2215. This makes everything very inconvenient if you are inside `chroot` action. You would have to leave `chroot`, remount, then come back.
  2216. * the overlay does not contain sub-filesystems, e.g. `/proc`. We would have to re-mount them. But should be doable with some automation.
  2217. Even more awesome than `chroot` would be to `pivot_root`, but I couldn't get that working either:
  2218. * https://stackoverflow.com/questions/28015688/pivot-root-device-or-resource-busy
  2219. * https://unix.stackexchange.com/questions/179788/pivot-root-device-or-resource-busy
  2220. === Secondary disk
  2221. A simpler and possibly less overhead alternative to <<9P>> would be to generate a secondary disk image with the benchmark you want to rebuild.
  2222. Then you can `umount` and re-mount on guest without reboot.
  2223. 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[].
  2224. 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
  2225. == Graphics
  2226. Both QEMU and gem5 are capable of outputting graphics to the screen, and taking mouse and keyboard input.
  2227. https://unix.stackexchange.com/questions/307390/what-is-the-difference-between-ttys0-ttyusb0-and-ttyama0-in-linux
  2228. === QEMU text mode
  2229. Text mode is the default mode for QEMU.
  2230. The opposite of text mode is <<qemu-graphic-mode>>
  2231. In text mode, we just show the serial console directly on the current terminal, without opening a QEMU GUI window.
  2232. You cannot see any graphics from text mode, but text operations in this mode, including:
  2233. * scrolling up: <<scroll-up-in-graphic-mode>>
  2234. * copy paste to and from the terminal
  2235. making this a good default, unless you really need to use with graphics.
  2236. Text mode works by sending the terminal character by character to a serial device.
  2237. 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.
  2238. For more details, see:
  2239. * https://unix.stackexchange.com/questions/307390/what-is-the-difference-between-ttys0-ttyusb0-and-ttyama0-in-linux
  2240. * <<tty>>
  2241. Note that you can still see an image even in text mode with the VNC:
  2242. ....
  2243. ./run --vnc
  2244. ....
  2245. and on another terminal:
  2246. ....
  2247. ./vnc
  2248. ....
  2249. but there is not terminal on the VNC window, just the <<config_logo>> penguin.
  2250. ==== Quit QEMU from text mode
  2251. https://superuser.com/questions/1087859/how-to-quit-the-qemu-monitor-when-not-using-a-gui
  2252. 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.
  2253. The simplest way to quit QEMU, is to do:
  2254. ....
  2255. Ctrl-A X
  2256. ....
  2257. Alternative methods include:
  2258. * `quit` command on the <<qemu-monitor>>
  2259. * `pkill qemu`
  2260. === QEMU graphic mode
  2261. Enable graphic mode with:
  2262. ....
  2263. ./run --graphic
  2264. ....
  2265. Outcome: you see a penguin due to <<config_logo>>.
  2266. For a more exciting GUI experience, see: <<x11>>
  2267. Text mode is the default due to the following considerable advantages:
  2268. * copy and paste commands and stdout output to / from host
  2269. * 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
  2270. * have a large scroll buffer, and be able to search it, e.g. by using tmux on host
  2271. * one less window floating around to think about in addition to your shell :-)
  2272. * graphics mode has only been properly tested on `x86_64`.
  2273. Text mode has the following limitations over graphics mode:
  2274. * you can't see graphics such as those produced by <<x11>>
  2275. * 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.
  2276. `x86_64` has a VGA device enabled by default, as can be seen as:
  2277. ....
  2278. ./qemu-monitor info qtree
  2279. ....
  2280. 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:
  2281. ....
  2282. cat /dev/urandom > /dev/fb0
  2283. ....
  2284. flooding the screen with colors. See also: https://superuser.com/questions/223094/how-do-i-know-if-i-have-kms-enabled
  2285. ==== Scroll up in graphic mode
  2286. Scroll up in <<qemu-graphic-mode>>:
  2287. ....
  2288. Shift-PgUp
  2289. ....
  2290. but I never managed to increase that buffer:
  2291. * https://askubuntu.com/questions/709697/how-to-increase-scrollback-lines-in-ubuntu14-04-2-server-edition
  2292. * https://unix.stackexchange.com/questions/346018/how-to-increase-the-scrollback-buffer-size-for-tty
  2293. The superior alternative is to use text mode and GNU screen or <<tmux>>.
  2294. ==== QEMU Graphic mode arm
  2295. ===== QEMU graphic mode arm terminal
  2296. TODO: on arm, we see the penguin and some boot messages, but don't get a shell at then end:
  2297. ....
  2298. ./run --arch aarch64 --graphic
  2299. ....
  2300. I think it does not work because the graphic window is <<drm>> only, i.e.:
  2301. ....
  2302. cat /dev/urandom > /dev/fb0
  2303. ....
  2304. fails with:
  2305. ....
  2306. cat: write error: No space left on device
  2307. ....
  2308. 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>>.
  2309. There is however one out-of-tree implementation: <<kmscon>>.
  2310. ===== QEMU graphic mode arm terminal implementation
  2311. `arm` and `aarch64` rely on the QEMU CLI option:
  2312. ....
  2313. -device virtio-gpu-pci
  2314. ....
  2315. and the kernel config options:
  2316. ....
  2317. CONFIG_DRM=y
  2318. CONFIG_DRM_VIRTIO_GPU=y
  2319. ....
  2320. Unlike x86, `arm` and `aarch64` don't have a display device attached by default, thus the need for `virtio-gpu-pci`.
  2321. See also https://wiki.qemu.org/Documentation/Platforms/ARM (recently edited and corrected by yours truly... :-)).
  2322. ===== QEMU graphic mode arm VGA
  2323. TODO: how to use VGA on ARM? https://stackoverflow.com/questions/20811203/how-can-i-output-to-vga-through-qemu-arm Tried:
  2324. ....
  2325. -device VGA
  2326. ....
  2327. But https://github.com/qemu/qemu/blob/v2.12.0/docs/config/mach-virt-graphical.cfg#L264 says:
  2328. ....
  2329. # We use virtio-gpu because the legacy VGA framebuffer is
  2330. # very troublesome on aarch64, and virtio-gpu is the only
  2331. # video device that doesn't implement it.
  2332. ....
  2333. so maybe it is not possible?
  2334. === gem5 Graphic mode
  2335. 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`.
  2336. TODO could not get it working on `x86_64`, only ARM.
  2337. Overview: https://stackoverflow.com/questions/50364863/how-to-get-graphical-gui-output-and-user-touch-keyboard-mouse-input-in-a-ful/50364864#50364864
  2338. More concretely:
  2339. ....
  2340. git -C "$(./getvar linux_src_dir)" checkout gem5/v4.15
  2341. ./build-linux \
  2342. --arch arm \
  2343. --custom-config-file "$(./getvar linux_src_dir)/arch/arm/configs/gem5_defconfig" \
  2344. --linux-build-id gem5-v4.15 \
  2345. ;
  2346. git -C "$(./getvar linux_src_dir)" checkout -
  2347. ./run --arch arm --gem5 --linux-build-id gem5-v4.15
  2348. ....
  2349. and then on another shell:
  2350. ....
  2351. vinagre localhost:5900
  2352. ....
  2353. The <<config_logo>> penguin only appears after several seconds, together with kernel messages of type:
  2354. ....
  2355. [ 0.152755] [drm] found ARM HDLCD version r0p0
  2356. [ 0.152790] hdlcd 2b000000.hdlcd: bound virt-encoder (ops 0x80935f94)
  2357. [ 0.152795] [drm] Supports vblank timestamp caching Rev 2 (21.10.2013).
  2358. [ 0.152799] [drm] No driver support for vblank timestamp query.
  2359. [ 0.215179] Console: switching to colour frame buffer device 240x67
  2360. [ 0.230389] hdlcd 2b000000.hdlcd: fb0: frame buffer device
  2361. [ 0.230509] [drm] Initialized hdlcd 1.0.0 20151021 for 2b000000.hdlcd on minor 0
  2362. ....
  2363. 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:
  2364. ....
  2365. system.vncserver: Listening for connections on port 5900
  2366. ....
  2367. and when we connect it shows a message:
  2368. ....
  2369. info: VNC client attached
  2370. ....
  2371. Alternatively, you can also view the frames with `--frame-capture`:
  2372. ....
  2373. ./run \
  2374. --arch arm \
  2375. --gem5 \
  2376. --linux-build-id gem5-v4.15 \
  2377. -- --frame-capture \
  2378. ;
  2379. ....
  2380. This option dumps one compressed PNG whenever the screen image changes inside `m5out`, indexed by the cycle ID. This allows for more controlled experiments.
  2381. It is fun to see how we get one new frame whenever the white underscore cursor appears and reappears under the penguin.
  2382. TODO <<kmscube>> failed on `aarch64` with:
  2383. ....
  2384. kmscube[706]: unhandled level 2 translation fault (11) at 0x00000000, esr 0x92000006, in libgbm.so.1.0.0[7fbf6a6000+e000]
  2385. ....
  2386. Tested on: link:http://github.com/cirosantilli/linux-kernel-module-cheat/commit/38fd6153d965ba20145f53dc1bb3ba34b336bde9[38fd6153d965ba20145f53dc1bb3ba34b336bde9]
  2387. ==== Graphic mode gem5 aarch64
  2388. For `aarch64` we also need to configure the kernel with link:linux_config/display[]:
  2389. ....
  2390. git -C "$(./getvar linux_src_dir)" checkout gem5/v4.15
  2391. ./build-linux \
  2392. --arch aarch64 \
  2393. --config-fragment linux_config/display \
  2394. --custom-config-file "$(./getvar linux_src_dir)/arch/arm64/configs/gem5_defconfig" \
  2395. --linux-build-id gem5-v4.15 \
  2396. ;
  2397. git -C "$(./getvar linux_src_dir)" checkout -
  2398. ./run --arch aarch64 --gem5 --linux-build-id gem5-v4.15
  2399. ....
  2400. This is because the gem5 `aarch64` defconfig does not enable HDLCD like the 32 bit one `arm` one for some reason.
  2401. ==== Graphic mode gem5 internals
  2402. We cannot use mainline Linux because the <<gem5-arm-linux-kernel-patches>> are required at least to provide the `CONFIG_DRM_VIRT_ENCODER` option.
  2403. 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`.
  2404. The kernel uses HDLCD to implement the <<drm>> interface, the required kernel config options are present at: link:linux_config/display[].
  2405. TODO: minimize out the `--custom-config-file`. If we just remove it on `arm`: it does not work with a failing dmesg:
  2406. ....
  2407. [ 0.066208] [drm] found ARM HDLCD version r0p0
  2408. [ 0.066241] hdlcd 2b000000.hdlcd: bound virt-encoder (ops drm_vencoder_ops)
  2409. [ 0.066247] [drm] Supports vblank timestamp caching Rev 2 (21.10.2013).
  2410. [ 0.066252] [drm] No driver support for vblank timestamp query.
  2411. [ 0.066276] hdlcd 2b000000.hdlcd: Cannot do DMA to address 0x0000000000000000
  2412. [ 0.066281] swiotlb: coherent allocation failed for device 2b000000.hdlcd size=8294400
  2413. [ 0.066288] CPU: 0 PID: 1 Comm: swapper/0 Not tainted 4.15.0 #1
  2414. [ 0.066293] Hardware name: V2P-AARCH64 (DT)
  2415. [ 0.066296] Call trace:
  2416. [ 0.066301] dump_backtrace+0x0/0x1b0
  2417. [ 0.066306] show_stack+0x24/0x30
  2418. [ 0.066311] dump_stack+0xb8/0xf0
  2419. [ 0.066316] swiotlb_alloc_coherent+0x17c/0x190
  2420. [ 0.066321] __dma_alloc+0x68/0x160
  2421. [ 0.066325] drm_gem_cma_create+0x98/0x120
  2422. [ 0.066330] drm_fbdev_cma_create+0x74/0x2e0
  2423. [ 0.066335] __drm_fb_helper_initial_config_and_unlock+0x1d8/0x3a0
  2424. [ 0.066341] drm_fb_helper_initial_config+0x4c/0x58
  2425. [ 0.066347] drm_fbdev_cma_init_with_funcs+0x98/0x148
  2426. [ 0.066352] drm_fbdev_cma_init+0x40/0x50
  2427. [ 0.066357] hdlcd_drm_bind+0x220/0x428
  2428. [ 0.066362] try_to_bring_up_master+0x21c/0x2b8
  2429. [ 0.066367] component_master_add_with_match+0xa8/0xf0
  2430. [ 0.066372] hdlcd_probe+0x60/0x78
  2431. [ 0.066377] platform_drv_probe+0x60/0xc8
  2432. [ 0.066382] driver_probe_device+0x30c/0x478
  2433. [ 0.066388] __driver_attach+0x10c/0x128
  2434. [ 0.066393] bus_for_each_dev+0x70/0xb0
  2435. [ 0.066398] driver_attach+0x30/0x40
  2436. [ 0.066402] bus_add_driver+0x1d0/0x298
  2437. [ 0.066408] driver_register+0x68/0x100
  2438. [ 0.066413] __platform_driver_register+0x54/0x60
  2439. [ 0.066418] hdlcd_platform_driver_init+0x20/0x28
  2440. [ 0.066424] do_one_initcall+0x44/0x130
  2441. [ 0.066428] kernel_init_freeable+0x13c/0x1d8
  2442. [ 0.066433] kernel_init+0x18/0x108
  2443. [ 0.066438] ret_from_fork+0x10/0x1c
  2444. [ 0.066444] hdlcd 2b000000.hdlcd: Failed to set initial hw configuration.
  2445. [ 0.066470] hdlcd 2b000000.hdlcd: master bind failed: -12
  2446. [ 0.066477] hdlcd: probe of 2b000000.hdlcd failed with error -12
  2447. [
  2448. ....
  2449. So what other options are missing from `gem5_defconfig`? It would be cool to minimize it out to better understand the options.
  2450. [[x11]]
  2451. === X11 Buildroot
  2452. Once you've seen the `CONFIG_LOGO` penguin as a sanity check, you can try to go for a cooler X11 Buildroot setup.
  2453. Build and run:
  2454. ....
  2455. ./build-buildroot --config-fragment buildroot_config/x11
  2456. ./run --graphic
  2457. ....
  2458. Inside QEMU:
  2459. ....
  2460. startx
  2461. ....
  2462. And then from the GUI you can start exciting graphical programs such as:
  2463. ....
  2464. xcalc
  2465. xeyes
  2466. ....
  2467. Outcome:
  2468. image:x11.png[image]
  2469. 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.
  2470. More details: https://unix.stackexchange.com/questions/70931/how-to-install-x11-on-my-own-linux-buildroot-system/306116#306116
  2471. 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.
  2472. To x11 packages have an `xserver` prefix as in:
  2473. ....
  2474. ./build-buildroot --config-fragment buildroot_config/x11 -- xserver_xorg-server-reconfigure
  2475. ....
  2476. the easiest way to find them out is to just list `"$(./getvar build_dir)/x*`.
  2477. TODO as of: c2696c978d6ca88e8b8599c92b1beeda80eb62b2 I noticed that `startx` leads to a <<bug_on>>:
  2478. ....
  2479. [ 2.809104] WARNING: CPU: 0 PID: 51 at drivers/gpu/drm/ttm/ttm_bo_vm.c:304 ttm_bo_vm_open+0x37/0x40
  2480. ....
  2481. ==== X11 Buildroot mouse not moving
  2482. 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.
  2483. * https://askubuntu.com/questions/730891/how-can-i-get-a-mouse-cursor-in-qemu
  2484. * https://stackoverflow.com/questions/19665412/mouse-and-keyboard-not-working-in-qemu-emulator
  2485. `-show-cursor` did not help, I just get to see the host cursor, but the guest cursor still does not move.
  2486. Doing:
  2487. ....
  2488. watch -n 1 grep i8042 /proc/interrupts
  2489. ....
  2490. shows that interrupts do happen when mouse and keyboard presses are done, so I expect that it is some wrong either with:
  2491. * QEMU. Same behaviour if I try the host's QEMU 2.10.1 however.
  2492. * X11 configuration. We do have `BR2_PACKAGE_XDRIVER_XF86_INPUT_MOUSE=y`.
  2493. `/var/log/Xorg.0.log` contains the following interesting lines:
  2494. ....
  2495. [ 27.549] (II) LoadModule: "mouse"
  2496. [ 27.549] (II) Loading /usr/lib/xorg/modules/input/mouse_drv.so
  2497. [ 27.590] (EE) <default pointer>: Cannot find which device to use.
  2498. [ 27.590] (EE) <default pointer>: cannot open input device
  2499. [ 27.590] (EE) PreInit returned 2 for "<default pointer>"
  2500. [ 27.590] (II) UnloadModule: "mouse"
  2501. ....
  2502. The file `/dev/inputs/mice` does not exist.
  2503. Note that our current link:kernel_confi_fragment sets:
  2504. ....
  2505. # CONFIG_INPUT_MOUSE is not set
  2506. # CONFIG_INPUT_MOUSEDEV_PSAUX is not set
  2507. ....
  2508. for gem5, so you might want to remove those lines to debug this.
  2509. ==== X11 Buildroot ARM
  2510. On ARM, `startx` hangs at a message:
  2511. ....
  2512. vgaarb: this pci device is not a vga device
  2513. ....
  2514. and nothing shows on the screen, and:
  2515. ....
  2516. grep EE /var/log/Xorg.0.log
  2517. ....
  2518. says:
  2519. ....
  2520. (EE) Failed to load module "modesetting" (module does not exist, 0)
  2521. ....
  2522. A friend told me this but I haven't tried it yet:
  2523. * `xf86-video-modesetting` is likely the missing ingredient, but it does not seem possible to activate it from Buildroot currently without patching things.
  2524. * `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`
  2525. == Networking
  2526. === Enable networking
  2527. 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>>
  2528. To enable networking on Buildroot, simply run:
  2529. ....
  2530. ifup -a
  2531. ....
  2532. That command goes over all (`-a`) the interfaces in `/etc/network/interfaces` and brings them up.
  2533. Then test it with:
  2534. ....
  2535. wget google.com
  2536. cat index.html
  2537. ....
  2538. Disable networking with:
  2539. ....
  2540. ifdown -a
  2541. ....
  2542. To enable networking by default after boot, use the methods documented at <<init-busybox>>.
  2543. === ping
  2544. `ping` does not work within QEMU by default, e.g.:
  2545. ....
  2546. ping google.com
  2547. ....
  2548. hangs after printing the header:
  2549. ....
  2550. PING google.com (216.58.204.46): 56 data bytes
  2551. ....
  2552. https://unix.stackexchange.com/questions/473448/how-to-ping-from-the-qemu-guest-to-an-external-url
  2553. === Guest host networking
  2554. In this section we discuss how to interact between the guest and the host through networking.
  2555. First ensure that you can access the external network since that is easier to get working: <<networking>>.
  2556. ==== Host to guest networking
  2557. ===== nc host to guest
  2558. With `nc` we can create the most minimal example possible as a sanity check.
  2559. On guest run:
  2560. ....
  2561. nc -l -p 45455
  2562. ....
  2563. Then on host run:
  2564. ....
  2565. echo asdf | nc localhost 45455
  2566. ....
  2567. `asdf` appears on the guest.
  2568. This uses:
  2569. * BusyBox' `nc` utility, which is enabled with `CONFIG_NC=y`
  2570. * `nc` from the `netcat-openbsd` package on an Ubuntu 18.04 host
  2571. Only this specific port works by default since we have forwarded it on the QEMU command line.
  2572. We us this exact procedure to connect to <<gdbserver>>.
  2573. ===== ssh into guest
  2574. Not enabled by default due to the build / runtime overhead. To enable, build with:
  2575. ....
  2576. ./build-buildroot --config 'BR2_PACKAGE_OPENSSH=y'
  2577. ....
  2578. Then inside the guest turn on sshd:
  2579. ....
  2580. /sshd.sh
  2581. ....
  2582. Source: link:rootfs_overlay/sshd.sh[]
  2583. And finally on host:
  2584. ....
  2585. ssh root@localhost -p 45456
  2586. ....
  2587. Bibliography: https://unix.stackexchange.com/questions/124681/how-to-ssh-from-host-to-guest-using-qemu/307557#307557
  2588. ===== gem5 host to guest networking
  2589. 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
  2590. ==== Guest to host networking
  2591. TODO I never got this to work.
  2592. There is `guestfwd`, which sounds analogous to `hostwfd` used in the other sense, but I was not able to get it working, e.g.:
  2593. ....
  2594. -netdev user,hostfwd=tcp::45455-:45455,guestfwd=tcp::45456-,id=net0 \
  2595. ....
  2596. gives:
  2597. ....
  2598. Could not open guest forwarding device 'guestfwd.tcp.45456'
  2599. ....
  2600. Bibliography: https://serverfault.com/questions/769874/how-to-forward-a-port-from-guest-to-host-in-qemu-kvm
  2601. === 9P
  2602. The link:https://en.wikipedia.org/wiki/9P_(protocol)[9p protocol] allows the guest to mount a host directory.
  2603. Both QEMU and <<9p-gem5>> support 9P.
  2604. ==== 9P vs NFS
  2605. All of 9P and NFS (and sshfs) allow sharing directories between guest and host.
  2606. Advantages of 9P
  2607. * we haven't managed to do <<guest-to-host-networking>>, which prevents us from mounting a host directory on the guest
  2608. +
  2609. Furthermore, this would require `sudo` on the host to mount
  2610. * 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>>
  2611. +
  2612. 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.
  2613. * 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.
  2614. +
  2615. 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.
  2616. Advantages of NFS:
  2617. * way more widely used and therefore stable and available, not to mention that it also works on real hardware.
  2618. * 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!
  2619. ==== 9P getting started
  2620. As usual, we have already set everything up for you. On host:
  2621. ....
  2622. cd "$(./getvar p9_dir)"
  2623. uname -a > host
  2624. ....
  2625. Guest:
  2626. ....
  2627. cd /mnt/9p/data
  2628. cat host
  2629. uname -a > guest
  2630. ....
  2631. Host:
  2632. ....
  2633. cat guest
  2634. ....
  2635. The main ingredients for this are:
  2636. * `9P` settings in our <<kernel-configs-about,kernel configs>>
  2637. * `9p` entry on our link:rootfs_overlay/etc/fstab[]
  2638. +
  2639. Alternatively, you could also mount your own with:
  2640. +
  2641. ....
  2642. mkdir /mnt/my9p
  2643. mount -t 9p -o trans=virtio,version=9p2000.L host0 /mnt/my9p
  2644. ....
  2645. * Launch QEMU with `-virtfs` as in your link:run[] script
  2646. +
  2647. When we tried:
  2648. +
  2649. ....
  2650. security_model=mapped
  2651. ....
  2652. +
  2653. writes from guest failed due to user mismatch problems: https://serverfault.com/questions/342801/read-write-access-for-passthrough-9p-filesystems-with-libvirt-qemu
  2654. Bibliography:
  2655. * https://superuser.com/questions/628169/how-to-share-a-directory-with-the-host-without-networking-in-qemu
  2656. * https://wiki.qemu.org/Documentation/9psetup
  2657. ==== 9P gem5
  2658. TODO seems possible! Lets do it:
  2659. * http://gem5.org/wiki/images/b/b8/Summit2017_wa_devlib.pdf
  2660. * http://gem5.org/WA-gem5
  2661. == Linux kernel
  2662. === Linux kernel configuration
  2663. ==== Modify kernel config
  2664. By default, we use a `.config` that is a mixture of:
  2665. * Buildroot's minimal per machine `.config`, which has the minimal options needed to boot
  2666. * our <<kernel-configs-about,kernel configs>> which enables options we want to play with
  2667. To modify a single option on top of our defaults, do:
  2668. ....
  2669. ./build-linux --config 'CONFIG_FORTIFY_SOURCE=y'
  2670. ....
  2671. 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:
  2672. ....
  2673. ./build-modules --clean
  2674. ./build-modules
  2675. ....
  2676. and then proceed as in <<your-first-kernel-module-hack>>.
  2677. You might often get way without rebuilding the kernel modules however.
  2678. To use an extra kernel config fragment file on top of our defaults, do:
  2679. ....
  2680. printf '
  2681. CONFIG_IKCONFIG=y
  2682. CONFIG_IKCONFIG_PROC=y
  2683. ' > data/myconfig
  2684. ./build-buildroot --config-fragment 'data/myconfig'
  2685. ....
  2686. To use just your own exact `.config` instead of our defaults ones, use:
  2687. ....
  2688. ./build-linux --custom-config-file data/myconfig
  2689. ....
  2690. The following options can all be used together, sorted by decreasing config setting power precedence:
  2691. * `--config`
  2692. * `--config-fragment`
  2693. * `--custom-config-file`
  2694. ==== Find the kernel config
  2695. Ge the build config in guest:
  2696. ....
  2697. zcat /proc/config.gz
  2698. ....
  2699. or with our shortcut:
  2700. ....
  2701. /conf.sh
  2702. ....
  2703. or to conveniently grep for a specific option case insensitively:
  2704. ....
  2705. /conf.sh ikconfig
  2706. ....
  2707. Source: link:rootfs_overlay/conf.sh[].
  2708. This is enabled by:
  2709. ....
  2710. CONFIG_IKCONFIG=y
  2711. CONFIG_IKCONFIG_PROC=y
  2712. ....
  2713. From host:
  2714. ....
  2715. cat "$(./getvar linux_build_dir)/.config"
  2716. ....
  2717. Just for fun link:https://stackoverflow.com/a/14958263/895245[]:
  2718. ....
  2719. ./linux/scripts/extract-ikconfig "$(./getvar vmlinux)"
  2720. ....
  2721. although this can be useful when someone gives you a random image.
  2722. [[kernel-configs-about]]
  2723. ==== About our Linux kernel configs
  2724. TODO: explain link:update-buildroot-kernel-config[]
  2725. TODO: mention `--dry-run`
  2726. TODO Beware that Buildroot can `sed` override some of the configurations we make no matter what, e.g. it forces `CONFIG_BLK_DEV_INITRD=y` when `BR2_TARGET_ROOTFS_CPIO` is on, so you might want to double check as explained at <<find-the-kernel-config>>. TODO check if there is a way to prevent that patching and maybe patch Buildroot for it, it is too fuzzy. People should be able to just build with whatever `.config` they want.
  2727. We have managed to come up with minimalistic kernel configs that work for both QEMU and gem5 (oh, the hours of bisection).
  2728. Our configs are all based on Buildroot's configs, which were designed for QEMU, and then on top of those we also add:
  2729. * link:linux_config/min[]: minimal tweaks required to boot gem5 or for using our slightly different QEMU command line options than Buildroot
  2730. * link:linux_config/default[]: optional configs that we add by default to our kernel build because they increase visibility, and don't significantly increase build time nor add significant runtime overhead
  2731. Changes to those files automatically trigger kernel reconfigures even without using the linux-reconfigure target, since timestamps are used to decide if changes happened or not.
  2732. Having the same config working for both QEMU and gem5 means that you can deal with functional matters in QEMU, which runs much faster, and switch to gem5 only for performance issues.
  2733. To see Buildroot's base configs, have a look at `buildroot/configs/qemu_x86_64_defconfig`, which our `./build` script uses.
  2734. That file contains `BR2_LINUX_KERNEL_CUSTOM_CONFIG_FILE="board/qemu/x86_64/linux-4.11.config"`, which points to the base config file used.
  2735. `arm`, on the other hand, uses `buildroot/configs/qemu_arm_vexpress_defconfig`, which contains `BR2_LINUX_KERNEL_DEFCONFIG="vexpress"`, and therefore just does a `make vexpress_defconfig`.
  2736. Other configs which we had previously tested at 4e0d9af81fcce2ce4e777cb82a1990d7c2ca7c1e are:
  2737. * 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`
  2738. * `arm` and `aarch64` configs present in the official ARM gem5 Linux kernel fork: https://gem5.googlesource.com/arm/linux, e.g. for arm v4.9: link:https://gem5.googlesource.com/arm/linux/+/917e007a4150d26a0aa95e4f5353ba72753669c7/arch/arm/configs/gem5_defconfig[]. The patches there are just simple optimizations and instrumentation, but they are not needed to boot.
  2739. On one hand, we would like to have our configs as a single git file tracked on this repo, to be able to easily refer people ot them. However, that would lose use the ability to:
  2740. * reuse Buildroot's configs
  2741. * split our configs into `min` and `default`
  2742. === Kernel version
  2743. ==== Find the kernel version
  2744. We try to use the latest possible kernel major release version.
  2745. In QEMU:
  2746. ....
  2747. cat /proc/version
  2748. ....
  2749. or in the source:
  2750. ....
  2751. cd "$(./getvar linux_src_dir)"
  2752. git log | grep -E ' Linux [0-9]+\.' | head
  2753. ....
  2754. ==== Update the Linux kernel
  2755. During update all you kernel modules may break since the kernel API is not stable.
  2756. They are usually trivial breaks of things moving around headers or to sub-structs.
  2757. The userland, however, should simply not break, as Linus enforces strict backwards compatibility of userland interfaces.
  2758. This backwards compatibility is just awesome, it makes getting and running the latest master painless.
  2759. This also makes this repo the perfect setup to develop the Linux kernel.
  2760. In case something breaks while updating the Linux kernel, you can try to bisect it to understand the root cause: <<bisection>>.
  2761. ==== Downgrade the Linux kernel
  2762. 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.
  2763. The default Linux kernel version is bumped in Buildroot with commit messages of type:
  2764. ....
  2765. linux: bump default to version 4.9.6
  2766. ....
  2767. So you can try:
  2768. ....
  2769. git log --grep 'linux: bump default to version'
  2770. ....
  2771. Those commits change `BR2_LINUX_KERNEL_LATEST_VERSION` in `/linux/Config.in`.
  2772. 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.
  2773. === Kernel command line parameters
  2774. 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.
  2775. This allows us to control the behaviour of the kernel without rebuilding anything.
  2776. With QEMU, QEMU itself acts as the bootloader, and provides the `-append` option and we expose it through `./run --kernel-cli`, e.g.:
  2777. ....
  2778. ./run --kernel-cli 'foo bar'
  2779. ....
  2780. Then inside the host, you can check which options were given with:
  2781. ....
  2782. cat /proc/cmdline
  2783. ....
  2784. They are also printed at the beginning of the boot message:
  2785. ....
  2786. dmesg | grep "Command line"
  2787. ....
  2788. See also:
  2789. * https://unix.stackexchange.com/questions/48601/how-to-display-the-linux-kernel-command-line-parameters-given-for-the-current-bo
  2790. * https://askubuntu.com/questions/32654/how-do-i-find-the-boot-parameters-used-by-the-running-kernel
  2791. The arguments are documented in the kernel documentation: https://www.kernel.org/doc/html/v4.14/admin-guide/kernel-parameters.html
  2792. When dealing with real boards, extra command line options are provided on some magic bootloader configuration file, e.g.:
  2793. * GRUB configuration files: https://askubuntu.com/questions/19486/how-do-i-add-a-kernel-boot-parameter
  2794. * 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
  2795. ==== Kernel command line parameters escaping
  2796. 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"`
  2797. This even lead us to use base64 encoding with `--eval`!
  2798. ==== Kernel command line parameters definition points
  2799. There are two methods:
  2800. * `__setup` as in:
  2801. +
  2802. ....
  2803. __setup("console=", console_setup);
  2804. ....
  2805. * `core_param` as in:
  2806. +
  2807. ....
  2808. core_param(panic, panic_timeout, int, 0644);
  2809. ....
  2810. `core_param` suggests how they are different:
  2811. ....
  2812. /**
  2813. * core_param - define a historical core kernel parameter.
  2814. ...
  2815. * core_param is just like module_param(), but cannot be modular and
  2816. * doesn't add a prefix (such as "printk."). This is for compatibility
  2817. * with __setup(), and it makes sense as truly core parameters aren't
  2818. * tied to the particular file they're in.
  2819. */
  2820. ....
  2821. ==== rw
  2822. By default, the Linux kernel mounts the root filesystem as readonly. TODO rationale?
  2823. This cannot be observed in the default BusyBox init, because by default our link:rootfs_overlay/etc/inittab[] does:
  2824. ....
  2825. /bin/mount -o remount,rw /
  2826. ....
  2827. Analogously, Ubuntu 18.04 does in its fstab something like:
  2828. ....
  2829. UUID=/dev/sda1 / ext4 errors=remount-ro 0 1
  2830. ....
  2831. which uses default mount `rw` flags.
  2832. 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.
  2833. To observe the default readonly behaviour, hack the link:run[] script to remove <<replace-init,replace init>>, and then run on a raw shell:
  2834. ....
  2835. ./run --kernel-cli 'init=/bin/sh'
  2836. ....
  2837. Now try to do:
  2838. ....
  2839. touch a
  2840. ....
  2841. which fails with:
  2842. ....
  2843. touch: a: Read-only file system
  2844. ....
  2845. We can also observe the read-onlyness with:
  2846. ....
  2847. mount -t proc /proc
  2848. mount
  2849. ....
  2850. which contains:
  2851. ....
  2852. /dev/root on / type ext2 (ro,relatime,block_validity,barrier,user_xattr)
  2853. ....
  2854. and so it is Read Only as shown by `ro`.
  2855. ==== norandmaps
  2856. Disable userland address space randomization. Test it out by running <<rand_check-out>> twice:
  2857. ....
  2858. ./run --eval-busybox '/rand_check.out;/poweroff.out'
  2859. ./run --eval-busybox '/rand_check.out;/poweroff.out'
  2860. ....
  2861. If we remove it from our link:run[] script by hacking it up, the addresses shown by `rand_check.out` vary across boots.
  2862. Equivalent to:
  2863. ....
  2864. echo 0 > /proc/sys/kernel/randomize_va_space
  2865. ....
  2866. === printk
  2867. `printk` is the most simple and widely used way of getting information from the kernel, so you should familiarize yourself with its basic configuration.
  2868. We use `printk` a lot in our kernel modules, and it shows on the terminal by default, along with stdout and what you type.
  2869. Hide all `printk` messages:
  2870. ....
  2871. dmesg -n 1
  2872. ....
  2873. or equivalently:
  2874. ....
  2875. echo 1 > /proc/sys/kernel/printk
  2876. ....
  2877. See also: https://superuser.com/questions/351387/how-to-stop-kernel-messages-from-flooding-my-console
  2878. Do it with a <<kernel-command-line-parameters>> to affect the boot itself:
  2879. ....
  2880. ./run --kernel-cli 'loglevel=5'
  2881. ....
  2882. and now only boot warning messages or worse show, which is useful to identify problems.
  2883. Our default `printk` format is:
  2884. ....
  2885. <LEVEL>[TIMESTAMP] MESSAGE
  2886. ....
  2887. e.g.:
  2888. ....
  2889. <6>[ 2.979121] Freeing unused kernel memory: 2024K
  2890. ....
  2891. where:
  2892. * `LEVEL`: higher means less serious
  2893. * `TIMESTAMP`: seconds since boot
  2894. This format is selected by the following boot options:
  2895. * `console_msg_format=syslog`: add the `<LEVEL>` part. Added in v4.16.
  2896. * `printk.time=y`: add the `[TIMESTAMP]` part
  2897. The debug highest level is a bit more magic, see: <<pr_debug>> for more info.
  2898. ==== ignore_loglevel
  2899. ....
  2900. ./run --kernel-cli 'ignore_loglevel'
  2901. ....
  2902. enables all log levels, and is basically the same as:
  2903. ....
  2904. ./run --kernel-cli 'loglevel=8'
  2905. ....
  2906. except that you don't need to know what is the maximum level.
  2907. ==== pr_debug
  2908. https://stackoverflow.com/questions/28936199/why-is-pr-debug-of-the-linux-kernel-not-giving-any-output/49835405#49835405
  2909. Debug messages are not printable by default without recompiling.
  2910. But the awesome `CONFIG_DYNAMIC_DEBUG=y` option which we enable by default allows us to do:
  2911. ....
  2912. echo 8 > /proc/sys/kernel/printk
  2913. echo 'file kernel/module.c +p' > /sys/kernel/debug/dynamic_debug/control
  2914. /myinsmod.out /hello.ko
  2915. ....
  2916. and we have a shortcut at:
  2917. ....
  2918. /pr_debug.sh
  2919. ....
  2920. Source: link:rootfs_overlay/pr_debug.sh[].
  2921. Syntax: https://www.kernel.org/doc/html/v4.11/admin-guide/dynamic-debug-howto.html
  2922. Wildcards are also accepted, e.g. enable all messages from all files:
  2923. ....
  2924. echo 'file * +p' > /sys/kernel/debug/dynamic_debug/control
  2925. ....
  2926. TODO: why is this not working:
  2927. ....
  2928. echo 'func sys_init_module +p' > /sys/kernel/debug/dynamic_debug/control
  2929. ....
  2930. Enable messages in specific modules:
  2931. ....
  2932. echo 8 > /proc/sys/kernel/printk
  2933. echo 'module myprintk +p' > /sys/kernel/debug/dynamic_debug/control
  2934. insmod /myprintk.ko
  2935. ....
  2936. Source: link:kernel_modules/myprintk.c[]
  2937. This outputs the `pr_debug` message:
  2938. ....
  2939. printk debug
  2940. ....
  2941. but TODO: it also shows debug messages even without enabling them explicitly:
  2942. ....
  2943. echo 8 > /proc/sys/kernel/printk
  2944. insmod /myprintk.ko
  2945. ....
  2946. and it shows as enabled:
  2947. ....
  2948. # grep myprintk /sys/kernel/debug/dynamic_debug/control
  2949. /linux-kernel-module-cheat/out/x86_64/buildroot/build/kernel_modules-1.0/./myprintk.c:12 [myprintk]myinit =p "pr_debug\012"
  2950. ....
  2951. Enable `pr_debug` for boot messages as well, before we can reach userland and write to `/proc`:
  2952. ....
  2953. ./run --kernel-cli 'dyndbg="file * +p" loglevel=8'
  2954. ....
  2955. Get ready for the noisiest boot ever, I think it overflows the `printk` buffer and funny things happen.
  2956. ===== pr_debug != printk(KERN_DEBUG
  2957. 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:
  2958. ....
  2959. ./run --kernel-cli 'initcall_debug logleve=8'
  2960. ....
  2961. which outputs lines of type:
  2962. ....
  2963. <7>[ 1.756680] calling clk_disable_unused+0x0/0x130 @ 1
  2964. <7>[ 1.757003] initcall clk_disable_unused+0x0/0x130 returned 0 after 111 usecs
  2965. ....
  2966. which are `printk(KERN_DEBUG` inside `init/main.c` in v4.16.
  2967. Mentioned at: https://stackoverflow.com/questions/37272109/how-to-get-details-of-all-modules-drivers-got-initialized-probed-during-kernel-b
  2968. This likely comes from the ifdef split at `init/main.c`:
  2969. ....
  2970. /* If you are writing a driver, please use dev_dbg instead */
  2971. #if defined(CONFIG_DYNAMIC_DEBUG)
  2972. #include <linux/dynamic_debug.h>
  2973. /* dynamic_pr_debug() uses pr_fmt() internally so we don't need it here */
  2974. #define pr_debug(fmt, ...) \
  2975. dynamic_pr_debug(fmt, ##__VA_ARGS__)
  2976. #elif defined(DEBUG)
  2977. #define pr_debug(fmt, ...) \
  2978. printk(KERN_DEBUG pr_fmt(fmt), ##__VA_ARGS__)
  2979. #else
  2980. #define pr_debug(fmt, ...) \
  2981. no_printk(KERN_DEBUG pr_fmt(fmt), ##__VA_ARGS__)
  2982. #endif
  2983. ....
  2984. === Linux kernel entry point
  2985. `start_kernel` is a good definition of it: https://stackoverflow.com/questions/18266063/does-kernel-have-main-function/33422401#33422401
  2986. === Kernel module APIs
  2987. ==== Kernel module parameters
  2988. The Linux kernel allows passing module parameters at insertion time <<myinsmod,through the `init_module` and `finit_module` system calls>>:
  2989. ....
  2990. /params.sh
  2991. echo $?
  2992. ....
  2993. Outcome: the test passes:
  2994. ....
  2995. 0
  2996. ....
  2997. Sources:
  2998. * link:kernel_modules/params.c[]
  2999. * link:rootfs_overlay/params.sh[]
  3000. As shown in the example, module parameters can also be read and modified at runtime from <<sysfs>>.
  3001. We can obtain the help text of the parameters with:
  3002. ....
  3003. modinfo /params.ko
  3004. ....
  3005. The output contains:
  3006. ....
  3007. parm: j:my second favorite int
  3008. parm: i:my favorite int
  3009. ....
  3010. ===== modprobe.conf
  3011. <<modprobe>> insertion can also set default parameters via the link:rootfs_overlay/etc/modprobe.conf[`/etc/modprobe.conf`] file:
  3012. ....
  3013. modprobe params
  3014. cat /sys/kernel/debug/lkmc_params
  3015. ....
  3016. Output:
  3017. ....
  3018. 12 34
  3019. ....
  3020. This is specially important when loading modules with <<kernel-module-dependencies>> or else we would have no opportunity of passing those.
  3021. `modprobe.conf` doesn't actually insmod anything for us: https://superuser.com/questions/397842/automatically-load-kernel-module-at-boot-angstrom/1267464#1267464
  3022. ==== Kernel module dependencies
  3023. One module can depend on symbols of another module that are exported with `EXPORT_SYMBOL`:
  3024. ....
  3025. /dep.sh
  3026. echo $?
  3027. ....
  3028. Outcome: the test passes:
  3029. ....
  3030. 0
  3031. ....
  3032. Sources:
  3033. * link:kernel_modules/dep.c[]
  3034. * link:kernel_modules/dep2.c[]
  3035. * link:rootfs_overlay/dep.sh[]
  3036. The kernel deduces dependencies based on the `EXPORT_SYMBOL` that each module uses.
  3037. Symbols exported by `EXPORT_SYMBOL` can be seen with:
  3038. ....
  3039. insmod /dep.ko
  3040. grep lkmc_dep /proc/kallsyms
  3041. ....
  3042. sample output:
  3043. ....
  3044. ffffffffc0001030 r __ksymtab_lkmc_dep [dep]
  3045. ffffffffc000104d r __kstrtab_lkmc_dep [dep]
  3046. ffffffffc0002300 B lkmc_dep [dep]
  3047. ....
  3048. This requires `CONFIG_KALLSYMS_ALL=y`.
  3049. Dependency information is stored by the kernel module build system in the `.ko` files' <<modinfo>>, e.g.:
  3050. ....
  3051. modinfo /dep2.ko
  3052. ....
  3053. contains:
  3054. ....
  3055. depends: dep
  3056. ....
  3057. We can double check with:
  3058. ....
  3059. strings 3 /dep2.ko | grep -E 'depends'
  3060. ....
  3061. The output contains:
  3062. ....
  3063. depends=dep
  3064. ....
  3065. Module dependencies are also stored at:
  3066. ....
  3067. cd /lib/module/*
  3068. grep dep modules.dep
  3069. ....
  3070. Output:
  3071. ....
  3072. extra/dep2.ko: extra/dep.ko
  3073. extra/dep.ko:
  3074. ....
  3075. TODO: what for, and at which point point does Buildroot / BusyBox generate that file?
  3076. ===== Kernel module dependencies with modprobe
  3077. Unlike `insmod`, `modprobe` deals with kernel module dependencies for us:
  3078. ....
  3079. modprobe dep2
  3080. ....
  3081. Removal also removes required modules that have zero usage count:
  3082. ....
  3083. modprobe -r dep2
  3084. ....
  3085. Bibliography:
  3086. * https://askubuntu.com/questions/20070/whats-the-difference-between-insmod-and-modprobe
  3087. * https://stackoverflow.com/questions/22891705/whats-the-difference-between-insmod-and-modprobe
  3088. `modprobe` seems to use information contained in the kernel module itself for the dependencies since `modprobe dep2` still works even if we modify `modules.dep` to remove the dependency.
  3089. ==== modinfo
  3090. Module metadata is stored on module files at compile time. Some of the fields can be retrieved through the `THIS_MODULE` `struct module`:
  3091. ....
  3092. insmod /module_info.ko
  3093. ....
  3094. Dmesg output:
  3095. ....
  3096. name = module_info
  3097. version = 1.0
  3098. ....
  3099. Source: link:kernel_modules/module_info.c[]
  3100. Some of those are also present on sysfs:
  3101. ....
  3102. cat /sys/module/module_info/version
  3103. ....
  3104. Output:
  3105. ....
  3106. 1.0
  3107. ....
  3108. And we can also observe them with the `modinfo` command line utility:
  3109. ....
  3110. modinfo /module_info.ko
  3111. ....
  3112. sample output:
  3113. ....
  3114. filename: /module_info.ko
  3115. license: GPL
  3116. version: 1.0
  3117. srcversion: AF3DE8A8CFCDEB6B00E35B6
  3118. depends:
  3119. vermagic: 4.17.0 SMP mod_unload modversions
  3120. ....
  3121. Module information is stored in a special `.modinfo` section of the ELF file:
  3122. ....
  3123. ./run-toolchain readelf -- -SW "$(./getvar target_dir)/module_info.ko"
  3124. ....
  3125. contains:
  3126. ....
  3127. [ 5] .modinfo PROGBITS 0000000000000000 0000d8 000096 00 A 0 0 8
  3128. ....
  3129. and:
  3130. ....
  3131. ./run-toolchain readelf -- -x .modinfo "$(./getvar build_dir)/module_info.ko"
  3132. ....
  3133. gives:
  3134. ....
  3135. 0x00000000 6c696365 6e73653d 47504c00 76657273 license=GPL.vers
  3136. 0x00000010 696f6e3d 312e3000 61736466 3d717765 ion=1.0.asdf=qwe
  3137. 0x00000020 72000000 00000000 73726376 65727369 r.......srcversi
  3138. 0x00000030 6f6e3d41 46334445 38413843 46434445 on=AF3DE8A8CFCDE
  3139. 0x00000040 42364230 30453335 42360000 00000000 B6B00E35B6......
  3140. 0x00000050 64657065 6e64733d 006e616d 653d6d6f depends=.name=mo
  3141. 0x00000060 64756c65 5f696e66 6f007665 726d6167 dule_info.vermag
  3142. 0x00000070 69633d34 2e31372e 3020534d 50206d6f ic=4.17.0 SMP mo
  3143. 0x00000080 645f756e 6c6f6164 206d6f64 76657273 d_unload modvers
  3144. 0x00000090 696f6e73 2000 ions .
  3145. ....
  3146. 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`.
  3147. Bibliography:
  3148. * https://stackoverflow.com/questions/19467150/significance-of-this-module-in-linux-driver/49812248#49812248
  3149. * https://stackoverflow.com/questions/4839024/how-to-find-the-version-of-a-compiled-kernel-module/42556565#42556565
  3150. * https://unix.stackexchange.com/questions/238167/how-to-understand-the-modinfo-output
  3151. ==== vermagic
  3152. Vermagic is a magic string present in the kernel and on <<modinfo>> of kernel modules. It is used to verify that the kernel module was compiled against a compatible kernel version and relevant configuration:
  3153. ....
  3154. insmod /vermagic.ko
  3155. ....
  3156. Possible dmesg output:
  3157. ....
  3158. VERMAGIC_STRING = 4.17.0 SMP mod_unload modversions
  3159. ....
  3160. Source: link:kernel_modules/vermagic.c[]
  3161. If we artificially create a mismatch with `MODULE_INFO(vermagic`, the insmod fails with:
  3162. ....
  3163. insmod: can't insert '/vermagic_fail.ko': invalid module format
  3164. ....
  3165. and `dmesg` says the expected and found vermagic found:
  3166. ....
  3167. vermagic_fail: version magic 'asdfqwer' should be '4.17.0 SMP mod_unload modversions '
  3168. ....
  3169. Source: link:kernel_modules/vermagic_fail.c[]
  3170. 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]:
  3171. ....
  3172. #define VERMAGIC_STRING \
  3173. UTS_RELEASE " " \
  3174. MODULE_VERMAGIC_SMP MODULE_VERMAGIC_PREEMPT \
  3175. MODULE_VERMAGIC_MODULE_UNLOAD MODULE_VERMAGIC_MODVERSIONS \
  3176. MODULE_ARCH_VERMAGIC \
  3177. MODULE_RANDSTRUCT_PLUGIN
  3178. ....
  3179. The `SMP` part of the string for example is defined on the same file based on the value of `CONFIG_SMP`:
  3180. ....
  3181. #ifdef CONFIG_SMP
  3182. #define MODULE_VERMAGIC_SMP "SMP "
  3183. #else
  3184. #define MODULE_VERMAGIC_SMP ""
  3185. ....
  3186. TODO how to get the vermagic from running kernel from userland? https://lists.kernelnewbies.org/pipermail/kernelnewbies/2012-October/006306.html
  3187. <<kmod-modprobe>> has a flag to skip the vermagic check:
  3188. ....
  3189. --force-modversion
  3190. ....
  3191. This option just strips `modversion` information from the module before loading, so it is not a kernel feature.
  3192. ==== module_init
  3193. `init_module` and `cleantup_module` are an older alternative to the `module_init` and `module_exit` macros:
  3194. ....
  3195. insmod /init_module.ko
  3196. rmmod init_module
  3197. ....
  3198. Dmesg output:
  3199. ....
  3200. init_module
  3201. cleanup_module
  3202. ....
  3203. Source: link:kernel_modules/module_init.c[]
  3204. 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
  3205. === Kernel panic and oops
  3206. To test out kernel panics and oops in controlled circumstances, try out the modules:
  3207. ....
  3208. insmod /panic.ko
  3209. insmod /oops.ko
  3210. ....
  3211. Source:
  3212. * link:kernel_modules/panic.c[]
  3213. * link:kernel_modules/oops.c[]
  3214. A panic can also be generated with:
  3215. ....
  3216. echo c > /proc/sysrq-trigger
  3217. ....
  3218. Panic vs oops: https://unix.stackexchange.com/questions/91854/whats-the-difference-between-a-kernel-oops-and-a-kernel-panic
  3219. How to generate them:
  3220. * https://unix.stackexchange.com/questions/66197/how-to-cause-kernel-panic-with-a-single-command
  3221. * https://stackoverflow.com/questions/23484147/generate-kernel-oops-or-crash-in-the-code
  3222. 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>>:
  3223. * https://superuser.com/questions/848412/scrolling-up-the-failed-screen-with-kernel-panic
  3224. * https://superuser.com/questions/269228/write-qemu-booting-virtual-machine-output-to-a-file
  3225. * http://www.reactos.org/wiki/QEMU#Redirect_to_a_file
  3226. ==== Kernel panic
  3227. On panic, the kernel dies, and so does our terminal.
  3228. The panic trace looks like:
  3229. ....
  3230. panic: loading out-of-tree module taints kernel.
  3231. panic myinit
  3232. Kernel panic - not syncing: hello panic
  3233. CPU: 0 PID: 53 Comm: insmod Tainted: G O 4.16.0 #6
  3234. Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS rel-1.11.0-0-g63451fca13-prebuilt.qemu-project.org 04/01/2014
  3235. Call Trace:
  3236. dump_stack+0x7d/0xba
  3237. ? 0xffffffffc0000000
  3238. panic+0xda/0x213
  3239. ? printk+0x43/0x4b
  3240. ? 0xffffffffc0000000
  3241. myinit+0x1d/0x20 [panic]
  3242. do_one_initcall+0x3e/0x170
  3243. do_init_module+0x5b/0x210
  3244. load_module+0x2035/0x29d0
  3245. ? kernel_read_file+0x7d/0x140
  3246. ? SyS_finit_module+0xa8/0xb0
  3247. SyS_finit_module+0xa8/0xb0
  3248. do_syscall_64+0x6f/0x310
  3249. ? trace_hardirqs_off_thunk+0x1a/0x32
  3250. entry_SYSCALL_64_after_hwframe+0x42/0xb7
  3251. RIP: 0033:0x7ffff7b36206
  3252. RSP: 002b:00007fffffffeb78 EFLAGS: 00000206 ORIG_RAX: 0000000000000139
  3253. RAX: ffffffffffffffda RBX: 000000000000005c RCX: 00007ffff7b36206
  3254. RDX: 0000000000000000 RSI: 000000000069e010 RDI: 0000000000000003
  3255. RBP: 000000000069e010 R08: 00007ffff7ddd320 R09: 0000000000000000
  3256. R10: 00007ffff7ddd320 R11: 0000000000000206 R12: 0000000000000003
  3257. R13: 00007fffffffef4a R14: 0000000000000000 R15: 0000000000000000
  3258. Kernel Offset: disabled
  3259. ---[ end Kernel panic - not syncing: hello panic
  3260. ....
  3261. Notice how our panic message `hello panic` is visible at:
  3262. ....
  3263. Kernel panic - not syncing: hello panic
  3264. ....
  3265. ===== Kernel module stack trace to source line
  3266. The log shows which module each symbol belongs to if any, e.g.:
  3267. ....
  3268. myinit+0x1d/0x20 [panic]
  3269. ....
  3270. says that the function `myinit` is in the module `panic`.
  3271. To find the line that panicked, do:
  3272. ....
  3273. ./run-gdb
  3274. ....
  3275. and then:
  3276. ....
  3277. info line *(myinit+0x1d)
  3278. ....
  3279. which gives us the correct line:
  3280. ....
  3281. Line 7 of "/linux-kernel-module-cheat/out/x86_64/buildroot/build/kernel_modules-1.0/./panic.c" starts at address 0xbf00001c <myinit+28> and ends at 0xbf00002c <myexit>.
  3282. ....
  3283. as explained at: https://stackoverflow.com/questions/8545931/using-gdb-to-convert-addresses-to-lines/27576029#27576029
  3284. The exact same thing can be done post mortem with:
  3285. ....
  3286. ./run-toolchain gdb -- \
  3287. -batch \
  3288. -ex 'info line *(myinit+0x1d)' \
  3289. "$(./getvar kernel_modules_build_subdir)/panic.ko" \
  3290. ;
  3291. ....
  3292. Related:
  3293. * https://stackoverflow.com/questions/6151538/addr2line-on-kernel-module
  3294. * https://stackoverflow.com/questions/13468286/how-to-read-understand-analyze-and-debug-a-linux-kernel-panic
  3295. ===== BUG_ON
  3296. Basically just calls `panic("BUG!")` for most archs.
  3297. ===== Exit emulator on panic
  3298. 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.
  3299. ====== Exit QEMU on panic
  3300. Enabled by default with:
  3301. * `panic=-1` command line option which reboots the kernel immediately on panic, see: <<reboot-on-panic>>
  3302. * QEMU `-no-reboot`, which makes QEMU exit when the guest tries to reboot
  3303. 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.
  3304. TODO neither method exits with exit status different from 0, so for now we are just grepping the logs for panic messages, which sucks.
  3305. 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.
  3306. ====== Exit gem5 on panic
  3307. gem5 actually detects panics automatically by parsing kernel symbols and detecting when the PC reaches the address of the `panic` function. gem5 then prints to stdout:
  3308. ....
  3309. Kernel panic in simulated kernel
  3310. ....
  3311. and exits with status -6.
  3312. 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!
  3313. If we don't set `system.panic_on_panic`, then gem5 just hangs.
  3314. TODO: why doesn't x86 support `system.panic_on_panic` as well? Trying to set `system.panic_on_panic` there fails with:
  3315. ....
  3316. AttributeError: Class LinuxX86System has no parameter panic_on_panic
  3317. ....
  3318. However, as of f9eb0b72de9029ff16091a18de109c18a9ecc30a, panic on x86 makes gem5 crash with:
  3319. ....
  3320. panic: i8042 "System reset" command not implemented.
  3321. ....
  3322. which is a good side effect of an unimplemented hardware feature, since the simulation actually stops.
  3323. The implementation of panic detection happens at: https://github.com/gem5/gem5/blob/1da285dfcc31b904afc27e440544d006aae25b38/src/arch/arm/linux/system.cc#L73
  3324. ....
  3325. kernelPanicEvent = addKernelFuncEventOrPanic<Linux::KernelPanicEvent>(
  3326. "panic", "Kernel panic in simulated kernel", dmesg_output);
  3327. ....
  3328. Here we see that the symbol `"panic"` for the `panic()` function is the one being tracked.
  3329. ===== Reboot on panic
  3330. Make the kernel reboot after n seconds after panic:
  3331. ....
  3332. echo 1 > /proc/sys/kernel/panic
  3333. ....
  3334. Can also be controlled with the `panic=` kernel boot parameter.
  3335. `0` to disable, `-1` to reboot immediately.
  3336. Bibliography:
  3337. * https://github.com/torvalds/linux/blob/v4.17/Documentation/admin-guide/kernel-parameters.txt#L2931
  3338. * https://unix.stackexchange.com/questions/29567/how-to-configure-the-linux-kernel-to-reboot-on-panic/29569#29569
  3339. ===== Panic trace show addresses instead of symbols
  3340. If `CONFIG_KALLSYMS=n`, then addresses are shown on traces instead of symbol plus offset.
  3341. In v4.16 it does not seem possible to configure that at runtime. GDB step debugging with:
  3342. ....
  3343. ./run --eval-busybox 'insmod /dump_stack.ko' --debug-guest --tmux=dump_stack
  3344. ....
  3345. shows that traces are printed at `arch/x86/kernel/dumpstack.c`:
  3346. ....
  3347. static void printk_stack_address(unsigned long address, int reliable,
  3348. char *log_lvl)
  3349. {
  3350. touch_nmi_watchdog();
  3351. printk("%s %s%pB\n", log_lvl, reliable ? "" : "? ", (void *)address);
  3352. }
  3353. ....
  3354. and `%pB` is documented at `Documentation/core-api/printk-formats.rst`:
  3355. ....
  3356. If KALLSYMS are disabled then the symbol address is printed instead.
  3357. ....
  3358. 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...
  3359. [[oops]]
  3360. ==== Kernel oops
  3361. On oops, the shell still lives after.
  3362. However we:
  3363. * leave the normal control flow, and `oops after` never gets printed: an interrupt is serviced
  3364. * cannot `rmmod oops` afterwards
  3365. It is possible to make `oops` lead to panics always with:
  3366. ....
  3367. echo 1 > /proc/sys/kernel/panic_on_oops
  3368. insmod /oops.ko
  3369. ....
  3370. An oops stack trace looks like:
  3371. ....
  3372. BUG: unable to handle kernel NULL pointer dereference at 0000000000000000
  3373. IP: myinit+0x18/0x30 [oops]
  3374. PGD dccf067 P4D dccf067 PUD dcc1067 PMD 0
  3375. Oops: 0002 [#1] SMP NOPTI
  3376. Modules linked in: oops(O+)
  3377. CPU: 0 PID: 53 Comm: insmod Tainted: G O 4.16.0 #6
  3378. Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS rel-1.11.0-0-g63451fca13-prebuilt.qemu-project.org 04/01/2014
  3379. RIP: 0010:myinit+0x18/0x30 [oops]
  3380. RSP: 0018:ffffc900000d3cb0 EFLAGS: 00000282
  3381. RAX: 000000000000000b RBX: ffffffffc0000000 RCX: ffffffff81e3e3a8
  3382. RDX: 0000000000000001 RSI: 0000000000000086 RDI: ffffffffc0001033
  3383. RBP: ffffc900000d3e30 R08: 69796d2073706f6f R09: 000000000000013b
  3384. R10: ffffea0000373280 R11: ffffffff822d8b2d R12: 0000000000000000
  3385. R13: ffffffffc0002050 R14: ffffffffc0002000 R15: ffff88000dc934c8
  3386. FS: 00007ffff7ff66a0(0000) GS:ffff88000fc00000(0000) knlGS:0000000000000000
  3387. CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033
  3388. CR2: 0000000000000000 CR3: 000000000dcd2000 CR4: 00000000000006f0
  3389. Call Trace:
  3390. do_one_initcall+0x3e/0x170
  3391. do_init_module+0x5b/0x210
  3392. load_module+0x2035/0x29d0
  3393. ? SyS_finit_module+0xa8/0xb0
  3394. SyS_finit_module+0xa8/0xb0
  3395. do_syscall_64+0x6f/0x310
  3396. ? trace_hardirqs_off_thunk+0x1a/0x32
  3397. entry_SYSCALL_64_after_hwframe+0x42/0xb7
  3398. RIP: 0033:0x7ffff7b36206
  3399. RSP: 002b:00007fffffffeb78 EFLAGS: 00000206 ORIG_RAX: 0000000000000139
  3400. RAX: ffffffffffffffda RBX: 000000000000005c RCX: 00007ffff7b36206
  3401. RDX: 0000000000000000 RSI: 000000000069e010 RDI: 0000000000000003
  3402. RBP: 000000000069e010 R08: 00007ffff7ddd320 R09: 0000000000000000
  3403. R10: 00007ffff7ddd320 R11: 0000000000000206 R12: 0000000000000003
  3404. R13: 00007fffffffef4b R14: 0000000000000000 R15: 0000000000000000
  3405. Code: <c7> 04 25 00 00 00 00 00 00 00 00 e8 b2 33 09 c1 31 c0 c3 0f 1f 44
  3406. RIP: myinit+0x18/0x30 [oops] RSP: ffffc900000d3cb0
  3407. CR2: 0000000000000000
  3408. ---[ end trace 3cdb4e9d9842b503 ]---
  3409. ....
  3410. To find the line that oopsed, look at the `RIP` register:
  3411. ....
  3412. RIP: 0010:myinit+0x18/0x30 [oops]
  3413. ....
  3414. and then on GDB:
  3415. ....
  3416. ./run-gdb
  3417. ....
  3418. run
  3419. ....
  3420. info line *(myinit+0x18)
  3421. ....
  3422. which gives us the correct line:
  3423. ....
  3424. Line 7 of "/linux-kernel-module-cheat/out/arm/buildroot/build/kernel_modules-1.0/./panic.c" starts at address 0xbf00001c <myinit+28> and ends at 0xbf00002c <myexit>.
  3425. ....
  3426. This-did not work on `arm` due to <<gdb-step-debug-kernel-module-arm>> so we need to either:
  3427. * <<gdb-module_init>>
  3428. * <<kernel-module-stack-trace-to-source-line>> post-mortem method
  3429. ==== dump_stack
  3430. 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:
  3431. ....
  3432. insmod /dump_stack.ko
  3433. ....
  3434. Source: link:kernel_modules/dump_stack.c[]
  3435. ==== WARN_ON
  3436. The `WARN_ON` macro basically just calls <<dump_stack,dump_stack>>.
  3437. One extra side effect is that we can make it also panic with:
  3438. ....
  3439. echo 1 > /proc/sys/kernel/panic_on_warn
  3440. insmod /warn_on.ko
  3441. ....
  3442. Source: link:kernel_modules/warn_on.c[]
  3443. Can also be activated with the `panic_on_warn` boot parameter.
  3444. === Pseudo filesystems
  3445. 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.
  3446. What each pseudo-file does for each related system call does is defined by its <<file-operations>>.
  3447. Bibliography:
  3448. * https://superuser.com/questions/1198292/what-is-a-pseudo-file-system-in-linux
  3449. * https://en.wikipedia.org/wiki/Synthetic_file_system
  3450. ==== debugfs
  3451. Debugfs is the simplest pseudo filesystem to play around with:
  3452. ....
  3453. /debugfs.sh
  3454. echo $?
  3455. ....
  3456. Outcome: the test passes:
  3457. ....
  3458. 0
  3459. ....
  3460. Sources:
  3461. * link:kernel_modules/debugfs.c[]
  3462. * link:rootfs_overlay/debugfs.sh[]
  3463. Debugfs is made specifically to help test kernel stuff. Just mount, set <<file-operations>>, and we are done.
  3464. For this reason, it is the filesystem that we use whenever possible in our tests.
  3465. `debugfs.sh` explicitly mounts a debugfs at a custom location, but the most common mount point is `/sys/kernel/debug`.
  3466. 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].
  3467. Debugfs support requires the kernel to be compiled with `CONFIG_DEBUG_FS=y`.
  3468. Only the more basic file operations can be implemented in debugfs, e.g. `mmap` never gets called:
  3469. * https://patchwork.kernel.org/patch/9252557/
  3470. * https://github.com/torvalds/linux/blob/v4.9/fs/debugfs/file.c#L212
  3471. Bibliography: https://github.com/chadversary/debugfs-tutorial
  3472. ==== procfs
  3473. Procfs is just another fops entry point:
  3474. ....
  3475. /procfs.sh
  3476. echo $?
  3477. ....
  3478. Outcome: the test passes:
  3479. ....
  3480. 0
  3481. ....
  3482. Procfs is a little less convenient than <<debugfs>>, but is more used in serious applications.
  3483. Procfs can run all system calls, including ones that debugfs can't, e.g. <<mmap>>.
  3484. Sources:
  3485. * link:kernel_modules/procfs.c[]
  3486. * link:rootfs_overlay/procfs.sh[]
  3487. Bibliography: https://stackoverflow.com/questions/8516021/proc-create-example-for-kernel-module/18924359#18924359
  3488. ==== sysfs
  3489. Sysfs is more restricted than <<procfs>>, as it does not take an arbitrary `file_operations`:
  3490. ....
  3491. /sysfs.sh
  3492. echo $?
  3493. ....
  3494. Outcome: the test passes:
  3495. ....
  3496. 0
  3497. ....
  3498. Sources:
  3499. * link:kernel_modules/sysfs.c[]
  3500. * link:rootfs_overlay/sysfs.sh[]
  3501. Vs procfs:
  3502. * https://unix.stackexchange.com/questions/4884/what-is-the-difference-between-procfs-and-sysfs
  3503. * https://stackoverflow.com/questions/37237835/how-to-attach-file-operations-to-sysfs-attribute-in-platform-driver
  3504. You basically can only do `open`, `close`, `read`, `write`, and `lseek` on sysfs files.
  3505. It is similar to a <<seq_file>> file operation, except that write is also implemented.
  3506. TODO: what are those `kobject` structs? Make a more complex example that shows what they can do.
  3507. Bibliography:
  3508. * https://github.com/t3rm1n4l/kern-dev-tutorial/blob/1f036ef40fc4378f5c8d2842e55bcea7c6f8894a/05-sysfs/sysfs.c
  3509. * https://www.kernel.org/doc/Documentation/kobject.txt
  3510. * https://www.quora.com/What-are-kernel-objects-Kobj
  3511. * http://www.makelinux.net/ldd3/chp-14-sect-1
  3512. * https://www.win.tue.nl/~aeb/linux/lk/lk-13.html
  3513. ==== Character devices
  3514. Character devices can have arbitrary <<file-operations>> associated to them:
  3515. ....
  3516. /character_device.sh
  3517. echo $?
  3518. ....
  3519. Outcome: the test passes:
  3520. ....
  3521. 0
  3522. ....
  3523. Sources:
  3524. * link:rootfs_overlay/character_device.sh[]
  3525. * link:rootfs_overlay/mknoddev.sh[]
  3526. * link:kernel_modules/character_device.c[]
  3527. Unlike <<procfs>> entires, character device files are created with userland `mknod` or `mknodat` syscalls:
  3528. ....
  3529. mknod </dev/path_to_dev> c <major> <minor>
  3530. ....
  3531. Intuitively, for physical devices like keyboards, the major number maps to which driver, and the minor number maps to which device it is.
  3532. A single driver can drive multiple compatible devices.
  3533. The major and minor numbers can be observed with:
  3534. ....
  3535. ls -l /dev/urandom
  3536. ....
  3537. Output:
  3538. ....
  3539. crw-rw-rw- 1 root root 1, 9 Jun 29 05:45 /dev/urandom
  3540. ....
  3541. which means:
  3542. * `c` (first letter): this is a character device. Would be `b` for a block device.
  3543. * `1, 9`: the major number is `1`, and the minor `9`
  3544. To avoid device number conflicts when registering the driver we:
  3545. * ask the kernel to allocate a free major number for us with: `register_chrdev(0`
  3546. * find ouf which number was assigned by grepping `/proc/devices` for the kernel module name
  3547. Bibliography: https://unix.stackexchange.com/questions/37829/understanding-character-device-or-character-special-files/371758#371758
  3548. ===== Automatically create character device file on insmod
  3549. And also destroy it on `rmmod`:
  3550. ....
  3551. /character_device_create.sh
  3552. echo $?
  3553. ....
  3554. Outcome: the test passes:
  3555. ....
  3556. 0
  3557. ....
  3558. Sources:
  3559. * link:kernel_modules/character_device_create.c[]
  3560. * link:rootfs_overlay/character_device_create.sh[]
  3561. Bibliography: https://stackoverflow.com/questions/5970595/how-to-create-a-device-node-from-the-init-module-code-of-a-linux-kernel-module/45531867#45531867
  3562. === Pseudo files
  3563. ==== File operations
  3564. 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>>.
  3565. This example illustrates the most basic system calls: `open`, `read`, `write`, `close` and `lseek`:
  3566. ....
  3567. /fops.sh
  3568. echo $?
  3569. ....
  3570. Outcome: the test passes:
  3571. ....
  3572. 0
  3573. ....
  3574. Sources:
  3575. * link:kernel_modules/fops.c[]
  3576. * link:rootfs_overlay/fops.sh[]
  3577. Then give this a try:
  3578. ....
  3579. sh -x /fops.sh
  3580. ....
  3581. We have put printks on each fop, so this allows you to see which system calls are being made for each command.
  3582. No, there no official documentation: http://stackoverflow.com/questions/15213932/what-are-the-struct-file-operations-arguments
  3583. ==== seq_file
  3584. Writing trivial read <<file-operations>> is repetitive and error prone. The `seq_file` API makes the process much easier for those trivial cases:
  3585. ....
  3586. /seq_file.sh
  3587. echo $?
  3588. ....
  3589. Outcome: the test passes:
  3590. ....
  3591. 0
  3592. ....
  3593. Sources:
  3594. * link:kernel_modules/seq_file.c[]
  3595. * link:rootfs_overlay/seq_file.sh[]
  3596. In this example we create a debugfs file that behaves just like a file that contains:
  3597. ....
  3598. 0
  3599. 1
  3600. 2
  3601. ....
  3602. However, we only store a single integer in memory and calculate the file on the fly in an iterator fashion.
  3603. `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
  3604. Bibliography:
  3605. * link:https://github.com/torvalds/linux/blob/v4.17/Documentation/filesystems/seq_file.txt[Documentation/filesystems/seq_file.txt]
  3606. * https://stackoverflow.com/questions/25399112/how-to-use-a-seq-file-in-linux-modules
  3607. ===== seq_file single_open
  3608. If you have the entire read output upfront, `single_open` is an even more convenient version of <<seq_file>>:
  3609. ....
  3610. /seq_file.sh
  3611. echo $?
  3612. ....
  3613. Outcome: the test passes:
  3614. ....
  3615. 0
  3616. ....
  3617. Sources:
  3618. * link:kernel_modules/seq_file_single_open.c[]
  3619. * link:rootfs_overlay/seq_file_single_open.sh[]
  3620. This example produces a debugfs file that behaves like a file that contains:
  3621. ....
  3622. ab
  3623. cd
  3624. ....
  3625. ==== poll
  3626. The poll system call allows an user process to do a non-busy wait on a kernel event:
  3627. ....
  3628. /poll.sh
  3629. ....
  3630. Outcome: `jiffies` gets printed to stdout every second from userland.
  3631. Sources:
  3632. * link:kernel_modules/poll.c[]
  3633. * link:kernel_modules/poll.c[]
  3634. * link:rootfs_overlay/poll.sh[]
  3635. Typically, we are waiting for some hardware to make some piece of data available available to the kernel.
  3636. The hardware notifies the kernel that the data is ready with an interrupt.
  3637. To simplify this example, we just fake the hardware interrupts with a <<kthread>> that sleeps for a second in an infinite loop.
  3638. Bibliography: https://stackoverflow.com/questions/30035776/how-to-add-poll-function-to-the-kernel-module-code/44645336#44645336
  3639. ==== ioctl
  3640. The `ioctl` system call is the best way to pass an arbitrary number of parameters to the kernel in a single go:
  3641. ....
  3642. /ioctl.sh
  3643. echo $?
  3644. ....
  3645. Outcome: the test passes:
  3646. ....
  3647. 0
  3648. ....
  3649. Sources:
  3650. * link:kernel_modules/ioctl.c[]
  3651. * link:kernel_modules/ioctl.h[]
  3652. * link:userland/ioctl.c[]
  3653. * link:rootfs_overlay/ioctl.sh[]
  3654. `ioctl` is one of the most important methods of communication with real device drivers, which often take several fields as input.
  3655. `ioctl` takes as input:
  3656. * an integer `request` : it usually identifies what type of operation we want to do on this call
  3657. * an untyped pointer to memory: can be anything, but is typically a pointer to a `struct`
  3658. +
  3659. The type of the `struct` often depends on the `request` input
  3660. +
  3661. This `struct` is defined on a uapi-style C header that is used both to compile the kernel module and the userland executable.
  3662. +
  3663. The fields of this `struct` can be thought of as arbitrary input parameters.
  3664. And the output is:
  3665. * an integer return value. `man ioctl` documents:
  3666. +
  3667. ____
  3668. 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.
  3669. ____
  3670. * the input pointer data may be overwritten to contain arbitrary output
  3671. Bibliography:
  3672. * https://stackoverflow.com/questions/2264384/how-do-i-use-ioctl-to-manipulate-my-kernel-module/44613896#44613896
  3673. * https://askubuntu.com/questions/54239/problem-with-ioctl-in-a-simple-kernel-module/926675#926675
  3674. ==== mmap
  3675. The `mmap` system call allows us to share memory between user and kernel space without copying:
  3676. ....
  3677. /mmap.sh
  3678. echo $?
  3679. ....
  3680. Outcome: the test passes:
  3681. ....
  3682. 0
  3683. ....
  3684. Sources:
  3685. * link:kernel_modules/mmap.c[]
  3686. * link:userland/mmap.c[]
  3687. * link:rootfs_overlay/mmap.sh[]
  3688. 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.
  3689. `mmap`, like most more complex <<file-operations>>, does not work with <<debugfs>> as of 4.9, so we use a <<procfs>> file for it.
  3690. Example adapted from: https://coherentmusings.wordpress.com/2014/06/10/implementing-mmap-for-transferring-data-from-user-space-to-kernel-space/
  3691. Bibliography:
  3692. * https://stackoverflow.com/questions/10760479/mmap-kernel-buffer-to-user-space/10770582#10770582
  3693. * https://stackoverflow.com/questions/1623008/allocating-memory-for-user-space-from-kernel-thread
  3694. * https://stackoverflow.com/questions/6967933/mmap-mapping-in-user-space-a-kernel-buffer-allocated-with-kmalloc
  3695. * https://github.com/jeremytrimble/ezdma
  3696. * https://github.com/simonjhall/dma
  3697. * https://github.com/ikwzm/udmabuf
  3698. ==== Anonymous inode
  3699. Anonymous inodes allow getting multiple file descriptors from a single filesystem entry, which reduces namespace pollution compared to creating multiple device files:
  3700. ....
  3701. /anonymous_inode.sh
  3702. echo $?
  3703. ....
  3704. Outcome: the test passes:
  3705. ....
  3706. 0
  3707. ....
  3708. Sources:
  3709. * link:kernel_modules/anonymous_inode.c[]
  3710. * link:kernel_modules/anonymous_inode.h[]
  3711. * link:userland/anonymous_inode.c[]
  3712. * link:rootfs_overlay/anonymous_inode.sh[]
  3713. This example gets an anonymous inode via <<ioctl>> from a debugfs entry by using `anon_inode_getfd`.
  3714. Reads to that inode return the sequence: `1`, `10`, `100`, ... `10000000`, `1`, `100`, ...
  3715. Bibliography: https://stackoverflow.com/questions/4508998/what-is-an-anonymous-inode-in-linux/44388030#44388030
  3716. ==== netlink sockets
  3717. Netlink sockets offer a socket API for kernel / userland communication:
  3718. ....
  3719. /netlink.sh
  3720. echo $?
  3721. ....
  3722. Outcome: the test passes:
  3723. ....
  3724. 0
  3725. ....
  3726. Sources:
  3727. * link:kernel_modules/netlink.c[]
  3728. * link:kernel_modules/netlink.h[]
  3729. * link:userland/netlink.c[]
  3730. * link:rootfs_overlay/netlink.sh[]
  3731. Launch multiple user requests in parallel to stress our socket:
  3732. ....
  3733. insmod /netlink.ko sleep=1
  3734. for i in `seq 16`; do /netlink.out & done
  3735. ....
  3736. 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
  3737. Bibliography:
  3738. * https://stackoverflow.com/questions/3299386/how-to-use-netlink-socket-to-communicate-with-a-kernel-module
  3739. * https://en.wikipedia.org/wiki/Netlink
  3740. === kthread
  3741. Kernel threads are managed exactly like userland threads; they also have a backing `task_struct`, and are scheduled with the same mechanism:
  3742. ....
  3743. insmod /kthread.ko
  3744. ....
  3745. Source: link:kernel_modules/kthread.c[]
  3746. Outcome: dmesg counts from `0` to `9` once every second infinitely many times:
  3747. ....
  3748. 0
  3749. 1
  3750. 2
  3751. ...
  3752. 8
  3753. 9
  3754. 0
  3755. 1
  3756. 2
  3757. ...
  3758. ....
  3759. The count stops when we `rmmod`:
  3760. ....
  3761. rmmod kthread
  3762. ....
  3763. The sleep is done with `usleep_range`, see: <<sleep>>.
  3764. Bibliography:
  3765. * http://stackoverflow.com/questions/10177641/proper-way-of-handling-threads-in-kernel
  3766. * http://stackoverflow.com/questions/4084708/how-to-wait-for-a-linux-kernel-thread-kthreadto-exit
  3767. ==== kthreads
  3768. Let's launch two threads and see if they actually run in parallel:
  3769. ....
  3770. insmod /kthreads.ko
  3771. ....
  3772. Source: link:kernel_modules/kthreads.c[]
  3773. Outcome: two threads count to dmesg from `0` to `9` in parallel.
  3774. Each line has output of form:
  3775. ....
  3776. <thread_id> <count>
  3777. ....
  3778. Possible very likely outcome:
  3779. ....
  3780. 1 0
  3781. 2 0
  3782. 1 1
  3783. 2 1
  3784. 1 2
  3785. 2 2
  3786. 1 3
  3787. 2 3
  3788. ....
  3789. The threads almost always interleaved nicely, thus confirming that they are actually running in parallel.
  3790. ==== sleep
  3791. Count to dmesg every one second from `0` up to `n - 1`:
  3792. ....
  3793. insmod /sleep.ko n=5
  3794. ....
  3795. Source: link:kernel_modules/sleep.c[]
  3796. 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.
  3797. Bibliography:
  3798. * https://stackoverflow.com/questions/15994603/how-to-sleep-in-the-linux-kernel/44153288#44153288
  3799. * https://github.com/torvalds/linux/blob/v4.17/Documentation/timers/timers-howto.txt
  3800. ==== Workqueues
  3801. A more convenient front-end for <<kthread>>:
  3802. ....
  3803. insmod /workqueue_cheat.ko
  3804. ....
  3805. Outcome: count from `0` to `9` infinitely many times
  3806. Stop counting:
  3807. ....
  3808. rmmod workqueue_cheat
  3809. ....
  3810. Source: link:kernel_modules/workqueue_cheat.c[]
  3811. The workqueue thread is killed after the worker function returns.
  3812. 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
  3813. Bibliography: https://github.com/torvalds/linux/blob/v4.17/Documentation/core-api/workqueue.rst
  3814. ===== Workqueue from workqueue
  3815. Count from `0` to `9` every second infinitely many times by scheduling a new work item from a work item:
  3816. ....
  3817. insmod /work_from_work.ko
  3818. ....
  3819. Stop:
  3820. ....
  3821. rmmod work_from_work
  3822. ....
  3823. 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.
  3824. Source: link:kernel_modules/work_from_work.c[]
  3825. ==== schedule
  3826. Let's block the entire kernel! Yay:
  3827. .....
  3828. ./run --eval-busybox 'dmesg -n 1;insmod /schedule.ko schedule=0'
  3829. .....
  3830. Outcome: the system hangs, the only way out is to kill the VM.
  3831. Source: link:kernel_modules/schedule.c[]
  3832. kthreads only allow interrupting if you call `schedule()`, and the `schedule=0` <<kernel-module-parameters,kernel module parameter>> turns it off.
  3833. Sleep functions like `usleep_range` also end up calling schedule.
  3834. If we allow `schedule()` to be called, then the system becomes responsive:
  3835. .....
  3836. ./run --eval-busybox 'dmesg -n 1;insmod /schedule.ko schedule=1'
  3837. .....
  3838. and we can observe the counting with:
  3839. ....
  3840. dmesg -w
  3841. ....
  3842. The system also responds if we <<number-of-cores,add another core>>:
  3843. ....
  3844. ./run --cpus 2 --eval-busybox 'dmesg -n 1;insmod /schedule.ko schedule=0'
  3845. ....
  3846. ==== Wait queues
  3847. Wait queues are a way to make a thread sleep until an event happens on the queue:
  3848. ....
  3849. insmod /wait_queue.c
  3850. ....
  3851. Dmesg output:
  3852. ....
  3853. 0 0
  3854. 1 0
  3855. 2 0
  3856. # Wait one second.
  3857. 0 1
  3858. 1 1
  3859. 2 1
  3860. # Wait one second.
  3861. 0 2
  3862. 1 2
  3863. 2 2
  3864. ...
  3865. ....
  3866. Stop the count:
  3867. ....
  3868. rmmod wait_queue
  3869. ....
  3870. Source: link:kernel_modules/wait_queue.c[]
  3871. This example launches three threads:
  3872. * one thread generates events every with link:https://github.com/torvalds/linux/blob/v4.17/include/linux/wait.h#L195[`wake_up`]
  3873. * 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.
  3874. +
  3875. The `wait_event` macro works a bit like:
  3876. +
  3877. ....
  3878. while (!cond)
  3879. sleep_until_event
  3880. ....
  3881. === Timers
  3882. Count from `0` to `9` infinitely many times in 1 second intervals using timers:
  3883. ....
  3884. insmod /timer.ko
  3885. ....
  3886. Stop counting:
  3887. ....
  3888. rmmod timer
  3889. ....
  3890. Source: link:kernel_modules/timer.c[]
  3891. Timers are callbacks that run when an interrupt happens, from the interrupt context itself.
  3892. Therefore they produce more accurate timing than thread scheduling, which is more complex, but you can't do too much work inside of them.
  3893. Bibliography:
  3894. * http://stackoverflow.com/questions/10812858/timers-in-linux-device-drivers
  3895. * https://gist.github.com/yagihiro/310149
  3896. === IRQ
  3897. ==== irq.ko
  3898. Brute force monitor every shared interrupt that will accept us:
  3899. ....
  3900. ./run --eval-busybox 'insmod /irq.ko' --graphic
  3901. ....
  3902. Source: link:kernel_modules/irq.c[].
  3903. Now try the following:
  3904. * press a keyboard key and then release it after a few seconds
  3905. * press a mouse key, and release it after a few seconds
  3906. * move the mouse around
  3907. Outcome: dmesg shows which IRQ was fired for each action through messages of type:
  3908. ....
  3909. handler irq = 1 dev = 250
  3910. ....
  3911. `dev` is the character device for the module and never changes, as can be confirmed by:
  3912. ....
  3913. grep lkmc_irq /proc/devices
  3914. ....
  3915. The IRQs that we observe are:
  3916. * `1` for keyboard press and release.
  3917. +
  3918. If you hold the key down for a while, it starts firing at a constant rate. So this happens at the hardware level!
  3919. * `12` mouse actions
  3920. This only works if for IRQs for which the other handlers are registered as `IRQF_SHARED`.
  3921. We can see which ones are those, either via dmesg messages of type:
  3922. ....
  3923. genirq: Flags mismatch irq 0. 00000080 (myirqhandler0) vs. 00015a00 (timer)
  3924. request_irq irq = 0 ret = -16
  3925. request_irq irq = 1 ret = 0
  3926. ....
  3927. which indicate that `0` is not, but `1` is, or with:
  3928. ....
  3929. cat /proc/interrupts
  3930. ....
  3931. which shows:
  3932. ....
  3933. 0: 31 IO-APIC 2-edge timer
  3934. 1: 9 IO-APIC 1-edge i8042, myirqhandler0
  3935. ....
  3936. so only `1` has `myirqhandler0` attached but not `0`.
  3937. The <<qemu-monitor>> also has some interrupt statistics for x86_64:
  3938. ....
  3939. ./qemu-monitor info irq
  3940. ....
  3941. TODO: properly understand how each IRQ maps to what number.
  3942. ==== dummy-irq
  3943. The Linux kernel v4.16 mainline also has a `dummy-irq` module at `drivers/misc/dummy-irq.c` for monitoring a single IRQ.
  3944. We build it by default with:
  3945. ....
  3946. CONFIG_DUMMY_IRQ=m
  3947. ....
  3948. And then you can do
  3949. ....
  3950. ./run --graphic
  3951. ....
  3952. and in guest:
  3953. ....
  3954. modprobe dummy-irq irq=1
  3955. ....
  3956. Outcome: when you click a key on the keyboard, dmesg shows:
  3957. ....
  3958. dummy-irq: interrupt occurred on IRQ 1
  3959. ....
  3960. However, this module is intended to fire only once as can be seen from its source:
  3961. ....
  3962. static int count = 0;
  3963. if (count == 0) {
  3964. printk(KERN_INFO "dummy-irq: interrupt occurred on IRQ %d\n",
  3965. irq);
  3966. count++;
  3967. }
  3968. ....
  3969. and furthermore interrupt `1` and `12` happen immediately TODO why, were they somehow pending?
  3970. So so see something interesting, you need to monitor an interrupt that is more rare than the keyboard, e.g. <<platform_device>>.
  3971. ==== /proc/interrupts
  3972. In the guest with <<qemu-graphic-mode>>:
  3973. ....
  3974. watch -n 1 cat /proc/interrupts
  3975. ....
  3976. Then see how clicking the mouse and keyboard affect the interrupt counts.
  3977. This confirms that:
  3978. * 1: keyboard
  3979. * 12: mouse click and drags
  3980. The module also shows which handlers are registered for each IRQ, as we have observed at <<irq-ko>>
  3981. When in text mode, we can also observe interrupt line 4 with handler `ttyS0` increase continuously as IO goes through the UART.
  3982. === Kernel utility functions
  3983. https://github.com/torvalds/linux/blob/v4.17/Documentation/core-api/kernel-api.rst
  3984. ==== kstrto
  3985. Convert a string to an integer:
  3986. ....
  3987. /kstrto.sh
  3988. echo $?
  3989. ....
  3990. Outcome: the test passes:
  3991. ....
  3992. 0
  3993. ....
  3994. Sources:
  3995. * link:kernel_modules/kstrto.c[]
  3996. * link:rootfs_overlay/kstrto.sh[]
  3997. Bibliography: https://stackoverflow.com/questions/6139493/how-convert-char-to-int-in-linux-kernel/49811658#49811658
  3998. ==== virt_to_phys
  3999. Convert a virtual address to physical:
  4000. ....
  4001. insmod /virt_to_phys.ko
  4002. cat /sys/kernel/debug/lkmc_virt_to_phys
  4003. ....
  4004. Source: link:kernel_modules/virt_to_phys.c[]
  4005. Sample output:
  4006. ....
  4007. *kmalloc_ptr = 0x12345678
  4008. kmalloc_ptr = ffff88000e169ae8
  4009. virt_to_phys(kmalloc_ptr) = 0xe169ae8
  4010. static_var = 0x12345678
  4011. &static_var = ffffffffc0002308
  4012. virt_to_phys(&static_var) = 0x40002308
  4013. ....
  4014. We can confirm that the `kmalloc_ptr` translation worked with:
  4015. ....
  4016. ./qemu-monitor 'xp 0xe169ae8'
  4017. ....
  4018. which reads four bytes from a given physical address, and gives the expected:
  4019. ....
  4020. 000000000e169ae8: 0x12345678
  4021. ....
  4022. TODO it only works for kmalloc however, for the static variable:
  4023. ....
  4024. ./qemu-monitor 'xp 0x40002308'
  4025. ....
  4026. it gave a wrong value of `00000000`.
  4027. Bibliography:
  4028. * https://stackoverflow.com/questions/5748492/is-there-any-api-for-determining-the-physical-address-from-virtual-address-in-li/45128487#45128487
  4029. * https://stackoverflow.com/questions/39134990/mmap-of-dev-mem-fails-with-invalid-argument-for-virt-to-phys-address-but-addre/45127582#45127582
  4030. * https://stackoverflow.com/questions/43325205/can-we-use-virt-to-phys-for-user-space-memory-in-kernel-module
  4031. ===== Userland physical address experiments
  4032. Only tested in x86_64.
  4033. The Linux kernel exposes physical addresses to userland through:
  4034. * `/proc/<pid>/maps`
  4035. * `/proc/<pid>/pagemap`
  4036. * `/dev/mem`
  4037. In this section we will play with them.
  4038. First get a virtual address to play with:
  4039. ....
  4040. /virt_to_phys_test.out &
  4041. ....
  4042. Source: link:userland/virt_to_phys_test.c[]
  4043. Sample output:
  4044. ....
  4045. vaddr 0x600800
  4046. pid 110
  4047. ....
  4048. The program:
  4049. * allocates a `volatile` variable and sets is value to `0x12345678`
  4050. * prints the virtual address of the variable, and the program PID
  4051. * runs a while loop until until the value of the variable gets mysteriously changed somehow, e.g. by nasty tinkerers like us
  4052. Then, translate the virtual address to physical using `/proc/<pid>/maps` and `/proc/<pid>/pagemap`:
  4053. ....
  4054. /virt_to_phys_user.out 110 0x600800
  4055. ....
  4056. Sample output physical address:
  4057. ....
  4058. 0x7c7b800
  4059. ....
  4060. Source: link:userland/virt_to_phys_user.c[]
  4061. Now we can verify that `virt_to_phys_user.out` gave the correct physical address in the following ways:
  4062. * <<qemu-xp>>
  4063. * <<dev-mem>>
  4064. Bibliography:
  4065. * https://stackoverflow.com/questions/17021214/decode-proc-pid-pagemap-entry/45126141#45126141
  4066. * https://stackoverflow.com/questions/6284810/proc-pid-pagemaps-and-proc-pid-maps-linux/45500208#45500208
  4067. ====== QEMU xp
  4068. The `xp` <<qemu-monitor>> command reads memory at a given physical address.
  4069. First launch `virt_to_phys_user.out` as described at <<userland-physical-address-experiments>>.
  4070. On a second terminal, use QEMU to read the physical address:
  4071. ....
  4072. ./qemu-monitor 'xp 0x7c7b800'
  4073. ....
  4074. Output:
  4075. ....
  4076. 0000000007c7b800: 0x12345678
  4077. ....
  4078. Yes!!! We read the correct value from the physical address.
  4079. We could not find however to write to memory from the QEMU monitor, boring.
  4080. ====== /dev/mem
  4081. `/dev/mem` exposes access to physical addresses, and we use it through the convenient `devmem` BusyBox utility.
  4082. First launch `virt_to_phys_user.out` as described at <<userland-physical-address-experiments>>.
  4083. Next, read from the physical address:
  4084. ....
  4085. devmem 0x7c7b800
  4086. ....
  4087. Possible output:
  4088. ....
  4089. Memory mapped at address 0x7ff7dbe01000.
  4090. Value at address 0X7C7B800 (0x7ff7dbe01800): 0x12345678
  4091. ....
  4092. which shows that the physical memory contains the expected value `0x12345678`.
  4093. `0x7ff7dbe01000` is a new virtual address that `devmem` maps to the physical address to be able to read from it.
  4094. Modify the physical memory:
  4095. ....
  4096. devmem 0x7c7b800 w 0x9abcdef0
  4097. ....
  4098. After one second, we see on the screen:
  4099. ....
  4100. i 9abcdef0
  4101. [1]+ Done /virt_to_phys_test.out
  4102. ....
  4103. so the value changed, and the `while` loop exited!
  4104. This example requires:
  4105. * `CONFIG_STRICT_DEVMEM=n`, otherwise `devmem` fails with:
  4106. +
  4107. ....
  4108. devmem: mmap: Operation not permitted
  4109. ....
  4110. * `nopat` kernel parameter
  4111. which we set by default.
  4112. Bibliography: https://stackoverflow.com/questions/11891979/how-to-access-mmaped-dev-mem-without-crashing-the-linux-kernel
  4113. ====== pagemap_dump.out
  4114. Dump the physical address of all pages mapped to a given process using `/proc/<pid>/maps` and `/proc/<pid>/pagemap`.
  4115. First launch `virt_to_phys_user.out` as described at <<userland-physical-address-experiments>>. Suppose that the output was:
  4116. ....
  4117. # /virt_to_phys_test.out &
  4118. vaddr 0x601048
  4119. pid 63
  4120. # /virt_to_phys_user.out 63 0x601048
  4121. 0x1a61048
  4122. ....
  4123. Now obtain the page map for the process:
  4124. ....
  4125. /pagemap_dump.out 63
  4126. ....
  4127. Sample output excerpt:
  4128. ....
  4129. vaddr pfn soft-dirty file/shared swapped present library
  4130. 400000 1ede 0 1 0 1 /virt_to_phys_test.out
  4131. 600000 1a6f 0 0 0 1 /virt_to_phys_test.out
  4132. 601000 1a61 0 0 0 1 /virt_to_phys_test.out
  4133. 602000 2208 0 0 0 1 [heap]
  4134. 603000 220b 0 0 0 1 [heap]
  4135. 7ffff78ec000 1fd4 0 1 0 1 /lib/libuClibc-1.0.30.so
  4136. ....
  4137. Source: link:userland/pagemap_dump.c[]
  4138. Adapted from: https://github.com/dwks/pagemap/blob/8a25747bc79d6080c8b94eac80807a4dceeda57a/pagemap2.c
  4139. Meaning of the flags:
  4140. * `vaddr`: first virtual address of a page the belongs to the process. Notably:
  4141. +
  4142. ....
  4143. ./run-toolchain readelf -- -l "$(./getvar userland_build_dir)/virt_to_phys_test.out"
  4144. ....
  4145. +
  4146. contains:
  4147. +
  4148. ....
  4149. Type Offset VirtAddr PhysAddr
  4150. FileSiz MemSiz Flags Align
  4151. ...
  4152. LOAD 0x0000000000000000 0x0000000000400000 0x0000000000400000
  4153. 0x000000000000075c 0x000000000000075c R E 0x200000
  4154. LOAD 0x0000000000000e98 0x0000000000600e98 0x0000000000600e98
  4155. 0x00000000000001b4 0x0000000000000218 RW 0x200000
  4156. Section to Segment mapping:
  4157. Segment Sections...
  4158. ...
  4159. 02 .interp .hash .dynsym .dynstr .rela.plt .init .plt .text .fini .rodata .eh_frame_hdr .eh_frame
  4160. 03 .ctors .dtors .jcr .dynamic .got.plt .data .bss
  4161. ....
  4162. +
  4163. from which we deduce that:
  4164. +
  4165. ** `400000` is the text segment
  4166. ** `600000` is the data segment
  4167. * `pfn`: add three zeroes to it, and you have the physical address.
  4168. +
  4169. Three zeroes is 12 bits which is 4kB, which is the size of a page.
  4170. +
  4171. For example, the virtual address `0x601000` has `pfn` of `0x1a61`, which means that its physical address is `0x1a61000`
  4172. +
  4173. This is consistent with what `virt_to_phys_user.out` told us: the virtual address `0x601048` has physical address `0x1a61048`.
  4174. +
  4175. `048` corresponds to the three last zeroes, and is the offset within the page.
  4176. +
  4177. 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.
  4178. * `soft-dirty`: TODO
  4179. * `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`.
  4180. * `swapped`: TODO swapped to disk?
  4181. * `present`: TODO vs swapped?
  4182. * `library`: which executable owns that page
  4183. This program works in two steps:
  4184. * parse the human readable lines lines from `/proc/<pid>/maps`. This files contains lines of form:
  4185. +
  4186. ....
  4187. 7ffff7b6d000-7ffff7bdd000 r-xp 00000000 fe:00 658 /lib/libuClibc-1.0.22.so
  4188. ....
  4189. +
  4190. which tells us that:
  4191. +
  4192. ** `7f8af99f8000-7f8af99ff000` is a virtual address range that belong to the process, possibly containing multiple pages.
  4193. ** `/lib/libuClibc-1.0.22.so` is the name of the library that owns that memory
  4194. * loop over each page of each address range, and ask `/proc/<pid>/pagemap` for more information about that page, including the physical address
  4195. === Linux kernel tracing
  4196. Good overviews:
  4197. * 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
  4198. * https://jvns.ca/blog/2017/07/05/linux-tracing-systems/
  4199. I hope to have examples of all methods some day, since I'm obsessed with visibility.
  4200. ==== CONFIG_PROC_EVENTS
  4201. Logs proc events such as process creation to a link:kernel_modules/netlink.c[netlink socket].
  4202. We then have a userland program that listens to the events and prints them out:
  4203. ....
  4204. # /proc_events.out &
  4205. # set mcast listen ok
  4206. # sleep 2 & sleep 1
  4207. fork: parent tid=48 pid=48 -> child tid=79 pid=79
  4208. fork: parent tid=48 pid=48 -> child tid=80 pid=80
  4209. exec: tid=80 pid=80
  4210. exec: tid=79 pid=79
  4211. # exit: tid=80 pid=80 exit_code=0
  4212. exit: tid=79 pid=79 exit_code=0
  4213. echo a
  4214. a
  4215. #
  4216. ....
  4217. Source: link:userland/proc_events.c[]
  4218. TODO: why `exit: tid=79` shows after `exit: tid=80`?
  4219. Note how `echo a` is a Bash built-in, and therefore does not spawn a new process.
  4220. TODO: why does this produce no output?
  4221. ....
  4222. /proc_events.out >f &
  4223. ....
  4224. * https://stackoverflow.com/questions/6075013/detect-launching-of-programs-on-linux-platform/8255487#8255487
  4225. * https://serverfault.com/questions/199654/does-anyone-know-a-simple-way-to-monitor-root-process-spawn
  4226. * https://unix.stackexchange.com/questions/260162/how-to-track-newly-created-processes
  4227. 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.
  4228. * https://unix.stackexchange.com/questions/163681/print-pids-and-names-of-processes-as-they-are-created/163689 requests process name
  4229. * https://serverfault.com/questions/199654/does-anyone-know-a-simple-way-to-monitor-root-process-spawn requests UID
  4230. ===== CONFIG_PROC_EVENTS aarch64
  4231. 0111ca406bdfa6fd65a2605d353583b4c4051781 was failing with:
  4232. ....
  4233. >>> kernel_modules 1.0 Building
  4234. /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"
  4235. /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'
  4236. In file included from /linux-kernel-module-cheat//out/aarch64/buildroot/host/aarch64-buildroot-linux-uclibc/sysroot/usr/include/signal.h:329:0,
  4237. from proc_events.c:12:
  4238. /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
  4239. mcontext_t uc_mcontext;
  4240. ^~~~~~~~~~~
  4241. ....
  4242. so we commented it out.
  4243. Related threads:
  4244. * https://mailman.uclibc-ng.org/pipermail/devel/2018-January/001624.html
  4245. * https://github.com/DynamoRIO/dynamorio/issues/2356
  4246. 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:
  4247. ....
  4248. ../utils/ldd.c: In function 'elf_find_dynamic':
  4249. ../utils/ldd.c:238:12: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
  4250. return (void *)byteswap_to_host(dynp->d_un.d_val);
  4251. ^
  4252. /tmp/user/20321/cciGScKB.o: In function `process_line_callback':
  4253. msgmerge.c:(.text+0x22): undefined reference to `escape'
  4254. /tmp/user/20321/cciGScKB.o: In function `process':
  4255. msgmerge.c:(.text+0xf6): undefined reference to `poparser_init'
  4256. msgmerge.c:(.text+0x11e): undefined reference to `poparser_feed_line'
  4257. msgmerge.c:(.text+0x128): undefined reference to `poparser_finish'
  4258. collect2: error: ld returned 1 exit status
  4259. Makefile.in:120: recipe for target '../utils/msgmerge.host' failed
  4260. make[2]: *** [../utils/msgmerge.host] Error 1
  4261. make[2]: *** Waiting for unfinished jobs....
  4262. /tmp/user/20321/ccF8V8jF.o: In function `process':
  4263. msgfmt.c:(.text+0xbf3): undefined reference to `poparser_init'
  4264. msgfmt.c:(.text+0xc1f): undefined reference to `poparser_feed_line'
  4265. msgfmt.c:(.text+0xc2b): undefined reference to `poparser_finish'
  4266. collect2: error: ld returned 1 exit status
  4267. Makefile.in:120: recipe for target '../utils/msgfmt.host' failed
  4268. make[2]: *** [../utils/msgfmt.host] Error 1
  4269. package/pkg-generic.mk:227: recipe for target '/data/git/linux-kernel-module-cheat/out/aarch64/buildroot/build/uclibc-custom/.stamp_built' failed
  4270. make[1]: *** [/data/git/linux-kernel-module-cheat/out/aarch64/buildroot/build/uclibc-custom/.stamp_built] Error 2
  4271. Makefile:79: recipe for target '_all' failed
  4272. make: *** [_all] Error 2
  4273. ....
  4274. 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.
  4275. ==== ftrace
  4276. Trace a single function:
  4277. ....
  4278. cd /sys/kernel/debug/tracing/
  4279. # Stop tracing.
  4280. echo 0 > tracing_on
  4281. # Clear previous trace.
  4282. echo > trace
  4283. # List the available tracers, and pick one.
  4284. cat available_tracers
  4285. echo function > current_tracer
  4286. # List all functions that can be traced
  4287. # cat available_filter_functions
  4288. # Choose one.
  4289. echo __kmalloc > set_ftrace_filter
  4290. # Confirm that only __kmalloc is enabled.
  4291. cat enabled_functions
  4292. echo 1 > tracing_on
  4293. # Latest events.
  4294. head trace
  4295. # Observe trace continuously, and drain seen events out.
  4296. cat trace_pipe &
  4297. ....
  4298. Sample output:
  4299. ....
  4300. # tracer: function
  4301. #
  4302. # entries-in-buffer/entries-written: 97/97 #P:1
  4303. #
  4304. # _-----=> irqs-off
  4305. # / _----=> need-resched
  4306. # | / _---=> hardirq/softirq
  4307. # || / _--=> preempt-depth
  4308. # ||| / delay
  4309. # TASK-PID CPU# |||| TIMESTAMP FUNCTION
  4310. # | | | |||| | |
  4311. head-228 [000] .... 825.534637: __kmalloc <-load_elf_phdrs
  4312. head-228 [000] .... 825.534692: __kmalloc <-load_elf_binary
  4313. head-228 [000] .... 825.534815: __kmalloc <-load_elf_phdrs
  4314. head-228 [000] .... 825.550917: __kmalloc <-__seq_open_private
  4315. head-228 [000] .... 825.550953: __kmalloc <-tracing_open
  4316. head-229 [000] .... 826.756585: __kmalloc <-load_elf_phdrs
  4317. head-229 [000] .... 826.756627: __kmalloc <-load_elf_binary
  4318. head-229 [000] .... 826.756719: __kmalloc <-load_elf_phdrs
  4319. head-229 [000] .... 826.773796: __kmalloc <-__seq_open_private
  4320. head-229 [000] .... 826.773835: __kmalloc <-tracing_open
  4321. head-230 [000] .... 827.174988: __kmalloc <-load_elf_phdrs
  4322. head-230 [000] .... 827.175046: __kmalloc <-load_elf_binary
  4323. head-230 [000] .... 827.175171: __kmalloc <-load_elf_phdrs
  4324. ....
  4325. Trace all possible functions, and draw a call graph:
  4326. ....
  4327. echo 1 > max_graph_depth
  4328. echo 1 > events/enable
  4329. echo function_graph > current_tracer
  4330. ....
  4331. Sample output:
  4332. ....
  4333. # CPU DURATION FUNCTION CALLS
  4334. # | | | | | | |
  4335. 0) 2.173 us | } /* ntp_tick_length */
  4336. 0) | timekeeping_update() {
  4337. 0) 4.176 us | ntp_get_next_leap();
  4338. 0) 5.016 us | update_vsyscall();
  4339. 0) | raw_notifier_call_chain() {
  4340. 0) 2.241 us | notifier_call_chain();
  4341. 0) + 19.879 us | }
  4342. 0) 3.144 us | update_fast_timekeeper();
  4343. 0) 2.738 us | update_fast_timekeeper();
  4344. 0) ! 117.147 us | }
  4345. 0) | _raw_spin_unlock_irqrestore() {
  4346. 0) 4.045 us | _raw_write_unlock_irqrestore();
  4347. 0) + 22.066 us | }
  4348. 0) ! 265.278 us | } /* update_wall_time */
  4349. ....
  4350. TODO: what do `+` and `!` mean?
  4351. Each `enable` under the `events/` tree enables a certain set of functions, the higher the `enable` more functions are enabled.
  4352. 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
  4353. ===== ftrace system calls
  4354. https://stackoverflow.com/questions/29840213/how-do-i-trace-a-system-call-in-linux/51856306#51856306
  4355. ===== trace-cmd
  4356. TODO example:
  4357. ....
  4358. ./build-buildroot --config 'BR2_PACKAGE_TRACE_CMD=y'
  4359. ....
  4360. ==== Kprobes
  4361. 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. :-)
  4362. ....
  4363. ./build-linux --config 'CONFIG_KPROBES=y'
  4364. ....
  4365. Then on guest:
  4366. ....
  4367. insmod /kprobe_example.ko
  4368. sleep 4 & sleep 4 &'
  4369. ....
  4370. Outcome: dmesg outputs on every fork:
  4371. ....
  4372. <_do_fork> pre_handler: p->addr = 0x00000000e1360063, ip = ffffffff810531d1, flags = 0x246
  4373. <_do_fork> post_handler: p->addr = 0x00000000e1360063, flags = 0x246
  4374. <_do_fork> pre_handler: p->addr = 0x00000000e1360063, ip = ffffffff810531d1, flags = 0x246
  4375. <_do_fork> post_handler: p->addr = 0x00000000e1360063, flags = 0x246
  4376. ....
  4377. Source: link:kernel_modules/kprobe_example.c[]
  4378. TODO: it does not work if I try to immediately launch `sleep`, why?
  4379. ....
  4380. insmod /kprobe_example.ko
  4381. sleep 4 & sleep 4 &
  4382. ....
  4383. I don't think your code can refer to the surrounding kernel code however: the only visible thing is the value of the registers.
  4384. You can then hack it up to read the stack and read argument values, but do you really want to?
  4385. 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
  4386. Bibliography:
  4387. * https://github.com/torvalds/linux/blob/v4.16/Documentation/kprobes.txt
  4388. * https://github.com/torvalds/linux/blob/v4.17/samples/kprobes/kprobe_example.c
  4389. ==== Count boot instructions
  4390. * https://www.quora.com/How-many-instructions-does-a-typical-Linux-kernel-boot-take
  4391. * https://github.com/cirosantilli/chat/issues/31
  4392. * https://rwmj.wordpress.com/2016/03/17/tracing-qemu-guest-execution/
  4393. * `qemu/docs/tracing.txt` and `qemu/docs/replay.txt`
  4394. * https://stackoverflow.com/questions/39149446/how-to-use-qemus-simple-trace-backend/46497873#46497873
  4395. Results (boot not excluded):
  4396. [options="header"]
  4397. |===
  4398. |Commit |Arch |Simulator |Instruction count
  4399. |7228f75ac74c896417fb8c5ba3d375a14ed4d36b
  4400. |arm
  4401. |QEMU
  4402. |680k
  4403. |7228f75ac74c896417fb8c5ba3d375a14ed4d36b
  4404. |arm
  4405. |gem5 AtomicSimpleCPU
  4406. |160M
  4407. |7228f75ac74c896417fb8c5ba3d375a14ed4d36b
  4408. |arm
  4409. |gem5 HPI
  4410. |155M
  4411. |7228f75ac74c896417fb8c5ba3d375a14ed4d36b
  4412. |x86_64
  4413. |QEMU
  4414. |3M
  4415. |7228f75ac74c896417fb8c5ba3d375a14ed4d36b
  4416. |x86_64
  4417. |gem5 AtomicSimpleCPU
  4418. |528M
  4419. |===
  4420. QEMU:
  4421. ....
  4422. ./trace-boot --arch x86_64
  4423. ....
  4424. sample output:
  4425. ....
  4426. instructions 1833863
  4427. entry_address 0x1000000
  4428. instructions_firmware 20708
  4429. ....
  4430. gem5:
  4431. ....
  4432. ./run --arch aarch64 --gem5 --eval 'm5 exit'
  4433. # Or:
  4434. # ./run --arch aarch64 --gem5 --eval 'm5 exit' -- --cpu-type=HPI --caches
  4435. ./gem5-stat --arch aarch64 sim_insts
  4436. ....
  4437. Notes:
  4438. * `0x1000000` is the address where QEMU puts the Linux kernel at with `-kernel` in x86.
  4439. +
  4440. It can be found from:
  4441. +
  4442. ....
  4443. ./run-toolchain readelf -- -e "$(./getvar vmlinux)" | grep Entry
  4444. ....
  4445. +
  4446. TODO confirm further. If I try to break there with:
  4447. +
  4448. ....
  4449. ./run-gdb *0x1000000
  4450. ....
  4451. +
  4452. 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:
  4453. +
  4454. ....
  4455. ./run-gdb extract_kernel
  4456. ....
  4457. +
  4458. It only appears once on every log I've seen so far, checked with `grep 0x1000000 trace.txt`
  4459. +
  4460. 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.
  4461. +
  4462. 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].
  4463. * 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:
  4464. +
  4465. ....
  4466. ./run-gdb-user "$(./getvar userland_build_dir)/poweroff.out" main
  4467. ....
  4468. +
  4469. And get that from the traces, e.g. if the address is `4003a0`, then we search:
  4470. +
  4471. ....
  4472. grep -n 4003a0 trace.txt
  4473. ....
  4474. +
  4475. 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.
  4476. * to disable networking. Is replacing `init` enough?
  4477. +
  4478. --
  4479. ** https://superuser.com/questions/181254/how-do-you-boot-linux-with-networking-disabled
  4480. ** https://superuser.com/questions/684005/how-does-one-permanently-disable-gnu-linux-networking/1255015#1255015
  4481. --
  4482. +
  4483. `CONFIG_NET=n` did not significantly reduce instruction counts, so maybe replacing `init` is enough.
  4484. * gem5 simulates memory latencies. So I think that the CPU loops idle while waiting for memory, and counts will be higher.
  4485. === Linux kernel hardening
  4486. Make it harder to get hacked and easier to notice that you were, at the cost of some (small?) runtime overhead.
  4487. ==== CONFIG_FORTIFY_SOURCE
  4488. Detects buffer overflows for us:
  4489. ....
  4490. ./build-linux --config 'CONFIG_FORTIFY_SOURCE=y' --linux-build-id fortify
  4491. ./build-modules --clean
  4492. ./build-modules
  4493. ./build-buildroot
  4494. ./run --eval-busybox 'insmod /strlen_overflow.ko' --linux-build-id fortify
  4495. ....
  4496. Possible dmesg output:
  4497. ....
  4498. strlen_overflow: loading out-of-tree module taints kernel.
  4499. detected buffer overflow in strlen
  4500. ------------[ cut here ]------------
  4501. ....
  4502. followed by a trace.
  4503. 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.
  4504. TODO not always reproducible. Find a more reproducible failure. I could not observe it on:
  4505. ....
  4506. insmod /memcpy_overflow.ko
  4507. ....
  4508. Source: link:kernel_modules/strlen_overflow.c[]
  4509. Bibliography: https://www.reddit.com/r/hacking/comments/8h4qxk/what_a_buffer_overflow_in_the_linux_kernel_looks/
  4510. === User mode Linux
  4511. 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
  4512. 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.
  4513. Maybe some brave soul will send a pull request one day.
  4514. === UIO
  4515. UIO is a kernel subsystem that allows to do certain types of driver operations from userland.
  4516. This would be awesome to improve debugability and safety of kernel modules.
  4517. 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
  4518. TODO get something interesting working. I currently don't understand the behaviour very well.
  4519. TODO how to ACK interrupts? How to ensure that every interrupt gets handled separately?
  4520. TODO how to write to registers. Currently using `/dev/mem` and `lspci`.
  4521. This example should handle interrupts from userland and print a message to stdout:
  4522. ....
  4523. /uio_read.sh
  4524. ....
  4525. 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 :-)
  4526. UIO interface in a nutshell:
  4527. * blocking read / poll: waits until interrupts
  4528. * `write`: call `irqcontrol` callback. Default: 0 or 1 to enable / disable interrupts.
  4529. * `mmap`: access device memory
  4530. Sources:
  4531. * link:userland/uio_read.c[]
  4532. * link:rootfs_overlay/uio_read.sh[]
  4533. Bibliography:
  4534. * https://stackoverflow.com/questions/15286772/userspace-vs-kernel-space-driver
  4535. * https://01.org/linuxgraphics/gfx-docs/drm/driver-api/uio-howto.html
  4536. * https://stackoverflow.com/questions/7986260/linux-interrupt-handling-in-user-space
  4537. * https://yurovsky.github.io/2014/10/10/linux-uio-gpio-interrupt/
  4538. * https://github.com/bmartini/zynq-axis/blob/65a3a448fda1f0ea4977adfba899eb487201853d/dev/axis.c
  4539. * https://yurovsky.github.io/2014/10/10/linux-uio-gpio-interrupt/
  4540. * 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.
  4541. * https://stackoverflow.com/questions/49309162/interfacing-with-qemu-edu-device-via-userspace-i-o-uio-linux-driver
  4542. * userland driver stability questions:
  4543. ** https://stackoverflow.com/questions/8030758/getting-kernel-version-from-linux-kernel-module-at-runtime/45430233#45430233
  4544. ** https://stackoverflow.com/questions/37098482/how-to-build-a-linux-kernel-module-so-that-it-is-compatible-with-all-kernel-rele/45429681#45429681
  4545. ** https://liquidat.wordpress.com/2007/07/21/linux-kernel-2623-to-have-stable-userspace-driver-api/
  4546. === Linux kernel interactive stuff
  4547. [[fbcon]]
  4548. ==== Linux kernel console fun
  4549. Requires <<graphics>>.
  4550. You can also try those on the `Ctrl-Alt-F3` of your Ubuntu host, but it is much more fun inside a VM!
  4551. Stop the cursor from blinking:
  4552. ....
  4553. echo 0 > /sys/class/graphics/fbcon/cursor_blink
  4554. ....
  4555. Rotate the console 90 degrees! https://askubuntu.com/questions/237963/how-do-i-rotate-my-display-when-not-using-an-x-server
  4556. ....
  4557. echo 1 > /sys/class/graphics/fbcon/rotate
  4558. ....
  4559. Relies on: `CONFIG_FRAMEBUFFER_CONSOLE_ROTATION=y`.
  4560. Documented under: `Documentation/fb/`.
  4561. 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:
  4562. * https://unix.stackexchange.com/questions/177024/remap-keyboard-on-the-linux-console
  4563. * https://superuser.com/questions/194202/remapping-keys-system-wide-in-linux-not-just-in-x
  4564. ==== Linux kernel magic keys
  4565. Requires <<graphics>>.
  4566. Let's have some fun.
  4567. I think most are implemented under:
  4568. ....
  4569. drivers/tty
  4570. ....
  4571. TODO find all.
  4572. Scroll up / down the terminal:
  4573. ....
  4574. Shift-PgDown
  4575. Shift-PgUp
  4576. ....
  4577. Or inside `./qemu-monitor`:
  4578. ....
  4579. sendkey shift-pgup
  4580. sendkey shift-pgdown
  4581. ....
  4582. ===== Ctrl Alt Del
  4583. Run `/sbin/reboot` on guest:
  4584. ....
  4585. Ctrl-Alt-Del
  4586. ....
  4587. Enabled from our link:rootfs_overlay/etc/inittab[]:
  4588. ....
  4589. ::ctrlaltdel:/sbin/reboot
  4590. ....
  4591. Linux tries to reboot, and QEMU shutdowns due to the `-no-reboot` option which we set by default for: <<exit-emulator-on-panic>>.
  4592. Under the hood, behaviour is controlled by the `reboot` syscall:
  4593. ....
  4594. man 2 reboot
  4595. ....
  4596. `reboot` calls can set either of the these behaviours for `Ctrl-Alt-Del`:
  4597. * do a hard shutdown syscall. Set in ublibc C code with:
  4598. +
  4599. ....
  4600. reboot(RB_ENABLE_CAD)
  4601. ....
  4602. +
  4603. or from procfs with:
  4604. +
  4605. ....
  4606. echo 1 > /proc/sys/kernel/ctrl-alt-del
  4607. ....
  4608. * send a SIGINT to the init process. This is what BusyBox' init does, and it then execs the string set in `inittab`.
  4609. +
  4610. Set in uclibc C code with:
  4611. +
  4612. ....
  4613. reboot(RB_DISABLE_CAD)
  4614. ....
  4615. +
  4616. or from procfs with:
  4617. +
  4618. ....
  4619. echo 0 > /proc/sys/kernel/ctrl-alt-del
  4620. ....
  4621. Minimal example:
  4622. ....
  4623. ./run --kernel-cli 'init=/ctrl_alt_del.out' --graphic
  4624. ....
  4625. Source: link:userland/ctrl_alt_del.c[]
  4626. When you hit `Ctrl-Alt-Del` in the guest, our tiny init handles a `SIGINT` sent by the kernel and outputs to stdout:
  4627. ....
  4628. cad
  4629. ....
  4630. To map between `man 2 reboot` and the uclibc `RB_*` magic constants see:
  4631. ....
  4632. less "$(./getvar build_dir)"/uclibc-*/include/sys/reboot.h"
  4633. ....
  4634. The procfs mechanism is documented at:
  4635. ....
  4636. less linux/Documentation/sysctl/kernel.txt
  4637. ....
  4638. which says:
  4639. ....
  4640. When the value in this file is 0, ctrl-alt-del is trapped and
  4641. sent to the init(1) program to handle a graceful restart.
  4642. When, however, the value is > 0, Linux's reaction to a Vulcan
  4643. Nerve Pinch (tm) will be an immediate reboot, without even
  4644. syncing its dirty buffers.
  4645. Note: when a program (like dosemu) has the keyboard in 'raw'
  4646. mode, the ctrl-alt-del is intercepted by the program before it
  4647. ever reaches the kernel tty layer, and it's up to the program
  4648. to decide what to do with it.
  4649. ....
  4650. Bibliography:
  4651. * https://superuser.com/questions/193652/does-linux-have-a-ctrlaltdel-equivalent/1324415#1324415
  4652. * https://unix.stackexchange.com/questions/42573/meaning-and-commands-for-ctrlaltdel/444969#444969
  4653. ===== SysRq
  4654. We cannot test these actual shortcuts on QEMU since the host captures them at a lower level, but from:
  4655. ....
  4656. ./qemu-monitor
  4657. ....
  4658. we can for example crash the system with:
  4659. ....
  4660. sendkey alt-sysrq-c
  4661. ....
  4662. Same but boring because no magic key:
  4663. ....
  4664. echo c > /proc/sysrq-trigger
  4665. ....
  4666. Implemented in:
  4667. ....
  4668. drivers/tty/sysrq.c
  4669. ....
  4670. On your host, on modern systems that don't have the `SysRq` key you can do:
  4671. ....
  4672. Alt-PrtSc-space
  4673. ....
  4674. which prints a message to `dmesg` of type:
  4675. ....
  4676. 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)
  4677. ....
  4678. Individual SysRq can be enabled or disabled with the bitmask:
  4679. ....
  4680. /proc/sys/kernel/sysrq
  4681. ....
  4682. The bitmask is documented at:
  4683. ....
  4684. less linux/Documentation/admin-guide/sysrq.rst
  4685. ....
  4686. Bibliography: https://en.wikipedia.org/wiki/Magic_SysRq_key
  4687. ==== TTY
  4688. In order to play with TTYs, do this:
  4689. ....
  4690. printf '
  4691. tty2::respawn:/sbin/getty -n -L -l /loginroot.sh tty2 0 vt100
  4692. tty3::respawn:-/bin/sh
  4693. tty4::respawn:/sbin/getty 0 tty4
  4694. tty63::respawn:-/bin/sh
  4695. ::respawn:/sbin/getty -L ttyS0 0 vt100
  4696. ::respawn:/sbin/getty -L ttyS1 0 vt100
  4697. ::respawn:/sbin/getty -L ttyS2 0 vt100
  4698. # Leave one serial empty.
  4699. #::respawn:/sbin/getty -L ttyS3 0 vt100
  4700. ' >> rootfs_overlay/etc/inittab
  4701. ./build-buildroot
  4702. ./run --graphic -- \
  4703. -serial telnet::1235,server,nowait \
  4704. -serial vc:800x600 \
  4705. -serial telnet::1236,server,nowait \
  4706. ;
  4707. ....
  4708. and on a second shell:
  4709. ....
  4710. telnet localhost 1235
  4711. ....
  4712. We don't add more TTYs by default because it would spawn more processes, even if we use `askfirst` instead of `respawn`.
  4713. On the GUI, switch TTYs with:
  4714. * `Alt-Left` or `Alt-Right:` go to previous / next populated `/dev/ttyN` TTY. Skips over empty TTYs.
  4715. * `Alt-Fn`: go to the nth TTY. If it is not populated, don't go there.
  4716. * `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
  4717. 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.
  4718. Next, we also have the following shells running on the serial ports, hit enter to activate them:
  4719. * `/dev/ttyS0`: first shell that was used to run QEMU, corresponds to QEMU's `-serial mon:stdio`.
  4720. +
  4721. It would also work if we used `-serial stdio`, but:
  4722. +
  4723. --
  4724. ** `Ctrl-C` would kill QEMU instead of going to the guest
  4725. ** `Ctrl-A C` wouldn't open the QEMU console there
  4726. --
  4727. +
  4728. see also: https://stackoverflow.com/questions/49716931/how-to-run-qemu-with-nographic-and-monitor-but-still-be-able-to-send-ctrlc-to
  4729. * `/dev/ttyS1`: second shell running `telnet`
  4730. * `/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`.
  4731. although we cannot change between terminals from there.
  4732. Each populated TTY contains a "shell":
  4733. * `-/bin/sh`: goes directly into an `sh` without a login prompt.
  4734. +
  4735. 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
  4736. +
  4737. The `getty` executable however also does this operation and therefore dispenses the `-`.
  4738. * `/sbin/getty` asks for password, and then gives you an `sh`
  4739. +
  4740. We can overcome the password prompt with the `-l /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.
  4741. Identify the current TTY with the command:
  4742. ....
  4743. tty
  4744. ....
  4745. Bibliography:
  4746. * https://unix.stackexchange.com/questions/270272/how-to-get-the-tty-in-which-bash-is-running/270372
  4747. * https://unix.stackexchange.com/questions/187319/how-to-get-the-real-name-of-the-controlling-terminal
  4748. * https://unix.stackexchange.com/questions/77796/how-to-get-the-current-terminal-name
  4749. * https://askubuntu.com/questions/902998/how-to-check-which-tty-am-i-using
  4750. This outputs:
  4751. * `/dev/console` for the initial GUI terminal. But I think it is the same as `/dev/tty1`, because if I try to do
  4752. +
  4753. ....
  4754. tty1::respawn:-/bin/sh
  4755. ....
  4756. +
  4757. it makes the terminal go crazy, as if multiple processes are randomly eating up the characters.
  4758. * `/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:
  4759. +
  4760. ....
  4761. #define MAX_NR_CONSOLES 63
  4762. ....
  4763. +
  4764. in `linux/include/uapi/linux/vt.h`.
  4765. * `/dev/ttySN` for the text shells.
  4766. +
  4767. 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
  4768. +
  4769. There are only 4 serial ports, I think this is determined by QEMU. TODO check.
  4770. +
  4771. See also: https://stackoverflow.com/questions/16706423/two-instances-of-busybox-on-separate-serial-lines-ttysn
  4772. Get the TTY in bulk for all processes:
  4773. ....
  4774. /psa.sh
  4775. ....
  4776. Source: link:rootfs_overlay/psa.sh[].
  4777. The TTY appears under the `TT` section, which is enabled by `-o tty`. This shows the TTY device number, e.g.:
  4778. ....
  4779. 4,1
  4780. ....
  4781. and we can then confirm it with:
  4782. ....
  4783. ls -l /dev/tty1
  4784. ....
  4785. Next try:
  4786. ....
  4787. insmod /kthread.ko
  4788. ....
  4789. 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.
  4790. Bibliography:
  4791. * https://serverfault.com/questions/119736/how-to-enable-multiple-virtual-consoles-on-linux
  4792. * https://github.com/mirror/busybox/blob/1_28_3/examples/inittab#L60
  4793. * http://web.archive.org/web/20180117124612/http://nairobi-embedded.org/qemu_serial_port_system_console.html
  4794. ===== Start a getty from outside of init
  4795. TODO: https://unix.stackexchange.com/questions/196704/getty-start-from-command-line
  4796. TODO: how to place an `sh` directly on a TTY as well without `getty`?
  4797. If I try the exact same command that the `inittab` is doing from a regular shell after boot:
  4798. ....
  4799. /sbin/getty 0 tty1
  4800. ....
  4801. it fails with:
  4802. ....
  4803. getty: setsid: Operation not permitted
  4804. ....
  4805. The following however works:
  4806. ....
  4807. ./run --eval 'getty 0 tty1 & getty 0 tty2 & getty 0 tty3 & sleep 99999999' --graphic
  4808. ....
  4809. presumably because it is being called from `init` directly?
  4810. Outcome: `Alt-Right` cycles between three TTYs, `tty1` being the default one that appears under the boot messages.
  4811. `man 2 setsid` says that there is only one failure possibility:
  4812. ____
  4813. 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.
  4814. ____
  4815. We can get some visibility into it to try and solve the problem with:
  4816. ....
  4817. /psa.sh
  4818. ....
  4819. ===== console kernel boot parameter
  4820. Take the command described at <<tty>> and try adding the following:
  4821. * `-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.
  4822. +
  4823. Instead, the shell appears on `/dev/tty7`.
  4824. * `-e 'console=tty2'` like `/dev/tty7`, but `/dev/tty2` is broken, because we have two shells there:
  4825. ** one due to the `::respawn:-/bin/sh` entry which uses whatever `console` points to
  4826. ** another one due to the `tty2::respawn:/sbin/getty` entry we added
  4827. * `-e 'console=ttyS0'` much like `tty2`, but messages show only on serial, and the terminal is broken due to having multiple shells on it
  4828. * `-e 'console=tty1 console=ttyS0'`: boot messages show on both `tty1` and `ttyS0`, but only `S0` gets a shell because it came last
  4829. ==== CONFIG_LOGO
  4830. 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
  4831. 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.
  4832. `reset` on the terminal then kills the poor penguins.
  4833. When `CONFIG_LOGO=y` is set, the logo can be disabled at boot with:
  4834. ....
  4835. ./run --kernel-cli 'logo.nologo'
  4836. ....
  4837. * https://stackoverflow.com/questions/39872463/how-can-i-disable-the-startup-penguins-and-boot-text-on-linaro-ubuntu
  4838. * https://unix.stackexchange.com/questions/332198/centos-remove-penguin-logo-at-startup
  4839. Looks like a recompile is needed to modify the image...
  4840. * https://superuser.com/questions/736423/changing-kernel-bootsplash-image
  4841. * https://unix.stackexchange.com/questions/153975/how-to-change-boot-logo-in-linux-mint
  4842. === DRM
  4843. DRM / DRI is the new interface that supersedes `fbdev`:
  4844. ....
  4845. ./build-buildroot --config 'BR2_PACKAGE_LIBDRM=y'
  4846. ./build-userland --has-package libdrm -- libdrm_modeset
  4847. ./run --eval-busybox '/libdrm_modeset.out' --graphic
  4848. ....
  4849. Source: link:userland/libdrm_modeset.c[]
  4850. Outcome: for a few seconds, the screen that contains the terminal gets taken over by changing colors of the rainbow.
  4851. 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.
  4852. ....
  4853. ./build-buildroot --config 'BR2_PACKAGE_LIBDRM=y'
  4854. ./build-userland --has-package libdrm
  4855. ./build-buildroot
  4856. ./run --eval-busybox '/libdrm_modeset.out' --graphic
  4857. ....
  4858. <<kmscube>> however worked, which means that it must be a bug with this demo?
  4859. We set `CONFIG_DRM=y` on our default kernel configuration, and it creates one device file for each display:
  4860. ....
  4861. # ls -l /dev/dri
  4862. total 0
  4863. crw------- 1 root root 226, 0 May 28 09:41 card0
  4864. # grep 226 /proc/devices
  4865. 226 drm
  4866. # ls /sys/module/drm /sys/module/drm_kms_helper/
  4867. ....
  4868. Try creating new displays:
  4869. ....
  4870. ./run --arch aarch64 --graphic -- -device virtio-gpu-pci
  4871. ....
  4872. to see multiple `/dev/dri/cardN`, and then use a different display with:
  4873. ....
  4874. ./run --eval-busybox '/libdrm_modeset.out' --graphic
  4875. ....
  4876. Bibliography:
  4877. * https://dri.freedesktop.org/wiki/DRM/
  4878. * https://en.wikipedia.org/wiki/Direct_Rendering_Infrastructure
  4879. * https://en.wikipedia.org/wiki/Direct_Rendering_Manager
  4880. * https://en.wikipedia.org/wiki/Mode_setting KMS
  4881. Tested on: link:http://github.com/cirosantilli/linux-kernel-module-cheat/commit/93e383902ebcc03d8a7ac0d65961c0e62af9612b[93e383902ebcc03d8a7ac0d65961c0e62af9612b]
  4882. ==== kmscube
  4883. ....
  4884. ./build-buildroot --config-fragment buildroot_config/kmscube
  4885. ....
  4886. Outcome: a colored spinning cube coded in OpenGL + EGL takes over your display and spins forever: https://www.youtube.com/watch?v=CqgJMgfxjsk
  4887. 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
  4888. TODO: it is very slow, about 1FPS. I tried Buildroot master ad684c20d146b220dd04a85dbf2533c69ec8ee52 with:
  4889. ....
  4890. make qemu_x86_64_defconfig
  4891. printf "
  4892. BR2_CCACHE=y
  4893. BR2_PACKAGE_HOST_QEMU=y
  4894. BR2_PACKAGE_HOST_QEMU_LINUX_USER_MODE=n
  4895. BR2_PACKAGE_HOST_QEMU_SYSTEM_MODE=y
  4896. BR2_PACKAGE_HOST_QEMU_VDE2=y
  4897. BR2_PACKAGE_KMSCUBE=y
  4898. BR2_PACKAGE_MESA3D=y
  4899. BR2_PACKAGE_MESA3D_DRI_DRIVER_SWRAST=y
  4900. BR2_PACKAGE_MESA3D_OPENGL_EGL=y
  4901. BR2_PACKAGE_MESA3D_OPENGL_ES=y
  4902. BR2_TOOLCHAIN_BUILDROOT_CXX=y
  4903. " >> .config
  4904. ....
  4905. and the FPS was much better, I estimate something like 15FPS.
  4906. On Ubuntu 18.04 with NVIDIA proprietary drivers:
  4907. ....
  4908. sudo apt-get instll kmscube
  4909. kmscube
  4910. ....
  4911. fails with:
  4912. ....
  4913. drmModeGetResources failed: Invalid argument
  4914. failed to initialize legacy DRM
  4915. ....
  4916. See also: https://github.com/robclark/kmscube/issues/12 and https://stackoverflow.com/questions/26920835/can-egl-application-run-in-console-mode/26921287#26921287
  4917. Tested on: link:http://github.com/cirosantilli/linux-kernel-module-cheat/commit/2903771275372ccfecc2b025edbb0d04c4016930[2903771275372ccfecc2b025edbb0d04c4016930]
  4918. ==== kmscon
  4919. TODO get working.
  4920. Implements a console for <<drm>>.
  4921. The Linux kernel has a built-in fbdev console: <<fbcon,fbcon>> but not for <<drm>> it seems.
  4922. The upstream project seems dead with last commit in 2014: https://www.freedesktop.org/wiki/Software/kmscon/
  4923. 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
  4924. Haven't tested the fork on QEMU too much insanity.
  4925. ==== libdri2
  4926. TODO get working.
  4927. Looks like a more raw alternative to libdrm:
  4928. ....
  4929. ./build-buildroot --config 'BR2_PACKABE_LIBDRI2=y'
  4930. wget \
  4931. -O "$(./getvar userland_src_dir)/dri2test.c" \
  4932. https://raw.githubusercontent.com/robclark/libdri2/master/test/dri2test.c \
  4933. ;
  4934. ./build-userland
  4935. ....
  4936. but then I noticed that that example requires multiple files, and I don't feel like integrating it into our build.
  4937. When I build it on Ubuntu 18.04 host, it does not generate any executable, so I'm confused.
  4938. === Linux kernel testing
  4939. Bibliography: https://stackoverflow.com/questions/3177338/how-is-the-linux-kernel-tested
  4940. ==== LTP
  4941. Linux Test Project
  4942. https://github.com/linux-test-project/ltp
  4943. C userland test suite.
  4944. Buildroot already has a package, so it is trivial to build it:
  4945. ....
  4946. ./build-buildroot --config 'BR2_PACKAGE_LTP_TESTSUITE=y'
  4947. ....
  4948. Then try it out with:
  4949. ....
  4950. cd /usr/lib/ltp-testsuite/testcases
  4951. ./bin/write01
  4952. ....
  4953. There is a main executable `execltp` to run everything, but it depends on Python, so let's just run them manually.
  4954. TODO a large chunk of tests, the Open POSIX test suite, is disabled with a comment on Buildroot master saying build failed: https://github.com/buildroot/buildroot/blob/3f37dd7c3b5eb25a41edc6f72ba73e5a21b07e9b/package/ltp-testsuite/ltp-testsuite.mk#L13 However, both tickets mentioned there were closed, so we should try it out and patch Buildroot if it works now.
  4955. ==== stress
  4956. POSIX userland stress. Two versions:
  4957. ....
  4958. ./build-buildroot --config 'BR2_PACKAGE_STRESS=y'
  4959. ./build-buildroot --config 'BR2_PACKAGE_STRESS_NG=y'
  4960. ....
  4961. Websites:
  4962. * https://people.seas.harvard.edu/~apw/stress/
  4963. * https://github.com/ColinIanKing/stress-ng
  4964. Likely the NG one is best, but it requires `BR2_TOOLCHAIN_USES_GLIBC=y` which we don't have currently because we use uclibc... arghhhh.
  4965. `stress` usage:
  4966. ....
  4967. stress --help
  4968. stress -c 16 &
  4969. ps
  4970. ....
  4971. and notice how 16 threads were created in addition to a parent worker thread.
  4972. It just runs forever, so kill it when you get tired:
  4973. ....
  4974. kill %1
  4975. ....
  4976. `stress -c 1 -t 1` makes gem5 irresponsive for a very long time.
  4977. == QEMU
  4978. Some QEMU specific features to play with and limitations to cry over.
  4979. === Disk persistency
  4980. We disable disk persistency for both QEMU and gem5 by default, to prevent the emulator from putting the image in an unknown state.
  4981. For QEMU, this is done by passing the `snapshot` option to `-drive`, and for gem5 it is the default behaviour.
  4982. If you hack up our link:run[] script to remove that option, then:
  4983. ....
  4984. ./run --eval-busybox 'date >f;poweroff'
  4985. ....
  4986. followed by:
  4987. ....
  4988. ./run --eval-busybox 'cat f'
  4989. ....
  4990. gives the date, because `poweroff` without `-n` syncs before shutdown.
  4991. The `sync` command also saves the disk:
  4992. ....
  4993. sync
  4994. ....
  4995. When you do:
  4996. ....
  4997. ./build-buildroot
  4998. ....
  4999. the disk image gets overwritten by a fresh filesystem and you lose all changes.
  5000. 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.
  5001. Persistency is also turned off when booting from <<initrd>> with a CPIO instead of with a disk.
  5002. 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.
  5003. ==== gem5 disk persistency
  5004. TODO how to make gem5 disk writes persistent?
  5005. As of cadb92f2df916dbb47f428fd1ec4932a2e1f0f48 there are some `read_only` entries in the <<config-ini>> under cow sections, but hacking them to true did not work:
  5006. ....
  5007. diff --git a/configs/common/FSConfig.py b/configs/common/FSConfig.py
  5008. index 17498c42b..76b8b351d 100644
  5009. --- a/configs/common/FSConfig.py
  5010. +++ b/configs/common/FSConfig.py
  5011. @@ -60,7 +60,7 @@ os_types = { 'alpha' : [ 'linux' ],
  5012. }
  5013. class CowIdeDisk(IdeDisk):
  5014. - image = CowDiskImage(child=RawDiskImage(read_only=True),
  5015. + image = CowDiskImage(child=RawDiskImage(read_only=False),
  5016. read_only=False)
  5017. def childImage(self, ci):
  5018. ....
  5019. The directory of interest is `src/dev/storage`.
  5020. === gem5 qcow2
  5021. 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
  5022. This would be good to allow storing smaller sparse ext2 images locally on disk.
  5023. === Snapshot
  5024. QEMU allows us to take snapshots at any time through the monitor.
  5025. You can then restore CPU, memory and disk state back at any time.
  5026. qcow2 filesystems must be used for that to work.
  5027. To test it out, login into the VM with and run:
  5028. ....
  5029. ./run --eval-busybox 'umount /mnt/9p/*;/count.sh'
  5030. ....
  5031. On another shell, take a snapshot:
  5032. ....
  5033. ./qemu-monitor savevm my_snap_id
  5034. ....
  5035. The counting continues.
  5036. Restore the snapshot:
  5037. ....
  5038. ./qemu-monitor loadvm my_snap_id
  5039. ....
  5040. and the counting goes back to where we saved. This shows that CPU and memory states were reverted.
  5041. 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:
  5042. .....
  5043. 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'
  5044. .....
  5045. We can also verify that the disk state is also reversed. Guest:
  5046. ....
  5047. echo 0 >f
  5048. ....
  5049. Monitor:
  5050. ....
  5051. ./qemu-monitor savevm my_snap_id
  5052. ....
  5053. Guest:
  5054. ....
  5055. echo 1 >f
  5056. ....
  5057. Monitor:
  5058. ....
  5059. ./qemu-monitor loadvm my_snap_id
  5060. ....
  5061. Guest:
  5062. ....
  5063. cat f
  5064. ....
  5065. And the output is `0`.
  5066. Our setup does not allow for snapshotting while using <<initrd>>.
  5067. Bibliography: https://stackoverflow.com/questions/40227651/does-qemu-emulator-have-checkpoint-function/48724371#48724371
  5068. ==== Snapshot internals
  5069. Snapshots are stored inside the `.qcow2` images themselves.
  5070. They can be observed with:
  5071. ....
  5072. "$(./getvar host_dir)/bin/qemu-img" info "$(./getvar qcow2_file)"
  5073. ....
  5074. which after `savevm my_snap_id` and `savevm asdf` contains an output of type:
  5075. ....
  5076. image: out/x86_64/buildroot/images/rootfs.ext2.qcow2
  5077. file format: qcow2
  5078. virtual size: 512M (536870912 bytes)
  5079. disk size: 180M
  5080. cluster_size: 65536
  5081. Snapshot list:
  5082. ID TAG VM SIZE DATE VM CLOCK
  5083. 1 my_snap_id 47M 2018-04-27 21:17:50 00:00:15.251
  5084. 2 asdf 47M 2018-04-27 21:20:39 00:00:18.583
  5085. Format specific information:
  5086. compat: 1.1
  5087. lazy refcounts: false
  5088. refcount bits: 16
  5089. corrupt: false
  5090. ....
  5091. As a consequence:
  5092. * it is possible to restore snapshots across boots, since they stay on the same image the entire time
  5093. * it is not possible to use snapshots with <<initrd>> in our setup, since we don't pass `-drive` at all when initrd is enabled
  5094. === Device models
  5095. This section documents:
  5096. * how to interact with peripheral hardware device models through device drivers
  5097. * 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
  5098. For the more complex interfaces, we focus on simplified educational devices, either:
  5099. * present in the QEMU upstream:
  5100. ** <<qemu-edu>>
  5101. * added in link:https://github.com/cirosantilli/qemu[our fork of QEMU]:
  5102. ** <<pci_min>>
  5103. ** <<platform_device>>
  5104. ==== PCI
  5105. Only tested in x86.
  5106. ===== pci_min
  5107. PCI driver for our minimal `pci_min.c` QEMU fork device:
  5108. ....
  5109. ./run -- -device lkmc_pci_min
  5110. ....
  5111. then:
  5112. ....
  5113. insmod /pci_min.ko
  5114. ....
  5115. Sources:
  5116. * Kernel module: link:kernel_modules/pci_min.c[].
  5117. * QEMU device: https://github.com/cirosantilli/qemu/blob/lkmc/hw/misc/lkmc_pci_min.c
  5118. Outcome:
  5119. ....
  5120. <4>[ 10.608241] pci_min: loading out-of-tree module taints kernel.
  5121. <6>[ 10.609935] probe
  5122. <6>[ 10.651881] dev->irq = 11
  5123. lkmc_pci_min mmio_write addr = 0 val = 12345678 size = 4
  5124. <6>[ 10.668515] irq_handler irq = 11 dev = 251
  5125. lkmc_pci_min mmio_write addr = 4 val = 0 size = 4
  5126. ....
  5127. What happened:
  5128. * right at probe time, we write to a register
  5129. * our hardware model is coded such that it generates an interrupt when written to
  5130. * the Linux kernel interrupt handler write to another register, which tells the hardware to stop sending interrupts
  5131. Kernel messages and printks from inside QEMU are shown all together, to see that more clearly, run in <<qemu-graphic-mode>> instead.
  5132. 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.
  5133. Probe already does a MMIO write, which generates an IRQ and tests everything.
  5134. [[qemu-edu]]
  5135. ===== QEMU edu PCI device
  5136. Small upstream educational PCI device:
  5137. ....
  5138. /qemu_edu.sh
  5139. ....
  5140. 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
  5141. Sources:
  5142. * kernel module: link:kernel_modules/qemu_edu.c[]
  5143. * QEMU device: https://github.com/qemu/qemu/blob/v2.12.0/hw/misc/edu.c
  5144. * test script: link:rootfs_overlay/qemu_edu.sh[]
  5145. Works because we add to our default QEMU CLI:
  5146. ....
  5147. -device edu
  5148. ....
  5149. This example uses:
  5150. * the QEMU `edu` educational device, which is a minimal educational in-tree PCI example
  5151. * out `/pci.ko` kernel module, which exercises the `edu` hardware.
  5152. +
  5153. 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.
  5154. TODO exercise DMA on the kernel module. The `edu` hardware model has that feature:
  5155. * https://stackoverflow.com/questions/32592734/are-there-any-dma-driver-example-pcie-and-fpga/44716747#44716747
  5156. * https://stackoverflow.com/questions/17913679/how-to-instantiate-and-use-a-dma-driver-linux-module
  5157. ===== Manipulate PCI registers directly
  5158. In this section we will try to interact with PCI devices directly from userland without kernel modules.
  5159. First identify the PCI device with:
  5160. ....
  5161. lspci
  5162. ....
  5163. In our case for example, we see:
  5164. ....
  5165. 00:06.0 Unclassified device [00ff]: Device 1234:11e8 (rev 10)
  5166. 00:07.0 Unclassified device [00ff]: Device 1234:11e9
  5167. ....
  5168. which we identify as being `edu` and `pci_min` respectively by the magic numbers: `1234:11e?`
  5169. Alternatively, we can also do use the QEMU monitor:
  5170. ....
  5171. ./qemu-monitor info qtree
  5172. ....
  5173. which gives:
  5174. ....
  5175. dev: lkmc_pci_min, id ""
  5176. addr = 07.0
  5177. romfile = ""
  5178. rombar = 1 (0x1)
  5179. multifunction = false
  5180. command_serr_enable = true
  5181. x-pcie-lnksta-dllla = true
  5182. x-pcie-extcap-init = true
  5183. class Class 00ff, addr 00:07.0, pci id 1234:11e9 (sub 1af4:1100)
  5184. bar 0: mem at 0xfeb54000 [0xfeb54007]
  5185. dev: edu, id ""
  5186. addr = 06.0
  5187. romfile = ""
  5188. rombar = 1 (0x1)
  5189. multifunction = false
  5190. command_serr_enable = true
  5191. x-pcie-lnksta-dllla = true
  5192. x-pcie-extcap-init = true
  5193. class Class 00ff, addr 00:06.0, pci id 1234:11e8 (sub 1af4:1100)
  5194. bar 0: mem at 0xfea00000 [0xfeafffff]
  5195. ....
  5196. See also: https://serverfault.com/questions/587189/list-all-devices-emulated-for-a-vm/913622#913622
  5197. Read the configuration registers as binary:
  5198. ....
  5199. hexdump /sys/bus/pci/devices/0000:00:06.0/config
  5200. ....
  5201. Get nice human readable names and offsets of the registers and some enums:
  5202. ....
  5203. setpci --dumpregs
  5204. ....
  5205. Get the values of a given config register from its human readable name, either with either bus or device id:
  5206. ....
  5207. setpci -s 0000:00:06.0 BASE_ADDRESS_0
  5208. setpci -d 1234:11e9 BASE_ADDRESS_0
  5209. ....
  5210. Note however that `BASE_ADDRESS_0` also appears when you do:
  5211. ....
  5212. lspci -v
  5213. ....
  5214. as:
  5215. ....
  5216. Memory at feb54000
  5217. ....
  5218. Then you can try messing with that address with <<dev-mem>>:
  5219. ....
  5220. devmem 0xfeb54000 w 0x12345678
  5221. ....
  5222. which writes to the first register of our <<pci_min>> device.
  5223. The device then fires an interrupt at irq 11, which is unhandled, which leads the kernel to say you are a bad boy:
  5224. ....
  5225. lkmc_pci_min mmio_write addr = 0 val = 12345678 size = 4
  5226. <5>[ 1064.042435] random: crng init done
  5227. <3>[ 1065.567742] irq 11: nobody cared (try booting with the "irqpoll" option)
  5228. ....
  5229. followed by a trace.
  5230. Next, also try using our <<irq-ko>> IRQ monitoring module before triggering the interrupt:
  5231. ....
  5232. insmod /irq.ko
  5233. devmem 0xfeb54000 w 0x12345678
  5234. ....
  5235. 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:
  5236. ....
  5237. handler irq = 11 dev = 251
  5238. ....
  5239. ===== pciutils
  5240. There are two versions of `setpci` and `lspci`:
  5241. * a simple one from BusyBox
  5242. * 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.
  5243. ===== Introduction to PCI
  5244. The PCI standard is non-free, obviously like everything in low level: https://pcisig.com/specifications but Google gives several illegal PDF hits :-)
  5245. And of course, the best documentation available is: http://wiki.osdev.org/PCI
  5246. Like every other hardware, we could interact with PCI on x86 using only IO instructions and memory operations.
  5247. But PCI is a complex communication protocol that the Linux kernel implements beautifully for us, so let's use the kernel API.
  5248. Bibliography:
  5249. * edu device source and spec in QEMU tree:
  5250. ** https://github.com/qemu/qemu/blob/v2.7.0/hw/misc/edu.c
  5251. ** https://github.com/qemu/qemu/blob/v2.7.0/docs/specs/edu.txt
  5252. * http://www.zarb.org/~trem/kernel/pci/pci-driver.c inb outb runnable example (no device)
  5253. * LDD3 PCI chapter
  5254. * another QEMU device + module, but using a custom QEMU device:
  5255. ** https://github.com/levex/kernel-qemu-pci/blob/31fc9355161b87cea8946b49857447ddd34c7aa6/module/levpci.c
  5256. ** https://github.com/levex/kernel-qemu-pci/blob/31fc9355161b87cea8946b49857447ddd34c7aa6/qemu/hw/char/lev-pci.c
  5257. * 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
  5258. * http://nairobi-embedded.org/linux_pci_device_driver.html
  5259. ===== PCI BFD
  5260. `lspci -k` shows something like:
  5261. ....
  5262. 00:04.0 Class 00ff: 1234:11e8 lkmc_pci
  5263. ....
  5264. Meaning of the first numbers:
  5265. ....
  5266. <8:bus>:<5:device>.<3:function>
  5267. ....
  5268. Often abbreviated to BDF.
  5269. * bus: groups PCI slots
  5270. * device: maps to one slot
  5271. * function: https://stackoverflow.com/questions/19223394/what-is-the-function-number-in-pci/44735372#44735372
  5272. Sometimes a fourth number is also added, e.g.:
  5273. ....
  5274. 0000:00:04.0
  5275. ....
  5276. TODO is that the domain?
  5277. 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:
  5278. ....
  5279. k->class_id = PCI_CLASS_OTHERS
  5280. ....
  5281. ===== PCI BAR
  5282. https://stackoverflow.com/questions/30190050/what-is-base-address-register-bar-in-pcie/44716618#44716618
  5283. Each PCI device has 6 BAR IOs (base address register) as per the PCI spec.
  5284. Each BAR corresponds to an address range that can be used to communicate with the PCI.
  5285. Each BAR is of one of the two types:
  5286. * `IORESOURCE_IO`: must be accessed with `inX` and `outX`
  5287. * `IORESOURCE_MEM`: must be accessed with `ioreadX` and `iowriteX`. This is the saner method apparently, and what the edu device uses.
  5288. The length of each region is defined by the hardware, and communicated to software via the configuration registers.
  5289. The Linux kernel automatically parses the 64 bytes of standardized configuration registers for us.
  5290. QEMU devices register those regions with:
  5291. ....
  5292. memory_region_init_io(&edu->mmio, OBJECT(edu), &edu_mmio_ops, edu,
  5293. "edu-mmio", 1 << 20);
  5294. pci_register_bar(pdev, 0, PCI_BASE_ADDRESS_SPACE_MEMORY, &edu->mmio);
  5295. ....
  5296. ==== GPIO
  5297. 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.
  5298. 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
  5299. The best you can do is to hack our link:build[] script to add:
  5300. ....
  5301. HOST_QEMU_OPTS='--extra-cflags=-DDEBUG_PL061=1'
  5302. ....
  5303. 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.
  5304. Then compile with:
  5305. ....
  5306. ./build-buildroot --arch arm --config-fragment buildroot_config/gpio
  5307. ./build-linux --config-fragment linux_config/gpio
  5308. ....
  5309. then test it out with:
  5310. ....
  5311. /gpio.sh
  5312. ....
  5313. Source: link:rootfs_overlay/gpio.sh[]
  5314. Buildroot's Linux tools package provides some GPIO CLI tools: `lsgpio`, `gpio-event-mon`, `gpio-hammer`, TODO document them here.
  5315. ==== LEDs
  5316. TODO: broken when `arm` moved to `-M virt`, same as <<gpio>>.
  5317. Hack QEMU's `hw/misc/arm_sysctl.c` with a printf:
  5318. ....
  5319. static void arm_sysctl_write(void *opaque, hwaddr offset,
  5320. uint64_t val, unsigned size)
  5321. {
  5322. arm_sysctl_state *s = (arm_sysctl_state *)opaque;
  5323. switch (offset) {
  5324. case 0x08: /* LED */
  5325. printf("LED val = %llx\n", (unsigned long long)val);
  5326. ....
  5327. and then rebuild with:
  5328. ....
  5329. ./build-qemu --arch arm
  5330. ./build-linux --arch arm --config-fragment linux_config/leds
  5331. ....
  5332. But beware that one of the LEDs has a heartbeat trigger by default (specified on dts), so it will produce a lot of output.
  5333. And then activate it with:
  5334. ....
  5335. cd /sys/class/leds/versatile:0
  5336. cat max_brightness
  5337. echo 255 >brightness
  5338. ....
  5339. Relevant QEMU files:
  5340. * `hw/arm/versatilepb.c`
  5341. * `hw/misc/arm_sysctl.c`
  5342. Relevant kernel files:
  5343. * `arch/arm/boot/dts/versatile-pb.dts`
  5344. * `drivers/leds/led-class.c`
  5345. * `drivers/leds/leds-sysctl.c`
  5346. ==== platform_device
  5347. Minimal platform device example coded into the `-M versatilepb` SoC of our QEMU fork.
  5348. Using this device now requires checking out to the branch:
  5349. ....
  5350. git checkout platform-device
  5351. git submodule sync
  5352. ....
  5353. before building, it does not work on master.
  5354. 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`.
  5355. The module itself can be found at: https://github.com/cirosantilli/linux-kernel-module-cheat/blob/platform-device/kernel_modules/platform_device.c
  5356. Uses:
  5357. * `hw/misc/lkmc_platform_device.c` minimal device added in our QEMU fork to `-M versatilepb`
  5358. * 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
  5359. Expected outcome after insmod:
  5360. * QEMU reports MMIO with printfs
  5361. * IRQs are generated and handled by this module, which logs to dmesg
  5362. Without insmoding this module, try writing to the register with <<dev-mem>>:
  5363. ....
  5364. devmem 0x101e9000 w 0x12345678
  5365. ....
  5366. We can also observe the interrupt with <<dummy-irq>>:
  5367. ....
  5368. modprobe dummy-irq irq=34
  5369. insmod /platform_device.ko
  5370. ....
  5371. The IRQ number `34` was found by on the dmesg after:
  5372. ....
  5373. insmod /platform_device.ko
  5374. ....
  5375. Bibliography: https://stackoverflow.com/questions/28315265/how-to-add-a-new-device-in-qemu-source-code/44612957#44612957
  5376. ==== gem5 educational hardware models
  5377. TODO get some working!
  5378. http://gedare-csphd.blogspot.co.uk/2013/02/adding-simple-io-device-to-gem5.html
  5379. === QEMU monitor
  5380. The QEMU monitor is a terminal that allows you to send text commands to the QEMU VM: https://en.wikibooks.org/wiki/QEMU/Monitor
  5381. On another terminal, run:
  5382. ....
  5383. ./qemu-monitor
  5384. ....
  5385. or send one command such as `info qtree` and quit the monitor:
  5386. ....
  5387. ./qemu-monitor info qtree
  5388. ....
  5389. Source: link:qemu-monitor[]
  5390. `qemu-monitor` uses the `-monitor` QEMU command line option, which makes the monitor listen from a socket.
  5391. `qemu-monitor` does not support input from an stdin pipe currently, see comments on the source for rationale.
  5392. Alternatively, from text mode:
  5393. ....
  5394. Ctrl-A C
  5395. ....
  5396. and go back to the terminal with:
  5397. ....
  5398. Ctrl-A C
  5399. ....
  5400. * http://stackoverflow.com/questions/14165158/how-to-switch-to-qemu-monitor-console-when-running-with-curses
  5401. * https://superuser.com/questions/488263/how-to-switch-to-the-qemu-control-panel-with-nographics
  5402. And in graphic mode from the GUI:
  5403. ....
  5404. Ctrl-Alt ?
  5405. ....
  5406. where `?` is a digit `1`, or `2`, or, `3`, etc. depending on what else is available on the GUI: serial, parallel and frame buffer.
  5407. In general, `./qemu-monitor` is the best option, as it:
  5408. * works on both modes
  5409. * allows to use the host Bash history to re-run one off commands
  5410. * allows you to search the output of commands on your host shell even when in graphic mode
  5411. Getting everything to work required careful choice of QEMU command line options:
  5412. * https://stackoverflow.com/questions/49716931/how-to-run-qemu-with-nographic-and-monitor-but-still-be-able-to-send-ctrlc-to/49751144#49751144
  5413. * https://unix.stackexchange.com/questions/167165/how-to-pass-ctrl-c-to-the-guest-when-running-qemu-with-nographic/436321#436321
  5414. ==== QEMU monitor from guest
  5415. 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
  5416. It is also worth looking into the QEMU Guest Agent tool `qemu-gq` that can be enabled with:
  5417. ....
  5418. ./build-buildroot --config 'BR2_PACKAGE_QEMU=y'
  5419. ....
  5420. See also: https://superuser.com/questions/930588/how-to-pass-commands-noninteractively-to-running-qemu-from-the-guest-qmp-via-te
  5421. ==== QEMU monitor from GDB
  5422. 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.
  5423. Try for example:
  5424. ....
  5425. monitor help
  5426. monitor info qtree
  5427. ....
  5428. === Debug the emulator
  5429. When you start hacking QEMU or gem5, it is useful to see what is going on inside the emulator themselves.
  5430. This is of course trivial since they are just regular userland programs on the host, but we make it a bit easier with:
  5431. ....
  5432. ./run --debug-vm
  5433. ....
  5434. Then you could:
  5435. ....
  5436. break edu_mmio_read
  5437. run
  5438. ....
  5439. And in QEMU:
  5440. ....
  5441. /qemu_edu.sh
  5442. ....
  5443. Or for a faster development loop:
  5444. ....
  5445. ./run --debug-vm='-ex "break edu_mmio_read" -ex "run"'
  5446. ....
  5447. 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:
  5448. ....
  5449. sleep 10
  5450. ....
  5451. 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.
  5452. 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.
  5453. ==== Debug gem5 Python scripts
  5454. Start pdb at the first instruction:
  5455. ....
  5456. ./run --gem5 --gem5-exe-args='--pdb' --terminal
  5457. ....
  5458. Requires `--terminal` as we must be on foreground.
  5459. Alternatively, you can add to the point of the code where you want to break the usual:
  5460. ....
  5461. import ipdb; ipdb.set_trace()
  5462. ....
  5463. and then run with:
  5464. ....
  5465. ./run --gem5 --terminal
  5466. ....
  5467. TODO test PyCharm: https://stackoverflow.com/questions/51982735/writing-gem5-configuration-scripts-with-pycharm
  5468. === Tracing
  5469. QEMU can log several different events.
  5470. The most interesting are events which show instructions that QEMU ran, for which we have a helper:
  5471. ....
  5472. ./trace-boot --arch x86_64
  5473. ....
  5474. Under the hood, this uses QEMU's `-trace` option.
  5475. You can then inspect the instructions with:
  5476. ....
  5477. less "$(./getvar --arch x86_64 run_dir)/trace.txt"
  5478. ....
  5479. Get the list of available trace events:
  5480. ....
  5481. ./run --trace help
  5482. ....
  5483. Enable other specific trace events:
  5484. ....
  5485. ./run --trace trace1,trace2
  5486. ./qemu-trace2txt -a "$arch"
  5487. less "$(./getvar -a "$arch" run_dir)/trace.txt"
  5488. ....
  5489. This functionality relies on the following setup:
  5490. * `./download-dependencies --enable-trace-backends=simple`. This logs in a binary format to the trace file.
  5491. +
  5492. It makes 3x execution faster than the default trace backend which logs human readable data to stdout.
  5493. +
  5494. Logging with the default backend `log` greatly slows down the CPU, and in particular leads to this boot message:
  5495. +
  5496. ....
  5497. All QSes seen, last rcu_sched kthread activity 5252 (4294901421-4294896169), jiffies_till_next_fqs=1, root ->qsmask 0x0
  5498. swapper/0 R running task 0 1 0 0x00000008
  5499. ffff880007c03ef8 ffffffff8107aa5d ffff880007c16b40 ffffffff81a3b100
  5500. ffff880007c03f60 ffffffff810a41d1 0000000000000000 0000000007c03f20
  5501. fffffffffffffedc 0000000000000004 fffffffffffffedc ffffffff00000000
  5502. Call Trace:
  5503. <IRQ> [<ffffffff8107aa5d>] sched_show_task+0xcd/0x130
  5504. [<ffffffff810a41d1>] rcu_check_callbacks+0x871/0x880
  5505. [<ffffffff810a799f>] update_process_times+0x2f/0x60
  5506. ....
  5507. +
  5508. in which the boot appears to hang for a considerable time.
  5509. * 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/
  5510. ==== QEMU -d tracing
  5511. QEMU also has a second trace mechanism in addition to `-trace`, find out the events with:
  5512. ....
  5513. ./run -- -d help
  5514. ....
  5515. Let's pick the one that dumps executed instructions, `in_asm`:
  5516. ....
  5517. ./run --eval '/poweroff.out' -- -D out/trace.txt -d in_asm
  5518. less out/trace.txt
  5519. ....
  5520. Sample output excerpt:
  5521. ....
  5522. ----------------
  5523. IN:
  5524. 0xfffffff0: ea 5b e0 00 f0 ljmpw $0xf000:$0xe05b
  5525. ----------------
  5526. IN:
  5527. 0x000fe05b: 2e 66 83 3e 88 61 00 cmpl $0, %cs:0x6188
  5528. 0x000fe062: 0f 85 7b f0 jne 0xd0e1
  5529. ....
  5530. 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
  5531. 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.
  5532. ==== Trace source lines
  5533. We can further use Binutils' `addr2line` to get the line that corresponds to each address:
  5534. ....
  5535. ./trace-boot --arch x86_64
  5536. ./trace2line --arch x86_64
  5537. less "$(./getvar --arch x86_64 run_dir)/trace-lines.txt"
  5538. ....
  5539. The format is as follows:
  5540. ....
  5541. 39368 _static_cpu_has arch/x86/include/asm/cpufeature.h:148
  5542. ....
  5543. Where:
  5544. * `39368`: number of consecutive times that a line ran. Makes the output much shorter and more meaningful
  5545. * `_static_cpu_has`: name of the function that contains the line
  5546. * `arch/x86/include/asm/cpufeature.h:148`: file and line
  5547. This could of course all be done with GDB, but it would likely be too slow to be practical.
  5548. TODO do even more awesome offline post-mortem analysis things, such as:
  5549. * detect if we are in userspace or kernelspace. Should be a simple matter of reading the
  5550. * read kernel data structures, and determine the current thread. Maybe we can reuse / extend the kernel's GDB Python scripts??
  5551. ==== QEMU record and replay
  5552. QEMU runs are not deterministic by default, however it does support a record and replay mechanism that allows you to replay a previous run deterministically:
  5553. This awesome feature allows you to examine a single run as many times as you would like until you understand everything:
  5554. ....
  5555. # Record a run.
  5556. ./run --eval-busybox '/rand_check.out;/poweroff.out;' --record
  5557. # Replay the run.
  5558. ./run --eval-busybox '/rand_check.out;/poweroff.out;' --replay
  5559. ....
  5560. A convenient shortcut to do both at once to test the feature is:
  5561. ....
  5562. ./qemu-rr --eval-busybox '/rand_check.out;/poweroff.out;'
  5563. ....
  5564. By comparing the terminal output of both runs, we can see that they are the exact same, including things which normally differ across runs:
  5565. * timestamps of dmesg output
  5566. * <<rand_check-out>> output
  5567. 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.
  5568. Documented at: https://github.com/qemu/qemu/blob/v2.12.0/docs/replay.txt
  5569. TODO: using `-r` as above leads to a kernel warning:
  5570. ....
  5571. rcu_sched detected stalls on CPUs/tasks
  5572. ....
  5573. TODO: replay deadlocks intermittently at disk operations, last kernel message:
  5574. ....
  5575. EXT4-fs (sda): re-mounted. Opts: block_validity,barrier,user_xattr
  5576. ....
  5577. TODO replay with network gets stuck:
  5578. ....
  5579. ./qemu-rr --eval-busybox 'ifup -a;wget -S google.com;/poweroff.out;'
  5580. ....
  5581. after the message:
  5582. ....
  5583. adding dns 10.0.2.3
  5584. ....
  5585. There is explicit network support on the QEMU patches, but either it is buggy or we are not using the correct magic options.
  5586. Solved on unmerged c42634d8e3428cfa60672c3ba89cabefc720cde9 from https://github.com/ispras/qemu/tree/rr-180725
  5587. 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
  5588. Then, when I tried with <<initrd>> and no disk:
  5589. ....
  5590. ./build-buildroot --arch aarch64 -i
  5591. ./qemu-rr --arch aarch64 --eval-busybox '/rand_check.out;/poweroff.out;' -i
  5592. ....
  5593. QEMU crashes with:
  5594. ....
  5595. ERROR:replay/replay-time.c:49:replay_read_clock: assertion failed: (replay_file && replay_mutex_locked())
  5596. ....
  5597. 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`?
  5598. Solved on unmerged c42634d8e3428cfa60672c3ba89cabefc720cde9 from https://github.com/ispras/qemu/tree/rr-180725
  5599. ===== QEMU reverse debugging
  5600. TODO get working.
  5601. 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[]:
  5602. ....
  5603. ./run --eval-busybox '/rand_check.out;/poweroff.out;' --record
  5604. ./run --eval-busybox '/rand_check.out;/poweroff.out;' --replay --debug-guest
  5605. ....
  5606. On another shell:
  5607. ....
  5608. ./run-gdb start_kernel
  5609. ....
  5610. In GDB:
  5611. ....
  5612. n
  5613. n
  5614. n
  5615. n
  5616. reverse-continue
  5617. ....
  5618. and we are back at `start_kernel`
  5619. ==== QEMU trace multicore
  5620. TODO: is there any way to distinguish which instruction runs on each core? Doing:
  5621. ....
  5622. ./run --arch x86_64 --cpus 2 --eval '/poweroff.out' --trace exec_tb
  5623. ./qemu-trace2txt
  5624. ....
  5625. just appears to output both cores intertwined without any clear differentiation.
  5626. ==== QEMU trace decode instructions
  5627. TODO: is is possible to show which instructions ran at each point in time, in addition to the address of the instruction with `exec_tb` shows? Hopefully dissembled, not just the instruction memory.
  5628. 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
  5629. Memory access on vanilla seem impossible due to optimizations that QEMU does:
  5630. * https://lists.gnu.org/archive/html/qemu-devel/2015-06/msg07479.html
  5631. * https://lists.gnu.org/archive/html/qemu-devel/2014-04/msg02856.html
  5632. * https://lists.gnu.org/archive/html/qemu-devel/2012-08/msg03057.html
  5633. ==== gem5 tracing
  5634. gem5 unlike QEMU is deterministic by default without needing to replay traces
  5635. But it also provides a tracing mechanism documented at: link:http://www.gem5.org/Trace_Based_Debugging[] to allow easily inspecting certain aspects of the system:
  5636. ....
  5637. ./run --arch aarch64 --eval 'm5 exit' --gem5 --trace Exec
  5638. less "$(./getvar --arch aarch64 run_dir)/trace.txt"
  5639. ....
  5640. List all available debug flags:
  5641. ....
  5642. ./run --arch aarch64 --gem5-exe-args='--debug-help' --gem5
  5643. ....
  5644. but to understand most of them you have to look at the source code:
  5645. ....
  5646. less "$(./getvar gem5_src_dir)/src/cpu/SConscript"
  5647. less "$(./getvar gem5_src_dir)/src/cpu/exetrace.cc"
  5648. ....
  5649. As can be seen on the `Sconstruct`, `Exec` is just an alias that enables a set of flags.
  5650. Be warned, the trace is humongous, at 16Gb.
  5651. 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.
  5652. Enabling tracing made the runtime about 4x slower on the <<p51>>, with or without `.gz` compression.
  5653. The output format is of type:
  5654. ....
  5655. 25007000: system.cpu T0 : @start_kernel : stp
  5656. 25007000: system.cpu T0 : @start_kernel.0 : addxi_uop ureg0, sp, #-112 : IntAlu : D=0xffffff8008913f90
  5657. 25007500: system.cpu T0 : @start_kernel.1 : strxi_uop x29, [ureg0] : MemWrite : D=0x0000000000000000 A=0xffffff8008913f90
  5658. 25008000: system.cpu T0 : @start_kernel.2 : strxi_uop x30, [ureg0, #8] : MemWrite : D=0x0000000000000000 A=0xffffff8008913f98
  5659. 25008500: system.cpu T0 : @start_kernel.3 : addxi_uop sp, ureg0, #0 : IntAlu : D=0xffffff8008913f90
  5660. ....
  5661. There are two types of lines:
  5662. * full instructions, as the first line. Only shown if the `ExecMacro` flag is given.
  5663. * 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.
  5664. Breakdown:
  5665. * `25007500`: time count in some unit. Note how the microops execute at further timestamps.
  5666. * `system.cpu`: distinguishes between CPUs when there are more than one
  5667. * `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?
  5668. * `@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`.
  5669. * `.1` as in `@start_kernel.1`: index of the microop
  5670. * `stp`: instruction disassembly. Seems to use `.isa` files dispersed per arch, which is an in house format: http://gem5.org/ISA_description_system
  5671. * `strxi_uop x29, [ureg0]`: microop disassembly.
  5672. * `MemWrite : D=0x0000000000000000 A=0xffffff8008913f90`: a memory write microop:
  5673. ** `D` stands for data, and represents the value that was written to memory or to a register
  5674. ** `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.
  5675. The best way to verify all of this is to write some <<baremetal,baremetal code>>
  5676. Trace the source lines just like <<trace-source-lines,for QEMU>> with:
  5677. ....
  5678. ./trace-boot --arch aarch64 --gem5
  5679. ./trace2line --arch aarch64 --gem5
  5680. less "$(./getvar --arch aarch64 run_dir)/trace-lines.txt"
  5681. ....
  5682. 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?
  5683. === QEMU GUI is unresponsive
  5684. 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.
  5685. We have not managed to track this problem down yet, but the following workaround always works:
  5686. ....
  5687. Ctrl-Shift-U
  5688. Ctrl-C
  5689. root
  5690. ....
  5691. This started happening when we switched to building QEMU through Buildroot, and has not been observed on later Ubuntu.
  5692. Using text mode is another workaround if you don't need GUI features.
  5693. == gem5
  5694. Getting started at: <<gem5-buildroot-setup>>.
  5695. === gem5 vs QEMU
  5696. * advantages of gem5:
  5697. ** 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:
  5698. +
  5699. --
  5700. *** do much more realistic performance benchmarking with it, which makes absolutely no sense in QEMU, which is purely functional
  5701. *** make certain functional observations that are not possible in QEMU, e.g.:
  5702. **** 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.
  5703. **** spectre / meltdown:
  5704. ***** https://www.mail-archive.com/gem5-users@gem5.org/msg15319.html
  5705. ***** https://github.com/jlpresearch/gem5/tree/spectre-test
  5706. --
  5707. +
  5708. It is not of course truly cycle accurate, as that:
  5709. +
  5710. --
  5711. ** 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[]
  5712. ** would make the simulation even slower TODO confirm, by how much
  5713. --
  5714. +
  5715. but the approximation is reasonable.
  5716. +
  5717. 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.
  5718. ** 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
  5719. ** gem5 ARM at least appears to implement more low level CPU functionality than QEMU, e.g. QEMU only added EL2 in 2018, and EL3 is yet unimplemented: https://stackoverflow.com/questions/42824706/qemu-system-aarch64-entering-el1-when-emulating-a53-power-up gem5 `fs.py` can enable EL3 with `-V` and EL2 with `--enable-security-extensions`
  5720. * disadvantage of gem5: slower than QEMU, see: <<benchmark-linux-kernel-boot>>
  5721. +
  5722. This implies that the user base is much smaller, since no Android devs.
  5723. +
  5724. 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:
  5725. +
  5726. --
  5727. ** the documentation is more scarce
  5728. ** it takes longer to support new hardware features
  5729. --
  5730. +
  5731. Well, not that AOSP is that much better anyways.
  5732. * not sure: gem5 has BSD license while QEMU has GPL
  5733. +
  5734. This suits chip makers that want to distribute forks with secret IP to their customers.
  5735. +
  5736. On the other hand, the chip makers tend to upstream less, and the project becomes more crappy in average :-)
  5737. === gem5 run benchmark
  5738. OK, this is why we used gem5 in the first place, performance measurements!
  5739. Let's see how many cycles https://en.wikipedia.org/wiki/Dhrystone[Dhrystone], which Buildroot provides, takes for a few different input parameters.
  5740. First build Dhrystone into the root filesystem:
  5741. ....
  5742. ./build-buildroot --config 'BR2_PACKAGE_DHRYSTONE=y'
  5743. ....
  5744. Then, a flexible setup is demonstrated at:
  5745. ....
  5746. ./gem5-bench-dhrystone
  5747. cat out/gem5-bench-dhrystone.txt
  5748. ....
  5749. Source: link:gem5-bench-dhrystone[]
  5750. Sample output:
  5751. ....
  5752. n cycles
  5753. 1000 12898577
  5754. 10000 23441629
  5755. 100000 128428617
  5756. ....
  5757. so as expected, the Dhrystone run with a larger input parameter `100000` took more cycles than the ones with smaller input parameters.
  5758. The `gem5-stats` commands output the approximate number of CPU cycles it took Dhrystone to run.
  5759. Another interesting example can be found at: link:gem5-bench-cache[].
  5760. A more naive and simpler to understand approach would be a direct:
  5761. ....
  5762. ./run --arch aarch64 --gem5 --eval 'm5 checkpoint;m5 resetstats;dhrystone 10000;m5 exit'
  5763. ....
  5764. 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>>.
  5765. Now you can play a fun little game with your friends:
  5766. * pick a computational problem
  5767. * make a program that solves the computation problem, and outputs output to stdout
  5768. * write the code that runs the correct computation in the smallest number of cycles possible
  5769. To find out why your program is slow, a good first step is to have a look at <<stats-txt>> file.
  5770. ==== Skip extra benchmark instructions
  5771. A few imperfections of our <<gem5-run-benchmark,benchmarking method>> are:
  5772. * 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
  5773. * 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?
  5774. Solutions to these problems include:
  5775. * modify benchmark code with instrumentation directly, see <<m5ops-instructions>> for an example.
  5776. * monitor known addresses TODO possible? Create an example.
  5777. 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
  5778. Those problems should be insignificant if the benchmark runs for long enough however.
  5779. ==== gem5 system parameters
  5780. Besides optimizing a program for a given CPU setup, chip developers can also do the inverse, and optimize the chip for a given benchmark!
  5781. The rabbit hole is likely deep, but let's scratch a bit of the surface.
  5782. ===== Number of cores
  5783. ....
  5784. ./run --arch arm --cpus 2 --gem5
  5785. ....
  5786. Check with:
  5787. ....
  5788. cat /proc/cpuinfo
  5789. getconf _NPROCESSORS_CONF
  5790. ....
  5791. ====== gem5 arm more than 8 cores
  5792. https://stackoverflow.com/questions/50248067/how-to-run-a-gem5-arm-aarch64-full-system-simulation-with-fs-py-with-more-than-8
  5793. ===== gem5 cache size
  5794. https://stackoverflow.com/questions/49624061/how-to-run-gem5-simulator-in-fs-mode-without-cache/49634544#49634544
  5795. A quick `+./run --gem5 -- -h+` leads us to the options:
  5796. ....
  5797. --caches
  5798. --l1d_size=1024
  5799. --l1i_size=1024
  5800. --l2cache
  5801. --l2_size=1024
  5802. --l3_size=1024
  5803. ....
  5804. But keep in mind that it only affects benchmark performance of the most detailed CPU types:
  5805. [options="header"]
  5806. |===
  5807. |arch |CPU type |caches used
  5808. |X86
  5809. |`AtomicSimpleCPU`
  5810. |no
  5811. |X86
  5812. |`DerivO3CPU`
  5813. |?*
  5814. |ARM
  5815. |`AtomicSimpleCPU`
  5816. |no
  5817. |ARM
  5818. |`HPI`
  5819. |yes
  5820. |===
  5821. {empty}*: couldn't test because of:
  5822. * https://stackoverflow.com/questions/49011096/how-to-switch-cpu-models-in-gem5-after-restoring-a-checkpoint-and-then-observe-t
  5823. Cache sizes can in theory be checked with the methods described at: link:https://superuser.com/questions/55776/finding-l2-cache-size-in-linux[]:
  5824. ....
  5825. getconf -a | grep CACHE
  5826. lscpu
  5827. cat /sys/devices/system/cpu/cpu0/cache/index2/size
  5828. ....
  5829. but for some reason the Linux kernel is not seeing the cache sizes:
  5830. * https://stackoverflow.com/questions/49008792/why-doesnt-the-linux-kernel-see-the-cache-sizes-in-the-gem5-emulator-in-full-sy
  5831. * http://gem5-users.gem5.narkive.com/4xVBlf3c/verify-cache-configuration
  5832. Behaviour breakdown:
  5833. * arm QEMU and gem5 (both `AtomicSimpleCPU` or `HPI`), x86 gem5: `/sys` files don't exist, and `getconf` and `lscpu` value empty
  5834. * x86 QEMU: `/sys` files exist, but `getconf` and `lscpu` values still empty
  5835. So we take a performance measurement approach instead:
  5836. ....
  5837. ./gem5-bench-cache --arch aarch64
  5838. cat "$(./getvar --arch aarch64 run_dir)/bench-cache.txt"
  5839. ....
  5840. which gives:
  5841. ....
  5842. cmd ./run --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
  5843. time 23.82
  5844. exit_status 0
  5845. cycles 93284622
  5846. instructions 4393457
  5847. cmd ./run --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
  5848. time 14.91
  5849. exit_status 0
  5850. cycles 10128985
  5851. instructions 4211458
  5852. cmd ./run --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
  5853. time 51.87
  5854. exit_status 0
  5855. cycles 188803630
  5856. instructions 12401336
  5857. cmd ./run --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
  5858. time 35.35
  5859. exit_status 0
  5860. cycles 20715757
  5861. instructions 12192527
  5862. cmd ./run --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
  5863. time 339.07
  5864. exit_status 0
  5865. cycles 1176559936
  5866. instructions 94222791
  5867. cmd ./run --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
  5868. time 240.37
  5869. exit_status 0
  5870. cycles 125666679
  5871. instructions 91738770
  5872. ....
  5873. We make the following conclusions:
  5874. * 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?
  5875. * 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.
  5876. ===== gem5 memory latency
  5877. TODO These look promising:
  5878. ....
  5879. --list-mem-types
  5880. --mem-type=MEM_TYPE
  5881. --mem-channels=MEM_CHANNELS
  5882. --mem-ranks=MEM_RANKS
  5883. --mem-size=MEM_SIZE
  5884. ....
  5885. TODO: now to verify this with the Linux kernel? Besides raw performance benchmarks.
  5886. ===== Memory size
  5887. ....
  5888. ./run --arch arm --memory 512M
  5889. ....
  5890. and verify inside the guest with:
  5891. ....
  5892. free -m
  5893. ....
  5894. ===== gem5 disk and network latency
  5895. TODO These look promising:
  5896. ....
  5897. --ethernet-linkspeed
  5898. --ethernet-linkdelay
  5899. ....
  5900. and also: `gem5-dist`: https://publish.illinois.edu/icsl-pdgem5/
  5901. ===== gem5 clock frequency
  5902. Clock frequency: TODO how does it affect performance in benchmarks?
  5903. ....
  5904. ./run --arch aarch64 --gem5 -- --cpu-clock 10000000
  5905. ....
  5906. Check with:
  5907. ....
  5908. m5 resetstats
  5909. sleep 10
  5910. m5 dumpstats
  5911. ....
  5912. and then:
  5913. ....
  5914. ./gem5-stat --arch aarch64
  5915. ....
  5916. TODO: why doesn't this exist:
  5917. ....
  5918. ls /sys/devices/system/cpu/cpu0/cpufreq
  5919. ....
  5920. ==== Interesting benchmarks
  5921. Buildroot built-in libraries, mostly under Libraries > Other:
  5922. * Armadillo `C++`: linear algebra
  5923. * fftw: Fourier transform
  5924. * Flann
  5925. * GSL: various
  5926. * liblinear
  5927. * libspacialindex
  5928. * libtommath
  5929. * qhull
  5930. There are not yet enabled, but it should be easy to so, see: <<add-new-buildroot-packages>>
  5931. ===== BST vs heap
  5932. https://stackoverflow.com/questions/6147242/heap-vs-binary-search-tree-bst/29548834#29548834
  5933. Usage:
  5934. ....
  5935. ./run \
  5936. --arch aarch64 \
  5937. --eval-busybox '/gem5.sh' \
  5938. --gem5 \
  5939. --gem5-readfile '/bst_vs_heap.out' \
  5940. ;
  5941. ./bst-vs-heap --arch aarch64 --gem5 > bst_vs_heap.dat
  5942. ....
  5943. and then feed `bst_vs_heap.dat` into: https://github.com/cirosantilli/cpp-cheat/blob/9d0f77792fc8e55b20b6ee32018761ef3c5a3f2f/cpp/interactive/bst_vs_heap.gnuplot
  5944. Sources:
  5945. * link:bst-vs-heap[]
  5946. * link:userland/bst_vs_heap.cpp[]
  5947. ===== OpenMP
  5948. Implemented by GCC itself, so just a toolchain configuration, no external libs, and we enable it by default:
  5949. ....
  5950. /openmp.out
  5951. ....
  5952. Source: link:userland/openmp.c[]
  5953. ===== BLAS
  5954. Buildroot supports it, which makes everything just trivial:
  5955. ....
  5956. ./build-buildroot --config 'BR2_PACKAGE_OPENBLAS=y'
  5957. ./build-userland --has-package openblas -- openblas_hello
  5958. ./run --eval-busybox '/openblas_hello.out; echo $?'
  5959. ....
  5960. Outcome: the test passes:
  5961. ....
  5962. 0
  5963. ....
  5964. Source: link:userland/openblas.c[]
  5965. The test performs a general matrix multiplication:
  5966. ....
  5967. | 1.0 -3.0 | | 1.0 2.0 1.0 | | 0.5 0.5 0.5 | | 11.0 - 9.0 5.0 |
  5968. 1 * | 2.0 4.0 | * | -3.0 4.0 -1.0 | + 2 * | 0.5 0.5 0.5 | = | - 9.0 21.0 -1.0 |
  5969. | 1.0 -1.0 | | 0.5 0.5 0.5 | | 5.0 - 1.0 3.0 |
  5970. ....
  5971. This can be deduced from the Fortran interfaces at
  5972. ....
  5973. less "$(./getvar build_dir)"/openblas-*/reference/dgemmf.f
  5974. ....
  5975. which we can map to our call as:
  5976. ....
  5977. C := alpha*op( A )*op( B ) + beta*C,
  5978. SUBROUTINE DGEMMF( TRANA, TRANB, M,N,K, ALPHA,A,LDA,B,LDB,BETA,C,LDC)
  5979. cblas_dgemm( CblasColMajor, CblasNoTrans, CblasTrans,3,3,2 ,1, A,3, B,3, 2 ,C,3 );
  5980. ....
  5981. ===== Eigen
  5982. Header only linear algebra library with a mainline Buildroot package:
  5983. ....
  5984. ./build-buildroot --config 'BR2_PACKAGE_EIGEN=y'
  5985. ./build-userland --has-package eigen -- eigen_hello
  5986. ....
  5987. Just create an array and print it:
  5988. ....
  5989. ./run --eval-busybox '/eigen_hello.out'
  5990. ....
  5991. Output:
  5992. ....
  5993. 3 -1
  5994. 2.5 1.5
  5995. ....
  5996. Source: link:userland/eigen_hello.cpp[]
  5997. This example just creates a matrix and prints it out.
  5998. Tested on: link:http://github.com/cirosantilli/linux-kernel-module-cheat/commit/a4bdcf102c068762bb1ef26c591fcf71e5907525[a4bdcf102c068762bb1ef26c591fcf71e5907525]
  5999. ===== PARSEC benchmark
  6000. 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.
  6001. There are two ways to run PARSEC with this repo:
  6002. * <<parsec-benchmark-without-parsecmgmt,without `pasecmgmt`>>, most likely what you want
  6003. * <<parsec-benchmark-with-parsecmgmt,with `pasecmgmt`>>
  6004. ====== PARSEC benchmark without parsecmgmt
  6005. ....
  6006. ./download-dependencies --gem5 --parsec-benchmark
  6007. ./build-buildroot --arch arm --config 'BR2_PACKAGE_PARSEC_BENCHMARK=y'
  6008. ./run --arch arm --gem5
  6009. ....
  6010. Once inside the guest, launch one of the `test` input sized benchmarks manually as in:
  6011. ....
  6012. cd /parsec/ext/splash2x/apps/fmm/run
  6013. ../inst/arm-linux.gcc/bin/fmm 1 < input_1
  6014. ....
  6015. To find run out how to run many of the benchmarks, have a look at the `test.sh` script of the `parse-benchmark` repo.
  6016. From the guest, you can also run it as:
  6017. ....
  6018. cd /parsec
  6019. ./test.sh
  6020. ....
  6021. but this might be a bit time consuming in gem5.
  6022. ====== PARSEC change the input size
  6023. Running a benchmark of a size different than `test`, e.g. `simsmall`, requires a rebuild with:
  6024. ....
  6025. ./build-buildroot \
  6026. --arch arm \
  6027. --config 'BR2_PACKAGE_PARSEC_BENCHMARK=y' \
  6028. --config 'BR2_PACKAGE_PARSEC_BENCHMARK_INPUT_SIZE="simsmall"' \
  6029. -- parsec-benchmark-reconfigure \
  6030. ;
  6031. ....
  6032. Large input may also require tweaking:
  6033. * <<br2_target_rootfs_ext2_size>> if the unpacked inputs are large
  6034. * <<memory-size>>, unless you want to meet the OOM killer, which is admittedly kind of fun
  6035. `test.sh` only contains the run commands for the `test` size, and cannot be used for `simsmall`.
  6036. 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:
  6037. ....
  6038. 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
  6039. ....
  6040. and then tweak the command found in `test.sh` accordingly.
  6041. 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`).
  6042. The rebuild is required because we unpack input files on the host.
  6043. Separating input sizes also allows to create smaller images when only running the smaller benchmarks.
  6044. 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!
  6045. One option would be to do that inside the guest with QEMU.
  6046. Also, we can't generate all input sizes at once, because many of them have the same name and would overwrite one another...
  6047. PARSEC simply wasn't designed with non native machines in mind...
  6048. ====== PARSEC benchmark with parsecmgmt
  6049. Most users won't want to use this method because:
  6050. * running the `parsecmgmt` Bash scripts takes forever before it ever starts running the actual benchmarks on gem5
  6051. +
  6052. Running on QEMU is feasible, but not the main use case, since QEMU cannot be used for performance measurements
  6053. * 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)
  6054. It would be awesome if it were possible to use this method, since this is what Parsec supports officially, and so:
  6055. * you don't have to dig into what raw command to run
  6056. * there is an easy way to run all the benchmarks in one go to test them out
  6057. * you can just run any of the benchmarks that you want
  6058. but it simply is not feasible in gem5 because it takes too long.
  6059. If you still want to run this, try it out with:
  6060. ....
  6061. ./build-buildroot \
  6062. --arch aarch64 \
  6063. --config 'BR2_PACKAGE_PARSEC_BENCHMARK=y' \
  6064. --config 'BR2_PACKAGE_PARSEC_BENCHMARK_PARSECMGMT=y' \
  6065. --config 'BR2_TARGET_ROOTFS_EXT2_SIZE="3G"' \
  6066. -- parsec-benchmark-reconfigure \
  6067. ;
  6068. ....
  6069. And then you can run it just as you would on the host:
  6070. ....
  6071. cd /parsec/
  6072. bash
  6073. . env.sh
  6074. parsecmgmt -a run -p splash2x.fmm -i test
  6075. ....
  6076. ====== PARSEC uninstall
  6077. 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:
  6078. ....
  6079. rm -rf \
  6080. "$(./getvar buildroot_download_dir)"/parsec-* \
  6081. "$(./getvar buildroot_build_dir)"/build/parsec-* \
  6082. "$(./getvar buildroot_build_dir)"/build/packages-file-list.txt \
  6083. "$(./getvar buildroot_build_dir)"/images/rootfs.* \
  6084. "$(./getvar buildroot_build_dir)"/target/parsec-* \
  6085. ;
  6086. ./build-buildroot --arch arm
  6087. ....
  6088. ====== PARSEC benchmark hacking
  6089. If you end up going inside link:submodules/parsec-benchmark[] to hack up the benchmark (you will!), these tips will be helpful.
  6090. 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.
  6091. A few workarounds are:
  6092. * develop in host first as much as you can. Our PARSEC fork supports it.
  6093. +
  6094. If you do this, don't forget to do a:
  6095. +
  6096. ....
  6097. cd "$(./getvar parsec_src_dir)"
  6098. git clean -xdf .
  6099. ....
  6100. before going for the cross compile build.
  6101. +
  6102. * patch Buildroot to work well, and keep cross compiling all the way. This should be totally viable, and we should do it.
  6103. +
  6104. Don't forget to explicitly rebuild PARSEC with:
  6105. +
  6106. ....
  6107. ./build-buildroot \
  6108. --arch arm \
  6109. --config 'BR2_PACKAGE_PARSEC_BENCHMARK=y' \
  6110. -- parsec-benchmark-reconfigure \
  6111. ;
  6112. ....
  6113. +
  6114. You may also want to test if your patches are still functionally correct inside of QEMU first, which is a faster emulator.
  6115. * 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
  6116. === gem5 kernel command line parameters
  6117. Analogous <<kernel-command-line-parameters,to QEMU>>:
  6118. ....
  6119. ./run --arch arm --kernel-cli 'init=/poweroff.out' --gem5
  6120. ....
  6121. Internals: when we give `--command-line=` to gem5, it overrides default command lines, including some mandatory ones which are required to boot properly.
  6122. Our run script hardcodes the require options in the default `--command-line` and appends extra options given by `-e`.
  6123. To find the default options in the first place, we removed `--command-line` and ran:
  6124. ....
  6125. ./run --arch arm --gem5
  6126. ....
  6127. and then looked at the line of the Linux kernel that starts with:
  6128. ....
  6129. Kernel command line:
  6130. ....
  6131. [[gem5-gdb]]
  6132. === gem5 GDB step debug
  6133. ==== gem5 GDB step debug kernel
  6134. Analogous <<gdb,to QEMU>>, on the first shell:
  6135. ....
  6136. ./run --arch arm --debug-guest --gem5
  6137. ....
  6138. On the second shell:
  6139. ....
  6140. ./run-gdb --arch arm --gem5
  6141. ....
  6142. On a third shell:
  6143. ....
  6144. ./gem5-shell
  6145. ....
  6146. When you want to break, just do a `Ctrl-C` on GDB shell, and then `continue`.
  6147. 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>>.
  6148. ===== gem5 GDB step debug kernel aarch64
  6149. TODO: GDB fails with:
  6150. ....
  6151. Reading symbols from vmlinux...done.
  6152. Remote debugging using localhost:7000
  6153. Remote 'g' packet reply is too long: 000000000000000090a4f90fc0ffffff4875450ec0ffffff01000000000000000100000000000000000000000000000001000000000000000000000000000000ffffffffffffffff646d60616b64fffe7f7f7f7f7f7f7f7f0101010101010101300000000000000000000000ffffffff48454422207d2c2017162f21262820160100000000000000070000000000000001000000000000004075450ec0ffffffc073450ec0ffffff82080000000000004075450ec0ffffff8060f90fc0ffffffc073450ec0fffffff040900880ffffff40ab400ec0ffffff586d900880ffffff0068a20ec0ffffff903b010880ffffffc8ff210880ffffff903b010880ffffffccff210880ffffff050000200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
  6154. ....
  6155. and gem5 says:
  6156. ....
  6157. 4107766500: system.remote_gdb: remote gdb attached
  6158. warn: Couldn't read data from debugger.
  6159. 4107767500: system.remote_gdb: remote gdb detached
  6160. ....
  6161. I've also tried the fix at: https://stackoverflow.com/questions/27411621/remote-g-packet-reply-is-too-long-aarch64-arm64 by adding to the link:run-gdb[] script:
  6162. ....
  6163. -ex 'set tdesc filename out/aarch64/buildroot/build/gdb-7.11.1/./gdb/features/aarch64.xml'
  6164. ....
  6165. but it did not help.
  6166. https://www.mail-archive.com/gem5-users@gem5.org/msg15383.html
  6167. ==== gem5 GDB step debug userland process
  6168. We are unable to use `gdbserver` because of networking: <<gem5-host-to-guest-networking>>
  6169. The alternative is to do as in <<gdb-step-debug-userland-processes>>.
  6170. First make sure that for your arch the kernel debugging on the given target works for the architecture: <<gem5-gdb>>, on which we rely. When we last tested, this was not the case for aarch64: <<gem5-gdb-step-debug-kernel-aarch64>>
  6171. Next, follow the exact same steps explained at <<gdb-step-debug-userland-non-init-without--d>>, but passing `-g` to every command as usual.
  6172. But then TODO (I'll still go crazy one of those days): for `arm`, while debugging `/myinsmod.out /hello.ko`, after then line:
  6173. ....
  6174. 23 if (argc < 3) {
  6175. 24 params = "";
  6176. ....
  6177. 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.
  6178. TODO:
  6179. ....
  6180. ./run-gdb-user --arch arm --gem5 gem5-1.0/gem5/util/m5/m5 main
  6181. ....
  6182. breaks when `m5` is run on guest, but does not show the source code.
  6183. === gem5 checkpoint
  6184. 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.
  6185. Documentation: http://gem5.org/Checkpoints
  6186. ....
  6187. ./run --arch arm --gem5
  6188. ....
  6189. In the guest, wait for the boot to end and run:
  6190. ....
  6191. m5 checkpoint
  6192. ....
  6193. where <<m5>> is a guest utility present inside the gem5 tree which we cross-compiled and installed into the guest.
  6194. To restore the checkpoint, kill the VM and run:
  6195. ....
  6196. ./run --arch arm --gem5 --gem5-restore 1
  6197. ....
  6198. The `--gem5-restore` option restores the checkpoint that was created most recently.
  6199. Let's create a second checkpoint to see how it works, in guest:
  6200. ....
  6201. date >f
  6202. m5 checkpoint
  6203. ....
  6204. Kill the VM, and try it out:
  6205. ....
  6206. ./run --arch arm --gem5 --gem5-restore 1
  6207. ....
  6208. Here we use `--gem5-restore 1` again, since the second snapshot we took is now the most recent one
  6209. Now in the guest:
  6210. ....
  6211. cat f
  6212. ....
  6213. 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.
  6214. If you automate things with <<kernel-command-line-parameters>> as in:
  6215. ....
  6216. ./run --arch arm --eval 'm5 checkpoint;m5 resetstats;dhrystone 1000;m5 exit' --gem5
  6217. ....
  6218. Then there is no need to pass the kernel command line again to gem5 for replay:
  6219. ....
  6220. ./run --arch arm --gem5 --gem5-restore 1
  6221. ....
  6222. since boot has already happened, and the parameters are already in the RAM of the snapshot.
  6223. ==== gem5 checkpoint internals
  6224. Checkpoints are stored inside the <<m5out-directory>> at:
  6225. ....
  6226. "$(./getvar --gem5 run_dir)/m5out/cpt.<checkpoint-time>"
  6227. ....
  6228. where `<checkpoint-time>` is the cycle number at which the checkpoint was taken.
  6229. `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
  6230. 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.
  6231. Therefore, just use our superior `--gem5-restore` flag, which uses directory timestamps to determine which checkpoint you created most recently.
  6232. 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.
  6233. [[gem5-restore-new-script]]
  6234. ==== gem5 checkpoint restore and run a different script
  6235. You want to automate running several tests from a single pristine post-boot state.
  6236. The problem is that boot takes forever, and after the checkpoint, the memory and disk states are fixed, so you can't for example:
  6237. * hack up an existing rc script, since the disk is fixed
  6238. * inject new kernel boot command line options, since those have already been put into memory by the bootloader
  6239. There is however a few loopholes, <<m5-readfile>> being the simplest, as it reads whatever is present on the host.
  6240. So we can do it like:
  6241. ....
  6242. # Boot, checkpoint and exit.
  6243. printf 'echo "setup run";m5 exit' > "$(./getvar gem5_readfile)"
  6244. ./run --gem5 --eval 'm5 checkpoint;m5 readfile > a.sh;sh a.sh'
  6245. # Restore and run the first benchmark.
  6246. printf 'echo "first benchmark";m5 exit' > "$(./getvar gem5_readfile)"
  6247. ./run --gem5 --gem5-restore 1
  6248. # Restore and run the second benchmark.
  6249. printf 'echo "second benchmark";m5 exit' > "$(./getvar gem5_readfile)"
  6250. ./run --gem5 --gem5-restore 1
  6251. # If something weird happened, create an interactive shell to examine the system.
  6252. printf 'sh' > "$(./getvar gem5_readfile)"
  6253. ./run --gem5 --gem5-restore 1
  6254. ....
  6255. Since this is such a common setup, we provide some helpers for it as described at <<gem5-run-benchmark>>:
  6256. * link:rootfs_overlay/gem5.sh[rootfs_overlay/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.
  6257. * `./run --gem5-readfile` is a convenient way to set the `m5 readfile`
  6258. Other loophole possibilities include:
  6259. * <<9p>>
  6260. * <<secondary-disk>>
  6261. * `expect` as mentioned at: https://stackoverflow.com/questions/7013137/automating-telnet-session-using-bash-scripts
  6262. +
  6263. ....
  6264. #!/usr/bin/expect
  6265. spawn telnet localhost 3456
  6266. expect "# $"
  6267. send "pwd\r"
  6268. send "ls /\r"
  6269. send "m5 exit\r"
  6270. expect eof
  6271. ....
  6272. +
  6273. This is ugly however as it is not deterministic.
  6274. https://www.mail-archive.com/gem5-users@gem5.org/msg15233.html
  6275. ==== gem5 restore checkpoint with a different CPU
  6276. gem5 can switch to a different CPU model when restoring a checkpoint.
  6277. 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.
  6278. An illustrative interactive run:
  6279. ....
  6280. ./run --arch arm --gem5
  6281. ....
  6282. In guest:
  6283. ....
  6284. m5 checkpoint
  6285. ....
  6286. And then restore the checkpoint with a different CPU:
  6287. ....
  6288. ./run --arch arm --gem5 --gem5-restore 1 -- --caches --restore-with-cpu=HPI
  6289. ....
  6290. === Pass extra options to gem5
  6291. Pass options to the `fs.py` script:
  6292. * get help:
  6293. +
  6294. ....
  6295. ./run --gem5 -- -h
  6296. ....
  6297. * boot with the more detailed and slow `HPI` CPU model:
  6298. +
  6299. ....
  6300. ./run --arch arm --gem5 -- --caches --cpu-type=HPI
  6301. ....
  6302. Pass options to the `gem5` executable itself:
  6303. * get help:
  6304. +
  6305. ....
  6306. ./run --gem5-exe-args='-h' --gem5
  6307. ....
  6308. === gem5 exit after a number of instructions
  6309. Quit the simulation after `1024` instructions:
  6310. ....
  6311. ./run --gem5 -- -I 1024
  6312. ....
  6313. Can be nicely checked with <<gem5-tracing>>.
  6314. Cycles instead of instructions:
  6315. ....
  6316. ./run --gem5 -- --memory 1024
  6317. ....
  6318. Otherwise the simulation runs forever by default.
  6319. === m5ops
  6320. m5ops are magic instructions which lead gem5 to do magic things, like quitting or dumping stats.
  6321. Documentation: http://gem5.org/M5ops
  6322. There are two main ways to use m5ops:
  6323. * <<m5>>
  6324. * <<m5ops-instructions>>
  6325. `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.
  6326. `m5` cannot should / should not be used however:
  6327. * in bare metal setups
  6328. * 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.
  6329. +
  6330. Why not just hardcode some <<m5ops-instructions>> as in our example instead, since you are going to modify the source of the benchmark anyways?
  6331. ==== m5
  6332. `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>>
  6333. Its source is present in the gem5 tree: https://github.com/gem5/gem5/blob/6925bf55005c118dc2580ba83e0fa10b31839ef9/util/m5/m5.c
  6334. It is possible to guess what most tools do from the corresponding <<m5ops>>, but let's at least document the less obvious ones here.
  6335. ===== m5 exit
  6336. End the simulation.
  6337. Sane Python scripts will exit gem5 with status 0, which is what `fs.py` does.
  6338. ===== m5 fail
  6339. End the simulation with a failure exit event:
  6340. ....
  6341. m5 fail 1
  6342. ....
  6343. 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:
  6344. ....
  6345. Simulated exit code not 0! Exit code is 1
  6346. ....
  6347. and exits with status 0.
  6348. TODO: it used to exit non 0, be like that, but it actually got changed to just print the message. Why? https://gem5-review.googlesource.com/c/public/gem5/+/4880
  6349. `m5 fail` is just a superset of `m5 exit`, which is just:
  6350. ....
  6351. m5 fail 0
  6352. ....
  6353. as can be seen from the source: https://github.com/gem5/gem5/blob/50a57c0376c02c912a978c4443dd58caebe0f173/src/sim/pseudo_inst.cc#L303
  6354. ===== m5 writefile
  6355. Send a guest file to the host. <<9p>> is a more advanced alternative.
  6356. Guest:
  6357. ....
  6358. echo mycontent > myfileguest
  6359. m5 writefile myfileguest myfilehost
  6360. ....
  6361. Host:
  6362. ....
  6363. cat "$(./getvar --arch aarch64 --gem5 m5out_dir)/myfilehost"
  6364. ....
  6365. Does not work for subdirectories, gem5 crashes:
  6366. ....
  6367. m5 writefile myfileguest mydirhost/myfilehost
  6368. ....
  6369. ===== m5 readfile
  6370. Read a host file pointed to by the `fs.py --script` option to stdout.
  6371. https://stackoverflow.com/questions/49516399/how-to-use-m5-readfile-and-m5-execfile-in-gem5/49538051#49538051
  6372. Host:
  6373. ....
  6374. date > "$(./getvar gem5_readfile)"
  6375. ....
  6376. Guest:
  6377. ....
  6378. m5 readfile
  6379. ....
  6380. Outcome: date shows on guest.
  6381. ===== m5 initparam
  6382. Ermm, just another <<m5-readfile>> that only takes integers and only from CLI options? Is this software so redundant?
  6383. Host:
  6384. ....
  6385. ./run --gem5 --gem5-restore 1 -- --initparam 13
  6386. ./run --gem5 --gem5-restore 1 -- --initparam 42
  6387. ....
  6388. Guest:
  6389. ....
  6390. m5 initparm
  6391. ....
  6392. Outputs the given paramter.
  6393. ===== m5 execfile
  6394. Trivial combination of `m5 readfile` + execute the script.
  6395. Host:
  6396. ....
  6397. printf '#!/bin/sh
  6398. echo asdf
  6399. ' > "$(./getvar gem5_readfile)"
  6400. ....
  6401. Guest:
  6402. ....
  6403. touch /tmp/execfile
  6404. chmod +x /tmp/execfile
  6405. m5 execfile
  6406. ....
  6407. Outcome:
  6408. ....
  6409. adsf
  6410. ....
  6411. ==== m5ops instructions
  6412. The executable `/m5ops.out` illustrates how to hard code with inline assembly the m5ops that you are most likely to hack into the benchmark you are analysing:
  6413. ....
  6414. # checkpoint
  6415. /m5ops.out c
  6416. # dumpstats
  6417. /m5ops.out d
  6418. # exit
  6419. /m5ops.out e
  6420. # dump resetstats
  6421. /m5ops.out r
  6422. ....
  6423. Sources:
  6424. * link:userland/m5ops.h[]
  6425. * link:userland/m5ops.c[]
  6426. That executable is of course a subset of <<m5>> and useless by itself: its goal is only illustrate how to hardcode some <<m5ops>> yourself as one-liners.
  6427. In theory, the cleanest way to add m5ops to your benchmarks would be to do exactly what the `m5` tool does:
  6428. * include link:https://github.com/gem5/gem5/blob/05c4c2b566ce351ab217b2bd7035562aa7a76570/include/gem5/asm/generic/m5ops.h[`include/gem5/asm/generic/m5ops.h`]
  6429. * link with the `.o` file under `util/m5` for the correct arch, e.g. `m5op_arm_A64.o` for aarch64.
  6430. 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`.
  6431. Related: https://www.mail-archive.com/gem5-users@gem5.org/msg15418.html
  6432. ===== m5ops instructions interface
  6433. Let's study how <<m5>> uses them:
  6434. * 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
  6435. * 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
  6436. * 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.
  6437. We notice that there are two different implementations for each arch:
  6438. * magic instructions, which don't exist in the corresponding arch
  6439. * magic memory addresses on a given page
  6440. 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.
  6441. Then, in aarch64 magic instructions for example, the lines:
  6442. ....
  6443. .macro m5op_func, name, func, subfunc
  6444. .globl \name
  6445. \name:
  6446. .long 0xff000110 | (\func << 16) | (\subfunc << 12)
  6447. ret
  6448. ....
  6449. define a simple function function for each m5op. Here we see that:
  6450. * `0xff000110` is a base mask for the magic non-existing instruction
  6451. * `\func` and `\subfunc` are OR-applied on top of the base mask, and define m5op this is.
  6452. +
  6453. Those values will loop over the magic constants defined in `m5ops.h` with the deferred preprocessor idiom.
  6454. +
  6455. For example, `exit` is `0x21` due to:
  6456. +
  6457. ....
  6458. #define M5OP_EXIT 0x21
  6459. ....
  6460. Finally, `m5.c` calls the defined functions as in:
  6461. ....
  6462. m5_exit(ints[0]);
  6463. ....
  6464. 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].
  6465. Keep in mind that for all archs, `m5.c` does the calls with 64-bit integers:
  6466. ....
  6467. uint64_t ints[2] = {0,0};
  6468. parse_int_args(argc, argv, ints, argc);
  6469. m5_fail(ints[1], ints[0]);
  6470. ....
  6471. Therefore, for example:
  6472. * aarch64 uses `x0` for the first argument and `x1` for the second, since each is 64 bits log already
  6473. * arm uses `r0` and `r1` for the first argument, and `r2` and `r3` for the second, since each register is only 32 bits long
  6474. That convention specifies that `x0` to `x7` contain the function arguments, so `x0` contains the first argument, and `x1` the second.
  6475. In our `m5ops` example, we just hardcode everything in the assembly one-liners we are producing.
  6476. We ignore the `\subfunc` since it is always 0 on the ops that interest us.
  6477. ===== m5op annotations
  6478. `include/gem5/asm/generic/m5ops.h` also describes some annotation instructions.
  6479. What they mean: https://stackoverflow.com/questions/50583962/what-are-the-gem5-annotations-mops-magic-instructions-and-how-to-use-them
  6480. === gem5 arm Linux kernel patches
  6481. https://gem5.googlesource.com/arm/linux/ contains an ARM Linux kernel fork with a few gem5 specific Linux kernel patches on top of mainline created by ARM Holdings.
  6482. Those patches look interesting, but it is obviously not possible to understand what they actually do from their commit message.
  6483. So let's explain them one by one here as we understand them:
  6484. * `drm: Add component-aware simple encoder` allows you to see images through VNC: <<gem5-graphic-mode>>
  6485. * `gem5: Add support for gem5's extended GIC mode` adds support for more than 8 cores: https://stackoverflow.com/questions/50248067/how-to-run-a-gem5-arm-aarch64-full-system-simulation-with-fs-py-with-more-than-8/50248068#5024806
  6486. === m5out directory
  6487. When you run gem5, it generates an `m5out` directory at:
  6488. ....
  6489. echo $(./getvar --arch arm --gem5 m5out_dir)"
  6490. ....
  6491. The location of that directory can be set with `./gem5.opt -d`, and defaults to `./m5out`.
  6492. The files in that directory contains some very important information about the run, and you should become familiar with every one of them.
  6493. ==== system.terminal
  6494. Contains UART output, both from the Linux kernel or from the baremetal system.
  6495. Can also be seen live on <<m5term>>.
  6496. ==== stats.txt
  6497. This file contains important statistics about the run:
  6498. ....
  6499. cat "$(./getvar --arch aarch64 m5out_dir)/stats.txt"
  6500. ....
  6501. Whenever we run `m5 dumpstats` or `m5 exit`, a section with the following format is added to that file:
  6502. ....
  6503. ---------- Begin Simulation Statistics ----------
  6504. [the stats]
  6505. ---------- End Simulation Statistics ----------
  6506. ....
  6507. That file contains several important execution metrics, e.g. number of cycles and several types of cache misses:
  6508. ....
  6509. system.cpu.numCycles
  6510. system.cpu.dtb.inst_misses
  6511. system.cpu.dtb.inst_hits
  6512. ....
  6513. ==== rdtsc
  6514. Let's have some fun and try to correlate the gem5 cycle count `system.cpu.numCycles` with the link:https://en.wikipedia.org/wiki/Time_Stamp_Counter[x86 `rdtsc` instruction] that is supposed to do the same thing:
  6515. ....
  6516. ./build-userland -- rdtsc
  6517. ./run --eval '/rdtsc.out;m5 exit;' --gem5
  6518. ./gem5-stat
  6519. ....
  6520. Source: link:userland/rdtsc.c[]
  6521. `rdtsc` outputs a cycle count which we compare with gem5's `gem5-stat`:
  6522. * `3828578153`: `rdtsc`
  6523. * `3830832635`: `gem5-stat`
  6524. which gives pretty close results, and serve as a nice sanity check that the cycle counter is coherent.
  6525. 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`.
  6526. Bibliography:
  6527. * https://en.wikipedia.org/wiki/Time_Stamp_Counter
  6528. * https://stackoverflow.com/questions/9887839/clock-cycle-count-wth-gcc/9887979
  6529. ===== pmccntr
  6530. TODO We didn't manage to find a working ARM analogue to <<rdtsc>>: 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:
  6531. * https://stackoverflow.com/questions/40454157/is-there-an-equivalent-instruction-to-rdtsc-in-arm
  6532. * https://stackoverflow.com/questions/31620375/arm-cortex-a7-returning-pmccntr-0-in-kernel-mode-and-illegal-instruction-in-u/31649809#31649809
  6533. * https://blog.regehr.org/archives/794
  6534. ==== config.ini
  6535. The `config.ini` file, contains a very good high level description of the system:
  6536. ....
  6537. less $(./getvar --arch arm --gem5 m5out_dir)"
  6538. ....
  6539. That file contains a tree representation of the system, sample excerpt:
  6540. ....
  6541. [root]
  6542. type=Root
  6543. children=system
  6544. full_system=true
  6545. [system]
  6546. type=ArmSystem
  6547. children=cpu cpu_clk_domain
  6548. auto_reset_addr_64=false
  6549. semihosting=Null
  6550. [system.cpu]
  6551. type=AtomicSimpleCPU
  6552. children=dstage2_mmu dtb interrupts isa istage2_mmu itb tracer
  6553. branchPred=Null
  6554. [system.cpu_clk_domain]
  6555. type=SrcClockDomain
  6556. clock=500
  6557. ....
  6558. Each node has:
  6559. * a list of child nodes, e.g. `system` is a child of `root`, and both `cpu` and `cpu_clk_domain` are children of `system`
  6560. * a list of parameters, e.g. `system.semihosting` is `Null`, which means that <<semihosting>> was turned off
  6561. ** the `type` parameter shows is present on every node, and it maps to a `Python` object that inherits from `SimObject`.
  6562. +
  6563. 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].
  6564. You can also get a simplified graphical view of the tree with:
  6565. ....
  6566. xdg-open "$(./getvar --arch arm --gem5 m5out_dir)/config.dot.pdf"
  6567. ....
  6568. Modifying the `config.ini` file manually does nothing since it gets overwritten every time.
  6569. Set custom configs with the `--param` option of `fs.py`, e.g. we can make gem5 wait for GDB to connect with:
  6570. ....
  6571. fs.py --param 'system.cpu[0].wait_for_remote_gdb = True'
  6572. ....
  6573. 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[].
  6574. === m5term
  6575. We use the `m5term` in-tree executable to connect to the terminal instead of a direct `telnet`.
  6576. If you use `telnet` directly, it mostly works, but certain interactive features don't, e.g.:
  6577. * up and down arrows for history havigation
  6578. * tab to complete paths
  6579. * `Ctrl-C` to kill processes
  6580. TODO understand in detail what `m5term` does differently than `telnet`.
  6581. === gem5 Python scripts without rebuild
  6582. We have made a crazy setup that allows you to just `cd` into `submodules/gem5`, and edit Python scripts directly there.
  6583. This is not normally possible with Buildroot, since normal Buildroot packages first copy files to the output directory (`$(./getvar -a <arch> build_dir)/<pkg>`), and then build there.
  6584. So if you modified the Python scripts with this setup, you would still need to `./build` to copy the modified files over.
  6585. 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://www.mail-archive.com/gem5-users@gem5.org/msg15421.html[out of tree] build to `out/common/gem5`.
  6586. 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.
  6587. Using Buildroot for gem5 is still convenient because we use it to:
  6588. * to cross build `m5` for us
  6589. * check timestamps and skip the gem5 build when it is not requested
  6590. 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.
  6591. === gem5 fs_bigLITTLE
  6592. By default, we use `configs/example/fs.py` script.
  6593. The `--gem5-script biglittle` option enables the alternative `configs/example/arm/fs_bigLITTLE.py` script instead.
  6594. First apply:
  6595. ....
  6596. patch -d "$(./getvar gem5_src_dir)" -p 1 < patches/manual/gem5-biglittle.patch
  6597. ....
  6598. then:
  6599. ....
  6600. ./run --arch aarch64 --gem5 --gem5-script biglittle
  6601. ....
  6602. Advantages over `fs.py`:
  6603. * more representative of mobile ARM SoCs, which almost always have big little cluster
  6604. * simpler than `fs.py`, and therefore easier to understand and modify
  6605. Disadvantages over `fs.py`:
  6606. * only works for ARM, not other archs
  6607. * not as many configuration options as `fs.py`, many things are hardcoded
  6608. 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`.
  6609. 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.
  6610. Tested on: link:http://github.com/cirosantilli/linux-kernel-module-cheat/commit/18c1c823feda65f8b54cd38e261c282eee01ed9f[18c1c823feda65f8b54cd38e261c282eee01ed9f]
  6611. === gem5 unit tests
  6612. https://stackoverflow.com/questions/52279971/how-to-run-the-gem5-unit-tests
  6613. Not currently exposed here.
  6614. == Buildroot
  6615. === Custom Buildroot configs
  6616. We provide the following mechanisms:
  6617. * `./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:br2/default[].
  6618. * `./build-buildroot --config 'BR2_SOME_OPTION="myval"'`: append a single option to a single build.
  6619. For example, if you decide to <<enable-buildroot-compiler-optimizations>> after an initial build is finished, you must <<clean-the-build>> and rebuild:
  6620. ....
  6621. ./build-buildroot \
  6622. --config 'BR2_OPTIMIZE_3=y' \
  6623. --config 'BR2_SAMPLE_PACKAGE=y' \
  6624. --
  6625. sample_package-dirclean \
  6626. sample_package-reconfigure \
  6627. ;
  6628. ....
  6629. as explained at: https://buildroot.org/downloads/manual/manual.html#rebuild-pkg
  6630. The clean is necessary because the source files didn't change, so `make` would just check the timestamps and not build anything.
  6631. You will then likely want to make those more permanent with: <<default-command-line-arguments>>
  6632. ==== Enable Buildroot compiler optimizations
  6633. If you are benchmarking compiled programs instead of hand written assembly, remember that we configure Buildroot to disable optimizations by default with:
  6634. ....
  6635. BR2_OPTIMIZE_0=y
  6636. ....
  6637. to improve the debugging experience.
  6638. You will likely want to change that to:
  6639. ....
  6640. BR2_OPTIMIZE_3=y
  6641. ....
  6642. 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.
  6643. Don't forget to do that if you are <<add-new-buildroot-packages,adding a new package>> with your own build system.
  6644. Then, you have two choices:
  6645. * 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>>
  6646. +
  6647. ....
  6648. ./build-buildroot \
  6649. --config 'BR2_OPTIMIZE_3=y' \
  6650. --config 'BR2_SAMPLE_PACKAGE=y' \
  6651. -- \
  6652. sample_package-dirclean \
  6653. sample_package-reconfigure \
  6654. ;
  6655. ....
  6656. +
  6657. However, this approach might not be representative since calls to an unoptimized libc and other libraries will have a negative performance impact.
  6658. +
  6659. Maybe you can get away with rebuilding libc, but I'm not sure that it will work properly.
  6660. +
  6661. Kernel-wise it should be fine though due to: <<kernel-o0>>
  6662. * <<clean-the-build,clean the build>> and rebuild from scratch:
  6663. +
  6664. ....
  6665. mv out out~
  6666. ./build-buildroot --config 'BR2_OPTIMIZE_3=y'
  6667. ....
  6668. === Find Buildroot options with make menuconfig
  6669. `make menuconfig` is a convenient way to find Buildroot configurations:
  6670. ....
  6671. cd "$(./getvar buildroot_build_dir)"
  6672. make menuconfig
  6673. ....
  6674. Hit `/` and search for the settings.
  6675. Save and quit.
  6676. ....
  6677. diff -u .config.olg .config
  6678. ....
  6679. Then copy and paste the diff additions to link:br2/default[] to make them permanent.
  6680. === Change user
  6681. At startup, we login automatically as the `root` user.
  6682. 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:
  6683. ....
  6684. login user0
  6685. ....
  6686. and password:
  6687. ....
  6688. a
  6689. ....
  6690. Then test that the user changed with:
  6691. ....
  6692. id
  6693. ....
  6694. which gives:
  6695. ....
  6696. uid=1000(user0) gid=1000(user0) groups=1000(user0)
  6697. ....
  6698. ==== Login as a non-root user without password
  6699. Replace on `inittab`:
  6700. ....
  6701. ::respawn:-/bin/sh
  6702. ....
  6703. with:
  6704. ....
  6705. ::respawn:-/bin/login -f user0
  6706. ....
  6707. `-f` forces login without asking for the password.
  6708. === Add new Buildroot packages
  6709. First, see if you can't get away without actually adding a new package, for example:
  6710. * 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
  6711. * 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>>
  6712. If none of those methods are flexible enough for you, you can just fork or hack up link:packages/sample_package[] the sample package to do what you want.
  6713. For how to use that package, see: <<packages-directory>>.
  6714. Then iterate trying to do what you want and reading the manual until it works: https://buildroot.org/downloads/manual/manual.html
  6715. === Remove Buildroot packages
  6716. Once you've built a package in to the image, there is no easy way to remove it.
  6717. Documented at: link:https://github.com/buildroot/buildroot/blob/2017.08/docs/manual/rebuilding-packages.txt#L90[]
  6718. See this for a sample manual workaround: <<parsec-uninstall>>.
  6719. === BR2_TARGET_ROOTFS_EXT2_SIZE
  6720. When adding new large package to the Buildroot root filesystem, it may fail with the message:
  6721. ....
  6722. Maybe you need to increase the filesystem size (BR2_TARGET_ROOTFS_EXT2_SIZE)
  6723. ....
  6724. The solution is to simply add:
  6725. ....
  6726. ./build-buildroot --config 'BR2_TARGET_ROOTFS_EXT2_SIZE="512M"'
  6727. ....
  6728. where 512Mb is "large enough".
  6729. Note that dots cannot be used as in `1.5G`, so just use Megs as in `1500M` instead.
  6730. Unfortunately, TODO we don't have a perfect way to find the right value for `BR2_TARGET_ROOTFS_EXT2_SIZE`. One good heuristic is:
  6731. ....
  6732. du -hsx "$(./getvar --arch arm target_dir)"
  6733. ....
  6734. Some promising ways to overcome this problem include:
  6735. * <<squashfs>>
  6736. TODO benchmark: would gem5 suffer a considerable disk read performance hit due to decompressing SquashFS?
  6737. * 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`]
  6738. * use methods described at: <<gem5-restore-new-script>> instead of putting builds on the root filesystem
  6739. Bibliography: https://stackoverflow.com/questions/49211241/is-there-a-way-to-automatically-detect-the-minimum-required-br2-target-rootfs-ex
  6740. ==== SquashFS
  6741. 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.
  6742. 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>>.
  6743. This is the exact unanswered question: https://unix.stackexchange.com/questions/343484/mounting-squashfs-image-with-read-write-overlay-for-rootfs
  6744. [[rpath]]
  6745. === Buildroot rebuild is slow when the root filesystem is large
  6746. Buildroot is not designed for large root filesystem images, and the rebuild becomes very slow when we add a large package to it.
  6747. 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`
  6748. 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:
  6749. ....
  6750. >>> Sanitizing RPATH in target tree
  6751. ....
  6752. which contributed to a large part of the slowness.
  6753. Test how Buildroot deals with many files with:
  6754. ....
  6755. ./build-buildroot \
  6756. --config 'BR2_PACKAGE_LKMC_MANY_FILES=y' \
  6757. -- \
  6758. lkmc_many_files-reconfigure \
  6759. |& \
  6760. ts -i '%.s' \
  6761. ;
  6762. ./build-buildroot |& ts -i '%.s'
  6763. ....
  6764. 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.
  6765. === Report upstream bugs
  6766. 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.
  6767. For example, QEMU developers will only want to see the final QEMU command that you are running.
  6768. 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.
  6769. We make that easy by building commands as strings, and then echoing them before evaling.
  6770. So for example when you run:
  6771. ....
  6772. ./run --arch arm
  6773. ....
  6774. the very first stdout output of that script is the actual QEMU command that is being run.
  6775. The command is also saved to a file for convenience:
  6776. ....
  6777. cat "$(./getvar --arch arm run_cmd_file)"
  6778. ....
  6779. which you can manually modify and execute during your experiments later:
  6780. ....
  6781. vim "$(./getvar --arch arm run_cmd_file)"
  6782. ./"$(./getvar --arch arm run_cmd_file)"
  6783. ....
  6784. Next, you will also want to give the relevant images to save them time, see: <<release-zip>>.
  6785. Finally, do a clone of the relevant repository out of tree and reproduce the bug there, to be 100% sure that it is an actual upstream bug, and to provide developers with the cleanest possible commands.
  6786. For QEMU and Buildroot, we have the following convenient setups respectively:
  6787. * https://github.com/cirosantilli/qemu-test
  6788. * https://github.com/cirosantilli/buildroot/tree/in-tree-package-master
  6789. == Baremetal
  6790. Getting started at: <<baremetal-setup>>
  6791. === Baremetal GDB step debug
  6792. GDB step debug works on baremetal exactly as it does on the Linux kernel, except that is is even cooler here since we can easily control and understand every single instruction that is being run!
  6793. For example, on the first shell:
  6794. ....
  6795. ./run --arch arm --baremetal prompt --debug-guest
  6796. ....
  6797. then on the second shell:
  6798. ....
  6799. ./run-gdb --arch arm --baremetal prompt --no-continue
  6800. ....
  6801. and now we are left at the very first executed instruction of our tiny bootloader: link:baremetal/lib/arm.S[]
  6802. Then just use `stepi` to when jumping into main to go to the C code in link:baremetal/prompt.c[].
  6803. The bootloader is used to put the hardware in its main operating mode before we run our main payload on it.
  6804. You can also find executables that don't use the bootloader at all under `baremetal/arch/<arch>/no_bootloader/*.S`, e.g.:
  6805. ....
  6806. ./run --arch arm --baremetal arch/arm/no_bootloader/semihost_exit --debug-guest
  6807. ....
  6808. Alternatively, skip directly to the C program main function with:
  6809. ....
  6810. ./run-gdb --arch arm --baremetal prompt main
  6811. ....
  6812. and then proceed as usual:
  6813. ....
  6814. ./run --arch arm --baremetal prompt --debug-guest --gem5
  6815. ....
  6816. and on another shell:
  6817. ....
  6818. ./run-gdb --arch arm --baremetal prompt --gem5 --no-continue
  6819. ....
  6820. `aarch64` GDB step debug is broken as mentioned at: <<gem5-gdb-step-debug-kernel-aarch64>>.
  6821. === Semihosting
  6822. Semihosting is a publicly documented interface specified by ARM Holdings that allows us to do some magic operations very useful in development.
  6823. Semihosting is implemented both on some real devices and on simulators such as QEMU and gem5.
  6824. It is documented at: https://developer.arm.com/docs/100863/latest/introduction
  6825. Example:
  6826. ....
  6827. ./run --arch arm --baremetal arch/arm/semihost_exit
  6828. ....
  6829. makes both the QEMU and gem5 host executables exit.
  6830. Source: link:baremetal/arch/arm/no_bootloader/semihost_exit.S[]
  6831. That program program contains the code:
  6832. ....
  6833. mov r0, #0x18
  6834. ldr r1, =#0x20026
  6835. svc 0x00123456
  6836. ....
  6837. and we can see from the docs that `0x18` stands for the `SYS_EXIT` command.
  6838. This is also how we implement the `exit(0)` system call in C for link:baremetal/exit.c[] through the Newlib via the function `_exit` at link:baremetal/lib/common.c[].
  6839. Other magic operations we can do with semihosting besides exiting the on the host include:
  6840. * exit
  6841. * read and write to host stdin and stdout
  6842. * read and write to host files
  6843. Alternatives exist for some semihosting operations, e.g.:
  6844. * UART IO for host stdin and stdout in both emulators and real hardware
  6845. * <<m5ops>> for <<gem5>>, e.g. `m5 exit` makes the emulator quit
  6846. 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.
  6847. The downside of semihosting is that it is ARM specific. TODO is it an open standard that other vendors can implement?
  6848. In QEMU, we enable semihosting with:
  6849. ....
  6850. -semihosting
  6851. ....
  6852. Newlib 9c84bfd47922aad4881f80243320422b621c95dc already has a semi-hosting implementation at:
  6853. ....
  6854. newlib/libc/sys/arm/syscalls.c
  6855. ....
  6856. TODO: how to use it? Possible through crosstool-NG? In the worst case we could just copy it.
  6857. Bibliography:
  6858. * https://stackoverflow.com/questions/31990487/how-to-cleanly-exit-qemu-after-executing-bare-metal-program-without-user-interve/40957928#40957928
  6859. * https://balau82.wordpress.com/2010/11/04/qemu-arm-semihosting/
  6860. === gem5 baremetal carriage return
  6861. TODO: our example is printing newlines without automatic carriage return `\r` as in:
  6862. ....
  6863. enter a character
  6864. got: a
  6865. ....
  6866. We use `m5term` by default, and if we try `telnet` instead:
  6867. ....
  6868. telnet localhost 3456
  6869. ....
  6870. it does add the carriage returns automatically.
  6871. === Baremetal host packaged toolchain
  6872. For `arm`, some baremetal examples compile fine with:
  6873. ....
  6874. sudo apt-get install gcc-arm-none-eabi qemu-system-arm
  6875. ./build-baremetal --arch arm --prebuilt
  6876. ./run --arch arm --baremetal prompt --prebuilt
  6877. ....
  6878. However, there are as usual limitations to using prebuilts:
  6879. * certain examples fail to build with the Ubuntu packaged toolchain. E.g.: link:baremetal/exit.c[] fails with:
  6880. +
  6881. ....
  6882. /usr/lib/gcc/arm-none-eabi/6.3.1/../../../arm-none-eabi/lib/libg.a(lib_a-fini.o): In function `__libc_fini_array':
  6883. /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'
  6884. collect2: error: ld returned 1 exit status
  6885. ....
  6886. +
  6887. with the prebuilt toolchain, and I'm lazy to debug.
  6888. * 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
  6889. === C++ baremetal
  6890. 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
  6891. === GDB builtin CPU simulator
  6892. 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
  6893. TODO: any advantage over QEMU? I doubt it, mostly using it as as toy for now:
  6894. Without running `./run`, do directly:
  6895. ....
  6896. ./run-gdb --arch arm --baremetal prompt --sim
  6897. ....
  6898. Then inside GDB:
  6899. ....
  6900. load
  6901. starti
  6902. ....
  6903. and now you can debug normally.
  6904. Enabled with the crosstool-NG configuration:
  6905. ....
  6906. CT_GDB_CROSS_SIM=y
  6907. ....
  6908. which by grepping crosstool-NG we can see does on GDB:
  6909. ....
  6910. ./download-dependencies --enable-sim
  6911. ....
  6912. Those are not set by default on `gdb-multiarch` in Ubuntu 16.04.
  6913. Bibliography:
  6914. * https://stackoverflow.com/questions/49470659/arm-none-eabi-gdb-undefined-target-command-sim
  6915. * http://cs107e.github.io/guides/gdb/
  6916. ==== GDB builtin CPU simulator userland
  6917. Since I had this compiled, I also decided to try it out on userland.
  6918. 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
  6919. It just ignores the `swi` however, and does not forward syscalls to the host like QEMU does.
  6920. Then I tried a glibc example: https://github.com/cirosantilli/arm-assembly-cheat/blob/cd232dcaf32c0ba6399b407e0b143d19b6ec15f4/v7/mov.S
  6921. First it wouldn't break, so I added `-static` to the `Makefile`, and then it started failing with:
  6922. ....
  6923. Unhandled v6 thumb insn
  6924. ....
  6925. Doing:
  6926. ....
  6927. help architecture
  6928. ....
  6929. shows ARM version up to `armv6`, so maybe `armv6` is not implemented?
  6930. === How we got some baremetal stuff to work
  6931. It is nice when thing just work.
  6932. But you can also learn a thing or two from how I actually made them work in the first place.
  6933. ==== Find the UART address
  6934. Enter the QEMU console:
  6935. ....
  6936. Ctrl-X C
  6937. ....
  6938. Then do:
  6939. ....
  6940. info mtree
  6941. ....
  6942. And look for `pl011`:
  6943. ....
  6944. 0000000009000000-0000000009000fff (prio 0, i/o): pl011
  6945. ....
  6946. 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
  6947. ....
  6948. class RealViewPBX(RealView):
  6949. uart = Pl011(pio_addr=0x10009000, int_num=44)
  6950. ....
  6951. ==== aarch64 baremetal NEON setup
  6952. Inside link:baremetal/lib/aarch64.S[] there is a chunk of code called "NEON setup".
  6953. Without that, the `printf`:
  6954. ....
  6955. printf("got: %c\n", c);
  6956. ....
  6957. compiled to a:
  6958. ....
  6959. str q0, [sp, #80]
  6960. ....
  6961. which uses NEON registers, and goes into an exception loop.
  6962. It was a bit confusing because there was a previous `printf`:
  6963. ....
  6964. printf("enter a character\n");
  6965. ....
  6966. which did not blow up because GCC compiles it into `puts` directly since it has no arguments, and that does not generate NEON instructions.
  6967. The last instructions ran was found with:
  6968. ....
  6969. while(1)
  6970. stepi
  6971. end
  6972. ....
  6973. or by hacking the QEMU CLI to contain:
  6974. .....
  6975. -D log.log -d in_asm
  6976. .....
  6977. I could not find any previous NEON instruction executed so this led me to suspect that some NEON initialization was required:
  6978. * 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"
  6979. * https://community.arm.com/processors/f/discussions/5409/how-to-enable-neon-in-cortex-a8
  6980. * https://stackoverflow.com/questions/19231197/enable-neon-on-arm-cortex-a-series
  6981. We then tried to copy the code from the "Bare-metal Boot Code for ARMv8-A Processors" document:
  6982. ....
  6983. // Disable trapping of accessing in EL3 and EL2.
  6984. MSR CPTR_EL3, XZR
  6985. MSR CPTR_EL3, XZR
  6986. // Disable access trapping in EL1 and EL0.
  6987. MOV X1, #(0x3 << 20) // FPEN disables trapping to EL1.
  6988. MSR CPACR_EL1, X1
  6989. ISB
  6990. ....
  6991. but it entered an exception loop at `MSR CPTR_EL3, XZR`.
  6992. We then found out that QEMU starts in EL1, and so we kept just the EL1 part, and it worked. Related:
  6993. * https://stackoverflow.com/questions/42824706/qemu-system-aarch64-entering-el1-when-emulating-a53-power-up
  6994. * https://stackoverflow.com/questions/37299524/neon-support-in-armv8-system-mode-qemu
  6995. === Baremetal bibliography
  6996. https://stackoverflow.com/questions/43682311/uart-communication-in-gem5-with-arm-bare-metal
  6997. 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:
  6998. ....
  6999. # Build gem5.
  7000. git clone https://gem5.googlesource.com/public/gem5
  7001. cd gem5
  7002. git checkout 60600f09c25255b3c8f72da7fb49100e2682093a
  7003. scons --ignore-style -j`nproc` build/ARM/gem5.opt
  7004. cd ..
  7005. # Build example.
  7006. sudo apt-get install gcc-arm-none-eabi
  7007. git clone https://github.com/tukl-msd/gem5.bare-metal
  7008. cd gem5.bare-metal
  7009. git checkout 6ad1069d4299b775b5491e9252739166bfac9bfe
  7010. cd Simple
  7011. make CROSS_COMPILE_DIR=/usr/bin
  7012. # Run example.
  7013. ../../gem5/default/build/ARM/gem5.opt' \
  7014. ../../gem5/configs/example/fs.py' \
  7015. --bare-metal \
  7016. --disk-image="$(pwd)/../common/fake.iso" \
  7017. --kernel="$(pwd)/main.elf" \
  7018. --machine-type=RealView_PBX \
  7019. --mem-size=256MB \
  7020. ;
  7021. ....
  7022. == Benchmark this repo
  7023. In this section document how benchmark builds and runs of this repo, and how to investigate what the bottleneck is.
  7024. Ideally, we should setup an automated build server that benchmarks those things continuously for us, but our <<travis>> attempt failed.
  7025. So currently, we are running benchmarks manually when it seems reasonable and uploading them to: https://github.com/cirosantilli/linux-kernel-module-cheat-regression
  7026. All benchmarks were run on the <<p51>> machine, unless stated otherwise.
  7027. Run all benchmarks and upload the results:
  7028. ....
  7029. cd ..
  7030. git clone https://github.com/cirosantilli/linux-kernel-module-cheat-regression
  7031. cd -
  7032. ./bench-all -A
  7033. ....
  7034. === Travis
  7035. 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.
  7036. === Benchmark this repo benchmarks
  7037. ==== Benchmark Linux kernel boot
  7038. Benchmark all:
  7039. ....
  7040. ./build all-linux
  7041. ./bench-boot
  7042. cat "$(./getvar bench_boot)"
  7043. ....
  7044. Sample results at 2bddcc2891b7e5ac38c10d509bdfc1c8fe347b94:
  7045. ....
  7046. cmd ./run --arch x86_64 --eval '/poweroff.out'
  7047. time 7.46
  7048. exit_status 0
  7049. cmd ./run --arch x86_64 --eval '/poweroff.out' --kvm
  7050. time 7.61
  7051. exit_status 0
  7052. cmd ./run --arch x86_64 --eval '/poweroff.out' --trace exec_tb
  7053. time 8.04
  7054. exit_status 0
  7055. instructions 1665023
  7056. cmd ./run --arch x86_64 --eval 'm5 exit' --gem5
  7057. time 254.32
  7058. exit_status 0
  7059. instructions 380799337
  7060. cmd ./run --arch arm --eval '/poweroff.out'
  7061. time 5.56
  7062. exit_status 0
  7063. cmd ./run --arch arm --eval '/poweroff.out' --trace exec_tb
  7064. time 5.78
  7065. exit_status 0
  7066. instructions 742319
  7067. cmd ./run --arch aarch64 --eval '/poweroff.out'
  7068. time 4.85
  7069. exit_status 0
  7070. cmd ./run --arch aarch64 --eval '/poweroff.out' --trace exec_tb
  7071. time 4.91
  7072. exit_status 0
  7073. instructions 245471
  7074. cmd ./run --arch aarch64 --eval 'm5 exit' --gem5
  7075. time 68.71
  7076. exit_status 0
  7077. instructions 120555566
  7078. ....
  7079. TODO: aarch64 gem5 and QEMU use the same kernel, so why is the gem5 instruction count so much much higher?
  7080. ===== gem5 arm HPI boot takes much longer than aarch64
  7081. TODO 62f6870e4e0b384c4bd2d514116247e81b241251 takes 33 minutes to finish at 62f6870e4e0b384c4bd2d514116247e81b241251:
  7082. ....
  7083. cmd ./run --arch arm --eval 'm5 exit' --gem5 -- --caches --cpu-type=HPI
  7084. ....
  7085. while aarch64 only 7 minutes.
  7086. 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?
  7087. Logs of the runs can be found at: https://github.com/cirosantilli-work/gem5-issues/tree/0df13e862b50ae20fcd10bae1a9a53e55d01caac/arm-hpi-slow
  7088. The cycle count is higher for `arm`, 350M vs 250M for `aarch64`, not nowhere near the 5x runtime time increase.
  7089. 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.
  7090. ===== gem5 x86_64 DerivO3CPU boot panics
  7091. https://github.com/cirosantilli-work/gem5-issues/issues/2
  7092. ....
  7093. Kernel panic - not syncing: Attempted to kill the idle task!
  7094. ....
  7095. ==== Benchmark builds
  7096. The build times are calculated after doing `./download-dependencies` and link:https://buildroot.org/downloads/manual/manual.html#_offline_builds[`make source`], which downloads the sources, and basically benchmarks the <<benchmark-internets,Internet>>.
  7097. 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
  7098. Buildroot automatically stores build timestamps as milliseconds since Epoch. Convert to minutes:
  7099. ....
  7100. awk -F: 'NR==1{start=$1}; END{print ($1 - start)/(60000.0)}' "$(./getvar build_dir)/build-time.log"
  7101. ....
  7102. Or to conveniently do a clean build without affecting your current one:
  7103. ....
  7104. ./bench-all -b
  7105. cat ../linux-kernel-module-cheat-regression/*/build-time.log
  7106. ....
  7107. ===== Find which packages are making the build slow and big
  7108. ....
  7109. ./build-buildroot -- graph-build graph-size graph-depends
  7110. cd "$(./getvar buildroot_build_dir)/graphs"
  7111. xdg-open build.pie-packages.pdf
  7112. xdg-open graph-depends.pdf
  7113. xdg-open graph-size.pdf
  7114. ....
  7115. [[prebuilt-toolchain]]
  7116. ====== Buildroot use prebuilt host toolchain
  7117. 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
  7118. ===== Benchmark Buildroot build baseline
  7119. This is the minimal build we could expect to get away with.
  7120. We will run this whenever the Buildroot submodule is updated.
  7121. On the upstream Buildroot repo at :
  7122. ....
  7123. ./bench-all -B
  7124. ....
  7125. Sample time on 2017.08: 11 minutes, 7 with full ccache hits. Breakdown: 47% GCC, 15% Linux kernel, 9% uclibc, 5% host-binutils. Conclusions:
  7126. * we have bloated our kernel build 3x with all those delicious features :-)
  7127. * GCC time increased 1.5x by our bloat, but its percentage of the total was greatly reduced, due to new packages being introduced.
  7128. +
  7129. `make graph-depends` shows that most new dependencies come from QEMU and GDB, which we can't get rid of anyways.
  7130. A quick look at the system monitor reveals that the build switches between times when:
  7131. * CPUs are at a max, memory is fine. So we must be CPU / memory speed bound. I bet that this happens during heavy compilation.
  7132. * CPUs are not at a max, and memory is fine. So we are likely disk bound. I bet that this happens during configuration steps.
  7133. 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.
  7134. The instructions counts varied very little between the baseline and LKMC, so runtime overhead is not a big deal apparently.
  7135. Size:
  7136. * `bzImage`: 4.4M
  7137. * `rootfs.cpio`: 1.6M
  7138. Zipped: 4.9M, `rootfs.cpio` deflates 50%, `bzImage` almost nothing.
  7139. ===== Benchmark gem5 build
  7140. How long it takes to build gem5 itself.
  7141. We will update this whenever the gem5 submoule is updated.
  7142. Sample results at gem5 2a9573f5942b5416fb0570cf5cb6cdecba733392: 10 to 12 minutes.
  7143. Get results with:
  7144. ....
  7145. ./bench-all --gem5
  7146. tail -n+1 ../linux-kernel-module-cheat-regression/*/gem5-bench-build-*.txt
  7147. ....
  7148. ====== Benchmark gem5 single file change rebuild time
  7149. This is the critical development parameter, and is dominated by the link time of huge binaries.
  7150. In order to benchmark it better, do a run with:
  7151. ....
  7152. ./build-gem5 -v
  7153. ....
  7154. and then copy the link command to a separate Bash file. Then you can time and modify it easily.
  7155. Some approximate refrence values on P51:
  7156. * `opt`
  7157. ** unmodified: 15 seconds
  7158. ** hack with `-fwith-ld=gold`: 7.5 seconds. Huge improvement!
  7159. * `debug`
  7160. ** unmodified: 30 seconds. Why two times slower than unmodified?
  7161. ** hack with `-fwith-ld=gold`: `internal error in read_cie, at ../../gold/ehframe.cc:919` on Ubuntu 18.04 all GCC. TODO report.
  7162. * `fast`
  7163. ** `--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.
  7164. ramfs made no difference, the kernel must be caching files in memory very efficiently already.
  7165. Tested at: d4b3e064adeeace3c3e7d106801f95c14637c12f + 1.
  7166. === Benchmark machines
  7167. ==== P51
  7168. Lenovo ThinkPad link:https://www3.lenovo.com/gb/en/laptops/thinkpad/p-series/P51/p/22TP2WPWP51[P51 laptop]:
  7169. * 2500 USD in 2018 (high end)
  7170. * Intel Core i7-7820HQ Processor (8MB Cache, up to 3.90GHz) (4 cores 8 threads)
  7171. * 32GB(16+16) DDR4 2400MHz SODIMM
  7172. * 512GB SSD PCIe TLC OPAL2
  7173. * NVIDIA Quadro M1200 Mobile, latest Ubuntu supported proprietary driver
  7174. * Latest Ubuntu
  7175. === Benchmark Internets
  7176. ==== 38Mbps internet
  7177. 2c12b21b304178a81c9912817b782ead0286d282:
  7178. * shallow clone of all submodules: 4 minutes.
  7179. * `make source`: 2 minutes
  7180. Google M-lab speed test: 36.4Mbps
  7181. === Benchmark this repo bibliography
  7182. gem5:
  7183. * link:https://www.mail-archive.com/gem5-users@gem5.org/msg15262.html[] which parts of the gem5 code make it slow
  7184. * what are the minimum system requirements:
  7185. ** https://stackoverflow.com/questions/47997565/gem5-system-requirements-for-decent-performance/48941793#48941793
  7186. ** https://github.com/gem5/gem5/issues/25
  7187. == About this repo
  7188. === Supported hosts
  7189. We tend to test this repo the most on the latest Ubuntu and on the latest Ubuntu LTS.
  7190. For other Linux distros, everything will likely also just work if you install the analogous required packages for your distro, just have a look at: link:configure[]. Reports and `./configure` ports are welcome and will be merged.
  7191. If something does not work however, <<docker>> should just work on any Linux distro.
  7192. Native Windows is unlikely feasible because Buildroot is a huge set of GNU Make scripts + host tools, just do everything from inside an Ubuntu in VirtualBox instance in that case.
  7193. === Common build issues
  7194. ==== You must put some 'source' URIs in your sources.list
  7195. If `./download-dependencies` fails with:
  7196. ....
  7197. E: You must put some 'source' URIs in your sources.list
  7198. ....
  7199. 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.
  7200. ==== Build from downloaded source zip files
  7201. 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.
  7202. `./download-dependencies` then fetches only the required submodules for you.
  7203. === Run command after boot
  7204. If you just want to run a command after boot ends without thinking much about it, just use the `--eval-busybox` option, e.g.:
  7205. ....
  7206. ./run --eval-busybox 'echo hello'
  7207. ....
  7208. 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.
  7209. See <<init>> for the gory details.
  7210. === Default command line arguments
  7211. It gets annoying to retype `--arch aarch64` for every single command, or to remember `--config` setups.
  7212. So simplify that, do:
  7213. ....
  7214. cp config.example data/config
  7215. ....
  7216. and then edit the `data/config` file to your needs.
  7217. === Build the documentation
  7218. You don't need to depend on GitHub:
  7219. ....
  7220. ./build-doc
  7221. xdg-open out/README.html
  7222. ....
  7223. Source: link:build-doc[]
  7224. === Clean the build
  7225. You did something crazy, and nothing seems to work anymore?
  7226. All our build outputs are stored under `out/`, so the coarsest and most effective thing you can do is:
  7227. ....
  7228. rm -rf out
  7229. ....
  7230. This implies a full rebuild for all archs however, so you might first want to explore finer grained cleans first.
  7231. All our individual `build-*` scripts have a `--clean` option to completely nuke their builds:
  7232. ....
  7233. ./build-gem5 --clean
  7234. ./build-qemu --clean
  7235. ./build-buildroot --clean
  7236. ....
  7237. Verify with:
  7238. ....
  7239. ls "$(./getvar qemu_build_dir)"
  7240. ls "$(./getvar gem5_build_dir)"
  7241. ls "$(./getvar buildroot_build_dir)"
  7242. ....
  7243. 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.
  7244. 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:
  7245. ....
  7246. ./build-buildroot --no-all -- <package-name>-dirclean
  7247. ....
  7248. e.g.:
  7249. ....
  7250. ./build-buildroot --no-all -- sample_package-dirclean
  7251. ....
  7252. Verify with:
  7253. ....
  7254. ls "$(./getvar build_dir)"
  7255. ....
  7256. === ccache
  7257. 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>>.
  7258. We have ccache enabled for everything we build by default.
  7259. However, you likely want to add the following to your `.bashrc` to take better advantage of `ccache`:
  7260. ....
  7261. export CCACHE_DIR=~/.ccache
  7262. export CCACHE_MAXSIZE="20G"
  7263. ....
  7264. We cannot automate this because you have to decide:
  7265. * should I store my cache on my HD or SSD?
  7266. * how big is my build, and how many build configurations do I need to keep around at a time?
  7267. If you don't those variables it, the default is to use `~/.buildroot-ccache` with `5G`, which is a bit small for us.
  7268. To check if `ccache` is working, run this command while a build is running on another shell:
  7269. ....
  7270. watch -n1 'make -C "$(./getvar buildroot_build_dir)" ccache-stats'
  7271. ....
  7272. or if you have it installed on host and the environment variables exported simply with:
  7273. ....
  7274. watch -n1 'ccache -s'
  7275. ....
  7276. and then watch the miss or hit counts go up.
  7277. We have link:https://buildroot.org/downloads/manual/manual.html#ccache[enabled ccached] builds by default.
  7278. `BR2_CCACHE_USE_BASEDIR=n` is used for Buildroot, which means that:
  7279. * absolute paths are used and GDB can find source files
  7280. * but builds are not reused across separated LKMC directories
  7281. === Rebuild while running
  7282. Not possible because
  7283. ....
  7284. Text file busy
  7285. ....
  7286. openat(AT_FDCWD, "sleep.out", O_WRONLY) = -1 ETXTBSY ()
  7287. === Simultaneous runs
  7288. When doing long simulations sweeping across multiple system parameters, it becomes fundamental to do multiple simulations in parallel.
  7289. 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.
  7290. This also has a good synergy with <<build-variants>>.
  7291. First shell:
  7292. ....
  7293. ./run
  7294. ....
  7295. Another shell:
  7296. ....
  7297. ./run --run-id 1
  7298. ....
  7299. and now you have two QEMU instances running in parallel.
  7300. The default run id is `0`.
  7301. Our scripts solve two difficulties with simultaneous runs:
  7302. * port conflicts, e.g. GDB and link:gem5-shell[]
  7303. * output directory conflicts, e.g. traces and gem5 stats overwriting one another
  7304. Each run gets a separate output directory. For example:
  7305. ....
  7306. ./run --arch aarch64 --gem5 --run-id 0 &>/dev/null &
  7307. ./run --arch aarch64 --gem5 --run-id 1 &>/dev/null &
  7308. ....
  7309. produces two separate <<m5out-directory,`m5out` directories>>:
  7310. ....
  7311. echo "$(./getvar --arch aarch64 --gem5 --run-id 0 m5out_dir)"
  7312. echo "$(./getvar --arch aarch64 --gem5 --run-id 1 m5out_dir)"
  7313. ....
  7314. and the gem5 host executable stdout and stderr can be found at:
  7315. ....
  7316. less "$(./getvar --arch aarch64 --gem5 --run-id 0 termout_file)"
  7317. less "$(./getvar --arch aarch64 --gem5 --run-id 1 termout_file)"
  7318. ....
  7319. Each line is prepended with the timestamp in seconds since the start of the program when it appeared.
  7320. 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:
  7321. ....
  7322. ./run --arch aarch64 --gem5 --run-id some-experiment --port-offset 1
  7323. ....
  7324. `--port-offset` defaults to the run ID when that is a number.
  7325. Like <<cpu-architecture>>, you will need to pass the `-n` option to anything that needs to know runtime information, e.g. <<gdb>>:
  7326. ....
  7327. ./run --run-id 1
  7328. ./run-gdb --run-id 1
  7329. ....
  7330. To run multiple gem5 checkouts, see: <<gem5-worktree>>.
  7331. Implementation note: we create multiple namespaces for two things:
  7332. * run output directory
  7333. * ports
  7334. ** QEMU allows setting all ports explicitly.
  7335. +
  7336. If a port is not free, it just crashes.
  7337. +
  7338. We assign a contiguous port range for each run ID.
  7339. ** gem5 automatically increments ports until it finds a free one.
  7340. +
  7341. 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>>.
  7342. +
  7343. The GDB port can be assigned on `gem5.opt --remote-gdb-port`, but it does not appear on `config.ini`.
  7344. === Build variants
  7345. 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.
  7346. 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.
  7347. ==== Linux kernel build variants
  7348. If you want to keep two builds around, one for the latest Linux version, and the other for Linux `v4.16`:
  7349. ....
  7350. # Build master.
  7351. ./build-linux
  7352. # Build another branch.
  7353. git -C "$(./getvar linux_src_dir)" fetch --tags --unshallow
  7354. git -C "$(./getvar linux_src_dir)" checkout v4.16
  7355. ./build-linux --linux-build-id v4.16
  7356. # Restore master.
  7357. git -C "$(./getvar linux_src_dir)" checkout -
  7358. # Run master.
  7359. ./run
  7360. # Run another branch.
  7361. ./run --linux-build-id v4.16
  7362. ....
  7363. The `git fetch --unshallow` is needed the first time because link:configure[] 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
  7364. 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:
  7365. .....
  7366. ./run-gdb --linux-build-id v4.16
  7367. .....
  7368. To run both kernels simultaneously, one on each QEMU instance, see: <<simultaneous-runs>>.
  7369. ==== QEMU build variants
  7370. Analogous to the <<linux-kernel-build-variants>> but with the `--qemu-build-id` option instead:
  7371. ....
  7372. ./build-qemu
  7373. git -C "$(./getvar qemu_src_dir)" checkout v2.12.0
  7374. ./build-qemu --qemu-build-id v2.12.0
  7375. git -C "$(./getvar qemu_src_dir)" checkout -
  7376. ./run
  7377. ./run --qemu-build-id v2.12.0
  7378. ....
  7379. ==== gem5 build variants
  7380. Analogous to the <<linux-kernel-build-variants>> but with the `--gem5-build-id` option instead:
  7381. ....
  7382. # Build master.
  7383. ./build-gem5
  7384. # Build another branch.
  7385. git -C "$(./getvar gem5_src_dir)" checkout some-branch
  7386. ./build-gem5 --gem5-build-id some-branch
  7387. # Restore master.
  7388. git -C "$(./getvar gem5_src_dir)" checkout -
  7389. # Run master.
  7390. ./run --gem5
  7391. # Run another branch.
  7392. git -C "$(./getvar gem5_src_dir)" checkout some-branch
  7393. ./run --gem5-build-id some-branch --gem5
  7394. ....
  7395. 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.
  7396. 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.
  7397. ===== gem5 worktree
  7398. <<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.
  7399. ....
  7400. # Build gem5 at the revision in the gem5 submodule.
  7401. ./build-gem5
  7402. # Create a branch at the same revision as the gem5 submodule.
  7403. ./build-gem5 --gem5-worktree my-new-feature
  7404. cd "$(./getvar --gem5-worktree my-new-feature)"
  7405. vim create-bugs
  7406. git add .
  7407. git commit -m 'Created a bug'
  7408. cd -
  7409. ./build-gem5 --gem5-worktree my-new-feature
  7410. # Run the submodule.
  7411. ./run --gem5 --run-id 0 &>/dev/null &
  7412. # Run the branch the need to check out anything.
  7413. # With --gem5-worktree, we can do both runs at the same time!
  7414. ./run --gem5 --gem5-worktree my-new-feature --run-id 1 &>/dev/null &
  7415. ....
  7416. `--gem5-worktree <worktree-id>` automatically creates:
  7417. * a link:https://git-scm.com/docs/git-worktree[Git worktree] of gem5 if one didn't exit yet for `<worktree-id>`
  7418. * a separate build directory, exactly like `--gem5-build-id my-new-feature` would
  7419. 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.
  7420. `--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.
  7421. 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.
  7422. 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.
  7423. ===== gem5 private source trees
  7424. Suppose that you are working on a private fork of gem5, but you want to use this repository to develop it as well.
  7425. 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.
  7426. Even removing remotes is not safe enough, since `git submodule update` and other submodule commands can restore the old public remote.
  7427. Instead, we provide the following safer process.
  7428. First do a separate private clone of you private repository outside of this repository:
  7429. ....
  7430. git clone https://my.private.repo.com/my-fork/gem5.git gem5-internal
  7431. gem5_internal="$(pwd)/gem5-internal"
  7432. ....
  7433. 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:
  7434. ....
  7435. cd linux-kernel-module-cheat
  7436. ./build-gem5 \
  7437. --gem5-build-dir "${gem5_internal}/build" \
  7438. --gem5-source-dir "$gem5_internal" \
  7439. ;
  7440. ./run-gem5 \
  7441. --gem5-build-dir "${gem5_internal}/build" \
  7442. --gem5-source-dir "$gem5_internal" \
  7443. ;
  7444. ....
  7445. With this setup, both your private gem5 source and build are safely kept outside of this public repository.
  7446. ===== gem5 debug build
  7447. The `gem5.debug` executable has optimizations turned off unlike the default `gem5.opt`, and provides a much better <<debug-the-emulator,debug experience>>:
  7448. ....
  7449. ./build-gem5 --arch aarch64 --gem5-build-type debug
  7450. ./run --arch aarch64 --debug-vm --gem5 --gem5-build-type debug
  7451. ....
  7452. 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.
  7453. Therefore, `--gem5-build-id` is not required.
  7454. 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:
  7455. ....
  7456. ./run --arch aarch64 --eval 'm5 exit' --gem5 --linux-build-id v4.16
  7457. ./run --arch aarch64 --eval 'm5 exit' --gem5 --linux-build-id v4.16 --gem5-build-type debug
  7458. ....
  7459. so you will likely only use this when it is unavoidable.
  7460. ==== Buildroot build variants
  7461. Allows you to have multiple versions of the GCC toolchain or root filesystem.
  7462. Analogous to the <<linux-kernel-build-variants>> but with the `--build-id` option instead:
  7463. ....
  7464. ./build-buildroot
  7465. git -C "$(./getvar buildroot_src_dir)" checkout 2018.05
  7466. ./build-buildroot --buildroot-build-id 2018.05
  7467. git -C "$(./getvar buildroot_src_dir)" checkout -
  7468. ./run
  7469. ./run --buildroot-build-id 2018.05
  7470. ....
  7471. === Directory structure
  7472. * `data`: gitignored user created data. Deleting this might lead to loss of data. Of course, if something there becomes is important enough to you, git track it.
  7473. ** `data/9p`: see <<9p>>
  7474. ** `data/gem5/<variant>`: see: <<gem5-build-variants>>
  7475. * link:packages/lkmc[]: Buildroot package that contains our kernel modules and userland C tests
  7476. * `out`: gitignored Build outputs. You won't lose data by deleting this folder since everything there can be re-generated, only time.
  7477. ** `out/<arch>`: arch specific outputs
  7478. *** `out/<arch>/buildroot`: standard Buildroot output
  7479. **** `out/<arch>/buildroot/build/linux-custom`: symlink to a variant, custom madness that we do on top of Buildroot: <<linux-kernel-build-variants>>
  7480. **** `out/<arch>/buildroot/build/linux-custom.<variant>`: what `linux-custom` points to
  7481. *** `out/<arch>/qemu`: QEMU runtime outputs
  7482. *** `out/<arch>/qemu/<run-id>/run.sh`: full CLI used to run QEMU. See: <<report-upstream-bugs>>
  7483. *** `out/<arch>/gem5/<run-id>/`: gem5 runtime outputs
  7484. **** `out/<arch>/gem5/<run-id>/m5out`
  7485. **** `out/<arch>/gem5/<run-id>/run.sh`: full CLI used to run gem5. See: <<report-upstream-bugs>>
  7486. ** `out/common`: cross arch outputs, for when we can gain a lot of time and space by sharing things that are common across different archs.
  7487. *** `out/common/dl/`: Buildroot caches downloaded source there due to `BR2_DL_DIR`
  7488. *** `out/common/gem5/`: `arm` and `aarch64` have the same build.
  7489. **** `out/common/gem5/<gem5-variant>/`: gem5 build output. In common to share the ARM and aarch64 builds.
  7490. ***** `out/common/gem5/<gem5-variant>/build/`: main build outputs, including the `gem5.opt` executable and object files
  7491. ***** `out/common/gem5/<gem5-variant>/system/`: `M5_PATH` directory, with DTBs and bootloaders
  7492. ==== gem5 directory
  7493. We Build the gem5 emulator through Buildroot basically just to reuse its timestamping system to avoid rebuilds.
  7494. There is also the `m5` tool that we must build through Buildroot ans install on the root filesystem, but we could just make two separate builds.
  7495. This directory has the following structure:
  7496. ==== include directory
  7497. link:include/[] contains headers that are shared across both kernel modules and userland structures.
  7498. They contain data structs and magic constant for kernel to userland communication.
  7499. ==== userland directory
  7500. Userland test programs.
  7501. For usage in the guest, build with:
  7502. ....
  7503. ./build-userland
  7504. ....
  7505. Source: link:build-userland[].
  7506. This makes them visible immediately on the 9P mount `/mnt/9p/out_root_overlay`.
  7507. In order to place them in the root filesystem image itself, you must also run:
  7508. ....
  7509. ./build-buildroot
  7510. ....
  7511. It is possible to build and run those examples directly on your host:
  7512. ....
  7513. cd userland
  7514. make
  7515. ./hello.out
  7516. make clean
  7517. ....
  7518. or more cleanly out of tree:
  7519. ....
  7520. ./build-userland --host --userland-build-id host
  7521. "$(./getvar --userland-build-id host userland_build_dir)/hello.out"
  7522. ....
  7523. Extra make flags may be passed as:
  7524. ....
  7525. ./build-userland --host --userland-build-id host-static --make-args='-B CFLAGS_EXTRA=-static'
  7526. "$(./getvar --userland-build-id host-static userland_build_dir)/hello.out"
  7527. ....
  7528. This for example would both force a rebuild due to `-B` and link statically due to `CFLAGS_EXTRA=-static`.
  7529. TODO: OpenMP does not like `-static`:
  7530. ....
  7531. /usr/lib/gcc/x86_64-linux-gnu/5/libgomp.a(target.o): In function `gomp_target_init':
  7532. (.text+0xba): warning: Using 'dlopen' in statically linked applications requires at runtime the shared libraries from the glibc version used for linking
  7533. ....
  7534. See: https://stackoverflow.com/questions/23869981/linking-openmp-statically-with-gcc
  7535. It is also possible to build other architectures with the host toolchain for other archs than your host arch:
  7536. ....
  7537. ./build-userland --arch arm --host --userland-build-id host
  7538. ....
  7539. You won't be able to run those executables directly, but this is interesting if you are playing around with <<qemu-user-mode>>.
  7540. ==== packages directory
  7541. Every directory inside it is a Buildroot package.
  7542. 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.:
  7543. ....
  7544. ./build-buildroot --config 'BR2_SAMPLE_PACKAGE=y'
  7545. ....
  7546. or force a rebuild after the first one with:
  7547. ....
  7548. ./build-buildroot --config 'BR2_SAMPLE_PACKAGE=y' -- sample_package-reconfigure
  7549. ....
  7550. then test it out with:
  7551. ....
  7552. ./run --eval-busybox '/sample_package.out'
  7553. ....
  7554. In particular, our kernel modules are stored inside a Buildroot package: link:packages/lkmc[].
  7555. ==== patches
  7556. ===== patches/global
  7557. Has the following structure:
  7558. ....
  7559. package-name/00001-do-something.patch
  7560. ....
  7561. The patches are then applied to the corresponding packages before build.
  7562. Uses `BR2_GLOBAL_PATCH_DIR`.
  7563. ===== patches/manual
  7564. 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.
  7565. These are typically patches that don't contain fundamental functionality, so we don't feel like forking the target repos.
  7566. ==== rootfs_overlay
  7567. We use this directory for:
  7568. * customized configuration files
  7569. * userland module test scripts that don't need to be compiled.
  7570. +
  7571. C files for example need compilation, and must go through the regular package system, e.g. through link:kernel_modules/user[].
  7572. This directory is copied into the target filesystem by link:copy-overlay[], which then it visible via <<9p>> on the guest at:
  7573. ....
  7574. ls /mnt/9p/out_rootfs_overlay
  7575. ....
  7576. Furthermore, since this directory does not require compilation, we also make it <<9p>> available to the guest directly even without `copy-overlay` at:
  7577. ....
  7578. ls /mnt/9p/rootfs_overlay
  7579. ....
  7580. This way you can just hack away the scripts and try them out immediately without any further operations.
  7581. === Test this repo
  7582. This section describes how to run the most complete set of tests possible.
  7583. It takes too much time to be feasible for every patch, but it should be done for every release.
  7584. ==== Automated tests
  7585. ....
  7586. ./build all-linux
  7587. ./test --size 3
  7588. echo $?
  7589. ....
  7590. should output 0.
  7591. Sources:
  7592. * link:build[]
  7593. * link:test[]
  7594. Test just the kernel modules:
  7595. ....
  7596. ./test-kernel-modules
  7597. echo $?
  7598. ....
  7599. Source: link:test-kernel-module[]
  7600. Test that the Internet works:
  7601. ....
  7602. ./run --arch x86_64 --kernel-cli '- lkmc_eval="ifup -a;wget -S google.com;poweroff;"'
  7603. ....
  7604. Source: link:rootfs_overlay/test_all.sh[].
  7605. ===== Test GDB
  7606. Shell 1:
  7607. ....
  7608. ./run --debug-guest
  7609. ....
  7610. Shell 2:
  7611. ....
  7612. ./run-gdb start_kernel
  7613. ....
  7614. Should break GDB at `start_kernel`.
  7615. Then proceed to do the following tests:
  7616. * `/count.sh` and `break __x64_sys_write`
  7617. * `insmod /timer.ko` and `break lkmc_timer_callback`
  7618. === Bisection
  7619. When updating the Linux kernel, QEMU and gem5, things sometimes break.
  7620. 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>>.
  7621. For example, when updating from QEMU `v2.12.0` to `v3.0.0-rc3`, the Linux kernel boot started to panic for `arm`.
  7622. 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:
  7623. ....
  7624. root_dir="$(pwd)"
  7625. cd "$(./getvar qemu_src_dir)"
  7626. git bisect start
  7627. # Check that our test script fails on v3.0.0-rc3 as expected, and mark it as bad.
  7628. "${root_dir}/qemu-bisect-boot"
  7629. # Should output 1.
  7630. echo #?
  7631. git bisect bad
  7632. # Same for the good end.
  7633. git checkout v2.12.0
  7634. "${root_dir}/qemu-bisect-boot"
  7635. # Should output 0.
  7636. echo #?
  7637. git bisect good
  7638. # This leaves us at the offending commit.
  7639. git bisect run ../biset-qemu-linux-boot
  7640. # Clean up after the bisection.
  7641. git bisect reset
  7642. git submodule update
  7643. "${root_dir}/build-qemu" --clean --qemu-build-id bisect
  7644. ....
  7645. An example of Linux kernel commit bisection on gem5 boots can be found at: link:bisect-linux-boot-gem5[].
  7646. === Update a forked submodule
  7647. This is a template update procedure for submodules for which we have some patches on on top of mainline.
  7648. This example is based on the Linux kernel, for which we used to have patches, but have since moved to mainline:
  7649. ....
  7650. # Last point before out patches.
  7651. last_mainline_revision=v4.15
  7652. next_mainline_revision=v4.16
  7653. cd "$(./getvar linux_src_dir)"
  7654. # Create a branch before the rebase in case things go wrong.
  7655. git checkout -b "lkmc-${last_mainline_revision}"
  7656. git remote set-url origin git@github.com:cirosantilli/linux.git
  7657. git push
  7658. git checkout master
  7659. git remote add up git://git.kernel.org/pub/scm/linux/kernel/git/stable/linux-stable.git
  7660. git fetch up
  7661. git rebase --onto "$next_mainline_revision" "$last_mainline_revision"
  7662. # And update the README to show off.
  7663. git commit -m "linux: update to ${next_mainline_revision}"
  7664. ....
  7665. === Sanity checks
  7666. Basic C and C++ hello worlds:
  7667. ....
  7668. /hello.out
  7669. /hello_cpp.out
  7670. ....
  7671. Output:
  7672. ....
  7673. hello
  7674. hello cpp
  7675. ....
  7676. Sources:
  7677. * link:userland/hello.c[]
  7678. * link:userland/hello_cpp.c[]
  7679. ==== rand_check.out
  7680. Print out several parameters that normally change randomly from boot to boot:
  7681. ....
  7682. ./run --eval-busybox '/rand_check.out;/poweroff.out'
  7683. ....
  7684. Source: link:userland/rand_check.c[]
  7685. This can be used to check the determinism of:
  7686. * <<norandmaps>>
  7687. * <<qemu-record-and-replay>>
  7688. === Release
  7689. Create a release:
  7690. ....
  7691. git clone https://github.com/cirosantilli/linux-kernel-module-cheat linux-kernel-module-cheat-release
  7692. cd linux-kernel-module-cheat-release
  7693. # export LKMC_GITHUB_TOKEN=<your-token>
  7694. ./release
  7695. ....
  7696. Source: link:release[]
  7697. This scripts does:
  7698. * configure
  7699. * build
  7700. * package with <<release-zip>>
  7701. * creates a tag of form `sha-<sha>`
  7702. * upload to GitHub with link:release-create-github[]
  7703. Cloning a clean tree is ideal as it generates clean images since <<remove-buildroot-packages,it is not possible to remove Buildroot packages>>
  7704. This should in particular enable to easily update <<prebuilt>>.
  7705. TODO also run tests and only release if they pass.
  7706. ==== release-zip
  7707. Create a zip containing all files required for <<prebuilt>>:
  7708. ....
  7709. ./build all-linux
  7710. ./release-zip
  7711. ....
  7712. Source: link:release-zip[]
  7713. This generates a zip file:
  7714. ....
  7715. echo "$(./getvar release_zip_file)"
  7716. ....
  7717. which you can then upload somewhere.
  7718. For example, you can create or update a GitHub release and upload automatically with:
  7719. ....
  7720. # export LKMC_GITHUB_TOKEN=<your-token>
  7721. ./release-upload
  7722. ....
  7723. Source: link:release-upload[]
  7724. Create `LKMC_GITHUB_TOKEN` under: https://github.com/settings/tokens/new and save it to your `.bashrc`.
  7725. TODO: generalize that so that people can upload to their forks.
  7726. === Design rationale
  7727. ==== Design goals
  7728. This project was created to help me understand, modify and test low level system components by using system simulators.
  7729. System simulators are cool compared to real hardware because they are:
  7730. * free
  7731. * make experiments highly reproducible
  7732. * 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.
  7733. The current components we focus the most on are:
  7734. * <<linux-kernel>> and Linux kernel modules
  7735. * full systems emulators, currently <<qemu-buildroot-setup,qemu>> and <<gem5-buildroot-setup,gem5>>
  7736. * <<buildroot>>. We use and therefore document, a large part of its feature set.
  7737. The following components are not covered, but they would also benefit from this setup, and it shouldn't be hard to add them:
  7738. * C standard libraries
  7739. * 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.
  7740. The design goals are to provide setups that are:
  7741. * highly automated: "just works"
  7742. * thoroughly documented: you know what "just works" means
  7743. * can be fully built from source: to give visibility and allow modifications
  7744. * can also use <<prebuilt, prebuilt binaries>> as much as possible: in case you are lazy or unable to build from source
  7745. ==== Setup trade-offs
  7746. The trade-offs between the different <<getting-started,setups>> are basically a balance between:
  7747. * speed ans size: how long and how much disk space do the build and run take?
  7748. * visibility: can you GDB step debug everything and read source code?
  7749. * modifiability: can you modify the source code and rebuild a modified version?
  7750. * portability: does it work on a Windows host? Could it ever?
  7751. * accuracy: how accurate does the simulation represent real hardware?
  7752. * compatibility: how likely is is that all the components will work well together: emulator, compiler, kernel, standard library, ...
  7753. * guest software availability: how wide is your choice of easily installed guest software packages? See also: <<linux-distro-choice>>
  7754. ==== Resource tradeoff guidelines
  7755. Choosing which features go into our default builds means making tradeoffs, here are our guidelines:
  7756. * keep the root filesystem as tiny as possible to make <<prebuilt>> small: only add BusyBox to have a small interactive system.
  7757. +
  7758. 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.
  7759. * enable every feature possible on the toolchain (GCC, Binutils), because changes imply Buildroot rebuilds
  7760. * runtime is sacred. Faster systems are:
  7761. +
  7762. --
  7763. ** easier to understand
  7764. ** run faster, which is specially for <<gem5>> which is slow
  7765. --
  7766. +
  7767. 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.
  7768. +
  7769. 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.
  7770. In order to learn how to measure some of those aspects, see: <<benchmark-this-repo>>
  7771. ==== Linux distro choice
  7772. We haven't found the ultimate distro yet, here is a summary table of trade-offs that we care about:
  7773. [options="header"]
  7774. |===
  7775. |Distro |Packages in single Git tree |Git tracked docs |Cross build without QEMU |Prebuilt downloads |Number of packages
  7776. |Buildroot 2018.05
  7777. |y
  7778. |y
  7779. |y
  7780. |n
  7781. |2k (1)
  7782. |Ubuntu 18.04
  7783. |n
  7784. |n
  7785. |n
  7786. |y
  7787. |50k (3)
  7788. |Yocto 2.5 (8)
  7789. |?
  7790. |y (5)
  7791. |?
  7792. |y (6)
  7793. |400 (7)
  7794. |Alpine Linux 3.8.0
  7795. |y
  7796. |n (1)
  7797. |?
  7798. |y
  7799. |2000 (4)
  7800. |===
  7801. * (1): Wiki... https://wiki.alpinelinux.org/wiki/Main_Page
  7802. * (2): `ls packages | wc`
  7803. * (3): https://askubuntu.com/questions/120630/how-many-packages-are-in-the-main-repository
  7804. * (4): `ls main community non-free | wc`
  7805. * (5): yes, but on a separate Git tree... https://git.yoctoproject.org/cgit/cgit.cgi/yocto-docs/
  7806. * (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
  7807. * (7): `ls recipes-* | wc`
  7808. * (8): Poky reference system: http://git.yoctoproject.org/cgit/cgit.cgi/poky
  7809. === Fairy tale
  7810. ____
  7811. Once upon a time, there was a boy called Linus.
  7812. Linus made a super fun toy, and since he was not very humble, decided to call it Linux.
  7813. Linux was an awesome toy, but it had one big problem: it was very difficult to learn how to play with it!
  7814. 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.
  7815. One day, a mysterious new kid called Ciro tried to play with Linux, and like many before him, got very frustrated, and gave up.
  7816. 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.
  7817. Ciro noticed that if you used Buildroot together with Linux, and Linux suddenly became very fun to play with!
  7818. So Ciro decided to explain to as many kids as possible how to use Buildroot to play with Linux.
  7819. And so everyone was happy. Except some of the old weird kernel hackers who wanted to keep their mystique, but so be it.
  7820. THE END
  7821. ____
  7822. === Bibliography
  7823. Runnable stuff:
  7824. * 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.
  7825. * 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.
  7826. * https://github.com/tinyclub/linux-lab Buildroot based, no kernel modules?
  7827. * https://github.com/agelastic/eudyptula
  7828. * 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/
  7829. * 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
  7830. * 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
  7831. Theory:
  7832. * 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.
  7833. +
  7834. 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...
  7835. * https://balau82.wordpress.com awesome low level resource
  7836. * https://rwmj.wordpress.com/ awesome red hatter
  7837. * https://lwn.net
  7838. * http://www.makelinux.net
  7839. * https://notes.shichao.io/lkd/
  7840. Awesome lists:
  7841. * https://github.com/gurugio/lowlevelprogramming-university
  7842. * https://github.com/uhub/awesome-c