README.adoc 370 KB

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