README.adoc 381 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557
  1. = Linux Kernel Module Cheat
  2. :idprefix:
  3. :idseparator: -
  4. :sectanchors:
  5. :sectlinks:
  6. :sectnumlevels: 6
  7. :sectnums:
  8. :toc: macro
  9. :toclevels: 6
  10. :toc-title:
  11. The perfect emulation setup to study and modify the <<linux-kernel>>, kernel modules, <<qemu-buildroot-setup,QEMU>> and <<gem5-buildroot-setup,gem5>>. Highly automated. Thoroughly documented. <<gdb>> and <<kgdb>> just work. Automated <<test-this-repo,tests>>. Powered by <<about-the-qemu-buildroot-setup,Buildroot>>. "Tested" in Ubuntu 18.04 host, x86 and ARM guests with kernel v4.20.
  12. TL;DR: <<qemu-buildroot-setup-getting-started>>
  13. toc::[]
  14. == Getting started
  15. Each child section describes a possible different setup for this repo.
  16. If you don't know which one to go for, start with <<qemu-buildroot-setup-getting-started>>.
  17. === QEMU Buildroot setup
  18. ==== QEMU Buildroot setup getting started
  19. This setup has been mostly tested on Ubuntu. For other host operating systems see: <<supported-hosts>>.
  20. Reserve 12Gb of disk and run:
  21. ....
  22. git clone https://github.com/cirosantilli/linux-kernel-module-cheat
  23. cd linux-kernel-module-cheat
  24. ./build --download-dependencies qemu-buildroot
  25. ./run
  26. ....
  27. You don't need to clone recursively even though we have `.git` submodules: `download-dependencies` fetches just the submodules that you need for this build to save time.
  28. If something goes wrong, see: <<common-build-issues>> and use our issue tracker: https://github.com/cirosantilli/linux-kernel-module-cheat/issues
  29. The initial build will take a while (30 minutes to 2 hours) to clone and build, see <<benchmark-builds>> for more details.
  30. If you don't want to wait, you could also try the following faster but much more limited methods:
  31. * <<prebuilt>>
  32. * <<host>>
  33. but you will soon find that they are simply not enough if you anywhere near serious about systems programming.
  34. After `./run`, QEMU opens up and you can start playing with the kernel modules inside the simulated system:
  35. ....
  36. insmod /hello.ko
  37. insmod /hello2.ko
  38. rmmod hello
  39. rmmod hello2
  40. ....
  41. This should print to the screen:
  42. ....
  43. hello init
  44. hello2 init
  45. hello cleanup
  46. hello2 cleanup
  47. ....
  48. which are `printk` messages from `init` and `cleanup` methods of those modules.
  49. Sources:
  50. * link:kernel_modules/hello.c[]
  51. * link:kernel_modules/hello2.c[]
  52. Quit QEMU with:
  53. ....
  54. Ctrl-A X
  55. ....
  56. See also: <<quit-qemu-from-text-mode>>.
  57. All available modules can be found in the link:kernel_modules[] directory.
  58. It is super easy to build for different <<cpu-architecture,CPU architectures>>, just use the `--arch` option:
  59. ....
  60. ./build --arch aarch64 --download-dependencies qemu-buildroot
  61. ./run --arch aarch64
  62. ....
  63. To avoid typing `--arch aarch64` many times, you set the default arch as explained at: <<default-command-line-arguments>>
  64. I now urge you to read the following sections which contain widely applicable information:
  65. * <<run-command-after-boot>>
  66. * <<clean-the-build>>
  67. * <<build-the-documentation>>
  68. * Linux kernel
  69. ** <<printk>>
  70. ** <<kernel-command-line-parameters>>
  71. Once you use <<gdb>> and <<tmux>>, your terminal will look a bit like this:
  72. ....
  73. [ 1.451857] input: AT Translated Set 2 keyboard as /devices/platform/i8042/s1│loading @0xffffffffc0000000: ../kernel_modules-1.0//timer.ko
  74. [ 1.454310] ledtrig-cpu: registered to indicate activity on CPUs │(gdb) b lkmc_timer_callback
  75. [ 1.455621] usbcore: registered new interface driver usbhid │Breakpoint 1 at 0xffffffffc0000000: file /home/ciro/bak/git/linux-kernel-module
  76. [ 1.455811] usbhid: USB HID core driver │-cheat/out/x86_64/buildroot/build/kernel_modules-1.0/./timer.c, line 28.
  77. [ 1.462044] NET: Registered protocol family 10 │(gdb) c
  78. [ 1.467911] Segment Routing with IPv6 │Continuing.
  79. [ 1.468407] sit: IPv6, IPv4 and MPLS over IPv4 tunneling driver │
  80. [ 1.470859] NET: Registered protocol family 17 │Breakpoint 1, lkmc_timer_callback (data=0xffffffffc0002000 <mytimer>)
  81. [ 1.472017] 9pnet: Installing 9P2000 support │ at /linux-kernel-module-cheat//out/x86_64/buildroot/build/
  82. [ 1.475461] sched_clock: Marking stable (1473574872, 0)->(1554017593, -80442)│kernel_modules-1.0/./timer.c:28
  83. [ 1.479419] ALSA device list: │28 {
  84. [ 1.479567] No soundcards found. │(gdb) c
  85. [ 1.619187] ata2.00: ATAPI: QEMU DVD-ROM, 2.5+, max UDMA/100 │Continuing.
  86. [ 1.622954] ata2.00: configured for MWDMA2 │
  87. [ 1.644048] scsi 1:0:0:0: CD-ROM QEMU QEMU DVD-ROM 2.5+ P5│Breakpoint 1, lkmc_timer_callback (data=0xffffffffc0002000 <mytimer>)
  88. [ 1.741966] tsc: Refined TSC clocksource calibration: 2904.010 MHz │ at /linux-kernel-module-cheat//out/x86_64/buildroot/build/
  89. [ 1.742796] clocksource: tsc: mask: 0xffffffffffffffff max_cycles: 0x29dc0f4s│kernel_modules-1.0/./timer.c:28
  90. [ 1.743648] clocksource: Switched to clocksource tsc │28 {
  91. [ 2.072945] input: ImExPS/2 Generic Explorer Mouse as /devices/platform/i8043│(gdb) bt
  92. [ 2.078641] EXT4-fs (vda): couldn't mount as ext3 due to feature incompatibis│#0 lkmc_timer_callback (data=0xffffffffc0002000 <mytimer>)
  93. [ 2.080350] EXT4-fs (vda): mounting ext2 file system using the ext4 subsystem│ at /linux-kernel-module-cheat//out/x86_64/buildroot/build/
  94. [ 2.088978] EXT4-fs (vda): mounted filesystem without journal. Opts: (null) │kernel_modules-1.0/./timer.c:28
  95. [ 2.089872] VFS: Mounted root (ext2 filesystem) readonly on device 254:0. │#1 0xffffffff810ab494 in call_timer_fn (timer=0xffffffffc0002000 <mytimer>,
  96. [ 2.097168] devtmpfs: mounted │ fn=0xffffffffc0000000 <lkmc_timer_callback>) at kernel/time/timer.c:1326
  97. [ 2.126472] Freeing unused kernel memory: 1264K │#2 0xffffffff810ab71f in expire_timers (head=<optimized out>,
  98. [ 2.126706] Write protecting the kernel read-only data: 16384k │ base=<optimized out>) at kernel/time/timer.c:1363
  99. [ 2.129388] Freeing unused kernel memory: 2024K │#3 __run_timers (base=<optimized out>) at kernel/time/timer.c:1666
  100. [ 2.139370] Freeing unused kernel memory: 1284K │#4 run_timer_softirq (h=<optimized out>) at kernel/time/timer.c:1692
  101. [ 2.246231] EXT4-fs (vda): warning: mounting unchecked fs, running e2fsck isd│#5 0xffffffff81a000cc in __do_softirq () at kernel/softirq.c:285
  102. [ 2.259574] EXT4-fs (vda): re-mounted. Opts: block_validity,barrier,user_xatr│#6 0xffffffff810577cc in invoke_softirq () at kernel/softirq.c:365
  103. hello S98 │#7 irq_exit () at kernel/softirq.c:405
  104. │#8 0xffffffff818021ba in exiting_irq () at ./arch/x86/include/asm/apic.h:541
  105. Apr 15 23:59:23 login[49]: root login on 'console' │#9 smp_apic_timer_interrupt (regs=<optimized out>)
  106. hello /root/.profile │ at arch/x86/kernel/apic/apic.c:1052
  107. # insmod /timer.ko │#10 0xffffffff8180190f in apic_timer_interrupt ()
  108. [ 6.791945] timer: loading out-of-tree module taints kernel. │ at arch/x86/entry/entry_64.S:857
  109. # [ 7.821621] 4294894248 │#11 0xffffffff82003df8 in init_thread_union ()
  110. [ 8.851385] 4294894504 │#12 0x0000000000000000 in ?? ()
  111. │(gdb)
  112. ....
  113. ==== How to hack stuff
  114. Besides a seamless <<qemu-buildroot-setup-getting-started,initial build>>, this project also aims to make it effortless to modify and rebuild several major components of the system, to serve as an awesome development setup.
  115. ===== Your first Linux kernel hack
  116. Let's hack up the <<linux-kernel-entry-point, Linux kernel entry point>>, which is an easy place to start.
  117. Open the file:
  118. ....
  119. vim submodules/linux/init/main.c
  120. ....
  121. and find the `start_kernel` function, then add there a:
  122. ....
  123. pr_info("I'VE HACKED THE LINUX KERNEL!!!");
  124. ....
  125. Then rebuild the Linux kernel, quit QEMU and reboot the modified kernel:
  126. ....
  127. ./build-linux
  128. ./run
  129. ....
  130. and, surely enough, your message has appeared at the beginning of the boot:
  131. ....
  132. <6>[ 0.000000] I'VE HACKED THE LINUX KERNEL!!!
  133. ....
  134. So you are now officially a Linux kernel hacker, way to go!
  135. We could have used just link:build[] to rebuild the kernel as in the <<qemu-buildroot-setup-getting-started,initial build>> instead of link:build-linux[], but building just the required individual components is preferred during development:
  136. * saves a few seconds from parsing Make scripts and reading timestamps
  137. * makes it easier to understand what is being done in more detail
  138. * allows passing more specific options to customize the build
  139. The link:build[] script is just a lightweight wrapper that calls the smaller build scripts, and you can see what `./build` does with:
  140. ....
  141. ./build --dry-run
  142. ....
  143. When you reach difficulties, QEMU makes it possible to easily GDB step debug the Linux kernel source code, see: <<gdb>>.
  144. ===== Your first kernel module hack
  145. Edit link:kernel_modules/hello.c[] to contain:
  146. ....
  147. pr_info("hello init hacked\n");
  148. ....
  149. and rebuild with:
  150. ....
  151. ./build-modules
  152. ....
  153. Now there are two way to test it out, the fast way, and the safe way.
  154. The fast way is, without quitting or rebooting QEMU, just directly re-insert the module with:
  155. ....
  156. insmod /mnt/9p/out_rootfs_overlay/hello.ko
  157. ....
  158. and the new `pr_info` message should now show on the terminal at the end of the boot.
  159. This works because we have a <<9p>> mount there setup by default, which mounts the host directory that contains the Build outputs on the guest:
  160. ....
  161. ls "$(./getvar out_rootfs_overlay_dir)"
  162. ....
  163. The fast method is slightly risky because your previously insmodded buggy kernel module attempt might have corrupted the kernel memory, which could affect future runs.
  164. Such failures are however unlikely, and you should be fine if you don't see anything weird happening.
  165. The safe way, is to fist quit QEMU, rebuild the modules, put them in the root filesystem, and then reboot:
  166. ....
  167. ./build-modules
  168. ./build-buildroot
  169. ./run --eval-after 'insmod /hello.ko'
  170. ....
  171. `./build-buildroot` is required after `./build-modules` because it re-generates the root filesystem with the modules that we compiled at `./build-modules`.
  172. You can see that `./build` does that as well, by running:
  173. ....
  174. ./build --dry-run
  175. ....
  176. `--eval-after` is optional: you could just type `insmod /hello.ko` in the terminal, but this makes it run automatically at the end of boot, and then drops you into a shell.
  177. If the guest and host are the same arch, typically x86_64, you can speed up boot further with <<kvm>>:
  178. ....
  179. ./run --kvm
  180. ....
  181. All of this put together makes the safe procedure acceptably fast for regular development as well.
  182. It is also easy to GDB step debug kernel modules with our setup, see: <<gdb-step-debug-kernel-module>>.
  183. ===== Your first QEMU hack
  184. Not satisfied with mere software? OK then, let's hack up the QEMU x86 CPU identification:
  185. ....
  186. vim submodules/qemu/target/i386/cpu.c
  187. ....
  188. and modify:
  189. ....
  190. .model_id = "QEMU Virtual CPU version " QEMU_HW_VERSION,
  191. ....
  192. to contain:
  193. ....
  194. .model_id = "QEMU Virtual CPU version HACKED " QEMU_HW_VERSION,
  195. ....
  196. then as usual rebuild and re-run:
  197. .....
  198. ./build-qemu
  199. ./run --eval-after 'grep "model name" /proc/cpuinfo'
  200. .....
  201. and once again, there is your message: QEMU communicated it to the Linux kernel, which printed it out.
  202. You have now gone from newb to hardware hacker in a mere 15 minutes, your rate of progress is truly astounding!!!
  203. Seriously though, if you want to be a real hardware hacker, it just can't be done with open source tools as of 2018. The root obstacle is that:
  204. * link:https://en.wikipedia.org/wiki/Semiconductor_fabrication_plant[Silicon fabs] don't publish reveal their link:https://en.wikipedia.org/wiki/Design_rule_checking[design rules]
  205. * which implies that there are no decent link:https://en.wikipedia.org/wiki/Standard_cell[standard cell libraries]. See also: https://www.quora.com/Are-there-good-open-source-standard-cell-libraries-to-learn-IC-synthesis-with-EDA-tools/answer/Ciro-Santilli
  206. * which implies that people can't develop open source link:https://en.wikipedia.org/wiki/Electronic_design_automation[EDA tools]
  207. * which implies that you can't get decent link:https://community.cadence.com/cadence_blogs_8/b/di/posts/hls-ppa-is-it-all-you-need-to-know[power, performance and area] estimates
  208. The only thing you can do with open source is purely functional designs with link:https://en.wikipedia.org/wiki/Verilator[Verilator], but you will never know if it can be actually produced and how efficient it can be.
  209. If you really want to develop semiconductors, your only choice is to join an university or a semiconductor company that has the EDA licenses.
  210. While hacking QEMU, you will likely want to GDB step its source. That is trivial since QEMU is just another userland program like any other, but our setup has a shortcut to make it even more convenient, see: <<debug-the-emulator>>.
  211. ==== About the QEMU Buildroot setup
  212. This is our reference setup, and the best supported one, use it unless you have good reason not to.
  213. It was historically the first one we did, and all sections have been tested with this setup unless explicitly noted.
  214. Read the following sections for further introductory material:
  215. * <<introduction-to-qemu>>
  216. * <<introduction-to-buildroot>>
  217. === gem5 Buildroot setup
  218. ==== About the gem5 Buildroot setup
  219. This setup is like the <<qemu-buildroot-setup>>, but it uses link:http://gem5.org/[gem5] instead of QEMU as a system simulator.
  220. QEMU tries to run as fast as possible and give correct results at the end, but it does not tell us how many CPU cycles it takes to do something, just the number of instructions it ran.
  221. The number of instructions executed is a very poor estimator of performance because in modern computers, a lot of time is spent waiting for memory requests rather than the instructions themselves.
  222. This kind of simulation is known as functional simulation.
  223. gem5 on the other hand, can simulate the system in more detail than QEMU, including:
  224. * simplified CPU pipeline
  225. * caches
  226. * DRAM timing
  227. and can therefore be used to estimate system performance, see: <<gem5-run-benchmark>> for an example.
  228. The downside of gem5 much slower than QEMU because of the greater simulation detail.
  229. See <<gem5-vs-qemu>> for a more thorough comparison.
  230. ==== gem5 Buildroot setup getting started
  231. For the most part, if you just add the `--emulator gem5` option or `*-gem5` suffix to all commands and everything should magically work.
  232. If you haven't built Buildroot yet for <<qemu-buildroot-setup>>, you can build from the beginning with:
  233. ....
  234. ./build --download-dependencies gem5-buildroot
  235. ./run --emulator gem5
  236. ....
  237. If you have already built previously, don't be afraid: gem5 and QEMU use almost the same root filesystem and kernel, so `./build` will be fast.
  238. Remember that the gem5 boot is <<benchmark-linux-kernel-boot,considerably slower>> than QEMU since the simulation is more detailed.
  239. To get a terminal, either open a new shell and run:
  240. ....
  241. ./gem5-shell
  242. ....
  243. You can quit the shell without killing gem5 by typing tilde followed by a period:
  244. ....
  245. ~.
  246. ....
  247. If you are inside <<tmux>>, which I highly recommend, you can both run gem5 stdout and open the guest terminal on a split window with:
  248. ....
  249. ./run --emulator gem5 --tmux
  250. ....
  251. See also: <<tmux-gem5>>.
  252. At the end of boot, it might not be very clear that you have the shell since some <<printk>> messages may appear in front of the prompt like this:
  253. ....
  254. # <6>[ 1.215329] clocksource: tsc: mask: 0xffffffffffffffff max_cycles: 0x1cd486fa865, max_idle_ns: 440795259574 ns
  255. <6>[ 1.215351] clocksource: Switched to clocksource tsc
  256. ....
  257. but if you look closely, the `PS1` prompt marker `#` is there already, just hit enter and a clear prompt line will appear.
  258. If you forgot to open the shell and gem5 exit, you can inspect the terminal output post-mortem at:
  259. ....
  260. less "$(./getvar --emulator gem5 m5out_dir)/system.pc.com_1.device"
  261. ....
  262. More gem5 information is present at: <<gem5>>
  263. Good next steps are:
  264. * <<gem5-run-benchmark>>
  265. * <<m5out-directory>>
  266. * <<m5ops>>
  267. [[docker]]
  268. === Docker host setup
  269. This repository has been tested inside clean link:https://en.wikipedia.org/wiki/Docker_(software)[Docker] containers.
  270. This is a good option if you are on a Linux host, but the native setup failed due to your weird host distribution, and you have better things to do with your life than to debug it. See also: <<supported-hosts>>.
  271. For example, to do a <<qemu-buildroot-setup>> inside Docker, run:
  272. ....
  273. sudo apt-get install docker
  274. ./run-docker create && \
  275. ./run-docker sh -- ./build --download-dependencies qemu-buildroot
  276. ./run-docker sh
  277. ....
  278. You are now left inside a shell in the Docker! From there, just run as usual:
  279. ....
  280. ./run
  281. ....
  282. The host git top level directory is mounted inside the guest with a link:https://stackoverflow.com/questions/23439126/how-to-mount-a-host-directory-in-a-docker-container[Docker volume], which means for example that you can use your host's GUI text editor directly on the files. Just don't forget that if you nuke that directory on the guest, then it gets nuked on the host as well!
  283. Command breakdown:
  284. * `./run-docker create`: create the image and container.
  285. +
  286. Needed only the very first time you use Docker, or if you run `./run-docker DESTROY` to restart for scratch, or save some disk space.
  287. +
  288. The image and container name is `lkmc`. The container shows under:
  289. +
  290. ....
  291. docker ps -a
  292. ....
  293. +
  294. and the image shows under:
  295. +
  296. ....
  297. docker images
  298. ....
  299. * `./run-docker sh`: open a shell on the container.
  300. +
  301. If it has not been started previously, start it. This can also be done explicitly with:
  302. +
  303. ....
  304. ./run-docker start
  305. ....
  306. +
  307. Quit the shell as usual with `Ctrl-D`
  308. +
  309. This can be called multiple times from different host terminals to open multiple shells.
  310. * `./run-docker stop`: stop the container.
  311. +
  312. This might save a bit of CPU and RAM once you stop working on this project, but it should not be a lot.
  313. * `./run-docker DESTROY`: delete the container and image.
  314. +
  315. This doesn't really clean the build, since we mount the guest's working directory on the host git top-level, so you basically just got rid of the `apt-get` installs.
  316. +
  317. To actually delete the Docker build, run on host:
  318. +
  319. ....
  320. # sudo rm -rf out.docker
  321. ....
  322. To use <<gdb>> from inside Docker, you need a second shell inside the container. You can either do that from another shell with:
  323. ....
  324. ./run-docker sh
  325. ....
  326. or even better, by starting a <<tmux>> session inside the container. We install `tmux` by default in the container.
  327. You can also start a second shell and run a command in it at the same time with:
  328. ....
  329. ./run-docker sh -- ./run-gdb start_kernel
  330. ....
  331. To use <<qemu-graphic-mode>> from Docker, run:
  332. ....
  333. ./run --graphic --vnc
  334. ....
  335. and then on host:
  336. ....
  337. sudo apt-get install vinagre
  338. ./vnc
  339. ....
  340. TODO make files created inside Docker be owned by the current user in host instead of `root`:
  341. * https://stackoverflow.com/questions/33681396/how-do-i-write-to-a-volume-container-as-non-root-in-docker
  342. * https://stackoverflow.com/questions/23544282/what-is-the-best-way-to-manage-permissions-for-docker-shared-volumes
  343. * https://stackoverflow.com/questions/31779802/shared-volume-file-permissions-ownership-docker
  344. [[prebuilt]]
  345. === Prebuilt setup
  346. ==== About the prebuilt setup
  347. This setup uses prebuilt binaries that we upload to GitHub from time to time.
  348. We don't currently provide a full prebuilt because it would be too big to host freely, notably because of the cross toolchain.
  349. Our prebuilts currently include:
  350. * <<qemu-buildroot-setup>> binaries
  351. ** Linux kernel
  352. ** root filesystem
  353. * <<baremetal-setup>> binaries for QEMU
  354. For more details, see our our <<release,release procedure>>.
  355. Advantage of this setup: saves time and disk space on the initial install, which is expensive in largely due to building the toolchain.
  356. The limitations are severe however:
  357. * can't <<gdb,GDB step debug the kernel>>, since the source and cross toolchain with GDB are not available. Buildroot cannot easily use a host toolchain: <<prebuilt-toolchain>>.
  358. +
  359. 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.
  360. * you won't get the latest version of this repository. Our <<travis>> attempt to automate builds failed, and storing a release for every commit would likely make GitHub mad at us anyways.
  361. * <<gem5>> is not currently supported. The major blocking point is how to avoid distributing the kernel images twice: once for gem5 which uses `vmlinux`, and once for QEMU which uses `arch/*` images, see also: <<vmlinux-vs-bzimage-vs-zimage-vs-image>>.
  362. This setup might be good enough for those developing simulators, as that requires less image modification. But once again, if you are serious about this, why not just let your computer build the <<qemu-buildroot-setup,full featured setup>> while you take a coffee or a nap? :-)
  363. ==== Prebuilt setup getting started
  364. Checkout to the latest tag and use the Ubuntu packaged QEMU to boot Linux:
  365. ....
  366. sudo apt-get install qemu-system-x86
  367. git clone https://github.com/cirosantilli/linux-kernel-module-cheat
  368. cd linux-kernel-module-cheat
  369. git checkout "$(git rev-list --tags --max-count=1)"
  370. ./release-download-latest
  371. unzip lkmc-*.zip
  372. ./run --prebuilt
  373. ....
  374. Or to run a baremetal example instead:
  375. ....
  376. ./run --arch aarch64 --baremetal baremetal/hello.c --prebuilt
  377. ....
  378. You have to checkout to the latest tag to ensure that the scripts match the release format: https://stackoverflow.com/questions/1404796/how-to-get-the-latest-tag-name-in-current-branch-in-git
  379. Be saner and use our custom built QEMU instead:
  380. ....
  381. ./build --download-dependencies qemu
  382. ./run
  383. ....
  384. This also allows you to <<your-first-qemu-hack,modify QEMU>> if you're into that sort of thing.
  385. To build the kernel modules as in <<your-first-kernel-module-hack>> do:
  386. ....
  387. git submodule update --depth 1 --init --recursive "$(./getvar linux_source_dir)"
  388. ./build-linux --no-modules-install -- modules_prepare
  389. ./build-modules
  390. ./run
  391. ....
  392. TODO: for now the only way to test those modules out without <<qemu-buildroot-setup-getting-started,building Buildroot>> is with 9p, since we currently rely on Buildroot to manipulate the root filesystem.
  393. Command explanation:
  394. * `modules_prepare` does the minimal build procedure required on the kernel for us to be able to compile the kernel modules, and is way faster than doing a full kernel build. A full kernel build would also work however.
  395. * the `./build-modules` command automatically falls back to the Ubuntu packaged GCC since you don't have the Buildroot toolchain
  396. * `--no-modules-install` is required otherwise the `make modules_install` target we run by default fails, since the kernel wasn't built
  397. To modify the Linux kernel, build and use it as usual:
  398. ....
  399. git submodule update --depth 1 --init --recursive "$(./getvar linux_source_dir)"
  400. ./build-linux
  401. ./run
  402. ....
  403. ////
  404. For gem5, do:
  405. ....
  406. git submodule update --init --depth 1 "$(./getvar linux_source_dir)"
  407. sudo apt-get install qemu-utils
  408. ./build-gem5
  409. ./run --emulator gem5 --prebuilt
  410. ....
  411. `qemu-utils` is required because we currently distribute `.qcow2` files which <<gem5-qcow2,gem5 can't handle>>, so we need `qemu-img` to extract them first.
  412. The Linux kernel is required for `extract-vmlinux` to convert the compressed kernel image which QEMU understands into the raw vmlinux that gem5 understands: https://superuser.com/questions/298826/how-do-i-uncompress-vmlinuz-to-vmlinux
  413. ////
  414. ////
  415. [[ubuntu]]
  416. === Ubuntu guest setup
  417. ==== About the Ubuntu guest setup
  418. This setup is similar to <<prebuilt>>, but instead of using Buildroot for the root filesystem, it downloads an Ubuntu image with Docker, and uses that as the root filesystem.
  419. The rationale for choice of Ubuntu as a second distribution in addition to Buildroot can be found at: <<linux-distro-choice>>
  420. Advantages over Buildroot:
  421. * saves build time
  422. * you get to play with a huge selection of Debian packages out of the box
  423. * more representative of most non-embedded production systems than BusyBox
  424. Disadvantages:
  425. * less visibility: https://askubuntu.com/questions/82302/how-to-compile-ubuntu-from-source-code The fact that that question has no answer makes me cringe
  426. * less compatibility, e.g. no one knows what the officially supported cross compilers are: https://askubuntu.com/questions/1046294/what-are-the-officially-supported-cross-compilers-for-ubuntu-server-alternative
  427. Docker is used here just as an image download provider since it has a wide variety of images. Why we don't just download the regular Ubuntu disk image:
  428. * that image is not ready to boot, but rather goes into an interactive installer: https://askubuntu.com/questions/884534/how-to-run-ubuntu-16-04-desktop-on-qemu/1046792#1046792
  429. * the default Ubuntu image has a large collection of software, and is large. The docker version is much more minimal.
  430. One alternative would be to use link:https://wiki.ubuntu.com/Base[Ubuntu base] which can be downloaded from: http://cdimage.ubuntu.com/ubuntu-base That provides a `.tgz` and comes very close to what we obtain with Docker, but without the need for `sudo`.
  431. ==== Ubuntu guest setup getting started
  432. TODO
  433. ....
  434. sudo ./build-docker
  435. ./run --docker
  436. ....
  437. `sudo` is required for Docker operations: https://askubuntu.com/questions/477551/how-can-i-use-docker-without-sudo
  438. ////
  439. [[host]]
  440. === Host kernel module setup
  441. **THIS IS DANGEROUS (AND FUN), YOU HAVE BEEN WARNED**
  442. 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.
  443. It has however severe limitations:
  444. * 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].
  445. * bugs can easily break you system. E.g.:
  446. ** segfaults can trivially lead to a kernel crash, and require a reboot
  447. ** 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`.
  448. ** 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]
  449. * can't control which hardware is used, notably the CPU architecture
  450. * can't step debug it with <<gdb,GDB>> easily. The alternatives are link:https://en.wikipedia.org/wiki/JTAG[JTAG] or <<kgdb>>, but those are less reliable, and require extra hardware.
  451. Still interested?
  452. ....
  453. ./build-modules --host
  454. ....
  455. Compilation will likely fail for some modules because of kernel or toolchain differences that we can't control on the host.
  456. The best solution is to compile just your modules with:
  457. ....
  458. ./build-modules --host -- hello hello2
  459. ....
  460. which is equivalent to:
  461. ....
  462. ./build-modules --host -- kernel_modules/hello.c kernel_modules/hello2.c
  463. ....
  464. Or just remove the `.c` extension from the failing files and try again:
  465. ....
  466. cd "$(./getvar kernel_modules_source_dir)"
  467. mv broken.c broken.c~
  468. ....
  469. Once you manage to compile, and have come to terms with the fact that this may blow up your host, try it out with:
  470. ....
  471. cd "$(./getvar kernel_modules_build_host_subdir)"
  472. sudo insmod hello.ko
  473. # Our module is there.
  474. sudo lsmod | grep hello
  475. # Last message should be: hello init
  476. dmesg -T
  477. sudo rmmod hello
  478. # Last message should be: hello exit
  479. dmesg -T
  480. # Not present anymore
  481. sudo lsmod | grep hello
  482. ....
  483. ==== Hello host
  484. Minimal host build system example:
  485. ....
  486. cd hello_host_kernel_module
  487. make
  488. sudo insmod hello.ko
  489. dmesg
  490. sudo rmmod hello.ko
  491. dmesg
  492. ....
  493. === Baremetal setup
  494. ==== About the baremetal setup
  495. This setup does not use the Linux kernel nor Buildroot at all: it just runs your very own minimal OS.
  496. `x86_64` is not currently supported, only `arm` and `aarch64`: I had made some x86 bare metal examples at: https://github.com/cirosantilli/x86-bare-metal-examples but I'm lazy to port them here now. Pull requests are welcome.
  497. The main reason this setup is included in this project, despite the word "Linux" being on the project name, is that a lot of the emulator boilerplate can be reused for both use cases.
  498. This setup allows you to make a tiny OS and that runs just a few instructions, use it to fully control the CPU to better understand the simulators for example, or develop your own OS if you are into that.
  499. You can also use C and a subset of the C standard library because we enable link:https://en.wikipedia.org/wiki/Newlib[Newlib] by default. See also: https://electronics.stackexchange.com/questions/223929/c-standard-libraries-on-bare-metal/400077#400077
  500. Our C bare-metal compiler is built with link:https://github.com/crosstool-ng/crosstool-ng[crosstool-NG]. If you have already built <<qemu-buildroot-setup,Buildroot>> previously, you will end up with two GCCs installed. Unfortunately I don't see a solution for this, since we need separate toolchains for Newlib on baremetal and glibc on Linux: https://stackoverflow.com/questions/38956680/difference-between-arm-none-eabi-and-arm-linux-gnueabi/38989869#38989869
  501. ==== Baremetal setup getting started
  502. Every `.c` file inside link:baremetal/[] and `.S` file inside `baremetal/arch/<arch>/` generates a separate baremetal image.
  503. For example, to run link:baremetal/hello.c[] in QEMU do:
  504. ....
  505. ./build --arch aarch64 --download-dependencies qemu-baremetal
  506. ./run --arch aarch64 --baremetal hello
  507. ....
  508. The terminal prints:
  509. ....
  510. hello
  511. ....
  512. Now let's run link:baremetal/arch/aarch64/add.S[]:
  513. ....
  514. ./run --arch aarch64 --baremetal arch/aarch64/add
  515. ....
  516. This time, the terminal does not print anything, which indicates success.
  517. If you look into the source, you will see that we just have an assertion there.
  518. You can see a sample assertion fail in link:baremetal/interactive/assert_fail.c[]:
  519. ....
  520. ./run --arch aarch64 --baremetal interactive/assert_fail
  521. ....
  522. and the terminal contains:
  523. ....
  524. lkmc_test_fail
  525. error: simulation error detected by parsing logs
  526. ....
  527. and the exit status of our script is 1:
  528. ....
  529. echo $?
  530. ....
  531. To modify a baremetal program, simply edit the file, .g.
  532. ....
  533. vim baremetal/hello.c
  534. ....
  535. and rebuild:
  536. ....
  537. ./build --arch aarch64 --download-dependencies qemu-baremetal
  538. ./run --arch aarch64 --baremetal hello
  539. ....
  540. `./build qemu-baremetal` had called link:build-baremetal[] for us previously, in addition to its requirements.
  541. `./build-baremetal` uses crosstool-NG, and so it must be preceded by link:build-crosstool-ng[], which `./build qemu-baremetal` also calls.
  542. Alternatively, for the sake of tab completion, we also accept relative paths inside `baremetal/`, for example the following also work:
  543. ....
  544. ./run --arch aarch64 --baremetal baremetal/hello.c
  545. ./run --arch aarch64 --baremetal baremetal/arch/aarch64/add.S
  546. ....
  547. Absolute paths however are used as is and must point to the actual executable:
  548. ....
  549. ./run --arch aarch64 --baremetal "$(./getvar --arch aarch64 baremetal_build_dir)/exit.elf"
  550. ....
  551. To use gem5 instead of QEMU do:
  552. ....
  553. ./build --download-dependencies gem5-baremetal
  554. ./run --arch aarch64 --baremetal interactive/prompt --emulator gem5
  555. ....
  556. and then <<qemu-buildroot-setup,as usual>> open a shell with:
  557. ....
  558. ./gem5-shell
  559. ....
  560. Or as usual, <<tmux>> users can do both in one go with:
  561. ....
  562. ./run --arch aarch64 --baremetal interactive/prompt --emulator gem5 --tmux
  563. ....
  564. TODO: the carriage returns are a bit different than in QEMU, see: <<gem5-baremetal-carriage-return>>.
  565. Note that `./build-baremetal` requires the `--emulator gem5` option, and generates separate executable images for both, as can be seen from:
  566. ....
  567. echo "$(./getvar --arch aarch64 --baremetal interactive/prompt --emulator qemu image)"
  568. echo "$(./getvar --arch aarch64 --baremetal interactive/prompt --emulator gem5 image)"
  569. ....
  570. This is unlike the Linux kernel that has a single image for both QEMU and gem5:
  571. ....
  572. echo "$(./getvar --arch aarch64 --emulator qemu image)"
  573. echo "$(./getvar --arch aarch64 --emulator gem5 image)"
  574. ....
  575. The reason for that is that on baremetal we don't parse the <<device-tree,device tress>> from memory like the Linux kernel does, which tells the kernel for example the UART address, and many other system parameters.
  576. `gem5` also supports the `RealViewPBX` machine, which represents an older hardware compared to the default `VExpress_GEM5_V1`:
  577. ....
  578. ./build-baremetal --arch aarch64 --emulator gem5 --machine RealViewPBX
  579. ./run --arch aarch64 --baremetal interactive/prompt --emulator gem5 --machine RealViewPBX
  580. ....
  581. This generates yet new separate images with new magic constants:
  582. ....
  583. echo "$(./getvar --arch aarch64 --baremetal interactive/prompt --emulator gem5 --machine VExpress_GEM5_V1 image)"
  584. echo "$(./getvar --arch aarch64 --baremetal interactive/prompt --emulator gem5 --machine RealViewPBX image)"
  585. ....
  586. But just stick to newer and better `VExpress_GEM5_V1` unless you have a good reason to use `RealViewPBX`.
  587. When doing bare metal programming, it is likely that you will want to learn assembly language basics. Have a look at these tutorials for the userland part:
  588. * https://github.com/cirosantilli/x86-assembly-cheat
  589. * https://github.com/cirosantilli/arm-assembly-cheat
  590. For more information on baremetal, see the section: <<baremetal>>.
  591. The following subjects are particularly important:
  592. * <<tracing>>
  593. * <<baremetal-gdb-step-debug>>
  594. === User mode setup
  595. Much like <<baremetal-setup>>, this is another fun setup that does not require Buildroot or the Linux kernel.
  596. Introduction at: <<user-mode-simulation>>.
  597. Getting started at: <<qemu-user-mode>>.
  598. [[gdb]]
  599. == GDB step debug
  600. === GDB step debug kernel boot
  601. `--wait-gdb` makes QEMU and gem5 wait for a GDB connection, otherwise we could accidentally go past the point we want to break at:
  602. ....
  603. ./run --wait-gdb
  604. ....
  605. Say you want to break at `start_kernel`. So on another shell:
  606. ....
  607. ./run-gdb start_kernel
  608. ....
  609. or at a given line:
  610. ....
  611. ./run-gdb init/main.c:1088
  612. ....
  613. Now QEMU will stop there, and you can use the normal GDB commands:
  614. ....
  615. list
  616. next
  617. continue
  618. ....
  619. See also:
  620. * http://stackoverflow.com/questions/11408041/how-to-debug-the-linux-kernel-with-gdb-and-qemu/33203642#33203642
  621. * http://stackoverflow.com/questions/4943857/linux-kernel-live-debugging-how-its-done-and-what-tools-are-used/42316607#42316607
  622. ==== GDB step debug kernel boot other archs
  623. Just don't forget to pass `--arch` to `./run-gdb`, e.g.:
  624. ....
  625. ./run --arch aarch64 --wait-gdb
  626. ....
  627. and:
  628. ....
  629. ./run-gdb --arch aarch64 start_kernel
  630. ....
  631. [[kernel-o0]]
  632. ==== Disable kernel compiler optimizations
  633. https://stackoverflow.com/questions/29151235/how-to-de-optimize-the-linux-kernel-to-and-compile-it-with-o0
  634. `O=0` is an impossible dream, `O=2` being the default.
  635. So get ready for some weird jumps, and `<value optimized out>` fun. Why, Linux, why.
  636. === GDB step debug kernel post-boot
  637. Let's observe the kernel `write` system call as it reacts to some userland actions.
  638. Start QEMU with just:
  639. ....
  640. ./run
  641. ....
  642. and after boot inside a shell run:
  643. ....
  644. /count.sh
  645. ....
  646. which counts to infinity to stdout. Source: link:rootfs_overlay/count.sh[].
  647. Then in another shell, run:
  648. ....
  649. ./run-gdb
  650. ....
  651. and then hit:
  652. ....
  653. Ctrl-C
  654. break __x64_sys_write
  655. continue
  656. continue
  657. continue
  658. ....
  659. And you now control the counting on the first shell from GDB!
  660. Before v4.17, the symbol name was just `sys_write`, the change happened at link:https://github.com/torvalds/linux/commit/d5a00528b58cdb2c71206e18bd021e34c4eab878[d5a00528b58cdb2c71206e18bd021e34c4eab878]. As of Linux v 4.19, the function is called `sys_write` in `arm`, and `__arm64_sys_write` in `aarch64`. One good way to find it if the name changes again is to try:
  661. ....
  662. rbreak .*sys_write
  663. ....
  664. or just have a quick look at the sources!
  665. 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.
  666. === tmux
  667. tmux just makes things even more fun by allowing us to see both terminals at once without dragging windows around!
  668. First start `tmux` with:
  669. ....
  670. tmux
  671. ....
  672. Now that you are inside a shell inside tmux, run:
  673. ....
  674. ./run --wait-gdb --tmux
  675. ....
  676. Gives splits the terminal into two panes:
  677. * left: usual QEMU
  678. * right: gdb
  679. and focuses on the GDB pane.
  680. Now you can navigate with the usual tmux shortcuts:
  681. * switch between the two panes with: `Ctrl-B O`
  682. * close either pane by killing its terminal with `Ctrl-D` as usual
  683. To start again, switch back to the QEMU pane, kill the emulator, and re-run:
  684. ....
  685. ./run --wait-gdb --tmux
  686. ....
  687. This automatically clears the GDB pane, and starts a new one.
  688. Pass extra GDB arguments with:
  689. ....
  690. ./run --wait-gdb --tmux-args start_kernel
  691. ....
  692. See the tmux manual for further details:
  693. ....
  694. man tmux
  695. ....
  696. Bibliography: https://unix.stackexchange.com/questions/152738/how-to-split-a-new-window-and-run-a-command-in-this-new-window-using-tmux/432111#432111
  697. ==== tmux gem5
  698. If you are using gem5 instead of QEMU, `--tmux` has a different effect: it opens the gem5 terminal instead of the debugger:
  699. ....
  700. ./run --emulator gem5 --tmux
  701. ....
  702. If you also want to use the debugger with gem5, you will need to create new terminals as usual.
  703. From inside tmux, you can do that with `Ctrl-B C` or `Ctrl-B %`.
  704. To see the debugger by default instead of the terminal, run:
  705. ....
  706. ./tmu ./run-gdb
  707. ./run --wait-gdb --emulator gem5
  708. ....
  709. === GDB step debug kernel module
  710. http://stackoverflow.com/questions/28607538/how-to-debug-linux-kernel-modules-with-qemu/44095831#44095831
  711. Loadable kernel modules are a bit trickier since the kernel can place them at different memory locations depending on load order.
  712. So we cannot set the breakpoints before `insmod`.
  713. However, the Linux kernel GDB scripts offer the `lx-symbols` command, which takes care of that beautifully for us.
  714. Shell 1:
  715. ....
  716. ./run
  717. ....
  718. Wait for the boot to end and run:
  719. ....
  720. insmod /timer.ko
  721. ....
  722. Source: link:kernel_modules/timer.c[].
  723. This prints a message to dmesg every second.
  724. Shell 2:
  725. ....
  726. ./run-gdb
  727. ....
  728. In GDB, hit `Ctrl-C`, and note how it says:
  729. ....
  730. scanning for modules in /root/linux-kernel-module-cheat/out/kernel_modules/x86_64/kernel_modules
  731. loading @0xffffffffc0000000: /root/linux-kernel-module-cheat/out/kernel_modules/x86_64/kernel_modules/timer.ko
  732. ....
  733. That's `lx-symbols` working! Now simply:
  734. ....
  735. break lkmc_timer_callback
  736. continue
  737. continue
  738. continue
  739. ....
  740. and we now control the callback from GDB!
  741. Just don't forget to remove your breakpoints after `rmmod`, or they will point to stale memory locations.
  742. TODO: why does `break work_func` for `insmod kthread.ko` not very well? Sometimes it breaks but not others.
  743. [[gdb-step-debug-kernel-module-arm]]
  744. ==== GDB step debug kernel module insmodded by init on ARM
  745. TODO on `arm` 51e31cdc2933a774c2a0dc62664ad8acec1d2dbe it does not always work, and `lx-symbols` fails with the message:
  746. ....
  747. loading vmlinux
  748. Traceback (most recent call last):
  749. File "/linux-kernel-module-cheat//out/arm/buildroot/build/linux-custom/scripts/gdb/linux/symbols.py", line 163, in invoke
  750. self.load_all_symbols()
  751. File "/linux-kernel-module-cheat//out/arm/buildroot/build/linux-custom/scripts/gdb/linux/symbols.py", line 150, in load_all_symbols
  752. [self.load_module_symbols(module) for module in module_list]
  753. File "/linux-kernel-module-cheat//out/arm/buildroot/build/linux-custom/scripts/gdb/linux/symbols.py", line 110, in load_module_symbols
  754. module_name = module['name'].string()
  755. gdb.MemoryError: Cannot access memory at address 0xbf0000cc
  756. Error occurred in Python command: Cannot access memory at address 0xbf0000cc
  757. ....
  758. Can't reproduce on `x86_64` and `aarch64` are fine.
  759. It is kind of random: if you just `insmod` manually and then immediately `./run-gdb --arch arm`, then it usually works.
  760. But this fails most of the time: shell 1:
  761. ....
  762. ./run --arch arm --eval-after 'insmod /hello.ko'
  763. ....
  764. shell 2:
  765. ....
  766. ./run-gdb --arch arm
  767. ....
  768. then hit `Ctrl-C` on shell 2, and voila.
  769. Then:
  770. ....
  771. cat /proc/modules
  772. ....
  773. says that the load address is:
  774. ....
  775. 0xbf000000
  776. ....
  777. so it is close to the failing `0xbf0000cc`.
  778. `readelf`:
  779. ....
  780. ./run-toolchain readelf -- -s "$(./getvar kernel_modules_build_subdir)/hello.ko"
  781. ....
  782. does not give any interesting hits at `cc`, no symbol was placed that far.
  783. ==== GDB module_init
  784. TODO find a more convenient method. We have working methods, but they are not ideal.
  785. 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!
  786. Possibly asked at:
  787. * https://stackoverflow.com/questions/37059320/debug-a-kernel-module-being-loaded
  788. * https://stackoverflow.com/questions/11888412/debug-the-init-module-call-of-a-linux-kernel-module
  789. ===== GDB module_init step into it
  790. This is the best method we've found so far.
  791. The kernel calls `module_init` synchronously, therefore it is not hard to step into that call.
  792. As of 4.16, the call happens in `do_one_initcall`, so we can do in shell 1:
  793. ....
  794. ./run
  795. ....
  796. shell 2 after boot finishes (because there are other calls to `do_init_module` at boot, presumably for the built-in modules):
  797. ....
  798. ./run-gdb do_one_initcall
  799. ....
  800. then step until the line:
  801. ....
  802. 833 ret = fn();
  803. ....
  804. which does the actual call, and then step into it.
  805. For the next time, you can also put a breakpoint there directly:
  806. ....
  807. ./run-gdb init/main.c:833
  808. ....
  809. How we found this out: first we got <<gdb-module_init-calculate-entry-address>> working, and then we did a `bt`. AKA cheating :-)
  810. ===== GDB module_init calculate entry address
  811. This works, but is a bit annoying.
  812. 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.
  813. So once we find the address the first time, we can just reuse it afterwards, as long as we don't modify the module.
  814. Do a fresh boot and get the module:
  815. ....
  816. ./run --eval-after '/pr_debug.sh;insmod /fops.ko;/poweroff.out'
  817. ....
  818. The boot must be fresh, because the load address changes every time we insert, even after removing previous modules.
  819. The base address shows on terminal:
  820. ....
  821. 0xffffffffc0000000 .text
  822. ....
  823. Now let's find the offset of `myinit`:
  824. ....
  825. ./run-toolchain readelf -- \
  826. -s "$(./getvar kernel_modules_build_subdir)/fops.ko" | \
  827. grep myinit
  828. ....
  829. which gives:
  830. ....
  831. 30: 0000000000000240 43 FUNC LOCAL DEFAULT 2 myinit
  832. ....
  833. so the offset address is `0x240` and we deduce that the function will be placed at:
  834. ....
  835. 0xffffffffc0000000 + 0x240 = 0xffffffffc0000240
  836. ....
  837. Now we can just do a fresh boot on shell 1:
  838. ....
  839. ./run --eval 'insmod /fops.ko;/poweroff.out' --wait-gdb
  840. ....
  841. and on shell 2:
  842. ....
  843. ./run-gdb '*0xffffffffc0000240'
  844. ....
  845. GDB then breaks, and `lx-symbols` works.
  846. ===== GDB module_init break at the end of sys_init_module
  847. TODO not working. This could be potentially very convenient.
  848. 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.
  849. Beware that there are both `sys_init_module` and `sys_finit_module` syscalls, and `insmod` uses `fmodule_init` by default.
  850. Both call `do_module_init` however, which is what `lx-symbols` hooks to.
  851. If we try:
  852. ....
  853. b sys_finit_module
  854. ....
  855. then hitting:
  856. ....
  857. n
  858. ....
  859. does not break, and insertion happens, likely because of optimizations? <<kernel-o0>>
  860. Then we try:
  861. ....
  862. b do_init_module
  863. ....
  864. A naive:
  865. ....
  866. fin
  867. ....
  868. also fails to break!
  869. Finally, in despair we notice that <<pr_debug>> prints the kernel load address as explained at <<bypass-lx-symbols>>.
  870. 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.
  871. ===== GDB module_init add trap instruction
  872. This is another possibility: we could modify the module source by adding a trap instruction of some kind.
  873. This appears to be described at: https://www.linuxjournal.com/article/4525
  874. But it refers to a `gdbstart` script which is not in the tree anymore and beyond my `git log` capabilities.
  875. And just adding:
  876. ....
  877. asm( " int $3");
  878. ....
  879. directly gives an <<oops,oops>> as I'd expect.
  880. ==== Bypass lx-symbols
  881. Useless, but a good way to show how hardcore you are. Disable `lx-symbols` with:
  882. ....
  883. ./run-gdb --no-lxsymbols
  884. ....
  885. From inside guest:
  886. ....
  887. insmod /timer.ko
  888. cat /proc/modules
  889. ....
  890. as mentioned at:
  891. * https://stackoverflow.com/questions/6384605/how-to-get-address-of-a-kernel-module-loaded-using-insmod/6385818
  892. * https://unix.stackexchange.com/questions/194405/get-base-address-and-size-of-a-loaded-kernel-module
  893. This will give a line of form:
  894. ....
  895. fops 2327 0 - Live 0xfffffffa00000000
  896. ....
  897. And then tell GDB where the module was loaded with:
  898. ....
  899. Ctrl-C
  900. add-symbol-file ../../../rootfs_overlay/x86_64/timer.ko 0xffffffffc0000000
  901. 0xffffffffc0000000
  902. ....
  903. Alternatively, if the module panics before you can read `/proc/modules`, there is a <<pr_debug>> which shows the load address:
  904. ....
  905. echo 8 > /proc/sys/kernel/printk
  906. echo 'file kernel/module.c +p' > /sys/kernel/debug/dynamic_debug/control
  907. /myinsmod.out /hello.ko
  908. ....
  909. And then search for a line of type:
  910. ....
  911. [ 84.877482] 0xfffffffa00000000 .text
  912. ....
  913. Tested on 4f4749148273c282e80b58c59db1b47049e190bf + 1.
  914. === GDB step debug early boot
  915. TODO successfully debug the very first instruction that the Linux kernel runs, before `start_kernel`!
  916. Break at the very first instruction executed by QEMU:
  917. ....
  918. ./run-gdb --no-continue
  919. ....
  920. TODO why can't we break at early startup stuff such as:
  921. ....
  922. ./run-gdb extract_kernel
  923. ./run-gdb main
  924. ....
  925. 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?
  926. See also: https://stackoverflow.com/questions/2589845/what-are-the-first-operations-that-the-linux-kernel-executes-on-boot
  927. <<gem5-tracing>> with `--debug-flags=Exec` does show the right symbols however! So in the worst case, we can just read their source. Amazing.
  928. v4.19 also added a `CONFIG_HAVE_KERNEL_UNCOMPRESSED=y` option for having the kernel uncompressed which could make following the startup easier, but it is only available on s390. `aarch64` however is already uncompressed by default, so might be the easiest one. See also: <<vmlinux-vs-bzimage-vs-zimage-vs-image>>.
  929. ==== GDB step debug early boot by address
  930. One possibility is to run:
  931. ....
  932. ./trace-boot --arch arm
  933. ....
  934. and then find the second address (the first one does not work, already too late maybe):
  935. ....
  936. less "$(./getvar --arch arm trace_txt_file)"
  937. ....
  938. and break there:
  939. ....
  940. ./run --arch arm --wait-gdb
  941. ./run-gdb --arch arm '*0x1000'
  942. ....
  943. 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
  944. I also tried to hack `run-gdb` with:
  945. ....
  946. @@ -81,7 +81,7 @@ else
  947. ${gdb} \
  948. -q \\
  949. -ex 'add-auto-load-safe-path $(pwd)' \\
  950. --ex 'file vmlinux' \\
  951. +-ex 'file arch/arm/boot/compressed/vmlinux' \\
  952. -ex 'target remote localhost:${port}' \\
  953. ${brk} \
  954. -ex 'continue' \\
  955. ....
  956. and no I do have the symbols from `arch/arm/boot/compressed/vmlinux'`, but the breaks still don't work.
  957. === GDB step debug userland processes
  958. QEMU's `-gdb` GDB breakpoints are set on virtual addresses, so you can in theory debug userland processes as well.
  959. * https://stackoverflow.com/questions/26271901/is-it-possible-to-use-gdb-and-qemu-to-debug-linux-user-space-programs-and-kernel
  960. * https://stackoverflow.com/questions/16273614/debug-init-on-qemu-using-gdb
  961. You will generally want to use <<gdbserver>> for this as it is more reliable, but this method can overcome the following limitations of `gdbserver`:
  962. * the emulator does not support host to guest networking. This seems to be the case for gem5: <<gem5-host-to-guest-networking>>
  963. * cannot see the start of the `init` process easily
  964. * `gdbserver` alters the working of the kernel, and makes your run less representative
  965. Known limitations of direct userland debugging:
  966. * 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.
  967. * TODO step into shared libraries. If I attempt to load them explicitly:
  968. +
  969. ....
  970. (gdb) sharedlibrary ../../staging/lib/libc.so.0
  971. No loaded shared libraries match the pattern `../../staging/lib/libc.so.0'.
  972. ....
  973. +
  974. since GDB does not know that libc is loaded.
  975. ==== GDB step debug userland custom init
  976. This is the userland debug setup most likely to work, since at init time there is only one userland executable running.
  977. For executables from the <<userland-directory>> such as link:userland/count.c[]:
  978. * Shell 1:
  979. +
  980. ....
  981. ./run --wait-gdb --kernel-cli 'init=/count.out'
  982. ....
  983. * Shell 2:
  984. +
  985. ....
  986. ./run-gdb-user count main
  987. ....
  988. +
  989. Alternatively, we could also pass the full path to the executable:
  990. +
  991. ....
  992. ./run-gdb-user "$(./getvar userland_build_dir)/sleep_forever.out" main
  993. ....
  994. +
  995. Path resolution is analogous to <<baremetal-setup-getting-started,that of `./run --baremetal`>>.
  996. Then, as soon as boot ends, we are left inside a debug session that looks just like what `gdbserver` would produce.
  997. ==== GDB step debug userland BusyBox init
  998. BusyBox custom init process:
  999. * Shell 1:
  1000. +
  1001. ....
  1002. ./run --wait-gdb --kernel-cli 'init=/bin/ls'
  1003. ....
  1004. * Shell 2:
  1005. +
  1006. ....
  1007. ./run-gdb-user "$(./getvar buildroot_build_build_dir)"/busybox-*/busybox ls_main
  1008. ....
  1009. This follows BusyBox' convention of calling the main for each executable as `<exec>_main` since the `busybox` executable has many "mains".
  1010. BusyBox default init process:
  1011. * Shell 1:
  1012. +
  1013. ....
  1014. ./run --wait-gdb
  1015. ....
  1016. * Shell 2:
  1017. +
  1018. ....
  1019. ./run-gdb-user "$(./getvar buildroot_build_build_dir)"/busybox-*/busybox init_main
  1020. ....
  1021. `init` cannot be debugged with <<gdbserver>> without modifying the source, or else `/sbin/init` exits early with:
  1022. ....
  1023. "must be run as PID 1"
  1024. ....
  1025. ==== GDB step debug userland non-init
  1026. Non-init process:
  1027. * Shell 1:
  1028. +
  1029. ....
  1030. ./run --wait-gdb
  1031. ....
  1032. * Shell 2:
  1033. +
  1034. ....
  1035. ./run-gdb-user myinsmod main
  1036. ....
  1037. * Shell 1 after the boot finishes:
  1038. +
  1039. ....
  1040. /myinsmod.out /hello.ko
  1041. ....
  1042. This is the least reliable setup as there might be other processes that use the given virtual address.
  1043. ===== GDB step debug userland non-init without --wait-gdb
  1044. TODO: without `--wait-gdb` and the `break main` that we do inside `./run-gdb-user` says:
  1045. ....
  1046. Cannot access memory at address 0x10604
  1047. ....
  1048. and then GDB never breaks. Tested at ac8663a44a450c3eadafe14031186813f90c21e4 + 1.
  1049. The exact behaviour seems to depend on the architecture:
  1050. * `arm`: happens always
  1051. * `x86_64`: appears to happen only if you try to connect GDB as fast as possible, before init has been reached.
  1052. * `aarch64`: could not observe the problem
  1053. We have also double checked the address with:
  1054. ....
  1055. ./run-toolchain --arch arm readelf -- \
  1056. -s "$(./getvar --arch arm kernel_modules_build_subdir)/fops.ko" | \
  1057. grep main
  1058. ....
  1059. and from GDB:
  1060. ....
  1061. info line main
  1062. ....
  1063. and both give:
  1064. ....
  1065. 000105fc
  1066. ....
  1067. which is just 8 bytes before `0x10604`.
  1068. `gdbserver` also says `0x10604`.
  1069. However, if do a `Ctrl-C` in GDB, and then a direct:
  1070. ....
  1071. b *0x000105fc
  1072. ....
  1073. it works. Why?!
  1074. 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.
  1075. === GDB call
  1076. GDB can call functions as explained at: https://stackoverflow.com/questions/1354731/how-to-evaluate-functions-in-gdb
  1077. However this is failing for us:
  1078. * some symbols are not visible to `call` even though `b` sees them
  1079. * for those that are, `call` fails with an E14 error
  1080. E.g.: if we break on `__x64_sys_write` on `/count.sh`:
  1081. ....
  1082. >>> call printk(0, "asdf")
  1083. Could not fetch register "orig_rax"; remote failure reply 'E14'
  1084. >>> b printk
  1085. Breakpoint 2 at 0xffffffff81091bca: file kernel/printk/printk.c, line 1824.
  1086. >>> call fdget_pos(fd)
  1087. No symbol "fdget_pos" in current context.
  1088. >>> b fdget_pos
  1089. Breakpoint 3 at 0xffffffff811615e3: fdget_pos. (9 locations)
  1090. >>>
  1091. ....
  1092. even though `fdget_pos` is the first thing `__x64_sys_write` does:
  1093. ....
  1094. 581 SYSCALL_DEFINE3(write, unsigned int, fd, const char __user *, buf,
  1095. 582 size_t, count)
  1096. 583 {
  1097. 584 struct fd f = fdget_pos(fd);
  1098. ....
  1099. I also noticed that I get the same error:
  1100. ....
  1101. Could not fetch register "orig_rax"; remote failure reply 'E14'
  1102. ....
  1103. when trying to use:
  1104. ....
  1105. fin
  1106. ....
  1107. on many (all?) functions.
  1108. See also: https://github.com/cirosantilli/linux-kernel-module-cheat/issues/19
  1109. === GDB view ARM system registers
  1110. `info all-registers` shows some of them.
  1111. The implementation is described at: https://stackoverflow.com/questions/46415059/how-to-observe-aarch64-system-registers-in-qemu/53043044#53043044
  1112. === GDB step debug multicore userland
  1113. For a more minimal baremetal multicore setup, see: <<arm-multicore>>.
  1114. We can set and get which cores the Linux kernel allows a program to run on with `sched_getaffinity` and `sched_setaffinity`:
  1115. ....
  1116. ./run --cpus 2 --eval-after '/sched_getaffinity.out'
  1117. ....
  1118. Source: link:userland/sched_getaffinity.c[]
  1119. Sample output:
  1120. ....
  1121. sched_getaffinity = 1 1
  1122. sched_getcpu = 1
  1123. sched_getaffinity = 1 0
  1124. sched_getcpu = 0
  1125. ....
  1126. Which shows us that:
  1127. * initially:
  1128. ** all 2 cores were enabled as shown by `sched_getaffinity = 1 1`
  1129. ** 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.
  1130. * then we restrict the affinity to just core 0, and we see that the program was actually moved to core 0
  1131. The number of cores is modified as explained at: <<number-of-cores>>
  1132. `taskset` from the util-linux package sets the initial core affinity of a program:
  1133. ....
  1134. ./build-buildroot \
  1135. --config 'BR2_PACKAGE_UTIL_LINUX=y' \
  1136. --config 'BR2_PACKAGE_UTIL_LINUX_SCHEDUTILS=y' \
  1137. ;
  1138. ./run --eval-after 'taskset -c 1,1 /sched_getaffinity.out'
  1139. ....
  1140. output:
  1141. ....
  1142. sched_getaffinity = 0 1
  1143. sched_getcpu = 1
  1144. sched_getaffinity = 1 0
  1145. sched_getcpu = 0
  1146. ....
  1147. so we see that the affinity was restricted to the second core from the start.
  1148. Let's do a QEMU observation to justify this example being in the repository with <<gdb-step-debug-userland-non-init,userland breakpoints>>.
  1149. We will run our `/sched_getaffinity.out` infinitely many time, on core 0 and core 1 alternatively:
  1150. ....
  1151. ./run \
  1152. --cpus 2 \
  1153. --wait-gdb \
  1154. --eval-after 'i=0; while true; do taskset -c $i,$i /sched_getaffinity.out; i=$((! $i)); done' \
  1155. ;
  1156. ....
  1157. on another shell:
  1158. ....
  1159. ./run-gdb-user "$(./getvar userland_build_dir)/sched_getaffinity.out" main
  1160. ....
  1161. Then, inside GDB:
  1162. ....
  1163. (gdb) info threads
  1164. Id Target Id Frame
  1165. * 1 Thread 1 (CPU#0 [running]) main () at sched_getaffinity.c:30
  1166. 2 Thread 2 (CPU#1 [halted ]) native_safe_halt () at ./arch/x86/include/asm/irqflags.h:55
  1167. (gdb) c
  1168. (gdb) info threads
  1169. Id Target Id Frame
  1170. 1 Thread 1 (CPU#0 [halted ]) native_safe_halt () at ./arch/x86/include/asm/irqflags.h:55
  1171. * 2 Thread 2 (CPU#1 [running]) main () at sched_getaffinity.c:30
  1172. (gdb) c
  1173. ....
  1174. and we observe that `info threads` shows the actual correct core on which the process was restricted to run by `taskset`!
  1175. We should also try it out with kernel modules: https://stackoverflow.com/questions/28347876/set-cpu-affinity-on-a-loadable-linux-kernel-module
  1176. TODO we then tried:
  1177. ....
  1178. ./run --cpus 2 --eval-after '/sched_getaffinity_threads.out'
  1179. ....
  1180. and:
  1181. ....
  1182. ./run-gdb-user "$(./getvar userland_build_dir)/sched_getaffinity_threads.out"
  1183. ....
  1184. to switch between two simultaneous live threads with different affinities, it just didn't break on our threads:
  1185. ....
  1186. b main_thread_0
  1187. ....
  1188. Bibliography:
  1189. * https://stackoverflow.com/questions/10490756/how-to-use-sched-getaffinity-and-sched-setaffinity-in-linux-from-c/50117787#50117787
  1190. * https://stackoverflow.com/questions/42800801/how-to-use-gdb-to-debug-qemu-with-smp-symmetric-multiple-processors
  1191. === Linux kernel GDB scripts
  1192. We source the Linux kernel GDB scripts by default for `lx-symbols`, but they also contains some other goodies worth looking into.
  1193. Those scripts basically parse some in-kernel data structures to offer greater visibility with GDB.
  1194. All defined commands are prefixed by `lx-`, so to get a full list just try to tab complete that.
  1195. 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.
  1196. Show dmesg:
  1197. ....
  1198. lx-dmesg
  1199. ....
  1200. Show the <<kernel-command-line-parameters>>:
  1201. ....
  1202. lx-cmdline
  1203. ....
  1204. Dump the device tree to a `fdtdump.dtb` file in the current directory:
  1205. ....
  1206. lx-fdtdump
  1207. pwd
  1208. ....
  1209. List inserted kernel modules:
  1210. ....
  1211. lx-lsmod
  1212. ....
  1213. Sample output:
  1214. ....
  1215. Address Module Size Used by
  1216. 0xffffff80006d0000 hello 16384 0
  1217. ....
  1218. Bibliography:
  1219. * https://events.static.linuxfound.org/sites/events/files/slides/Debugging%20the%20Linux%20Kernel%20with%20GDB.pdf
  1220. * https://wiki.linaro.org/LandingTeams/ST/GDB
  1221. ==== lx-ps
  1222. List all processes:
  1223. ....
  1224. lx-ps
  1225. ....
  1226. Sample output:
  1227. ....
  1228. 0xffff88000ed08000 1 init
  1229. 0xffff88000ed08ac0 2 kthreadd
  1230. ....
  1231. The second and third fields are obviously PID and process name.
  1232. The first one is more interesting, and contains the address of the `task_struct` in memory.
  1233. This can be confirmed with:
  1234. ....
  1235. p ((struct task_struct)*0xffff88000ed08000
  1236. ....
  1237. which contains the correct PID for all threads I've tried:
  1238. ....
  1239. pid = 1,
  1240. ....
  1241. 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!
  1242. On ARM, I tried:
  1243. ....
  1244. task_pt_regs((struct thread_info *)((struct task_struct)*0xffffffc00e8f8000))->uregs[ARM_pc]
  1245. ....
  1246. 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?
  1247. Bibliography:
  1248. * https://stackoverflow.com/questions/9561546/thread-aware-gdb-for-kernel
  1249. * https://wiki.linaro.org/LandingTeams/ST/GDB
  1250. * https://events.static.linuxfound.org/sites/events/files/slides/Debugging%20the%20Linux%20Kernel%20with%20GDB.pdf presentation: https://www.youtube.com/watch?v=pqn5hIrz3A8
  1251. === Debug the GDB remote protocol
  1252. For when it breaks again, or you want to add a new feature!
  1253. ....
  1254. ./run --debug
  1255. ./run-gdb --before '-ex "set remotetimeout 99999" -ex "set debug remote 1"' start_kernel
  1256. ....
  1257. See also: https://stackoverflow.com/questions/13496389/gdb-remote-protocol-how-to-analyse-packets
  1258. ==== Remote 'g' packet reply is too long
  1259. This error means that the GDB server, e.g. in QEMU, sent more registers than the GDB client expected.
  1260. This can happen for the following reasons:
  1261. * you set the architecture of the client wrong, often 32 vs 64 bit as mentioned at: https://stackoverflow.com/questions/4896316/gdb-remote-cross-debugging-fails-with-remote-g-packet-reply-is-too-long
  1262. * there is a bug in the GDB server and the XML description does not match the number of registers actually sent
  1263. * the GDB server does not send XML target descriptions and your GDB expects a different number of registers by default. E.g., gem5 d4b3e064adeeace3c3e7d106801f95c14637c12f does not send the XML files
  1264. The XML target description format is described a bit further at: https://stackoverflow.com/questions/46415059/how-to-observe-aarch64-system-registers-in-qemu/53043044#53043044
  1265. == KGDB
  1266. KGDB is kernel dark magic that allows you to GDB the kernel on real hardware without any extra hardware support.
  1267. It is useless with QEMU since we already have full system visibility with `-gdb`. So the goal of this setup is just to prepare you for what to expect when you will be in the treches of real hardware.
  1268. KGDB is cheaper than JTAG (free) and easier to setup (all you need is serial), but with less visibility as it depends on the kernel working, so e.g.: dies on panic, does not see boot sequence.
  1269. First run the kernel with:
  1270. ....
  1271. ./run --kgdb
  1272. ....
  1273. this passes the following options on the kernel CLI:
  1274. ....
  1275. kgdbwait kgdboc=ttyS1,115200
  1276. ....
  1277. `kgdbwait` tells the kernel to wait for KGDB to connect.
  1278. So the kernel sets things up enough for KGDB to start working, and then boot pauses waiting for connection:
  1279. ....
  1280. <6>[ 4.866050] Serial: 8250/16550 driver, 4 ports, IRQ sharing disabled
  1281. <6>[ 4.893205] 00:05: ttyS0 at I/O 0x3f8 (irq = 4, base_baud = 115200) is a 16550A
  1282. <6>[ 4.916271] 00:06: ttyS1 at I/O 0x2f8 (irq = 3, base_baud = 115200) is a 16550A
  1283. <6>[ 4.987771] KGDB: Registered I/O driver kgdboc
  1284. <2>[ 4.996053] KGDB: Waiting for connection from remote gdb...
  1285. Entering kdb (current=0x(____ptrval____), pid 1) on processor 0 due to Keyboard Entry
  1286. [0]kdb>
  1287. ....
  1288. KGDB expects the connection at `ttyS1`, our second serial port after `ttyS0` which contains the terminal.
  1289. The last line is the KDB prompt, and is covered at: <<kdb>>. Typing now shows nothing because that prompt is expecting input from `ttyS1`.
  1290. Instead, we connect to the serial port `ttyS1` with GDB:
  1291. ....
  1292. ./run-gdb --kgdb --no-continue
  1293. ....
  1294. Once GDB connects, it is left inside the function `kgdb_breakpoint`.
  1295. So now we can set breakpoints and continue as usual.
  1296. For example, in GDB:
  1297. ....
  1298. continue
  1299. ....
  1300. Then in QEMU:
  1301. ....
  1302. /count.sh &
  1303. /kgdb.sh
  1304. ....
  1305. link:rootfs_overlay:kgdb.sh[] pauses the kernel for KGDB, and gives control back to GDB.
  1306. And now in GDB we do the usual:
  1307. ....
  1308. break __x64_sys_write
  1309. continue
  1310. continue
  1311. continue
  1312. continue
  1313. ....
  1314. And now you can count from KGDB!
  1315. If you do: `break __x64_sys_write` immediately after `./run-gdb --kgdb`, it fails with `KGDB: BP remove failed: <address>`. I think this is because it would break too early on the boot sequence, and KGDB is not yet ready.
  1316. See also:
  1317. * https://github.com/torvalds/linux/blob/v4.9/Documentation/DocBook/kgdb.tmpl
  1318. * https://stackoverflow.com/questions/22004616/qemu-kernel-debugging-with-kgdb/44197715#44197715
  1319. === KGDB ARM
  1320. TODO: we would need a second serial for KGDB to work, but it is not currently supported on `arm` and `aarch64` with `-M virt` that we use: https://unix.stackexchange.com/questions/479085/can-qemu-m-virt-on-arm-aarch64-have-multiple-serial-ttys-like-such-as-pl011-t/479340#479340
  1321. One possible workaround for this would be to use <<kdb-arm>>.
  1322. Main more generic question: https://stackoverflow.com/questions/14155577/how-to-use-kgdb-on-arm
  1323. === KGDB kernel modules
  1324. Just works as you would expect:
  1325. ....
  1326. insmod /timer.ko
  1327. /kgdb.sh
  1328. ....
  1329. In GDB:
  1330. ....
  1331. break lkmc_timer_callback
  1332. continue
  1333. continue
  1334. continue
  1335. ....
  1336. and you now control the count.
  1337. === KDB
  1338. KDB is a way to use KDB directly in your main console, without GDB.
  1339. Advantage over KGDB: you can do everything in one serial. This can actually be important if you only have one serial for both shell and .
  1340. Disadvantage: not as much functionality as GDB, especially when you use Python scripts. Notably, TODO confirm you can't see the the kernel source code and line step as from GDB, since the kernel source is not available on guest (ah, if only debugging information supported full source, or if the kernel had a crazy mechanism to embed it).
  1341. Run QEMU as:
  1342. ....
  1343. ./run --kdb
  1344. ....
  1345. This passes `kgdboc=ttyS0` to the Linux CLI, therefore using our main console. Then QEMU:
  1346. ....
  1347. [0]kdb> go
  1348. ....
  1349. And now the `kdb>` prompt is responsive because it is listening to the main console.
  1350. After boot finishes, run the usual:
  1351. ....
  1352. /count.sh &
  1353. /kgdb.sh
  1354. ....
  1355. And you are back in KDB. Now you can count with:
  1356. ....
  1357. [0]kdb> bp __x64_sys_write
  1358. [0]kdb> go
  1359. [0]kdb> go
  1360. [0]kdb> go
  1361. [0]kdb> go
  1362. ....
  1363. And you will break whenever `__x64_sys_write` is hit.
  1364. You can get see further commands with:
  1365. ....
  1366. [0]kdb> help
  1367. ....
  1368. The other KDB commands allow you to step instructions, view memory, registers and some higher level kernel runtime data similar to the superior GDB Python scripts.
  1369. ==== KDB graphic
  1370. You can also use KDB directly from the <<graphics,graphic>> window with:
  1371. ....
  1372. ./run --graphic --kdb
  1373. ....
  1374. This setup could be used to debug the kernel on machines without serial, such as modern desktops.
  1375. This works because `--graphics` adds `kbd` (which stands for `KeyBoarD`!) to `kgdboc`.
  1376. ==== KDB ARM
  1377. TODO neither `arm` and `aarch64` are working as of 1cd1e58b023791606498ca509256cc48e95e4f5b + 1.
  1378. `arm` seems to place and hit the breakpoint correctly, but no matter how many `go` commands I do, the `count.sh` stdout simply does not show.
  1379. `aarch64` seems to place the breakpoint correctly, but after the first `go` the kernel oopses with warning:
  1380. ....
  1381. WARNING: CPU: 0 PID: 46 at /root/linux-kernel-module-cheat/submodules/linux/kernel/smp.c:416 smp_call_function_many+0xdc/0x358
  1382. ....
  1383. and stack trace:
  1384. ....
  1385. smp_call_function_many+0xdc/0x358
  1386. kick_all_cpus_sync+0x30/0x38
  1387. kgdb_flush_swbreak_addr+0x3c/0x48
  1388. dbg_deactivate_sw_breakpoints+0x7c/0xb8
  1389. kgdb_cpu_enter+0x284/0x6a8
  1390. kgdb_handle_exception+0x138/0x240
  1391. kgdb_brk_fn+0x2c/0x40
  1392. brk_handler+0x7c/0xc8
  1393. do_debug_exception+0xa4/0x1c0
  1394. el1_dbg+0x18/0x78
  1395. __arm64_sys_write+0x0/0x30
  1396. el0_svc_handler+0x74/0x90
  1397. el0_svc+0x8/0xc
  1398. ....
  1399. My theory is that every serious ARM developer has JTAG, and no one ever tests this, and the kernel code is just broken.
  1400. == gdbserver
  1401. Step debug userland processes to understand how they are talking to the kernel.
  1402. First build `gdbserver` into the root filesystem:
  1403. ....
  1404. ./build-buildroot --config 'BR2_PACKAGE_GDB=y'
  1405. ....
  1406. Then on guest, to debug link:userland/myinsmod.c[]:
  1407. ....
  1408. /gdbserver.sh /myinsmod.out /hello.ko
  1409. ....
  1410. Source: link:rootfs_overlay/gdbserver.sh[].
  1411. And on host:
  1412. ....
  1413. ./run-gdbserver myinsmod
  1414. ....
  1415. or alternatively with the full path:
  1416. ....
  1417. ./run-gdbserver "$(./getvar userland_build_dir)/myinsmod.out"
  1418. ....
  1419. https://reverseengineering.stackexchange.com/questions/8829/cross-debugging-for-arm-mips-elf-with-qemu-toolchain/16214#16214
  1420. === gdbserver BusyBox
  1421. Analogous to <<gdb-step-debug-userland-processes>>:
  1422. ....
  1423. /gdbserver.sh ls
  1424. ....
  1425. on host you need:
  1426. ....
  1427. ./run-gdbserver "$(./getvar buildroot_build_build_dir)"/busybox-*/busybox ls_main
  1428. ....
  1429. === gdbserver libc
  1430. Our setup gives you the rare opportunity to step debug libc and other system libraries.
  1431. For example in the guest:
  1432. ....
  1433. /gdbserver.sh /count.out
  1434. ....
  1435. Then on host:
  1436. ....
  1437. ./run-gdbserver count
  1438. ....
  1439. and inside GDB:
  1440. ....
  1441. break sleep
  1442. continue
  1443. ....
  1444. And you are now left inside the `sleep` function of our default libc implementation uclibc link:https://cgit.uclibc-ng.org/cgi/cgit/uclibc-ng.git/tree/libc/unistd/sleep.c?h=v1.0.30#n91[`libc/unistd/sleep.c`]!
  1445. You can also step into the `sleep` call:
  1446. ....
  1447. step
  1448. ....
  1449. This is made possible by the GDB command that we use by default:
  1450. ....
  1451. set sysroot ${common_buildroot_build_dir}/staging
  1452. ....
  1453. which automatically finds unstripped shared libraries on the host for us.
  1454. See also: https://stackoverflow.com/questions/8611194/debugging-shared-libraries-with-gdbserver/45252113#45252113
  1455. === gdbserver dynamic loader
  1456. 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
  1457. Bibliography: https://stackoverflow.com/questions/20114565/gdb-step-into-dynamic-linkerld-so-code
  1458. == CPU architecture
  1459. The portability of the kernel and toolchains is amazing: change an option and most things magically work on completely different hardware.
  1460. To use `arm` instead of x86 for example:
  1461. ....
  1462. ./build-buildroot --arch arm
  1463. ./run --arch arm
  1464. ....
  1465. Debug:
  1466. ....
  1467. ./run --arch arm --wait-gdb
  1468. # On another terminal.
  1469. ./run-gdb --arch arm
  1470. ....
  1471. We also have one letter shorthand names for the architectures and `--arch` option:
  1472. ....
  1473. # aarch64
  1474. ./run -a A
  1475. # arm
  1476. ./run -a a
  1477. # x86_64
  1478. ./run -a x
  1479. ....
  1480. Known quirks of the supported architectures are documented in this section.
  1481. === x86_64
  1482. ==== ring0
  1483. This example illustrates how reading from the x86 control registers with `mov crX, rax` can only be done from kernel land on ring0.
  1484. From kernel land:
  1485. ....
  1486. insmod ring0.ko
  1487. ....
  1488. works and output the registers, for example:
  1489. ....
  1490. cr0 = 0xFFFF880080050033
  1491. cr2 = 0xFFFFFFFF006A0008
  1492. cr3 = 0xFFFFF0DCDC000
  1493. ....
  1494. However if we try to do it from userland:
  1495. ....
  1496. /ring0.out
  1497. ....
  1498. stdout gives:
  1499. ....
  1500. Segmentation fault
  1501. ....
  1502. and dmesg outputs:
  1503. ....
  1504. traps: ring0.out[55] general protection ip:40054c sp:7fffffffec20 error:0 in ring0.out[400000+1000]
  1505. ....
  1506. Sources:
  1507. * link:kernel_modules/ring0.c[]
  1508. * link:kernel_modules/ring0.h[]
  1509. * link:userland/ring0.c[]
  1510. In both cases, we attempt to run the exact same code which is shared on the `ring0.h` header file.
  1511. Bibliography:
  1512. * https://stackoverflow.com/questions/7415515/how-to-access-the-control-registers-cr0-cr2-cr3-from-a-program-getting-segmenta/7419306#7419306
  1513. * https://stackoverflow.com/questions/18717016/what-are-ring-0-and-ring-3-in-the-context-of-operating-systems/44483439#44483439
  1514. === arm
  1515. ==== Run arm executable in aarch64
  1516. 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
  1517. I've tried:
  1518. ....
  1519. ./run-toolchain --arch aarch64 gcc -- -static ~/test/hello_world.c -o "$(./getvar p9_dir)/a.out"
  1520. ./run --arch aarch64 --eval-after '/mnt/9p/data/a.out'
  1521. ....
  1522. but it fails with:
  1523. ....
  1524. a.out: line 1: syntax error: unexpected word (expecting ")")
  1525. ....
  1526. === MIPS
  1527. We used to "support" it until f8c0502bb2680f2dbe7c1f3d7958f60265347005 (it booted) but dropped since one was testing it often.
  1528. If you want to revive and maintain it, send a pull request.
  1529. === Other architectures
  1530. It should not be too hard to port this repository to any architecture that Buildroot supports. Pull requests are welcome.
  1531. == init
  1532. When the Linux kernel finishes booting, it runs an executable as the first and only userland process. This executable is called the `init` program.
  1533. The init process is then responsible for setting up the entire userland (or destroying everything when you want to have fun).
  1534. This typically means reading some configuration files (e.g. `/etc/initrc`) and forking a bunch of userland executables based on those files, including the very interactive shell that we end up on.
  1535. systemd provides a "popular" init implementation for desktop distros as of 2017.
  1536. BusyBox provides its own minimalistic init implementation which Buildroot, and therefore this repo, uses by default.
  1537. The `init` program can be either an executable shell text file, or a compiled ELF file. It becomes easy to accept this once you see that the `exec` system call handles both cases equally: https://unix.stackexchange.com/questions/174062/can-the-init-process-be-a-shell-script-in-linux/395375#395375
  1538. The `init` executable is searched for in a list of paths in the root filesystem, including `/init`, `/sbin/init` and a few others. For more details see: <<path-to-init>>
  1539. === Replace init
  1540. To have more control over the system, you can replace BusyBox's init with your own.
  1541. The most direct way to replace `init` with our own is to just use the `init=` <<kernel-command-line-parameters,command line parameter>> directly:
  1542. ....
  1543. ./run --kernel-cli 'init=/count.sh'
  1544. ....
  1545. This just counts every second forever and does not give you a shell.
  1546. This method is not very flexible however, as it is hard to reliably pass multiple commands and command line arguments to the init with it, as explained at: <<init-environment>>.
  1547. For this reason, we have created a more robust helper method with the `--eval` option:
  1548. ....
  1549. ./run --eval 'echo "asdf qwer";insmod /hello.ko;/poweroff.out'
  1550. ....
  1551. The `--eval` option replaces init with a shell script that just evals the given command.
  1552. It is basically a shortcut for:
  1553. ....
  1554. ./run --kernel-cli 'init=/eval_base64.sh - lkmc_eval="insmod /hello.ko;/poweroff.out"'
  1555. ....
  1556. Source: link:rootfs_overlay/eval_base64.sh[].
  1557. This allows quoting and newlines by base64 encoding on host, and decoding on guest, see: <<kernel-command-line-parameters-escaping>>.
  1558. It also automatically chooses between `init=` and `rcinit=` for you, see: <<path-to-init>>
  1559. `--eval` replaces BusyBox' init completely, which makes things more minimal, but also has has the following consequences:
  1560. * `/etc/fstab` mounts are not done, notably `/proc` and `/sys`, test it out with:
  1561. +
  1562. ....
  1563. ./run --eval 'echo asdf;ls /proc;ls /sys;echo qwer'
  1564. ....
  1565. * 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:
  1566. +
  1567. ....
  1568. ./run --eval 'echo hello;sh'
  1569. ....
  1570. The best way to overcome those limitations is to use: <<init-busybox>>
  1571. If the script is large, you can add it to a gitignored file and pass that to `-E` as in:
  1572. ....
  1573. echo '
  1574. insmod /hello.ko
  1575. /poweroff.out
  1576. ' > gitignore.sh
  1577. ./run --eval "$(cat gitignore.sh)"
  1578. ....
  1579. or add it to a file to the root filesystem guest and rebuild:
  1580. ....
  1581. echo '#!/bin/sh
  1582. insmod /hello.ko
  1583. /poweroff.out
  1584. ' > rootfs_overlay/gitignore.sh
  1585. chmod +x rootfs_overlay/gitignore.sh
  1586. ./build-buildroot
  1587. ./run --kernel-cli 'init=/gitignore.sh'
  1588. ....
  1589. Remember that if your init returns, the kernel will panic, there are just two non-panic possibilities:
  1590. * run forever in a loop or long sleep
  1591. * `poweroff` the machine
  1592. ==== poweroff.out
  1593. Just using BusyBox' `poweroff` at the end of the `init` does not work and the kernel panics:
  1594. ....
  1595. ./run --eval poweroff
  1596. ....
  1597. because BusyBox' `poweroff` tries to do some fancy stuff like killing init, likely to allow userland to shutdown nicely.
  1598. But this fails when we are `init` itself!
  1599. `poweroff` works more brutally and effectively if you add `-f`:
  1600. ....
  1601. ./run --eval 'poweroff -f'
  1602. ....
  1603. but why not just use our minimal `/poweroff.out` and be done with it?
  1604. ....
  1605. ./run --eval '/poweroff.out'
  1606. ....
  1607. Source: link:userland/poweroff.c[]
  1608. 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
  1609. ==== sleep_forever.out
  1610. I dare you to guess what this does:
  1611. ....
  1612. ./run --eval '/sleep_forever.out'
  1613. ....
  1614. Source: link:userland/sleep_forever.c[]
  1615. This executable is a convenient simple init that does not panic and sleeps instead.
  1616. ==== time_boot.out
  1617. Get a reasonable answer to "how long does boot take?":
  1618. ....
  1619. ./run --eval-after '/time_boot.out'
  1620. ....
  1621. Dmesg contains a message of type:
  1622. ....
  1623. [ 2.188242] time_boot.c
  1624. ....
  1625. which tells us that boot took `2.188242` seconds.
  1626. Bibliography: https://stackoverflow.com/questions/12683169/measure-time-taken-for-linux-kernel-from-bootup-to-userpace/46517014#46517014
  1627. [[init-busybox]]
  1628. === Run command at the end of BusyBox init
  1629. Use the `--eval-after` option is for you rely on something that BusyBox' init set up for you like `/etc/fstab`:
  1630. ....
  1631. ./run --eval-after 'echo asdf;ls /proc;ls /sys;echo qwer'
  1632. ....
  1633. After the commands run, you are left on an interactive shell.
  1634. The above command is basically equivalent to:
  1635. ....
  1636. ./run --kernel-cli-after-dash 'lkmc_eval="insmod /hello.ko;poweroff.out;"'
  1637. ....
  1638. where the `lkmc_eval` option gets evaled by our default link:rootfs_overlay/etc/init.d/S98[S98] startup script.
  1639. Except that `--eval-after` is smarter and uses `base64` encoding.
  1640. Alternatively, you can also add the comamdns to run to a new `init.d` entry to run at the end o the BusyBox init:
  1641. ....
  1642. cp rootfs_overlay/etc/init.d/S98 rootfs_overlay/etc/init.d/S99.gitignore
  1643. vim rootfs_overlay/etc/init.d/S99.gitignore
  1644. ./build-buildroot
  1645. ./run
  1646. ....
  1647. and they will be run automatically before the login prompt.
  1648. Scripts under `/etc/init.d` are run by `/etc/init.d/rcS`, which gets called by the line `::sysinit:/etc/init.d/rcS` in link:rootfs_overlay/etc/inittab[`/etc/inittab`].
  1649. === Path to init
  1650. The init is selected at:
  1651. * initrd or initramfs system: `/init`, a custom one can be set with the `rdinit=` <<kernel-command-line-parameters,kernel command line parameter>>
  1652. * otherwise: default is `/sbin/init`, followed by some other paths, a custom one can be set with `init=`
  1653. 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
  1654. === Init environment
  1655. Documented at link:https://www.kernel.org/doc/html/v4.14/admin-guide/kernel-parameters.html[]:
  1656. ____
  1657. 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.
  1658. ____
  1659. And you can try it out with:
  1660. ....
  1661. ./run --kernel-cli 'init=/init_env_poweroff.out - asdf=qwer zxcv'
  1662. ....
  1663. Output:
  1664. ....
  1665. args:
  1666. /init_env_poweroff.out
  1667. -
  1668. zxcv
  1669. env:
  1670. HOME=/
  1671. TERM=linux
  1672. asdf=qwer
  1673. ....
  1674. Source: link:userland/init_env_poweroff.c[].
  1675. ==== init arguments
  1676. The annoying dash `-` gets passed as a parameter to `init`, which makes it impossible to use this method for most non custom executables.
  1677. Arguments with dots that come after `-` are still treated specially (of the form `subsystem.somevalue`) and disappear, from args, e.g.:
  1678. ....
  1679. ./run --kernel-cli 'init=/init_env_poweroff.out - /poweroff.out'
  1680. ....
  1681. outputs:
  1682. ....
  1683. args
  1684. /init_env_poweroff.out
  1685. -
  1686. ab
  1687. ....
  1688. so see how `a.b` is gone.
  1689. The simple workaround is to just create a shell script that does it, e.g. as we've done at: link:rootfs_overlay/gem5_exit.sh[].
  1690. ==== init environment env
  1691. Wait, where do `HOME` and `TERM` come from? (greps the kernel). Ah, OK, the kernel sets those by default: https://github.com/torvalds/linux/blob/94710cac0ef4ee177a63b5227664b38c95bbf703/init/main.c#L173
  1692. ....
  1693. const char *envp_init[MAX_INIT_ENVS+2] = { "HOME=/", "TERM=linux", NULL, };
  1694. ....
  1695. ==== BusyBox shell init environment
  1696. On top of the Linux kernel, the BusyBox `/bin/sh` shell will also define other variables.
  1697. We can explore the shenanigans that the shell adds on top of the Linux kernel with:
  1698. ....
  1699. ./run --kernel-cli 'init=/bin/sh'
  1700. ....
  1701. From there we observe that:
  1702. ....
  1703. env
  1704. ....
  1705. gives:
  1706. ....
  1707. SHLVL=1
  1708. HOME=/
  1709. TERM=linux
  1710. PWD=/
  1711. ....
  1712. therefore adding `SHLVL` and `PWD` to the default kernel exported variables.
  1713. Furthermore, to increase confusion, if you list all non-exported shell variables https://askubuntu.com/questions/275965/how-to-list-all-variables-names-and-their-current-values with:
  1714. ....
  1715. set
  1716. ....
  1717. then it shows more variables, notably:
  1718. ....
  1719. PATH='/sbin:/usr/sbin:/bin:/usr/bin'
  1720. ....
  1721. Finally, login shells will source some default files, notably:
  1722. ....
  1723. /etc/profile
  1724. /root/.profile
  1725. ....
  1726. We currently control `/root/.profile` at link:rootfs_overlay/root/.profile[], and use the default BusyBox `/etc/profile`.
  1727. The shell knows that it is a login shell if the first character of `argv[0]` is `-`, see also: https://stackoverflow.com/questions/2050961/is-argv0-name-of-executable-an-accepted-standard-or-just-a-common-conventi/42291142#42291142
  1728. When we use just `init=/bin/sh`, the Linux kernel sets `argv[0]` to `/bin/sh`, which does not start with `-`.
  1729. However, if you use `::respawn:-/bin/sh` on inttab described at <<tty>>, BusyBox' init sets `argv[0]` to `-`, and so does `getty`. This can be observed with:
  1730. ....
  1731. cat /proc/$$/cmdline
  1732. ....
  1733. where `$$` is the PID of the shell itself: https://stackoverflow.com/questions/21063765/get-pid-in-shell-bash
  1734. == initrd
  1735. 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
  1736. The bootloader, which for us is provided by QEMU itself, is then configured to put that CPIO into memory, and tell the kernel that it is there.
  1737. This is very similar to the kernel image itself, which already gets put into memory by the QEMU `-kernel` option.
  1738. 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.
  1739. To enable initrd instead of the default ext2 disk image, do:
  1740. ....
  1741. ./build-buildroot --initrd
  1742. ./run --initrd
  1743. ....
  1744. By looking at the QEMU run command generated, you can see that we didn't give the `-drive` option at all:
  1745. ....
  1746. cat "$(./getvar run_dir)/run.sh"
  1747. ....
  1748. Instead, we used the QEMU `-initrd` option to point to the `.cpio` filesystem that Buildroot generated for us.
  1749. Try removing that `-initrd` option to watch the kernel panic without rootfs at the end of boot.
  1750. When using `.cpio`, there can be no filesystem persistency across boots, since all file operations happen in memory in a tmpfs:
  1751. ....
  1752. date >f
  1753. poweroff
  1754. cat f
  1755. # can't open 'f': No such file or directory
  1756. ....
  1757. which can be good for automated tests, as it ensures that you are using a pristine unmodified system image every time.
  1758. Not however that we already disable disk persistency by default on ext2 filesystems even without `--initrd`: <<disk-persistency>>.
  1759. One downside of this method is that it has to put the entire filesystem into memory, and could lead to a panic:
  1760. ....
  1761. end Kernel panic - not syncing: Out of memory and no killable processes...
  1762. ....
  1763. This can be solved by increasing the memory with:
  1764. ....
  1765. ./run --initrd --memory 256M
  1766. ....
  1767. The main ingredients to get initrd working are:
  1768. * `BR2_TARGET_ROOTFS_CPIO=y`: make Buildroot generate `images/rootfs.cpio` in addition to the other images.
  1769. +
  1770. It is also possible to compress that image with other options.
  1771. * `qemu -initrd`: make QEMU put the image into memory and tell the kernel about it.
  1772. * `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
  1773. +
  1774. Buildroot forces that option when `BR2_TARGET_ROOTFS_CPIO=y` is given
  1775. TODO: how does the bootloader inform the kernel where to find initrd? https://unix.stackexchange.com/questions/89923/how-does-linux-load-the-initrd-image
  1776. === initrd in desktop distros
  1777. Most modern desktop distributions have an initrd in their root disk to do early setup.
  1778. The rationale for this is described at: https://en.wikipedia.org/wiki/Initial_ramdisk
  1779. One obvious use case is having an encrypted root filesystem: you keep the initrd in an unencrypted partition, and then setup decryption from there.
  1780. 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:
  1781. ....
  1782. initrd /initrd.img-4.4.0-108-generic
  1783. ....
  1784. Related: https://stackoverflow.com/questions/6405083/initrd-and-booting-the-linux-kernel
  1785. === initramfs
  1786. initramfs is just like <<initrd>>, but you also glue the image directly to the kernel image itself using the kernel's build system.
  1787. Try it out with:
  1788. ....
  1789. ./build-buildroot --initramfs
  1790. ./build-linux --initramfs
  1791. ./run --initramfs
  1792. ....
  1793. Notice how we had to rebuild the Linux kernel this time around as well after Buildroot, since in that build we will be gluing the CPIO to the kernel image.
  1794. Now, once again, if we look at the QEMU run command generated, we see all that QEMU needs is the `-kernel` option, no `-drive` not even `-initrd`! Pretty cool:
  1795. ....
  1796. cat "$(./getvar run_dir)/run.sh"
  1797. ....
  1798. It is also interesting to observe how this increases the size of the kernel image if you do a:
  1799. ....
  1800. ls -lh "$(./getvar linux_image)"
  1801. ....
  1802. before and after using initramfs, since the `.cpio` is now glued to the kernel image.
  1803. Don't forget that to stop using initramfs, you must rebuild the kernel without `--initramfs` to get rid of the attached CPIO image:
  1804. ....
  1805. ./build-linux
  1806. ./run
  1807. ....
  1808. Alternatively, consider using <<linux-kernel-build-variants>> if you need to switch between initramfs and non initramfs often:
  1809. ....
  1810. ./build-buildroot --initramfs
  1811. ./build-linux --initramfs --linux-build-id initramfs
  1812. ./run --initramfs --linux-build-id
  1813. ....
  1814. Setting up initramfs is very easy: our scripts just set `CONFIG_INITRAMFS_SOURCE` to point to the CPIO path.
  1815. http://nairobi-embedded.org/initramfs_tutorial.html shows a full manual setup.
  1816. === gem5 initrd
  1817. 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
  1818. This would require gem5 to load the CPIO into memory, just like QEMU. Grepping `initrd` shows some ARM hits under:
  1819. ....
  1820. src/arch/arm/linux/atag.hh
  1821. ....
  1822. but they are commented out.
  1823. === gem5 initramfs
  1824. This could in theory be easier to make work than initrd since the emulator does not have to do anything special.
  1825. However, it didn't: boot fails at the end because it does not see the initramfs, but rather tries to open our dummy root filesystem, which unsurprisingly does not have a format in a way that the kernel understands:
  1826. ....
  1827. VFS: Cannot open root device "sda" or unknown-block(8,0): error -5
  1828. ....
  1829. We think that this might be because gem5 boots directly `vmlinux`, and not from the final compressed images that contain the attached rootfs such as `bzImage`, which is what QEMU does, see also: <<vmlinux-vs-bzimage-vs-zimage-vs-image>>.
  1830. To do this failed test, we automatically pass a dummy disk image as of gem5 7fa4c946386e7207ad5859e8ade0bbfc14000d91 since the scripts don't handle a missing `--disk-image` well, much like is currently done for <<baremetal>>.
  1831. Interestingly, using initramfs significantly slows down the gem5 boot, even though it did not work. For example, we've observed a 4x slowdown of as 17062a2e8b6e7888a14c3506e9415989362c58bf for aarch64. This must be because expanding the large attached CPIO must be expensive. We can clearly see from the kernel logs that the kernel just hangs at a point after the message `PCI: CLS 0 bytes, default 64` for a long time before proceeding further.
  1832. == Device tree
  1833. The device tree is a Linux kernel defined data structure that serves to inform the kernel how the hardware is setup.
  1834. <<platform_device>> contains a minimal runnable example of device tree manipulation.
  1835. Device trees serve to reduce the need for hardware vendors to patch the kernel: they just provide a device tree file instead, which is much simpler.
  1836. x86 does not use it device trees, but many other archs to, notably ARM.
  1837. This is notably because ARM boards:
  1838. * typically don't have discoverable hardware extensions like PCI, but rather just put everything on an SoC with magic register addresses
  1839. * are made by a wide variety of vendors due to ARM's licensing business model, which increases variability
  1840. The Linux kernel itself has several device trees under `./arch/<arch>/boot/dts`, see also: https://stackoverflow.com/questions/21670967/how-to-compile-dts-linux-device-tree-source-files-to-dtb/42839737#42839737
  1841. === DTB files
  1842. Files that contain device trees have the `.dtb` extension when compiled, and `.dts` when in text form.
  1843. You can convert between those formats with:
  1844. ....
  1845. "$(./getvar host_dir)"/bin/dtc -I dtb -O dts -o a.dts a.dtb
  1846. "$(./getvar host_dir)"/bin/dtc -I dts -O dtb -o a.dtb a.dts
  1847. ....
  1848. Buildroot builds the tool due to `BR2_PACKAGE_HOST_DTC=y`.
  1849. On Ubuntu 18.04, the package is named:
  1850. ....
  1851. sudo apt-get install device-tree-compiler
  1852. ....
  1853. See also: https://stackoverflow.com/questions/14000736/tool-to-visualize-the-device-tree-file-dtb-used-by-the-linux-kernel/39931834#39931834
  1854. Device tree files are provided to the emulator just like the root filesystem and the Linux kernel image.
  1855. In real hardware, those components are also often provided separately. For example, on the Raspberry Pi 2, the SD card must contain two partitions:
  1856. * the first contains all magic files, including the Linux kernel and the device tree
  1857. * the second contains the root filesystem
  1858. See also: https://stackoverflow.com/questions/29837892/how-to-run-a-c-program-with-no-os-on-the-raspberry-pi/40063032#40063032
  1859. === Device tree syntax
  1860. Good format descriptions:
  1861. * https://www.raspberrypi.org/documentation/configuration/device-tree.md
  1862. Minimal example
  1863. ....
  1864. /dts-v1/;
  1865. / {
  1866. a;
  1867. };
  1868. ....
  1869. Check correctness with:
  1870. ....
  1871. dtc a.dts
  1872. ....
  1873. Separate nodes are simply merged by node path, e.g.:
  1874. ....
  1875. /dts-v1/;
  1876. / {
  1877. a;
  1878. };
  1879. / {
  1880. b;
  1881. };
  1882. ....
  1883. then `dtc a.dts` gives:
  1884. ....
  1885. /dts-v1/;
  1886. / {
  1887. a;
  1888. b;
  1889. };
  1890. ....
  1891. === Get device tree from a running kernel
  1892. https://unix.stackexchange.com/questions/265890/is-it-possible-to-get-the-information-for-a-device-tree-using-sys-of-a-running/330926#330926
  1893. 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.
  1894. So observing the device tree from the guest allows to easily see what the emulator has generated.
  1895. Compile the `dtc` tool into the root filesystem:
  1896. ....
  1897. ./build-buildroot \
  1898. --arch aarch64 \
  1899. --config 'BR2_PACKAGE_DTC=y' \
  1900. --config 'BR2_PACKAGE_DTC_PROGRAMS=y' \
  1901. ;
  1902. ....
  1903. `-M virt` for example, which we use by default for `aarch64`, boots just fine without the `-dtb` option:
  1904. ....
  1905. ./run --arch aarch64
  1906. ....
  1907. Then, from inside the guest:
  1908. ....
  1909. dtc -I fs -O dts /sys/firmware/devicetree/base
  1910. ....
  1911. contains:
  1912. ....
  1913. cpus {
  1914. #address-cells = <0x1>;
  1915. #size-cells = <0x0>;
  1916. cpu@0 {
  1917. compatible = "arm,cortex-a57";
  1918. device_type = "cpu";
  1919. reg = <0x0>;
  1920. };
  1921. };
  1922. ....
  1923. === Device tree emulator generation
  1924. Since emulators know everything about the hardware, they can automatically generate device trees for us, which is very convenient.
  1925. This is the case for both QEMU and gem5.
  1926. For example, if we increase the <<number-of-cores,number of cores>> to 2:
  1927. ....
  1928. ./run --arch aarch64 --cpus 2
  1929. ....
  1930. QEMU automatically adds a second CPU to the DTB!
  1931. ....
  1932. cpu@0 {
  1933. cpu@1 {
  1934. ....
  1935. The action seems to be happening at: `hw/arm/virt.c`.
  1936. You can dump the DTB QEMU generated with:
  1937. ....
  1938. ./run --arch aarch64 -- -machine dumpdtb=dtb.dtb
  1939. ....
  1940. as mentioned at: https://lists.gnu.org/archive/html/qemu-discuss/2017-02/msg00051.html
  1941. <<gem5-fs_biglittle>> 2a9573f5942b5416fb0570cf5cb6cdecba733392 can also generate its own DTB.
  1942. gem5 can generate DTBs on ARM with `--generate-dtb`. The generated DTB is placed in the <<m5out-directory>> named as `system.dtb`.
  1943. == KVM
  1944. link:https://en.wikipedia.org/wiki/Kernel-based_Virtual_Machine[KVM] is Linux kernel interface that <<benchmark-linux-kernel-boot,greatly speeds up>> execution of virtual machines.
  1945. You can make QEMU or gem5 by passing enabling KVM with:
  1946. ....
  1947. ./run --kvm
  1948. ....
  1949. but it was broken in gem5 with pending patches: https://www.mail-archive.com/gem5-users@gem5.org/msg15046.html It fails immediately on:
  1950. ....
  1951. panic: KVM: Failed to enter virtualized mode (hw reason: 0x80000021)
  1952. ....
  1953. KVM works by running userland instructions natively directly on the real hardware instead of running a software simulation of those instructions.
  1954. Therefore, KVM only works if you the host architecture is the same as the guest architecture. This means that this will likely only work for x86 guests since almost all development machines are x86 nowadays. Unless you are link:https://www.youtube.com/watch?v=8ItXpmLsINs[running an ARM desktop for some weird reason] :-)
  1955. We don't enable KVM by default because:
  1956. * it limits visibility, since more things are running natively:
  1957. ** can't use GDB
  1958. ** can't do instruction tracing
  1959. ** on gem5, you lose cycle counts and therefor any notion of performance
  1960. * QEMU kernel boots are already fast enough for most purposes without it
  1961. One important use case for KVM is to fast forward gem5 execution, often to skip boot, take a <<gem5-checkpoint>>, and then move on to a more detailed and slow simulation
  1962. === KVM arm
  1963. TODO: we haven't gotten it to work yet, but it should be doable, and this is an outline of how to do it. Just don't expect this to tested very often for now.
  1964. We can test KVM on arm by running this repository inside an Ubuntu arm QEMU VM.
  1965. This produces no speedup of course, since the VM is already slow since it cannot use KVM on the x86 host.
  1966. First, obtain an Ubuntu arm64 virtual machine as explained at: https://askubuntu.com/questions/281763/is-there-any-prebuilt-qemu-ubuntu-image32bit-online/1081171#1081171
  1967. Then, from inside that image:
  1968. ....
  1969. sudo apt-get install git
  1970. git clone https://github.com/cirosantilli/linux-kernel-module-cheat
  1971. cd linux-kernel-module-cheat
  1972. sudo ./setup -y
  1973. ....
  1974. and then proceed exactly as in <<prebuilt>>.
  1975. We don't want to build the full Buildroot image inside the VM as that would be way too slow, thus the recommendation for the prebuilt setup.
  1976. TODO: do the right thing and cross compile QEMU and gem5. gem5's Python parts might be a pain. QEMU should be easy: https://stackoverflow.com/questions/26514252/cross-compile-qemu-for-arm
  1977. == User mode simulation
  1978. Both QEMU and gem5 have an user mode simulation mode in addition to full system simulation that we consider elsewhere in this project.
  1979. In QEMU, it is called just <<qemu-user-mode,"user mode">>, and in gem5 it is called <<gem5-syscall-emulation-mode,syscall emulation mode>>.
  1980. In both, the basic idea is the same.
  1981. User mode simulation takes regular userland executables of any arch as input and executes them directly, without booting a kernel.
  1982. Instead of simulating the full system, it translates normal instructions like in full system mode, but magically forwards system calls to the host OS.
  1983. Advantages over full system simulation:
  1984. * the simulation may <<user-mode-vs-full-system-benchmark,run faster>> since you don't have to simulate the Linux kernel and several device models
  1985. * you don't need to build your own kernel or root filesystem, which saves time. You still need a toolchain however, but the pre-packaged ones may work fine.
  1986. Disadvantages:
  1987. * lower guest to host portability:
  1988. ** TODO confirm: host OS == guest OS?
  1989. ** TODO confirm: the host Linux kernel should be newer than the kernel the executable was built for.
  1990. +
  1991. It may still work even if that is not the case, but could fail is a missing system call is reached.
  1992. +
  1993. The target Linux kernel of the executable is a GCC toolchain build-time configuration.
  1994. * cannot be used to test the Linux kernel, and results are less representative of a real system since we are faking more
  1995. === QEMU user mode
  1996. First let's run a dynamically linked executable built with the Buildroot toolchain:
  1997. ....
  1998. ./build --arch aarch64 user-mode-qemu
  1999. ./run \
  2000. --arch aarch64 \
  2001. --userland print_argv \
  2002. --userland-args 'asdf "qw er"' \
  2003. ;
  2004. ....
  2005. Output:
  2006. ....
  2007. asdf
  2008. qw er
  2009. ....
  2010. This runs link:userland/print_argv.c[].
  2011. `./run --userland` path resolution is analogous to <<baremetal-setup-getting-started,that of `./run --baremetal`>>.
  2012. `./build-userland` is further documented at: <<userland-directory>>.
  2013. Running dynamically linked executables in QEMU requires pointing it to the root filesystem with the `-L` option so that it can find the dynamic linker and shared libraries.
  2014. We pass `-L` by default, so everything just works:
  2015. You can also try statically linked executables with:
  2016. ....
  2017. ./build-userland \
  2018. --arch aarch64 \
  2019. --static \
  2020. --userland-build-id static \
  2021. ;
  2022. ./run \
  2023. --arch aarch64 \
  2024. --userland-build-id static \
  2025. --userland print_argv \
  2026. --userland-args 'asdf "qw er"' \
  2027. ;
  2028. ....
  2029. Or you can run statically linked built by the host packaged toolchain with:
  2030. ....
  2031. ./build-userland \
  2032. --arch aarch64 \
  2033. --host \
  2034. --static \
  2035. --userland-build-id host-static \
  2036. ;
  2037. ./run \
  2038. --arch aarch64 \
  2039. --userland-build-id host-static \
  2040. --userland print_argv \
  2041. --userland-args 'asdf "qw er"' \
  2042. ;
  2043. ....
  2044. TODO expose dynamically linked executables built by the host toolchain. It also works, we just have to use e.g. `-L /usr/aarch64-linux-gnu`, so it's not really hard, I'm just lazy.
  2045. ==== User mode GDB
  2046. It's nice when <<gdb,the obvious>> just works, right?
  2047. ....
  2048. ./run \
  2049. --arch aarch64 \
  2050. --userland print_argv \
  2051. --userland-args 'asdf "qw er"' \
  2052. --wait-gdb \
  2053. ;
  2054. ....
  2055. and on another shell:
  2056. ....
  2057. ./run-gdb \
  2058. --arch aarch64 \
  2059. --userland print_argv \
  2060. main \
  2061. ;
  2062. ....
  2063. Or alternatively, if you are using <<tmux>>, do everything in one go with:
  2064. ....
  2065. ./run \
  2066. --arch aarch64 \
  2067. --tmux-args main \
  2068. --userland print_argv \
  2069. --userland-args 'asdf "qw er"' \
  2070. --wait-gdb \
  2071. ;
  2072. ....
  2073. To stop at the very first instruction of a freestanding program, just use `--no-continue` TODO example.
  2074. === gem5 syscall emulation mode
  2075. Less robust than QEMU's, but still usable:
  2076. * https://stackoverflow.com/questions/48986597/when-should-you-use-full-system-fs-vs-syscall-emulation-se-with-userland-program
  2077. * https://stackoverflow.com/questions/48959349/how-to-solve-fatal-kernel-too-old-when-running-gem5-in-syscall-emulation-se-m
  2078. There are much more unimplemented syscalls in gem5 than in QEMU. Many of those are trivial to implement however.
  2079. As of 185c2730cc78d5adda683d76c0e3b35e7cb534f0, dynamically linked executables only work on x86, and they can only use the host libraries, which is ugly:
  2080. * https://stackoverflow.com/questions/50542222/how-to-run-a-dynamically-linked-executable-syscall-emulation-mode-se-py-in-gem5
  2081. * https://www.mail-archive.com/gem5-users@gem5.org/msg15585.html
  2082. If you try dynamically linked executables on ARM, they fail with:
  2083. ....
  2084. fatal: Unable to open dynamic executable's interpreter.
  2085. ....
  2086. So let's just play with some static ones:
  2087. ....
  2088. ./build-userland \
  2089. --arch aarch64 \
  2090. --static \
  2091. --userland-build-id static \
  2092. ;
  2093. ./run \
  2094. --arch aarch64 \
  2095. --emulator gem5 \
  2096. --userland print_argv \
  2097. --userland-args 'asdf "qw er"' \
  2098. ;
  2099. ....
  2100. TODO: how to escape spaces on the command line arguments?
  2101. Step debug also works:
  2102. ....
  2103. ./run \
  2104. --arch aarch64 \
  2105. --emulator gem5 \
  2106. --userland print_argv \
  2107. --userland-args 'asdf "qw er"' \
  2108. --userland-build-id static \
  2109. --wait-gdb \
  2110. ;
  2111. ./run-gdb \
  2112. --arch aarch64 \
  2113. --emulator gem5 \
  2114. --userland print_argv \
  2115. --userland-build-id static \
  2116. main \
  2117. ;
  2118. ....
  2119. ==== gem5 syscall emulation exit status
  2120. As of gem5 7fa4c946386e7207ad5859e8ade0bbfc14000d91, the crappy `se.py` script does not forward the exit status of syscall emulation mode, you can test it with:
  2121. ....
  2122. ./run --dry-run --emulator gem5 --userland false --userland-build-id static
  2123. ....
  2124. Source: link:userland/false[].
  2125. Then manually run the generated gem5 CLI, and do:
  2126. ....
  2127. echo $?
  2128. ....
  2129. and the output is always `0`.
  2130. Instead, it just outputs a message to stdout just like for <<m5-fail>>:
  2131. ....
  2132. Simulated exit code not 0! Exit code is 1
  2133. ....
  2134. which we parse in link:run[] and then exit with the correct result ourselves...
  2135. ==== User mode vs full system benchmark
  2136. Let's see if user mode runs considerably faster than full system or not.
  2137. gem5 user mode:
  2138. ....
  2139. ./build-buildroot --config 'BR2_PACKAGE_DHRYSTONE=y' --arch arm
  2140. make \
  2141. -B \
  2142. -C "$(./getvar --arch arm buildroot_build_build_dir)/dhrystone-2" \
  2143. CC="$(./run-toolchain --arch arm --dry gcc)" \
  2144. CFLAGS=-static \
  2145. ;
  2146. time \
  2147. ./run \
  2148. --arch arm \
  2149. --emulator gem5 \
  2150. --userland "$(./getvar --arch arm buildroot_build_build_dir)/dhrystone-2/dhrystone" \
  2151. --userland-args 'asdf qwer' \
  2152. ;
  2153. ....
  2154. gem5 full system:
  2155. ....
  2156. time \
  2157. ./run \
  2158. --arch arm \
  2159. --eval-after '/gem5.sh' \
  2160. --emulator gem5
  2161. --gem5-readfile 'dhrystone 100000' \
  2162. ;
  2163. ....
  2164. QEMU user mode:
  2165. ....
  2166. time qemu-arm "$(./getvar --arch arm buildroot_build_build_dir)/dhrystone-2/dhrystone" 100000000
  2167. ....
  2168. QEMU full system:
  2169. ....
  2170. time \
  2171. ./run \
  2172. --arch arm \
  2173. --eval-after 'time dhrystone 100000000;/poweroff.out' \
  2174. ;
  2175. ....
  2176. Result on <<p51>> at bad30f513c46c1b0995d3a10c0d9bc2a33dc4fa0:
  2177. * gem5 user: 33 seconds
  2178. * gem5 full system: 51 seconds
  2179. * QEMU user: 45 seconds
  2180. * QEMU full system: 223 seconds
  2181. === User mode tests
  2182. Automatically run non-interactive userland tests that can be run in user mode simulation:
  2183. ....
  2184. ./build --all-archs test-user-mode
  2185. ./test-user-mode --all-archs --all-emulators
  2186. ....
  2187. Or just for QEMU:
  2188. ....
  2189. ./build --all-archs test-user-mode-qemu
  2190. ./test-user-mode --all-archs --emulator qemu
  2191. ....
  2192. Source: link:test-user-mode[]
  2193. This testing excludes notably kernel module tests which depend on a full running kernel.
  2194. The gem5 tests require building statically with build id `static`, see also: <<gem5-syscall-emulation-mode>>. TODO automate this better.
  2195. See: <<test-this-repo>> for more useful testing tips.
  2196. == Kernel module utilities
  2197. === insmod
  2198. link:https://git.busybox.net/busybox/tree/modutils/insmod.c?h=1_29_3[Provided by BusyBox]:
  2199. ....
  2200. ./run --eval-after 'insmod /hello.ko'
  2201. ....
  2202. === myinsmod
  2203. If you are feeling raw, you can insert and remove modules with our own minimal module inserter and remover!
  2204. ....
  2205. # init_module
  2206. /myinsmod.out /hello.ko
  2207. # finit_module
  2208. /myinsmod.out /hello.ko "" 1
  2209. /myrmmod.out hello
  2210. ....
  2211. which teaches you how it is done from C code.
  2212. Source:
  2213. * link:userland/myinsmod.c[]
  2214. * link:userland/myrmmod.c[]
  2215. The Linux kernel offers two system calls for module insertion:
  2216. * `init_module`
  2217. * `finit_module`
  2218. and:
  2219. ....
  2220. man init_module
  2221. ....
  2222. documents that:
  2223. ____
  2224. 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().
  2225. ____
  2226. `finit` is newer and was added only in v3.8. More rationale: https://lwn.net/Articles/519010/
  2227. Bibliography: https://stackoverflow.com/questions/5947286/how-to-load-linux-kernel-modules-from-c-code
  2228. === modprobe
  2229. Implemented as a BusyBox applet by default: https://git.busybox.net/busybox/tree/modutils/modprobe.c?h=1_29_stable
  2230. `modprobe` searches for modules installed under:
  2231. ....
  2232. ls /lib/modules/<kernel_version>
  2233. ....
  2234. and specified in the `modules.order` file.
  2235. This is the default install path for `CONFIG_SOME_MOD=m` modules built with `make modules_install` in the Linux kernel tree, with root path given by `INSTALL_MOD_PATH`, and therefore canonical in that sense.
  2236. Currently, there are only two kinds of kernel modules that you can try out with `modprobe`:
  2237. * modules built with Buildroot, see: <<kernel_modules-package>>
  2238. * modules built from the kernel tree itself, see: <<dummy-irq>>
  2239. We are not installing out custom `./build-modules` modules there, because:
  2240. * we don't know the right way. Why is there no `install` or `install_modules` target for kernel modules?
  2241. +
  2242. This can of course be solved by running Buildroot in verbose mode, and copying whatever it is doing, initial exploration at: https://stackoverflow.com/questions/22783793/how-to-install-kernel-modules-from-source-code-error-while-make-process/53169078#53169078
  2243. * we would have to think how to not have to include the kernel modules twice in the root filesystem, but still have <<9p>> working for fast development as described at: <<your-first-kernel-module-hack>>
  2244. === kmod
  2245. The more "reference" kernel.org implementation of `lsmod`, `insmod`, `rmmod`, etc.: https://git.kernel.org/pub/scm/utils/kernel/kmod/kmod.git
  2246. Default implementation on desktop distros such as Ubuntu 16.04, where e.g.:
  2247. ....
  2248. ls -l /bin/lsmod
  2249. ....
  2250. gives:
  2251. ....
  2252. lrwxrwxrwx 1 root root 4 Jul 25 15:35 /bin/lsmod -> kmod
  2253. ....
  2254. and:
  2255. ....
  2256. dpkg -l | grep -Ei
  2257. ....
  2258. contains:
  2259. ....
  2260. ii kmod 22-1ubuntu5 amd64 tools for managing Linux kernel modules
  2261. ....
  2262. BusyBox also implements its own version of those executables, see e.g. <<modprobe>>. Here we will only describe features that differ from kmod to the BusyBox implementation.
  2263. ==== module-init-tools
  2264. Name of a predecessor set of tools.
  2265. ==== kmod modprobe
  2266. kmod's `modprobe` can also load modules under different names to avoid conflicts, e.g.:
  2267. ....
  2268. sudo modprobe vmhgfs -o vm_hgfs
  2269. ....
  2270. == Filesystems
  2271. === OverlayFS
  2272. link:https://en.wikipedia.org/wiki/OverlayFS[OverlayFS] is a filesystem merged in the Linux kernel in 3.18.
  2273. As the name suggests, OverlayFS allows you to merge multiple directories into one. The following minimal runnable examples should give you an intuition on how it works:
  2274. * https://askubuntu.com/questions/109413/how-do-i-use-overlayfs/1075564#1075564
  2275. * https://stackoverflow.com/questions/31044982/how-to-use-multiple-lower-layers-in-overlayfs/52792397#52792397
  2276. We are very interested in this filesystem because we are looking for a way to make host cross compiled executables appear on the guest root `/` without reboot.
  2277. This would have several advantages:
  2278. * makes it faster to test modified guest programs
  2279. ** not rebooting is fundamental for <<gem5>>, where the reboot is very costly.
  2280. ** no need to regenerate the root filesystem at all and reboot
  2281. ** overcomes the `check_bin_arch` problem: <<rpath>>
  2282. * we could keep the base root filesystem very small, which implies:
  2283. ** less host disk usage, no need to copy the entire `./getvar out_rootfs_overlay_dir` to the image again
  2284. ** no need to worry about <<br2_target_rootfs_ext2_size>>
  2285. We can already make host files appear on the guest with <<9p>>, but they appear on a subdirectory instead of the root.
  2286. If they would appear on the root instead, that would be even more awesome, because you would just use the exact same paths relative to the root transparently.
  2287. For example, we wouldn't have to mess around with variables such as `PATH` and `LD_LIBRARY_PATH`.
  2288. The idea is to:
  2289. * 9P mount our overlay directory `./getvar out_rootfs_overlay_dir` on the guest, which we already do at `/mnt/9p/out_rootfs_overlay`
  2290. * then create an overlay with that directory and the root, and `chroot` into it.
  2291. +
  2292. I was unable to mount directly to `/` avoid the `chroot`:
  2293. ** https://stackoverflow.com/questions/41119656/how-can-i-overlayfs-the-root-filesystem-on-linux
  2294. ** https://unix.stackexchange.com/questions/316018/how-to-use-overlayfs-to-protect-the-root-filesystem
  2295. ** https://unix.stackexchange.com/questions/420646/mount-root-as-overlayfs
  2296. We already have a prototype of this running from `fstab` on guest at `/mnt/overlay`, but it has the following shortcomings:
  2297. * changes to underlying filesystems are not visible on the overlay unless you remount with `mount -r remount /mnt/overlay`, as mentioned link:https://github.com/torvalds/linux/blob/v4.18/Documentation/filesystems/overlayfs.txt#L332[on the kernel docs]:
  2298. +
  2299. ....
  2300. Changes to the underlying filesystems while part of a mounted overlay
  2301. filesystem are not allowed. If the underlying filesystem is changed,
  2302. the behavior of the overlay is undefined, though it will not result in
  2303. a crash or deadlock.
  2304. ....
  2305. +
  2306. This makes everything very inconvenient if you are inside `chroot` action. You would have to leave `chroot`, remount, then come back.
  2307. * the overlay does not contain sub-filesystems, e.g. `/proc`. We would have to re-mount them. But should be doable with some automation.
  2308. Even more awesome than `chroot` would be to `pivot_root`, but I couldn't get that working either:
  2309. * https://stackoverflow.com/questions/28015688/pivot-root-device-or-resource-busy
  2310. * https://unix.stackexchange.com/questions/179788/pivot-root-device-or-resource-busy
  2311. === Secondary disk
  2312. A simpler and possibly less overhead alternative to <<9P>> would be to generate a secondary disk image with the benchmark you want to rebuild.
  2313. Then you can `umount` and re-mount on guest without reboot.
  2314. 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[].
  2315. This was not possible from gem5 `fs.py` as of 60600f09c25255b3c8f72da7fb49100e2682093a: https://stackoverflow.com/questions/50862906/how-to-attach-multiple-disk-images-in-a-simulation-with-gem5-fs-py/51037661#51037661
  2316. == Graphics
  2317. Both QEMU and gem5 are capable of outputting graphics to the screen, and taking mouse and keyboard input.
  2318. https://unix.stackexchange.com/questions/307390/what-is-the-difference-between-ttys0-ttyusb0-and-ttyama0-in-linux
  2319. === QEMU text mode
  2320. Text mode is the default mode for QEMU.
  2321. The opposite of text mode is <<qemu-graphic-mode>>
  2322. In text mode, we just show the serial console directly on the current terminal, without opening a QEMU GUI window.
  2323. You cannot see any graphics from text mode, but text operations in this mode, including:
  2324. * scrolling up: <<scroll-up-in-graphic-mode>>
  2325. * copy paste to and from the terminal
  2326. making this a good default, unless you really need to use with graphics.
  2327. Text mode works by sending the terminal character by character to a serial device.
  2328. This is different from a display screen, where each character is a bunch of pixels, and it would be much harder to convert that into actual terminal text.
  2329. For more details, see:
  2330. * https://unix.stackexchange.com/questions/307390/what-is-the-difference-between-ttys0-ttyusb0-and-ttyama0-in-linux
  2331. * <<tty>>
  2332. Note that you can still see an image even in text mode with the VNC:
  2333. ....
  2334. ./run --vnc
  2335. ....
  2336. and on another terminal:
  2337. ....
  2338. ./vnc
  2339. ....
  2340. but there is not terminal on the VNC window, just the <<config_logo>> penguin.
  2341. ==== Quit QEMU from text mode
  2342. https://superuser.com/questions/1087859/how-to-quit-the-qemu-monitor-when-not-using-a-gui
  2343. However, our QEMU setup captures Ctrl + C and other common signals and sends them to the guest, which makes it hard to quit QEMU for the first time since there is no GUI either.
  2344. The simplest way to quit QEMU, is to do:
  2345. ....
  2346. Ctrl-A X
  2347. ....
  2348. Alternative methods include:
  2349. * `quit` command on the <<qemu-monitor>>
  2350. * `pkill qemu`
  2351. === QEMU graphic mode
  2352. Enable graphic mode with:
  2353. ....
  2354. ./run --graphic
  2355. ....
  2356. Outcome: you see a penguin due to <<config_logo>>.
  2357. For a more exciting GUI experience, see: <<x11>>
  2358. Text mode is the default due to the following considerable advantages:
  2359. * copy and paste commands and stdout output to / from host
  2360. * 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
  2361. * have a large scroll buffer, and be able to search it, e.g. by using tmux on host
  2362. * one less window floating around to think about in addition to your shell :-)
  2363. * graphics mode has only been properly tested on `x86_64`.
  2364. Text mode has the following limitations over graphics mode:
  2365. * you can't see graphics such as those produced by <<x11>>
  2366. * 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.
  2367. `x86_64` has a VGA device enabled by default, as can be seen as:
  2368. ....
  2369. ./qemu-monitor info qtree
  2370. ....
  2371. 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:
  2372. ....
  2373. cat /dev/urandom > /dev/fb0
  2374. ....
  2375. flooding the screen with colors. See also: https://superuser.com/questions/223094/how-do-i-know-if-i-have-kms-enabled
  2376. ==== Scroll up in graphic mode
  2377. Scroll up in <<qemu-graphic-mode>>:
  2378. ....
  2379. Shift-PgUp
  2380. ....
  2381. but I never managed to increase that buffer:
  2382. * https://askubuntu.com/questions/709697/how-to-increase-scrollback-lines-in-ubuntu14-04-2-server-edition
  2383. * https://unix.stackexchange.com/questions/346018/how-to-increase-the-scrollback-buffer-size-for-tty
  2384. The superior alternative is to use text mode and GNU screen or <<tmux>>.
  2385. ==== QEMU Graphic mode arm
  2386. ===== QEMU graphic mode arm terminal
  2387. TODO: on arm, we see the penguin and some boot messages, but don't get a shell at then end:
  2388. ....
  2389. ./run --arch aarch64 --graphic
  2390. ....
  2391. I think it does not work because the graphic window is <<drm>> only, i.e.:
  2392. ....
  2393. cat /dev/urandom > /dev/fb0
  2394. ....
  2395. fails with:
  2396. ....
  2397. cat: write error: No space left on device
  2398. ....
  2399. 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>>.
  2400. There is however one out-of-tree implementation: <<kmscon>>.
  2401. ===== QEMU graphic mode arm terminal implementation
  2402. `arm` and `aarch64` rely on the QEMU CLI option:
  2403. ....
  2404. -device virtio-gpu-pci
  2405. ....
  2406. and the kernel config options:
  2407. ....
  2408. CONFIG_DRM=y
  2409. CONFIG_DRM_VIRTIO_GPU=y
  2410. ....
  2411. Unlike x86, `arm` and `aarch64` don't have a display device attached by default, thus the need for `virtio-gpu-pci`.
  2412. See also https://wiki.qemu.org/Documentation/Platforms/ARM (recently edited and corrected by yours truly... :-)).
  2413. ===== QEMU graphic mode arm VGA
  2414. TODO: how to use VGA on ARM? https://stackoverflow.com/questions/20811203/how-can-i-output-to-vga-through-qemu-arm Tried:
  2415. ....
  2416. -device VGA
  2417. ....
  2418. But https://github.com/qemu/qemu/blob/v2.12.0/docs/config/mach-virt-graphical.cfg#L264 says:
  2419. ....
  2420. # We use virtio-gpu because the legacy VGA framebuffer is
  2421. # very troublesome on aarch64, and virtio-gpu is the only
  2422. # video device that doesn't implement it.
  2423. ....
  2424. so maybe it is not possible?
  2425. === gem5 graphic mode
  2426. gem5 does not have a "text mode", since it cannot redirect the Linux terminal to same host terminal where the executable is running: you are always forced to connect to the terminal with `gem-shell`.
  2427. TODO could not get it working on `x86_64`, only ARM.
  2428. Overview: https://stackoverflow.com/questions/50364863/how-to-get-graphical-gui-output-and-user-touch-keyboard-mouse-input-in-a-ful/50364864#50364864
  2429. More concretely, first build the kernel with the <<gem5-arm-linux-kernel-patches>>, and then run:
  2430. ....
  2431. ./build-linux \
  2432. --arch arm \
  2433. --custom-config-file-gem5 \
  2434. --linux-build-id gem5-v4.15 \
  2435. ;
  2436. ./run --arch arm --emulator gem5 --linux-build-id gem5-v4.15
  2437. ....
  2438. and then on another shell:
  2439. ....
  2440. vinagre localhost:5900
  2441. ....
  2442. The <<config_logo>> penguin only appears after several seconds, together with kernel messages of type:
  2443. ....
  2444. [ 0.152755] [drm] found ARM HDLCD version r0p0
  2445. [ 0.152790] hdlcd 2b000000.hdlcd: bound virt-encoder (ops 0x80935f94)
  2446. [ 0.152795] [drm] Supports vblank timestamp caching Rev 2 (21.10.2013).
  2447. [ 0.152799] [drm] No driver support for vblank timestamp query.
  2448. [ 0.215179] Console: switching to colour frame buffer device 240x67
  2449. [ 0.230389] hdlcd 2b000000.hdlcd: fb0: frame buffer device
  2450. [ 0.230509] [drm] Initialized hdlcd 1.0.0 20151021 for 2b000000.hdlcd on minor 0
  2451. ....
  2452. 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:
  2453. ....
  2454. system.vncserver: Listening for connections on port 5900
  2455. ....
  2456. and when we connect it shows a message:
  2457. ....
  2458. info: VNC client attached
  2459. ....
  2460. Alternatively, you can also dump each new frame to an image file with `--frame-capture`:
  2461. ....
  2462. ./run \
  2463. --arch arm \
  2464. --emulator gem5 \
  2465. --linux-build-id gem5-v4.15 \
  2466. -- --frame-capture \
  2467. ;
  2468. ....
  2469. This creates on compressed PNG whenever the screen image changes inside the <<m5out-directory>> with filename of type:
  2470. ....
  2471. frames_system.vncserver/fb.<frame-index>.<timestamp>.png.gz
  2472. ....
  2473. It is fun to see how we get one new frame whenever the white underscore cursor appears and reappears under the penguin!
  2474. The last frame is always available uncompressed at: `system.framebuffer.png`.
  2475. TODO <<kmscube>> failed on `aarch64` with:
  2476. ....
  2477. kmscube[706]: unhandled level 2 translation fault (11) at 0x00000000, esr 0x92000006, in libgbm.so.1.0.0[7fbf6a6000+e000]
  2478. ....
  2479. Tested on: link:http://github.com/cirosantilli/linux-kernel-module-cheat/commit/38fd6153d965ba20145f53dc1bb3ba34b336bde9[38fd6153d965ba20145f53dc1bb3ba34b336bde9]
  2480. ==== Graphic mode gem5 aarch64
  2481. For `aarch64` we also need to configure the kernel with link:linux_config/display[]:
  2482. ....
  2483. git -C "$(./getvar linux_source_dir)" fetch https://gem5.googlesource.com/arm/linux gem5/v4.15:gem5/v4.15
  2484. git -C "$(./getvar linux_source_dir)" checkout gem5/v4.15
  2485. ./build-linux \
  2486. --arch aarch64 \
  2487. --config-fragment linux_config/display \
  2488. --custom-config-file-gem5 \
  2489. --linux-build-id gem5-v4.15 \
  2490. ;
  2491. git -C "$(./getvar linux_source_dir)" checkout -
  2492. ./run --arch aarch64 --emulator gem5 --linux-build-id gem5-v4.15
  2493. ....
  2494. This is because the gem5 `aarch64` defconfig does not enable HDLCD like the 32 bit one `arm` one for some reason.
  2495. ==== gem5 graphic mode DP650
  2496. TODO get working. There is an unmerged patchset at: https://gem5-review.googlesource.com/c/public/gem5/+/11036/1
  2497. The DP650 is a newer display hardware than HDLCD. TODO is its interface publicly documented anywhere? Since it has a gem5 model and link:https://github.com/torvalds/linux/blob/v4.19/drivers/gpu/drm/arm/Kconfig#L39[in-tree Linux kernel support], that information cannot be secret?
  2498. The key option to enable support in Linux is `DRM_MALI_DISPLAY=y` which we enable at link:linux_config/display[].
  2499. Build the kernel exactly as for <<graphic-mode-gem5-aarch64>> and then run with:
  2500. ....
  2501. ./run --arch aarch64 --dp650 --emulator gem5 --linux-build-id gem5-v4.15
  2502. ....
  2503. ==== Graphic mode gem5 internals
  2504. We cannot use mainline Linux because the <<gem5-arm-linux-kernel-patches>> are required at least to provide the `CONFIG_DRM_VIRT_ENCODER` option.
  2505. 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`.
  2506. The kernel uses HDLCD to implement the <<drm>> interface, the required kernel config options are present at: link:linux_config/display[].
  2507. TODO: minimize out the `--custom-config-file`. If we just remove it on `arm`: it does not work with a failing dmesg:
  2508. ....
  2509. [ 0.066208] [drm] found ARM HDLCD version r0p0
  2510. [ 0.066241] hdlcd 2b000000.hdlcd: bound virt-encoder (ops drm_vencoder_ops)
  2511. [ 0.066247] [drm] Supports vblank timestamp caching Rev 2 (21.10.2013).
  2512. [ 0.066252] [drm] No driver support for vblank timestamp query.
  2513. [ 0.066276] hdlcd 2b000000.hdlcd: Cannot do DMA to address 0x0000000000000000
  2514. [ 0.066281] swiotlb: coherent allocation failed for device 2b000000.hdlcd size=8294400
  2515. [ 0.066288] CPU: 0 PID: 1 Comm: swapper/0 Not tainted 4.15.0 #1
  2516. [ 0.066293] Hardware name: V2P-AARCH64 (DT)
  2517. [ 0.066296] Call trace:
  2518. [ 0.066301] dump_backtrace+0x0/0x1b0
  2519. [ 0.066306] show_stack+0x24/0x30
  2520. [ 0.066311] dump_stack+0xb8/0xf0
  2521. [ 0.066316] swiotlb_alloc_coherent+0x17c/0x190
  2522. [ 0.066321] __dma_alloc+0x68/0x160
  2523. [ 0.066325] drm_gem_cma_create+0x98/0x120
  2524. [ 0.066330] drm_fbdev_cma_create+0x74/0x2e0
  2525. [ 0.066335] __drm_fb_helper_initial_config_and_unlock+0x1d8/0x3a0
  2526. [ 0.066341] drm_fb_helper_initial_config+0x4c/0x58
  2527. [ 0.066347] drm_fbdev_cma_init_with_funcs+0x98/0x148
  2528. [ 0.066352] drm_fbdev_cma_init+0x40/0x50
  2529. [ 0.066357] hdlcd_drm_bind+0x220/0x428
  2530. [ 0.066362] try_to_bring_up_master+0x21c/0x2b8
  2531. [ 0.066367] component_master_add_with_match+0xa8/0xf0
  2532. [ 0.066372] hdlcd_probe+0x60/0x78
  2533. [ 0.066377] platform_drv_probe+0x60/0xc8
  2534. [ 0.066382] driver_probe_device+0x30c/0x478
  2535. [ 0.066388] __driver_attach+0x10c/0x128
  2536. [ 0.066393] bus_for_each_dev+0x70/0xb0
  2537. [ 0.066398] driver_attach+0x30/0x40
  2538. [ 0.066402] bus_add_driver+0x1d0/0x298
  2539. [ 0.066408] driver_register+0x68/0x100
  2540. [ 0.066413] __platform_driver_register+0x54/0x60
  2541. [ 0.066418] hdlcd_platform_driver_init+0x20/0x28
  2542. [ 0.066424] do_one_initcall+0x44/0x130
  2543. [ 0.066428] kernel_init_freeable+0x13c/0x1d8
  2544. [ 0.066433] kernel_init+0x18/0x108
  2545. [ 0.066438] ret_from_fork+0x10/0x1c
  2546. [ 0.066444] hdlcd 2b000000.hdlcd: Failed to set initial hw configuration.
  2547. [ 0.066470] hdlcd 2b000000.hdlcd: master bind failed: -12
  2548. [ 0.066477] hdlcd: probe of 2b000000.hdlcd failed with error -12
  2549. [
  2550. ....
  2551. So what other options are missing from `gem5_defconfig`? It would be cool to minimize it out to better understand the options.
  2552. [[x11]]
  2553. === X11 Buildroot
  2554. Once you've seen the `CONFIG_LOGO` penguin as a sanity check, you can try to go for a cooler X11 Buildroot setup.
  2555. Build and run:
  2556. ....
  2557. ./build-buildroot --config-fragment buildroot_config/x11
  2558. ./run --graphic
  2559. ....
  2560. Inside QEMU:
  2561. ....
  2562. startx
  2563. ....
  2564. And then from the GUI you can start exciting graphical programs such as:
  2565. ....
  2566. xcalc
  2567. xeyes
  2568. ....
  2569. Outcome:
  2570. image:x11.png[image]
  2571. 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.
  2572. More details: https://unix.stackexchange.com/questions/70931/how-to-install-x11-on-my-own-linux-buildroot-system/306116#306116
  2573. 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.
  2574. To x11 packages have an `xserver` prefix as in:
  2575. ....
  2576. ./build-buildroot --config-fragment buildroot_config/x11 -- xserver_xorg-server-reconfigure
  2577. ....
  2578. the easiest way to find them out is to just list `"$(./getvar buildroot_build_build_dir)/x*`.
  2579. TODO as of: c2696c978d6ca88e8b8599c92b1beeda80eb62b2 I noticed that `startx` leads to a <<bug_on>>:
  2580. ....
  2581. [ 2.809104] WARNING: CPU: 0 PID: 51 at drivers/gpu/drm/ttm/ttm_bo_vm.c:304 ttm_bo_vm_open+0x37/0x40
  2582. ....
  2583. ==== X11 Buildroot mouse not moving
  2584. 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.
  2585. * https://askubuntu.com/questions/730891/how-can-i-get-a-mouse-cursor-in-qemu
  2586. * https://stackoverflow.com/questions/19665412/mouse-and-keyboard-not-working-in-qemu-emulator
  2587. `-show-cursor` did not help, I just get to see the host cursor, but the guest cursor still does not move.
  2588. Doing:
  2589. ....
  2590. watch -n 1 grep i8042 /proc/interrupts
  2591. ....
  2592. shows that interrupts do happen when mouse and keyboard presses are done, so I expect that it is some wrong either with:
  2593. * QEMU. Same behaviour if I try the host's QEMU 2.10.1 however.
  2594. * X11 configuration. We do have `BR2_PACKAGE_XDRIVER_XF86_INPUT_MOUSE=y`.
  2595. `/var/log/Xorg.0.log` contains the following interesting lines:
  2596. ....
  2597. [ 27.549] (II) LoadModule: "mouse"
  2598. [ 27.549] (II) Loading /usr/lib/xorg/modules/input/mouse_drv.so
  2599. [ 27.590] (EE) <default pointer>: Cannot find which device to use.
  2600. [ 27.590] (EE) <default pointer>: cannot open input device
  2601. [ 27.590] (EE) PreInit returned 2 for "<default pointer>"
  2602. [ 27.590] (II) UnloadModule: "mouse"
  2603. ....
  2604. The file `/dev/inputs/mice` does not exist.
  2605. Note that our current link:kernel_confi_fragment sets:
  2606. ....
  2607. # CONFIG_INPUT_MOUSE is not set
  2608. # CONFIG_INPUT_MOUSEDEV_PSAUX is not set
  2609. ....
  2610. for gem5, so you might want to remove those lines to debug this.
  2611. ==== X11 Buildroot ARM
  2612. On ARM, `startx` hangs at a message:
  2613. ....
  2614. vgaarb: this pci device is not a vga device
  2615. ....
  2616. and nothing shows on the screen, and:
  2617. ....
  2618. grep EE /var/log/Xorg.0.log
  2619. ....
  2620. says:
  2621. ....
  2622. (EE) Failed to load module "modesetting" (module does not exist, 0)
  2623. ....
  2624. A friend told me this but I haven't tried it yet:
  2625. * `xf86-video-modesetting` is likely the missing ingredient, but it does not seem possible to activate it from Buildroot currently without patching things.
  2626. * `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`
  2627. == Networking
  2628. === Enable networking
  2629. We disable networking by default because it starts an userland process, and we want to keep the number of userland processes to a minimum to make the system more understandable: <<resource-tradeoff-guidelines>>
  2630. To enable networking on Buildroot, simply run:
  2631. ....
  2632. ifup -a
  2633. ....
  2634. That command goes over all (`-a`) the interfaces in `/etc/network/interfaces` and brings them up.
  2635. Then test it with:
  2636. ....
  2637. wget google.com
  2638. cat index.html
  2639. ....
  2640. Disable networking with:
  2641. ....
  2642. ifdown -a
  2643. ....
  2644. To enable networking by default after boot, use the methods documented at <<init-busybox>>.
  2645. === ping
  2646. `ping` does not work within QEMU by default, e.g.:
  2647. ....
  2648. ping google.com
  2649. ....
  2650. hangs after printing the header:
  2651. ....
  2652. PING google.com (216.58.204.46): 56 data bytes
  2653. ....
  2654. https://unix.stackexchange.com/questions/473448/how-to-ping-from-the-qemu-guest-to-an-external-url
  2655. === Guest host networking
  2656. In this section we discuss how to interact between the guest and the host through networking.
  2657. First ensure that you can access the external network since that is easier to get working: <<networking>>.
  2658. ==== Host to guest networking
  2659. ===== nc host to guest
  2660. With `nc` we can create the most minimal example possible as a sanity check.
  2661. On guest run:
  2662. ....
  2663. nc -l -p 45455
  2664. ....
  2665. Then on host run:
  2666. ....
  2667. echo asdf | nc localhost 45455
  2668. ....
  2669. `asdf` appears on the guest.
  2670. This uses:
  2671. * BusyBox' `nc` utility, which is enabled with `CONFIG_NC=y`
  2672. * `nc` from the `netcat-openbsd` package on an Ubuntu 18.04 host
  2673. Only this specific port works by default since we have forwarded it on the QEMU command line.
  2674. We us this exact procedure to connect to <<gdbserver>>.
  2675. ===== ssh into guest
  2676. Not enabled by default due to the build / runtime overhead. To enable, build with:
  2677. ....
  2678. ./build-buildroot --config 'BR2_PACKAGE_OPENSSH=y'
  2679. ....
  2680. Then inside the guest turn on sshd:
  2681. ....
  2682. /sshd.sh
  2683. ....
  2684. Source: link:rootfs_overlay/sshd.sh[]
  2685. And finally on host:
  2686. ....
  2687. ssh root@localhost -p 45456
  2688. ....
  2689. Bibliography: https://unix.stackexchange.com/questions/124681/how-to-ssh-from-host-to-guest-using-qemu/307557#307557
  2690. ===== gem5 host to guest networking
  2691. 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
  2692. ==== Guest to host networking
  2693. TODO I never got this to work.
  2694. There is `guestfwd`, which sounds analogous to `hostwfd` used in the other sense, but I was not able to get it working, e.g.:
  2695. ....
  2696. -netdev user,hostfwd=tcp::45455-:45455,guestfwd=tcp::45456-,id=net0 \
  2697. ....
  2698. gives:
  2699. ....
  2700. Could not open guest forwarding device 'guestfwd.tcp.45456'
  2701. ....
  2702. Bibliography: https://serverfault.com/questions/769874/how-to-forward-a-port-from-guest-to-host-in-qemu-kvm
  2703. === 9P
  2704. The link:https://en.wikipedia.org/wiki/9P_(protocol)[9p protocol] allows the guest to mount a host directory.
  2705. Both QEMU and <<9p-gem5>> support 9P.
  2706. ==== 9P vs NFS
  2707. All of 9P and NFS (and sshfs) allow sharing directories between guest and host.
  2708. Advantages of 9P
  2709. * we haven't managed to do <<guest-to-host-networking>>, which prevents us from mounting a host directory on the guest
  2710. +
  2711. Furthermore, this would require `sudo` on the host to mount
  2712. * we could share a guest directory to the host, but this would require running a server on the guest, which adds <<resource-tradeoff-guidelines,simulation overhead>>
  2713. +
  2714. Furthermore, this would be inconvenient, since what we usually want to do is to share host cross built files with the guest, and to do that we would have to copy the files over after the guest starts the server.
  2715. * QEMU implements 9P natively, which makes it very stable and convenient, and must mean it is a simpler protocol than NFS as one would expect.
  2716. +
  2717. This is not the case for gem5 7bfb7f3a43f382eb49853f47b140bfd6caad0fb8 unfortunately, which relies on the link:https://github.com/chaos/diod[diod] host daemon, although it is not unfeasible that future versions could implement it natively as well.
  2718. Advantages of NFS:
  2719. * way more widely used and therefore stable and available, not to mention that it also works on real hardware.
  2720. * the name does not start with a digit, which is an invalid identifier in all programming languages known to man. Who in their right mind would call a software project as such? It does not even match the natural order of Plan 9; Plan then 9: P9!
  2721. ==== 9P getting started
  2722. As usual, we have already set everything up for you. On host:
  2723. ....
  2724. cd "$(./getvar p9_dir)"
  2725. uname -a > host
  2726. ....
  2727. Guest:
  2728. ....
  2729. cd /mnt/9p/data
  2730. cat host
  2731. uname -a > guest
  2732. ....
  2733. Host:
  2734. ....
  2735. cat guest
  2736. ....
  2737. The main ingredients for this are:
  2738. * `9P` settings in our <<kernel-configs-about,kernel configs>>
  2739. * `9p` entry on our link:rootfs_overlay/etc/fstab[]
  2740. +
  2741. Alternatively, you could also mount your own with:
  2742. +
  2743. ....
  2744. mkdir /mnt/my9p
  2745. mount -t 9p -o trans=virtio,version=9p2000.L host0 /mnt/my9p
  2746. ....
  2747. * Launch QEMU with `-virtfs` as in your link:run[] script
  2748. +
  2749. When we tried:
  2750. +
  2751. ....
  2752. security_model=mapped
  2753. ....
  2754. +
  2755. writes from guest failed due to user mismatch problems: https://serverfault.com/questions/342801/read-write-access-for-passthrough-9p-filesystems-with-libvirt-qemu
  2756. Bibliography:
  2757. * https://superuser.com/questions/628169/how-to-share-a-directory-with-the-host-without-networking-in-qemu
  2758. * https://wiki.qemu.org/Documentation/9psetup
  2759. ==== 9P gem5
  2760. TODO seems possible! Lets do it:
  2761. * http://gem5.org/wiki/images/b/b8/Summit2017_wa_devlib.pdf
  2762. * http://gem5.org/WA-gem5
  2763. == Linux kernel
  2764. === Linux kernel configuration
  2765. ==== Modify kernel config
  2766. By default, we use a `.config` that is a mixture of:
  2767. * Buildroot's minimal per machine `.config`, which has the minimal options needed to boot
  2768. * our <<kernel-configs-about,kernel configs>> which enables options we want to play with
  2769. To modify a single option on top of our defaults, do:
  2770. ....
  2771. ./build-linux --config 'CONFIG_FORTIFY_SOURCE=y'
  2772. ....
  2773. Kernel modules depend on certain kernel configs, and therefore in general you might have to clean and rebuild the kernel modules after changing the kernel config:
  2774. ....
  2775. ./build-modules --clean
  2776. ./build-modules
  2777. ....
  2778. and then proceed as in <<your-first-kernel-module-hack>>.
  2779. You might often get way without rebuilding the kernel modules however.
  2780. To use an extra kernel config fragment file on top of our defaults, do:
  2781. ....
  2782. printf '
  2783. CONFIG_IKCONFIG=y
  2784. CONFIG_IKCONFIG_PROC=y
  2785. ' > data/myconfig
  2786. ./build-linux --config-fragment 'data/myconfig'
  2787. ....
  2788. To use just your own exact `.config` instead of our defaults ones, use:
  2789. ....
  2790. ./build-linux --custom-config-file data/myconfig
  2791. ....
  2792. The following options can all be used together, sorted by decreasing config setting power precedence:
  2793. * `--config`
  2794. * `--config-fragment`
  2795. * `--custom-config-file`
  2796. ==== Find the kernel config
  2797. Ge the build config in guest:
  2798. ....
  2799. zcat /proc/config.gz
  2800. ....
  2801. or with our shortcut:
  2802. ....
  2803. /conf.sh
  2804. ....
  2805. or to conveniently grep for a specific option case insensitively:
  2806. ....
  2807. /conf.sh ikconfig
  2808. ....
  2809. Source: link:rootfs_overlay/conf.sh[].
  2810. This is enabled by:
  2811. ....
  2812. CONFIG_IKCONFIG=y
  2813. CONFIG_IKCONFIG_PROC=y
  2814. ....
  2815. From host:
  2816. ....
  2817. cat "$(./getvar linux_build_dir)/.config"
  2818. ....
  2819. Just for fun link:https://stackoverflow.com/a/14958263/895245[]:
  2820. ....
  2821. ./linux/scripts/extract-ikconfig "$(./getvar vmlinux)"
  2822. ....
  2823. although this can be useful when someone gives you a random image.
  2824. [[kernel-configs-about]]
  2825. ==== About our Linux kernel configs
  2826. All our Linux kernel configs are stored under link:linux_config/[].
  2827. To find out which kernel configs are being used, simply run:
  2828. ....
  2829. ./build-linux --dry-run
  2830. ....
  2831. and look for the `merge_config.sh` call. This script from the Linux kernel tree, as the name suggests, merges multiple configuration files into one as explained at: https://unix.stackexchange.com/questions/224887/how-to-script-make-menuconfig-to-automate-linux-kernel-build-configuration/450407#450407
  2832. For each arch, the base of our configs are named as:
  2833. ....
  2834. linux_config/buildroot-<arch>
  2835. ....
  2836. e.g.: link:linux_config/buildroot-x86_64[].
  2837. These configs are extracted directly from a Buildroot build with link:update-buildroot-kernel-config[].
  2838. Note that Buildroot can `sed` override some of the configurations, e.g. it forces `CONFIG_BLK_DEV_INITRD=y` when `BR2_TARGET_ROOTFS_CPIO` is on. For this reason, those configs are not simply copy pasted from Buildroot files, but rather from a Buildroot kernel build, and then minimized with `make savedefconfig`.
  2839. On top of those, we add the following by default:
  2840. * link:linux_config/min[]: minimal tweaks required to boot gem5 or for using our slightly different QEMU command line options than Buildroot on all archs
  2841. +
  2842. Having the same config working for both QEMU and gem5 (oh, the hours of bisection) means that you can deal with functional matters in QEMU, which runs much faster, and switch to gem5 only for performance issues.
  2843. +
  2844. * link:linux_config/default[]: other optional configs that we enable by default because they increase visibility, or expose some cool feature, and don't significantly increase build time nor add significant runtime overhead
  2845. ===== About Buildroot's kernel configs
  2846. To see Buildroot's base configs, start from link:https://github.com/buildroot/buildroot/blob/2018.05/configs/qemu_x86_64_defconfig[`buildroot/configs/qemu_x86_64_defconfig`].
  2847. That file contains `BR2_LINUX_KERNEL_CUSTOM_CONFIG_FILE="board/qemu/x86_64/linux-4.15.config"`, which points to the base config file used: link:https://github.com/buildroot/buildroot/blob/2018.05/board/qemu/x86_64/linux-4.15.config[board/qemu/x86_64/linux-4.15.config].
  2848. `arm`, on the other hand, uses link:https://github.com/buildroot/buildroot/blob/2018.05/configs/qemu_arm_vexpress_defconfig[`buildroot/configs/qemu_arm_vexpress_defconfig`], which contains `BR2_LINUX_KERNEL_DEFCONFIG="vexpress"`, and therefore just does a `make vexpress_defconfig`, and gets its config from the Linux kernel tree itself.
  2849. ====== Linux kernel defconfigs
  2850. It would be interesting to test out if `make defconfig` configs boot and work on QEMU + Buildroot: https://unix.stackexchange.com/questions/29439/compiling-the-kernel-with-default-configurations/204512#204512
  2851. TODO.
  2852. ===== Notable alternate gem5 kernel configs
  2853. Other configs which we had previously tested at 4e0d9af81fcce2ce4e777cb82a1990d7c2ca7c1e are:
  2854. * `arm` and `aarch64` configs present in the official ARM gem5 Linux kernel fork: <<gem5-arm-linux-kernel-patches>>. Some of the configs present there are added by the patches.
  2855. * 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`.
  2856. === Kernel version
  2857. ==== Find the kernel version
  2858. We try to use the latest possible kernel major release version.
  2859. In QEMU:
  2860. ....
  2861. cat /proc/version
  2862. ....
  2863. or in the source:
  2864. ....
  2865. cd "$(./getvar linux_source_dir)"
  2866. git log | grep -E ' Linux [0-9]+\.' | head
  2867. ....
  2868. ==== Update the Linux kernel
  2869. During update all you kernel modules may break since the kernel API is not stable.
  2870. They are usually trivial breaks of things moving around headers or to sub-structs.
  2871. The userland, however, should simply not break, as Linus enforces strict backwards compatibility of userland interfaces.
  2872. This backwards compatibility is just awesome, it makes getting and running the latest master painless.
  2873. This also makes this repo the perfect setup to develop the Linux kernel.
  2874. In case something breaks while updating the Linux kernel, you can try to bisect it to understand the root cause: <<bisection>>.
  2875. ==== Downgrade the Linux kernel
  2876. 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.
  2877. The default Linux kernel version is bumped in Buildroot with commit messages of type:
  2878. ....
  2879. linux: bump default to version 4.9.6
  2880. ....
  2881. So you can try:
  2882. ....
  2883. git log --grep 'linux: bump default to version'
  2884. ....
  2885. Those commits change `BR2_LINUX_KERNEL_LATEST_VERSION` in `/linux/Config.in`.
  2886. 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.
  2887. Finally, after downgrading Buildroot, if something does not work, you might also have to make some changes to how this repo uses Buildroot, as the Buildroot configuration options might have changed.
  2888. We don't expect those changes to be very difficult. A good way to approach the task is to:
  2889. * do a dry run build to get the equivalent Bash commands used:
  2890. +
  2891. ....
  2892. ./build-buildroot --dry-run
  2893. ....
  2894. * build the Buildroot documentation for the version you are going to use, and check if all Buildroot build commands make sense there
  2895. Then, if you spot an option that is wrong, some grepping in this repo should quickly point you to the code you need to modify.
  2896. It also possible that you will need to apply some patches from newer Buildroot versions for it to build, due to incompatibilities with the host Ubuntu packages and that Buildroot version. Just read the error message, and try:
  2897. * `git log master -- packages/<pkg>`
  2898. * Google the error message for mailing list hits
  2899. Successful port reports:
  2900. * v3.18: https://github.com/cirosantilli/linux-kernel-module-cheat/issues/39#issuecomment-438525481
  2901. === Kernel command line parameters
  2902. 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.
  2903. This allows us to control the behaviour of the kernel without rebuilding anything.
  2904. With QEMU, QEMU itself acts as the bootloader, and provides the `-append` option and we expose it through `./run --kernel-cli`, e.g.:
  2905. ....
  2906. ./run --kernel-cli 'foo bar'
  2907. ....
  2908. Then inside the host, you can check which options were given with:
  2909. ....
  2910. cat /proc/cmdline
  2911. ....
  2912. They are also printed at the beginning of the boot message:
  2913. ....
  2914. dmesg | grep "Command line"
  2915. ....
  2916. See also:
  2917. * https://unix.stackexchange.com/questions/48601/how-to-display-the-linux-kernel-command-line-parameters-given-for-the-current-bo
  2918. * https://askubuntu.com/questions/32654/how-do-i-find-the-boot-parameters-used-by-the-running-kernel
  2919. The arguments are documented in the kernel documentation: https://www.kernel.org/doc/html/v4.14/admin-guide/kernel-parameters.html
  2920. When dealing with real boards, extra command line options are provided on some magic bootloader configuration file, e.g.:
  2921. * GRUB configuration files: https://askubuntu.com/questions/19486/how-do-i-add-a-kernel-boot-parameter
  2922. * 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
  2923. ==== Kernel command line parameters escaping
  2924. 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"`
  2925. This even lead us to use base64 encoding with `--eval`!
  2926. ==== Kernel command line parameters definition points
  2927. There are two methods:
  2928. * `__setup` as in:
  2929. +
  2930. ....
  2931. __setup("console=", console_setup);
  2932. ....
  2933. * `core_param` as in:
  2934. +
  2935. ....
  2936. core_param(panic, panic_timeout, int, 0644);
  2937. ....
  2938. `core_param` suggests how they are different:
  2939. ....
  2940. /**
  2941. * core_param - define a historical core kernel parameter.
  2942. ...
  2943. * core_param is just like module_param(), but cannot be modular and
  2944. * doesn't add a prefix (such as "printk."). This is for compatibility
  2945. * with __setup(), and it makes sense as truly core parameters aren't
  2946. * tied to the particular file they're in.
  2947. */
  2948. ....
  2949. ==== rw
  2950. By default, the Linux kernel mounts the root filesystem as readonly. TODO rationale?
  2951. This cannot be observed in the default BusyBox init, because by default our link:rootfs_overlay/etc/inittab[] does:
  2952. ....
  2953. /bin/mount -o remount,rw /
  2954. ....
  2955. Analogously, Ubuntu 18.04 does in its fstab something like:
  2956. ....
  2957. UUID=/dev/sda1 / ext4 errors=remount-ro 0 1
  2958. ....
  2959. which uses default mount `rw` flags.
  2960. We have however removed those setups init setups to keep things more minimal, and replaced them with the `rw` kernel boot parameter makes the root mounted as writable.
  2961. To observe the default readonly behaviour, hack the link:run[] script to remove <<replace-init,replace init>>, and then run on a raw shell:
  2962. ....
  2963. ./run --kernel-cli 'init=/bin/sh'
  2964. ....
  2965. Now try to do:
  2966. ....
  2967. touch a
  2968. ....
  2969. which fails with:
  2970. ....
  2971. touch: a: Read-only file system
  2972. ....
  2973. We can also observe the read-onlyness with:
  2974. ....
  2975. mount -t proc /proc
  2976. mount
  2977. ....
  2978. which contains:
  2979. ....
  2980. /dev/root on / type ext2 (ro,relatime,block_validity,barrier,user_xattr)
  2981. ....
  2982. and so it is Read Only as shown by `ro`.
  2983. ==== norandmaps
  2984. Disable userland address space randomization. Test it out by running <<rand_check-out>> twice:
  2985. ....
  2986. ./run --eval-after '/rand_check.out;/poweroff.out'
  2987. ./run --eval-after '/rand_check.out;/poweroff.out'
  2988. ....
  2989. If we remove it from our link:run[] script by hacking it up, the addresses shown by `rand_check.out` vary across boots.
  2990. Equivalent to:
  2991. ....
  2992. echo 0 > /proc/sys/kernel/randomize_va_space
  2993. ....
  2994. === printk
  2995. `printk` is the most simple and widely used way of getting information from the kernel, so you should familiarize yourself with its basic configuration.
  2996. We use `printk` a lot in our kernel modules, and it shows on the terminal by default, along with stdout and what you type.
  2997. Hide all `printk` messages:
  2998. ....
  2999. dmesg -n 1
  3000. ....
  3001. or equivalently:
  3002. ....
  3003. echo 1 > /proc/sys/kernel/printk
  3004. ....
  3005. See also: https://superuser.com/questions/351387/how-to-stop-kernel-messages-from-flooding-my-console
  3006. Do it with a <<kernel-command-line-parameters>> to affect the boot itself:
  3007. ....
  3008. ./run --kernel-cli 'loglevel=5'
  3009. ....
  3010. and now only boot warning messages or worse show, which is useful to identify problems.
  3011. Our default `printk` format is:
  3012. ....
  3013. <LEVEL>[TIMESTAMP] MESSAGE
  3014. ....
  3015. e.g.:
  3016. ....
  3017. <6>[ 2.979121] Freeing unused kernel memory: 2024K
  3018. ....
  3019. where:
  3020. * `LEVEL`: higher means less serious
  3021. * `TIMESTAMP`: seconds since boot
  3022. This format is selected by the following boot options:
  3023. * `console_msg_format=syslog`: add the `<LEVEL>` part. Added in v4.16.
  3024. * `printk.time=y`: add the `[TIMESTAMP]` part
  3025. The debug highest level is a bit more magic, see: <<pr_debug>> for more info.
  3026. ==== ignore_loglevel
  3027. ....
  3028. ./run --kernel-cli 'ignore_loglevel'
  3029. ....
  3030. enables all log levels, and is basically the same as:
  3031. ....
  3032. ./run --kernel-cli 'loglevel=8'
  3033. ....
  3034. except that you don't need to know what is the maximum level.
  3035. ==== pr_debug
  3036. https://stackoverflow.com/questions/28936199/why-is-pr-debug-of-the-linux-kernel-not-giving-any-output/49835405#49835405
  3037. Debug messages are not printable by default without recompiling.
  3038. But the awesome `CONFIG_DYNAMIC_DEBUG=y` option which we enable by default allows us to do:
  3039. ....
  3040. echo 8 > /proc/sys/kernel/printk
  3041. echo 'file kernel/module.c +p' > /sys/kernel/debug/dynamic_debug/control
  3042. /myinsmod.out /hello.ko
  3043. ....
  3044. and we have a shortcut at:
  3045. ....
  3046. /pr_debug.sh
  3047. ....
  3048. Source: link:rootfs_overlay/pr_debug.sh[].
  3049. Syntax: https://www.kernel.org/doc/html/v4.11/admin-guide/dynamic-debug-howto.html
  3050. Wildcards are also accepted, e.g. enable all messages from all files:
  3051. ....
  3052. echo 'file * +p' > /sys/kernel/debug/dynamic_debug/control
  3053. ....
  3054. TODO: why is this not working:
  3055. ....
  3056. echo 'func sys_init_module +p' > /sys/kernel/debug/dynamic_debug/control
  3057. ....
  3058. Enable messages in specific modules:
  3059. ....
  3060. echo 8 > /proc/sys/kernel/printk
  3061. echo 'module myprintk +p' > /sys/kernel/debug/dynamic_debug/control
  3062. insmod /myprintk.ko
  3063. ....
  3064. Source: link:kernel_modules/myprintk.c[]
  3065. This outputs the `pr_debug` message:
  3066. ....
  3067. printk debug
  3068. ....
  3069. but TODO: it also shows debug messages even without enabling them explicitly:
  3070. ....
  3071. echo 8 > /proc/sys/kernel/printk
  3072. insmod /myprintk.ko
  3073. ....
  3074. and it shows as enabled:
  3075. ....
  3076. # grep myprintk /sys/kernel/debug/dynamic_debug/control
  3077. /root/linux-kernel-module-cheat/out/kernel_modules/x86_64/kernel_modules/panic.c:12 [myprintk]myinit =p "pr_debug\012"
  3078. ....
  3079. Enable `pr_debug` for boot messages as well, before we can reach userland and write to `/proc`:
  3080. ....
  3081. ./run --kernel-cli 'dyndbg="file * +p" loglevel=8'
  3082. ....
  3083. Get ready for the noisiest boot ever, I think it overflows the `printk` buffer and funny things happen.
  3084. ===== pr_debug != printk(KERN_DEBUG
  3085. 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:
  3086. ....
  3087. ./run --kernel-cli 'initcall_debug logleve=8'
  3088. ....
  3089. which outputs lines of type:
  3090. ....
  3091. <7>[ 1.756680] calling clk_disable_unused+0x0/0x130 @ 1
  3092. <7>[ 1.757003] initcall clk_disable_unused+0x0/0x130 returned 0 after 111 usecs
  3093. ....
  3094. which are `printk(KERN_DEBUG` inside `init/main.c` in v4.16.
  3095. Mentioned at: https://stackoverflow.com/questions/37272109/how-to-get-details-of-all-modules-drivers-got-initialized-probed-during-kernel-b
  3096. This likely comes from the ifdef split at `init/main.c`:
  3097. ....
  3098. /* If you are writing a driver, please use dev_dbg instead */
  3099. #if defined(CONFIG_DYNAMIC_DEBUG)
  3100. #include <linux/dynamic_debug.h>
  3101. /* dynamic_pr_debug() uses pr_fmt() internally so we don't need it here */
  3102. #define pr_debug(fmt, ...) \
  3103. dynamic_pr_debug(fmt, ##__VA_ARGS__)
  3104. #elif defined(DEBUG)
  3105. #define pr_debug(fmt, ...) \
  3106. printk(KERN_DEBUG pr_fmt(fmt), ##__VA_ARGS__)
  3107. #else
  3108. #define pr_debug(fmt, ...) \
  3109. no_printk(KERN_DEBUG pr_fmt(fmt), ##__VA_ARGS__)
  3110. #endif
  3111. ....
  3112. === Linux kernel entry point
  3113. `start_kernel` is a good definition of it: https://stackoverflow.com/questions/18266063/does-kernel-have-main-function/33422401#33422401
  3114. === Kernel module APIs
  3115. ==== Kernel module parameters
  3116. The Linux kernel allows passing module parameters at insertion time <<myinsmod,through the `init_module` and `finit_module` system calls>>:
  3117. ....
  3118. /params.sh
  3119. echo $?
  3120. ....
  3121. Outcome: the test passes:
  3122. ....
  3123. 0
  3124. ....
  3125. Sources:
  3126. * link:kernel_modules/params.c[]
  3127. * link:rootfs_overlay/params.sh[]
  3128. As shown in the example, module parameters can also be read and modified at runtime from <<sysfs>>.
  3129. We can obtain the help text of the parameters with:
  3130. ....
  3131. modinfo /params.ko
  3132. ....
  3133. The output contains:
  3134. ....
  3135. parm: j:my second favorite int
  3136. parm: i:my favorite int
  3137. ....
  3138. ===== modprobe.conf
  3139. <<modprobe>> insertion can also set default parameters via the link:rootfs_overlay/etc/modprobe.conf[`/etc/modprobe.conf`] file:
  3140. ....
  3141. modprobe params
  3142. cat /sys/kernel/debug/lkmc_params
  3143. ....
  3144. Output:
  3145. ....
  3146. 12 34
  3147. ....
  3148. This is specially important when loading modules with <<kernel-module-dependencies>> or else we would have no opportunity of passing those.
  3149. `modprobe.conf` doesn't actually insmod anything for us: https://superuser.com/questions/397842/automatically-load-kernel-module-at-boot-angstrom/1267464#1267464
  3150. ==== Kernel module dependencies
  3151. One module can depend on symbols of another module that are exported with `EXPORT_SYMBOL`:
  3152. ....
  3153. /dep.sh
  3154. echo $?
  3155. ....
  3156. Outcome: the test passes:
  3157. ....
  3158. 0
  3159. ....
  3160. Sources:
  3161. * link:kernel_modules/dep.c[]
  3162. * link:kernel_modules/dep2.c[]
  3163. * link:rootfs_overlay/dep.sh[]
  3164. The kernel deduces dependencies based on the `EXPORT_SYMBOL` that each module uses.
  3165. Symbols exported by `EXPORT_SYMBOL` can be seen with:
  3166. ....
  3167. insmod /dep.ko
  3168. grep lkmc_dep /proc/kallsyms
  3169. ....
  3170. sample output:
  3171. ....
  3172. ffffffffc0001030 r __ksymtab_lkmc_dep [dep]
  3173. ffffffffc000104d r __kstrtab_lkmc_dep [dep]
  3174. ffffffffc0002300 B lkmc_dep [dep]
  3175. ....
  3176. This requires `CONFIG_KALLSYMS_ALL=y`.
  3177. Dependency information is stored by the kernel module build system in the `.ko` files' <<module_info>>, e.g.:
  3178. ....
  3179. modinfo /dep2.ko
  3180. ....
  3181. contains:
  3182. ....
  3183. depends: dep
  3184. ....
  3185. We can double check with:
  3186. ....
  3187. strings 3 /dep2.ko | grep -E 'depends'
  3188. ....
  3189. The output contains:
  3190. ....
  3191. depends=dep
  3192. ....
  3193. Module dependencies are also stored at:
  3194. ....
  3195. cd /lib/module/*
  3196. grep dep modules.dep
  3197. ....
  3198. Output:
  3199. ....
  3200. extra/dep2.ko: extra/dep.ko
  3201. extra/dep.ko:
  3202. ....
  3203. TODO: what for, and at which point point does Buildroot / BusyBox generate that file?
  3204. ===== Kernel module dependencies with modprobe
  3205. Unlike `insmod`, <<modprobe>> deals with kernel module dependencies for us.
  3206. First get <<kernel_modules-package>> working.
  3207. Then, for example:
  3208. ....
  3209. modprobe buildroot_dep2
  3210. ....
  3211. outputs to dmesg:
  3212. ....
  3213. 42
  3214. ....
  3215. and then:
  3216. ....
  3217. lsmod
  3218. ....
  3219. outputs:
  3220. ....
  3221. Module Size Used by Tainted: G
  3222. buildroot_dep2 16384 0
  3223. buildroot_dep 16384 1 buildroot_dep2
  3224. ....
  3225. Sources:
  3226. * link:buildroot_packages/kernel_modules/buildroot_dep.c[]
  3227. * link:buildroot_packages/kernel_modules/buildroot_dep2.c[]
  3228. Removal also removes required modules that have zero usage count:
  3229. ....
  3230. modprobe -r buildroot_dep2
  3231. ....
  3232. `modprobe` uses information from the `modules.dep` file to decide the required dependencies. That file contains:
  3233. ....
  3234. extra/buildroot_dep2.ko: extra/buildroot_dep.ko
  3235. ....
  3236. Bibliography:
  3237. * https://askubuntu.com/questions/20070/whats-the-difference-between-insmod-and-modprobe
  3238. * https://stackoverflow.com/questions/22891705/whats-the-difference-between-insmod-and-modprobe
  3239. ==== MODULE_INFO
  3240. Module metadata is stored on module files at compile time. Some of the fields can be retrieved through the `THIS_MODULE` `struct module`:
  3241. ....
  3242. insmod /module_info.ko
  3243. ....
  3244. Dmesg output:
  3245. ....
  3246. name = module_info
  3247. version = 1.0
  3248. ....
  3249. Source: link:kernel_modules/module_info.c[]
  3250. Some of those are also present on sysfs:
  3251. ....
  3252. cat /sys/module/module_info/version
  3253. ....
  3254. Output:
  3255. ....
  3256. 1.0
  3257. ....
  3258. And we can also observe them with the `modinfo` command line utility:
  3259. ....
  3260. modinfo /module_info.ko
  3261. ....
  3262. sample output:
  3263. ....
  3264. filename: /module_info.ko
  3265. license: GPL
  3266. version: 1.0
  3267. srcversion: AF3DE8A8CFCDEB6B00E35B6
  3268. depends:
  3269. vermagic: 4.17.0 SMP mod_unload modversions
  3270. ....
  3271. Module information is stored in a special `.modinfo` section of the ELF file:
  3272. ....
  3273. ./run-toolchain readelf -- -SW "$(./getvar target_dir)/module_info.ko"
  3274. ....
  3275. contains:
  3276. ....
  3277. [ 5] .modinfo PROGBITS 0000000000000000 0000d8 000096 00 A 0 0 8
  3278. ....
  3279. and:
  3280. ....
  3281. ./run-toolchain readelf -- -x .modinfo "$(./getvar buildroot_build_build_dir)/module_info.ko"
  3282. ....
  3283. gives:
  3284. ....
  3285. 0x00000000 6c696365 6e73653d 47504c00 76657273 license=GPL.vers
  3286. 0x00000010 696f6e3d 312e3000 61736466 3d717765 ion=1.0.asdf=qwe
  3287. 0x00000020 72000000 00000000 73726376 65727369 r.......srcversi
  3288. 0x00000030 6f6e3d41 46334445 38413843 46434445 on=AF3DE8A8CFCDE
  3289. 0x00000040 42364230 30453335 42360000 00000000 B6B00E35B6......
  3290. 0x00000050 64657065 6e64733d 006e616d 653d6d6f depends=.name=mo
  3291. 0x00000060 64756c65 5f696e66 6f007665 726d6167 dule_info.vermag
  3292. 0x00000070 69633d34 2e31372e 3020534d 50206d6f ic=4.17.0 SMP mo
  3293. 0x00000080 645f756e 6c6f6164 206d6f64 76657273 d_unload modvers
  3294. 0x00000090 696f6e73 2000 ions .
  3295. ....
  3296. 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`.
  3297. Bibliography:
  3298. * https://stackoverflow.com/questions/19467150/significance-of-this-module-in-linux-driver/49812248#49812248
  3299. * https://stackoverflow.com/questions/4839024/how-to-find-the-version-of-a-compiled-kernel-module/42556565#42556565
  3300. * https://unix.stackexchange.com/questions/238167/how-to-understand-the-modinfo-output
  3301. ==== vermagic
  3302. Vermagic is a magic string present in the kernel and on <<module_info>> of kernel modules. It is used to verify that the kernel module was compiled against a compatible kernel version and relevant configuration:
  3303. ....
  3304. insmod /vermagic.ko
  3305. ....
  3306. Possible dmesg output:
  3307. ....
  3308. VERMAGIC_STRING = 4.17.0 SMP mod_unload modversions
  3309. ....
  3310. Source: link:kernel_modules/vermagic.c[]
  3311. If we artificially create a mismatch with `MODULE_INFO(vermagic`, the insmod fails with:
  3312. ....
  3313. insmod: can't insert '/vermagic_fail.ko': invalid module format
  3314. ....
  3315. and `dmesg` says the expected and found vermagic found:
  3316. ....
  3317. vermagic_fail: version magic 'asdfqwer' should be '4.17.0 SMP mod_unload modversions '
  3318. ....
  3319. Source: link:kernel_modules/vermagic_fail.c[]
  3320. 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]:
  3321. ....
  3322. #define VERMAGIC_STRING \
  3323. UTS_RELEASE " " \
  3324. MODULE_VERMAGIC_SMP MODULE_VERMAGIC_PREEMPT \
  3325. MODULE_VERMAGIC_MODULE_UNLOAD MODULE_VERMAGIC_MODVERSIONS \
  3326. MODULE_ARCH_VERMAGIC \
  3327. MODULE_RANDSTRUCT_PLUGIN
  3328. ....
  3329. The `SMP` part of the string for example is defined on the same file based on the value of `CONFIG_SMP`:
  3330. ....
  3331. #ifdef CONFIG_SMP
  3332. #define MODULE_VERMAGIC_SMP "SMP "
  3333. #else
  3334. #define MODULE_VERMAGIC_SMP ""
  3335. ....
  3336. TODO how to get the vermagic from running kernel from userland? https://lists.kernelnewbies.org/pipermail/kernelnewbies/2012-October/006306.html
  3337. <<kmod-modprobe>> has a flag to skip the vermagic check:
  3338. ....
  3339. --force-modversion
  3340. ....
  3341. This option just strips `modversion` information from the module before loading, so it is not a kernel feature.
  3342. ==== module_init
  3343. `init_module` and `cleantup_module` are an older alternative to the `module_init` and `module_exit` macros:
  3344. ....
  3345. insmod /init_module.ko
  3346. rmmod init_module
  3347. ....
  3348. Dmesg output:
  3349. ....
  3350. init_module
  3351. cleanup_module
  3352. ....
  3353. Source: link:kernel_modules/module_init.c[]
  3354. 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
  3355. === Kernel panic and oops
  3356. To test out kernel panics and oops in controlled circumstances, try out the modules:
  3357. ....
  3358. insmod /panic.ko
  3359. insmod /oops.ko
  3360. ....
  3361. Source:
  3362. * link:kernel_modules/panic.c[]
  3363. * link:kernel_modules/oops.c[]
  3364. A panic can also be generated with:
  3365. ....
  3366. echo c > /proc/sysrq-trigger
  3367. ....
  3368. Panic vs oops: https://unix.stackexchange.com/questions/91854/whats-the-difference-between-a-kernel-oops-and-a-kernel-panic
  3369. How to generate them:
  3370. * https://unix.stackexchange.com/questions/66197/how-to-cause-kernel-panic-with-a-single-command
  3371. * https://stackoverflow.com/questions/23484147/generate-kernel-oops-or-crash-in-the-code
  3372. When a panic happens, <<linux-kernel-magic-keys,`Shift-PgUp`>> does not work as it normally does, and it is hard to get the logs if on are on <<qemu-graphic-mode>>:
  3373. * https://superuser.com/questions/848412/scrolling-up-the-failed-screen-with-kernel-panic
  3374. * https://superuser.com/questions/269228/write-qemu-booting-virtual-machine-output-to-a-file
  3375. * http://www.reactos.org/wiki/QEMU#Redirect_to_a_file
  3376. ==== Kernel panic
  3377. On panic, the kernel dies, and so does our terminal.
  3378. The panic trace looks like:
  3379. ....
  3380. panic: loading out-of-tree module taints kernel.
  3381. panic myinit
  3382. Kernel panic - not syncing: hello panic
  3383. CPU: 0 PID: 53 Comm: insmod Tainted: G O 4.16.0 #6
  3384. Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS rel-1.11.0-0-g63451fca13-prebuilt.qemu-project.org 04/01/2014
  3385. Call Trace:
  3386. dump_stack+0x7d/0xba
  3387. ? 0xffffffffc0000000
  3388. panic+0xda/0x213
  3389. ? printk+0x43/0x4b
  3390. ? 0xffffffffc0000000
  3391. myinit+0x1d/0x20 [panic]
  3392. do_one_initcall+0x3e/0x170
  3393. do_init_module+0x5b/0x210
  3394. load_module+0x2035/0x29d0
  3395. ? kernel_read_file+0x7d/0x140
  3396. ? SyS_finit_module+0xa8/0xb0
  3397. SyS_finit_module+0xa8/0xb0
  3398. do_syscall_64+0x6f/0x310
  3399. ? trace_hardirqs_off_thunk+0x1a/0x32
  3400. entry_SYSCALL_64_after_hwframe+0x42/0xb7
  3401. RIP: 0033:0x7ffff7b36206
  3402. RSP: 002b:00007fffffffeb78 EFLAGS: 00000206 ORIG_RAX: 0000000000000139
  3403. RAX: ffffffffffffffda RBX: 000000000000005c RCX: 00007ffff7b36206
  3404. RDX: 0000000000000000 RSI: 000000000069e010 RDI: 0000000000000003
  3405. RBP: 000000000069e010 R08: 00007ffff7ddd320 R09: 0000000000000000
  3406. R10: 00007ffff7ddd320 R11: 0000000000000206 R12: 0000000000000003
  3407. R13: 00007fffffffef4a R14: 0000000000000000 R15: 0000000000000000
  3408. Kernel Offset: disabled
  3409. ---[ end Kernel panic - not syncing: hello panic
  3410. ....
  3411. Notice how our panic message `hello panic` is visible at:
  3412. ....
  3413. Kernel panic - not syncing: hello panic
  3414. ....
  3415. ===== Kernel module stack trace to source line
  3416. The log shows which module each symbol belongs to if any, e.g.:
  3417. ....
  3418. myinit+0x1d/0x20 [panic]
  3419. ....
  3420. says that the function `myinit` is in the module `panic`.
  3421. To find the line that panicked, do:
  3422. ....
  3423. ./run-gdb
  3424. ....
  3425. and then:
  3426. ....
  3427. info line *(myinit+0x1d)
  3428. ....
  3429. which gives us the correct line:
  3430. ....
  3431. Line 7 of "/root/linux-kernel-module-cheat/out/kernel_modules/x86_64/kernel_modules/panic.c" starts at address 0xbf00001c <myinit+28> and ends at 0xbf00002c <myexit>.
  3432. ....
  3433. as explained at: https://stackoverflow.com/questions/8545931/using-gdb-to-convert-addresses-to-lines/27576029#27576029
  3434. The exact same thing can be done post mortem with:
  3435. ....
  3436. ./run-toolchain gdb -- \
  3437. -batch \
  3438. -ex 'info line *(myinit+0x1d)' \
  3439. "$(./getvar kernel_modules_build_subdir)/panic.ko" \
  3440. ;
  3441. ....
  3442. Related:
  3443. * https://stackoverflow.com/questions/6151538/addr2line-on-kernel-module
  3444. * https://stackoverflow.com/questions/13468286/how-to-read-understand-analyze-and-debug-a-linux-kernel-panic
  3445. ===== BUG_ON
  3446. Basically just calls `panic("BUG!")` for most archs.
  3447. ===== Exit emulator on panic
  3448. 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.
  3449. ====== Exit QEMU on panic
  3450. Enabled by default with:
  3451. * `panic=-1` command line option which reboots the kernel immediately on panic, see: <<reboot-on-panic>>
  3452. * QEMU `-no-reboot`, which makes QEMU exit when the guest tries to reboot
  3453. 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.
  3454. TODO neither method exits with exit status different from 0, so for now we are just grepping the logs for panic messages, which sucks.
  3455. 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.
  3456. ====== Exit gem5 on panic
  3457. gem5 actually detects panics automatically by parsing kernel symbols and detecting when the PC reaches the address of the `panic` function. gem5 then prints to stdout:
  3458. ....
  3459. Kernel panic in simulated kernel
  3460. ....
  3461. and exits with status -6.
  3462. We enable the `system.panic_on_panic` option by default on `arm` and `aarch64`, which makes gem5 exit immediately in case of panic, which is awesome!
  3463. If we don't set `system.panic_on_panic`, then gem5 just hangs.
  3464. TODO: why doesn't x86 support `system.panic_on_panic` as well? Trying to set `system.panic_on_panic` there fails with:
  3465. ....
  3466. AttributeError: Class LinuxX86System has no parameter panic_on_panic
  3467. ....
  3468. However, as of f9eb0b72de9029ff16091a18de109c18a9ecc30a, panic on x86 makes gem5 crash with:
  3469. ....
  3470. panic: i8042 "System reset" command not implemented.
  3471. ....
  3472. which is a good side effect of an unimplemented hardware feature, since the simulation actually stops.
  3473. The implementation of panic detection happens at: https://github.com/gem5/gem5/blob/1da285dfcc31b904afc27e440544d006aae25b38/src/arch/arm/linux/system.cc#L73
  3474. ....
  3475. kernelPanicEvent = addKernelFuncEventOrPanic<Linux::KernelPanicEvent>(
  3476. "panic", "Kernel panic in simulated kernel", dmesg_output);
  3477. ....
  3478. Here we see that the symbol `"panic"` for the `panic()` function is the one being tracked.
  3479. ===== Reboot on panic
  3480. Make the kernel reboot after n seconds after panic:
  3481. ....
  3482. echo 1 > /proc/sys/kernel/panic
  3483. ....
  3484. Can also be controlled with the `panic=` kernel boot parameter.
  3485. `0` to disable, `-1` to reboot immediately.
  3486. Bibliography:
  3487. * https://github.com/torvalds/linux/blob/v4.17/Documentation/admin-guide/kernel-parameters.txt#L2931
  3488. * https://unix.stackexchange.com/questions/29567/how-to-configure-the-linux-kernel-to-reboot-on-panic/29569#29569
  3489. ===== Panic trace show addresses instead of symbols
  3490. If `CONFIG_KALLSYMS=n`, then addresses are shown on traces instead of symbol plus offset.
  3491. In v4.16 it does not seem possible to configure that at runtime. GDB step debugging with:
  3492. ....
  3493. ./run --eval-after 'insmod /dump_stack.ko' --wait-gdb --tmux-args dump_stack
  3494. ....
  3495. shows that traces are printed at `arch/x86/kernel/dumpstack.c`:
  3496. ....
  3497. static void printk_stack_address(unsigned long address, int reliable,
  3498. char *log_lvl)
  3499. {
  3500. touch_nmi_watchdog();
  3501. printk("%s %s%pB\n", log_lvl, reliable ? "" : "? ", (void *)address);
  3502. }
  3503. ....
  3504. and `%pB` is documented at `Documentation/core-api/printk-formats.rst`:
  3505. ....
  3506. If KALLSYMS are disabled then the symbol address is printed instead.
  3507. ....
  3508. 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...
  3509. [[oops]]
  3510. ==== Kernel oops
  3511. On oops, the shell still lives after.
  3512. However we:
  3513. * leave the normal control flow, and `oops after` never gets printed: an interrupt is serviced
  3514. * cannot `rmmod oops` afterwards
  3515. It is possible to make `oops` lead to panics always with:
  3516. ....
  3517. echo 1 > /proc/sys/kernel/panic_on_oops
  3518. insmod /oops.ko
  3519. ....
  3520. An oops stack trace looks like:
  3521. ....
  3522. BUG: unable to handle kernel NULL pointer dereference at 0000000000000000
  3523. IP: myinit+0x18/0x30 [oops]
  3524. PGD dccf067 P4D dccf067 PUD dcc1067 PMD 0
  3525. Oops: 0002 [#1] SMP NOPTI
  3526. Modules linked in: oops(O+)
  3527. CPU: 0 PID: 53 Comm: insmod Tainted: G O 4.16.0 #6
  3528. Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS rel-1.11.0-0-g63451fca13-prebuilt.qemu-project.org 04/01/2014
  3529. RIP: 0010:myinit+0x18/0x30 [oops]
  3530. RSP: 0018:ffffc900000d3cb0 EFLAGS: 00000282
  3531. RAX: 000000000000000b RBX: ffffffffc0000000 RCX: ffffffff81e3e3a8
  3532. RDX: 0000000000000001 RSI: 0000000000000086 RDI: ffffffffc0001033
  3533. RBP: ffffc900000d3e30 R08: 69796d2073706f6f R09: 000000000000013b
  3534. R10: ffffea0000373280 R11: ffffffff822d8b2d R12: 0000000000000000
  3535. R13: ffffffffc0002050 R14: ffffffffc0002000 R15: ffff88000dc934c8
  3536. FS: 00007ffff7ff66a0(0000) GS:ffff88000fc00000(0000) knlGS:0000000000000000
  3537. CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033
  3538. CR2: 0000000000000000 CR3: 000000000dcd2000 CR4: 00000000000006f0
  3539. Call Trace:
  3540. do_one_initcall+0x3e/0x170
  3541. do_init_module+0x5b/0x210
  3542. load_module+0x2035/0x29d0
  3543. ? SyS_finit_module+0xa8/0xb0
  3544. SyS_finit_module+0xa8/0xb0
  3545. do_syscall_64+0x6f/0x310
  3546. ? trace_hardirqs_off_thunk+0x1a/0x32
  3547. entry_SYSCALL_64_after_hwframe+0x42/0xb7
  3548. RIP: 0033:0x7ffff7b36206
  3549. RSP: 002b:00007fffffffeb78 EFLAGS: 00000206 ORIG_RAX: 0000000000000139
  3550. RAX: ffffffffffffffda RBX: 000000000000005c RCX: 00007ffff7b36206
  3551. RDX: 0000000000000000 RSI: 000000000069e010 RDI: 0000000000000003
  3552. RBP: 000000000069e010 R08: 00007ffff7ddd320 R09: 0000000000000000
  3553. R10: 00007ffff7ddd320 R11: 0000000000000206 R12: 0000000000000003
  3554. R13: 00007fffffffef4b R14: 0000000000000000 R15: 0000000000000000
  3555. Code: <c7> 04 25 00 00 00 00 00 00 00 00 e8 b2 33 09 c1 31 c0 c3 0f 1f 44
  3556. RIP: myinit+0x18/0x30 [oops] RSP: ffffc900000d3cb0
  3557. CR2: 0000000000000000
  3558. ---[ end trace 3cdb4e9d9842b503 ]---
  3559. ....
  3560. To find the line that oopsed, look at the `RIP` register:
  3561. ....
  3562. RIP: 0010:myinit+0x18/0x30 [oops]
  3563. ....
  3564. and then on GDB:
  3565. ....
  3566. ./run-gdb
  3567. ....
  3568. run
  3569. ....
  3570. info line *(myinit+0x18)
  3571. ....
  3572. which gives us the correct line:
  3573. ....
  3574. Line 7 of "/root/linux-kernel-module-cheat/out/kernel_modules/x86_64/kernel_modules/panic.c" starts at address 0xbf00001c <myinit+28> and ends at 0xbf00002c <myexit>.
  3575. ....
  3576. This-did not work on `arm` due to <<gdb-step-debug-kernel-module-arm>> so we need to either:
  3577. * <<gdb-module_init>>
  3578. * <<kernel-module-stack-trace-to-source-line>> post-mortem method
  3579. ==== dump_stack
  3580. 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:
  3581. ....
  3582. insmod /dump_stack.ko
  3583. ....
  3584. Source: link:kernel_modules/dump_stack.c[]
  3585. ==== WARN_ON
  3586. The `WARN_ON` macro basically just calls <<dump_stack,dump_stack>>.
  3587. One extra side effect is that we can make it also panic with:
  3588. ....
  3589. echo 1 > /proc/sys/kernel/panic_on_warn
  3590. insmod /warn_on.ko
  3591. ....
  3592. Source: link:kernel_modules/warn_on.c[]
  3593. Can also be activated with the `panic_on_warn` boot parameter.
  3594. === Pseudo filesystems
  3595. 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.
  3596. What each pseudo-file does for each related system call does is defined by its <<file-operations>>.
  3597. Bibliography:
  3598. * https://superuser.com/questions/1198292/what-is-a-pseudo-file-system-in-linux
  3599. * https://en.wikipedia.org/wiki/Synthetic_file_system
  3600. ==== debugfs
  3601. Debugfs is the simplest pseudo filesystem to play around with:
  3602. ....
  3603. /debugfs.sh
  3604. echo $?
  3605. ....
  3606. Outcome: the test passes:
  3607. ....
  3608. 0
  3609. ....
  3610. Sources:
  3611. * link:kernel_modules/debugfs.c[]
  3612. * link:rootfs_overlay/debugfs.sh[]
  3613. Debugfs is made specifically to help test kernel stuff. Just mount, set <<file-operations>>, and we are done.
  3614. For this reason, it is the filesystem that we use whenever possible in our tests.
  3615. `debugfs.sh` explicitly mounts a debugfs at a custom location, but the most common mount point is `/sys/kernel/debug`.
  3616. 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].
  3617. Debugfs support requires the kernel to be compiled with `CONFIG_DEBUG_FS=y`.
  3618. Only the more basic file operations can be implemented in debugfs, e.g. `mmap` never gets called:
  3619. * https://patchwork.kernel.org/patch/9252557/
  3620. * https://github.com/torvalds/linux/blob/v4.9/fs/debugfs/file.c#L212
  3621. Bibliography: https://github.com/chadversary/debugfs-tutorial
  3622. ==== procfs
  3623. Procfs is just another fops entry point:
  3624. ....
  3625. /procfs.sh
  3626. echo $?
  3627. ....
  3628. Outcome: the test passes:
  3629. ....
  3630. 0
  3631. ....
  3632. Procfs is a little less convenient than <<debugfs>>, but is more used in serious applications.
  3633. Procfs can run all system calls, including ones that debugfs can't, e.g. <<mmap>>.
  3634. Sources:
  3635. * link:kernel_modules/procfs.c[]
  3636. * link:rootfs_overlay/procfs.sh[]
  3637. Bibliography: https://stackoverflow.com/questions/8516021/proc-create-example-for-kernel-module/18924359#18924359
  3638. ===== /proc/version
  3639. Its data is shared with `uname()`, which is a POSIX C function and has a Linux syscall to back it up.
  3640. Where the data comes from and how to modify it:
  3641. * https://unix.stackexchange.com/questions/136959/where-does-uname-get-its-information-from/485962#485962
  3642. * https://stackoverflow.com/questions/23424174/how-to-customize-or-remove-extra-linux-kernel-version-details-shown-at-boot
  3643. In this repo, leaking host information, and to make builds more reproducible, we are setting:
  3644. - user and date to dummy values with `KBUILD_BUILD_USER` and `KBUILD_BUILD_TIMESTAMP`
  3645. - hostname to the kernel git commit with `KBUILD_BUILD_HOST` and `KBUILD_BUILD_VERSION`
  3646. A sample result is:
  3647. ....
  3648. Linux version 4.19.0-dirty (lkmc@84df9525b0c27f3ebc2ebb1864fa62a97fdedb7d) (gcc version 6.4.0 (Buildroot 2018.05-00002-gbc60382b8f)) #1 SMP Thu Jan 1 00:00:00 UTC 1970
  3649. ....
  3650. ==== sysfs
  3651. Sysfs is more restricted than <<procfs>>, as it does not take an arbitrary `file_operations`:
  3652. ....
  3653. /sysfs.sh
  3654. echo $?
  3655. ....
  3656. Outcome: the test passes:
  3657. ....
  3658. 0
  3659. ....
  3660. Sources:
  3661. * link:kernel_modules/sysfs.c[]
  3662. * link:rootfs_overlay/sysfs.sh[]
  3663. Vs procfs:
  3664. * https://unix.stackexchange.com/questions/4884/what-is-the-difference-between-procfs-and-sysfs
  3665. * https://stackoverflow.com/questions/37237835/how-to-attach-file-operations-to-sysfs-attribute-in-platform-driver
  3666. You basically can only do `open`, `close`, `read`, `write`, and `lseek` on sysfs files.
  3667. It is similar to a <<seq_file>> file operation, except that write is also implemented.
  3668. TODO: what are those `kobject` structs? Make a more complex example that shows what they can do.
  3669. Bibliography:
  3670. * https://github.com/t3rm1n4l/kern-dev-tutorial/blob/1f036ef40fc4378f5c8d2842e55bcea7c6f8894a/05-sysfs/sysfs.c
  3671. * https://www.kernel.org/doc/Documentation/kobject.txt
  3672. * https://www.quora.com/What-are-kernel-objects-Kobj
  3673. * http://www.makelinux.net/ldd3/chp-14-sect-1
  3674. * https://www.win.tue.nl/~aeb/linux/lk/lk-13.html
  3675. ==== Character devices
  3676. Character devices can have arbitrary <<file-operations>> associated to them:
  3677. ....
  3678. /character_device.sh
  3679. echo $?
  3680. ....
  3681. Outcome: the test passes:
  3682. ....
  3683. 0
  3684. ....
  3685. Sources:
  3686. * link:rootfs_overlay/character_device.sh[]
  3687. * link:rootfs_overlay/mknoddev.sh[]
  3688. * link:kernel_modules/character_device.c[]
  3689. Unlike <<procfs>> entires, character device files are created with userland `mknod` or `mknodat` syscalls:
  3690. ....
  3691. mknod </dev/path_to_dev> c <major> <minor>
  3692. ....
  3693. Intuitively, for physical devices like keyboards, the major number maps to which driver, and the minor number maps to which device it is.
  3694. A single driver can drive multiple compatible devices.
  3695. The major and minor numbers can be observed with:
  3696. ....
  3697. ls -l /dev/urandom
  3698. ....
  3699. Output:
  3700. ....
  3701. crw-rw-rw- 1 root root 1, 9 Jun 29 05:45 /dev/urandom
  3702. ....
  3703. which means:
  3704. * `c` (first letter): this is a character device. Would be `b` for a block device.
  3705. * `1, 9`: the major number is `1`, and the minor `9`
  3706. To avoid device number conflicts when registering the driver we:
  3707. * ask the kernel to allocate a free major number for us with: `register_chrdev(0`
  3708. * find ouf which number was assigned by grepping `/proc/devices` for the kernel module name
  3709. Bibliography: https://unix.stackexchange.com/questions/37829/understanding-character-device-or-character-special-files/371758#371758
  3710. ===== Automatically create character device file on insmod
  3711. And also destroy it on `rmmod`:
  3712. ....
  3713. /character_device_create.sh
  3714. echo $?
  3715. ....
  3716. Outcome: the test passes:
  3717. ....
  3718. 0
  3719. ....
  3720. Sources:
  3721. * link:kernel_modules/character_device_create.c[]
  3722. * link:rootfs_overlay/character_device_create.sh[]
  3723. Bibliography: https://stackoverflow.com/questions/5970595/how-to-create-a-device-node-from-the-init-module-code-of-a-linux-kernel-module/45531867#45531867
  3724. === Pseudo files
  3725. ==== File operations
  3726. 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>>.
  3727. This example illustrates the most basic system calls: `open`, `read`, `write`, `close` and `lseek`:
  3728. ....
  3729. /fops.sh
  3730. echo $?
  3731. ....
  3732. Outcome: the test passes:
  3733. ....
  3734. 0
  3735. ....
  3736. Sources:
  3737. * link:kernel_modules/fops.c[]
  3738. * link:rootfs_overlay/fops.sh[]
  3739. Then give this a try:
  3740. ....
  3741. sh -x /fops.sh
  3742. ....
  3743. We have put printks on each fop, so this allows you to see which system calls are being made for each command.
  3744. No, there no official documentation: http://stackoverflow.com/questions/15213932/what-are-the-struct-file-operations-arguments
  3745. ==== seq_file
  3746. Writing trivial read <<file-operations>> is repetitive and error prone. The `seq_file` API makes the process much easier for those trivial cases:
  3747. ....
  3748. /seq_file.sh
  3749. echo $?
  3750. ....
  3751. Outcome: the test passes:
  3752. ....
  3753. 0
  3754. ....
  3755. Sources:
  3756. * link:kernel_modules/seq_file.c[]
  3757. * link:rootfs_overlay/seq_file.sh[]
  3758. In this example we create a debugfs file that behaves just like a file that contains:
  3759. ....
  3760. 0
  3761. 1
  3762. 2
  3763. ....
  3764. However, we only store a single integer in memory and calculate the file on the fly in an iterator fashion.
  3765. `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
  3766. Bibliography:
  3767. * link:https://github.com/torvalds/linux/blob/v4.17/Documentation/filesystems/seq_file.txt[Documentation/filesystems/seq_file.txt]
  3768. * https://stackoverflow.com/questions/25399112/how-to-use-a-seq-file-in-linux-modules
  3769. ===== seq_file single_open
  3770. If you have the entire read output upfront, `single_open` is an even more convenient version of <<seq_file>>:
  3771. ....
  3772. /seq_file.sh
  3773. echo $?
  3774. ....
  3775. Outcome: the test passes:
  3776. ....
  3777. 0
  3778. ....
  3779. Sources:
  3780. * link:kernel_modules/seq_file_single_open.c[]
  3781. * link:rootfs_overlay/seq_file_single_open.sh[]
  3782. This example produces a debugfs file that behaves like a file that contains:
  3783. ....
  3784. ab
  3785. cd
  3786. ....
  3787. ==== poll
  3788. The poll system call allows an user process to do a non-busy wait on a kernel event:
  3789. ....
  3790. /poll.sh
  3791. ....
  3792. Outcome: `jiffies` gets printed to stdout every second from userland.
  3793. Sources:
  3794. * link:kernel_modules/poll.c[]
  3795. * link:kernel_modules/poll.c[]
  3796. * link:rootfs_overlay/poll.sh[]
  3797. Typically, we are waiting for some hardware to make some piece of data available available to the kernel.
  3798. The hardware notifies the kernel that the data is ready with an interrupt.
  3799. To simplify this example, we just fake the hardware interrupts with a <<kthread>> that sleeps for a second in an infinite loop.
  3800. Bibliography: https://stackoverflow.com/questions/30035776/how-to-add-poll-function-to-the-kernel-module-code/44645336#44645336
  3801. ==== ioctl
  3802. The `ioctl` system call is the best way to pass an arbitrary number of parameters to the kernel in a single go:
  3803. ....
  3804. /ioctl.sh
  3805. echo $?
  3806. ....
  3807. Outcome: the test passes:
  3808. ....
  3809. 0
  3810. ....
  3811. Sources:
  3812. * link:kernel_modules/ioctl.c[]
  3813. * link:kernel_modules/ioctl.h[]
  3814. * link:userland/ioctl.c[]
  3815. * link:rootfs_overlay/ioctl.sh[]
  3816. `ioctl` is one of the most important methods of communication with real device drivers, which often take several fields as input.
  3817. `ioctl` takes as input:
  3818. * an integer `request` : it usually identifies what type of operation we want to do on this call
  3819. * an untyped pointer to memory: can be anything, but is typically a pointer to a `struct`
  3820. +
  3821. The type of the `struct` often depends on the `request` input
  3822. +
  3823. This `struct` is defined on a uapi-style C header that is used both to compile the kernel module and the userland executable.
  3824. +
  3825. The fields of this `struct` can be thought of as arbitrary input parameters.
  3826. And the output is:
  3827. * an integer return value. `man ioctl` documents:
  3828. +
  3829. ____
  3830. 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.
  3831. ____
  3832. * the input pointer data may be overwritten to contain arbitrary output
  3833. Bibliography:
  3834. * https://stackoverflow.com/questions/2264384/how-do-i-use-ioctl-to-manipulate-my-kernel-module/44613896#44613896
  3835. * https://askubuntu.com/questions/54239/problem-with-ioctl-in-a-simple-kernel-module/926675#926675
  3836. ==== mmap
  3837. The `mmap` system call allows us to share memory between user and kernel space without copying:
  3838. ....
  3839. /mmap.sh
  3840. echo $?
  3841. ....
  3842. Outcome: the test passes:
  3843. ....
  3844. 0
  3845. ....
  3846. Sources:
  3847. * link:kernel_modules/mmap.c[]
  3848. * link:userland/mmap.c[]
  3849. * link:rootfs_overlay/mmap.sh[]
  3850. 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.
  3851. `mmap`, like most more complex <<file-operations>>, does not work with <<debugfs>> as of 4.9, so we use a <<procfs>> file for it.
  3852. Example adapted from: https://coherentmusings.wordpress.com/2014/06/10/implementing-mmap-for-transferring-data-from-user-space-to-kernel-space/
  3853. Bibliography:
  3854. * https://stackoverflow.com/questions/10760479/mmap-kernel-buffer-to-user-space/10770582#10770582
  3855. * https://stackoverflow.com/questions/1623008/allocating-memory-for-user-space-from-kernel-thread
  3856. * https://stackoverflow.com/questions/6967933/mmap-mapping-in-user-space-a-kernel-buffer-allocated-with-kmalloc
  3857. * https://github.com/jeremytrimble/ezdma
  3858. * https://github.com/simonjhall/dma
  3859. * https://github.com/ikwzm/udmabuf
  3860. ==== Anonymous inode
  3861. Anonymous inodes allow getting multiple file descriptors from a single filesystem entry, which reduces namespace pollution compared to creating multiple device files:
  3862. ....
  3863. /anonymous_inode.sh
  3864. echo $?
  3865. ....
  3866. Outcome: the test passes:
  3867. ....
  3868. 0
  3869. ....
  3870. Sources:
  3871. * link:kernel_modules/anonymous_inode.c[]
  3872. * link:kernel_modules/anonymous_inode.h[]
  3873. * link:userland/anonymous_inode.c[]
  3874. * link:rootfs_overlay/anonymous_inode.sh[]
  3875. This example gets an anonymous inode via <<ioctl>> from a debugfs entry by using `anon_inode_getfd`.
  3876. Reads to that inode return the sequence: `1`, `10`, `100`, ... `10000000`, `1`, `100`, ...
  3877. Bibliography: https://stackoverflow.com/questions/4508998/what-is-an-anonymous-inode-in-linux/44388030#44388030
  3878. ==== netlink sockets
  3879. Netlink sockets offer a socket API for kernel / userland communication:
  3880. ....
  3881. /netlink.sh
  3882. echo $?
  3883. ....
  3884. Outcome: the test passes:
  3885. ....
  3886. 0
  3887. ....
  3888. Sources:
  3889. * link:kernel_modules/netlink.c[]
  3890. * link:kernel_modules/netlink.h[]
  3891. * link:userland/netlink.c[]
  3892. * link:rootfs_overlay/netlink.sh[]
  3893. Launch multiple user requests in parallel to stress our socket:
  3894. ....
  3895. insmod /netlink.ko sleep=1
  3896. for i in `seq 16`; do /netlink.out & done
  3897. ....
  3898. 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
  3899. Bibliography:
  3900. * https://stackoverflow.com/questions/3299386/how-to-use-netlink-socket-to-communicate-with-a-kernel-module
  3901. * https://en.wikipedia.org/wiki/Netlink
  3902. === kthread
  3903. Kernel threads are managed exactly like userland threads; they also have a backing `task_struct`, and are scheduled with the same mechanism:
  3904. ....
  3905. insmod /kthread.ko
  3906. ....
  3907. Source: link:kernel_modules/kthread.c[]
  3908. Outcome: dmesg counts from `0` to `9` once every second infinitely many times:
  3909. ....
  3910. 0
  3911. 1
  3912. 2
  3913. ...
  3914. 8
  3915. 9
  3916. 0
  3917. 1
  3918. 2
  3919. ...
  3920. ....
  3921. The count stops when we `rmmod`:
  3922. ....
  3923. rmmod kthread
  3924. ....
  3925. The sleep is done with `usleep_range`, see: <<sleep>>.
  3926. Bibliography:
  3927. * http://stackoverflow.com/questions/10177641/proper-way-of-handling-threads-in-kernel
  3928. * http://stackoverflow.com/questions/4084708/how-to-wait-for-a-linux-kernel-thread-kthreadto-exit
  3929. ==== kthreads
  3930. Let's launch two threads and see if they actually run in parallel:
  3931. ....
  3932. insmod /kthreads.ko
  3933. ....
  3934. Source: link:kernel_modules/kthreads.c[]
  3935. Outcome: two threads count to dmesg from `0` to `9` in parallel.
  3936. Each line has output of form:
  3937. ....
  3938. <thread_id> <count>
  3939. ....
  3940. Possible very likely outcome:
  3941. ....
  3942. 1 0
  3943. 2 0
  3944. 1 1
  3945. 2 1
  3946. 1 2
  3947. 2 2
  3948. 1 3
  3949. 2 3
  3950. ....
  3951. The threads almost always interleaved nicely, thus confirming that they are actually running in parallel.
  3952. ==== sleep
  3953. Count to dmesg every one second from `0` up to `n - 1`:
  3954. ....
  3955. insmod /sleep.ko n=5
  3956. ....
  3957. Source: link:kernel_modules/sleep.c[]
  3958. 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.
  3959. Bibliography:
  3960. * https://stackoverflow.com/questions/15994603/how-to-sleep-in-the-linux-kernel/44153288#44153288
  3961. * https://github.com/torvalds/linux/blob/v4.17/Documentation/timers/timers-howto.txt
  3962. ==== Workqueues
  3963. A more convenient front-end for <<kthread>>:
  3964. ....
  3965. insmod /workqueue_cheat.ko
  3966. ....
  3967. Outcome: count from `0` to `9` infinitely many times
  3968. Stop counting:
  3969. ....
  3970. rmmod workqueue_cheat
  3971. ....
  3972. Source: link:kernel_modules/workqueue_cheat.c[]
  3973. The workqueue thread is killed after the worker function returns.
  3974. 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
  3975. Bibliography: https://github.com/torvalds/linux/blob/v4.17/Documentation/core-api/workqueue.rst
  3976. ===== Workqueue from workqueue
  3977. Count from `0` to `9` every second infinitely many times by scheduling a new work item from a work item:
  3978. ....
  3979. insmod /work_from_work.ko
  3980. ....
  3981. Stop:
  3982. ....
  3983. rmmod work_from_work
  3984. ....
  3985. 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.
  3986. Source: link:kernel_modules/work_from_work.c[]
  3987. ==== schedule
  3988. Let's block the entire kernel! Yay:
  3989. .....
  3990. ./run --eval-after 'dmesg -n 1;insmod /schedule.ko schedule=0'
  3991. .....
  3992. Outcome: the system hangs, the only way out is to kill the VM.
  3993. Source: link:kernel_modules/schedule.c[]
  3994. kthreads only allow interrupting if you call `schedule()`, and the `schedule=0` <<kernel-module-parameters,kernel module parameter>> turns it off.
  3995. Sleep functions like `usleep_range` also end up calling schedule.
  3996. If we allow `schedule()` to be called, then the system becomes responsive:
  3997. .....
  3998. ./run --eval-after 'dmesg -n 1;insmod /schedule.ko schedule=1'
  3999. .....
  4000. and we can observe the counting with:
  4001. ....
  4002. dmesg -w
  4003. ....
  4004. The system also responds if we <<number-of-cores,add another core>>:
  4005. ....
  4006. ./run --cpus 2 --eval-after 'dmesg -n 1;insmod /schedule.ko schedule=0'
  4007. ....
  4008. ==== Wait queues
  4009. Wait queues are a way to make a thread sleep until an event happens on the queue:
  4010. ....
  4011. insmod /wait_queue.c
  4012. ....
  4013. Dmesg output:
  4014. ....
  4015. 0 0
  4016. 1 0
  4017. 2 0
  4018. # Wait one second.
  4019. 0 1
  4020. 1 1
  4021. 2 1
  4022. # Wait one second.
  4023. 0 2
  4024. 1 2
  4025. 2 2
  4026. ...
  4027. ....
  4028. Stop the count:
  4029. ....
  4030. rmmod wait_queue
  4031. ....
  4032. Source: link:kernel_modules/wait_queue.c[]
  4033. This example launches three threads:
  4034. * one thread generates events every with link:https://github.com/torvalds/linux/blob/v4.17/include/linux/wait.h#L195[`wake_up`]
  4035. * 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.
  4036. +
  4037. The `wait_event` macro works a bit like:
  4038. +
  4039. ....
  4040. while (!cond)
  4041. sleep_until_event
  4042. ....
  4043. === Timers
  4044. Count from `0` to `9` infinitely many times in 1 second intervals using timers:
  4045. ....
  4046. insmod /timer.ko
  4047. ....
  4048. Stop counting:
  4049. ....
  4050. rmmod timer
  4051. ....
  4052. Source: link:kernel_modules/timer.c[]
  4053. Timers are callbacks that run when an interrupt happens, from the interrupt context itself.
  4054. Therefore they produce more accurate timing than thread scheduling, which is more complex, but you can't do too much work inside of them.
  4055. Bibliography:
  4056. * http://stackoverflow.com/questions/10812858/timers-in-linux-device-drivers
  4057. * https://gist.github.com/yagihiro/310149
  4058. === IRQ
  4059. ==== irq.ko
  4060. Brute force monitor every shared interrupt that will accept us:
  4061. ....
  4062. ./run --eval-after 'insmod /irq.ko' --graphic
  4063. ....
  4064. Source: link:kernel_modules/irq.c[].
  4065. Now try the following:
  4066. * press a keyboard key and then release it after a few seconds
  4067. * press a mouse key, and release it after a few seconds
  4068. * move the mouse around
  4069. Outcome: dmesg shows which IRQ was fired for each action through messages of type:
  4070. ....
  4071. handler irq = 1 dev = 250
  4072. ....
  4073. `dev` is the character device for the module and never changes, as can be confirmed by:
  4074. ....
  4075. grep lkmc_irq /proc/devices
  4076. ....
  4077. The IRQs that we observe are:
  4078. * `1` for keyboard press and release.
  4079. +
  4080. If you hold the key down for a while, it starts firing at a constant rate. So this happens at the hardware level!
  4081. * `12` mouse actions
  4082. This only works if for IRQs for which the other handlers are registered as `IRQF_SHARED`.
  4083. We can see which ones are those, either via dmesg messages of type:
  4084. ....
  4085. genirq: Flags mismatch irq 0. 00000080 (myirqhandler0) vs. 00015a00 (timer)
  4086. request_irq irq = 0 ret = -16
  4087. request_irq irq = 1 ret = 0
  4088. ....
  4089. which indicate that `0` is not, but `1` is, or with:
  4090. ....
  4091. cat /proc/interrupts
  4092. ....
  4093. which shows:
  4094. ....
  4095. 0: 31 IO-APIC 2-edge timer
  4096. 1: 9 IO-APIC 1-edge i8042, myirqhandler0
  4097. ....
  4098. so only `1` has `myirqhandler0` attached but not `0`.
  4099. The <<qemu-monitor>> also has some interrupt statistics for x86_64:
  4100. ....
  4101. ./qemu-monitor info irq
  4102. ....
  4103. TODO: properly understand how each IRQ maps to what number.
  4104. ==== dummy-irq
  4105. The Linux kernel v4.16 mainline also has a `dummy-irq` module at `drivers/misc/dummy-irq.c` for monitoring a single IRQ.
  4106. We build it by default with:
  4107. ....
  4108. CONFIG_DUMMY_IRQ=m
  4109. ....
  4110. And then you can do
  4111. ....
  4112. ./run --graphic
  4113. ....
  4114. and in guest:
  4115. ....
  4116. modprobe dummy-irq irq=1
  4117. ....
  4118. Outcome: when you click a key on the keyboard, dmesg shows:
  4119. ....
  4120. dummy-irq: interrupt occurred on IRQ 1
  4121. ....
  4122. However, this module is intended to fire only once as can be seen from its source:
  4123. ....
  4124. static int count = 0;
  4125. if (count == 0) {
  4126. printk(KERN_INFO "dummy-irq: interrupt occurred on IRQ %d\n",
  4127. irq);
  4128. count++;
  4129. }
  4130. ....
  4131. and furthermore interrupt `1` and `12` happen immediately TODO why, were they somehow pending?
  4132. So so see something interesting, you need to monitor an interrupt that is more rare than the keyboard, e.g. <<platform_device>>.
  4133. ==== /proc/interrupts
  4134. In the guest with <<qemu-graphic-mode>>:
  4135. ....
  4136. watch -n 1 cat /proc/interrupts
  4137. ....
  4138. Then see how clicking the mouse and keyboard affect the interrupt counts.
  4139. This confirms that:
  4140. * 1: keyboard
  4141. * 12: mouse click and drags
  4142. The module also shows which handlers are registered for each IRQ, as we have observed at <<irq-ko>>
  4143. When in text mode, we can also observe interrupt line 4 with handler `ttyS0` increase continuously as IO goes through the UART.
  4144. === Kernel utility functions
  4145. https://github.com/torvalds/linux/blob/v4.17/Documentation/core-api/kernel-api.rst
  4146. ==== kstrto
  4147. Convert a string to an integer:
  4148. ....
  4149. /kstrto.sh
  4150. echo $?
  4151. ....
  4152. Outcome: the test passes:
  4153. ....
  4154. 0
  4155. ....
  4156. Sources:
  4157. * link:kernel_modules/kstrto.c[]
  4158. * link:rootfs_overlay/kstrto.sh[]
  4159. Bibliography: https://stackoverflow.com/questions/6139493/how-convert-char-to-int-in-linux-kernel/49811658#49811658
  4160. ==== virt_to_phys
  4161. Convert a virtual address to physical:
  4162. ....
  4163. insmod /virt_to_phys.ko
  4164. cat /sys/kernel/debug/lkmc_virt_to_phys
  4165. ....
  4166. Source: link:kernel_modules/virt_to_phys.c[]
  4167. Sample output:
  4168. ....
  4169. *kmalloc_ptr = 0x12345678
  4170. kmalloc_ptr = ffff88000e169ae8
  4171. virt_to_phys(kmalloc_ptr) = 0xe169ae8
  4172. static_var = 0x12345678
  4173. &static_var = ffffffffc0002308
  4174. virt_to_phys(&static_var) = 0x40002308
  4175. ....
  4176. We can confirm that the `kmalloc_ptr` translation worked with:
  4177. ....
  4178. ./qemu-monitor 'xp 0xe169ae8'
  4179. ....
  4180. which reads four bytes from a given physical address, and gives the expected:
  4181. ....
  4182. 000000000e169ae8: 0x12345678
  4183. ....
  4184. TODO it only works for kmalloc however, for the static variable:
  4185. ....
  4186. ./qemu-monitor 'xp 0x40002308'
  4187. ....
  4188. it gave a wrong value of `00000000`.
  4189. Bibliography:
  4190. * https://stackoverflow.com/questions/5748492/is-there-any-api-for-determining-the-physical-address-from-virtual-address-in-li/45128487#45128487
  4191. * https://stackoverflow.com/questions/39134990/mmap-of-dev-mem-fails-with-invalid-argument-for-virt-to-phys-address-but-addre/45127582#45127582
  4192. * https://stackoverflow.com/questions/43325205/can-we-use-virt-to-phys-for-user-space-memory-in-kernel-module
  4193. ===== Userland physical address experiments
  4194. Only tested in x86_64.
  4195. The Linux kernel exposes physical addresses to userland through:
  4196. * `/proc/<pid>/maps`
  4197. * `/proc/<pid>/pagemap`
  4198. * `/dev/mem`
  4199. In this section we will play with them.
  4200. First get a virtual address to play with:
  4201. ....
  4202. /virt_to_phys_test.out &
  4203. ....
  4204. Source: link:userland/virt_to_phys_test.c[]
  4205. Sample output:
  4206. ....
  4207. vaddr 0x600800
  4208. pid 110
  4209. ....
  4210. The program:
  4211. * allocates a `volatile` variable and sets is value to `0x12345678`
  4212. * prints the virtual address of the variable, and the program PID
  4213. * runs a while loop until until the value of the variable gets mysteriously changed somehow, e.g. by nasty tinkerers like us
  4214. Then, translate the virtual address to physical using `/proc/<pid>/maps` and `/proc/<pid>/pagemap`:
  4215. ....
  4216. /virt_to_phys_user.out 110 0x600800
  4217. ....
  4218. Sample output physical address:
  4219. ....
  4220. 0x7c7b800
  4221. ....
  4222. Source: link:userland/virt_to_phys_user.c[]
  4223. Now we can verify that `virt_to_phys_user.out` gave the correct physical address in the following ways:
  4224. * <<qemu-xp>>
  4225. * <<dev-mem>>
  4226. Bibliography:
  4227. * https://stackoverflow.com/questions/17021214/decode-proc-pid-pagemap-entry/45126141#45126141
  4228. * https://stackoverflow.com/questions/6284810/proc-pid-pagemaps-and-proc-pid-maps-linux/45500208#45500208
  4229. ====== QEMU xp
  4230. The `xp` <<qemu-monitor>> command reads memory at a given physical address.
  4231. First launch `virt_to_phys_user.out` as described at <<userland-physical-address-experiments>>.
  4232. On a second terminal, use QEMU to read the physical address:
  4233. ....
  4234. ./qemu-monitor 'xp 0x7c7b800'
  4235. ....
  4236. Output:
  4237. ....
  4238. 0000000007c7b800: 0x12345678
  4239. ....
  4240. Yes!!! We read the correct value from the physical address.
  4241. We could not find however to write to memory from the QEMU monitor, boring.
  4242. ====== /dev/mem
  4243. `/dev/mem` exposes access to physical addresses, and we use it through the convenient `devmem` BusyBox utility.
  4244. First launch `virt_to_phys_user.out` as described at <<userland-physical-address-experiments>>.
  4245. Next, read from the physical address:
  4246. ....
  4247. devmem 0x7c7b800
  4248. ....
  4249. Possible output:
  4250. ....
  4251. Memory mapped at address 0x7ff7dbe01000.
  4252. Value at address 0X7C7B800 (0x7ff7dbe01800): 0x12345678
  4253. ....
  4254. which shows that the physical memory contains the expected value `0x12345678`.
  4255. `0x7ff7dbe01000` is a new virtual address that `devmem` maps to the physical address to be able to read from it.
  4256. Modify the physical memory:
  4257. ....
  4258. devmem 0x7c7b800 w 0x9abcdef0
  4259. ....
  4260. After one second, we see on the screen:
  4261. ....
  4262. i 9abcdef0
  4263. [1]+ Done /virt_to_phys_test.out
  4264. ....
  4265. so the value changed, and the `while` loop exited!
  4266. This example requires:
  4267. * `CONFIG_STRICT_DEVMEM=n`, otherwise `devmem` fails with:
  4268. +
  4269. ....
  4270. devmem: mmap: Operation not permitted
  4271. ....
  4272. * `nopat` kernel parameter
  4273. which we set by default.
  4274. Bibliography: https://stackoverflow.com/questions/11891979/how-to-access-mmaped-dev-mem-without-crashing-the-linux-kernel
  4275. ====== pagemap_dump.out
  4276. Dump the physical address of all pages mapped to a given process using `/proc/<pid>/maps` and `/proc/<pid>/pagemap`.
  4277. First launch `virt_to_phys_user.out` as described at <<userland-physical-address-experiments>>. Suppose that the output was:
  4278. ....
  4279. # /virt_to_phys_test.out &
  4280. vaddr 0x601048
  4281. pid 63
  4282. # /virt_to_phys_user.out 63 0x601048
  4283. 0x1a61048
  4284. ....
  4285. Now obtain the page map for the process:
  4286. ....
  4287. /pagemap_dump.out 63
  4288. ....
  4289. Sample output excerpt:
  4290. ....
  4291. vaddr pfn soft-dirty file/shared swapped present library
  4292. 400000 1ede 0 1 0 1 /virt_to_phys_test.out
  4293. 600000 1a6f 0 0 0 1 /virt_to_phys_test.out
  4294. 601000 1a61 0 0 0 1 /virt_to_phys_test.out
  4295. 602000 2208 0 0 0 1 [heap]
  4296. 603000 220b 0 0 0 1 [heap]
  4297. 7ffff78ec000 1fd4 0 1 0 1 /lib/libuClibc-1.0.30.so
  4298. ....
  4299. Source: link:userland/pagemap_dump.c[]
  4300. Adapted from: https://github.com/dwks/pagemap/blob/8a25747bc79d6080c8b94eac80807a4dceeda57a/pagemap2.c
  4301. Meaning of the flags:
  4302. * `vaddr`: first virtual address of a page the belongs to the process. Notably:
  4303. +
  4304. ....
  4305. ./run-toolchain readelf -- -l "$(./getvar userland_build_dir)/virt_to_phys_test.out"
  4306. ....
  4307. +
  4308. contains:
  4309. +
  4310. ....
  4311. Type Offset VirtAddr PhysAddr
  4312. FileSiz MemSiz Flags Align
  4313. ...
  4314. LOAD 0x0000000000000000 0x0000000000400000 0x0000000000400000
  4315. 0x000000000000075c 0x000000000000075c R E 0x200000
  4316. LOAD 0x0000000000000e98 0x0000000000600e98 0x0000000000600e98
  4317. 0x00000000000001b4 0x0000000000000218 RW 0x200000
  4318. Section to Segment mapping:
  4319. Segment Sections...
  4320. ...
  4321. 02 .interp .hash .dynsym .dynstr .rela.plt .init .plt .text .fini .rodata .eh_frame_hdr .eh_frame
  4322. 03 .ctors .dtors .jcr .dynamic .got.plt .data .bss
  4323. ....
  4324. +
  4325. from which we deduce that:
  4326. +
  4327. ** `400000` is the text segment
  4328. ** `600000` is the data segment
  4329. * `pfn`: add three zeroes to it, and you have the physical address.
  4330. +
  4331. Three zeroes is 12 bits which is 4kB, which is the size of a page.
  4332. +
  4333. For example, the virtual address `0x601000` has `pfn` of `0x1a61`, which means that its physical address is `0x1a61000`
  4334. +
  4335. This is consistent with what `virt_to_phys_user.out` told us: the virtual address `0x601048` has physical address `0x1a61048`.
  4336. +
  4337. `048` corresponds to the three last zeroes, and is the offset within the page.
  4338. +
  4339. 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.
  4340. * `soft-dirty`: TODO
  4341. * `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`.
  4342. * `swapped`: TODO swapped to disk?
  4343. * `present`: TODO vs swapped?
  4344. * `library`: which executable owns that page
  4345. This program works in two steps:
  4346. * parse the human readable lines lines from `/proc/<pid>/maps`. This files contains lines of form:
  4347. +
  4348. ....
  4349. 7ffff7b6d000-7ffff7bdd000 r-xp 00000000 fe:00 658 /lib/libuClibc-1.0.22.so
  4350. ....
  4351. +
  4352. which tells us that:
  4353. +
  4354. ** `7f8af99f8000-7f8af99ff000` is a virtual address range that belong to the process, possibly containing multiple pages.
  4355. ** `/lib/libuClibc-1.0.22.so` is the name of the library that owns that memory
  4356. * loop over each page of each address range, and ask `/proc/<pid>/pagemap` for more information about that page, including the physical address
  4357. === Linux kernel tracing
  4358. Good overviews:
  4359. * 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
  4360. * https://jvns.ca/blog/2017/07/05/linux-tracing-systems/
  4361. I hope to have examples of all methods some day, since I'm obsessed with visibility.
  4362. ==== CONFIG_PROC_EVENTS
  4363. Logs proc events such as process creation to a link:kernel_modules/netlink.c[netlink socket].
  4364. We then have a userland program that listens to the events and prints them out:
  4365. ....
  4366. # /proc_events.out &
  4367. # set mcast listen ok
  4368. # sleep 2 & sleep 1
  4369. fork: parent tid=48 pid=48 -> child tid=79 pid=79
  4370. fork: parent tid=48 pid=48 -> child tid=80 pid=80
  4371. exec: tid=80 pid=80
  4372. exec: tid=79 pid=79
  4373. # exit: tid=80 pid=80 exit_code=0
  4374. exit: tid=79 pid=79 exit_code=0
  4375. echo a
  4376. a
  4377. #
  4378. ....
  4379. Source: link:userland/proc_events.c[]
  4380. TODO: why `exit: tid=79` shows after `exit: tid=80`?
  4381. Note how `echo a` is a Bash built-in, and therefore does not spawn a new process.
  4382. TODO: why does this produce no output?
  4383. ....
  4384. /proc_events.out >f &
  4385. ....
  4386. * https://stackoverflow.com/questions/6075013/detect-launching-of-programs-on-linux-platform/8255487#8255487
  4387. * https://serverfault.com/questions/199654/does-anyone-know-a-simple-way-to-monitor-root-process-spawn
  4388. * https://unix.stackexchange.com/questions/260162/how-to-track-newly-created-processes
  4389. 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.
  4390. * https://unix.stackexchange.com/questions/163681/print-pids-and-names-of-processes-as-they-are-created/163689 requests process name
  4391. * https://serverfault.com/questions/199654/does-anyone-know-a-simple-way-to-monitor-root-process-spawn requests UID
  4392. ===== CONFIG_PROC_EVENTS aarch64
  4393. 0111ca406bdfa6fd65a2605d353583b4c4051781 was failing with:
  4394. ....
  4395. >>> kernel_modules 1.0 Building
  4396. /usr/bin/make -j8 -C '/linux-kernel-module-cheat//out/aarch64/buildroot/build/kernel_modules-1.0/user' BR2_PACKAGE_OPENBLAS="" CC="/linux-kernel-module-cheat//out/aarch64/buildroot/host/bin/aarch64-buildroot-linux-uclibc-gcc" LD="/linux-kernel-module-cheat//out/aarch64/buildroot/host/bin/aarch64-buildroot-linux-uclibc-ld"
  4397. /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'
  4398. In file included from /linux-kernel-module-cheat//out/aarch64/buildroot/host/aarch64-buildroot-linux-uclibc/sysroot/usr/include/signal.h:329:0,
  4399. from proc_events.c:12:
  4400. /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
  4401. mcontext_t uc_mcontext;
  4402. ^~~~~~~~~~~
  4403. ....
  4404. so we commented it out.
  4405. Related threads:
  4406. * https://mailman.uclibc-ng.org/pipermail/devel/2018-January/001624.html
  4407. * https://github.com/DynamoRIO/dynamorio/issues/2356
  4408. 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:
  4409. ....
  4410. ../utils/ldd.c: In function 'elf_find_dynamic':
  4411. ../utils/ldd.c:238:12: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
  4412. return (void *)byteswap_to_host(dynp->d_un.d_val);
  4413. ^
  4414. /tmp/user/20321/cciGScKB.o: In function `process_line_callback':
  4415. msgmerge.c:(.text+0x22): undefined reference to `escape'
  4416. /tmp/user/20321/cciGScKB.o: In function `process':
  4417. msgmerge.c:(.text+0xf6): undefined reference to `poparser_init'
  4418. msgmerge.c:(.text+0x11e): undefined reference to `poparser_feed_line'
  4419. msgmerge.c:(.text+0x128): undefined reference to `poparser_finish'
  4420. collect2: error: ld returned 1 exit status
  4421. Makefile.in:120: recipe for target '../utils/msgmerge.host' failed
  4422. make[2]: *** [../utils/msgmerge.host] Error 1
  4423. make[2]: *** Waiting for unfinished jobs....
  4424. /tmp/user/20321/ccF8V8jF.o: In function `process':
  4425. msgfmt.c:(.text+0xbf3): undefined reference to `poparser_init'
  4426. msgfmt.c:(.text+0xc1f): undefined reference to `poparser_feed_line'
  4427. msgfmt.c:(.text+0xc2b): undefined reference to `poparser_finish'
  4428. collect2: error: ld returned 1 exit status
  4429. Makefile.in:120: recipe for target '../utils/msgfmt.host' failed
  4430. make[2]: *** [../utils/msgfmt.host] Error 1
  4431. package/pkg-generic.mk:227: recipe for target '/data/git/linux-kernel-module-cheat/out/aarch64/buildroot/build/uclibc-custom/.stamp_built' failed
  4432. make[1]: *** [/data/git/linux-kernel-module-cheat/out/aarch64/buildroot/build/uclibc-custom/.stamp_built] Error 2
  4433. Makefile:79: recipe for target '_all' failed
  4434. make: *** [_all] Error 2
  4435. ....
  4436. 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.
  4437. ==== ftrace
  4438. Trace a single function:
  4439. ....
  4440. cd /sys/kernel/debug/tracing/
  4441. # Stop tracing.
  4442. echo 0 > tracing_on
  4443. # Clear previous trace.
  4444. echo > trace
  4445. # List the available tracers, and pick one.
  4446. cat available_tracers
  4447. echo function > current_tracer
  4448. # List all functions that can be traced
  4449. # cat available_filter_functions
  4450. # Choose one.
  4451. echo __kmalloc > set_ftrace_filter
  4452. # Confirm that only __kmalloc is enabled.
  4453. cat enabled_functions
  4454. echo 1 > tracing_on
  4455. # Latest events.
  4456. head trace
  4457. # Observe trace continuously, and drain seen events out.
  4458. cat trace_pipe &
  4459. ....
  4460. Sample output:
  4461. ....
  4462. # tracer: function
  4463. #
  4464. # entries-in-buffer/entries-written: 97/97 #P:1
  4465. #
  4466. # _-----=> irqs-off
  4467. # / _----=> need-resched
  4468. # | / _---=> hardirq/softirq
  4469. # || / _--=> preempt-depth
  4470. # ||| / delay
  4471. # TASK-PID CPU# |||| TIMESTAMP FUNCTION
  4472. # | | | |||| | |
  4473. head-228 [000] .... 825.534637: __kmalloc <-load_elf_phdrs
  4474. head-228 [000] .... 825.534692: __kmalloc <-load_elf_binary
  4475. head-228 [000] .... 825.534815: __kmalloc <-load_elf_phdrs
  4476. head-228 [000] .... 825.550917: __kmalloc <-__seq_open_private
  4477. head-228 [000] .... 825.550953: __kmalloc <-tracing_open
  4478. head-229 [000] .... 826.756585: __kmalloc <-load_elf_phdrs
  4479. head-229 [000] .... 826.756627: __kmalloc <-load_elf_binary
  4480. head-229 [000] .... 826.756719: __kmalloc <-load_elf_phdrs
  4481. head-229 [000] .... 826.773796: __kmalloc <-__seq_open_private
  4482. head-229 [000] .... 826.773835: __kmalloc <-tracing_open
  4483. head-230 [000] .... 827.174988: __kmalloc <-load_elf_phdrs
  4484. head-230 [000] .... 827.175046: __kmalloc <-load_elf_binary
  4485. head-230 [000] .... 827.175171: __kmalloc <-load_elf_phdrs
  4486. ....
  4487. Trace all possible functions, and draw a call graph:
  4488. ....
  4489. echo 1 > max_graph_depth
  4490. echo 1 > events/enable
  4491. echo function_graph > current_tracer
  4492. ....
  4493. Sample output:
  4494. ....
  4495. # CPU DURATION FUNCTION CALLS
  4496. # | | | | | | |
  4497. 0) 2.173 us | } /* ntp_tick_length */
  4498. 0) | timekeeping_update() {
  4499. 0) 4.176 us | ntp_get_next_leap();
  4500. 0) 5.016 us | update_vsyscall();
  4501. 0) | raw_notifier_call_chain() {
  4502. 0) 2.241 us | notifier_call_chain();
  4503. 0) + 19.879 us | }
  4504. 0) 3.144 us | update_fast_timekeeper();
  4505. 0) 2.738 us | update_fast_timekeeper();
  4506. 0) ! 117.147 us | }
  4507. 0) | _raw_spin_unlock_irqrestore() {
  4508. 0) 4.045 us | _raw_write_unlock_irqrestore();
  4509. 0) + 22.066 us | }
  4510. 0) ! 265.278 us | } /* update_wall_time */
  4511. ....
  4512. TODO: what do `+` and `!` mean?
  4513. Each `enable` under the `events/` tree enables a certain set of functions, the higher the `enable` more functions are enabled.
  4514. 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
  4515. ===== ftrace system calls
  4516. https://stackoverflow.com/questions/29840213/how-do-i-trace-a-system-call-in-linux/51856306#51856306
  4517. ===== trace-cmd
  4518. TODO example:
  4519. ....
  4520. ./build-buildroot --config 'BR2_PACKAGE_TRACE_CMD=y'
  4521. ....
  4522. ==== Kprobes
  4523. 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. :-)
  4524. ....
  4525. ./build-linux --config 'CONFIG_KPROBES=y'
  4526. ....
  4527. Then on guest:
  4528. ....
  4529. insmod /kprobe_example.ko
  4530. sleep 4 & sleep 4 &'
  4531. ....
  4532. Outcome: dmesg outputs on every fork:
  4533. ....
  4534. <_do_fork> pre_handler: p->addr = 0x00000000e1360063, ip = ffffffff810531d1, flags = 0x246
  4535. <_do_fork> post_handler: p->addr = 0x00000000e1360063, flags = 0x246
  4536. <_do_fork> pre_handler: p->addr = 0x00000000e1360063, ip = ffffffff810531d1, flags = 0x246
  4537. <_do_fork> post_handler: p->addr = 0x00000000e1360063, flags = 0x246
  4538. ....
  4539. Source: link:kernel_modules/kprobe_example.c[]
  4540. TODO: it does not work if I try to immediately launch `sleep`, why?
  4541. ....
  4542. insmod /kprobe_example.ko
  4543. sleep 4 & sleep 4 &
  4544. ....
  4545. I don't think your code can refer to the surrounding kernel code however: the only visible thing is the value of the registers.
  4546. You can then hack it up to read the stack and read argument values, but do you really want to?
  4547. 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
  4548. Bibliography:
  4549. * https://github.com/torvalds/linux/blob/v4.16/Documentation/kprobes.txt
  4550. * https://github.com/torvalds/linux/blob/v4.17/samples/kprobes/kprobe_example.c
  4551. ==== Count boot instructions
  4552. TODO: didn't port during refactor after 3b0a343647bed577586989fb702b760bd280844a. Reimplementing should not be hard.
  4553. * https://www.quora.com/How-many-instructions-does-a-typical-Linux-kernel-boot-take
  4554. * https://github.com/cirosantilli/chat/issues/31
  4555. * https://rwmj.wordpress.com/2016/03/17/tracing-qemu-guest-execution/
  4556. * `qemu/docs/tracing.txt` and `qemu/docs/replay.txt`
  4557. * https://stackoverflow.com/questions/39149446/how-to-use-qemus-simple-trace-backend/46497873#46497873
  4558. Results (boot not excluded):
  4559. [options="header"]
  4560. |===
  4561. |Commit |Arch |Simulator |Instruction count
  4562. |7228f75ac74c896417fb8c5ba3d375a14ed4d36b
  4563. |arm
  4564. |QEMU
  4565. |680k
  4566. |7228f75ac74c896417fb8c5ba3d375a14ed4d36b
  4567. |arm
  4568. |gem5 AtomicSimpleCPU
  4569. |160M
  4570. |7228f75ac74c896417fb8c5ba3d375a14ed4d36b
  4571. |arm
  4572. |gem5 HPI
  4573. |155M
  4574. |7228f75ac74c896417fb8c5ba3d375a14ed4d36b
  4575. |x86_64
  4576. |QEMU
  4577. |3M
  4578. |7228f75ac74c896417fb8c5ba3d375a14ed4d36b
  4579. |x86_64
  4580. |gem5 AtomicSimpleCPU
  4581. |528M
  4582. |===
  4583. QEMU:
  4584. ....
  4585. ./trace-boot --arch x86_64
  4586. ....
  4587. sample output:
  4588. ....
  4589. instructions 1833863
  4590. entry_address 0x1000000
  4591. instructions_firmware 20708
  4592. ....
  4593. gem5:
  4594. ....
  4595. ./run --arch aarch64 --emulator gem5 --eval 'm5 exit'
  4596. # Or:
  4597. # ./run --arch aarch64 --emulator gem5 --eval 'm5 exit' -- --cpu-type=HPI --caches
  4598. ./gem5-stat --arch aarch64 sim_insts
  4599. ....
  4600. Notes:
  4601. * `0x1000000` is the address where QEMU puts the Linux kernel at with `-kernel` in x86.
  4602. +
  4603. It can be found from:
  4604. +
  4605. ....
  4606. ./run-toolchain readelf -- -e "$(./getvar vmlinux)" | grep Entry
  4607. ....
  4608. +
  4609. TODO confirm further. If I try to break there with:
  4610. +
  4611. ....
  4612. ./run-gdb *0x1000000
  4613. ....
  4614. +
  4615. 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:
  4616. +
  4617. ....
  4618. ./run-gdb extract_kernel
  4619. ....
  4620. +
  4621. It only appears once on every log I've seen so far, checked with `grep 0x1000000 trace.txt`
  4622. +
  4623. 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.
  4624. +
  4625. TODO `--arch arm` and `--arch aarch64` does not count firmware instructions properly because the entry point address of the ELF file (`ffffff8008080000` for `aarch64`) does not show up on the trace at all. Tested on link:http://github.com/cirosantilli/linux-kernel-module-cheat/commit/f8c0502bb2680f2dbe7c1f3d7958f60265347005[f8c0502bb2680f2dbe7c1f3d7958f60265347005].
  4626. * 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:
  4627. +
  4628. ....
  4629. ./run-gdb-user "$(./getvar userland_build_dir)/poweroff.out" main
  4630. ....
  4631. +
  4632. And get that from the traces, e.g. if the address is `4003a0`, then we search:
  4633. +
  4634. ....
  4635. grep -n 4003a0 trace.txt
  4636. ....
  4637. +
  4638. 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.
  4639. * to disable networking. Is replacing `init` enough?
  4640. +
  4641. --
  4642. ** https://superuser.com/questions/181254/how-do-you-boot-linux-with-networking-disabled
  4643. ** https://superuser.com/questions/684005/how-does-one-permanently-disable-gnu-linux-networking/1255015#1255015
  4644. --
  4645. +
  4646. `CONFIG_NET=n` did not significantly reduce instruction counts, so maybe replacing `init` is enough.
  4647. * gem5 simulates memory latencies. So I think that the CPU loops idle while waiting for memory, and counts will be higher.
  4648. === Linux kernel hardening
  4649. Make it harder to get hacked and easier to notice that you were, at the cost of some (small?) runtime overhead.
  4650. ==== CONFIG_FORTIFY_SOURCE
  4651. Detects buffer overflows for us:
  4652. ....
  4653. ./build-linux --config 'CONFIG_FORTIFY_SOURCE=y' --linux-build-id fortify
  4654. ./build-modules --clean
  4655. ./build-modules
  4656. ./build-buildroot
  4657. ./run --eval-after 'insmod /strlen_overflow.ko' --linux-build-id fortify
  4658. ....
  4659. Possible dmesg output:
  4660. ....
  4661. strlen_overflow: loading out-of-tree module taints kernel.
  4662. detected buffer overflow in strlen
  4663. ------------[ cut here ]------------
  4664. ....
  4665. followed by a trace.
  4666. 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.
  4667. TODO not always reproducible. Find a more reproducible failure. I could not observe it on:
  4668. ....
  4669. insmod /memcpy_overflow.ko
  4670. ....
  4671. Source: link:kernel_modules/strlen_overflow.c[]
  4672. Bibliography: https://www.reddit.com/r/hacking/comments/8h4qxk/what_a_buffer_overflow_in_the_linux_kernel_looks/
  4673. === User mode Linux
  4674. 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
  4675. 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.
  4676. Maybe some brave soul will send a pull request one day.
  4677. === UIO
  4678. UIO is a kernel subsystem that allows to do certain types of driver operations from userland.
  4679. This would be awesome to improve debugability and safety of kernel modules.
  4680. 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
  4681. TODO get something interesting working. I currently don't understand the behaviour very well.
  4682. TODO how to ACK interrupts? How to ensure that every interrupt gets handled separately?
  4683. TODO how to write to registers. Currently using `/dev/mem` and `lspci`.
  4684. This example should handle interrupts from userland and print a message to stdout:
  4685. ....
  4686. /uio_read.sh
  4687. ....
  4688. 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 :-)
  4689. UIO interface in a nutshell:
  4690. * blocking read / poll: waits until interrupts
  4691. * `write`: call `irqcontrol` callback. Default: 0 or 1 to enable / disable interrupts.
  4692. * `mmap`: access device memory
  4693. Sources:
  4694. * link:userland/uio_read.c[]
  4695. * link:rootfs_overlay/uio_read.sh[]
  4696. Bibliography:
  4697. * https://stackoverflow.com/questions/15286772/userspace-vs-kernel-space-driver
  4698. * https://01.org/linuxgraphics/gfx-docs/drm/driver-api/uio-howto.html
  4699. * https://stackoverflow.com/questions/7986260/linux-interrupt-handling-in-user-space
  4700. * https://yurovsky.github.io/2014/10/10/linux-uio-gpio-interrupt/
  4701. * https://github.com/bmartini/zynq-axis/blob/65a3a448fda1f0ea4977adfba899eb487201853d/dev/axis.c
  4702. * https://yurovsky.github.io/2014/10/10/linux-uio-gpio-interrupt/
  4703. * 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.
  4704. * https://stackoverflow.com/questions/49309162/interfacing-with-qemu-edu-device-via-userspace-i-o-uio-linux-driver
  4705. * userland driver stability questions:
  4706. ** https://stackoverflow.com/questions/8030758/getting-kernel-version-from-linux-kernel-module-at-runtime/45430233#45430233
  4707. ** https://stackoverflow.com/questions/37098482/how-to-build-a-linux-kernel-module-so-that-it-is-compatible-with-all-kernel-rele/45429681#45429681
  4708. ** https://liquidat.wordpress.com/2007/07/21/linux-kernel-2623-to-have-stable-userspace-driver-api/
  4709. === Linux kernel interactive stuff
  4710. [[fbcon]]
  4711. ==== Linux kernel console fun
  4712. Requires <<graphics>>.
  4713. You can also try those on the `Ctrl-Alt-F3` of your Ubuntu host, but it is much more fun inside a VM!
  4714. Stop the cursor from blinking:
  4715. ....
  4716. echo 0 > /sys/class/graphics/fbcon/cursor_blink
  4717. ....
  4718. Rotate the console 90 degrees! https://askubuntu.com/questions/237963/how-do-i-rotate-my-display-when-not-using-an-x-server
  4719. ....
  4720. echo 1 > /sys/class/graphics/fbcon/rotate
  4721. ....
  4722. Relies on: `CONFIG_FRAMEBUFFER_CONSOLE_ROTATION=y`.
  4723. Documented under: `Documentation/fb/`.
  4724. 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:
  4725. * https://unix.stackexchange.com/questions/177024/remap-keyboard-on-the-linux-console
  4726. * https://superuser.com/questions/194202/remapping-keys-system-wide-in-linux-not-just-in-x
  4727. ==== Linux kernel magic keys
  4728. Requires <<graphics>>.
  4729. Let's have some fun.
  4730. I think most are implemented under:
  4731. ....
  4732. drivers/tty
  4733. ....
  4734. TODO find all.
  4735. Scroll up / down the terminal:
  4736. ....
  4737. Shift-PgDown
  4738. Shift-PgUp
  4739. ....
  4740. Or inside `./qemu-monitor`:
  4741. ....
  4742. sendkey shift-pgup
  4743. sendkey shift-pgdown
  4744. ....
  4745. ===== Ctrl Alt Del
  4746. Run `/sbin/reboot` on guest:
  4747. ....
  4748. Ctrl-Alt-Del
  4749. ....
  4750. Enabled from our link:rootfs_overlay/etc/inittab[]:
  4751. ....
  4752. ::ctrlaltdel:/sbin/reboot
  4753. ....
  4754. Linux tries to reboot, and QEMU shutdowns due to the `-no-reboot` option which we set by default for: <<exit-emulator-on-panic>>.
  4755. Under the hood, behaviour is controlled by the `reboot` syscall:
  4756. ....
  4757. man 2 reboot
  4758. ....
  4759. `reboot` calls can set either of the these behaviours for `Ctrl-Alt-Del`:
  4760. * do a hard shutdown syscall. Set in ublibc C code with:
  4761. +
  4762. ....
  4763. reboot(RB_ENABLE_CAD)
  4764. ....
  4765. +
  4766. or from procfs with:
  4767. +
  4768. ....
  4769. echo 1 > /proc/sys/kernel/ctrl-alt-del
  4770. ....
  4771. * send a SIGINT to the init process. This is what BusyBox' init does, and it then execs the string set in `inittab`.
  4772. +
  4773. Set in uclibc C code with:
  4774. +
  4775. ....
  4776. reboot(RB_DISABLE_CAD)
  4777. ....
  4778. +
  4779. or from procfs with:
  4780. +
  4781. ....
  4782. echo 0 > /proc/sys/kernel/ctrl-alt-del
  4783. ....
  4784. Minimal example:
  4785. ....
  4786. ./run --kernel-cli 'init=/ctrl_alt_del.out' --graphic
  4787. ....
  4788. Source: link:userland/ctrl_alt_del.c[]
  4789. When you hit `Ctrl-Alt-Del` in the guest, our tiny init handles a `SIGINT` sent by the kernel and outputs to stdout:
  4790. ....
  4791. cad
  4792. ....
  4793. To map between `man 2 reboot` and the uclibc `RB_*` magic constants see:
  4794. ....
  4795. less "$(./getvar buildroot_build_build_dir)"/uclibc-*/include/sys/reboot.h"
  4796. ....
  4797. The procfs mechanism is documented at:
  4798. ....
  4799. less linux/Documentation/sysctl/kernel.txt
  4800. ....
  4801. which says:
  4802. ....
  4803. When the value in this file is 0, ctrl-alt-del is trapped and
  4804. sent to the init(1) program to handle a graceful restart.
  4805. When, however, the value is > 0, Linux's reaction to a Vulcan
  4806. Nerve Pinch (tm) will be an immediate reboot, without even
  4807. syncing its dirty buffers.
  4808. Note: when a program (like dosemu) has the keyboard in 'raw'
  4809. mode, the ctrl-alt-del is intercepted by the program before it
  4810. ever reaches the kernel tty layer, and it's up to the program
  4811. to decide what to do with it.
  4812. ....
  4813. Bibliography:
  4814. * https://superuser.com/questions/193652/does-linux-have-a-ctrlaltdel-equivalent/1324415#1324415
  4815. * https://unix.stackexchange.com/questions/42573/meaning-and-commands-for-ctrlaltdel/444969#444969
  4816. ===== SysRq
  4817. We cannot test these actual shortcuts on QEMU since the host captures them at a lower level, but from:
  4818. ....
  4819. ./qemu-monitor
  4820. ....
  4821. we can for example crash the system with:
  4822. ....
  4823. sendkey alt-sysrq-c
  4824. ....
  4825. Same but boring because no magic key:
  4826. ....
  4827. echo c > /proc/sysrq-trigger
  4828. ....
  4829. Implemented in:
  4830. ....
  4831. drivers/tty/sysrq.c
  4832. ....
  4833. On your host, on modern systems that don't have the `SysRq` key you can do:
  4834. ....
  4835. Alt-PrtSc-space
  4836. ....
  4837. which prints a message to `dmesg` of type:
  4838. ....
  4839. 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)
  4840. ....
  4841. Individual SysRq can be enabled or disabled with the bitmask:
  4842. ....
  4843. /proc/sys/kernel/sysrq
  4844. ....
  4845. The bitmask is documented at:
  4846. ....
  4847. less linux/Documentation/admin-guide/sysrq.rst
  4848. ....
  4849. Bibliography: https://en.wikipedia.org/wiki/Magic_SysRq_key
  4850. ==== TTY
  4851. In order to play with TTYs, do this:
  4852. ....
  4853. printf '
  4854. tty2::respawn:/sbin/getty -n -L -l /loginroot.sh tty2 0 vt100
  4855. tty3::respawn:-/bin/sh
  4856. tty4::respawn:/sbin/getty 0 tty4
  4857. tty63::respawn:-/bin/sh
  4858. ::respawn:/sbin/getty -L ttyS0 0 vt100
  4859. ::respawn:/sbin/getty -L ttyS1 0 vt100
  4860. ::respawn:/sbin/getty -L ttyS2 0 vt100
  4861. # Leave one serial empty.
  4862. #::respawn:/sbin/getty -L ttyS3 0 vt100
  4863. ' >> rootfs_overlay/etc/inittab
  4864. ./build-buildroot
  4865. ./run --graphic -- \
  4866. -serial telnet::1235,server,nowait \
  4867. -serial vc:800x600 \
  4868. -serial telnet::1236,server,nowait \
  4869. ;
  4870. ....
  4871. and on a second shell:
  4872. ....
  4873. telnet localhost 1235
  4874. ....
  4875. We don't add more TTYs by default because it would spawn more processes, even if we use `askfirst` instead of `respawn`.
  4876. On the GUI, switch TTYs with:
  4877. * `Alt-Left` or `Alt-Right:` go to previous / next populated `/dev/ttyN` TTY. Skips over empty TTYs.
  4878. * `Alt-Fn`: go to the nth TTY. If it is not populated, don't go there.
  4879. * `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
  4880. 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.
  4881. Next, we also have the following shells running on the serial ports, hit enter to activate them:
  4882. * `/dev/ttyS0`: first shell that was used to run QEMU, corresponds to QEMU's `-serial mon:stdio`.
  4883. +
  4884. It would also work if we used `-serial stdio`, but:
  4885. +
  4886. --
  4887. ** `Ctrl-C` would kill QEMU instead of going to the guest
  4888. ** `Ctrl-A C` wouldn't open the QEMU console there
  4889. --
  4890. +
  4891. see also: https://stackoverflow.com/questions/49716931/how-to-run-qemu-with-nographic-and-monitor-but-still-be-able-to-send-ctrlc-to
  4892. * `/dev/ttyS1`: second shell running `telnet`
  4893. * `/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`.
  4894. although we cannot change between terminals from there.
  4895. Each populated TTY contains a "shell":
  4896. * `-/bin/sh`: goes directly into an `sh` without a login prompt.
  4897. +
  4898. The trailing dash `-` can be used on any command. It makes the command that follows take over the TTY, which is what we typically want for interactive shells: https://askubuntu.com/questions/902998/how-to-check-which-tty-am-i-using
  4899. +
  4900. The `getty` executable however also does this operation and therefore dispenses the `-`.
  4901. * `/sbin/getty` asks for password, and then gives you an `sh`
  4902. +
  4903. 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.
  4904. Identify the current TTY with the command:
  4905. ....
  4906. tty
  4907. ....
  4908. Bibliography:
  4909. * https://unix.stackexchange.com/questions/270272/how-to-get-the-tty-in-which-bash-is-running/270372
  4910. * https://unix.stackexchange.com/questions/187319/how-to-get-the-real-name-of-the-controlling-terminal
  4911. * https://unix.stackexchange.com/questions/77796/how-to-get-the-current-terminal-name
  4912. * https://askubuntu.com/questions/902998/how-to-check-which-tty-am-i-using
  4913. This outputs:
  4914. * `/dev/console` for the initial GUI terminal. But I think it is the same as `/dev/tty1`, because if I try to do
  4915. +
  4916. ....
  4917. tty1::respawn:-/bin/sh
  4918. ....
  4919. +
  4920. it makes the terminal go crazy, as if multiple processes are randomly eating up the characters.
  4921. * `/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:
  4922. +
  4923. ....
  4924. #define MAX_NR_CONSOLES 63
  4925. ....
  4926. +
  4927. in `linux/include/uapi/linux/vt.h`.
  4928. * `/dev/ttySN` for the text shells.
  4929. +
  4930. 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
  4931. +
  4932. There are only 4 serial ports, I think this is determined by QEMU. TODO check.
  4933. +
  4934. See also: https://stackoverflow.com/questions/16706423/two-instances-of-busybox-on-separate-serial-lines-ttysn
  4935. Get the TTY in bulk for all processes:
  4936. ....
  4937. /psa.sh
  4938. ....
  4939. Source: link:rootfs_overlay/psa.sh[].
  4940. The TTY appears under the `TT` section, which is enabled by `-o tty`. This shows the TTY device number, e.g.:
  4941. ....
  4942. 4,1
  4943. ....
  4944. and we can then confirm it with:
  4945. ....
  4946. ls -l /dev/tty1
  4947. ....
  4948. Next try:
  4949. ....
  4950. insmod /kthread.ko
  4951. ....
  4952. 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.
  4953. Bibliography:
  4954. * https://serverfault.com/questions/119736/how-to-enable-multiple-virtual-consoles-on-linux
  4955. * https://github.com/mirror/busybox/blob/1_28_3/examples/inittab#L60
  4956. * http://web.archive.org/web/20180117124612/http://nairobi-embedded.org/qemu_serial_port_system_console.html
  4957. ===== Start a getty from outside of init
  4958. TODO: https://unix.stackexchange.com/questions/196704/getty-start-from-command-line
  4959. TODO: how to place an `sh` directly on a TTY as well without `getty`?
  4960. If I try the exact same command that the `inittab` is doing from a regular shell after boot:
  4961. ....
  4962. /sbin/getty 0 tty1
  4963. ....
  4964. it fails with:
  4965. ....
  4966. getty: setsid: Operation not permitted
  4967. ....
  4968. The following however works:
  4969. ....
  4970. ./run --eval 'getty 0 tty1 & getty 0 tty2 & getty 0 tty3 & sleep 99999999' --graphic
  4971. ....
  4972. presumably because it is being called from `init` directly?
  4973. Outcome: `Alt-Right` cycles between three TTYs, `tty1` being the default one that appears under the boot messages.
  4974. `man 2 setsid` says that there is only one failure possibility:
  4975. ____
  4976. 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.
  4977. ____
  4978. We can get some visibility into it to try and solve the problem with:
  4979. ....
  4980. /psa.sh
  4981. ....
  4982. ===== console kernel boot parameter
  4983. Take the command described at <<tty>> and try adding the following:
  4984. * `-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.
  4985. +
  4986. Instead, the shell appears on `/dev/tty7`.
  4987. * `-e 'console=tty2'` like `/dev/tty7`, but `/dev/tty2` is broken, because we have two shells there:
  4988. ** one due to the `::respawn:-/bin/sh` entry which uses whatever `console` points to
  4989. ** another one due to the `tty2::respawn:/sbin/getty` entry we added
  4990. * `-e 'console=ttyS0'` much like `tty2`, but messages show only on serial, and the terminal is broken due to having multiple shells on it
  4991. * `-e 'console=tty1 console=ttyS0'`: boot messages show on both `tty1` and `ttyS0`, but only `S0` gets a shell because it came last
  4992. ==== CONFIG_LOGO
  4993. If you run in <<graphics>>, then you get a Penguin image for <<number-of-cores,every core>> above the console! https://askubuntu.com/questions/80938/is-it-possible-to-get-the-tux-logo-on-the-text-based-boot
  4994. 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.
  4995. `reset` on the terminal then kills the poor penguins.
  4996. When `CONFIG_LOGO=y` is set, the logo can be disabled at boot with:
  4997. ....
  4998. ./run --kernel-cli 'logo.nologo'
  4999. ....
  5000. * https://stackoverflow.com/questions/39872463/how-can-i-disable-the-startup-penguins-and-boot-text-on-linaro-ubuntu
  5001. * https://unix.stackexchange.com/questions/332198/centos-remove-penguin-logo-at-startup
  5002. Looks like a recompile is needed to modify the image...
  5003. * https://superuser.com/questions/736423/changing-kernel-bootsplash-image
  5004. * https://unix.stackexchange.com/questions/153975/how-to-change-boot-logo-in-linux-mint
  5005. === DRM
  5006. DRM / DRI is the new interface that supersedes `fbdev`:
  5007. ....
  5008. ./build-buildroot --config 'BR2_PACKAGE_LIBDRM=y'
  5009. ./build-userland --has-package libdrm -- libdrm_modeset
  5010. ./run --eval-after '/libdrm_modeset.out' --graphic
  5011. ....
  5012. Source: link:userland/libdrm_modeset.c[]
  5013. Outcome: for a few seconds, the screen that contains the terminal gets taken over by changing colors of the rainbow.
  5014. 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.
  5015. ....
  5016. ./build-buildroot --config 'BR2_PACKAGE_LIBDRM=y'
  5017. ./build-userland --has-package libdrm
  5018. ./build-buildroot
  5019. ./run --eval-after '/libdrm_modeset.out' --graphic
  5020. ....
  5021. <<kmscube>> however worked, which means that it must be a bug with this demo?
  5022. We set `CONFIG_DRM=y` on our default kernel configuration, and it creates one device file for each display:
  5023. ....
  5024. # ls -l /dev/dri
  5025. total 0
  5026. crw------- 1 root root 226, 0 May 28 09:41 card0
  5027. # grep 226 /proc/devices
  5028. 226 drm
  5029. # ls /sys/module/drm /sys/module/drm_kms_helper/
  5030. ....
  5031. Try creating new displays:
  5032. ....
  5033. ./run --arch aarch64 --graphic -- -device virtio-gpu-pci
  5034. ....
  5035. to see multiple `/dev/dri/cardN`, and then use a different display with:
  5036. ....
  5037. ./run --eval-after '/libdrm_modeset.out' --graphic
  5038. ....
  5039. Bibliography:
  5040. * https://dri.freedesktop.org/wiki/DRM/
  5041. * https://en.wikipedia.org/wiki/Direct_Rendering_Infrastructure
  5042. * https://en.wikipedia.org/wiki/Direct_Rendering_Manager
  5043. * https://en.wikipedia.org/wiki/Mode_setting KMS
  5044. Tested on: link:http://github.com/cirosantilli/linux-kernel-module-cheat/commit/93e383902ebcc03d8a7ac0d65961c0e62af9612b[93e383902ebcc03d8a7ac0d65961c0e62af9612b]
  5045. ==== kmscube
  5046. ....
  5047. ./build-buildroot --config-fragment buildroot_config/kmscube
  5048. ....
  5049. Outcome: a colored spinning cube coded in OpenGL + EGL takes over your display and spins forever: https://www.youtube.com/watch?v=CqgJMgfxjsk
  5050. 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
  5051. TODO: it is very slow, about 1FPS. I tried Buildroot master ad684c20d146b220dd04a85dbf2533c69ec8ee52 with:
  5052. ....
  5053. make qemu_x86_64_defconfig
  5054. printf "
  5055. BR2_CCACHE=y
  5056. BR2_PACKAGE_HOST_QEMU=y
  5057. BR2_PACKAGE_HOST_QEMU_LINUX_USER_MODE=n
  5058. BR2_PACKAGE_HOST_QEMU_SYSTEM_MODE=y
  5059. BR2_PACKAGE_HOST_QEMU_VDE2=y
  5060. BR2_PACKAGE_KMSCUBE=y
  5061. BR2_PACKAGE_MESA3D=y
  5062. BR2_PACKAGE_MESA3D_DRI_DRIVER_SWRAST=y
  5063. BR2_PACKAGE_MESA3D_OPENGL_EGL=y
  5064. BR2_PACKAGE_MESA3D_OPENGL_ES=y
  5065. BR2_TOOLCHAIN_BUILDROOT_CXX=y
  5066. " >> .config
  5067. ....
  5068. and the FPS was much better, I estimate something like 15FPS.
  5069. On Ubuntu 18.04 with NVIDIA proprietary drivers:
  5070. ....
  5071. sudo apt-get instll kmscube
  5072. kmscube
  5073. ....
  5074. fails with:
  5075. ....
  5076. drmModeGetResources failed: Invalid argument
  5077. failed to initialize legacy DRM
  5078. ....
  5079. See also: https://github.com/robclark/kmscube/issues/12 and https://stackoverflow.com/questions/26920835/can-egl-application-run-in-console-mode/26921287#26921287
  5080. Tested on: link:http://github.com/cirosantilli/linux-kernel-module-cheat/commit/2903771275372ccfecc2b025edbb0d04c4016930[2903771275372ccfecc2b025edbb0d04c4016930]
  5081. ==== kmscon
  5082. TODO get working.
  5083. Implements a console for <<drm>>.
  5084. The Linux kernel has a built-in fbdev console: <<fbcon,fbcon>> but not for <<drm>> it seems.
  5085. The upstream project seems dead with last commit in 2014: https://www.freedesktop.org/wiki/Software/kmscon/
  5086. 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
  5087. Haven't tested the fork on QEMU too much insanity.
  5088. ==== libdri2
  5089. TODO get working.
  5090. Looks like a more raw alternative to libdrm:
  5091. ....
  5092. ./build-buildroot --config 'BR2_PACKABE_LIBDRI2=y'
  5093. wget \
  5094. -O "$(./getvar userland_source_dir)/dri2test.c" \
  5095. https://raw.githubusercontent.com/robclark/libdri2/master/test/dri2test.c \
  5096. ;
  5097. ./build-userland
  5098. ....
  5099. but then I noticed that that example requires multiple files, and I don't feel like integrating it into our build.
  5100. When I build it on Ubuntu 18.04 host, it does not generate any executable, so I'm confused.
  5101. === Linux kernel testing
  5102. Bibliography: https://stackoverflow.com/questions/3177338/how-is-the-linux-kernel-tested
  5103. ==== LTP
  5104. Linux Test Project
  5105. https://github.com/linux-test-project/ltp
  5106. C userland test suite.
  5107. Buildroot already has a package, so it is trivial to build it:
  5108. ....
  5109. ./build-buildroot --config 'BR2_PACKAGE_LTP_TESTSUITE=y'
  5110. ....
  5111. Then try it out with:
  5112. ....
  5113. cd /usr/lib/ltp-testsuite/testcases
  5114. ./bin/write01
  5115. ....
  5116. There is a main executable `execltp` to run everything, but it depends on Python, so let's just run them manually.
  5117. 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.
  5118. ==== stress
  5119. POSIX userland stress. Two versions:
  5120. ....
  5121. ./build-buildroot --config 'BR2_PACKAGE_STRESS=y'
  5122. ./build-buildroot --config 'BR2_PACKAGE_STRESS_NG=y'
  5123. ....
  5124. Websites:
  5125. * https://people.seas.harvard.edu/~apw/stress/
  5126. * https://github.com/ColinIanKing/stress-ng
  5127. 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.
  5128. `stress` usage:
  5129. ....
  5130. stress --help
  5131. stress -c 16 &
  5132. ps
  5133. ....
  5134. and notice how 16 threads were created in addition to a parent worker thread.
  5135. It just runs forever, so kill it when you get tired:
  5136. ....
  5137. kill %1
  5138. ....
  5139. `stress -c 1 -t 1` makes gem5 irresponsive for a very long time.
  5140. == Linux kernel build system
  5141. === vmlinux vs bzImage vs zImage vs Image
  5142. Between all archs on QEMU and gem5 we touch all of those kernel built output files.
  5143. We are trying to maintain a description of each at: https://unix.stackexchange.com/questions/5518/what-is-the-difference-between-the-following-kernel-makefile-terms-vmlinux-vml/482978#482978
  5144. QEMU does not seem able to boot ELF files like `vmlinux`, only `objdump` code: https://superuser.com/questions/1376944/can-qemu-boot-linux-from-vmlinux-instead-of-bzimage
  5145. Converting `arch/*` images to `vmlinux` is possible in x86 with link:https://github.com/torvalds/linux/blob/master/scripts/extract-vmlinux[`extract-vmlinux`]. But for arm it fails with:
  5146. ....
  5147. run-detectors: unable to find an interpreter for
  5148. ....
  5149. as mentioned at:
  5150. * https://unix.stackexchange.com/questions/352215/how-do-i-extract-vmlinux-from-an-arm-image
  5151. * https://raspberrypi.stackexchange.com/questions/88621/why-doesnt-extract-vmlinux-work-with-raspbians-boot-kernel-img
  5152. == QEMU
  5153. === Introduction to QEMU
  5154. link:https://en.wikipedia.org/wiki/QEMU[QEMU] is a system simulator: it simulates a CPU and devices such as interrupt handlers, timers, UART, screen, keyboard, etc.
  5155. If you are familiar with link:https://en.wikipedia.org/wiki/VirtualBox[VirtualBox], then QEMU then basically does the same thing: it opens a "window" inside your desktop that can run an operating system inside your operating system.
  5156. Also both can use very similar techniques: either link:lhttps://en.wikipedia.org/wiki/Binary_translation[binary translation] or <<KVM>>. VirtualBox' binary translator is / was based on QEMU's it seems: https://en.wikipedia.org/wiki/VirtualBox#Software-based_virtualization
  5157. The huge advantage of QEMU over VirtualBox is that is supports cross arch simulation, e.g. simulate an ARM guest on an x86 host.
  5158. QEMU is likely the leading cross arch system simulator as of 2018. It is even the default Android simulator that developers get with Android Studio 3 to develop apps without real hardware.
  5159. Another advantage of QEMU over virtual box is that it doesn't have Oracle' hands all all over it, more like RedHat + ARM.
  5160. Another advantage of QEMU is that is has no nice configuration GUI. Because who needs GUIs when you have 50 million semi-documented CLI options? Android Studio adds a custom GUI configuration tool on top of it.
  5161. QEMU is also supported by Buildroot in-tree, see e.g.: https://github.com/buildroot/buildroot/blob/2018.05/configs/qemu_aarch64_virt_defconfig We however just build our own manually with link:build-qemu[], as it gives more flexibility, and building QEMU is very easy!
  5162. All of this makes QEMU the natural choice of reference system simulator for this repo.
  5163. === Disk persistency
  5164. We disable disk persistency for both QEMU and gem5 by default, to prevent the emulator from putting the image in an unknown state.
  5165. For QEMU, this is done by passing the `snapshot` option to `-drive`, and for gem5 it is the default behaviour.
  5166. If you hack up our link:run[] script to remove that option, then:
  5167. ....
  5168. ./run --eval-after 'date >f;poweroff'
  5169. ....
  5170. followed by:
  5171. ....
  5172. ./run --eval-after 'cat f'
  5173. ....
  5174. gives the date, because `poweroff` without `-n` syncs before shutdown.
  5175. The `sync` command also saves the disk:
  5176. ....
  5177. sync
  5178. ....
  5179. When you do:
  5180. ....
  5181. ./build-buildroot
  5182. ....
  5183. the disk image gets overwritten by a fresh filesystem and you lose all changes.
  5184. 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.
  5185. Persistency is also turned off when booting from <<initrd>> with a CPIO instead of with a disk.
  5186. 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.
  5187. ==== gem5 disk persistency
  5188. TODO how to make gem5 disk writes persistent?
  5189. As of cadb92f2df916dbb47f428fd1ec4932a2e1f0f48 there are some `read_only` entries in the <<config-ini>> under cow sections, but hacking them to true did not work:
  5190. ....
  5191. diff --git a/configs/common/FSConfig.py b/configs/common/FSConfig.py
  5192. index 17498c42b..76b8b351d 100644
  5193. --- a/configs/common/FSConfig.py
  5194. +++ b/configs/common/FSConfig.py
  5195. @@ -60,7 +60,7 @@ os_types = { 'alpha' : [ 'linux' ],
  5196. }
  5197. class CowIdeDisk(IdeDisk):
  5198. - image = CowDiskImage(child=RawDiskImage(read_only=True),
  5199. + image = CowDiskImage(child=RawDiskImage(read_only=False),
  5200. read_only=False)
  5201. def childImage(self, ci):
  5202. ....
  5203. The directory of interest is `src/dev/storage`.
  5204. === gem5 qcow2
  5205. 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
  5206. This would be good to allow storing smaller sparse ext2 images locally on disk.
  5207. === Snapshot
  5208. QEMU allows us to take snapshots at any time through the monitor.
  5209. You can then restore CPU, memory and disk state back at any time.
  5210. qcow2 filesystems must be used for that to work.
  5211. To test it out, login into the VM with and run:
  5212. ....
  5213. ./run --eval-after 'umount /mnt/9p/*;/count.sh'
  5214. ....
  5215. On another shell, take a snapshot:
  5216. ....
  5217. ./qemu-monitor savevm my_snap_id
  5218. ....
  5219. The counting continues.
  5220. Restore the snapshot:
  5221. ....
  5222. ./qemu-monitor loadvm my_snap_id
  5223. ....
  5224. and the counting goes back to where we saved. This shows that CPU and memory states were reverted.
  5225. 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:
  5226. .....
  5227. 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'
  5228. .....
  5229. We can also verify that the disk state is also reversed. Guest:
  5230. ....
  5231. echo 0 >f
  5232. ....
  5233. Monitor:
  5234. ....
  5235. ./qemu-monitor savevm my_snap_id
  5236. ....
  5237. Guest:
  5238. ....
  5239. echo 1 >f
  5240. ....
  5241. Monitor:
  5242. ....
  5243. ./qemu-monitor loadvm my_snap_id
  5244. ....
  5245. Guest:
  5246. ....
  5247. cat f
  5248. ....
  5249. And the output is `0`.
  5250. Our setup does not allow for snapshotting while using <<initrd>>.
  5251. Bibliography: https://stackoverflow.com/questions/40227651/does-qemu-emulator-have-checkpoint-function/48724371#48724371
  5252. ==== Snapshot internals
  5253. Snapshots are stored inside the `.qcow2` images themselves.
  5254. They can be observed with:
  5255. ....
  5256. "$(./getvar host_dir)/bin/qemu-img" info "$(./getvar qcow2_file)"
  5257. ....
  5258. which after `savevm my_snap_id` and `savevm asdf` contains an output of type:
  5259. ....
  5260. image: out/x86_64/buildroot/images/rootfs.ext2.qcow2
  5261. file format: qcow2
  5262. virtual size: 512M (536870912 bytes)
  5263. disk size: 180M
  5264. cluster_size: 65536
  5265. Snapshot list:
  5266. ID TAG VM SIZE DATE VM CLOCK
  5267. 1 my_snap_id 47M 2018-04-27 21:17:50 00:00:15.251
  5268. 2 asdf 47M 2018-04-27 21:20:39 00:00:18.583
  5269. Format specific information:
  5270. compat: 1.1
  5271. lazy refcounts: false
  5272. refcount bits: 16
  5273. corrupt: false
  5274. ....
  5275. As a consequence:
  5276. * it is possible to restore snapshots across boots, since they stay on the same image the entire time
  5277. * it is not possible to use snapshots with <<initrd>> in our setup, since we don't pass `-drive` at all when initrd is enabled
  5278. === Device models
  5279. This section documents:
  5280. * how to interact with peripheral hardware device models through device drivers
  5281. * 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
  5282. For the more complex interfaces, we focus on simplified educational devices, either:
  5283. * present in the QEMU upstream:
  5284. ** <<qemu-edu>>
  5285. * added in link:https://github.com/cirosantilli/qemu[our fork of QEMU]:
  5286. ** <<pci_min>>
  5287. ** <<platform_device>>
  5288. ==== PCI
  5289. Only tested in x86.
  5290. ===== pci_min
  5291. PCI driver for our minimal `pci_min.c` QEMU fork device:
  5292. ....
  5293. ./run -- -device lkmc_pci_min
  5294. ....
  5295. then:
  5296. ....
  5297. insmod /pci_min.ko
  5298. ....
  5299. Sources:
  5300. * Kernel module: link:kernel_modules/pci_min.c[].
  5301. * QEMU device: https://github.com/cirosantilli/qemu/blob/lkmc/hw/misc/lkmc_pci_min.c
  5302. Outcome:
  5303. ....
  5304. <4>[ 10.608241] pci_min: loading out-of-tree module taints kernel.
  5305. <6>[ 10.609935] probe
  5306. <6>[ 10.651881] dev->irq = 11
  5307. lkmc_pci_min mmio_write addr = 0 val = 12345678 size = 4
  5308. <6>[ 10.668515] irq_handler irq = 11 dev = 251
  5309. lkmc_pci_min mmio_write addr = 4 val = 0 size = 4
  5310. ....
  5311. What happened:
  5312. * right at probe time, we write to a register
  5313. * our hardware model is coded such that it generates an interrupt when written to
  5314. * the Linux kernel interrupt handler write to another register, which tells the hardware to stop sending interrupts
  5315. Kernel messages and printks from inside QEMU are shown all together, to see that more clearly, run in <<qemu-graphic-mode>> instead.
  5316. 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.
  5317. Probe already does a MMIO write, which generates an IRQ and tests everything.
  5318. [[qemu-edu]]
  5319. ===== QEMU edu PCI device
  5320. Small upstream educational PCI device:
  5321. ....
  5322. /qemu_edu.sh
  5323. ....
  5324. 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
  5325. Sources:
  5326. * kernel module: link:kernel_modules/qemu_edu.c[]
  5327. * QEMU device: https://github.com/qemu/qemu/blob/v2.12.0/hw/misc/edu.c
  5328. * test script: link:rootfs_overlay/qemu_edu.sh[]
  5329. Works because we add to our default QEMU CLI:
  5330. ....
  5331. -device edu
  5332. ....
  5333. This example uses:
  5334. * the QEMU `edu` educational device, which is a minimal educational in-tree PCI example
  5335. * out `/pci.ko` kernel module, which exercises the `edu` hardware.
  5336. +
  5337. 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.
  5338. TODO exercise DMA on the kernel module. The `edu` hardware model has that feature:
  5339. * https://stackoverflow.com/questions/32592734/are-there-any-dma-driver-example-pcie-and-fpga/44716747#44716747
  5340. * https://stackoverflow.com/questions/17913679/how-to-instantiate-and-use-a-dma-driver-linux-module
  5341. ===== Manipulate PCI registers directly
  5342. In this section we will try to interact with PCI devices directly from userland without kernel modules.
  5343. First identify the PCI device with:
  5344. ....
  5345. lspci
  5346. ....
  5347. In our case for example, we see:
  5348. ....
  5349. 00:06.0 Unclassified device [00ff]: Device 1234:11e8 (rev 10)
  5350. 00:07.0 Unclassified device [00ff]: Device 1234:11e9
  5351. ....
  5352. which we identify as being `edu` and `pci_min` respectively by the magic numbers: `1234:11e?`
  5353. Alternatively, we can also do use the QEMU monitor:
  5354. ....
  5355. ./qemu-monitor info qtree
  5356. ....
  5357. which gives:
  5358. ....
  5359. dev: lkmc_pci_min, id ""
  5360. addr = 07.0
  5361. romfile = ""
  5362. rombar = 1 (0x1)
  5363. multifunction = false
  5364. command_serr_enable = true
  5365. x-pcie-lnksta-dllla = true
  5366. x-pcie-extcap-init = true
  5367. class Class 00ff, addr 00:07.0, pci id 1234:11e9 (sub 1af4:1100)
  5368. bar 0: mem at 0xfeb54000 [0xfeb54007]
  5369. dev: edu, id ""
  5370. addr = 06.0
  5371. romfile = ""
  5372. rombar = 1 (0x1)
  5373. multifunction = false
  5374. command_serr_enable = true
  5375. x-pcie-lnksta-dllla = true
  5376. x-pcie-extcap-init = true
  5377. class Class 00ff, addr 00:06.0, pci id 1234:11e8 (sub 1af4:1100)
  5378. bar 0: mem at 0xfea00000 [0xfeafffff]
  5379. ....
  5380. See also: https://serverfault.com/questions/587189/list-all-devices-emulated-for-a-vm/913622#913622
  5381. Read the configuration registers as binary:
  5382. ....
  5383. hexdump /sys/bus/pci/devices/0000:00:06.0/config
  5384. ....
  5385. Get nice human readable names and offsets of the registers and some enums:
  5386. ....
  5387. setpci --dumpregs
  5388. ....
  5389. Get the values of a given config register from its human readable name, either with either bus or device id:
  5390. ....
  5391. setpci -s 0000:00:06.0 BASE_ADDRESS_0
  5392. setpci -d 1234:11e9 BASE_ADDRESS_0
  5393. ....
  5394. Note however that `BASE_ADDRESS_0` also appears when you do:
  5395. ....
  5396. lspci -v
  5397. ....
  5398. as:
  5399. ....
  5400. Memory at feb54000
  5401. ....
  5402. Then you can try messing with that address with <<dev-mem>>:
  5403. ....
  5404. devmem 0xfeb54000 w 0x12345678
  5405. ....
  5406. which writes to the first register of our <<pci_min>> device.
  5407. The device then fires an interrupt at irq 11, which is unhandled, which leads the kernel to say you are a bad boy:
  5408. ....
  5409. lkmc_pci_min mmio_write addr = 0 val = 12345678 size = 4
  5410. <5>[ 1064.042435] random: crng init done
  5411. <3>[ 1065.567742] irq 11: nobody cared (try booting with the "irqpoll" option)
  5412. ....
  5413. followed by a trace.
  5414. Next, also try using our <<irq-ko>> IRQ monitoring module before triggering the interrupt:
  5415. ....
  5416. insmod /irq.ko
  5417. devmem 0xfeb54000 w 0x12345678
  5418. ....
  5419. 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:
  5420. ....
  5421. handler irq = 11 dev = 251
  5422. ....
  5423. ===== pciutils
  5424. There are two versions of `setpci` and `lspci`:
  5425. * a simple one from BusyBox
  5426. * 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.
  5427. ===== Introduction to PCI
  5428. The PCI standard is non-free, obviously like everything in low level: https://pcisig.com/specifications but Google gives several illegal PDF hits :-)
  5429. And of course, the best documentation available is: http://wiki.osdev.org/PCI
  5430. Like every other hardware, we could interact with PCI on x86 using only IO instructions and memory operations.
  5431. But PCI is a complex communication protocol that the Linux kernel implements beautifully for us, so let's use the kernel API.
  5432. Bibliography:
  5433. * edu device source and spec in QEMU tree:
  5434. ** https://github.com/qemu/qemu/blob/v2.7.0/hw/misc/edu.c
  5435. ** https://github.com/qemu/qemu/blob/v2.7.0/docs/specs/edu.txt
  5436. * http://www.zarb.org/~trem/kernel/pci/pci-driver.c inb outb runnable example (no device)
  5437. * LDD3 PCI chapter
  5438. * another QEMU device + module, but using a custom QEMU device:
  5439. ** https://github.com/levex/kernel-qemu-pci/blob/31fc9355161b87cea8946b49857447ddd34c7aa6/module/levpci.c
  5440. ** https://github.com/levex/kernel-qemu-pci/blob/31fc9355161b87cea8946b49857447ddd34c7aa6/qemu/hw/char/lev-pci.c
  5441. * 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
  5442. * http://nairobi-embedded.org/linux_pci_device_driver.html
  5443. ===== PCI BFD
  5444. `lspci -k` shows something like:
  5445. ....
  5446. 00:04.0 Class 00ff: 1234:11e8 lkmc_pci
  5447. ....
  5448. Meaning of the first numbers:
  5449. ....
  5450. <8:bus>:<5:device>.<3:function>
  5451. ....
  5452. Often abbreviated to BDF.
  5453. * bus: groups PCI slots
  5454. * device: maps to one slot
  5455. * function: https://stackoverflow.com/questions/19223394/what-is-the-function-number-in-pci/44735372#44735372
  5456. Sometimes a fourth number is also added, e.g.:
  5457. ....
  5458. 0000:00:04.0
  5459. ....
  5460. TODO is that the domain?
  5461. 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:
  5462. ....
  5463. k->class_id = PCI_CLASS_OTHERS
  5464. ....
  5465. ===== PCI BAR
  5466. https://stackoverflow.com/questions/30190050/what-is-base-address-register-bar-in-pcie/44716618#44716618
  5467. Each PCI device has 6 BAR IOs (base address register) as per the PCI spec.
  5468. Each BAR corresponds to an address range that can be used to communicate with the PCI.
  5469. Each BAR is of one of the two types:
  5470. * `IORESOURCE_IO`: must be accessed with `inX` and `outX`
  5471. * `IORESOURCE_MEM`: must be accessed with `ioreadX` and `iowriteX`. This is the saner method apparently, and what the edu device uses.
  5472. The length of each region is defined by the hardware, and communicated to software via the configuration registers.
  5473. The Linux kernel automatically parses the 64 bytes of standardized configuration registers for us.
  5474. QEMU devices register those regions with:
  5475. ....
  5476. memory_region_init_io(&edu->mmio, OBJECT(edu), &edu_mmio_ops, edu,
  5477. "edu-mmio", 1 << 20);
  5478. pci_register_bar(pdev, 0, PCI_BASE_ADDRESS_SPACE_MEMORY, &edu->mmio);
  5479. ....
  5480. ==== GPIO
  5481. 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.
  5482. 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
  5483. The best you can do is to hack our link:build[] script to add:
  5484. ....
  5485. HOST_QEMU_OPTS='--extra-cflags=-DDEBUG_PL061=1'
  5486. ....
  5487. 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.
  5488. Then compile with:
  5489. ....
  5490. ./build-buildroot --arch arm --config-fragment buildroot_config/gpio
  5491. ./build-linux --config-fragment linux_config/gpio
  5492. ....
  5493. then test it out with:
  5494. ....
  5495. /gpio.sh
  5496. ....
  5497. Source: link:rootfs_overlay/gpio.sh[]
  5498. Buildroot's Linux tools package provides some GPIO CLI tools: `lsgpio`, `gpio-event-mon`, `gpio-hammer`, TODO document them here.
  5499. ==== LEDs
  5500. TODO: broken when `arm` moved to `-M virt`, same as <<gpio>>.
  5501. Hack QEMU's `hw/misc/arm_sysctl.c` with a printf:
  5502. ....
  5503. static void arm_sysctl_write(void *opaque, hwaddr offset,
  5504. uint64_t val, unsigned size)
  5505. {
  5506. arm_sysctl_state *s = (arm_sysctl_state *)opaque;
  5507. switch (offset) {
  5508. case 0x08: /* LED */
  5509. printf("LED val = %llx\n", (unsigned long long)val);
  5510. ....
  5511. and then rebuild with:
  5512. ....
  5513. ./build-qemu --arch arm
  5514. ./build-linux --arch arm --config-fragment linux_config/leds
  5515. ....
  5516. But beware that one of the LEDs has a heartbeat trigger by default (specified on dts), so it will produce a lot of output.
  5517. And then activate it with:
  5518. ....
  5519. cd /sys/class/leds/versatile:0
  5520. cat max_brightness
  5521. echo 255 >brightness
  5522. ....
  5523. Relevant QEMU files:
  5524. * `hw/arm/versatilepb.c`
  5525. * `hw/misc/arm_sysctl.c`
  5526. Relevant kernel files:
  5527. * `arch/arm/boot/dts/versatile-pb.dts`
  5528. * `drivers/leds/led-class.c`
  5529. * `drivers/leds/leds-sysctl.c`
  5530. ==== platform_device
  5531. Minimal platform device example coded into the `-M versatilepb` SoC of our QEMU fork.
  5532. Using this device now requires checking out to the branch:
  5533. ....
  5534. git checkout platform-device
  5535. git submodule sync
  5536. ....
  5537. before building, it does not work on master.
  5538. Rationale: we found out that the kernels that build for `qemu -M versatilepb` don't work on gem5 because `versatilepb` is an old pre-v7 platform, and gem5 requires armv7. So we migrated over to `-M virt` to have a single kernel for both gem5 and QEMU, and broke this since the single kernel was more important. TODO port to `-M virt`.
  5539. The module itself can be found at: https://github.com/cirosantilli/linux-kernel-module-cheat/blob/platform-device/kernel_modules/platform_device.c
  5540. Uses:
  5541. * `hw/misc/lkmc_platform_device.c` minimal device added in our QEMU fork to `-M versatilepb`
  5542. * 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
  5543. Expected outcome after insmod:
  5544. * QEMU reports MMIO with printfs
  5545. * IRQs are generated and handled by this module, which logs to dmesg
  5546. Without insmoding this module, try writing to the register with <<dev-mem>>:
  5547. ....
  5548. devmem 0x101e9000 w 0x12345678
  5549. ....
  5550. We can also observe the interrupt with <<dummy-irq>>:
  5551. ....
  5552. modprobe dummy-irq irq=34
  5553. insmod /platform_device.ko
  5554. ....
  5555. The IRQ number `34` was found by on the dmesg after:
  5556. ....
  5557. insmod /platform_device.ko
  5558. ....
  5559. Bibliography: https://stackoverflow.com/questions/28315265/how-to-add-a-new-device-in-qemu-source-code/44612957#44612957
  5560. ==== gem5 educational hardware models
  5561. TODO get some working!
  5562. http://gedare-csphd.blogspot.co.uk/2013/02/adding-simple-io-device-to-gem5.html
  5563. === QEMU monitor
  5564. The QEMU monitor is a terminal that allows you to send text commands to the QEMU VM: https://en.wikibooks.org/wiki/QEMU/Monitor
  5565. On another terminal, run:
  5566. ....
  5567. ./qemu-monitor
  5568. ....
  5569. or send one command such as `info qtree` and quit the monitor:
  5570. ....
  5571. ./qemu-monitor info qtree
  5572. ....
  5573. or equivalently:
  5574. ....
  5575. echo 'info qtree' | ./qemu-monitor
  5576. ....
  5577. Source: link:qemu-monitor[]
  5578. `qemu-monitor` uses the `-monitor` QEMU command line option, which makes the monitor listen from a socket.
  5579. Alternatively, from text mode:
  5580. ....
  5581. Ctrl-A C
  5582. ....
  5583. and go back to the terminal with:
  5584. ....
  5585. Ctrl-A C
  5586. ....
  5587. * http://stackoverflow.com/questions/14165158/how-to-switch-to-qemu-monitor-console-when-running-with-curses
  5588. * https://superuser.com/questions/488263/how-to-switch-to-the-qemu-control-panel-with-nographics
  5589. And in graphic mode from the GUI:
  5590. ....
  5591. Ctrl-Alt ?
  5592. ....
  5593. where `?` is a digit `1`, or `2`, or, `3`, etc. depending on what else is available on the GUI: serial, parallel and frame buffer.
  5594. In general, `./qemu-monitor` is the best option, as it:
  5595. * works on both modes
  5596. * allows to use the host Bash history to re-run one off commands
  5597. * allows you to search the output of commands on your host shell even when in graphic mode
  5598. Getting everything to work required careful choice of QEMU command line options:
  5599. * https://stackoverflow.com/questions/49716931/how-to-run-qemu-with-nographic-and-monitor-but-still-be-able-to-send-ctrlc-to/49751144#49751144
  5600. * https://unix.stackexchange.com/questions/167165/how-to-pass-ctrl-c-to-the-guest-when-running-qemu-with-nographic/436321#436321
  5601. ==== QEMU monitor from guest
  5602. 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
  5603. It is also worth looking into the QEMU Guest Agent tool `qemu-gq` that can be enabled with:
  5604. ....
  5605. ./build-buildroot --config 'BR2_PACKAGE_QEMU=y'
  5606. ....
  5607. See also: https://superuser.com/questions/930588/how-to-pass-commands-noninteractively-to-running-qemu-from-the-guest-qmp-via-te
  5608. ==== QEMU monitor from GDB
  5609. 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.
  5610. Try for example:
  5611. ....
  5612. monitor help
  5613. monitor info qtree
  5614. ....
  5615. === Debug the emulator
  5616. When you start hacking QEMU or gem5, it is useful to see what is going on inside the emulator themselves.
  5617. This is of course trivial since they are just regular userland programs on the host, but we make it a bit easier with:
  5618. ....
  5619. ./run --debug-vm
  5620. ....
  5621. Then you could:
  5622. ....
  5623. break edu_mmio_read
  5624. run
  5625. ....
  5626. And in QEMU:
  5627. ....
  5628. /qemu_edu.sh
  5629. ....
  5630. Or for a faster development loop:
  5631. ....
  5632. ./run --debug-vm --debug-vm-args '-ex "break edu_mmio_read" -ex "run"'
  5633. ....
  5634. When in <<qemu-text-mode>>, using `--debug-vm` makes Ctrl-C not get passed to the QEMU guest anymore: it is instead captured by GDB itself, so allow breaking. So e.g. you won't be able to easily quit from a guest program like:
  5635. ....
  5636. sleep 10
  5637. ....
  5638. 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.
  5639. 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.
  5640. ==== Debug gem5 Python scripts
  5641. Start pdb at the first instruction:
  5642. ....
  5643. ./run --emulator gem5 --gem5-exe-args='--pdb' --terminal
  5644. ....
  5645. Requires `--terminal` as we must be on foreground.
  5646. Alternatively, you can add to the point of the code where you want to break the usual:
  5647. ....
  5648. import ipdb; ipdb.set_trace()
  5649. ....
  5650. and then run with:
  5651. ....
  5652. ./run --emulator gem5 --terminal
  5653. ....
  5654. TODO test PyCharm: https://stackoverflow.com/questions/51982735/writing-gem5-configuration-scripts-with-pycharm
  5655. === Tracing
  5656. QEMU can log several different events.
  5657. The most interesting are events which show instructions that QEMU ran, for which we have a helper:
  5658. ....
  5659. ./trace-boot --arch x86_64
  5660. ....
  5661. Under the hood, this uses QEMU's `-trace` option.
  5662. You can then inspect the address of each instruction run:
  5663. ....
  5664. less "$(./getvar --arch x86_64 run_dir)/trace.txt"
  5665. ....
  5666. Sample output excerpt:
  5667. ....
  5668. exec_tb 0.000 pid=10692 tb=0x7fb4f8000040 pc=0xfffffff0
  5669. exec_tb 35.391 pid=10692 tb=0x7fb4f8000180 pc=0xfe05b
  5670. exec_tb 21.047 pid=10692 tb=0x7fb4f8000340 pc=0xfe066
  5671. exec_tb 12.197 pid=10692 tb=0x7fb4f8000480 pc=0xfe06a
  5672. ....
  5673. Get the list of available trace events:
  5674. ....
  5675. ./run --trace help
  5676. ....
  5677. TODO: any way to show the actualy disassembled instruction executed directly from there? Possible with <<qemu-d-tracing>>.
  5678. Enable other specific trace events:
  5679. ....
  5680. ./run --trace trace1,trace2
  5681. ./qemu-trace2txt -a "$arch"
  5682. less "$(./getvar -a "$arch" run_dir)/trace.txt"
  5683. ....
  5684. This functionality relies on the following setup:
  5685. * `./configure --enable-trace-backends=simple`. This logs in a binary format to the trace file.
  5686. +
  5687. It makes 3x execution faster than the default trace backend which logs human readable data to stdout.
  5688. +
  5689. Logging with the default backend `log` greatly slows down the CPU, and in particular leads to this boot message:
  5690. +
  5691. ....
  5692. All QSes seen, last rcu_sched kthread activity 5252 (4294901421-4294896169), jiffies_till_next_fqs=1, root ->qsmask 0x0
  5693. swapper/0 R running task 0 1 0 0x00000008
  5694. ffff880007c03ef8 ffffffff8107aa5d ffff880007c16b40 ffffffff81a3b100
  5695. ffff880007c03f60 ffffffff810a41d1 0000000000000000 0000000007c03f20
  5696. fffffffffffffedc 0000000000000004 fffffffffffffedc ffffffff00000000
  5697. Call Trace:
  5698. <IRQ> [<ffffffff8107aa5d>] sched_show_task+0xcd/0x130
  5699. [<ffffffff810a41d1>] rcu_check_callbacks+0x871/0x880
  5700. [<ffffffff810a799f>] update_process_times+0x2f/0x60
  5701. ....
  5702. +
  5703. in which the boot appears to hang for a considerable time.
  5704. * 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/
  5705. ==== QEMU -d tracing
  5706. QEMU also has a second trace mechanism in addition to `-trace`, find out the events with:
  5707. ....
  5708. ./run -- -d help
  5709. ....
  5710. Let's pick the one that dumps executed instructions, `in_asm`:
  5711. ....
  5712. ./run --eval '/poweroff.out' -- -D out/trace.txt -d in_asm
  5713. less out/trace.txt
  5714. ....
  5715. Sample output excerpt:
  5716. ....
  5717. ----------------
  5718. IN:
  5719. 0xfffffff0: ea 5b e0 00 f0 ljmpw $0xf000:$0xe05b
  5720. ----------------
  5721. IN:
  5722. 0x000fe05b: 2e 66 83 3e 88 61 00 cmpl $0, %cs:0x6188
  5723. 0x000fe062: 0f 85 7b f0 jne 0xd0e1
  5724. ....
  5725. TODO: after `IN:`, symbol names are meant to show, which is awesome, but I don't get any. I do see them however when running a bare metal example from: https://github.com/cirosantilli/newlib-examples/tree/900a9725947b1f375323c7da54f69e8049158881
  5726. TODO: what is the point of having two mechanisms, `-trace` and `-d`? `-d` tracing is cool because it does not require a messy recompile, and it can also show symbols.
  5727. ==== QEMU trace register values
  5728. TODO: is it possible to show the register values for each instruction?
  5729. This would include the memory values read into the registers.
  5730. Asked at: https://superuser.com/questions/1377764/how-to-trace-the-register-values-of-executed-instructions-in-qemu
  5731. Seems impossible due to optimizations that QEMU does:
  5732. * https://lists.gnu.org/archive/html/qemu-devel/2015-06/msg07479.html
  5733. * https://lists.gnu.org/archive/html/qemu-devel/2014-04/msg02856.html
  5734. * https://lists.gnu.org/archive/html/qemu-devel/2012-08/msg03057.html
  5735. 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
  5736. gem5 can do it: <<gem5-tracing>>.
  5737. ==== Trace source lines
  5738. We can further use Binutils' `addr2line` to get the line that corresponds to each address:
  5739. ....
  5740. ./trace-boot --arch x86_64
  5741. ./trace2line --arch x86_64
  5742. less "$(./getvar --arch x86_64 run_dir)/trace-lines.txt"
  5743. ....
  5744. The format is as follows:
  5745. ....
  5746. 39368 _static_cpu_has arch/x86/include/asm/cpufeature.h:148
  5747. ....
  5748. Where:
  5749. * `39368`: number of consecutive times that a line ran. Makes the output much shorter and more meaningful
  5750. * `_static_cpu_has`: name of the function that contains the line
  5751. * `arch/x86/include/asm/cpufeature.h:148`: file and line
  5752. This could of course all be done with GDB, but it would likely be too slow to be practical.
  5753. TODO do even more awesome offline post-mortem analysis things, such as:
  5754. * detect if we are in userspace or kernelspace. Should be a simple matter of reading the
  5755. * read kernel data structures, and determine the current thread. Maybe we can reuse / extend the kernel's GDB Python scripts??
  5756. ==== QEMU record and replay
  5757. QEMU runs, unlike gem5, are not deterministic by default, however it does support a record and replay mechanism that allows you to replay a previous run deterministically.
  5758. This awesome feature allows you to examine a single run as many times as you would like until you understand everything:
  5759. ....
  5760. # Record a run.
  5761. ./run --eval-after '/rand_check.out;/poweroff.out;' --record
  5762. # Replay the run.
  5763. ./run --eval-after '/rand_check.out;/poweroff.out;' --replay
  5764. ....
  5765. A convenient shortcut to do both at once to test the feature is:
  5766. ....
  5767. ./qemu-rr --eval-after '/rand_check.out;/poweroff.out;'
  5768. ....
  5769. By comparing the terminal output of both runs, we can see that they are the exact same, including things which normally differ across runs:
  5770. * timestamps of dmesg output
  5771. * <<rand_check-out>> output
  5772. 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.
  5773. Documented at: https://github.com/qemu/qemu/blob/v2.12.0/docs/replay.txt
  5774. TODO: using `-r` as above leads to a kernel warning:
  5775. ....
  5776. rcu_sched detected stalls on CPUs/tasks
  5777. ....
  5778. TODO: replay deadlocks intermittently at disk operations, last kernel message:
  5779. ....
  5780. EXT4-fs (sda): re-mounted. Opts: block_validity,barrier,user_xattr
  5781. ....
  5782. TODO replay with network gets stuck:
  5783. ....
  5784. ./qemu-rr --eval-after 'ifup -a;wget -S google.com;/poweroff.out;'
  5785. ....
  5786. after the message:
  5787. ....
  5788. adding dns 10.0.2.3
  5789. ....
  5790. There is explicit network support on the QEMU patches, but either it is buggy or we are not using the correct magic options.
  5791. Solved on unmerged c42634d8e3428cfa60672c3ba89cabefc720cde9 from https://github.com/ispras/qemu/tree/rr-180725
  5792. 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
  5793. Then, when I tried with <<initrd>> and no disk:
  5794. ....
  5795. ./build-buildroot --arch aarch64 --initrd
  5796. ./qemu-rr --arch aarch64 --eval-after '/rand_check.out;/poweroff.out;' --initrd
  5797. ....
  5798. QEMU crashes with:
  5799. ....
  5800. ERROR:replay/replay-time.c:49:replay_read_clock: assertion failed: (replay_file && replay_mutex_locked())
  5801. ....
  5802. 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`?
  5803. Solved on unmerged c42634d8e3428cfa60672c3ba89cabefc720cde9 from https://github.com/ispras/qemu/tree/rr-180725
  5804. ===== QEMU reverse debugging
  5805. TODO get working.
  5806. 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[]:
  5807. ....
  5808. ./run --eval-after '/rand_check.out;/poweroff.out;' --record
  5809. ./run --eval-after '/rand_check.out;/poweroff.out;' --replay --wait-gdb
  5810. ....
  5811. On another shell:
  5812. ....
  5813. ./run-gdb start_kernel
  5814. ....
  5815. In GDB:
  5816. ....
  5817. n
  5818. n
  5819. n
  5820. n
  5821. reverse-continue
  5822. ....
  5823. and we are back at `start_kernel`
  5824. ==== QEMU trace multicore
  5825. TODO: is there any way to distinguish which instruction runs on each core? Doing:
  5826. ....
  5827. ./run --arch x86_64 --cpus 2 --eval '/poweroff.out' --trace exec_tb
  5828. ./qemu-trace2txt
  5829. ....
  5830. just appears to output both cores intertwined without any clear differentiation.
  5831. ==== gem5 tracing
  5832. gem5 provides also provides a tracing mechanism documented at: link:http://www.gem5.org/Trace_Based_Debugging[]:
  5833. ....
  5834. ./run --arch aarch64 --eval 'm5 exit' --emulator gem5 --trace Exec
  5835. less "$(./getvar --arch aarch64 run_dir)/trace.txt"
  5836. ....
  5837. Output the trace to stdout instead of a file:
  5838. ....
  5839. ./run --arch aarch64 --eval 'm5 exit' --emulator gem5 --trace Exec --trace-stdout
  5840. ....
  5841. This would produce a lot of output however, so you will likely not want that when tracing a Linux kernel boot instructions. But it can be very convenient for smaller traces.
  5842. List all available debug flags:
  5843. ....
  5844. ./run --arch aarch64 --gem5-exe-args='--debug-help' --emulator gem5
  5845. ....
  5846. but to understand most of them you have to look at the source code:
  5847. ....
  5848. less "$(./getvar gem5_source_dir)/src/cpu/SConscript"
  5849. less "$(./getvar gem5_source_dir)/src/cpu/exetrace.cc"
  5850. ....
  5851. The traces are generated from `DPRINTF(<trace-id>` calls scattered throughout the code.
  5852. As can be seen on the `Sconstruct`, `Exec` is just an alias that enables a set of flags.
  5853. Be warned, the trace is humongous, at 16Gb.
  5854. 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.
  5855. Enabling tracing made the runtime about 4x slower on the <<p51>>, with or without `.gz` compression.
  5856. The output format is of type:
  5857. ....
  5858. 25007000: system.cpu T0 : @start_kernel : stp
  5859. 25007000: system.cpu T0 : @start_kernel.0 : addxi_uop ureg0, sp, #-112 : IntAlu : D=0xffffff8008913f90
  5860. 25007500: system.cpu T0 : @start_kernel.1 : strxi_uop x29, [ureg0] : MemWrite : D=0x0000000000000000 A=0xffffff8008913f90
  5861. 25008000: system.cpu T0 : @start_kernel.2 : strxi_uop x30, [ureg0, #8] : MemWrite : D=0x0000000000000000 A=0xffffff8008913f98
  5862. 25008500: system.cpu T0 : @start_kernel.3 : addxi_uop sp, ureg0, #0 : IntAlu : D=0xffffff8008913f90
  5863. ....
  5864. There are two types of lines:
  5865. * full instructions, as the first line. Only shown if the `ExecMacro` flag is given.
  5866. * 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.
  5867. Breakdown:
  5868. * `25007500`: time count in some unit. Note how the microops execute at further timestamps.
  5869. * `system.cpu`: distinguishes between CPUs when there are more than one
  5870. * `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?
  5871. * `@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`.
  5872. * `.1` as in `@start_kernel.1`: index of the microop
  5873. * `stp`: instruction disassembly. Seems to use `.isa` files dispersed per arch, which is an in house format: http://gem5.org/ISA_description_system
  5874. * `strxi_uop x29, [ureg0]`: microop disassembly.
  5875. * `MemWrite : D=0x0000000000000000 A=0xffffff8008913f90`: a memory write microop:
  5876. ** `D` stands for data, and represents the value that was written to memory or to a register
  5877. ** `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.
  5878. The best way to verify all of this is to write some <<baremetal,baremetal code>>
  5879. Trace the source lines just like <<trace-source-lines,for QEMU>> with:
  5880. ....
  5881. ./trace-boot --arch aarch64 --emulator gem5
  5882. ./trace2line --arch aarch64 --emulator gem5
  5883. less "$(./getvar --arch aarch64 run_dir)/trace-lines.txt"
  5884. ....
  5885. 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?
  5886. === QEMU GUI is unresponsive
  5887. 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.
  5888. We have not managed to track this problem down yet, but the following workaround always works:
  5889. ....
  5890. Ctrl-Shift-U
  5891. Ctrl-C
  5892. root
  5893. ....
  5894. This started happening when we switched to building QEMU through Buildroot, and has not been observed on later Ubuntu.
  5895. Using text mode is another workaround if you don't need GUI features.
  5896. == gem5
  5897. Getting started at: <<gem5-buildroot-setup>>.
  5898. === gem5 vs QEMU
  5899. * advantages of gem5:
  5900. ** 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:
  5901. +
  5902. --
  5903. *** do much more realistic performance benchmarking with it, which makes absolutely no sense in QEMU, which is purely functional
  5904. *** make certain functional observations that are not possible in QEMU, e.g.:
  5905. **** 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.
  5906. **** spectre / meltdown:
  5907. ***** https://www.mail-archive.com/gem5-users@gem5.org/msg15319.html
  5908. ***** https://github.com/jlpresearch/gem5/tree/spectre-test
  5909. --
  5910. +
  5911. It is not of course truly cycle accurate, as that:
  5912. +
  5913. --
  5914. ** 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[]
  5915. ** would make the simulation even slower TODO confirm, by how much
  5916. --
  5917. +
  5918. but the approximation is reasonable.
  5919. +
  5920. 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.
  5921. ** 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
  5922. ** gem5 ARM at least appears to implement more low level CPU functionality than QEMU, e.g. QEMU only added EL2 in 2018: https://stackoverflow.com/questions/42824706/qemu-system-aarch64-entering-el1-when-emulating-a53-power-up See also: <<arm-exception-level>>
  5923. * disadvantage of gem5: slower than QEMU, see: <<benchmark-linux-kernel-boot>>
  5924. +
  5925. This implies that the user base is much smaller, since no Android devs.
  5926. +
  5927. 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:
  5928. +
  5929. --
  5930. ** the documentation is more scarce
  5931. ** it takes longer to support new hardware features
  5932. --
  5933. +
  5934. Well, not that AOSP is that much better anyways.
  5935. * not sure: gem5 has BSD license while QEMU has GPL
  5936. +
  5937. This suits chip makers that want to distribute forks with secret IP to their customers.
  5938. +
  5939. On the other hand, the chip makers tend to upstream less, and the project becomes more crappy in average :-)
  5940. === gem5 run benchmark
  5941. OK, this is why we used gem5 in the first place, performance measurements!
  5942. Let's see how many cycles https://en.wikipedia.org/wiki/Dhrystone[Dhrystone], which Buildroot provides, takes for a few different input parameters.
  5943. First build Dhrystone into the root filesystem:
  5944. ....
  5945. ./build-buildroot --config 'BR2_PACKAGE_DHRYSTONE=y'
  5946. ....
  5947. Then, a flexible setup is demonstrated at:
  5948. ....
  5949. ./gem5-bench-dhrystone
  5950. cat out/gem5-bench-dhrystone.txt
  5951. ....
  5952. Source: link:gem5-bench-dhrystone[]
  5953. Sample output:
  5954. ....
  5955. n cycles
  5956. 1000 12898577
  5957. 10000 23441629
  5958. 100000 128428617
  5959. ....
  5960. so as expected, the Dhrystone run with a larger input parameter `100000` took more cycles than the ones with smaller input parameters.
  5961. The `gem5-stats` commands output the approximate number of CPU cycles it took Dhrystone to run.
  5962. Another interesting example can be found at: link:gem5-bench-cache[].
  5963. A more naive and simpler to understand approach would be a direct:
  5964. ....
  5965. ./run --arch aarch64 --emulator gem5 --eval 'm5 checkpoint;m5 resetstats;dhrystone 10000;m5 exit'
  5966. ....
  5967. but the problem is that this method does not allow to easily run a different script without running the boot again, see: <<gem5-restore-new-script>>.
  5968. Now you can play a fun little game with your friends:
  5969. * pick a computational problem
  5970. * make a program that solves the computation problem, and outputs output to stdout
  5971. * write the code that runs the correct computation in the smallest number of cycles possible
  5972. To find out why your program is slow, a good first step is to have a look at <<stats-txt>> file.
  5973. ==== Skip extra benchmark instructions
  5974. A few imperfections of our <<gem5-run-benchmark,benchmarking method>> are:
  5975. * 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
  5976. * 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?
  5977. Solutions to these problems include:
  5978. * modify benchmark code with instrumentation directly, see <<m5ops-instructions>> for an example.
  5979. * monitor known addresses TODO possible? Create an example.
  5980. 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
  5981. Those problems should be insignificant if the benchmark runs for long enough however.
  5982. ==== gem5 system parameters
  5983. Besides optimizing a program for a given CPU setup, chip developers can also do the inverse, and optimize the chip for a given benchmark!
  5984. The rabbit hole is likely deep, but let's scratch a bit of the surface.
  5985. ===== Number of cores
  5986. ....
  5987. ./run --arch arm --cpus 2 --emulator gem5
  5988. ....
  5989. Check with:
  5990. ....
  5991. cat /proc/cpuinfo
  5992. getconf _NPROCESSORS_CONF
  5993. ....
  5994. ====== gem5 arm more than 8 cores
  5995. https://stackoverflow.com/questions/50248067/how-to-run-a-gem5-arm-aarch64-full-system-simulation-with-fs-py-with-more-than-8
  5996. Build the kernel with the <<gem5-arm-linux-kernel-patches>>, and then run:
  5997. ....
  5998. ./run \
  5999. --arch aarch64 \
  6000. --linux-build-id gem5-v4.15 \
  6001. --emulator gem5 \
  6002. --cpus 16 \
  6003. -- \
  6004. --param 'system.realview.gic.gem5_extensions = True' \
  6005. ;
  6006. ....
  6007. ===== gem5 cache size
  6008. https://stackoverflow.com/questions/49624061/how-to-run-gem5-simulator-in-fs-mode-without-cache/49634544#49634544
  6009. A quick `+./run --emulator gem5 -- -h+` leads us to the options:
  6010. ....
  6011. --caches
  6012. --l1d_size=1024
  6013. --l1i_size=1024
  6014. --l2cache
  6015. --l2_size=1024
  6016. --l3_size=1024
  6017. ....
  6018. But keep in mind that it only affects benchmark performance of the most detailed CPU types:
  6019. [options="header"]
  6020. |===
  6021. |arch |CPU type |caches used
  6022. |X86
  6023. |`AtomicSimpleCPU`
  6024. |no
  6025. |X86
  6026. |`DerivO3CPU`
  6027. |?*
  6028. |ARM
  6029. |`AtomicSimpleCPU`
  6030. |no
  6031. |ARM
  6032. |`HPI`
  6033. |yes
  6034. |===
  6035. {empty}*: couldn't test because of:
  6036. * https://stackoverflow.com/questions/49011096/how-to-switch-cpu-models-in-gem5-after-restoring-a-checkpoint-and-then-observe-t
  6037. Cache sizes can in theory be checked with the methods described at: link:https://superuser.com/questions/55776/finding-l2-cache-size-in-linux[]:
  6038. ....
  6039. getconf -a | grep CACHE
  6040. lscpu
  6041. cat /sys/devices/system/cpu/cpu0/cache/index2/size
  6042. ....
  6043. but for some reason the Linux kernel is not seeing the cache sizes:
  6044. * https://stackoverflow.com/questions/49008792/why-doesnt-the-linux-kernel-see-the-cache-sizes-in-the-gem5-emulator-in-full-sy
  6045. * http://gem5-users.gem5.narkive.com/4xVBlf3c/verify-cache-configuration
  6046. Behaviour breakdown:
  6047. * arm QEMU and gem5 (both `AtomicSimpleCPU` or `HPI`), x86 gem5: `/sys` files don't exist, and `getconf` and `lscpu` value empty
  6048. * x86 QEMU: `/sys` files exist, but `getconf` and `lscpu` values still empty
  6049. So we take a performance measurement approach instead:
  6050. ....
  6051. ./gem5-bench-cache --arch aarch64
  6052. cat "$(./getvar --arch aarch64 run_dir)/bench-cache.txt"
  6053. ....
  6054. which gives:
  6055. ....
  6056. cmd ./run --emulator gem5 --arch aarch64 --gem5-readfile "dhrystone 1000" --gem5-restore 1 -- --caches --l2cache --l1d_size=1024 --l1i_size=1024 --l2_size=1024 --l3_size=1024 --cpu-type=HPI --restore-with-cpu=HPI
  6057. time 23.82
  6058. exit_status 0
  6059. cycles 93284622
  6060. instructions 4393457
  6061. cmd ./run --emulator gem5 --arch aarch64 --gem5-readfile "dhrystone 1000" --gem5-restore 1 -- --caches --l2cache --l1d_size=1024kB --l1i_size=1024kB --l2_size=1024kB --l3_size=1024kB --cpu-type=HPI --restore-with-cpu=HPI
  6062. time 14.91
  6063. exit_status 0
  6064. cycles 10128985
  6065. instructions 4211458
  6066. cmd ./run --emulator gem5 --arch aarch64 --gem5-readfile "dhrystone 10000" --gem5-restore 1 -- --caches --l2cache --l1d_size=1024 --l1i_size=1024 --l2_size=1024 --l3_size=1024 --cpu-type=HPI --restore-with-cpu=HPI
  6067. time 51.87
  6068. exit_status 0
  6069. cycles 188803630
  6070. instructions 12401336
  6071. cmd ./run --emulator gem5 --arch aarch64 --gem5-readfile "dhrystone 10000" --gem5-restore 1 -- --caches --l2cache --l1d_size=1024kB --l1i_size=1024kB --l2_size=1024kB --l3_size=1024kB --cpu-type=HPI --restore-with-cpu=HPI
  6072. time 35.35
  6073. exit_status 0
  6074. cycles 20715757
  6075. instructions 12192527
  6076. cmd ./run --emulator gem5 --arch aarch64 --gem5-readfile "dhrystone 100000" --gem5-restore 1 -- --caches --l2cache --l1d_size=1024 --l1i_size=1024 --l2_size=1024 --l3_size=1024 --cpu-type=HPI --restore-with-cpu=HPI
  6077. time 339.07
  6078. exit_status 0
  6079. cycles 1176559936
  6080. instructions 94222791
  6081. cmd ./run --emulator gem5 --arch aarch64 --gem5-readfile "dhrystone 100000" --gem5-restore 1 -- --caches --l2cache --l1d_size=1024kB --l1i_size=1024kB --l2_size=1024kB --l3_size=1024kB --cpu-type=HPI --restore-with-cpu=HPI
  6082. time 240.37
  6083. exit_status 0
  6084. cycles 125666679
  6085. instructions 91738770
  6086. ....
  6087. We make the following conclusions:
  6088. * 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?
  6089. * 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.
  6090. ===== gem5 memory latency
  6091. TODO These look promising:
  6092. ....
  6093. --list-mem-types
  6094. --mem-type=MEM_TYPE
  6095. --mem-channels=MEM_CHANNELS
  6096. --mem-ranks=MEM_RANKS
  6097. --mem-size=MEM_SIZE
  6098. ....
  6099. TODO: now to verify this with the Linux kernel? Besides raw performance benchmarks.
  6100. ===== Memory size
  6101. ....
  6102. ./run --arch arm --memory 512M
  6103. ....
  6104. and verify inside the guest with:
  6105. ....
  6106. free -m
  6107. ....
  6108. ===== gem5 disk and network latency
  6109. TODO These look promising:
  6110. ....
  6111. --ethernet-linkspeed
  6112. --ethernet-linkdelay
  6113. ....
  6114. and also: `gem5-dist`: https://publish.illinois.edu/icsl-pdgem5/
  6115. ===== gem5 clock frequency
  6116. Clock frequency: TODO how does it affect performance in benchmarks?
  6117. ....
  6118. ./run --arch aarch64 --emulator gem5 -- --cpu-clock 10000000
  6119. ....
  6120. Check with:
  6121. ....
  6122. m5 resetstats
  6123. sleep 10
  6124. m5 dumpstats
  6125. ....
  6126. and then:
  6127. ....
  6128. ./gem5-stat --arch aarch64
  6129. ....
  6130. TODO: why doesn't this exist:
  6131. ....
  6132. ls /sys/devices/system/cpu/cpu0/cpufreq
  6133. ....
  6134. ==== Interesting benchmarks
  6135. Buildroot built-in libraries, mostly under Libraries > Other:
  6136. * Armadillo `C++`: linear algebra
  6137. * fftw: Fourier transform
  6138. * Flann
  6139. * GSL: various
  6140. * liblinear
  6141. * libspacialindex
  6142. * libtommath
  6143. * qhull
  6144. There are not yet enabled, but it should be easy to so, see: <<add-new-buildroot-packages>>
  6145. ===== BST vs heap
  6146. https://stackoverflow.com/questions/6147242/heap-vs-binary-search-tree-bst/29548834#29548834
  6147. Usage:
  6148. ....
  6149. ./run \
  6150. --arch aarch64 \
  6151. --eval-after '/gem5.sh' \
  6152. --emulator gem5 \
  6153. --gem5-readfile '/bst_vs_heap.out' \
  6154. ;
  6155. ./bst-vs-heap --arch aarch64 --emulator gem5 > bst_vs_heap.dat
  6156. ....
  6157. and then feed `bst_vs_heap.dat` into: https://github.com/cirosantilli/cpp-cheat/blob/9d0f77792fc8e55b20b6ee32018761ef3c5a3f2f/cpp/interactive/bst_vs_heap.gnuplot
  6158. Sources:
  6159. * link:bst-vs-heap[]
  6160. * link:userland/bst_vs_heap.cpp[]
  6161. ===== OpenMP
  6162. Implemented by GCC itself, so just a toolchain configuration, no external libs, and we enable it by default:
  6163. ....
  6164. /openmp.out
  6165. ....
  6166. Source: link:userland/openmp.c[]
  6167. ===== BLAS
  6168. Buildroot supports it, which makes everything just trivial:
  6169. ....
  6170. ./build-buildroot --config 'BR2_PACKAGE_OPENBLAS=y'
  6171. ./build-userland --has-package openblas -- openblas_hello
  6172. ./run --eval-after '/openblas_hello.out; echo $?'
  6173. ....
  6174. Outcome: the test passes:
  6175. ....
  6176. 0
  6177. ....
  6178. Source: link:userland/openblas.c[]
  6179. The test performs a general matrix multiplication:
  6180. ....
  6181. | 1.0 -3.0 | | 1.0 2.0 1.0 | | 0.5 0.5 0.5 | | 11.0 - 9.0 5.0 |
  6182. 1 * | 2.0 4.0 | * | -3.0 4.0 -1.0 | + 2 * | 0.5 0.5 0.5 | = | - 9.0 21.0 -1.0 |
  6183. | 1.0 -1.0 | | 0.5 0.5 0.5 | | 5.0 - 1.0 3.0 |
  6184. ....
  6185. This can be deduced from the Fortran interfaces at
  6186. ....
  6187. less "$(./getvar buildroot_build_build_dir)"/openblas-*/reference/dgemmf.f
  6188. ....
  6189. which we can map to our call as:
  6190. ....
  6191. C := alpha*op( A )*op( B ) + beta*C,
  6192. SUBROUTINE DGEMMF( TRANA, TRANB, M,N,K, ALPHA,A,LDA,B,LDB,BETA,C,LDC)
  6193. cblas_dgemm( CblasColMajor, CblasNoTrans, CblasTrans,3,3,2 ,1, A,3, B,3, 2 ,C,3 );
  6194. ....
  6195. ===== Eigen
  6196. Header only linear algebra library with a mainline Buildroot package:
  6197. ....
  6198. ./build-buildroot --config 'BR2_PACKAGE_EIGEN=y'
  6199. ./build-userland --has-package eigen -- eigen_hello
  6200. ....
  6201. Just create an array and print it:
  6202. ....
  6203. ./run --eval-after '/eigen_hello.out'
  6204. ....
  6205. Output:
  6206. ....
  6207. 3 -1
  6208. 2.5 1.5
  6209. ....
  6210. Source: link:userland/eigen_hello.cpp[]
  6211. This example just creates a matrix and prints it out.
  6212. Tested on: link:http://github.com/cirosantilli/linux-kernel-module-cheat/commit/a4bdcf102c068762bb1ef26c591fcf71e5907525[a4bdcf102c068762bb1ef26c591fcf71e5907525]
  6213. ===== PARSEC benchmark
  6214. 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.
  6215. There are two ways to run PARSEC with this repo:
  6216. * <<parsec-benchmark-without-parsecmgmt,without `pasecmgmt`>>, most likely what you want
  6217. * <<parsec-benchmark-with-parsecmgmt,with `pasecmgmt`>>
  6218. ====== PARSEC benchmark without parsecmgmt
  6219. ....
  6220. ./build --arch arm --download-dependencies gem5-buildroot parsec-benchmark
  6221. ./build-buildroot --arch arm --config 'BR2_PACKAGE_PARSEC_BENCHMARK=y'
  6222. ./run --arch arm --emulator gem5
  6223. ....
  6224. Once inside the guest, launch one of the `test` input sized benchmarks manually as in:
  6225. ....
  6226. cd /parsec/ext/splash2x/apps/fmm/run
  6227. ../inst/arm-linux.gcc/bin/fmm 1 < input_1
  6228. ....
  6229. To find run out how to run many of the benchmarks, have a look at the `test.sh` script of the `parse-benchmark` repo.
  6230. From the guest, you can also run it as:
  6231. ....
  6232. cd /parsec
  6233. ./test.sh
  6234. ....
  6235. but this might be a bit time consuming in gem5.
  6236. ====== PARSEC change the input size
  6237. Running a benchmark of a size different than `test`, e.g. `simsmall`, requires a rebuild with:
  6238. ....
  6239. ./build-buildroot \
  6240. --arch arm \
  6241. --config 'BR2_PACKAGE_PARSEC_BENCHMARK=y' \
  6242. --config 'BR2_PACKAGE_PARSEC_BENCHMARK_INPUT_SIZE="simsmall"' \
  6243. -- parsec_benchmark-reconfigure \
  6244. ;
  6245. ....
  6246. Large input may also require tweaking:
  6247. * <<br2_target_rootfs_ext2_size>> if the unpacked inputs are large
  6248. * <<memory-size>>, unless you want to meet the OOM killer, which is admittedly kind of fun
  6249. `test.sh` only contains the run commands for the `test` size, and cannot be used for `simsmall`.
  6250. 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:
  6251. ....
  6252. Running /root/linux-kernel-module-cheat/out/aarch64/buildroot/build/parsec-benchmark-custom/ext/splash2x/apps/ocean_ncp/inst/aarch64-linux.gcc/bin/ocean_ncp -n2050 -p1 -e1e-07 -r20000 -t28800
  6253. ....
  6254. and then tweak the command found in `test.sh` accordingly.
  6255. 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`).
  6256. The rebuild is required because we unpack input files on the host.
  6257. Separating input sizes also allows to create smaller images when only running the smaller benchmarks.
  6258. 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!
  6259. One option would be to do that inside the guest with QEMU.
  6260. Also, we can't generate all input sizes at once, because many of them have the same name and would overwrite one another...
  6261. PARSEC simply wasn't designed with non native machines in mind...
  6262. ====== PARSEC benchmark with parsecmgmt
  6263. Most users won't want to use this method because:
  6264. * running the `parsecmgmt` Bash scripts takes forever before it ever starts running the actual benchmarks on gem5
  6265. +
  6266. Running on QEMU is feasible, but not the main use case, since QEMU cannot be used for performance measurements
  6267. * 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)
  6268. It would be awesome if it were possible to use this method, since this is what Parsec supports officially, and so:
  6269. * you don't have to dig into what raw command to run
  6270. * there is an easy way to run all the benchmarks in one go to test them out
  6271. * you can just run any of the benchmarks that you want
  6272. but it simply is not feasible in gem5 because it takes too long.
  6273. If you still want to run this, try it out with:
  6274. ....
  6275. ./build-buildroot \
  6276. --arch aarch64 \
  6277. --config 'BR2_PACKAGE_PARSEC_BENCHMARK=y' \
  6278. --config 'BR2_PACKAGE_PARSEC_BENCHMARK_PARSECMGMT=y' \
  6279. --config 'BR2_TARGET_ROOTFS_EXT2_SIZE="3G"' \
  6280. -- parsec_benchmark-reconfigure \
  6281. ;
  6282. ....
  6283. And then you can run it just as you would on the host:
  6284. ....
  6285. cd /parsec/
  6286. bash
  6287. . env.sh
  6288. parsecmgmt -a run -p splash2x.fmm -i test
  6289. ....
  6290. ====== PARSEC uninstall
  6291. If you want to remove PARSEC later, Buildroot doesn't provide an automated package removal mechanism: <<remove-buildroot-packages>>, but the following procedure should be satisfactory:
  6292. ....
  6293. rm -rf \
  6294. "$(./getvar buildroot_download_dir)"/parsec-* \
  6295. "$(./getvar buildroot_build_dir)"/build/parsec-* \
  6296. "$(./getvar buildroot_build_dir)"/build/packages-file-list.txt \
  6297. "$(./getvar buildroot_build_dir)"/images/rootfs.* \
  6298. "$(./getvar buildroot_build_dir)"/target/parsec-* \
  6299. ;
  6300. ./build-buildroot --arch arm
  6301. ....
  6302. ====== PARSEC benchmark hacking
  6303. If you end up going inside link:submodules/parsec-benchmark[] to hack up the benchmark (you will!), these tips will be helpful.
  6304. 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.
  6305. A few workarounds are:
  6306. * develop in host first as much as you can. Our PARSEC fork supports it.
  6307. +
  6308. If you do this, don't forget to do a:
  6309. +
  6310. ....
  6311. cd "$(./getvar parsec_source_dir)"
  6312. git clean -xdf .
  6313. ....
  6314. before going for the cross compile build.
  6315. +
  6316. * patch Buildroot to work well, and keep cross compiling all the way. This should be totally viable, and we should do it.
  6317. +
  6318. Don't forget to explicitly rebuild PARSEC with:
  6319. +
  6320. ....
  6321. ./build-buildroot \
  6322. --arch arm \
  6323. --config 'BR2_PACKAGE_PARSEC_BENCHMARK=y' \
  6324. -- parsec_benchmark-reconfigure \
  6325. ;
  6326. ....
  6327. +
  6328. You may also want to test if your patches are still functionally correct inside of QEMU first, which is a faster emulator.
  6329. * 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
  6330. === gem5 kernel command line parameters
  6331. Analogous <<kernel-command-line-parameters,to QEMU>>:
  6332. ....
  6333. ./run --arch arm --kernel-cli 'init=/poweroff.out' --emulator gem5
  6334. ....
  6335. Internals: when we give `--command-line=` to gem5, it overrides default command lines, including some mandatory ones which are required to boot properly.
  6336. Our run script hardcodes the require options in the default `--command-line` and appends extra options given by `-e`.
  6337. To find the default options in the first place, we removed `--command-line` and ran:
  6338. ....
  6339. ./run --arch arm --emulator gem5
  6340. ....
  6341. and then looked at the line of the Linux kernel that starts with:
  6342. ....
  6343. Kernel command line:
  6344. ....
  6345. [[gem5-gdb]]
  6346. === gem5 GDB step debug
  6347. ==== gem5 GDB step debug kernel
  6348. Analogous <<gdb,to QEMU>>, on the first shell:
  6349. ....
  6350. ./run --arch arm --wait-gdb --emulator gem5
  6351. ....
  6352. On the second shell:
  6353. ....
  6354. ./run-gdb --arch arm --emulator gem5
  6355. ....
  6356. On a third shell:
  6357. ....
  6358. ./gem5-shell
  6359. ....
  6360. When you want to break, just do a `Ctrl-C` on GDB shell, and then `continue`.
  6361. 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>>.
  6362. ==== gem5 GDB step debug userland process
  6363. We are unable to use `gdbserver` because of networking: <<gem5-host-to-guest-networking>>
  6364. The alternative is to do as in <<gdb-step-debug-userland-processes>>.
  6365. Next, follow the exact same steps explained at <<gdb-step-debug-userland-non-init-without--d>>, but passing `-g` to every command as usual.
  6366. But then TODO (I'll still go crazy one of those days): for `arm`, while debugging `/myinsmod.out /hello.ko`, after then line:
  6367. ....
  6368. 23 if (argc < 3) {
  6369. 24 params = "";
  6370. ....
  6371. 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.
  6372. TODO:
  6373. ....
  6374. ./run-gdb-user --arch arm --emulator gem5 gem5-1.0/gem5/util/m5/m5 main
  6375. ....
  6376. breaks when `m5` is run on guest, but does not show the source code.
  6377. === gem5 checkpoint
  6378. 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.
  6379. Documentation: http://gem5.org/Checkpoints
  6380. ....
  6381. ./run --arch arm --emulator gem5
  6382. ....
  6383. In the guest, wait for the boot to end and run:
  6384. ....
  6385. m5 checkpoint
  6386. ....
  6387. where <<m5>> is a guest utility present inside the gem5 tree which we cross-compiled and installed into the guest.
  6388. To restore the checkpoint, kill the VM and run:
  6389. ....
  6390. ./run --arch arm --emulator gem5 --gem5-restore 1
  6391. ....
  6392. The `--gem5-restore` option restores the checkpoint that was created most recently.
  6393. Let's create a second checkpoint to see how it works, in guest:
  6394. ....
  6395. date >f
  6396. m5 checkpoint
  6397. ....
  6398. Kill the VM, and try it out:
  6399. ....
  6400. ./run --arch arm --emulator gem5 --gem5-restore 1
  6401. ....
  6402. Here we use `--gem5-restore 1` again, since the second snapshot we took is now the most recent one
  6403. Now in the guest:
  6404. ....
  6405. cat f
  6406. ....
  6407. contains the `date`. The file `f` wouldn't exist had we used the first checkpoint with `--gem5-restore 2`, which is the second most recent snapshot taken.
  6408. If you automate things with <<kernel-command-line-parameters>> as in:
  6409. ....
  6410. ./run --arch arm --eval 'm5 checkpoint;m5 resetstats;dhrystone 1000;m5 exit' --emulator gem5
  6411. ....
  6412. Then there is no need to pass the kernel command line again to gem5 for replay:
  6413. ....
  6414. ./run --arch arm --emulator gem5 --gem5-restore 1
  6415. ....
  6416. since boot has already happened, and the parameters are already in the RAM of the snapshot.
  6417. ==== gem5 checkpoint internals
  6418. Checkpoints are stored inside the <<m5out-directory>> at:
  6419. ....
  6420. "$(./getvar --emulator gem5 m5out_dir)/cpt.<checkpoint-time>"
  6421. ....
  6422. where `<checkpoint-time>` is the cycle number at which the checkpoint was taken.
  6423. `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
  6424. 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.
  6425. Therefore, just use our superior `--gem5-restore` flag, which uses directory timestamps to determine which checkpoint you created most recently.
  6426. 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.
  6427. [[gem5-restore-new-script]]
  6428. ==== gem5 checkpoint restore and run a different script
  6429. You want to automate running several tests from a single pristine post-boot state.
  6430. The problem is that boot takes forever, and after the checkpoint, the memory and disk states are fixed, so you can't for example:
  6431. * hack up an existing rc script, since the disk is fixed
  6432. * inject new kernel boot command line options, since those have already been put into memory by the bootloader
  6433. There is however a few loopholes, <<m5-readfile>> being the simplest, as it reads whatever is present on the host.
  6434. So we can do it like:
  6435. ....
  6436. # Boot, checkpoint and exit.
  6437. printf 'echo "setup run";m5 exit' > "$(./getvar gem5_readfile)"
  6438. ./run --emulator gem5 --eval 'm5 checkpoint;m5 readfile > a.sh;sh a.sh'
  6439. # Restore and run the first benchmark.
  6440. printf 'echo "first benchmark";m5 exit' > "$(./getvar gem5_readfile)"
  6441. ./run --emulator gem5 --gem5-restore 1
  6442. # Restore and run the second benchmark.
  6443. printf 'echo "second benchmark";m5 exit' > "$(./getvar gem5_readfile)"
  6444. ./run --emulator gem5 --gem5-restore 1
  6445. # If something weird happened, create an interactive shell to examine the system.
  6446. printf 'sh' > "$(./getvar gem5_readfile)"
  6447. ./run --emulator gem5 --gem5-restore 1
  6448. ....
  6449. Since this is such a common setup, we provide some helpers for it as described at <<gem5-run-benchmark>>:
  6450. * link:rootfs_overlay/gem5.sh[rootfs_overlay/gem5.sh]. This script is analogous to gem5's in-tree link:https://github.com/gem5/gem5/blob/2b4b94d0556c2d03172ebff63f7fc502c3c26ff8/configs/boot/hack_back_ckpt.rcS[hack_back_ckpt.rcS], but with less noise.
  6451. * `./run --gem5-readfile` is a convenient way to set the `m5 readfile`
  6452. Other loophole possibilities include:
  6453. * <<9p>>
  6454. * <<secondary-disk>>
  6455. * `expect` as mentioned at: https://stackoverflow.com/questions/7013137/automating-telnet-session-using-bash-scripts
  6456. +
  6457. ....
  6458. #!/usr/bin/expect
  6459. spawn telnet localhost 3456
  6460. expect "# $"
  6461. send "pwd\r"
  6462. send "ls /\r"
  6463. send "m5 exit\r"
  6464. expect eof
  6465. ....
  6466. +
  6467. This is ugly however as it is not deterministic.
  6468. https://www.mail-archive.com/gem5-users@gem5.org/msg15233.html
  6469. ==== gem5 restore checkpoint with a different CPU
  6470. gem5 can switch to a different CPU model when restoring a checkpoint.
  6471. 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.
  6472. An illustrative interactive run:
  6473. ....
  6474. ./run --arch arm --emulator gem5
  6475. ....
  6476. In guest:
  6477. ....
  6478. m5 checkpoint
  6479. ....
  6480. And then restore the checkpoint with a different CPU:
  6481. ....
  6482. ./run --arch arm --emulator gem5 --gem5-restore 1 -- --caches --restore-with-cpu=HPI
  6483. ....
  6484. === Pass extra options to gem5
  6485. Pass options to the `fs.py` script:
  6486. * get help:
  6487. +
  6488. ....
  6489. ./run --emulator gem5 -- -h
  6490. ....
  6491. * boot with the more detailed and slow `HPI` CPU model:
  6492. +
  6493. ....
  6494. ./run --arch arm --emulator gem5 -- --caches --cpu-type=HPI
  6495. ....
  6496. Pass options to the `gem5` executable itself:
  6497. * get help:
  6498. +
  6499. ....
  6500. ./run --gem5-exe-args='-h' --emulator gem5
  6501. ....
  6502. === gem5 exit after a number of instructions
  6503. Quit the simulation after `1024` instructions:
  6504. ....
  6505. ./run --emulator gem5 -- -I 1024
  6506. ....
  6507. Can be nicely checked with <<gem5-tracing>>.
  6508. Cycles instead of instructions:
  6509. ....
  6510. ./run --emulator gem5 -- --memory 1024
  6511. ....
  6512. Otherwise the simulation runs forever by default.
  6513. === m5ops
  6514. m5ops are magic instructions which lead gem5 to do magic things, like quitting or dumping stats.
  6515. Documentation: http://gem5.org/M5ops
  6516. There are two main ways to use m5ops:
  6517. * <<m5>>
  6518. * <<m5ops-instructions>>
  6519. `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.
  6520. `m5` cannot should / should not be used however:
  6521. * in bare metal setups
  6522. * 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.
  6523. +
  6524. Why not just hardcode some <<m5ops-instructions>> as in our example instead, since you are going to modify the source of the benchmark anyways?
  6525. ==== m5
  6526. `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>>
  6527. Its source is present in the gem5 tree: https://github.com/gem5/gem5/blob/6925bf55005c118dc2580ba83e0fa10b31839ef9/util/m5/m5.c
  6528. It is possible to guess what most tools do from the corresponding <<m5ops>>, but let's at least document the less obvious ones here.
  6529. ===== m5 exit
  6530. End the simulation.
  6531. Sane Python scripts will exit gem5 with status 0, which is what `fs.py` does.
  6532. ===== m5 fail
  6533. End the simulation with a failure exit event:
  6534. ....
  6535. m5 fail 1
  6536. ....
  6537. Sane Python scripts would use that as the exit status of gem5, which would be useful for testing purposes, but `fs.py` at 200281b08ca21f0d2678e23063f088960d3c0819 just prints an error message:
  6538. ....
  6539. Simulated exit code not 0! Exit code is 1
  6540. ....
  6541. and exits with status 0.
  6542. We then parse that string ourselves in link:run[] and exit with the correct status...
  6543. TODO: it used to be like that, but it actually got changed to just print the message. Why? https://gem5-review.googlesource.com/c/public/gem5/+/4880
  6544. `m5 fail` is just a superset of `m5 exit`, which is just:
  6545. ....
  6546. m5 fail 0
  6547. ....
  6548. as can be seen from the source: https://github.com/gem5/gem5/blob/50a57c0376c02c912a978c4443dd58caebe0f173/src/sim/pseudo_inst.cc#L303
  6549. ===== m5 writefile
  6550. Send a guest file to the host. <<9p>> is a more advanced alternative.
  6551. Guest:
  6552. ....
  6553. echo mycontent > myfileguest
  6554. m5 writefile myfileguest myfilehost
  6555. ....
  6556. Host:
  6557. ....
  6558. cat "$(./getvar --arch aarch64 --emulator gem5 m5out_dir)/myfilehost"
  6559. ....
  6560. Does not work for subdirectories, gem5 crashes:
  6561. ....
  6562. m5 writefile myfileguest mydirhost/myfilehost
  6563. ....
  6564. ===== m5 readfile
  6565. Read a host file pointed to by the `fs.py --script` option to stdout.
  6566. https://stackoverflow.com/questions/49516399/how-to-use-m5-readfile-and-m5-execfile-in-gem5/49538051#49538051
  6567. Host:
  6568. ....
  6569. date > "$(./getvar gem5_readfile)"
  6570. ....
  6571. Guest:
  6572. ....
  6573. m5 readfile
  6574. ....
  6575. Outcome: date shows on guest.
  6576. ===== m5 initparam
  6577. Ermm, just another <<m5-readfile>> that only takes integers and only from CLI options? Is this software so redundant?
  6578. Host:
  6579. ....
  6580. ./run --emulator gem5 --gem5-restore 1 -- --initparam 13
  6581. ./run --emulator gem5 --gem5-restore 1 -- --initparam 42
  6582. ....
  6583. Guest:
  6584. ....
  6585. m5 initparm
  6586. ....
  6587. Outputs the given paramter.
  6588. ===== m5 execfile
  6589. Trivial combination of `m5 readfile` + execute the script.
  6590. Host:
  6591. ....
  6592. printf '#!/bin/sh
  6593. echo asdf
  6594. ' > "$(./getvar gem5_readfile)"
  6595. ....
  6596. Guest:
  6597. ....
  6598. touch /tmp/execfile
  6599. chmod +x /tmp/execfile
  6600. m5 execfile
  6601. ....
  6602. Outcome:
  6603. ....
  6604. adsf
  6605. ....
  6606. ==== m5ops instructions
  6607. 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:
  6608. ....
  6609. # checkpoint
  6610. /m5ops.out c
  6611. # dumpstats
  6612. /m5ops.out d
  6613. # exit
  6614. /m5ops.out e
  6615. # dump resetstats
  6616. /m5ops.out r
  6617. ....
  6618. Sources:
  6619. * link:userland/m5ops.h[]
  6620. * link:userland/m5ops.c[]
  6621. 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.
  6622. In theory, the cleanest way to add m5ops to your benchmarks would be to do exactly what the `m5` tool does:
  6623. * include link:https://github.com/gem5/gem5/blob/05c4c2b566ce351ab217b2bd7035562aa7a76570/include/gem5/asm/generic/m5ops.h[`include/gem5/asm/generic/m5ops.h`]
  6624. * link with the `.o` file under `util/m5` for the correct arch, e.g. `m5op_arm_A64.o` for aarch64.
  6625. 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`.
  6626. Related: https://www.mail-archive.com/gem5-users@gem5.org/msg15418.html
  6627. ===== m5ops instructions interface
  6628. Let's study how <<m5>> uses them:
  6629. * 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
  6630. * 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
  6631. * 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.
  6632. We notice that there are two different implementations for each arch:
  6633. * magic instructions, which don't exist in the corresponding arch
  6634. * magic memory addresses on a given page
  6635. 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.
  6636. Then, in aarch64 magic instructions for example, the lines:
  6637. ....
  6638. .macro m5op_func, name, func, subfunc
  6639. .globl \name
  6640. \name:
  6641. .long 0xff000110 | (\func << 16) | (\subfunc << 12)
  6642. ret
  6643. ....
  6644. define a simple function function for each m5op. Here we see that:
  6645. * `0xff000110` is a base mask for the magic non-existing instruction
  6646. * `\func` and `\subfunc` are OR-applied on top of the base mask, and define m5op this is.
  6647. +
  6648. Those values will loop over the magic constants defined in `m5ops.h` with the deferred preprocessor idiom.
  6649. +
  6650. For example, `exit` is `0x21` due to:
  6651. +
  6652. ....
  6653. #define M5OP_EXIT 0x21
  6654. ....
  6655. Finally, `m5.c` calls the defined functions as in:
  6656. ....
  6657. m5_exit(ints[0]);
  6658. ....
  6659. Therefore, the runtime "argument" that gets passed to the instruction, e.g. the delay in ticks until the exit for `m5 exit`, gets passed directly through the link:https://en.wikipedia.org/wiki/Calling_convention#ARM_(A64)[aarch64 calling convention].
  6660. Keep in mind that for all archs, `m5.c` does the calls with 64-bit integers:
  6661. ....
  6662. uint64_t ints[2] = {0,0};
  6663. parse_int_args(argc, argv, ints, argc);
  6664. m5_fail(ints[1], ints[0]);
  6665. ....
  6666. Therefore, for example:
  6667. * aarch64 uses `x0` for the first argument and `x1` for the second, since each is 64 bits log already
  6668. * arm uses `r0` and `r1` for the first argument, and `r2` and `r3` for the second, since each register is only 32 bits long
  6669. That convention specifies that `x0` to `x7` contain the function arguments, so `x0` contains the first argument, and `x1` the second.
  6670. In our `m5ops` example, we just hardcode everything in the assembly one-liners we are producing.
  6671. We ignore the `\subfunc` since it is always 0 on the ops that interest us.
  6672. ===== m5op annotations
  6673. `include/gem5/asm/generic/m5ops.h` also describes some annotation instructions.
  6674. What they mean: https://stackoverflow.com/questions/50583962/what-are-the-gem5-annotations-mops-magic-instructions-and-how-to-use-them
  6675. === gem5 arm Linux kernel patches
  6676. https://gem5.googlesource.com/arm/linux/ contains an ARM Linux kernel forks with a few gem5 specific Linux kernel patches on top of mainline created by ARM Holdings on top of a few upstream kernel releases.
  6677. The patches are optional: the vanilla kernel does boot. But they add some interesting gem5-specific optimizations, instrumentations and device support.
  6678. The patches also <<notable-alternate-gem5-kernel-configs,add defconfigs>> that are known to work well with gem5.
  6679. E.g. for arm v4.9 there is: link:https://gem5.googlesource.com/arm/linux/+/917e007a4150d26a0aa95e4f5353ba72753669c7/arch/arm/configs/gem5_defconfig[].
  6680. In order to use those patches and their associated configs, and, we recommend using <<linux-kernel-build-variants>> as:
  6681. ....
  6682. git -C "$(./getvar linux_source_dir)" fetch https://gem5.googlesource.com/arm/linux gem5/v4.15:gem5/v4.15
  6683. git -C "$(./getvar linux_source_dir)" checkout gem5/v4.15
  6684. ./build-linux \
  6685. --arch aarch64 \
  6686. --custom-config-file-gem5 \
  6687. --linux-build-id gem5-v4.15 \
  6688. ;
  6689. git -C "$(./getvar linux_source_dir)" checkout -
  6690. ....
  6691. It is obviously not possible to understand what they actually do from their commit message, so let's explain them one by one here as we understand them:
  6692. * `drm: Add component-aware simple encoder` allows you to see images through VNC: <<gem5-graphic-mode>>
  6693. * `gem5: Add support for gem5's extended GIC mode` adds support for more than 8 cores: <<gem5-arm-more-than-8-cores>>
  6694. === m5out directory
  6695. When you run gem5, it generates an `m5out` directory at:
  6696. ....
  6697. echo $(./getvar --arch arm --emulator gem5 m5out_dir)"
  6698. ....
  6699. The location of that directory can be set with `./gem5.opt -d`, and defaults to `./m5out`.
  6700. The files in that directory contains some very important information about the run, and you should become familiar with every one of them.
  6701. ==== system.terminal
  6702. Contains UART output, both from the Linux kernel or from the baremetal system.
  6703. Can also be seen live on <<m5term>>.
  6704. ==== stats.txt
  6705. This file contains important statistics about the run:
  6706. ....
  6707. cat "$(./getvar --arch aarch64 m5out_dir)/stats.txt"
  6708. ....
  6709. Whenever we run `m5 dumpstats` or `m5 exit`, a section with the following format is added to that file:
  6710. ....
  6711. ---------- Begin Simulation Statistics ----------
  6712. [the stats]
  6713. ---------- End Simulation Statistics ----------
  6714. ....
  6715. That file contains several important execution metrics, e.g. number of cycles and several types of cache misses:
  6716. ....
  6717. system.cpu.numCycles
  6718. system.cpu.dtb.inst_misses
  6719. system.cpu.dtb.inst_hits
  6720. ....
  6721. ==== rdtsc
  6722. Let's have some fun and try to correlate the gem5 cycle count `system.cpu.numCycles` with the link:https://en.wikipedia.org/wiki/Time_Stamp_Counter[x86 `rdtsc` instruction] that is supposed to do the same thing:
  6723. ....
  6724. ./build-userland -- rdtsc
  6725. ./run --eval '/rdtsc.out;m5 exit;' --emulator gem5
  6726. ./gem5-stat
  6727. ....
  6728. Source: link:userland/rdtsc.c[]
  6729. `rdtsc` outputs a cycle count which we compare with gem5's `gem5-stat`:
  6730. * `3828578153`: `rdtsc`
  6731. * `3830832635`: `gem5-stat`
  6732. which gives pretty close results, and serve as a nice sanity check that the cycle counter is coherent.
  6733. 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`.
  6734. Bibliography:
  6735. * https://en.wikipedia.org/wiki/Time_Stamp_Counter
  6736. * https://stackoverflow.com/questions/9887839/clock-cycle-count-wth-gcc/9887979
  6737. ===== pmccntr
  6738. TODO We didn't manage to find a working ARM analogue to <<rdtsc>>: link:kernel_modules/pmccntr.c[] is oopsing, and even it if weren't, it likely won't give the cycle count since boot since it needs to be activate before it starts counting anything:
  6739. * https://stackoverflow.com/questions/40454157/is-there-an-equivalent-instruction-to-rdtsc-in-arm
  6740. * https://stackoverflow.com/questions/31620375/arm-cortex-a7-returning-pmccntr-0-in-kernel-mode-and-illegal-instruction-in-u/31649809#31649809
  6741. * https://blog.regehr.org/archives/794
  6742. ==== config.ini
  6743. The `config.ini` file, contains a very good high level description of the system:
  6744. ....
  6745. less $(./getvar --arch arm --emulator gem5 m5out_dir)"
  6746. ....
  6747. That file contains a tree representation of the system, sample excerpt:
  6748. ....
  6749. [root]
  6750. type=Root
  6751. children=system
  6752. full_system=true
  6753. [system]
  6754. type=ArmSystem
  6755. children=cpu cpu_clk_domain
  6756. auto_reset_addr_64=false
  6757. semihosting=Null
  6758. [system.cpu]
  6759. type=AtomicSimpleCPU
  6760. children=dstage2_mmu dtb interrupts isa istage2_mmu itb tracer
  6761. branchPred=Null
  6762. [system.cpu_clk_domain]
  6763. type=SrcClockDomain
  6764. clock=500
  6765. ....
  6766. Each node has:
  6767. * a list of child nodes, e.g. `system` is a child of `root`, and both `cpu` and `cpu_clk_domain` are children of `system`
  6768. * a list of parameters, e.g. `system.semihosting` is `Null`, which means that <<semihosting>> was turned off
  6769. ** the `type` parameter shows is present on every node, and it maps to a `Python` object that inherits from `SimObject`.
  6770. +
  6771. For example, `AtomicSimpleCPU` maps is defined at link:https://github.com/gem5/gem5/blob/05c4c2b566ce351ab217b2bd7035562aa7a76570/src/cpu/simple/AtomicSimpleCPU.py#L45[src/cpu/simple/AtomicSimpleCPU.py].
  6772. You can also get a simplified graphical view of the tree with:
  6773. ....
  6774. xdg-open "$(./getvar --arch arm --emulator gem5 m5out_dir)/config.dot.pdf"
  6775. ....
  6776. Modifying the `config.ini` file manually does nothing since it gets overwritten every time.
  6777. Set custom configs with the `--param` option of `fs.py`, e.g. we can make gem5 wait for GDB to connect with:
  6778. ....
  6779. fs.py --param 'system.cpu[0].wait_for_remote_gdb = True'
  6780. ....
  6781. More complex settings involving new classes however require patching the config files, although it is easy to hack this up. See for example: link:patches/manual/gem5-semihost.patch[].
  6782. === m5term
  6783. We use the `m5term` in-tree executable to connect to the terminal instead of a direct `telnet`.
  6784. If you use `telnet` directly, it mostly works, but certain interactive features don't, e.g.:
  6785. * up and down arrows for history navigation
  6786. * tab to complete paths
  6787. * `Ctrl-C` to kill processes
  6788. TODO understand in detail what `m5term` does differently than `telnet`.
  6789. === gem5 Python scripts without rebuild
  6790. We have made a crazy setup that allows you to just `cd` into `submodules/gem5`, and edit Python scripts directly there.
  6791. This is not normally possible with Buildroot, since normal Buildroot packages first copy files to the output directory (`$(./getvar -a <arch> buildroot_build_build_dir)/<pkg>`), and then build there.
  6792. So if you modified the Python scripts with this setup, you would still need to `./build` to copy the modified files over.
  6793. For gem5 specifically however, we have hacked up the build so that we `cd` into the `submodules/gem5` tree, and then do an link:https://www.mail-archive.com/gem5-users@gem5.org/msg15421.html[out of tree] build to `out/common/gem5`.
  6794. 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.
  6795. Using Buildroot for gem5 is still convenient because we use it to:
  6796. * to cross build `m5` for us
  6797. * check timestamps and skip the gem5 build when it is not requested
  6798. 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.
  6799. === gem5 fs_bigLITTLE
  6800. By default, we use `configs/example/fs.py` script.
  6801. The `--gem5-script biglittle` option enables the alternative `configs/example/arm/fs_bigLITTLE.py` script instead.
  6802. First apply:
  6803. ....
  6804. patch -d "$(./getvar gem5_source_dir)" -p 1 < patches/manual/gem5-biglittle.patch
  6805. ....
  6806. then:
  6807. ....
  6808. ./run --arch aarch64 --emulator gem5 --gem5-script biglittle
  6809. ....
  6810. Advantages over `fs.py`:
  6811. * more representative of mobile ARM SoCs, which almost always have big little cluster
  6812. * simpler than `fs.py`, and therefore easier to understand and modify
  6813. Disadvantages over `fs.py`:
  6814. * only works for ARM, not other archs
  6815. * not as many configuration options as `fs.py`, many things are hardcoded
  6816. 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`.
  6817. 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.
  6818. Tested on: link:http://github.com/cirosantilli/linux-kernel-module-cheat/commit/18c1c823feda65f8b54cd38e261c282eee01ed9f[18c1c823feda65f8b54cd38e261c282eee01ed9f]
  6819. === gem5 unit tests
  6820. https://stackoverflow.com/questions/52279971/how-to-run-the-gem5-unit-tests
  6821. Not currently exposed here.
  6822. == Buildroot
  6823. === Introduction to Buildroot
  6824. link:https://en.wikipedia.org/wiki/Buildroot[Buildroot] is a set of Make scripts that download and compile from source compatible versions of:
  6825. * GCC
  6826. * Linux kernel
  6827. * C standard library: Buildroot supports several implementations, we use link:https://en.wikipedia.org/wiki/GNU_C_Library[glibc] by default
  6828. * link:https://en.wikipedia.org/wiki/BusyBox[BusyBox]: provides the shell and basic command line utilities
  6829. It therefore produces a pristine, blob-less, debuggable setup, where all moving parts are configured to work perfectly together.
  6830. Perhaps the awesomeness of Buildroot only sinks in once you notice that all it takes is 4 commands as explained at https://stackoverflow.com/questions/47557262/how-to-download-the-torvalds-linux-kernel-master-recompile-it-and-boot-it-wi/49349237#49349237
  6831. ....
  6832. git clone https://github.com/buildroot/buildroot
  6833. cd buildroot
  6834. git checkout 2018.02
  6835. make qemu_aarch64_virt_defconfig
  6836. make olddefconfig
  6837. time make BR2_JLEVEL="$(nproc)"
  6838. qemu-system-aarch64 -M virt -cpu cortex-a57 -nographic -smp 1 -kernel output/images/Image -append "root=/dev/vda console=ttyAMA0" -netdev user,id=eth0 -device virtio-net-device,netdev=eth0 -drive file=output/images/rootfs.ext4,if=none,format=raw,id=hd0 -device virtio-blk-device,drive=hd0
  6839. ....
  6840. This repo basically wraps around that, and tries to make everything even more awesome for kernel developers.
  6841. The downsides of Buildroot are:
  6842. * the first build takes a while, but it is well worth it
  6843. * the selection of software packages is relatively limited if compared to Debian, e.g. no Java or Python package in guest out of the box.
  6844. +
  6845. In theory, any software can be packaged, and the Buildroot side is easy.
  6846. +
  6847. The hard part is dealing with crappy third party build systems and huge dependency chains.
  6848. === Custom Buildroot configs
  6849. We provide the following mechanisms:
  6850. * `./build-buildroot --config-fragment data/br2`: append the Buildroot configuration file `data/br2` to a single build. Must be passed every time you run `./build`. The format is the same as link:buildroot_config/default[].
  6851. * `./build-buildroot --config 'BR2_SOME_OPTION="myval"'`: append a single option to a single build.
  6852. For example, if you decide to <<enable-buildroot-compiler-optimizations>> after an initial build is finished, you must <<clean-the-build>> and rebuild:
  6853. ....
  6854. ./build-buildroot \
  6855. --config 'BR2_OPTIMIZE_3=y' \
  6856. --config 'BR2_PACKAGE_SAMPLE_PACKAGE=y' \
  6857. --
  6858. sample_package-dirclean \
  6859. sample_package-reconfigure \
  6860. ;
  6861. ....
  6862. as explained at: https://buildroot.org/downloads/manual/manual.html#rebuild-pkg
  6863. The clean is necessary because the source files didn't change, so `make` would just check the timestamps and not build anything.
  6864. You will then likely want to make those more permanent with: <<default-command-line-arguments>>
  6865. ==== Enable Buildroot compiler optimizations
  6866. If you are benchmarking compiled programs instead of hand written assembly, remember that we configure Buildroot to disable optimizations by default with:
  6867. ....
  6868. BR2_OPTIMIZE_0=y
  6869. ....
  6870. to improve the debugging experience.
  6871. You will likely want to change that to:
  6872. ....
  6873. BR2_OPTIMIZE_3=y
  6874. ....
  6875. Our link:kernel_modules/user[] package correctly forwards the Buildroot options to the build with `$(TARGET_CONFIGURE_OPTS)`, so you don't have to do any extra work.
  6876. Don't forget to do that if you are <<add-new-buildroot-packages,adding a new package>> with your own build system.
  6877. Then, you have two choices:
  6878. * if you already have a full `-O0` build, you can choose to rebuild just your package of interest to save some time as described at: <<custom-buildroot-configs>>
  6879. +
  6880. ....
  6881. ./build-buildroot \
  6882. --config 'BR2_OPTIMIZE_3=y' \
  6883. --config 'BR2_PACKAGE_SAMPLE_PACKAGE=y' \
  6884. -- \
  6885. sample_package-dirclean \
  6886. sample_package-reconfigure \
  6887. ;
  6888. ....
  6889. +
  6890. However, this approach might not be representative since calls to an unoptimized libc and other libraries will have a negative performance impact.
  6891. +
  6892. Maybe you can get away with rebuilding libc, but I'm not sure that it will work properly.
  6893. +
  6894. Kernel-wise it should be fine though due to: <<kernel-o0>>
  6895. * <<clean-the-build,clean the build>> and rebuild from scratch:
  6896. +
  6897. ....
  6898. mv out out~
  6899. ./build-buildroot --config 'BR2_OPTIMIZE_3=y'
  6900. ....
  6901. === Find Buildroot options with make menuconfig
  6902. `make menuconfig` is a convenient way to find Buildroot configurations:
  6903. ....
  6904. cd "$(./getvar buildroot_build_dir)"
  6905. make menuconfig
  6906. ....
  6907. Hit `/` and search for the settings.
  6908. Save and quit.
  6909. ....
  6910. diff -u .config.olg .config
  6911. ....
  6912. Then copy and paste the diff additions to link:buildroot_config/default[] to make them permanent.
  6913. === Change user
  6914. At startup, we login automatically as the `root` user.
  6915. 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:
  6916. ....
  6917. login user0
  6918. ....
  6919. and password:
  6920. ....
  6921. a
  6922. ....
  6923. Then test that the user changed with:
  6924. ....
  6925. id
  6926. ....
  6927. which gives:
  6928. ....
  6929. uid=1000(user0) gid=1000(user0) groups=1000(user0)
  6930. ....
  6931. ==== Login as a non-root user without password
  6932. Replace on `inittab`:
  6933. ....
  6934. ::respawn:-/bin/sh
  6935. ....
  6936. with:
  6937. ....
  6938. ::respawn:-/bin/login -f user0
  6939. ....
  6940. `-f` forces login without asking for the password.
  6941. === Add new Buildroot packages
  6942. First, see if you can't get away without actually adding a new package, for example:
  6943. * if you have a standalone C file with no dependencies besides the C standard library to be compiled with GCC, just add a new file under link:kernel_modules/user[] and you are done
  6944. * if you have a dependency on a library, first check if Buildroot doesn't have a package for it already with `ls buildroot/package`. If yes, just enable that package as explained at: <<custom-buildroot-configs>>
  6945. If none of those methods are flexible enough for you, you can just fork or hack up link:buildroot_packages/sample_package[] the sample package to do what you want.
  6946. For how to use that package, see: <<buildroot_packages-directory>>.
  6947. Then iterate trying to do what you want and reading the manual until it works: https://buildroot.org/downloads/manual/manual.html
  6948. === Remove Buildroot packages
  6949. Once you've built a package in to the image, there is no easy way to remove it.
  6950. Documented at: link:https://github.com/buildroot/buildroot/blob/2017.08/docs/manual/rebuilding-packages.txt#L90[]
  6951. Also mentioned at: https://stackoverflow.com/questions/47320800/how-to-clean-only-target-in-buildroot
  6952. See this for a sample manual workaround: <<parsec-uninstall>>.
  6953. === BR2_TARGET_ROOTFS_EXT2_SIZE
  6954. When adding new large package to the Buildroot root filesystem, it may fail with the message:
  6955. ....
  6956. Maybe you need to increase the filesystem size (BR2_TARGET_ROOTFS_EXT2_SIZE)
  6957. ....
  6958. The solution is to simply add:
  6959. ....
  6960. ./build-buildroot --config 'BR2_TARGET_ROOTFS_EXT2_SIZE="512M"'
  6961. ....
  6962. where 512Mb is "large enough".
  6963. Note that dots cannot be used as in `1.5G`, so just use Megs as in `1500M` instead.
  6964. Unfortunately, TODO we don't have a perfect way to find the right value for `BR2_TARGET_ROOTFS_EXT2_SIZE`. One good heuristic is:
  6965. ....
  6966. du -hsx "$(./getvar --arch arm target_dir)"
  6967. ....
  6968. Some promising ways to overcome this problem include:
  6969. * <<squashfs>>
  6970. TODO benchmark: would gem5 suffer a considerable disk read performance hit due to decompressing SquashFS?
  6971. * libguestfs: link:https://serverfault.com/questions/246835/convert-directory-to-qemu-kvm-virtual-disk-image/916697#916697[], in particular link:http://libguestfs.org/guestfish.1.html#vfs-minimum-size[`vfs-minimum-size`]
  6972. * use methods described at: <<gem5-restore-new-script>> instead of putting builds on the root filesystem
  6973. Bibliography: https://stackoverflow.com/questions/49211241/is-there-a-way-to-automatically-detect-the-minimum-required-br2-target-rootfs-ex
  6974. ==== SquashFS
  6975. link:https://en.wikipedia.org/wiki/SquashFS[SquashFS] creation with `mksquashfs` does not take fixed sizes, and I have successfully booted from it, but it is readonly, which is unacceptable.
  6976. But then we could mount link:https://wiki.debian.org/ramfs[ramfs] on top of it with <<overlayfs>> to make it writable, but my attempts failed exactly as mentioned at <<overlayfs>>.
  6977. This is the exact unanswered question: https://unix.stackexchange.com/questions/343484/mounting-squashfs-image-with-read-write-overlay-for-rootfs
  6978. [[rpath]]
  6979. === Buildroot rebuild is slow when the root filesystem is large
  6980. Buildroot is not designed for large root filesystem images, and the rebuild becomes very slow when we add a large package to it.
  6981. 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`
  6982. 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:
  6983. ....
  6984. >>> Sanitizing RPATH in target tree
  6985. ....
  6986. which contributed to a large part of the slowness.
  6987. Test how Buildroot deals with many files with:
  6988. ....
  6989. ./build-buildroot \
  6990. --config 'BR2_PACKAGE_LKMC_MANY_FILES=y' \
  6991. -- \
  6992. lkmc_many_files-reconfigure \
  6993. |& \
  6994. ts -i '%.s' \
  6995. ;
  6996. ./build-buildroot |& ts -i '%.s'
  6997. ....
  6998. 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.
  6999. === Report upstream bugs
  7000. 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.
  7001. For example, QEMU developers will only want to see the final QEMU command that you are running.
  7002. 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.
  7003. We make that easy by building commands as strings, and then echoing them before evaling.
  7004. So for example when you run:
  7005. ....
  7006. ./run --arch arm
  7007. ....
  7008. the very first stdout output of that script is the actual QEMU command that is being run.
  7009. The command is also saved to a file for convenience:
  7010. ....
  7011. cat "$(./getvar --arch arm run_cmd_file)"
  7012. ....
  7013. which you can manually modify and execute during your experiments later:
  7014. ....
  7015. vim "$(./getvar --arch arm run_cmd_file)"
  7016. ./"$(./getvar --arch arm run_cmd_file)"
  7017. ....
  7018. Next, you will also want to give the relevant images to save them time, see: <<release-zip>>.
  7019. 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.
  7020. For QEMU and Buildroot, we have the following convenient setups respectively:
  7021. * https://github.com/cirosantilli/qemu-test
  7022. * https://github.com/cirosantilli/buildroot/tree/in-tree-package-master
  7023. == Baremetal
  7024. Getting started at: <<baremetal-setup>>
  7025. === Baremetal GDB step debug
  7026. GDB step debug works on baremetal exactly as it does on the Linux kernel, except that is is even cooler here since we can easily control and understand every single instruction that is being run!
  7027. For example, on the first shell:
  7028. ....
  7029. ./run --arch arm --baremetal interactive/prompt --wait-gdb
  7030. ....
  7031. then on the second shell:
  7032. ....
  7033. ./run-gdb --arch arm --baremetal interactive/prompt -- main
  7034. ....
  7035. Or if you are a <<tmux,tmux pro>>, do everything in one go with:
  7036. ....
  7037. ./run --arch arm --baremetal interactive/prompt --wait-gdb --tmux-args main
  7038. ....
  7039. Alternatively, to start from the very first executed instruction of our tiny <<baremetal-bootloaders>>:
  7040. ....
  7041. ./run --arch arm --baremetal interactive/prompt --wait-gdb --tmux-args --no-continue
  7042. ....
  7043. Now you can just `stepi` to when jumping into main to go to the C code in link:baremetal/interactive/prompt.c[].
  7044. This is specially interesting for the executables that don't use the bootloader from under `baremetal/arch/<arch>/no_bootloader/*.S`, e.g.:
  7045. ....
  7046. ./run --arch arm --baremetal arch/arm/no_bootloader/semihost_exit --wait-gdb --tmux-args --no-continue
  7047. ....
  7048. The cool thing about those examples is that you start at the very first instruction of your program, which gives more control.
  7049. === Baremetal bootloaders
  7050. As can be seen from <<baremetal-gdb-step-debug>>, all examples under link:baremetal/[], with the exception of `baremetal/arch/<arch>/no_bootloader`, start from our tiny bootloaders:
  7051. * link:baremetal/lib/arm.S[]
  7052. * link:baremetal/lib/aarch64.S[]
  7053. Out simplistic bootloaders basically setup up just enough system state to allow calling:
  7054. * C functions such as `exit` from the assembly examples
  7055. * the `main` of C examples itself
  7056. The most important things that we setup in the bootloaders are:
  7057. * the stack pointer
  7058. * NEON: <<aarch64-baremetal-neon-setup>>
  7059. * TODO: we don't do this currently but maybe we should setup BSS
  7060. The C functions that become available as a result are:
  7061. * Newlib functions implemented at link:baremetal/lib/syscalls.c[]
  7062. * non-Newlib functions implemented at link:kwargs['c'][]
  7063. It is not possible to call those C functions from the examples that don't use a bootloader.
  7064. For this reason, we tend to create examples with bootloaders, as it is easier to write them portably.
  7065. === Semihosting
  7066. Semihosting is a publicly documented interface specified by ARM Holdings that allows us to do some magic operations very useful in development.
  7067. Semihosting is implemented both on some real devices and on simulators such as QEMU and <<gem5-semihosting>>.
  7068. It is documented at: https://developer.arm.com/docs/100863/latest/introduction
  7069. For example, the following code makes QEMU exit:
  7070. ....
  7071. ./run --arch arm --baremetal arch/arm/semihost_exit
  7072. ....
  7073. Source: link:baremetal/arch/arm/no_bootloader/semihost_exit.S[]
  7074. That program program contains the code:
  7075. ....
  7076. mov r0, #0x18
  7077. ldr r1, =#0x20026
  7078. svc 0x00123456
  7079. ....
  7080. and we can see from the docs that `0x18` stands for the `SYS_EXIT` command.
  7081. This is also how we implement the `exit(0)` system call in C for QEMU for link:baremetal/exit.c[] through the Newlib via the function `_exit` at link:baremetal/lib/kwargs['c'][].
  7082. Other magic operations we can do with semihosting besides exiting the on the host include:
  7083. * read and write to host stdin and stdout
  7084. * read and write to host files
  7085. Alternatives exist for some semihosting operations, e.g.:
  7086. * UART IO for host stdin and stdout in both emulators and real hardware
  7087. * <<m5ops>> for <<gem5>>, e.g. `m5 exit` makes the emulator quit
  7088. The big advantage of semihosting is that it is standardized across all ARM boards, and therefore allows you to make a single image that does those magic operations instead of having to compile multiple images with different magic addresses.
  7089. The downside of semihosting is that it is ARM specific. TODO is it an open standard that other vendors can implement?
  7090. In QEMU, we enable semihosting with:
  7091. ....
  7092. -semihosting
  7093. ....
  7094. Newlib 9c84bfd47922aad4881f80243320422b621c95dc already has a semi-hosting implementation at:
  7095. ....
  7096. newlib/libc/sys/arm/syscalls.c
  7097. ....
  7098. TODO: how to use it? Possible through crosstool-NG? In the worst case we could just copy it.
  7099. Bibliography:
  7100. * https://stackoverflow.com/questions/31990487/how-to-cleanly-exit-qemu-after-executing-bare-metal-program-without-user-interve/40957928#40957928
  7101. * https://balau82.wordpress.com/2010/11/04/qemu-arm-semihosting/
  7102. ==== gem5 semihosting
  7103. For gem5, you need:
  7104. ....
  7105. patch -d "$(./getvar gem5_source_dir)" -p 1 < patches/manual/gem5-semihost.patch
  7106. ....
  7107. https://stackoverflow.com/questions/52475268/how-to-enable-arm-semihosting-in-gem5/52475269#52475269
  7108. === gem5 baremetal carriage return
  7109. TODO: our example is printing newlines without automatic carriage return `\r` as in:
  7110. ....
  7111. enter a character
  7112. got: a
  7113. ....
  7114. We use `m5term` by default, and if we try `telnet` instead:
  7115. ....
  7116. telnet localhost 3456
  7117. ....
  7118. it does add the carriage returns automatically.
  7119. === Baremetal host packaged toolchain
  7120. For `arm`, some baremetal examples compile fine with:
  7121. ....
  7122. sudo apt-get install gcc-arm-none-eabi qemu-system-arm
  7123. ./build-baremetal --arch arm --prebuilt
  7124. ./run --arch arm --baremetal interactive/prompt --prebuilt
  7125. ....
  7126. However, there are as usual limitations to using prebuilts:
  7127. * certain examples fail to build with the Ubuntu packaged toolchain. E.g.: link:baremetal/exit.c[] fails with:
  7128. +
  7129. ....
  7130. /usr/lib/gcc/arm-none-eabi/6.3.1/../../../arm-none-eabi/lib/libg.a(lib_a-fini.o): In function `__libc_fini_array':
  7131. /build/newlib-8gJlYR/newlib-2.4.0.20160527/build/arm-none-eabi/newlib/libc/misc/../../../../../newlib/libc/misc/fini.c:33: undefined reference to `_fini'
  7132. collect2: error: ld returned 1 exit status
  7133. ....
  7134. +
  7135. with the prebuilt toolchain, and I'm lazy to debug.
  7136. * there seems to to be no analogous `aarch64` Ubuntu package to `gcc-arm-none-eabi`: https://askubuntu.com/questions/1049249/is-there-a-package-with-the-aarch64-version-of-gcc-arm-none-eabi-for-bare-metal
  7137. === C++ baremetal
  7138. TODO I tried by there was an error. Not yet properly reported. Should not be hard in theory since `libstdc++` is just part of GCC, as shown at: https://stackoverflow.com/questions/21872229/how-to-edit-and-re-build-the-gcc-libstdc-c-standard-library-source/51946224#51946224
  7139. === GDB builtin CPU simulator
  7140. It is incredible, but GDB also has a CPU simulator inside of it as documented at: https://sourceware.org/gdb/onlinedocs/gdb/Target-Commands.html
  7141. TODO: any advantage over QEMU? I doubt it, mostly using it as as toy for now:
  7142. Without running `./run`, do directly:
  7143. ....
  7144. ./run-gdb --arch arm --baremetal interactive/prompt --sim
  7145. ....
  7146. Then inside GDB:
  7147. ....
  7148. load
  7149. starti
  7150. ....
  7151. and now you can debug normally.
  7152. Enabled with the crosstool-NG configuration:
  7153. ....
  7154. CT_GDB_CROSS_SIM=y
  7155. ....
  7156. which by grepping crosstool-NG we can see does on GDB:
  7157. ....
  7158. ./configure --enable-sim
  7159. ....
  7160. Those are not set by default on `gdb-multiarch` in Ubuntu 16.04.
  7161. Bibliography:
  7162. * https://stackoverflow.com/questions/49470659/arm-none-eabi-gdb-undefined-target-command-sim
  7163. * http://cs107e.github.io/guides/gdb/
  7164. ==== GDB builtin CPU simulator userland
  7165. Since I had this compiled, I also decided to try it out on userland.
  7166. I was also able to run a freestanding Linux userland example on it: https://github.com/cirosantilli/arm-assembly-cheat/blob/cd232dcaf32c0ba6399b407e0b143d19b6ec15f4/v7/linux/hello.S
  7167. It just ignores the `swi` however, and does not forward syscalls to the host like QEMU does.
  7168. Then I tried a glibc example: https://github.com/cirosantilli/arm-assembly-cheat/blob/cd232dcaf32c0ba6399b407e0b143d19b6ec15f4/v7/mov.S
  7169. First it wouldn't break, so I added `-static` to the `Makefile`, and then it started failing with:
  7170. ....
  7171. Unhandled v6 thumb insn
  7172. ....
  7173. Doing:
  7174. ....
  7175. help architecture
  7176. ....
  7177. shows ARM version up to `armv6`, so maybe `armv6` is not implemented?
  7178. === ARM baremetal
  7179. In this section we will focus on learning ARM architecture concepts that can only learnt on baremetal setups.
  7180. Userland information can be found at: https://github.com/cirosantilli/arm-assembly-cheat
  7181. ==== ARM exception level
  7182. ARM exception levels are analogous to x86 <<ring0,rings>>.
  7183. Print the EL at the beginning of a baremetal simulation:
  7184. ....
  7185. ./run --arch arm --baremetal arch/arm/el
  7186. ./run --arch aarch64 --baremetal arch/aarch64/el
  7187. ....
  7188. Sources:
  7189. * link:baremetal/arch/arm/el.c[]
  7190. * link:baremetal/arch/aarch64/el.c[]
  7191. The instructions that find the ARM EL are explained at: https://stackoverflow.com/questions/31787617/what-is-the-current-execution-mode-exception-level-etc
  7192. The lower ELs are not mandated by the architecture, and can be controlled through command line options in QEMU and gem5.
  7193. In QEMU, you can configure the lowest EL as explained at https://stackoverflow.com/questions/42824706/qemu-system-aarch64-entering-el1-when-emulating-a53-power-up
  7194. ....
  7195. ./run --arch arm --baremetal arch/arm/el
  7196. ./run --arch arm --baremetal arch/arm/el -- -machine virtualization=on
  7197. ./run --arch arm --baremetal arch/arm/el -- -machine secure=on
  7198. ./run --arch aarch64 --baremetal arch/aarch64/el
  7199. ./run --arch aarch64 --baremetal arch/aarch64/el -- -machine virtualization=on
  7200. ./run --arch aarch64 --baremetal arch/aarch64/el -- -machine secure=on
  7201. ....
  7202. outputs respectively:
  7203. ....
  7204. 19
  7205. 19
  7206. 19
  7207. 1
  7208. 2
  7209. 3
  7210. ....
  7211. TODO: why is `arm` stuck at `19` which equals Supervisor mode?
  7212. In gem5, you can configure the lowest EL with:
  7213. ....
  7214. ./run --arch arm --baremetal arch/arm/el --emulator gem5
  7215. cat "$(./getvar --arch arm --emulator gem5 gem5_guest_terminal_file)"
  7216. ./run --arch arm --baremetal arch/arm/el --emulator gem5 -- --param 'system.have_virtualization = True'
  7217. cat "$(./getvar --arch arm --emulator gem5 gem5_guest_terminal_file)"
  7218. ./run --arch arm --baremetal arch/arm/el --emulator gem5 -- --param 'system.have_security = True'
  7219. cat "$(./getvar --arch arm --emulator gem5 gem5_guest_terminal_file)"
  7220. ./run --arch aarch64 --baremetal arch/aarch64/el --emulator gem5
  7221. cat "$(./getvar --arch aarch64 --emulator gem5 gem5_guest_terminal_file)"
  7222. ./run --arch aarch64 --baremetal arch/aarch64/el --emulator gem5 -- --param 'system.have_virtualization = True'
  7223. cat "$(./getvar --arch aarch64 --emulator gem5 gem5_guest_terminal_file)"
  7224. ./run --arch aarch64 --baremetal arch/aarch64/el --emulator gem5 -- --param 'system.have_security = True'
  7225. cat "$(./getvar --arch aarch64 --emulator gem5 gem5_guest_terminal_file)"
  7226. ....
  7227. output:
  7228. ....
  7229. 19
  7230. 26
  7231. 19
  7232. 1
  7233. 2
  7234. 3
  7235. ....
  7236. ==== ARM multicore
  7237. ....
  7238. ./run --arch aarch64 --baremetal arch/aarch64/multicore --cpus 2
  7239. ./run --arch aarch64 --baremetal arch/aarch64/multicore --cpus 2 --emulator gem5
  7240. ./run --arch arm --baremetal arch/aarch64/multicore --cpus 2
  7241. ./run --arch arm --baremetal arch/aarch64/multicore --cpus 2 --emulator gem5
  7242. ....
  7243. Sources:
  7244. * link:baremetal/arch/aarch64/multicore.S[]
  7245. * link:baremetal/arch/arm/multicore.S[]
  7246. CPU 0 of this program enters a spinlock loop: it repeatedly checks if a given memory address is `1`.
  7247. So, we need CPU 1 to come to the rescue and set that memory address to `1`, otherwise CPU 0 will be stuck there forever!
  7248. Don't believe me? Then try:
  7249. ....
  7250. ./run --arch aarch64 --baremetal arch/aarch64/multicore --cpus 1
  7251. ....
  7252. and watch it hang forever.
  7253. Note that if you try the same thing on gem5:
  7254. ....
  7255. ./run --arch aarch64 --baremetal arch/aarch64/multicore --cpus 1 --emulator gem5
  7256. ....
  7257. then the gem5 actually exits, but with a different message:
  7258. ....
  7259. Exiting @ tick 18446744073709551615 because simulate() limit reached
  7260. ....
  7261. as opposed to the expected:
  7262. ....
  7263. Exiting @ tick 36500 because m5_exit instruction encountered
  7264. ....
  7265. since gem5 is able to detect when nothing will ever happen, and exits.
  7266. When GDB step debugging, switch between cores with the usual `thread` commands, see also: <<gdb-step-debug-multicore-userland>>.
  7267. Bibliography: https://stackoverflow.com/questions/980999/what-does-multicore-assembly-language-look-like/33651438#33651438
  7268. ===== WFE and SEV
  7269. The `WFE` and `SEV` instructions are just hints: a compliant implementation can treat them as NOPs.
  7270. However, likely no implementation likely does (TODO confirm), since:
  7271. * `WFE` puts the core in a low power mode
  7272. * `SEV` wakes up cores from a low power mode
  7273. and power consumption is key in ARM applications.
  7274. In QEMU 3.0.0, `SEV` is a NOPs, and `WFE` might be, but I'm not sure, see: https://github.com/qemu/qemu/blob/v3.0.0/target/arm/translate-a64.c#L1423
  7275. ....
  7276. case 2: /* WFE */
  7277. if (!(tb_cflags(s->base.tb) & CF_PARALLEL)) {
  7278. s->base.is_jmp = DISAS_WFE;
  7279. }
  7280. return;
  7281. case 4: /* SEV */
  7282. case 5: /* SEVL */
  7283. /* we treat all as NOP at least for now */
  7284. return;
  7285. ....
  7286. TODO: what does the WFE code do? How can it not be a NOP if SEV is a NOP? https://github.com/qemu/qemu/blob/v3.0.0/target/arm/translate.c#L4609 might explain why, but it is Chinese to me (I only understand 30% ;-)):
  7287. ....
  7288. * For WFI we will halt the vCPU until an IRQ. For WFE and YIELD we
  7289. * only call the helper when running single threaded TCG code to ensure
  7290. * the next round-robin scheduled vCPU gets a crack. In MTTCG mode we
  7291. * just skip this instruction. Currently the SEV/SEVL instructions
  7292. * which are *one* of many ways to wake the CPU from WFE are not
  7293. * implemented so we can't sleep like WFI does.
  7294. */
  7295. ....
  7296. For gem5 however, if we comment out the `SVE` instruction, then it actually exits with `simulate() limit reached`, so the CPU truly never wakes up, which is a more realistic behaviour.
  7297. The following Raspberry Pi bibliography helped us get this sample up and running:
  7298. * https://github.com/bztsrc/raspi3-tutorial/tree/a3f069b794aeebef633dbe1af3610784d55a0efa/02_multicorec
  7299. * https://github.com/dwelch67/raspberrypi/tree/a09771a1d5a0b53d8e7a461948dc226c5467aeec/multi00
  7300. * https://github.com/LdB-ECM/Raspberry-Pi/blob/3b628a2c113b3997ffdb408db03093b2953e4961/Multicore/SmartStart64.S
  7301. * https://github.com/LdB-ECM/Raspberry-Pi/blob/3b628a2c113b3997ffdb408db03093b2953e4961/Multicore/SmartStart32.S
  7302. ===== PSCI
  7303. In QEMU, CPU 1 starts in a halted state. This can be observed from GDB, where:
  7304. ....
  7305. info threads
  7306. ....
  7307. shows something like:
  7308. ....
  7309. * 1 Thread 1 (CPU#0 [running]) mystart
  7310. 2 Thread 2 (CPU#1 [halted ]) mystart
  7311. ....
  7312. To wake up CPU 1 on QEMU, we must use the Power State Coordination Interface (PSCI) which is documented at: link:https://developer.arm.com/docs/den0022/latest/arm-power-state-coordination-interface-platform-design-document[].
  7313. This interface uses `HVC` calls, and the calling convention is documented at "SMC CALLING CONVENTION" link:https://developer.arm.com/docs/den0028/latest[].
  7314. If we boot the Linux kernel on QEMU and <<get-device-tree-from-a-running-kernel,dump the auto-generated device tree>>, we observe that it contains the address of the PSCI CPU_ON call:
  7315. ....
  7316. psci {
  7317. method = "hvc";
  7318. compatible = "arm,psci-0.2", "arm,psci";
  7319. cpu_on = <0xc4000003>;
  7320. migrate = <0xc4000005>;
  7321. cpu_suspend = <0xc4000001>;
  7322. cpu_off = <0x84000002>;
  7323. };
  7324. ....
  7325. The Linux kernel wakes up the secondary cores in this exact same way at: https://github.com/torvalds/linux/blob/v4.19/drivers/firmware/psci.c#L122 We first actually got it working here by grepping the kernel and step debugging that call :-)
  7326. In gem5, CPU 1 starts woken up from the start, so PSCI is not needed. TODO gem5 actually blows up if we try to do the `hvc` call, understand why.
  7327. Bibliography: https://stackoverflow.com/questions/20055754/arm-start-wakeup-bringup-the-other-cpu-cores-aps-and-pass-execution-start-addre/53473447#53473447
  7328. ===== DMB
  7329. TODO: create and study a minimal examples in gem5 where the `DMB` instruction leads to less cycles: https://stackoverflow.com/questions/15491751/real-life-use-cases-of-barriers-dsb-dmb-isb-in-arm
  7330. ==== ARM baremetal bibliography
  7331. The most useful ARM baremetal example sets we've seen so far are:
  7332. * https://github.com/dwelch67/raspberrypi real hardware
  7333. * https://github.com/dwelch67/qemu_arm_samples QEMU `-m vexpress`
  7334. * https://github.com/bztsrc/raspi3-tutorial real hardware + QEMU `-m raspi`
  7335. * https://github.com/LdB-ECM/Raspberry-Pi real hardware
  7336. * https://github.com/NienfengYao/armv8-bare-metal QEMU `-m virt` aarch64. A large part of the code is taken from the awesome educational OS under 2-clause BSD: https://github.com/takeharukato/sample-tsk-sw/tree/ce7973aa5d46c9eedb58309de43df3b09d4f8d8d/hal/aarch64
  7337. === How we got some baremetal stuff to work
  7338. It is nice when thing just work.
  7339. But you can also learn a thing or two from how I actually made them work in the first place.
  7340. ==== Find the UART address
  7341. Enter the QEMU console:
  7342. ....
  7343. Ctrl-X C
  7344. ....
  7345. Then do:
  7346. ....
  7347. info mtree
  7348. ....
  7349. And look for `pl011`:
  7350. ....
  7351. 0000000009000000-0000000009000fff (prio 0, i/o): pl011
  7352. ....
  7353. On gem5, it is easy to find it on the source. We are using the machine `RealView_PBX`, and a quick grep leads us to: https://github.com/gem5/gem5/blob/a27ce59a39ec8fa20a3c4e9fa53e9b3db1199e91/src/dev/arm/RealView.py#L615
  7354. ....
  7355. class RealViewPBX(RealView):
  7356. uart = Pl011(pio_addr=0x10009000, int_num=44)
  7357. ....
  7358. ==== aarch64 baremetal NEON setup
  7359. Inside link:baremetal/lib/aarch64.S[] there is a chunk of code called "NEON setup".
  7360. Without that, the `printf`:
  7361. ....
  7362. printf("got: %c\n", c);
  7363. ....
  7364. compiled to a:
  7365. ....
  7366. str q0, [sp, #80]
  7367. ....
  7368. which uses NEON registers, and goes into an exception loop.
  7369. It was a bit confusing because there was a previous `printf`:
  7370. ....
  7371. printf("enter a character\n");
  7372. ....
  7373. which did not blow up because GCC compiles it into `puts` directly since it has no arguments, and that does not generate NEON instructions.
  7374. The last instructions ran was found with:
  7375. ....
  7376. while(1)
  7377. stepi
  7378. end
  7379. ....
  7380. or by hacking the QEMU CLI to contain:
  7381. .....
  7382. -D log.log -d in_asm
  7383. .....
  7384. I could not find any previous NEON instruction executed so this led me to suspect that some NEON initialization was required:
  7385. * http://infocenter.arm.com/help/topic/com.arm.doc.dai0527a/DAI0527A_baremetal_boot_code_for_ARMv8_A_processors.pdf "Bare-metal Boot Code for ARMv8-A Processors"
  7386. * https://community.arm.com/processors/f/discussions/5409/how-to-enable-neon-in-cortex-a8
  7387. * https://stackoverflow.com/questions/19231197/enable-neon-on-arm-cortex-a-series
  7388. We then tried to copy the code from the "Bare-metal Boot Code for ARMv8-A Processors" document:
  7389. ....
  7390. // Disable trapping of accessing in EL3 and EL2.
  7391. MSR CPTR_EL3, XZR
  7392. MSR CPTR_EL3, XZR
  7393. // Disable access trapping in EL1 and EL0.
  7394. MOV X1, #(0x3 << 20) // FPEN disables trapping to EL1.
  7395. MSR CPACR_EL1, X1
  7396. ISB
  7397. ....
  7398. but it entered an exception loop at `MSR CPTR_EL3, XZR`.
  7399. We then found out that QEMU starts in EL1, and so we kept just the EL1 part, and it worked. Related:
  7400. * https://stackoverflow.com/questions/42824706/qemu-system-aarch64-entering-el1-when-emulating-a53-power-up
  7401. * https://stackoverflow.com/questions/37299524/neon-support-in-armv8-system-mode-qemu
  7402. === Baremetal tests
  7403. Automatically run non-interactive baremetal tests:
  7404. ....
  7405. ./test-baremetal
  7406. ....
  7407. Source: link:test-baremetal[]
  7408. We detect if tests failed by parsing logs for the <<magic-failure-string>>.
  7409. We also skip tests that cannot work on certain conditions based on their basenames, e.g.:
  7410. * tests that start with `gem5_` only run in `gem5`
  7411. * tests that start with `semihost_` only run in QEMU, until we find a better way to automate <<gem5-semihosting>>
  7412. See: <<test-this-repo>> for more useful testing tips.
  7413. === Baremetal bibliography
  7414. https://stackoverflow.com/questions/43682311/uart-communication-in-gem5-with-arm-bare-metal
  7415. https://github.com/tukl-msd/gem5.bare-metal contains an alternative working baremetal setup. Our setup has more features at the time of writing however. Usage:
  7416. ....
  7417. # Build gem5.
  7418. git clone https://gem5.googlesource.com/public/gem5
  7419. cd gem5
  7420. git checkout 60600f09c25255b3c8f72da7fb49100e2682093a
  7421. scons --ignore-style -j`nproc` build/ARM/gem5.opt
  7422. cd ..
  7423. # Build example.
  7424. sudo apt-get install gcc-arm-none-eabi
  7425. git clone https://github.com/tukl-msd/gem5.bare-metal
  7426. cd gem5.bare-metal
  7427. git checkout 6ad1069d4299b775b5491e9252739166bfac9bfe
  7428. cd Simple
  7429. make CROSS_COMPILE_DIR=/usr/bin
  7430. # Run example.
  7431. ../../gem5/default/build/ARM/gem5.opt' \
  7432. ../../gem5/configs/example/fs.py' \
  7433. --bare-metal \
  7434. --disk-image="$(pwd)/../common/fake.iso" \
  7435. --kernel="$(pwd)/main.elf" \
  7436. --machine-type=RealView_PBX \
  7437. --mem-size=256MB \
  7438. ;
  7439. ....
  7440. == Benchmark this repo
  7441. TODO: didn't fully port during refactor after 3b0a343647bed577586989fb702b760bd280844a. Reimplementing should not be hard.
  7442. In this section document how benchmark builds and runs of this repo, and how to investigate what the bottleneck is.
  7443. Ideally, we should setup an automated build server that benchmarks those things continuously for us, but our <<travis>> attempt failed.
  7444. So currently, we are running benchmarks manually when it seems reasonable and uploading them to: https://github.com/cirosantilli/linux-kernel-module-cheat-regression
  7445. All benchmarks were run on the <<p51>> machine, unless stated otherwise.
  7446. Run all benchmarks and upload the results:
  7447. ....
  7448. cd ..
  7449. git clone https://github.com/cirosantilli/linux-kernel-module-cheat-regression
  7450. cd -
  7451. ./bench-all -A
  7452. ....
  7453. === Travis
  7454. 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.
  7455. === Benchmark this repo benchmarks
  7456. ==== Benchmark Linux kernel boot
  7457. Run all kernel boot benchmarks for one arch:
  7458. ....
  7459. ./build-test-boot --size 3 && ./test-boot --size 3
  7460. cat "$(./getvar test_boot_benchmark_file)"
  7461. ....
  7462. Sample results at 8fb9db39316d43a6dbd571e04dd46ae73915027f:
  7463. ....
  7464. cmd ./run --arch x86_64 --eval '/poweroff.out'
  7465. time 8.25
  7466. exit_status 0
  7467. cmd ./run --arch x86_64 --eval '/poweroff.out' --kvm
  7468. time 1.22
  7469. exit_status 0
  7470. cmd ./run --arch x86_64 --eval '/poweroff.out' --trace exec_tb
  7471. time 8.83
  7472. exit_status 0
  7473. instructions 2244297
  7474. cmd ./run --arch x86_64 --eval 'm5 exit' --emulator gem5
  7475. time 213.39
  7476. exit_status 0
  7477. instructions 318486337
  7478. cmd ./run --arch arm --eval '/poweroff.out'
  7479. time 6.62
  7480. exit_status 0
  7481. cmd ./run --arch arm --eval '/poweroff.out' --trace exec_tb
  7482. time 6.90
  7483. exit_status 0
  7484. instructions 776374
  7485. cmd ./run --arch arm --eval 'm5 exit' --emulator gem5
  7486. time 118.46
  7487. exit_status 0
  7488. instructions 153023392
  7489. cmd ./run --arch arm --eval 'm5 exit' --emulator gem5 -- --cpu-type=HPI --caches --l2cache --l1d_size=1024kB --l1i_size=1024kB --l2_size=1024kB --l3_size=1024kB
  7490. time 2250.40
  7491. exit_status 0
  7492. instructions 151981914
  7493. cmd ./run --arch aarch64 --eval '/poweroff.out'
  7494. time 4.94
  7495. exit_status 0
  7496. cmd ./run --arch aarch64 --eval '/poweroff.out' --trace exec_tb
  7497. time 5.04
  7498. exit_status 0
  7499. instructions 233162
  7500. cmd ./run --arch aarch64 --eval 'm5 exit' --emulator gem5
  7501. time 70.89
  7502. exit_status 0
  7503. instructions 124346081
  7504. cmd ./run --arch aarch64 --eval 'm5 exit' --emulator gem5 -- --cpu-type=HPI --caches --l2cache --l1d_size=1024kB --l1i_size=1024kB --l2_size=1024kB --l3_size=1024kB
  7505. time 381.86
  7506. exit_status 0
  7507. instructions 124564620
  7508. cmd ./run --arch aarch64 --eval 'm5 exit' --emulator gem5 --gem5-build-type fast
  7509. time 58.00
  7510. exit_status 0
  7511. instructions 124346081
  7512. cmd ./run --arch aarch64 --eval 'm5 exit' --emulator gem5 --gem5-build-type debug
  7513. time 1022.03
  7514. exit_status 0
  7515. instructions 124346081
  7516. ....
  7517. TODO: aarch64 gem5 and QEMU use the same kernel, so why is the gem5 instruction count so much much higher?
  7518. ===== gem5 arm HPI boot takes much longer than aarch64
  7519. TODO 62f6870e4e0b384c4bd2d514116247e81b241251 takes 33 minutes to finish at 62f6870e4e0b384c4bd2d514116247e81b241251:
  7520. ....
  7521. cmd ./run --arch arm --eval 'm5 exit' --emulator gem5 -- --caches --cpu-type=HPI
  7522. ....
  7523. while aarch64 only 7 minutes.
  7524. 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?
  7525. Logs of the runs can be found at: https://github.com/cirosantilli-work/gem5-issues/tree/0df13e862b50ae20fcd10bae1a9a53e55d01caac/arm-hpi-slow
  7526. The cycle count is higher for `arm`, 350M vs 250M for `aarch64`, not nowhere near the 5x runtime time increase.
  7527. 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.
  7528. ===== gem5 x86_64 DerivO3CPU boot panics
  7529. https://github.com/cirosantilli-work/gem5-issues/issues/2
  7530. ....
  7531. Kernel panic - not syncing: Attempted to kill the idle task!
  7532. ....
  7533. ==== Benchmark builds
  7534. 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>>.
  7535. 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
  7536. Buildroot automatically stores build timestamps as milliseconds since Epoch. Convert to minutes:
  7537. ....
  7538. awk -F: 'NR==1{start=$1}; END{print ($1 - start)/(60000.0)}' "$(./getvar buildroot_build_build_dir)/build-time.log"
  7539. ....
  7540. Or to conveniently do a clean build without affecting your current one:
  7541. ....
  7542. ./bench-all -b
  7543. cat ../linux-kernel-module-cheat-regression/*/build-time.log
  7544. ....
  7545. ===== Find which packages are making the build slow and big
  7546. ....
  7547. ./build-buildroot -- graph-build graph-size graph-depends
  7548. cd "$(./getvar buildroot_build_dir)/graphs"
  7549. xdg-open build.pie-packages.pdf
  7550. xdg-open graph-depends.pdf
  7551. xdg-open graph-size.pdf
  7552. ....
  7553. [[prebuilt-toolchain]]
  7554. ====== Buildroot use prebuilt host toolchain
  7555. 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
  7556. ===== Benchmark Buildroot build baseline
  7557. This is the minimal build we could expect to get away with.
  7558. We will run this whenever the Buildroot submodule is updated.
  7559. On the upstream Buildroot repo at :
  7560. ....
  7561. ./bench-all -B
  7562. ....
  7563. Sample time on 2017.08: 11 minutes, 7 with full ccache hits. Breakdown: 47% GCC, 15% Linux kernel, 9% uclibc, 5% host-binutils. Conclusions:
  7564. * we have bloated our kernel build 3x with all those delicious features :-)
  7565. * GCC time increased 1.5x by our bloat, but its percentage of the total was greatly reduced, due to new packages being introduced.
  7566. +
  7567. `make graph-depends` shows that most new dependencies come from QEMU and GDB, which we can't get rid of anyways.
  7568. A quick look at the system monitor reveals that the build switches between times when:
  7569. * CPUs are at a max, memory is fine. So we must be CPU / memory speed bound. I bet that this happens during heavy compilation.
  7570. * CPUs are not at a max, and memory is fine. So we are likely disk bound. I bet that this happens during configuration steps.
  7571. 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.
  7572. The instructions counts varied very little between the baseline and LKMC, so runtime overhead is not a big deal apparently.
  7573. Size:
  7574. * `bzImage`: 4.4M
  7575. * `rootfs.cpio`: 1.6M
  7576. Zipped: 4.9M, `rootfs.cpio` deflates 50%, `bzImage` almost nothing.
  7577. ===== Benchmark gem5 build
  7578. How long it takes to build gem5 itself.
  7579. We will update this whenever the gem5 submoule is updated.
  7580. Sample results at gem5 2a9573f5942b5416fb0570cf5cb6cdecba733392: 10 to 12 minutes.
  7581. Get results with:
  7582. ....
  7583. ./bench-all --emulator gem5
  7584. tail -n+1 ../linux-kernel-module-cheat-regression/*/gem5-bench-build-*.txt
  7585. ....
  7586. ====== Benchmark gem5 single file change rebuild time
  7587. This is the critical development parameter, and is dominated by the link time of huge binaries.
  7588. In order to benchmark it better, make a comment only change to:
  7589. ....
  7590. vim submodules/gem5/src/sim/main.cc
  7591. ....
  7592. then rebuild with:
  7593. ....
  7594. ./build-gem5 --arch aarch64 --verbose
  7595. ....
  7596. and then copy the link command to a separate Bash file. Then you can time and modify it easily.
  7597. Some approximate refrence values on <<p51>>:
  7598. * `opt`
  7599. ** unmodified: 10 seconds
  7600. ** hack with `-fuse-ld=gold`: 6 seconds. Huge improvement!
  7601. * `debug`
  7602. ** unmodified: 14 seconds. Why two times slower than unmodified?
  7603. ** hack with `-fuse-ld=gold`: `internal error in read_cie, at ../../gold/ehframe.cc:919` on Ubuntu 18.04 all GCC. TODO report.
  7604. * `fast`
  7605. ** `--force-lto`: 1 minute. Slower as expected, since more optimizations are done at link time. `--force-lto` is only used for `fast`, and it adds `-flto` to the build.
  7606. ramfs made no difference, the kernel must be caching files in memory very efficiently already.
  7607. Tested at: d4b3e064adeeace3c3e7d106801f95c14637c12f + 1.
  7608. === Benchmark machines
  7609. ==== P51
  7610. Lenovo ThinkPad link:https://www3.lenovo.com/gb/en/laptops/thinkpad/p-series/P51/p/22TP2WPWP51[P51 laptop]:
  7611. * 2500 USD in 2018 (high end)
  7612. * Intel Core i7-7820HQ Processor (8MB Cache, up to 3.90GHz) (4 cores 8 threads)
  7613. * 32GB(16+16) DDR4 2400MHz SODIMM
  7614. * 512GB SSD PCIe TLC OPAL2
  7615. * NVIDIA Quadro M1200 Mobile, latest Ubuntu supported proprietary driver
  7616. * Latest Ubuntu
  7617. === Benchmark Internets
  7618. ==== 38Mbps internet
  7619. 2c12b21b304178a81c9912817b782ead0286d282:
  7620. * shallow clone of all submodules: 4 minutes.
  7621. * `make source`: 2 minutes
  7622. Google M-lab speed test: 36.4Mbps
  7623. === Benchmark this repo bibliography
  7624. gem5:
  7625. * link:https://www.mail-archive.com/gem5-users@gem5.org/msg15262.html[] which parts of the gem5 code make it slow
  7626. * what are the minimum system requirements:
  7627. ** https://stackoverflow.com/questions/47997565/gem5-system-requirements-for-decent-performance/48941793#48941793
  7628. ** https://github.com/gem5/gem5/issues/25
  7629. == About this repo
  7630. === Supported hosts
  7631. We tend to test this repo the most on the latest Ubuntu and on the latest link:https://askubuntu.com/questions/16366/whats-the-difference-between-a-long-term-support-release-and-a-normal-release[Ubuntu LTS].
  7632. For other Linux distros, everything will likely also just work if you install the analogous required packages for your distro
  7633. Find out the packages that we install with:
  7634. ....
  7635. ./build --download-dependencies --dry-run | less
  7636. ....
  7637. and then just look for the `apt-get` commands shown on the log.
  7638. After installing the missing packages for your distro, do the build with:
  7639. ....
  7640. ./build --download-dependencies --no-apt
  7641. ....
  7642. which does everything as normal, except that it skips any `apt` commands.
  7643. Ports to new host systems are welcome and will be merged.
  7644. If something does not work however, <<docker>> should just work on any Linux distro.
  7645. Native Windows is unlikely feasible because Buildroot is a huge set of GNU Make scripts + host tools, just do everything from inside an Ubuntu in VirtualBox instance in that case.
  7646. === Common build issues
  7647. ==== You must put some 'source' URIs in your sources.list
  7648. If `./build --download-dependencies` fails with:
  7649. ....
  7650. E: You must put some 'source' URIs in your sources.list
  7651. ....
  7652. see this: https://askubuntu.com/questions/496549/error-you-must-put-some-source-uris-in-your-sources-list/857433#857433 I don't know how to automate this step. Why, Ubuntu, why.
  7653. ==== Build from downloaded source zip files
  7654. It does not work if you just download the `.zip` with the sources for this repository from GitHub because we use link:.gitmodules[Git submodules], you must clone this repo.
  7655. `./build --download-dependencies` then fetches only the required submodules for you.
  7656. === Run command after boot
  7657. If you just want to run a command after boot ends without thinking much about it, just use the `--eval-after` option, e.g.:
  7658. ....
  7659. ./run --eval-after 'echo hello'
  7660. ....
  7661. This option passes the command to our init scripts through <<kernel-command-line-parameters>>, and uses a few clever tricks along the way to make it just work.
  7662. See <<init>> for the gory details.
  7663. === Default command line arguments
  7664. It gets annoying to retype `--arch aarch64` for every single command, or to remember `--config` setups.
  7665. So simplify that, do:
  7666. ....
  7667. cp config.py data/
  7668. ....
  7669. and then edit the `data/config` file to your needs.
  7670. Source: link:config.py[]
  7671. You can also choose a different configuration file explicitly with:
  7672. ....
  7673. ./run --config data/config2.py
  7674. ....
  7675. Almost all options names are automatically deduced from their command line `--help` name: just replace `-` with `_`.
  7676. More precisely, we use the `dest=` value of Python's link:https://docs.python.org/3/library/argparse.html[argparse module].
  7677. To get a list of all global options that you can use, try:
  7678. ....
  7679. ./getvar --type input
  7680. ....
  7681. but note that this does not include script specific options.
  7682. === Build the documentation
  7683. You don't need to depend on GitHub:
  7684. ....
  7685. sudo apt install asciidoctor
  7686. ./build-doc
  7687. xdg-open out/README.html
  7688. ....
  7689. Source: link:build-doc[]
  7690. === Clean the build
  7691. You did something crazy, and nothing seems to work anymore?
  7692. All our build outputs are stored under `out/`, so the coarsest and most effective thing you can do is:
  7693. ....
  7694. rm -rf out
  7695. ....
  7696. This implies a full rebuild for all archs however, so you might first want to explore finer grained cleans first.
  7697. All our individual `build-*` scripts have a `--clean` option to completely nuke their builds:
  7698. ....
  7699. ./build-gem5 --clean
  7700. ./build-qemu --clean
  7701. ./build-buildroot --clean
  7702. ....
  7703. Verify with:
  7704. ....
  7705. ls "$(./getvar qemu_build_dir)"
  7706. ls "$(./getvar gem5_build_dir)"
  7707. ls "$(./getvar buildroot_build_dir)"
  7708. ....
  7709. Note that host tools like QEMU and gem5 store all archs in a single directory to factor out build objects, so cleaning one arch will clean all of them.
  7710. To only nuke only one Buildroot package, we can use the link:https://buildroot.org/downloads/manual/manual.html#pkg-build-steps[]`-dirclean`] Buildroot target:
  7711. ....
  7712. ./build-buildroot --no-all -- <package-name>-dirclean
  7713. ....
  7714. e.g.:
  7715. ....
  7716. ./build-buildroot --no-all -- sample_package-dirclean
  7717. ....
  7718. Verify with:
  7719. ....
  7720. ls "$(./getvar buildroot_build_build_dir)"
  7721. ....
  7722. === ccache
  7723. link:https://en.wikipedia.org/wiki/Ccache[ccache] <<benchmark-builds,might>> save you a lot of re-build when you decide to <<clean-the-build>> or create a new <<build-variants,build variant>>.
  7724. We have ccache enabled for everything we build by default.
  7725. However, you likely want to add the following to your `.bashrc` to take better advantage of `ccache`:
  7726. ....
  7727. export CCACHE_DIR=~/.ccache
  7728. export CCACHE_MAXSIZE="20G"
  7729. ....
  7730. We cannot automate this because you have to decide:
  7731. * should I store my cache on my HD or SSD?
  7732. * how big is my build, and how many build configurations do I need to keep around at a time?
  7733. If you don't those variables it, the default is to use `~/.buildroot-ccache` with `5G`, which is a bit small for us.
  7734. To check if `ccache` is working, run this command while a build is running on another shell:
  7735. ....
  7736. watch -n1 'make -C "$(./getvar buildroot_build_dir)" ccache-stats'
  7737. ....
  7738. or if you have it installed on host and the environment variables exported simply with:
  7739. ....
  7740. watch -n1 'ccache -s'
  7741. ....
  7742. and then watch the miss or hit counts go up.
  7743. We have link:https://buildroot.org/downloads/manual/manual.html#ccache[enabled ccached] builds by default.
  7744. `BR2_CCACHE_USE_BASEDIR=n` is used for Buildroot, which means that:
  7745. * absolute paths are used and GDB can find source files
  7746. * but builds are not reused across separated LKMC directories
  7747. === Rebuild while running
  7748. Not possible because
  7749. ....
  7750. Text file busy
  7751. ....
  7752. openat(AT_FDCWD, "sleep.out", O_WRONLY) = -1 ETXTBSY ()
  7753. === Simultaneous runs
  7754. When doing long simulations sweeping across multiple system parameters, it becomes fundamental to do multiple simulations in parallel.
  7755. This is specially true for gem5, which runs much slower than QEMU, and cannot use multiple host cores to speed up the simulation: link:https://github.com/cirosantilli-work/gem5-issues/issues/15[], so the only way to parallelize is to run multiple instances in parallel.
  7756. This also has a good synergy with <<build-variants>>.
  7757. First shell:
  7758. ....
  7759. ./run
  7760. ....
  7761. Another shell:
  7762. ....
  7763. ./run --run-id 1
  7764. ....
  7765. and now you have two QEMU instances running in parallel.
  7766. The default run id is `0`.
  7767. Our scripts solve two difficulties with simultaneous runs:
  7768. * port conflicts, e.g. GDB and link:gem5-shell[]
  7769. * output directory conflicts, e.g. traces and gem5 stats overwriting one another
  7770. Each run gets a separate output directory. For example:
  7771. ....
  7772. ./run --arch aarch64 --emulator gem5 --run-id 0 &>/dev/null &
  7773. ./run --arch aarch64 --emulator gem5 --run-id 1 &>/dev/null &
  7774. ....
  7775. produces two separate <<m5out-directory,`m5out` directories>>:
  7776. ....
  7777. echo "$(./getvar --arch aarch64 --emulator gem5 --run-id 0 m5out_dir)"
  7778. echo "$(./getvar --arch aarch64 --emulator gem5 --run-id 1 m5out_dir)"
  7779. ....
  7780. and the gem5 host executable stdout and stderr can be found at:
  7781. ....
  7782. less "$(./getvar --arch aarch64 --emulator gem5 --run-id 0 termout_file)"
  7783. less "$(./getvar --arch aarch64 --emulator gem5 --run-id 1 termout_file)"
  7784. ....
  7785. Each line is prepended with the timestamp in seconds since the start of the program when it appeared.
  7786. To have more semantic output directories names for later inspection, you can use a non numeric string for the run ID, and indicate the port offset explicitly:
  7787. ....
  7788. ./run --arch aarch64 --emulator gem5 --run-id some-experiment --port-offset 1
  7789. ....
  7790. `--port-offset` defaults to the run ID when that is a number.
  7791. Like <<cpu-architecture>>, you will need to pass the `-n` option to anything that needs to know runtime information, e.g. <<gdb>>:
  7792. ....
  7793. ./run --run-id 1
  7794. ./run-gdb --run-id 1
  7795. ....
  7796. To run multiple gem5 checkouts, see: <<gem5-worktree>>.
  7797. Implementation note: we create multiple namespaces for two things:
  7798. * run output directory
  7799. * ports
  7800. ** QEMU allows setting all ports explicitly.
  7801. +
  7802. If a port is not free, it just crashes.
  7803. +
  7804. We assign a contiguous port range for each run ID.
  7805. ** gem5 automatically increments ports until it finds a free one.
  7806. +
  7807. 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>>.
  7808. +
  7809. The GDB port can be assigned on `gem5.opt --remote-gdb-port`, but it does not appear on `config.ini`.
  7810. === Build variants
  7811. 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.
  7812. Our build variants system allows you to keep multiple built versions of all major components, so that you can easily switching between running one or the other.
  7813. ==== Linux kernel build variants
  7814. If you want to keep two builds around, one for the latest Linux version, and the other for Linux `v4.16`:
  7815. ....
  7816. # Build master.
  7817. ./build-linux
  7818. # Build another branch.
  7819. git -C "$(./getvar linux_source_dir)" fetch --tags --unshallow
  7820. git -C "$(./getvar linux_source_dir)" checkout v4.16
  7821. ./build-linux --linux-build-id v4.16
  7822. # Restore master.
  7823. git -C "$(./getvar linux_source_dir)" checkout -
  7824. # Run master.
  7825. ./run
  7826. # Run another branch.
  7827. ./run --linux-build-id v4.16
  7828. ....
  7829. The `git fetch --unshallow` is needed the first time because `./build --download-dependencies` only does a shallow clone of the Linux kernel to save space and time, see also: https://stackoverflow.com/questions/6802145/how-to-convert-a-git-shallow-clone-to-a-full-clone
  7830. The `--linux-build-id` option should be passed to all scripts that support it, much like `--arch` for the <<cpu-architecture>>, e.g. to step debug:
  7831. .....
  7832. ./run-gdb --linux-build-id v4.16
  7833. .....
  7834. To run both kernels simultaneously, one on each QEMU instance, see: <<simultaneous-runs>>.
  7835. ==== QEMU build variants
  7836. Analogous to the <<linux-kernel-build-variants>> but with the `--qemu-build-id` option instead:
  7837. ....
  7838. ./build-qemu
  7839. git -C "$(./getvar qemu_source_dir)" checkout v2.12.0
  7840. ./build-qemu --qemu-build-id v2.12.0
  7841. git -C "$(./getvar qemu_source_dir)" checkout -
  7842. ./run
  7843. ./run --qemu-build-id v2.12.0
  7844. ....
  7845. ==== gem5 build variants
  7846. Analogous to the <<linux-kernel-build-variants>> but with the `--gem5-build-id` option instead:
  7847. ....
  7848. # Build master.
  7849. ./build-gem5
  7850. # Build another branch.
  7851. git -C "$(./getvar gem5_source_dir)" checkout some-branch
  7852. ./build-gem5 --gem5-build-id some-branch
  7853. # Restore master.
  7854. git -C "$(./getvar gem5_source_dir)" checkout -
  7855. # Run master.
  7856. ./run --emulator gem5
  7857. # Run another branch.
  7858. git -C "$(./getvar gem5_source_dir)" checkout some-branch
  7859. ./run --gem5-build-id some-branch --emulator gem5
  7860. ....
  7861. 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.
  7862. Therefore, you can't forget to checkout to the sources to that of the corresponding build before running, unless you explicitly tell gem5 to use a non-default source tree with <<gem5-worktree>>. This becomes inevitable when you want to launch multiple simultaneous runs at different checkouts.
  7863. ===== gem5 worktree
  7864. <<gem5-build-variants,`--gem5-build-id`>> goes a long way, but if you want to seamlessly switch between two gem5 tress without checking out multiple times, then `--gem5-worktree` is for you.
  7865. ....
  7866. # Build gem5 at the revision in the gem5 submodule.
  7867. ./build-gem5
  7868. # Create a branch at the same revision as the gem5 submodule.
  7869. ./build-gem5 --gem5-worktree my-new-feature
  7870. cd "$(./getvar --gem5-worktree my-new-feature)"
  7871. vim create-bugs
  7872. git add .
  7873. git commit -m 'Created a bug'
  7874. cd -
  7875. ./build-gem5 --gem5-worktree my-new-feature
  7876. # Run the submodule.
  7877. ./run --emulator gem5 --run-id 0 &>/dev/null &
  7878. # Run the branch the need to check out anything.
  7879. # With --gem5-worktree, we can do both runs at the same time!
  7880. ./run --emulator gem5 --gem5-worktree my-new-feature --run-id 1 &>/dev/null &
  7881. ....
  7882. `--gem5-worktree <worktree-id>` automatically creates:
  7883. * a link:https://git-scm.com/docs/git-worktree[Git worktree] of gem5 if one didn't exit yet for `<worktree-id>`
  7884. * a separate build directory, exactly like `--gem5-build-id my-new-feature` would
  7885. We promise that the scripts sill never touch that worktree again once it has been created: it is now up to you to manage the code manually.
  7886. `--gem5-worktree` is required if you want to do multiple simultaneous runs of different gem5 versions, because each gem5 build needs to use the matching Python scripts inside the source tree.
  7887. The difference between `--gem5-build-id` and `--gem5-worktree` is that `--gem5-build-id` specifies only the gem5 build output directory, while `--gem5-worktree` specifies the source input directory.
  7888. Each Git worktree needs a branch name, and we append the `wt/` prefix to the `--gem5-worktree` value, where `wt` stands for `WorkTree`. This is done to allow us to checkout to a test `some-branch` branch under `submodules/gem5` and still use `--gem5-worktree some-branch`, without conflict for the worktree branch, which can only be checked out once.
  7889. ===== gem5 private source trees
  7890. Suppose that you are working on a private fork of gem5, but you want to use this repository to develop it as well.
  7891. Simply adding your private repository as a remote to `submodules/gem5` is dangerous, as you might forget and push your private work by mistake one day.
  7892. Even removing remotes is not safe enough, since `git submodule update` and other submodule commands can restore the old public remote.
  7893. Instead, we provide the following safer process.
  7894. First do a separate private clone of you private repository outside of this repository:
  7895. ....
  7896. git clone https://my.private.repo.com/my-fork/gem5.git gem5-internal
  7897. gem5_internal="$(pwd)/gem5-internal"
  7898. ....
  7899. Next, when you want to build with the private repository, use the `--gem5-build-dir` and `--gem5-source-dir` argument to override our default gem5 source and build locations:
  7900. ....
  7901. cd linux-kernel-module-cheat
  7902. ./build-gem5 \
  7903. --gem5-build-dir "${gem5_internal}/build" \
  7904. --gem5-source-dir "$gem5_internal" \
  7905. ;
  7906. ./run-gem5 \
  7907. --gem5-build-dir "${gem5_internal}/build" \
  7908. --gem5-source-dir "$gem5_internal" \
  7909. ;
  7910. ....
  7911. With this setup, both your private gem5 source and build are safely kept outside of this public repository.
  7912. ===== gem5 debug build
  7913. The `gem5.debug` executable has optimizations turned off unlike the default `gem5.opt`, and provides a much better <<debug-the-emulator,debug experience>>:
  7914. ....
  7915. ./build-gem5 --arch aarch64 --gem5-build-type debug
  7916. ./run --arch aarch64 --debug-vm --emulator gem5 --gem5-build-type debug
  7917. ....
  7918. The build outputs are automatically stored in a different directory from other build types such as `.opt` build, which prevents `.debug` files from overwriting `.opt` ones.
  7919. Therefore, `--gem5-build-id` is not required.
  7920. The price to pay for debuggability is high however: a Linux kernel boot was about 14 times slower than opt at 71e927e63bda6507d5a528f22c78d65099bdf36f between the commands:
  7921. ....
  7922. ./run --arch aarch64 --eval 'm5 exit' --emulator gem5 --linux-build-id v4.16
  7923. ./run --arch aarch64 --eval 'm5 exit' --emulator gem5 --linux-build-id v4.16 --gem5-build-type debug
  7924. ....
  7925. so you will likely only use this when it is unavoidable.
  7926. ==== Buildroot build variants
  7927. Allows you to have multiple versions of the GCC toolchain or root filesystem.
  7928. Analogous to the <<linux-kernel-build-variants>> but with the `--build-id` option instead:
  7929. ....
  7930. ./build-buildroot
  7931. git -C "$(./getvar buildroot_source_dir)" checkout 2018.05
  7932. ./build-buildroot --buildroot-build-id 2018.05
  7933. git -C "$(./getvar buildroot_source_dir)" checkout -
  7934. ./run
  7935. ./run --buildroot-build-id 2018.05
  7936. ....
  7937. === Directory structure
  7938. ==== include directory
  7939. link:include/[] contains headers that are shared across both kernel modules and userland structures.
  7940. They contain data structs and magic constant for kernel to userland communication.
  7941. ==== userland directory
  7942. Userland test programs. They can be used in the following ways:
  7943. * inside a full system simulation, e.g.: <<qemu-buildroot-setup>>
  7944. * inside <<user-mode-simulation>>
  7945. * directly on the host: <<userland-directory-host-build>>
  7946. For usage inside full system simulation, first ensure that Buildroot has been built for the toolchain, and then build the examples with:
  7947. ....
  7948. ./build-userland
  7949. ....
  7950. Source: link:build-userland[].
  7951. This makes them visible immediately on the <<9p>> mount of a running simulator.
  7952. In order to place them in the root filesystem image itself, you must also run:
  7953. ....
  7954. ./build-buildroot
  7955. ....
  7956. ===== userland directory host build
  7957. It is possible to build and run some of the userland examples directly on your host:
  7958. ....
  7959. cd userland
  7960. make
  7961. ./hello.out
  7962. make clean
  7963. ....
  7964. or more cleanly out of tree:
  7965. ....
  7966. ./build-userland --host --userland-build-id host
  7967. "$(./getvar --userland-build-id host userland_build_dir)/hello.out"
  7968. ....
  7969. Extra make flags may be passed as:
  7970. ....
  7971. ./build-userland --host --userland-build-id host-static --make-args='-B CFLAGS_EXTRA=-static'
  7972. "$(./getvar --userland-build-id host-static userland_build_dir)/hello.out"
  7973. ....
  7974. This for example would both force a rebuild due to `-B` and link statically due to `CFLAGS_EXTRA=-static`.
  7975. TODO: OpenMP does not like `-static`:
  7976. ....
  7977. /usr/lib/gcc/x86_64-linux-gnu/5/libgomp.a(target.o): In function `gomp_target_init':
  7978. (.text+0xba): warning: Using 'dlopen' in statically linked applications requires at runtime the shared libraries from the glibc version used for linking
  7979. ....
  7980. See: https://stackoverflow.com/questions/23869981/linking-openmp-statically-with-gcc
  7981. ==== buildroot_packages directory
  7982. Source: link:buildroot_packages/[]
  7983. Every directory inside it is a Buildroot package.
  7984. Those packages get automatically added to Buildroot's `BR2_EXTERNAL`, so all you need to do is to turn them on during build, e.g.:
  7985. ....
  7986. ./build-buildroot --config 'BR2_PACKAGE_SAMPLE_PACKAGE=y'
  7987. ....
  7988. then test it out with:
  7989. ....
  7990. ./run --eval-after '/sample_package.out'
  7991. ....
  7992. and you should see:
  7993. ....
  7994. hello sample_package
  7995. ....
  7996. Source: link:buildroot_packages/sample_package/sample_package.c[]
  7997. You can force a rebuild with:
  7998. ....
  7999. ./build-buildroot --config 'BR2_PACKAGE_SAMPLE_PACKAGE=y' -- sample_package-reconfigure
  8000. ....
  8001. Buildroot packages are convenient, but in general, if a package if very important to you, but not really mergeable back to Buildroot, you might want to just use a custom build script for it, and point it to the Buildroot toolchain, and then use `BR2_ROOTFS_OVERLAY`, much like we do for <<userland-directory>>.
  8002. A custom build script can give you more flexibility: e.g. the package can be made work with other root filesystems more easily, have better <<9p>> support, and rebuild faster as it evades some Buildroot boilerplate.
  8003. ===== kernel_modules package
  8004. Source: link:buildroot_packages/kernel_modules/[]
  8005. An example of how to use kernel modules in Buildroot.
  8006. Usage:
  8007. ....
  8008. ./build-buildroot \
  8009. --build-linux \
  8010. --config 'BR2_PACKAGE_KERNEL_MODULES=y' \
  8011. --no-overlay \
  8012. -- \
  8013. kernel_modules-reconfigure \
  8014. ;
  8015. ....
  8016. Then test one of the modules with:
  8017. ....
  8018. ./run --buildroot-linux --eval-after 'modprobe buildroot_hello'
  8019. ....
  8020. Source: link:buildroot_packages/kernel_modules/buildroot_hello.c[]
  8021. As you have just seen, this sets up everything so that <<modprobe>> can conrrectly find the module.
  8022. `./build-buildroot --build-linux` and `./run --buildroot-linux` are needed because the Buildroot kernel modules must use the Buildroot Linux kernel at build and run time.
  8023. The `--no-overlay` is required otherwise our `modules.order` generated by `./build-linux` and installed with `BR2_ROOTFS_OVERLAY` overwrites the Buildroot generated one.
  8024. Implementattion described at: https://stackoverflow.com/questions/40307328/how-to-add-a-linux-kernel-driver-module-as-a-buildroot-package/43874273#43874273
  8025. ==== patches directory
  8026. ===== patches/global
  8027. Has the following structure:
  8028. ....
  8029. package-name/00001-do-something.patch
  8030. ....
  8031. The patches are then applied to the corresponding packages before build.
  8032. Uses `BR2_GLOBAL_PATCH_DIR`.
  8033. ===== patches/manual
  8034. 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.
  8035. These are typically patches that don't contain fundamental functionality, so we don't feel like forking the target repos.
  8036. ==== rootfs_overlay
  8037. We use this directory for:
  8038. * customized configuration files
  8039. * userland module test scripts that don't need to be compiled.
  8040. +
  8041. C files for example need compilation, and must go through the regular package system, e.g. through link:kernel_modules/user[].
  8042. This directory is copied into the target filesystem by:
  8043. ....
  8044. ./copy-overlay
  8045. ./build-buildroot
  8046. ....
  8047. Source: link:copy-overlay[]
  8048. Build Buildroot is required for the same reason as described at: <<your-first-kernel-module-hack>>.
  8049. However, since the link:rootfs_overlay[] directory does not require compilation, unlike say <<your-first-kernel-module-hack,kernel modules>>, we also make it <<9p>> available to the guest directly even without `./copy-overlay` at:
  8050. ....
  8051. ls /mnt/9p/rootfs_overlay
  8052. ....
  8053. This way you can just hack away the scripts and try them out immediately without any further operations.
  8054. === Test this repo
  8055. ==== Automated tests
  8056. Run almost all tests:
  8057. ....
  8058. ./build-test --size 3 && \
  8059. ./test --size 3
  8060. echo $?
  8061. ....
  8062. should output 0.
  8063. Sources:
  8064. * link:build-test[]
  8065. * link:test[]
  8066. The link:test[] script runs several different types of tests, which can also be run separately as explained at:
  8067. * link:test-boot[]
  8068. * <<test-userland-in-full-system>>
  8069. * <<user-mode-tests>>
  8070. * <<baremetal-tests>>
  8071. * <<test-gdb>>
  8072. link:test[] does not all possible tests, because there are too many possible variations and that would take forever. The rationale is the same as for `./build all` and is explained in `./build --help`.
  8073. ===== Test arch and emulator selection
  8074. You can select multiple archs and emulators of interest, as for an other command, with:
  8075. ....
  8076. ./test-user-mode \
  8077. --arch x86_64 \
  8078. --arch aarch64 \
  8079. --emulator gem5 \
  8080. --emulator qemu \
  8081. ;
  8082. ....
  8083. You can also test all supported archs and emulators with:
  8084. ....
  8085. ./test-user-mode \
  8086. --all-archs \
  8087. --all-emulators \
  8088. ;
  8089. ....
  8090. This command would run the test four times, using `x86_64` and `aarch64` with both gem5 and QEMU.
  8091. Without those flags, it defaults to just running the default arch and emulator once: `x86_64` and `qemu`.
  8092. ===== Quit on fail
  8093. By default, tests stop running as soon as the first failure happens.
  8094. You can prevent this with the `--no-quit-on-fail option, e.g.:
  8095. ....
  8096. ./test-user-mode --no-quit-on-fail
  8097. ....
  8098. You can then see which tests failed on the test summary report at the end.
  8099. ===== Test userland in full system
  8100. Run all userland tests from inside full system simulation (i.e. not <<user-mode-simulation>>):
  8101. ....
  8102. ./test-userland-full-system
  8103. ....
  8104. This includes, in particular, userland programs that test the kernel modules, which cannot be tested in user mode simulation.
  8105. Basically just boots and runs: link:rootfs_overlay/test_all.sh[]
  8106. Failure is detected by looking for the <<magic-failure-string>>
  8107. Most userland programs that don't rely on kernel modules can also be tested in user mode simulation as explained at: <<user-mode-tests>>.
  8108. ===== Test GDB
  8109. We have some link:https://github.com/pexpect/pexpect[pexpect] automated tests for the baremetal programs!
  8110. ....
  8111. ./build --all-archs test-gdb && \
  8112. ./test-gdb --all-archs --all-emulators
  8113. ....
  8114. Sources:
  8115. * link:build-test-gdb[]
  8116. * link:test-gdb[]
  8117. If a test fails, re-run the test commands manually and use `--verbose` to understand what happened:
  8118. ....
  8119. ./run --arch arm --background --baremetal add --wait-gdb &
  8120. ./run-gdb --arch arm --baremetal add --verbose -- main
  8121. ....
  8122. and possibly repeat the GDB steps manually with the usual:
  8123. ....
  8124. ./run-gdb --arch arm --baremetal add --no-continue --verbose
  8125. ....
  8126. To debug GDB problems on gem5, you might want to enable the following <<gem5-tracing,tracing>> options:
  8127. ....
  8128. ./run \
  8129. --arch arm \
  8130. --baremetal add \
  8131. --wait-gdb \
  8132. --trace GDBRecv,GDBSend \
  8133. --trace-stdout \
  8134. ;
  8135. ....
  8136. ===== Magic failure string
  8137. Since there is no standardized exit status concept that works across all emulators for full system, we just parse the terminal output for a magic failure string to check if tests failed.
  8138. If a full system simulation outputs a line containing only exactly the magic string:
  8139. ....
  8140. lkmc_test_fail
  8141. ....
  8142. to the terminal, then our run scripts detect that and exit with status `1`.
  8143. This magic output string is notably used by:
  8144. * the `common_assert_fail()` function, which is used by <<baremetal-tests>>
  8145. * link:rootfs_overlay/test_fail.sh[], which is used by <<test-userland-in-full-system>>
  8146. === Non-automated tests
  8147. ==== Test GDB Linux kernel
  8148. For the Linux kernel, do the following manual tests for now.
  8149. Shell 1:
  8150. ....
  8151. ./run --wait-gdb
  8152. ....
  8153. Shell 2:
  8154. ....
  8155. ./run-gdb start_kernel
  8156. ....
  8157. Should break GDB at `start_kernel`.
  8158. Then proceed to do the following tests:
  8159. * `/count.sh` and `break __x64_sys_write`
  8160. * `insmod /timer.ko` and `break lkmc_timer_callback`
  8161. ==== Test the Internet
  8162. You should also test that the Internet works:
  8163. ....
  8164. ./run --arch x86_64 --kernel-cli '- lkmc_eval="ifup -a;wget -S google.com;poweroff;"'
  8165. ....
  8166. === Bisection
  8167. When updating the Linux kernel, QEMU and gem5, things sometimes break.
  8168. 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>>.
  8169. For example, when updating from QEMU `v2.12.0` to `v3.0.0-rc3`, the Linux kernel boot started to panic for `arm`.
  8170. 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:
  8171. ....
  8172. root_dir="$(pwd)"
  8173. cd "$(./getvar qemu_source_dir)"
  8174. git bisect start
  8175. # Check that our test script fails on v3.0.0-rc3 as expected, and mark it as bad.
  8176. "${root_dir}/qemu-bisect-boot"
  8177. # Should output 1.
  8178. echo #?
  8179. git bisect bad
  8180. # Same for the good end.
  8181. git checkout v2.12.0
  8182. "${root_dir}/qemu-bisect-boot"
  8183. # Should output 0.
  8184. echo #?
  8185. git bisect good
  8186. # This leaves us at the offending commit.
  8187. git bisect run ../bisect-qemu-linux-boot
  8188. # Clean up after the bisection.
  8189. git bisect reset
  8190. git submodule update
  8191. "${root_dir}/build-qemu" --clean --qemu-build-id bisect
  8192. ....
  8193. TODO broken, fix: An example of Linux kernel commit bisection on gem5 boots can be found at: link:bisect-linux-boot-gem5[].
  8194. === Update a forked submodule
  8195. This is a template update procedure for submodules for which we have some patches on on top of mainline.
  8196. This example is based on the Linux kernel, for which we used to have patches, but have since moved to mainline:
  8197. ....
  8198. # Last point before out patches.
  8199. last_mainline_revision=v4.15
  8200. next_mainline_revision=v4.16
  8201. cd "$(./getvar linux_source_dir)"
  8202. # Create a branch before the rebase in case things go wrong.
  8203. git checkout -b "lkmc-${last_mainline_revision}"
  8204. git remote set-url origin git@github.com:cirosantilli/linux.git
  8205. git push
  8206. git checkout master
  8207. git remote add up git://git.kernel.org/pub/scm/linux/kernel/git/stable/linux-stable.git
  8208. git fetch up
  8209. git rebase --onto "$next_mainline_revision" "$last_mainline_revision"
  8210. # And update the README to show off.
  8211. git commit -m "linux: update to ${next_mainline_revision}"
  8212. ....
  8213. === Sanity checks
  8214. Basic C and C++ hello worlds:
  8215. ....
  8216. /hello.out
  8217. /hello_cpp.out
  8218. ....
  8219. Output:
  8220. ....
  8221. hello
  8222. hello cpp
  8223. ....
  8224. Sources:
  8225. * link:userland/hello.c[]
  8226. * link:userland/hello_cpp.c[]
  8227. ==== rand_check.out
  8228. Print out several parameters that normally change randomly from boot to boot:
  8229. ....
  8230. ./run --eval-after '/rand_check.out;/poweroff.out'
  8231. ....
  8232. Source: link:userland/rand_check.c[]
  8233. This can be used to check the determinism of:
  8234. * <<norandmaps>>
  8235. * <<qemu-record-and-replay>>
  8236. === Release
  8237. ==== Release procedure
  8238. Ensure that the <<automated-tests>> are passing on a clean build:
  8239. ....
  8240. mv out out.bak
  8241. ./build-test --size 3 && ./test --size 3
  8242. ....
  8243. The clean build is necessary as it generates clean images since <<remove-buildroot-packages,it is not possible to remove Buildroot packages>>
  8244. Run all tests in <<non-automated-tests>> just QEMU x86_64 and QEMU aarch64.
  8245. TODO: not working currently, so skipped: Ensure that the <<benchmark-this-repo,benchmarks>> look fine:
  8246. ....
  8247. ./bench-all -A
  8248. ....
  8249. Create a release candidate and upload it:
  8250. ....
  8251. git tag -a -m '' v3.0-rc1
  8252. git push --follow-tags
  8253. ./release-zip --all-archs
  8254. # export LKMC_GITHUB_TOKEN=<your-token>
  8255. ./release-upload
  8256. ....
  8257. Now let's do an out-of-box testing for the release candidate:
  8258. ....
  8259. cd ..
  8260. git clone https://github.com/cirosantilli/linux-kernel-module-cheat linux-kernel-module-cheat-release
  8261. cd linux-kernel-module-cheat-release
  8262. ....
  8263. Test <<prebuilt>>.
  8264. Clean up, and re-start from scratch:
  8265. ....
  8266. cd ..
  8267. rm -rf linux-kernel-module-cheat-release
  8268. git clone https://github.com/cirosantilli/linux-kernel-module-cheat linux-kernel-module-cheat-release
  8269. cd linux-kernel-module-cheat-release
  8270. ....
  8271. Go through all the other <<getting-started>> sections in order.
  8272. Once everything looks fine, publish the release with:
  8273. ....
  8274. git tag -a v3.0
  8275. # Describe the release int the tag message.
  8276. git push --follow-tags
  8277. ./release-zip --all-archs
  8278. # export LKMC_GITHUB_TOKEN=<your-token>
  8279. ./release-upload
  8280. ....
  8281. ==== release-zip
  8282. Create a zip containing all files required for <<prebuilt>>:
  8283. ....
  8284. ./build --all-archs release && ./release-zip --all-archs
  8285. ....
  8286. Source: link:release-zip[]
  8287. This generates a zip file:
  8288. ....
  8289. echo "$(./getvar release_zip_file)"
  8290. ....
  8291. which you can then upload somewhere.
  8292. ==== release-upload
  8293. After:
  8294. * running <<release-zip>>
  8295. * creating and pushing a tag to GitHub
  8296. you can upload the release to GitHub automatically with:
  8297. ....
  8298. # export LKMC_GITHUB_TOKEN=<your-token>
  8299. ./release-upload
  8300. ....
  8301. Source: link:release-upload[]
  8302. The HEAD of the local repository must be on top of a tag that has been pushed for this to work.
  8303. Create `LKMC_GITHUB_TOKEN` under: https://github.com/settings/tokens/new and save it to your `.bashrc`.
  8304. The implementation of this script is described at:
  8305. * https://stackoverflow.com/questions/5207269/how-to-release-a-build-artifact-asset-on-github-with-a-script/52354732#52354732
  8306. * https://stackoverflow.com/questions/38153418/can-someone-give-a-python-requests-example-of-uploading-a-release-asset-in-githu/52354681#52354681
  8307. === Design rationale
  8308. ==== Design goals
  8309. This project was created to help me understand, modify and test low level system components by using system simulators.
  8310. System simulators are cool compared to real hardware because they are:
  8311. * free
  8312. * make experiments highly reproducible
  8313. * give full visibility to the system: you can inspect any byte in memory, or the state of any hardware register. The laws of physics sometimes get in the way when doing that for real hardware.
  8314. The current components we focus the most on are:
  8315. * <<linux-kernel>> and Linux kernel modules
  8316. * full systems emulators, currently <<qemu-buildroot-setup,qemu>> and <<gem5-buildroot-setup,gem5>>
  8317. * <<buildroot>>. We use and therefore document, a large part of its feature set.
  8318. The following components are not covered, but they would also benefit from this setup, and it shouldn't be hard to add them:
  8319. * C standard libraries
  8320. * compilers. Project idea: add a new instruction to x86, then hack up GCC to actually use it, and make a C program that generates it.
  8321. The design goals are to provide setups that are:
  8322. * highly automated: "just works"
  8323. * thoroughly documented: you know what "just works" means
  8324. * can be fully built from source: to give visibility and allow modifications
  8325. * can also use <<prebuilt, prebuilt binaries>> as much as possible: in case you are lazy or unable to build from source
  8326. ==== Setup trade-offs
  8327. The trade-offs between the different <<getting-started,setups>> are basically a balance between:
  8328. * speed ans size: how long and how much disk space do the build and run take?
  8329. * visibility: can you GDB step debug everything and read source code?
  8330. * modifiability: can you modify the source code and rebuild a modified version?
  8331. * portability: does it work on a Windows host? Could it ever?
  8332. * accuracy: how accurate does the simulation represent real hardware?
  8333. * compatibility: how likely is is that all the components will work well together: emulator, compiler, kernel, standard library, ...
  8334. * guest software availability: how wide is your choice of easily installed guest software packages? See also: <<linux-distro-choice>>
  8335. ==== Resource tradeoff guidelines
  8336. Choosing which features go into our default builds means making tradeoffs, here are our guidelines:
  8337. * keep the root filesystem as tiny as possible to make <<prebuilt>> small: only add BusyBox to have a small interactive system.
  8338. +
  8339. It is easy to add new packages once you have the toolchain, and if you don't there are infinitely many packages to cover and we can't cover them all.
  8340. * enable every feature possible on the toolchain (GCC, Binutils), because changes imply Buildroot rebuilds
  8341. * runtime is sacred. Faster systems are:
  8342. +
  8343. --
  8344. ** easier to understand
  8345. ** run faster, which is specially for <<gem5>> which is slow
  8346. --
  8347. +
  8348. Runtime basically just comes down to how we configure the Linux kernel, since in the root filesystem all that matters is `init=`, and that is easy to control.
  8349. +
  8350. 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.
  8351. In order to learn how to measure some of those aspects, see: <<benchmark-this-repo>>
  8352. ==== Linux distro choice
  8353. We haven't found the ultimate distro yet, here is a summary table of trade-offs that we care about:
  8354. [options="header"]
  8355. |===
  8356. |Distro |Packages in single Git tree |Git tracked docs |Cross build without QEMU |Prebuilt downloads |Number of packages
  8357. |Buildroot 2018.05
  8358. |y
  8359. |y
  8360. |y
  8361. |n
  8362. |2k (1)
  8363. |Ubuntu 18.04
  8364. |n
  8365. |n
  8366. |n
  8367. |y
  8368. |50k (3)
  8369. |Yocto 2.5 (8)
  8370. |?
  8371. |y (5)
  8372. |?
  8373. |y (6)
  8374. |400 (7)
  8375. |Alpine Linux 3.8.0
  8376. |y
  8377. |n (1)
  8378. |?
  8379. |y
  8380. |2000 (4)
  8381. |===
  8382. * (1): Wiki... https://wiki.alpinelinux.org/wiki/Main_Page
  8383. * (2): `ls packages | wc`
  8384. * (3): https://askubuntu.com/questions/120630/how-many-packages-are-in-the-main-repository
  8385. * (4): `ls main community non-free | wc`
  8386. * (5): yes, but on a separate Git tree... https://git.yoctoproject.org/cgit/cgit.cgi/yocto-docs/
  8387. * (6): yes, but the initial Poky build / download still took 5 hours on <<38mbps-internet>>, and QEMU failed to boot at the end... https://bugzilla.yoctoproject.org/show_bug.cgi?id=12953
  8388. * (7): `ls recipes-* | wc`
  8389. * (8): Poky reference system: http://git.yoctoproject.org/cgit/cgit.cgi/poky
  8390. === Fairy tale
  8391. ____
  8392. Once upon a time, there was a boy called Linus.
  8393. Linus made a super fun toy, and since he was not very humble, decided to call it Linux.
  8394. Linux was an awesome toy, but it had one big problem: it was very difficult to learn how to play with it!
  8395. 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.
  8396. One day, a mysterious new kid called Ciro tried to play with Linux, and like many before him, got very frustrated, and gave up.
  8397. 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.
  8398. Ciro noticed that if you used Buildroot together with Linux, and Linux suddenly became very fun to play with!
  8399. So Ciro decided to explain to as many kids as possible how to use Buildroot to play with Linux.
  8400. And so everyone was happy. Except some of the old weird kernel hackers who wanted to keep their mystique, but so be it.
  8401. THE END
  8402. ____
  8403. === Bibliography
  8404. Runnable stuff:
  8405. * 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.
  8406. * 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.
  8407. * https://github.com/tinyclub/linux-lab Buildroot based, no kernel modules?
  8408. * https://github.com/agelastic/eudyptula
  8409. * 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/
  8410. * 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
  8411. * 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
  8412. * https://github.com/pw4ever/linux-kernel-hacking-helper as of bd9952127e7eda643cbb6cb4c51ad7b5b224f438, Bash, Arch Linux rootfs
  8413. Theory:
  8414. * 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.
  8415. +
  8416. 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...
  8417. * https://balau82.wordpress.com awesome low level resource
  8418. * https://rwmj.wordpress.com/ awesome red hatter
  8419. * https://lwn.net
  8420. * http://www.makelinux.net
  8421. * https://notes.shichao.io/lkd/
  8422. Awesome lists:
  8423. * https://github.com/gurugio/lowlevelprogramming-university
  8424. * https://github.com/uhub/awesome-c