README.adoc 293 KB

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