sleepgraph.py 233 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183
  1. #!/usr/bin/env python3
  2. # SPDX-License-Identifier: GPL-2.0-only
  3. #
  4. # Tool for analyzing suspend/resume timing
  5. # Copyright (c) 2013, Intel Corporation.
  6. #
  7. # This program is free software; you can redistribute it and/or modify it
  8. # under the terms and conditions of the GNU General Public License,
  9. # version 2, as published by the Free Software Foundation.
  10. #
  11. # This program is distributed in the hope it will be useful, but WITHOUT
  12. # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13. # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
  14. # more details.
  15. #
  16. # Authors:
  17. # Todd Brandt <todd.e.brandt@linux.intel.com>
  18. #
  19. # Links:
  20. # Home Page
  21. # https://01.org/pm-graph
  22. # Source repo
  23. # git@github.com:intel/pm-graph
  24. #
  25. # Description:
  26. # This tool is designed to assist kernel and OS developers in optimizing
  27. # their linux stack's suspend/resume time. Using a kernel image built
  28. # with a few extra options enabled, the tool will execute a suspend and
  29. # will capture dmesg and ftrace data until resume is complete. This data
  30. # is transformed into a device timeline and a callgraph to give a quick
  31. # and detailed view of which devices and callbacks are taking the most
  32. # time in suspend/resume. The output is a single html file which can be
  33. # viewed in firefox or chrome.
  34. #
  35. # The following kernel build options are required:
  36. # CONFIG_DEVMEM=y
  37. # CONFIG_PM_DEBUG=y
  38. # CONFIG_PM_SLEEP_DEBUG=y
  39. # CONFIG_FTRACE=y
  40. # CONFIG_FUNCTION_TRACER=y
  41. # CONFIG_FUNCTION_GRAPH_TRACER=y
  42. # CONFIG_KPROBES=y
  43. # CONFIG_KPROBES_ON_FTRACE=y
  44. #
  45. # For kernel versions older than 3.15:
  46. # The following additional kernel parameters are required:
  47. # (e.g. in file /etc/default/grub)
  48. # GRUB_CMDLINE_LINUX_DEFAULT="... initcall_debug log_buf_len=16M ..."
  49. #
  50. # ----------------- LIBRARIES --------------------
  51. import sys
  52. import time
  53. import os
  54. import string
  55. import re
  56. import platform
  57. import signal
  58. import codecs
  59. from datetime import datetime, timedelta
  60. import struct
  61. import configparser
  62. import gzip
  63. from threading import Thread
  64. from subprocess import call, Popen, PIPE
  65. import base64
  66. debugtiming = False
  67. mystarttime = time.time()
  68. def pprint(msg):
  69. if debugtiming:
  70. print('[%09.3f] %s' % (time.time()-mystarttime, msg))
  71. else:
  72. print(msg)
  73. sys.stdout.flush()
  74. def ascii(text):
  75. return text.decode('ascii', 'ignore')
  76. # ----------------- CLASSES --------------------
  77. # Class: SystemValues
  78. # Description:
  79. # A global, single-instance container used to
  80. # store system values and test parameters
  81. class SystemValues:
  82. title = 'SleepGraph'
  83. version = '5.12'
  84. ansi = False
  85. rs = 0
  86. display = ''
  87. gzip = False
  88. sync = False
  89. wifi = False
  90. netfix = False
  91. verbose = False
  92. testlog = True
  93. dmesglog = True
  94. ftracelog = False
  95. acpidebug = True
  96. tstat = True
  97. wifitrace = False
  98. mindevlen = 0.0001
  99. mincglen = 0.0
  100. cgphase = ''
  101. cgtest = -1
  102. cgskip = ''
  103. maxfail = 0
  104. multitest = {'run': False, 'count': 1000000, 'delay': 0}
  105. max_graph_depth = 0
  106. callloopmaxgap = 0.0001
  107. callloopmaxlen = 0.005
  108. bufsize = 0
  109. cpucount = 0
  110. memtotal = 204800
  111. memfree = 204800
  112. osversion = ''
  113. srgap = 0
  114. cgexp = False
  115. testdir = ''
  116. outdir = ''
  117. tpath = '/sys/kernel/tracing/'
  118. fpdtpath = '/sys/firmware/acpi/tables/FPDT'
  119. epath = '/sys/kernel/tracing/events/power/'
  120. pmdpath = '/sys/power/pm_debug_messages'
  121. s0ixpath = '/sys/module/intel_pmc_core/parameters/warn_on_s0ix_failures'
  122. s0ixres = '/sys/devices/system/cpu/cpuidle/low_power_idle_system_residency_us'
  123. acpipath='/sys/module/acpi/parameters/debug_level'
  124. traceevents = [
  125. 'suspend_resume',
  126. 'wakeup_source_activate',
  127. 'wakeup_source_deactivate',
  128. 'device_pm_callback_end',
  129. 'device_pm_callback_start'
  130. ]
  131. logmsg = ''
  132. testcommand = ''
  133. mempath = '/dev/mem'
  134. powerfile = '/sys/power/state'
  135. mempowerfile = '/sys/power/mem_sleep'
  136. diskpowerfile = '/sys/power/disk'
  137. suspendmode = 'mem'
  138. memmode = ''
  139. diskmode = ''
  140. hostname = 'localhost'
  141. prefix = 'test'
  142. teststamp = ''
  143. sysstamp = ''
  144. dmesgstart = 0.0
  145. dmesgfile = ''
  146. ftracefile = ''
  147. htmlfile = 'output.html'
  148. result = ''
  149. rtcwake = True
  150. rtcwaketime = 15
  151. rtcpath = ''
  152. devicefilter = []
  153. cgfilter = []
  154. stamp = 0
  155. execcount = 1
  156. x2delay = 0
  157. skiphtml = False
  158. usecallgraph = False
  159. ftopfunc = 'pm_suspend'
  160. ftop = False
  161. usetraceevents = False
  162. usetracemarkers = True
  163. useftrace = True
  164. usekprobes = True
  165. usedevsrc = False
  166. useprocmon = False
  167. notestrun = False
  168. cgdump = False
  169. devdump = False
  170. mixedphaseheight = True
  171. devprops = dict()
  172. cfgdef = dict()
  173. platinfo = []
  174. predelay = 0
  175. postdelay = 0
  176. tmstart = 'SUSPEND START %Y%m%d-%H:%M:%S.%f'
  177. tmend = 'RESUME COMPLETE %Y%m%d-%H:%M:%S.%f'
  178. tracefuncs = {
  179. 'async_synchronize_full': {},
  180. 'sys_sync': {},
  181. 'ksys_sync': {},
  182. '__pm_notifier_call_chain': {},
  183. 'pm_prepare_console': {},
  184. 'pm_notifier_call_chain': {},
  185. 'freeze_processes': {},
  186. 'freeze_kernel_threads': {},
  187. 'pm_restrict_gfp_mask': {},
  188. 'acpi_suspend_begin': {},
  189. 'acpi_hibernation_begin': {},
  190. 'acpi_hibernation_enter': {},
  191. 'acpi_hibernation_leave': {},
  192. 'acpi_pm_freeze': {},
  193. 'acpi_pm_thaw': {},
  194. 'acpi_s2idle_end': {},
  195. 'acpi_s2idle_sync': {},
  196. 'acpi_s2idle_begin': {},
  197. 'acpi_s2idle_prepare': {},
  198. 'acpi_s2idle_prepare_late': {},
  199. 'acpi_s2idle_wake': {},
  200. 'acpi_s2idle_wakeup': {},
  201. 'acpi_s2idle_restore': {},
  202. 'acpi_s2idle_restore_early': {},
  203. 'hibernate_preallocate_memory': {},
  204. 'create_basic_memory_bitmaps': {},
  205. 'swsusp_write': {},
  206. 'suspend_console': {},
  207. 'acpi_pm_prepare': {},
  208. 'syscore_suspend': {},
  209. 'arch_enable_nonboot_cpus_end': {},
  210. 'syscore_resume': {},
  211. 'acpi_pm_finish': {},
  212. 'resume_console': {},
  213. 'acpi_pm_end': {},
  214. 'pm_restore_gfp_mask': {},
  215. 'thaw_processes': {},
  216. 'pm_restore_console': {},
  217. 'CPU_OFF': {
  218. 'func':'_cpu_down',
  219. 'args_x86_64': {'cpu':'%di:s32'},
  220. 'format': 'CPU_OFF[{cpu}]'
  221. },
  222. 'CPU_ON': {
  223. 'func':'_cpu_up',
  224. 'args_x86_64': {'cpu':'%di:s32'},
  225. 'format': 'CPU_ON[{cpu}]'
  226. },
  227. }
  228. dev_tracefuncs = {
  229. # general wait/delay/sleep
  230. 'msleep': { 'args_x86_64': {'time':'%di:s32'}, 'ub': 1 },
  231. 'schedule_timeout': { 'args_x86_64': {'timeout':'%di:s32'}, 'ub': 1 },
  232. 'udelay': { 'func':'__const_udelay', 'args_x86_64': {'loops':'%di:s32'}, 'ub': 1 },
  233. 'usleep_range': { 'args_x86_64': {'min':'%di:s32', 'max':'%si:s32'}, 'ub': 1 },
  234. 'mutex_lock_slowpath': { 'func':'__mutex_lock_slowpath', 'ub': 1 },
  235. 'acpi_os_stall': {'ub': 1},
  236. 'rt_mutex_slowlock': {'ub': 1},
  237. # ACPI
  238. 'acpi_resume_power_resources': {},
  239. 'acpi_ps_execute_method': { 'args_x86_64': {
  240. 'fullpath':'+0(+40(%di)):string',
  241. }},
  242. # mei_me
  243. 'mei_reset': {},
  244. # filesystem
  245. 'ext4_sync_fs': {},
  246. # 80211
  247. 'ath10k_bmi_read_memory': { 'args_x86_64': {'length':'%cx:s32'} },
  248. 'ath10k_bmi_write_memory': { 'args_x86_64': {'length':'%cx:s32'} },
  249. 'ath10k_bmi_fast_download': { 'args_x86_64': {'length':'%cx:s32'} },
  250. 'iwlagn_mac_start': {},
  251. 'iwlagn_alloc_bcast_station': {},
  252. 'iwl_trans_pcie_start_hw': {},
  253. 'iwl_trans_pcie_start_fw': {},
  254. 'iwl_run_init_ucode': {},
  255. 'iwl_load_ucode_wait_alive': {},
  256. 'iwl_alive_start': {},
  257. 'iwlagn_mac_stop': {},
  258. 'iwlagn_mac_suspend': {},
  259. 'iwlagn_mac_resume': {},
  260. 'iwlagn_mac_add_interface': {},
  261. 'iwlagn_mac_remove_interface': {},
  262. 'iwlagn_mac_change_interface': {},
  263. 'iwlagn_mac_config': {},
  264. 'iwlagn_configure_filter': {},
  265. 'iwlagn_mac_hw_scan': {},
  266. 'iwlagn_bss_info_changed': {},
  267. 'iwlagn_mac_channel_switch': {},
  268. 'iwlagn_mac_flush': {},
  269. # ATA
  270. 'ata_eh_recover': { 'args_x86_64': {'port':'+36(%di):s32'} },
  271. # i915
  272. 'i915_gem_resume': {},
  273. 'i915_restore_state': {},
  274. 'intel_opregion_setup': {},
  275. 'g4x_pre_enable_dp': {},
  276. 'vlv_pre_enable_dp': {},
  277. 'chv_pre_enable_dp': {},
  278. 'g4x_enable_dp': {},
  279. 'vlv_enable_dp': {},
  280. 'intel_hpd_init': {},
  281. 'intel_opregion_register': {},
  282. 'intel_dp_detect': {},
  283. 'intel_hdmi_detect': {},
  284. 'intel_opregion_init': {},
  285. 'intel_fbdev_set_suspend': {},
  286. }
  287. infocmds = [
  288. [0, 'sysinfo', 'uname', '-a'],
  289. [0, 'cpuinfo', 'head', '-7', '/proc/cpuinfo'],
  290. [0, 'kparams', 'cat', '/proc/cmdline'],
  291. [0, 'mcelog', 'mcelog'],
  292. [0, 'pcidevices', 'lspci', '-tv'],
  293. [0, 'usbdevices', 'lsusb', '-tv'],
  294. [0, 'acpidevices', 'sh', '-c', 'ls -l /sys/bus/acpi/devices/*/physical_node'],
  295. [0, 's0ix_require', 'cat', '/sys/kernel/debug/pmc_core/substate_requirements'],
  296. [0, 's0ix_debug', 'cat', '/sys/kernel/debug/pmc_core/slp_s0_debug_status'],
  297. [0, 'ethtool', 'ethtool', '{ethdev}'],
  298. [1, 's0ix_residency', 'cat', '/sys/kernel/debug/pmc_core/slp_s0_residency_usec'],
  299. [1, 'interrupts', 'cat', '/proc/interrupts'],
  300. [1, 'wakeups', 'cat', '/sys/kernel/debug/wakeup_sources'],
  301. [2, 'gpecounts', 'sh', '-c', 'grep -v invalid /sys/firmware/acpi/interrupts/*'],
  302. [2, 'suspendstats', 'sh', '-c', 'grep -v invalid /sys/power/suspend_stats/*'],
  303. [2, 'cpuidle', 'sh', '-c', 'grep -v invalid /sys/devices/system/cpu/cpu*/cpuidle/state*/s2idle/*'],
  304. [2, 'battery', 'sh', '-c', 'grep -v invalid /sys/class/power_supply/*/*'],
  305. [2, 'thermal', 'sh', '-c', 'grep . /sys/class/thermal/thermal_zone*/temp'],
  306. ]
  307. cgblacklist = []
  308. kprobes = dict()
  309. timeformat = '%.3f'
  310. cmdline = '%s %s' % \
  311. (os.path.basename(sys.argv[0]), ' '.join(sys.argv[1:]))
  312. sudouser = ''
  313. def __init__(self):
  314. self.archargs = 'args_'+platform.machine()
  315. self.hostname = platform.node()
  316. if(self.hostname == ''):
  317. self.hostname = 'localhost'
  318. rtc = "rtc0"
  319. if os.path.exists('/dev/rtc'):
  320. rtc = os.readlink('/dev/rtc')
  321. rtc = '/sys/class/rtc/'+rtc
  322. if os.path.exists(rtc) and os.path.exists(rtc+'/date') and \
  323. os.path.exists(rtc+'/time') and os.path.exists(rtc+'/wakealarm'):
  324. self.rtcpath = rtc
  325. if (hasattr(sys.stdout, 'isatty') and sys.stdout.isatty()):
  326. self.ansi = True
  327. self.testdir = datetime.now().strftime('suspend-%y%m%d-%H%M%S')
  328. if os.getuid() == 0 and 'SUDO_USER' in os.environ and \
  329. os.environ['SUDO_USER']:
  330. self.sudouser = os.environ['SUDO_USER']
  331. def resetlog(self):
  332. self.logmsg = ''
  333. self.platinfo = []
  334. def vprint(self, msg):
  335. self.logmsg += msg+'\n'
  336. if self.verbose or msg.startswith('WARNING:'):
  337. pprint(msg)
  338. def signalHandler(self, signum, frame):
  339. if not self.result:
  340. return
  341. signame = self.signames[signum] if signum in self.signames else 'UNKNOWN'
  342. msg = 'Signal %s caused a tool exit, line %d' % (signame, frame.f_lineno)
  343. self.outputResult({'error':msg})
  344. sys.exit(3)
  345. def signalHandlerInit(self):
  346. capture = ['BUS', 'SYS', 'XCPU', 'XFSZ', 'PWR', 'HUP', 'INT', 'QUIT',
  347. 'ILL', 'ABRT', 'FPE', 'SEGV', 'TERM']
  348. self.signames = dict()
  349. for i in capture:
  350. s = 'SIG'+i
  351. try:
  352. signum = getattr(signal, s)
  353. signal.signal(signum, self.signalHandler)
  354. except:
  355. continue
  356. self.signames[signum] = s
  357. def rootCheck(self, fatal=True):
  358. if(os.access(self.powerfile, os.W_OK)):
  359. return True
  360. if fatal:
  361. msg = 'This command requires sysfs mount and root access'
  362. pprint('ERROR: %s\n' % msg)
  363. self.outputResult({'error':msg})
  364. sys.exit(1)
  365. return False
  366. def rootUser(self, fatal=False):
  367. if 'USER' in os.environ and os.environ['USER'] == 'root':
  368. return True
  369. if fatal:
  370. msg = 'This command must be run as root'
  371. pprint('ERROR: %s\n' % msg)
  372. self.outputResult({'error':msg})
  373. sys.exit(1)
  374. return False
  375. def usable(self, file, ishtml=False):
  376. if not os.path.exists(file) or os.path.getsize(file) < 1:
  377. return False
  378. if ishtml:
  379. try:
  380. fp = open(file, 'r')
  381. res = fp.read(1000)
  382. fp.close()
  383. except:
  384. return False
  385. if '<html>' not in res:
  386. return False
  387. return True
  388. def getExec(self, cmd):
  389. try:
  390. fp = Popen(['which', cmd], stdout=PIPE, stderr=PIPE).stdout
  391. out = ascii(fp.read()).strip()
  392. fp.close()
  393. except:
  394. out = ''
  395. if out:
  396. return out
  397. for path in ['/sbin', '/bin', '/usr/sbin', '/usr/bin',
  398. '/usr/local/sbin', '/usr/local/bin']:
  399. cmdfull = os.path.join(path, cmd)
  400. if os.path.exists(cmdfull):
  401. return cmdfull
  402. return out
  403. def setPrecision(self, num):
  404. if num < 0 or num > 6:
  405. return
  406. self.timeformat = '%.{0}f'.format(num)
  407. def setOutputFolder(self, value):
  408. args = dict()
  409. n = datetime.now()
  410. args['date'] = n.strftime('%y%m%d')
  411. args['time'] = n.strftime('%H%M%S')
  412. args['hostname'] = args['host'] = self.hostname
  413. args['mode'] = self.suspendmode
  414. return value.format(**args)
  415. def setOutputFile(self):
  416. if self.dmesgfile != '':
  417. m = re.match(r'(?P<name>.*)_dmesg\.txt.*', self.dmesgfile)
  418. if(m):
  419. self.htmlfile = m.group('name')+'.html'
  420. if self.ftracefile != '':
  421. m = re.match(r'(?P<name>.*)_ftrace\.txt.*', self.ftracefile)
  422. if(m):
  423. self.htmlfile = m.group('name')+'.html'
  424. def systemInfo(self, info):
  425. p = m = ''
  426. if 'baseboard-manufacturer' in info:
  427. m = info['baseboard-manufacturer']
  428. elif 'system-manufacturer' in info:
  429. m = info['system-manufacturer']
  430. if 'system-product-name' in info:
  431. p = info['system-product-name']
  432. elif 'baseboard-product-name' in info:
  433. p = info['baseboard-product-name']
  434. if m[:5].lower() == 'intel' and 'baseboard-product-name' in info:
  435. p = info['baseboard-product-name']
  436. c = info['processor-version'] if 'processor-version' in info else ''
  437. b = info['bios-version'] if 'bios-version' in info else ''
  438. r = info['bios-release-date'] if 'bios-release-date' in info else ''
  439. self.sysstamp = '# sysinfo | man:%s | plat:%s | cpu:%s | bios:%s | biosdate:%s | numcpu:%d | memsz:%d | memfr:%d' % \
  440. (m, p, c, b, r, self.cpucount, self.memtotal, self.memfree)
  441. if self.osversion:
  442. self.sysstamp += ' | os:%s' % self.osversion
  443. def printSystemInfo(self, fatal=False):
  444. self.rootCheck(True)
  445. out = dmidecode(self.mempath, fatal)
  446. if len(out) < 1:
  447. return
  448. fmt = '%-24s: %s'
  449. if self.osversion:
  450. print(fmt % ('os-version', self.osversion))
  451. for name in sorted(out):
  452. print(fmt % (name, out[name]))
  453. print(fmt % ('cpucount', ('%d' % self.cpucount)))
  454. print(fmt % ('memtotal', ('%d kB' % self.memtotal)))
  455. print(fmt % ('memfree', ('%d kB' % self.memfree)))
  456. def cpuInfo(self):
  457. self.cpucount = 0
  458. if os.path.exists('/proc/cpuinfo'):
  459. with open('/proc/cpuinfo', 'r') as fp:
  460. for line in fp:
  461. if re.match(r'^processor[ \t]*:[ \t]*[0-9]*', line):
  462. self.cpucount += 1
  463. if os.path.exists('/proc/meminfo'):
  464. with open('/proc/meminfo', 'r') as fp:
  465. for line in fp:
  466. m = re.match(r'^MemTotal:[ \t]*(?P<sz>[0-9]*) *kB', line)
  467. if m:
  468. self.memtotal = int(m.group('sz'))
  469. m = re.match(r'^MemFree:[ \t]*(?P<sz>[0-9]*) *kB', line)
  470. if m:
  471. self.memfree = int(m.group('sz'))
  472. if os.path.exists('/etc/os-release'):
  473. with open('/etc/os-release', 'r') as fp:
  474. for line in fp:
  475. if line.startswith('PRETTY_NAME='):
  476. self.osversion = line[12:].strip().replace('"', '')
  477. def initTestOutput(self, name):
  478. self.prefix = self.hostname
  479. v = open('/proc/version', 'r').read().strip()
  480. kver = v.split()[2]
  481. fmt = name+'-%m%d%y-%H%M%S'
  482. testtime = datetime.now().strftime(fmt)
  483. self.teststamp = \
  484. '# '+testtime+' '+self.prefix+' '+self.suspendmode+' '+kver
  485. ext = ''
  486. if self.gzip:
  487. ext = '.gz'
  488. self.dmesgfile = \
  489. self.testdir+'/'+self.prefix+'_'+self.suspendmode+'_dmesg.txt'+ext
  490. self.ftracefile = \
  491. self.testdir+'/'+self.prefix+'_'+self.suspendmode+'_ftrace.txt'+ext
  492. self.htmlfile = \
  493. self.testdir+'/'+self.prefix+'_'+self.suspendmode+'.html'
  494. if not os.path.isdir(self.testdir):
  495. os.makedirs(self.testdir)
  496. self.sudoUserchown(self.testdir)
  497. def getValueList(self, value):
  498. out = []
  499. for i in value.split(','):
  500. if i.strip():
  501. out.append(i.strip())
  502. return out
  503. def setDeviceFilter(self, value):
  504. self.devicefilter = self.getValueList(value)
  505. def setCallgraphFilter(self, value):
  506. self.cgfilter = self.getValueList(value)
  507. def skipKprobes(self, value):
  508. for k in self.getValueList(value):
  509. if k in self.tracefuncs:
  510. del self.tracefuncs[k]
  511. if k in self.dev_tracefuncs:
  512. del self.dev_tracefuncs[k]
  513. def setCallgraphBlacklist(self, file):
  514. self.cgblacklist = self.listFromFile(file)
  515. def rtcWakeAlarmOn(self):
  516. call('echo 0 > '+self.rtcpath+'/wakealarm', shell=True)
  517. nowtime = open(self.rtcpath+'/since_epoch', 'r').read().strip()
  518. if nowtime:
  519. nowtime = int(nowtime)
  520. else:
  521. # if hardware time fails, use the software time
  522. nowtime = int(datetime.now().strftime('%s'))
  523. alarm = nowtime + self.rtcwaketime
  524. call('echo %d > %s/wakealarm' % (alarm, self.rtcpath), shell=True)
  525. def rtcWakeAlarmOff(self):
  526. call('echo 0 > %s/wakealarm' % self.rtcpath, shell=True)
  527. def initdmesg(self):
  528. # get the latest time stamp from the dmesg log
  529. lines = Popen('dmesg', stdout=PIPE).stdout.readlines()
  530. ktime = '0'
  531. for line in reversed(lines):
  532. line = ascii(line).replace('\r\n', '')
  533. idx = line.find('[')
  534. if idx > 1:
  535. line = line[idx:]
  536. m = re.match(r'[ \t]*(\[ *)(?P<ktime>[0-9\.]*)(\]) (?P<msg>.*)', line)
  537. if(m):
  538. ktime = m.group('ktime')
  539. break
  540. self.dmesgstart = float(ktime)
  541. def getdmesg(self, testdata):
  542. op = self.writeDatafileHeader(self.dmesgfile, testdata)
  543. # store all new dmesg lines since initdmesg was called
  544. fp = Popen('dmesg', stdout=PIPE).stdout
  545. for line in fp:
  546. line = ascii(line).replace('\r\n', '')
  547. idx = line.find('[')
  548. if idx > 1:
  549. line = line[idx:]
  550. m = re.match(r'[ \t]*(\[ *)(?P<ktime>[0-9\.]*)(\]) (?P<msg>.*)', line)
  551. if(not m):
  552. continue
  553. ktime = float(m.group('ktime'))
  554. if ktime > self.dmesgstart:
  555. op.write(line)
  556. fp.close()
  557. op.close()
  558. def listFromFile(self, file):
  559. list = []
  560. fp = open(file)
  561. for i in fp.read().split('\n'):
  562. i = i.strip()
  563. if i and i[0] != '#':
  564. list.append(i)
  565. fp.close()
  566. return list
  567. def addFtraceFilterFunctions(self, file):
  568. for i in self.listFromFile(file):
  569. if len(i) < 2:
  570. continue
  571. self.tracefuncs[i] = dict()
  572. def getFtraceFilterFunctions(self, current):
  573. self.rootCheck(True)
  574. if not current:
  575. call('cat '+self.tpath+'available_filter_functions', shell=True)
  576. return
  577. master = self.listFromFile(self.tpath+'available_filter_functions')
  578. for i in sorted(self.tracefuncs):
  579. if 'func' in self.tracefuncs[i]:
  580. i = self.tracefuncs[i]['func']
  581. if i in master:
  582. print(i)
  583. else:
  584. print(self.colorText(i))
  585. def setFtraceFilterFunctions(self, list):
  586. master = self.listFromFile(self.tpath+'available_filter_functions')
  587. flist = ''
  588. for i in list:
  589. if i not in master:
  590. continue
  591. if ' [' in i:
  592. flist += i.split(' ')[0]+'\n'
  593. else:
  594. flist += i+'\n'
  595. fp = open(self.tpath+'set_graph_function', 'w')
  596. fp.write(flist)
  597. fp.close()
  598. def basicKprobe(self, name):
  599. self.kprobes[name] = {'name': name,'func': name,'args': dict(),'format': name}
  600. def defaultKprobe(self, name, kdata):
  601. k = kdata
  602. for field in ['name', 'format', 'func']:
  603. if field not in k:
  604. k[field] = name
  605. if self.archargs in k:
  606. k['args'] = k[self.archargs]
  607. else:
  608. k['args'] = dict()
  609. k['format'] = name
  610. self.kprobes[name] = k
  611. def kprobeColor(self, name):
  612. if name not in self.kprobes or 'color' not in self.kprobes[name]:
  613. return ''
  614. return self.kprobes[name]['color']
  615. def kprobeDisplayName(self, name, dataraw):
  616. if name not in self.kprobes:
  617. self.basicKprobe(name)
  618. data = ''
  619. quote=0
  620. # first remvoe any spaces inside quotes, and the quotes
  621. for c in dataraw:
  622. if c == '"':
  623. quote = (quote + 1) % 2
  624. if quote and c == ' ':
  625. data += '_'
  626. elif c != '"':
  627. data += c
  628. fmt, args = self.kprobes[name]['format'], self.kprobes[name]['args']
  629. arglist = dict()
  630. # now process the args
  631. for arg in sorted(args):
  632. arglist[arg] = ''
  633. m = re.match(r'.* '+arg+'=(?P<arg>.*) ', data);
  634. if m:
  635. arglist[arg] = m.group('arg')
  636. else:
  637. m = re.match(r'.* '+arg+'=(?P<arg>.*)', data);
  638. if m:
  639. arglist[arg] = m.group('arg')
  640. out = fmt.format(**arglist)
  641. out = out.replace(' ', '_').replace('"', '')
  642. return out
  643. def kprobeText(self, kname, kprobe):
  644. name = fmt = func = kname
  645. args = dict()
  646. if 'name' in kprobe:
  647. name = kprobe['name']
  648. if 'format' in kprobe:
  649. fmt = kprobe['format']
  650. if 'func' in kprobe:
  651. func = kprobe['func']
  652. if self.archargs in kprobe:
  653. args = kprobe[self.archargs]
  654. if 'args' in kprobe:
  655. args = kprobe['args']
  656. if re.findall('{(?P<n>[a-z,A-Z,0-9]*)}', func):
  657. doError('Kprobe "%s" has format info in the function name "%s"' % (name, func))
  658. for arg in re.findall('{(?P<n>[a-z,A-Z,0-9]*)}', fmt):
  659. if arg not in args:
  660. doError('Kprobe "%s" is missing argument "%s"' % (name, arg))
  661. val = 'p:%s_cal %s' % (name, func)
  662. for i in sorted(args):
  663. val += ' %s=%s' % (i, args[i])
  664. val += '\nr:%s_ret %s $retval\n' % (name, func)
  665. return val
  666. def addKprobes(self, output=False):
  667. if len(self.kprobes) < 1:
  668. return
  669. if output:
  670. pprint(' kprobe functions in this kernel:')
  671. # first test each kprobe
  672. rejects = []
  673. # sort kprobes: trace, ub-dev, custom, dev
  674. kpl = [[], [], [], []]
  675. linesout = len(self.kprobes)
  676. for name in sorted(self.kprobes):
  677. res = self.colorText('YES', 32)
  678. if not self.testKprobe(name, self.kprobes[name]):
  679. res = self.colorText('NO')
  680. rejects.append(name)
  681. else:
  682. if name in self.tracefuncs:
  683. kpl[0].append(name)
  684. elif name in self.dev_tracefuncs:
  685. if 'ub' in self.dev_tracefuncs[name]:
  686. kpl[1].append(name)
  687. else:
  688. kpl[3].append(name)
  689. else:
  690. kpl[2].append(name)
  691. if output:
  692. pprint(' %s: %s' % (name, res))
  693. kplist = kpl[0] + kpl[1] + kpl[2] + kpl[3]
  694. # remove all failed ones from the list
  695. for name in rejects:
  696. self.kprobes.pop(name)
  697. # set the kprobes all at once
  698. self.fsetVal('', 'kprobe_events')
  699. kprobeevents = ''
  700. for kp in kplist:
  701. kprobeevents += self.kprobeText(kp, self.kprobes[kp])
  702. self.fsetVal(kprobeevents, 'kprobe_events')
  703. if output:
  704. check = self.fgetVal('kprobe_events')
  705. linesack = (len(check.split('\n')) - 1) // 2
  706. pprint(' kprobe functions enabled: %d/%d' % (linesack, linesout))
  707. self.fsetVal('1', 'events/kprobes/enable')
  708. def testKprobe(self, kname, kprobe):
  709. self.fsetVal('0', 'events/kprobes/enable')
  710. kprobeevents = self.kprobeText(kname, kprobe)
  711. if not kprobeevents:
  712. return False
  713. try:
  714. self.fsetVal(kprobeevents, 'kprobe_events')
  715. check = self.fgetVal('kprobe_events')
  716. except:
  717. return False
  718. linesout = len(kprobeevents.split('\n'))
  719. linesack = len(check.split('\n'))
  720. if linesack < linesout:
  721. return False
  722. return True
  723. def setVal(self, val, file):
  724. if not os.path.exists(file):
  725. return False
  726. try:
  727. fp = open(file, 'wb', 0)
  728. fp.write(val.encode())
  729. fp.flush()
  730. fp.close()
  731. except:
  732. return False
  733. return True
  734. def fsetVal(self, val, path):
  735. if not self.useftrace:
  736. return False
  737. return self.setVal(val, self.tpath+path)
  738. def getVal(self, file):
  739. res = ''
  740. if not os.path.exists(file):
  741. return res
  742. try:
  743. fp = open(file, 'r')
  744. res = fp.read()
  745. fp.close()
  746. except:
  747. pass
  748. return res
  749. def fgetVal(self, path):
  750. if not self.useftrace:
  751. return ''
  752. return self.getVal(self.tpath+path)
  753. def cleanupFtrace(self):
  754. if self.useftrace:
  755. self.fsetVal('0', 'events/kprobes/enable')
  756. self.fsetVal('', 'kprobe_events')
  757. self.fsetVal('1024', 'buffer_size_kb')
  758. def setupAllKprobes(self):
  759. for name in self.tracefuncs:
  760. self.defaultKprobe(name, self.tracefuncs[name])
  761. for name in self.dev_tracefuncs:
  762. self.defaultKprobe(name, self.dev_tracefuncs[name])
  763. def isCallgraphFunc(self, name):
  764. if len(self.tracefuncs) < 1 and self.suspendmode == 'command':
  765. return True
  766. for i in self.tracefuncs:
  767. if 'func' in self.tracefuncs[i]:
  768. f = self.tracefuncs[i]['func']
  769. else:
  770. f = i
  771. if name == f:
  772. return True
  773. return False
  774. def initFtrace(self, quiet=False):
  775. if not self.useftrace:
  776. return
  777. if not quiet:
  778. sysvals.printSystemInfo(False)
  779. pprint('INITIALIZING FTRACE')
  780. # turn trace off
  781. self.fsetVal('0', 'tracing_on')
  782. self.cleanupFtrace()
  783. # set the trace clock to global
  784. self.fsetVal('global', 'trace_clock')
  785. self.fsetVal('nop', 'current_tracer')
  786. # set trace buffer to an appropriate value
  787. cpus = max(1, self.cpucount)
  788. if self.bufsize > 0:
  789. tgtsize = self.bufsize
  790. elif self.usecallgraph or self.usedevsrc:
  791. bmax = (1*1024*1024) if self.suspendmode in ['disk', 'command'] \
  792. else (3*1024*1024)
  793. tgtsize = min(self.memfree, bmax)
  794. else:
  795. tgtsize = 65536
  796. while not self.fsetVal('%d' % (tgtsize // cpus), 'buffer_size_kb'):
  797. # if the size failed to set, lower it and keep trying
  798. tgtsize -= 65536
  799. if tgtsize < 65536:
  800. tgtsize = int(self.fgetVal('buffer_size_kb')) * cpus
  801. break
  802. self.vprint('Setting trace buffers to %d kB (%d kB per cpu)' % (tgtsize, tgtsize/cpus))
  803. # initialize the callgraph trace
  804. if(self.usecallgraph):
  805. # set trace type
  806. self.fsetVal('function_graph', 'current_tracer')
  807. self.fsetVal('', 'set_ftrace_filter')
  808. # temporary hack to fix https://bugzilla.kernel.org/show_bug.cgi?id=212761
  809. fp = open(self.tpath+'set_ftrace_notrace', 'w')
  810. fp.write('native_queued_spin_lock_slowpath\ndev_driver_string')
  811. fp.close()
  812. # set trace format options
  813. self.fsetVal('print-parent', 'trace_options')
  814. self.fsetVal('funcgraph-abstime', 'trace_options')
  815. self.fsetVal('funcgraph-cpu', 'trace_options')
  816. self.fsetVal('funcgraph-duration', 'trace_options')
  817. self.fsetVal('funcgraph-proc', 'trace_options')
  818. self.fsetVal('funcgraph-tail', 'trace_options')
  819. self.fsetVal('nofuncgraph-overhead', 'trace_options')
  820. self.fsetVal('context-info', 'trace_options')
  821. self.fsetVal('graph-time', 'trace_options')
  822. self.fsetVal('%d' % self.max_graph_depth, 'max_graph_depth')
  823. cf = ['dpm_run_callback']
  824. if(self.usetraceevents):
  825. cf += ['dpm_prepare', 'dpm_complete']
  826. for fn in self.tracefuncs:
  827. if 'func' in self.tracefuncs[fn]:
  828. cf.append(self.tracefuncs[fn]['func'])
  829. else:
  830. cf.append(fn)
  831. if self.ftop:
  832. self.setFtraceFilterFunctions([self.ftopfunc])
  833. else:
  834. self.setFtraceFilterFunctions(cf)
  835. # initialize the kprobe trace
  836. elif self.usekprobes:
  837. for name in self.tracefuncs:
  838. self.defaultKprobe(name, self.tracefuncs[name])
  839. if self.usedevsrc:
  840. for name in self.dev_tracefuncs:
  841. self.defaultKprobe(name, self.dev_tracefuncs[name])
  842. if not quiet:
  843. pprint('INITIALIZING KPROBES')
  844. self.addKprobes(self.verbose)
  845. if(self.usetraceevents):
  846. # turn trace events on
  847. events = iter(self.traceevents)
  848. for e in events:
  849. self.fsetVal('1', 'events/power/'+e+'/enable')
  850. # clear the trace buffer
  851. self.fsetVal('', 'trace')
  852. def verifyFtrace(self):
  853. # files needed for any trace data
  854. files = ['buffer_size_kb', 'current_tracer', 'trace', 'trace_clock',
  855. 'trace_marker', 'trace_options', 'tracing_on']
  856. # files needed for callgraph trace data
  857. tp = self.tpath
  858. if(self.usecallgraph):
  859. files += [
  860. 'available_filter_functions',
  861. 'set_ftrace_filter',
  862. 'set_graph_function'
  863. ]
  864. for f in files:
  865. if(os.path.exists(tp+f) == False):
  866. return False
  867. return True
  868. def verifyKprobes(self):
  869. # files needed for kprobes to work
  870. files = ['kprobe_events', 'events']
  871. tp = self.tpath
  872. for f in files:
  873. if(os.path.exists(tp+f) == False):
  874. return False
  875. return True
  876. def colorText(self, str, color=31):
  877. if not self.ansi:
  878. return str
  879. return '\x1B[%d;40m%s\x1B[m' % (color, str)
  880. def writeDatafileHeader(self, filename, testdata):
  881. fp = self.openlog(filename, 'w')
  882. fp.write('%s\n%s\n# command | %s\n' % (self.teststamp, self.sysstamp, self.cmdline))
  883. for test in testdata:
  884. if 'fw' in test:
  885. fw = test['fw']
  886. if(fw):
  887. fp.write('# fwsuspend %u fwresume %u\n' % (fw[0], fw[1]))
  888. if 'turbo' in test:
  889. fp.write('# turbostat %s\n' % test['turbo'])
  890. if 'wifi' in test:
  891. fp.write('# wifi %s\n' % test['wifi'])
  892. if 'netfix' in test:
  893. fp.write('# netfix %s\n' % test['netfix'])
  894. if test['error'] or len(testdata) > 1:
  895. fp.write('# enter_sleep_error %s\n' % test['error'])
  896. return fp
  897. def sudoUserchown(self, dir):
  898. if os.path.exists(dir) and self.sudouser:
  899. cmd = 'chown -R {0}:{0} {1} > /dev/null 2>&1'
  900. call(cmd.format(self.sudouser, dir), shell=True)
  901. def outputResult(self, testdata, num=0):
  902. if not self.result:
  903. return
  904. n = ''
  905. if num > 0:
  906. n = '%d' % num
  907. fp = open(self.result, 'a')
  908. if 'error' in testdata:
  909. fp.write('result%s: fail\n' % n)
  910. fp.write('error%s: %s\n' % (n, testdata['error']))
  911. else:
  912. fp.write('result%s: pass\n' % n)
  913. if 'mode' in testdata:
  914. fp.write('mode%s: %s\n' % (n, testdata['mode']))
  915. for v in ['suspend', 'resume', 'boot', 'lastinit']:
  916. if v in testdata:
  917. fp.write('%s%s: %.3f\n' % (v, n, testdata[v]))
  918. for v in ['fwsuspend', 'fwresume']:
  919. if v in testdata:
  920. fp.write('%s%s: %.3f\n' % (v, n, testdata[v] / 1000000.0))
  921. if 'bugurl' in testdata:
  922. fp.write('url%s: %s\n' % (n, testdata['bugurl']))
  923. fp.close()
  924. self.sudoUserchown(self.result)
  925. def configFile(self, file):
  926. dir = os.path.dirname(os.path.realpath(__file__))
  927. if os.path.exists(file):
  928. return file
  929. elif os.path.exists(dir+'/'+file):
  930. return dir+'/'+file
  931. elif os.path.exists(dir+'/config/'+file):
  932. return dir+'/config/'+file
  933. return ''
  934. def openlog(self, filename, mode):
  935. isgz = self.gzip
  936. if mode == 'r':
  937. try:
  938. with gzip.open(filename, mode+'t') as fp:
  939. test = fp.read(64)
  940. isgz = True
  941. except:
  942. isgz = False
  943. if isgz:
  944. return gzip.open(filename, mode+'t')
  945. return open(filename, mode)
  946. def putlog(self, filename, text):
  947. with self.openlog(filename, 'a') as fp:
  948. fp.write(text)
  949. fp.close()
  950. def dlog(self, text):
  951. if not self.dmesgfile:
  952. return
  953. self.putlog(self.dmesgfile, '# %s\n' % text)
  954. def flog(self, text):
  955. self.putlog(self.ftracefile, text)
  956. def b64unzip(self, data):
  957. try:
  958. out = codecs.decode(base64.b64decode(data), 'zlib').decode()
  959. except:
  960. out = data
  961. return out
  962. def b64zip(self, data):
  963. out = base64.b64encode(codecs.encode(data.encode(), 'zlib')).decode()
  964. return out
  965. def platforminfo(self, cmdafter):
  966. # add platform info on to a completed ftrace file
  967. if not os.path.exists(self.ftracefile):
  968. return False
  969. footer = '#\n'
  970. # add test command string line if need be
  971. if self.suspendmode == 'command' and self.testcommand:
  972. footer += '# platform-testcmd: %s\n' % (self.testcommand)
  973. # get a list of target devices from the ftrace file
  974. props = dict()
  975. tp = TestProps()
  976. tf = self.openlog(self.ftracefile, 'r')
  977. for line in tf:
  978. if tp.stampInfo(line, self):
  979. continue
  980. # parse only valid lines, if this is not one move on
  981. m = re.match(tp.ftrace_line_fmt, line)
  982. if(not m or 'device_pm_callback_start' not in line):
  983. continue
  984. m = re.match(r'.*: (?P<drv>.*) (?P<d>.*), parent: *(?P<p>.*), .*', m.group('msg'));
  985. if(not m):
  986. continue
  987. dev = m.group('d')
  988. if dev not in props:
  989. props[dev] = DevProps()
  990. tf.close()
  991. # now get the syspath for each target device
  992. for dirname, dirnames, filenames in os.walk('/sys/devices'):
  993. if(re.match(r'.*/power', dirname) and 'async' in filenames):
  994. dev = dirname.split('/')[-2]
  995. if dev in props and (not props[dev].syspath or len(dirname) < len(props[dev].syspath)):
  996. props[dev].syspath = dirname[:-6]
  997. # now fill in the properties for our target devices
  998. for dev in sorted(props):
  999. dirname = props[dev].syspath
  1000. if not dirname or not os.path.exists(dirname):
  1001. continue
  1002. props[dev].isasync = False
  1003. if os.path.exists(dirname+'/power/async'):
  1004. fp = open(dirname+'/power/async')
  1005. if 'enabled' in fp.read():
  1006. props[dev].isasync = True
  1007. fp.close()
  1008. fields = os.listdir(dirname)
  1009. for file in ['product', 'name', 'model', 'description', 'id', 'idVendor']:
  1010. if file not in fields:
  1011. continue
  1012. try:
  1013. with open(os.path.join(dirname, file), 'rb') as fp:
  1014. props[dev].altname = ascii(fp.read())
  1015. except:
  1016. continue
  1017. if file == 'idVendor':
  1018. idv, idp = props[dev].altname.strip(), ''
  1019. try:
  1020. with open(os.path.join(dirname, 'idProduct'), 'rb') as fp:
  1021. idp = ascii(fp.read()).strip()
  1022. except:
  1023. props[dev].altname = ''
  1024. break
  1025. props[dev].altname = '%s:%s' % (idv, idp)
  1026. break
  1027. if props[dev].altname:
  1028. out = props[dev].altname.strip().replace('\n', ' ')\
  1029. .replace(',', ' ').replace(';', ' ')
  1030. props[dev].altname = out
  1031. # add a devinfo line to the bottom of ftrace
  1032. out = ''
  1033. for dev in sorted(props):
  1034. out += props[dev].out(dev)
  1035. footer += '# platform-devinfo: %s\n' % self.b64zip(out)
  1036. # add a line for each of these commands with their outputs
  1037. for name, cmdline, info in cmdafter:
  1038. footer += '# platform-%s: %s | %s\n' % (name, cmdline, self.b64zip(info))
  1039. self.flog(footer)
  1040. return True
  1041. def commonPrefix(self, list):
  1042. if len(list) < 2:
  1043. return ''
  1044. prefix = list[0]
  1045. for s in list[1:]:
  1046. while s[:len(prefix)] != prefix and prefix:
  1047. prefix = prefix[:len(prefix)-1]
  1048. if not prefix:
  1049. break
  1050. if '/' in prefix and prefix[-1] != '/':
  1051. prefix = prefix[0:prefix.rfind('/')+1]
  1052. return prefix
  1053. def dictify(self, text, format):
  1054. out = dict()
  1055. header = True if format == 1 else False
  1056. delim = ' ' if format == 1 else ':'
  1057. for line in text.split('\n'):
  1058. if header:
  1059. header, out['@'] = False, line
  1060. continue
  1061. line = line.strip()
  1062. if delim in line:
  1063. data = line.split(delim, 1)
  1064. num = re.search(r'[\d]+', data[1])
  1065. if format == 2 and num:
  1066. out[data[0].strip()] = num.group()
  1067. else:
  1068. out[data[0].strip()] = data[1]
  1069. return out
  1070. def cmdinfovar(self, arg):
  1071. if arg == 'ethdev':
  1072. try:
  1073. cmd = [self.getExec('ip'), '-4', '-o', '-br', 'addr']
  1074. fp = Popen(cmd, stdout=PIPE, stderr=PIPE).stdout
  1075. info = ascii(fp.read()).strip()
  1076. fp.close()
  1077. except:
  1078. return 'iptoolcrash'
  1079. for line in info.split('\n'):
  1080. if line[0] == 'e' and 'UP' in line:
  1081. return line.split()[0]
  1082. return 'nodevicefound'
  1083. return 'unknown'
  1084. def cmdinfo(self, begin, debug=False):
  1085. out = []
  1086. if begin:
  1087. self.cmd1 = dict()
  1088. for cargs in self.infocmds:
  1089. delta, name, args = cargs[0], cargs[1], cargs[2:]
  1090. for i in range(len(args)):
  1091. if args[i][0] == '{' and args[i][-1] == '}':
  1092. args[i] = self.cmdinfovar(args[i][1:-1])
  1093. cmdline, cmdpath = ' '.join(args[0:]), self.getExec(args[0])
  1094. if not cmdpath or (begin and not delta):
  1095. continue
  1096. self.dlog('[%s]' % cmdline)
  1097. try:
  1098. fp = Popen([cmdpath]+args[1:], stdout=PIPE, stderr=PIPE).stdout
  1099. info = ascii(fp.read()).strip()
  1100. fp.close()
  1101. except:
  1102. continue
  1103. if not debug and begin:
  1104. self.cmd1[name] = self.dictify(info, delta)
  1105. elif not debug and delta and name in self.cmd1:
  1106. before, after = self.cmd1[name], self.dictify(info, delta)
  1107. dinfo = ('\t%s\n' % before['@']) if '@' in before and len(before) > 1 else ''
  1108. prefix = self.commonPrefix(list(before.keys()))
  1109. for key in sorted(before):
  1110. if key in after and before[key] != after[key]:
  1111. title = key.replace(prefix, '')
  1112. if delta == 2:
  1113. dinfo += '\t%s : %s -> %s\n' % \
  1114. (title, before[key].strip(), after[key].strip())
  1115. else:
  1116. dinfo += '%10s (start) : %s\n%10s (after) : %s\n' % \
  1117. (title, before[key], title, after[key])
  1118. dinfo = '\tnothing changed' if not dinfo else dinfo.rstrip()
  1119. out.append((name, cmdline, dinfo))
  1120. else:
  1121. out.append((name, cmdline, '\tnothing' if not info else info))
  1122. return out
  1123. def testVal(self, file, fmt='basic', value=''):
  1124. if file == 'restoreall':
  1125. for f in self.cfgdef:
  1126. if os.path.exists(f):
  1127. fp = open(f, 'w')
  1128. fp.write(self.cfgdef[f])
  1129. fp.close()
  1130. self.cfgdef = dict()
  1131. elif value and os.path.exists(file):
  1132. fp = open(file, 'r+')
  1133. if fmt == 'radio':
  1134. m = re.match(r'.*\[(?P<v>.*)\].*', fp.read())
  1135. if m:
  1136. self.cfgdef[file] = m.group('v')
  1137. elif fmt == 'acpi':
  1138. line = fp.read().strip().split('\n')[-1]
  1139. m = re.match(r'.* (?P<v>[0-9A-Fx]*) .*', line)
  1140. if m:
  1141. self.cfgdef[file] = m.group('v')
  1142. else:
  1143. self.cfgdef[file] = fp.read().strip()
  1144. fp.write(value)
  1145. fp.close()
  1146. def s0ixSupport(self):
  1147. if not os.path.exists(self.s0ixres) or not os.path.exists(self.mempowerfile):
  1148. return False
  1149. fp = open(sysvals.mempowerfile, 'r')
  1150. data = fp.read().strip()
  1151. fp.close()
  1152. if '[s2idle]' in data:
  1153. return True
  1154. return False
  1155. def haveTurbostat(self):
  1156. if not self.tstat:
  1157. return False
  1158. cmd = self.getExec('turbostat')
  1159. if not cmd:
  1160. return False
  1161. fp = Popen([cmd, '-v'], stdout=PIPE, stderr=PIPE).stderr
  1162. out = ascii(fp.read()).strip()
  1163. fp.close()
  1164. if re.match(r'turbostat version .*', out):
  1165. self.vprint(out)
  1166. return True
  1167. return False
  1168. def turbostat(self, s0ixready):
  1169. cmd = self.getExec('turbostat')
  1170. rawout = keyline = valline = ''
  1171. fullcmd = '%s -q -S echo freeze > %s' % (cmd, self.powerfile)
  1172. fp = Popen(['sh', '-c', fullcmd], stdout=PIPE, stderr=PIPE)
  1173. for line in fp.stderr:
  1174. line = ascii(line)
  1175. rawout += line
  1176. if keyline and valline:
  1177. continue
  1178. if re.match(r'(?i)Avg_MHz.*', line):
  1179. keyline = line.strip().split()
  1180. elif keyline:
  1181. valline = line.strip().split()
  1182. fp.wait()
  1183. if not keyline or not valline or len(keyline) != len(valline):
  1184. errmsg = 'unrecognized turbostat output:\n'+rawout.strip()
  1185. self.vprint(errmsg)
  1186. if not self.verbose:
  1187. pprint(errmsg)
  1188. return (fp.returncode, '')
  1189. if self.verbose:
  1190. pprint(rawout.strip())
  1191. out = []
  1192. for key in keyline:
  1193. idx = keyline.index(key)
  1194. val = valline[idx]
  1195. if key == 'SYS%LPI' and not s0ixready and re.match(r'^[0\.]*$', val):
  1196. continue
  1197. out.append('%s=%s' % (key, val))
  1198. return (fp.returncode, '|'.join(out))
  1199. def netfixon(self, net='both'):
  1200. cmd = self.getExec('netfix')
  1201. if not cmd:
  1202. return ''
  1203. fp = Popen([cmd, '-s', net, 'on'], stdout=PIPE, stderr=PIPE).stdout
  1204. out = ascii(fp.read()).strip()
  1205. fp.close()
  1206. return out
  1207. def wifiDetails(self, dev):
  1208. try:
  1209. info = open('/sys/class/net/%s/device/uevent' % dev, 'r').read().strip()
  1210. except:
  1211. return dev
  1212. vals = [dev]
  1213. for prop in info.split('\n'):
  1214. if prop.startswith('DRIVER=') or prop.startswith('PCI_ID='):
  1215. vals.append(prop.split('=')[-1])
  1216. return ':'.join(vals)
  1217. def checkWifi(self, dev=''):
  1218. try:
  1219. w = open('/proc/net/wireless', 'r').read().strip()
  1220. except:
  1221. return ''
  1222. for line in reversed(w.split('\n')):
  1223. m = re.match(r' *(?P<dev>.*): (?P<stat>[0-9a-f]*) .*', line)
  1224. if not m or (dev and dev != m.group('dev')):
  1225. continue
  1226. return m.group('dev')
  1227. return ''
  1228. def pollWifi(self, dev, timeout=10):
  1229. start = time.time()
  1230. while (time.time() - start) < timeout:
  1231. w = self.checkWifi(dev)
  1232. if w:
  1233. return '%s reconnected %.2f' % \
  1234. (self.wifiDetails(dev), max(0, time.time() - start))
  1235. time.sleep(0.01)
  1236. return '%s timeout %d' % (self.wifiDetails(dev), timeout)
  1237. def errorSummary(self, errinfo, msg):
  1238. found = False
  1239. for entry in errinfo:
  1240. if re.match(entry['match'], msg):
  1241. entry['count'] += 1
  1242. if self.hostname not in entry['urls']:
  1243. entry['urls'][self.hostname] = [self.htmlfile]
  1244. elif self.htmlfile not in entry['urls'][self.hostname]:
  1245. entry['urls'][self.hostname].append(self.htmlfile)
  1246. found = True
  1247. break
  1248. if found:
  1249. return
  1250. arr = msg.split()
  1251. for j in range(len(arr)):
  1252. if re.match(r'^[0-9,\-\.]*$', arr[j]):
  1253. arr[j] = r'[0-9,\-\.]*'
  1254. else:
  1255. arr[j] = arr[j]\
  1256. .replace('\\', r'\\\\').replace(']', r'\]').replace('[', r'\[')\
  1257. .replace('.', r'\.').replace('+', r'\+').replace('*', r'\*')\
  1258. .replace('(', r'\(').replace(')', r'\)').replace('}', r'\}')\
  1259. .replace('{', r'\{')
  1260. mstr = ' *'.join(arr)
  1261. entry = {
  1262. 'line': msg,
  1263. 'match': mstr,
  1264. 'count': 1,
  1265. 'urls': {self.hostname: [self.htmlfile]}
  1266. }
  1267. errinfo.append(entry)
  1268. def multistat(self, start, idx, finish):
  1269. if 'time' in self.multitest:
  1270. id = '%d Duration=%dmin' % (idx+1, self.multitest['time'])
  1271. else:
  1272. id = '%d/%d' % (idx+1, self.multitest['count'])
  1273. t = time.time()
  1274. if 'start' not in self.multitest:
  1275. self.multitest['start'] = self.multitest['last'] = t
  1276. self.multitest['total'] = 0.0
  1277. pprint('TEST (%s) START' % id)
  1278. return
  1279. dt = t - self.multitest['last']
  1280. if not start:
  1281. if idx == 0 and self.multitest['delay'] > 0:
  1282. self.multitest['total'] += self.multitest['delay']
  1283. pprint('TEST (%s) COMPLETE -- Duration %.1fs' % (id, dt))
  1284. return
  1285. self.multitest['total'] += dt
  1286. self.multitest['last'] = t
  1287. avg = self.multitest['total'] / idx
  1288. if 'time' in self.multitest:
  1289. left = finish - datetime.now()
  1290. left -= timedelta(microseconds=left.microseconds)
  1291. else:
  1292. left = timedelta(seconds=((self.multitest['count'] - idx) * int(avg)))
  1293. pprint('TEST (%s) START - Avg Duration %.1fs, Time left %s' % \
  1294. (id, avg, str(left)))
  1295. def multiinit(self, c, d):
  1296. sz, unit = 'count', 'm'
  1297. if c.endswith('d') or c.endswith('h') or c.endswith('m'):
  1298. sz, unit, c = 'time', c[-1], c[:-1]
  1299. self.multitest['run'] = True
  1300. self.multitest[sz] = getArgInt('multi: n d (exec count)', c, 1, 1000000, False)
  1301. self.multitest['delay'] = getArgInt('multi: n d (delay between tests)', d, 0, 3600, False)
  1302. if unit == 'd':
  1303. self.multitest[sz] *= 1440
  1304. elif unit == 'h':
  1305. self.multitest[sz] *= 60
  1306. def displayControl(self, cmd):
  1307. xset, ret = 'timeout 10 xset -d :0.0 {0}', 0
  1308. if self.sudouser:
  1309. xset = 'sudo -u %s %s' % (self.sudouser, xset)
  1310. if cmd == 'init':
  1311. ret = call(xset.format('dpms 0 0 0'), shell=True)
  1312. if not ret:
  1313. ret = call(xset.format('s off'), shell=True)
  1314. elif cmd == 'reset':
  1315. ret = call(xset.format('s reset'), shell=True)
  1316. elif cmd in ['on', 'off', 'standby', 'suspend']:
  1317. b4 = self.displayControl('stat')
  1318. ret = call(xset.format('dpms force %s' % cmd), shell=True)
  1319. if not ret:
  1320. curr = self.displayControl('stat')
  1321. self.vprint('Display Switched: %s -> %s' % (b4, curr))
  1322. if curr != cmd:
  1323. self.vprint('WARNING: Display failed to change to %s' % cmd)
  1324. if ret:
  1325. self.vprint('WARNING: Display failed to change to %s with xset' % cmd)
  1326. return ret
  1327. elif cmd == 'stat':
  1328. fp = Popen(xset.format('q').split(' '), stdout=PIPE).stdout
  1329. ret = 'unknown'
  1330. for line in fp:
  1331. m = re.match(r'[\s]*Monitor is (?P<m>.*)', ascii(line))
  1332. if(m and len(m.group('m')) >= 2):
  1333. out = m.group('m').lower()
  1334. ret = out[3:] if out[0:2] == 'in' else out
  1335. break
  1336. fp.close()
  1337. return ret
  1338. def setRuntimeSuspend(self, before=True):
  1339. if before:
  1340. # runtime suspend disable or enable
  1341. if self.rs > 0:
  1342. self.rstgt, self.rsval, self.rsdir = 'on', 'auto', 'enabled'
  1343. else:
  1344. self.rstgt, self.rsval, self.rsdir = 'auto', 'on', 'disabled'
  1345. pprint('CONFIGURING RUNTIME SUSPEND...')
  1346. self.rslist = deviceInfo(self.rstgt)
  1347. for i in self.rslist:
  1348. self.setVal(self.rsval, i)
  1349. pprint('runtime suspend %s on all devices (%d changed)' % (self.rsdir, len(self.rslist)))
  1350. pprint('waiting 5 seconds...')
  1351. time.sleep(5)
  1352. else:
  1353. # runtime suspend re-enable or re-disable
  1354. for i in self.rslist:
  1355. self.setVal(self.rstgt, i)
  1356. pprint('runtime suspend settings restored on %d devices' % len(self.rslist))
  1357. def start(self, pm):
  1358. if self.useftrace:
  1359. self.dlog('start ftrace tracing')
  1360. self.fsetVal('1', 'tracing_on')
  1361. if self.useprocmon:
  1362. self.dlog('start the process monitor')
  1363. pm.start()
  1364. def stop(self, pm):
  1365. if self.useftrace:
  1366. if self.useprocmon:
  1367. self.dlog('stop the process monitor')
  1368. pm.stop()
  1369. self.dlog('stop ftrace tracing')
  1370. self.fsetVal('0', 'tracing_on')
  1371. sysvals = SystemValues()
  1372. switchvalues = ['enable', 'disable', 'on', 'off', 'true', 'false', '1', '0']
  1373. switchoff = ['disable', 'off', 'false', '0']
  1374. suspendmodename = {
  1375. 'standby': 'standby (S1)',
  1376. 'freeze': 'freeze (S2idle)',
  1377. 'mem': 'suspend (S3)',
  1378. 'disk': 'hibernate (S4)'
  1379. }
  1380. # Class: DevProps
  1381. # Description:
  1382. # Simple class which holds property values collected
  1383. # for all the devices used in the timeline.
  1384. class DevProps:
  1385. def __init__(self):
  1386. self.syspath = ''
  1387. self.altname = ''
  1388. self.isasync = True
  1389. self.xtraclass = ''
  1390. self.xtrainfo = ''
  1391. def out(self, dev):
  1392. return '%s,%s,%d;' % (dev, self.altname, self.isasync)
  1393. def debug(self, dev):
  1394. pprint('%s:\n\taltname = %s\n\t async = %s' % (dev, self.altname, self.isasync))
  1395. def altName(self, dev):
  1396. if not self.altname or self.altname == dev:
  1397. return dev
  1398. return '%s [%s]' % (self.altname, dev)
  1399. def xtraClass(self):
  1400. if self.xtraclass:
  1401. return ' '+self.xtraclass
  1402. if not self.isasync:
  1403. return ' sync'
  1404. return ''
  1405. def xtraInfo(self):
  1406. if self.xtraclass:
  1407. return ' '+self.xtraclass
  1408. if self.isasync:
  1409. return ' (async)'
  1410. return ' (sync)'
  1411. # Class: DeviceNode
  1412. # Description:
  1413. # A container used to create a device hierachy, with a single root node
  1414. # and a tree of child nodes. Used by Data.deviceTopology()
  1415. class DeviceNode:
  1416. def __init__(self, nodename, nodedepth):
  1417. self.name = nodename
  1418. self.children = []
  1419. self.depth = nodedepth
  1420. # Class: Data
  1421. # Description:
  1422. # The primary container for suspend/resume test data. There is one for
  1423. # each test run. The data is organized into a cronological hierarchy:
  1424. # Data.dmesg {
  1425. # phases {
  1426. # 10 sequential, non-overlapping phases of S/R
  1427. # contents: times for phase start/end, order/color data for html
  1428. # devlist {
  1429. # device callback or action list for this phase
  1430. # device {
  1431. # a single device callback or generic action
  1432. # contents: start/stop times, pid/cpu/driver info
  1433. # parents/children, html id for timeline/callgraph
  1434. # optionally includes an ftrace callgraph
  1435. # optionally includes dev/ps data
  1436. # }
  1437. # }
  1438. # }
  1439. # }
  1440. #
  1441. class Data:
  1442. phasedef = {
  1443. 'suspend_prepare': {'order': 0, 'color': '#CCFFCC'},
  1444. 'suspend': {'order': 1, 'color': '#88FF88'},
  1445. 'suspend_late': {'order': 2, 'color': '#00AA00'},
  1446. 'suspend_noirq': {'order': 3, 'color': '#008888'},
  1447. 'suspend_machine': {'order': 4, 'color': '#0000FF'},
  1448. 'resume_machine': {'order': 5, 'color': '#FF0000'},
  1449. 'resume_noirq': {'order': 6, 'color': '#FF9900'},
  1450. 'resume_early': {'order': 7, 'color': '#FFCC00'},
  1451. 'resume': {'order': 8, 'color': '#FFFF88'},
  1452. 'resume_complete': {'order': 9, 'color': '#FFFFCC'},
  1453. }
  1454. errlist = {
  1455. 'HWERROR' : r'.*\[ *Hardware Error *\].*',
  1456. 'FWBUG' : r'.*\[ *Firmware Bug *\].*',
  1457. 'TASKFAIL': r'.*Freezing .*after *.*',
  1458. 'BUG' : r'(?i).*\bBUG\b.*',
  1459. 'ERROR' : r'(?i).*\bERROR\b.*',
  1460. 'WARNING' : r'(?i).*\bWARNING\b.*',
  1461. 'FAULT' : r'(?i).*\bFAULT\b.*',
  1462. 'FAIL' : r'(?i).*\bFAILED\b.*',
  1463. 'INVALID' : r'(?i).*\bINVALID\b.*',
  1464. 'CRASH' : r'(?i).*\bCRASHED\b.*',
  1465. 'TIMEOUT' : r'(?i).*\bTIMEOUT\b.*',
  1466. 'ABORT' : r'(?i).*\bABORT\b.*',
  1467. 'IRQ' : r'.*\bgenirq: .*',
  1468. 'ACPI' : r'.*\bACPI *(?P<b>[A-Za-z]*) *Error[: ].*',
  1469. 'DISKFULL': r'.*\bNo space left on device.*',
  1470. 'USBERR' : r'.*usb .*device .*, error [0-9-]*',
  1471. 'ATAERR' : r' *ata[0-9\.]*: .*failed.*',
  1472. 'MEIERR' : r' *mei.*: .*failed.*',
  1473. 'TPMERR' : r'(?i) *tpm *tpm[0-9]*: .*error.*',
  1474. }
  1475. def __init__(self, num):
  1476. idchar = 'abcdefghij'
  1477. self.start = 0.0 # test start
  1478. self.end = 0.0 # test end
  1479. self.hwstart = 0 # rtc test start
  1480. self.hwend = 0 # rtc test end
  1481. self.tSuspended = 0.0 # low-level suspend start
  1482. self.tResumed = 0.0 # low-level resume start
  1483. self.tKernSus = 0.0 # kernel level suspend start
  1484. self.tKernRes = 0.0 # kernel level resume end
  1485. self.fwValid = False # is firmware data available
  1486. self.fwSuspend = 0 # time spent in firmware suspend
  1487. self.fwResume = 0 # time spent in firmware resume
  1488. self.html_device_id = 0
  1489. self.stamp = 0
  1490. self.outfile = ''
  1491. self.kerror = False
  1492. self.wifi = dict()
  1493. self.turbostat = 0
  1494. self.enterfail = ''
  1495. self.currphase = ''
  1496. self.pstl = dict() # process timeline
  1497. self.testnumber = num
  1498. self.idstr = idchar[num]
  1499. self.dmesgtext = [] # dmesg text file in memory
  1500. self.dmesg = dict() # root data structure
  1501. self.errorinfo = {'suspend':[],'resume':[]}
  1502. self.tLow = [] # time spent in low-level suspends (standby/freeze)
  1503. self.devpids = []
  1504. self.devicegroups = 0
  1505. def sortedPhases(self):
  1506. return sorted(self.dmesg, key=lambda k:self.dmesg[k]['order'])
  1507. def initDevicegroups(self):
  1508. # called when phases are all finished being added
  1509. for phase in sorted(self.dmesg.keys()):
  1510. if '*' in phase:
  1511. p = phase.split('*')
  1512. pnew = '%s%d' % (p[0], len(p))
  1513. self.dmesg[pnew] = self.dmesg.pop(phase)
  1514. self.devicegroups = []
  1515. for phase in self.sortedPhases():
  1516. self.devicegroups.append([phase])
  1517. def nextPhase(self, phase, offset):
  1518. order = self.dmesg[phase]['order'] + offset
  1519. for p in self.dmesg:
  1520. if self.dmesg[p]['order'] == order:
  1521. return p
  1522. return ''
  1523. def lastPhase(self, depth=1):
  1524. plist = self.sortedPhases()
  1525. if len(plist) < depth:
  1526. return ''
  1527. return plist[-1*depth]
  1528. def turbostatInfo(self):
  1529. tp = TestProps()
  1530. out = {'syslpi':'N/A','pkgpc10':'N/A'}
  1531. for line in self.dmesgtext:
  1532. m = re.match(tp.tstatfmt, line)
  1533. if not m:
  1534. continue
  1535. for i in m.group('t').split('|'):
  1536. if 'SYS%LPI' in i:
  1537. out['syslpi'] = i.split('=')[-1]+'%'
  1538. elif 'pc10' in i:
  1539. out['pkgpc10'] = i.split('=')[-1]+'%'
  1540. break
  1541. return out
  1542. def extractErrorInfo(self):
  1543. lf = self.dmesgtext
  1544. if len(self.dmesgtext) < 1 and sysvals.dmesgfile:
  1545. lf = sysvals.openlog(sysvals.dmesgfile, 'r')
  1546. i = 0
  1547. tp = TestProps()
  1548. list = []
  1549. for line in lf:
  1550. i += 1
  1551. if tp.stampInfo(line, sysvals):
  1552. continue
  1553. m = re.match(r'[ \t]*(\[ *)(?P<ktime>[0-9\.]*)(\]) (?P<msg>.*)', line)
  1554. if not m:
  1555. continue
  1556. t = float(m.group('ktime'))
  1557. if t < self.start or t > self.end:
  1558. continue
  1559. dir = 'suspend' if t < self.tSuspended else 'resume'
  1560. msg = m.group('msg')
  1561. if re.match(r'capability: warning: .*', msg):
  1562. continue
  1563. for err in self.errlist:
  1564. if re.match(self.errlist[err], msg):
  1565. list.append((msg, err, dir, t, i, i))
  1566. self.kerror = True
  1567. break
  1568. tp.msglist = []
  1569. for msg, type, dir, t, idx1, idx2 in list:
  1570. tp.msglist.append(msg)
  1571. self.errorinfo[dir].append((type, t, idx1, idx2))
  1572. if self.kerror:
  1573. sysvals.dmesglog = True
  1574. if len(self.dmesgtext) < 1 and sysvals.dmesgfile:
  1575. lf.close()
  1576. return tp
  1577. def setStart(self, time, msg=''):
  1578. self.start = time
  1579. if msg:
  1580. try:
  1581. self.hwstart = datetime.strptime(msg, sysvals.tmstart)
  1582. except:
  1583. self.hwstart = 0
  1584. def setEnd(self, time, msg=''):
  1585. self.end = time
  1586. if msg:
  1587. try:
  1588. self.hwend = datetime.strptime(msg, sysvals.tmend)
  1589. except:
  1590. self.hwend = 0
  1591. def isTraceEventOutsideDeviceCalls(self, pid, time):
  1592. for phase in self.sortedPhases():
  1593. list = self.dmesg[phase]['list']
  1594. for dev in list:
  1595. d = list[dev]
  1596. if(d['pid'] == pid and time >= d['start'] and
  1597. time < d['end']):
  1598. return False
  1599. return True
  1600. def sourcePhase(self, start):
  1601. for phase in self.sortedPhases():
  1602. if 'machine' in phase:
  1603. continue
  1604. pend = self.dmesg[phase]['end']
  1605. if start <= pend:
  1606. return phase
  1607. return 'resume_complete' if 'resume_complete' in self.dmesg else ''
  1608. def sourceDevice(self, phaselist, start, end, pid, type):
  1609. tgtdev = ''
  1610. for phase in phaselist:
  1611. list = self.dmesg[phase]['list']
  1612. for devname in list:
  1613. dev = list[devname]
  1614. # pid must match
  1615. if dev['pid'] != pid:
  1616. continue
  1617. devS = dev['start']
  1618. devE = dev['end']
  1619. if type == 'device':
  1620. # device target event is entirely inside the source boundary
  1621. if(start < devS or start >= devE or end <= devS or end > devE):
  1622. continue
  1623. elif type == 'thread':
  1624. # thread target event will expand the source boundary
  1625. if start < devS:
  1626. dev['start'] = start
  1627. if end > devE:
  1628. dev['end'] = end
  1629. tgtdev = dev
  1630. break
  1631. return tgtdev
  1632. def addDeviceFunctionCall(self, displayname, kprobename, proc, pid, start, end, cdata, rdata):
  1633. # try to place the call in a device
  1634. phases = self.sortedPhases()
  1635. tgtdev = self.sourceDevice(phases, start, end, pid, 'device')
  1636. # calls with device pids that occur outside device bounds are dropped
  1637. # TODO: include these somehow
  1638. if not tgtdev and pid in self.devpids:
  1639. return False
  1640. # try to place the call in a thread
  1641. if not tgtdev:
  1642. tgtdev = self.sourceDevice(phases, start, end, pid, 'thread')
  1643. # create new thread blocks, expand as new calls are found
  1644. if not tgtdev:
  1645. if proc == '<...>':
  1646. threadname = 'kthread-%d' % (pid)
  1647. else:
  1648. threadname = '%s-%d' % (proc, pid)
  1649. tgtphase = self.sourcePhase(start)
  1650. if not tgtphase:
  1651. return False
  1652. self.newAction(tgtphase, threadname, pid, '', start, end, '', ' kth', '')
  1653. return self.addDeviceFunctionCall(displayname, kprobename, proc, pid, start, end, cdata, rdata)
  1654. # this should not happen
  1655. if not tgtdev:
  1656. sysvals.vprint('[%f - %f] %s-%d %s %s %s' % \
  1657. (start, end, proc, pid, kprobename, cdata, rdata))
  1658. return False
  1659. # place the call data inside the src element of the tgtdev
  1660. if('src' not in tgtdev):
  1661. tgtdev['src'] = []
  1662. dtf = sysvals.dev_tracefuncs
  1663. ubiquitous = False
  1664. if kprobename in dtf and 'ub' in dtf[kprobename]:
  1665. ubiquitous = True
  1666. mc = re.match(r'\(.*\) *(?P<args>.*)', cdata)
  1667. mr = re.match(r'\((?P<caller>\S*).* arg1=(?P<ret>.*)', rdata)
  1668. if mc and mr:
  1669. c = mr.group('caller').split('+')[0]
  1670. a = mc.group('args').strip()
  1671. r = mr.group('ret')
  1672. if len(r) > 6:
  1673. r = ''
  1674. else:
  1675. r = 'ret=%s ' % r
  1676. if ubiquitous and c in dtf and 'ub' in dtf[c]:
  1677. return False
  1678. else:
  1679. return False
  1680. color = sysvals.kprobeColor(kprobename)
  1681. e = DevFunction(displayname, a, c, r, start, end, ubiquitous, proc, pid, color)
  1682. tgtdev['src'].append(e)
  1683. return True
  1684. def overflowDevices(self):
  1685. # get a list of devices that extend beyond the end of this test run
  1686. devlist = []
  1687. for phase in self.sortedPhases():
  1688. list = self.dmesg[phase]['list']
  1689. for devname in list:
  1690. dev = list[devname]
  1691. if dev['end'] > self.end:
  1692. devlist.append(dev)
  1693. return devlist
  1694. def mergeOverlapDevices(self, devlist):
  1695. # merge any devices that overlap devlist
  1696. for dev in devlist:
  1697. devname = dev['name']
  1698. for phase in self.sortedPhases():
  1699. list = self.dmesg[phase]['list']
  1700. if devname not in list:
  1701. continue
  1702. tdev = list[devname]
  1703. o = min(dev['end'], tdev['end']) - max(dev['start'], tdev['start'])
  1704. if o <= 0:
  1705. continue
  1706. dev['end'] = tdev['end']
  1707. if 'src' not in dev or 'src' not in tdev:
  1708. continue
  1709. dev['src'] += tdev['src']
  1710. del list[devname]
  1711. def usurpTouchingThread(self, name, dev):
  1712. # the caller test has priority of this thread, give it to him
  1713. for phase in self.sortedPhases():
  1714. list = self.dmesg[phase]['list']
  1715. if name in list:
  1716. tdev = list[name]
  1717. if tdev['start'] - dev['end'] < 0.1:
  1718. dev['end'] = tdev['end']
  1719. if 'src' not in dev:
  1720. dev['src'] = []
  1721. if 'src' in tdev:
  1722. dev['src'] += tdev['src']
  1723. del list[name]
  1724. break
  1725. def stitchTouchingThreads(self, testlist):
  1726. # merge any threads between tests that touch
  1727. for phase in self.sortedPhases():
  1728. list = self.dmesg[phase]['list']
  1729. for devname in list:
  1730. dev = list[devname]
  1731. if 'htmlclass' not in dev or 'kth' not in dev['htmlclass']:
  1732. continue
  1733. for data in testlist:
  1734. data.usurpTouchingThread(devname, dev)
  1735. def optimizeDevSrc(self):
  1736. # merge any src call loops to reduce timeline size
  1737. for phase in self.sortedPhases():
  1738. list = self.dmesg[phase]['list']
  1739. for dev in list:
  1740. if 'src' not in list[dev]:
  1741. continue
  1742. src = list[dev]['src']
  1743. p = 0
  1744. for e in sorted(src, key=lambda event: event.time):
  1745. if not p or not e.repeat(p):
  1746. p = e
  1747. continue
  1748. # e is another iteration of p, move it into p
  1749. p.end = e.end
  1750. p.length = p.end - p.time
  1751. p.count += 1
  1752. src.remove(e)
  1753. def trimTimeVal(self, t, t0, dT, left):
  1754. if left:
  1755. if(t > t0):
  1756. if(t - dT < t0):
  1757. return t0
  1758. return t - dT
  1759. else:
  1760. return t
  1761. else:
  1762. if(t < t0 + dT):
  1763. if(t > t0):
  1764. return t0 + dT
  1765. return t + dT
  1766. else:
  1767. return t
  1768. def trimTime(self, t0, dT, left):
  1769. self.tSuspended = self.trimTimeVal(self.tSuspended, t0, dT, left)
  1770. self.tResumed = self.trimTimeVal(self.tResumed, t0, dT, left)
  1771. self.start = self.trimTimeVal(self.start, t0, dT, left)
  1772. self.tKernSus = self.trimTimeVal(self.tKernSus, t0, dT, left)
  1773. self.tKernRes = self.trimTimeVal(self.tKernRes, t0, dT, left)
  1774. self.end = self.trimTimeVal(self.end, t0, dT, left)
  1775. for phase in self.sortedPhases():
  1776. p = self.dmesg[phase]
  1777. p['start'] = self.trimTimeVal(p['start'], t0, dT, left)
  1778. p['end'] = self.trimTimeVal(p['end'], t0, dT, left)
  1779. list = p['list']
  1780. for name in list:
  1781. d = list[name]
  1782. d['start'] = self.trimTimeVal(d['start'], t0, dT, left)
  1783. d['end'] = self.trimTimeVal(d['end'], t0, dT, left)
  1784. d['length'] = d['end'] - d['start']
  1785. if('ftrace' in d):
  1786. cg = d['ftrace']
  1787. cg.start = self.trimTimeVal(cg.start, t0, dT, left)
  1788. cg.end = self.trimTimeVal(cg.end, t0, dT, left)
  1789. for line in cg.list:
  1790. line.time = self.trimTimeVal(line.time, t0, dT, left)
  1791. if('src' in d):
  1792. for e in d['src']:
  1793. e.time = self.trimTimeVal(e.time, t0, dT, left)
  1794. e.end = self.trimTimeVal(e.end, t0, dT, left)
  1795. e.length = e.end - e.time
  1796. if('cpuexec' in d):
  1797. cpuexec = dict()
  1798. for e in d['cpuexec']:
  1799. c0, cN = e
  1800. c0 = self.trimTimeVal(c0, t0, dT, left)
  1801. cN = self.trimTimeVal(cN, t0, dT, left)
  1802. cpuexec[(c0, cN)] = d['cpuexec'][e]
  1803. d['cpuexec'] = cpuexec
  1804. for dir in ['suspend', 'resume']:
  1805. list = []
  1806. for e in self.errorinfo[dir]:
  1807. type, tm, idx1, idx2 = e
  1808. tm = self.trimTimeVal(tm, t0, dT, left)
  1809. list.append((type, tm, idx1, idx2))
  1810. self.errorinfo[dir] = list
  1811. def trimFreezeTime(self, tZero):
  1812. # trim out any standby or freeze clock time
  1813. lp = ''
  1814. for phase in self.sortedPhases():
  1815. if 'resume_machine' in phase and 'suspend_machine' in lp:
  1816. tS, tR = self.dmesg[lp]['end'], self.dmesg[phase]['start']
  1817. tL = tR - tS
  1818. if tL <= 0:
  1819. continue
  1820. left = True if tR > tZero else False
  1821. self.trimTime(tS, tL, left)
  1822. if 'waking' in self.dmesg[lp]:
  1823. tCnt = self.dmesg[lp]['waking'][0]
  1824. if self.dmesg[lp]['waking'][1] >= 0.001:
  1825. tTry = '%.0f' % (round(self.dmesg[lp]['waking'][1] * 1000))
  1826. else:
  1827. tTry = '%.3f' % (self.dmesg[lp]['waking'][1] * 1000)
  1828. text = '%.0f (%s ms waking %d times)' % (tL * 1000, tTry, tCnt)
  1829. else:
  1830. text = '%.0f' % (tL * 1000)
  1831. self.tLow.append(text)
  1832. lp = phase
  1833. def getMemTime(self):
  1834. if not self.hwstart or not self.hwend:
  1835. return
  1836. stime = (self.tSuspended - self.start) * 1000000
  1837. rtime = (self.end - self.tResumed) * 1000000
  1838. hws = self.hwstart + timedelta(microseconds=stime)
  1839. hwr = self.hwend - timedelta(microseconds=rtime)
  1840. self.tLow.append('%.0f'%((hwr - hws).total_seconds() * 1000))
  1841. def getTimeValues(self):
  1842. s = (self.tSuspended - self.tKernSus) * 1000
  1843. r = (self.tKernRes - self.tResumed) * 1000
  1844. return (max(s, 0), max(r, 0))
  1845. def setPhase(self, phase, ktime, isbegin, order=-1):
  1846. if(isbegin):
  1847. # phase start over current phase
  1848. if self.currphase:
  1849. if 'resume_machine' not in self.currphase:
  1850. sysvals.vprint('WARNING: phase %s failed to end' % self.currphase)
  1851. self.dmesg[self.currphase]['end'] = ktime
  1852. phases = self.dmesg.keys()
  1853. color = self.phasedef[phase]['color']
  1854. count = len(phases) if order < 0 else order
  1855. # create unique name for every new phase
  1856. while phase in phases:
  1857. phase += '*'
  1858. self.dmesg[phase] = {'list': dict(), 'start': -1.0, 'end': -1.0,
  1859. 'row': 0, 'color': color, 'order': count}
  1860. self.dmesg[phase]['start'] = ktime
  1861. self.currphase = phase
  1862. else:
  1863. # phase end without a start
  1864. if phase not in self.currphase:
  1865. if self.currphase:
  1866. sysvals.vprint('WARNING: %s ended instead of %s, ftrace corruption?' % (phase, self.currphase))
  1867. else:
  1868. sysvals.vprint('WARNING: %s ended without a start, ftrace corruption?' % phase)
  1869. return phase
  1870. phase = self.currphase
  1871. self.dmesg[phase]['end'] = ktime
  1872. self.currphase = ''
  1873. return phase
  1874. def sortedDevices(self, phase):
  1875. list = self.dmesg[phase]['list']
  1876. return sorted(list, key=lambda k:list[k]['start'])
  1877. def fixupInitcalls(self, phase):
  1878. # if any calls never returned, clip them at system resume end
  1879. phaselist = self.dmesg[phase]['list']
  1880. for devname in phaselist:
  1881. dev = phaselist[devname]
  1882. if(dev['end'] < 0):
  1883. for p in self.sortedPhases():
  1884. if self.dmesg[p]['end'] > dev['start']:
  1885. dev['end'] = self.dmesg[p]['end']
  1886. break
  1887. sysvals.vprint('%s (%s): callback didnt return' % (devname, phase))
  1888. def deviceFilter(self, devicefilter):
  1889. for phase in self.sortedPhases():
  1890. list = self.dmesg[phase]['list']
  1891. rmlist = []
  1892. for name in list:
  1893. keep = False
  1894. for filter in devicefilter:
  1895. if filter in name or \
  1896. ('drv' in list[name] and filter in list[name]['drv']):
  1897. keep = True
  1898. if not keep:
  1899. rmlist.append(name)
  1900. for name in rmlist:
  1901. del list[name]
  1902. def fixupInitcallsThatDidntReturn(self):
  1903. # if any calls never returned, clip them at system resume end
  1904. for phase in self.sortedPhases():
  1905. self.fixupInitcalls(phase)
  1906. def phaseOverlap(self, phases):
  1907. rmgroups = []
  1908. newgroup = []
  1909. for group in self.devicegroups:
  1910. for phase in phases:
  1911. if phase not in group:
  1912. continue
  1913. for p in group:
  1914. if p not in newgroup:
  1915. newgroup.append(p)
  1916. if group not in rmgroups:
  1917. rmgroups.append(group)
  1918. for group in rmgroups:
  1919. self.devicegroups.remove(group)
  1920. self.devicegroups.append(newgroup)
  1921. def newActionGlobal(self, name, start, end, pid=-1, color=''):
  1922. # which phase is this device callback or action in
  1923. phases = self.sortedPhases()
  1924. targetphase = 'none'
  1925. htmlclass = ''
  1926. overlap = 0.0
  1927. myphases = []
  1928. for phase in phases:
  1929. pstart = self.dmesg[phase]['start']
  1930. pend = self.dmesg[phase]['end']
  1931. # see if the action overlaps this phase
  1932. o = max(0, min(end, pend) - max(start, pstart))
  1933. if o > 0:
  1934. myphases.append(phase)
  1935. # set the target phase to the one that overlaps most
  1936. if o > overlap:
  1937. if overlap > 0 and phase == 'post_resume':
  1938. continue
  1939. targetphase = phase
  1940. overlap = o
  1941. # if no target phase was found, pin it to the edge
  1942. if targetphase == 'none':
  1943. p0start = self.dmesg[phases[0]]['start']
  1944. if start <= p0start:
  1945. targetphase = phases[0]
  1946. else:
  1947. targetphase = phases[-1]
  1948. if pid == -2:
  1949. htmlclass = ' bg'
  1950. elif pid == -3:
  1951. htmlclass = ' ps'
  1952. if len(myphases) > 1:
  1953. htmlclass = ' bg'
  1954. self.phaseOverlap(myphases)
  1955. if targetphase in phases:
  1956. newname = self.newAction(targetphase, name, pid, '', start, end, '', htmlclass, color)
  1957. return (targetphase, newname)
  1958. return False
  1959. def newAction(self, phase, name, pid, parent, start, end, drv, htmlclass='', color=''):
  1960. # new device callback for a specific phase
  1961. self.html_device_id += 1
  1962. devid = '%s%d' % (self.idstr, self.html_device_id)
  1963. list = self.dmesg[phase]['list']
  1964. length = -1.0
  1965. if(start >= 0 and end >= 0):
  1966. length = end - start
  1967. if pid == -2 or name not in sysvals.tracefuncs.keys():
  1968. i = 2
  1969. origname = name
  1970. while(name in list):
  1971. name = '%s[%d]' % (origname, i)
  1972. i += 1
  1973. list[name] = {'name': name, 'start': start, 'end': end, 'pid': pid,
  1974. 'par': parent, 'length': length, 'row': 0, 'id': devid, 'drv': drv }
  1975. if htmlclass:
  1976. list[name]['htmlclass'] = htmlclass
  1977. if color:
  1978. list[name]['color'] = color
  1979. return name
  1980. def findDevice(self, phase, name):
  1981. list = self.dmesg[phase]['list']
  1982. mydev = ''
  1983. for devname in sorted(list):
  1984. if name == devname or re.match(r'^%s\[(?P<num>[0-9]*)\]$' % name, devname):
  1985. mydev = devname
  1986. if mydev:
  1987. return list[mydev]
  1988. return False
  1989. def deviceChildren(self, devname, phase):
  1990. devlist = []
  1991. list = self.dmesg[phase]['list']
  1992. for child in list:
  1993. if(list[child]['par'] == devname):
  1994. devlist.append(child)
  1995. return devlist
  1996. def maxDeviceNameSize(self, phase):
  1997. size = 0
  1998. for name in self.dmesg[phase]['list']:
  1999. if len(name) > size:
  2000. size = len(name)
  2001. return size
  2002. def printDetails(self):
  2003. sysvals.vprint('Timeline Details:')
  2004. sysvals.vprint(' test start: %f' % self.start)
  2005. sysvals.vprint('kernel suspend start: %f' % self.tKernSus)
  2006. tS = tR = False
  2007. for phase in self.sortedPhases():
  2008. devlist = self.dmesg[phase]['list']
  2009. dc, ps, pe = len(devlist), self.dmesg[phase]['start'], self.dmesg[phase]['end']
  2010. if not tS and ps >= self.tSuspended:
  2011. sysvals.vprint(' machine suspended: %f' % self.tSuspended)
  2012. tS = True
  2013. if not tR and ps >= self.tResumed:
  2014. sysvals.vprint(' machine resumed: %f' % self.tResumed)
  2015. tR = True
  2016. sysvals.vprint('%20s: %f - %f (%d devices)' % (phase, ps, pe, dc))
  2017. if sysvals.devdump:
  2018. sysvals.vprint(''.join('-' for i in range(80)))
  2019. maxname = '%d' % self.maxDeviceNameSize(phase)
  2020. fmt = '%3d) %'+maxname+'s - %f - %f'
  2021. c = 1
  2022. for name in sorted(devlist):
  2023. s = devlist[name]['start']
  2024. e = devlist[name]['end']
  2025. sysvals.vprint(fmt % (c, name, s, e))
  2026. c += 1
  2027. sysvals.vprint(''.join('-' for i in range(80)))
  2028. sysvals.vprint(' kernel resume end: %f' % self.tKernRes)
  2029. sysvals.vprint(' test end: %f' % self.end)
  2030. def deviceChildrenAllPhases(self, devname):
  2031. devlist = []
  2032. for phase in self.sortedPhases():
  2033. list = self.deviceChildren(devname, phase)
  2034. for dev in sorted(list):
  2035. if dev not in devlist:
  2036. devlist.append(dev)
  2037. return devlist
  2038. def masterTopology(self, name, list, depth):
  2039. node = DeviceNode(name, depth)
  2040. for cname in list:
  2041. # avoid recursions
  2042. if name == cname:
  2043. continue
  2044. clist = self.deviceChildrenAllPhases(cname)
  2045. cnode = self.masterTopology(cname, clist, depth+1)
  2046. node.children.append(cnode)
  2047. return node
  2048. def printTopology(self, node):
  2049. html = ''
  2050. if node.name:
  2051. info = ''
  2052. drv = ''
  2053. for phase in self.sortedPhases():
  2054. list = self.dmesg[phase]['list']
  2055. if node.name in list:
  2056. s = list[node.name]['start']
  2057. e = list[node.name]['end']
  2058. if list[node.name]['drv']:
  2059. drv = ' {'+list[node.name]['drv']+'}'
  2060. info += ('<li>%s: %.3fms</li>' % (phase, (e-s)*1000))
  2061. html += '<li><b>'+node.name+drv+'</b>'
  2062. if info:
  2063. html += '<ul>'+info+'</ul>'
  2064. html += '</li>'
  2065. if len(node.children) > 0:
  2066. html += '<ul>'
  2067. for cnode in node.children:
  2068. html += self.printTopology(cnode)
  2069. html += '</ul>'
  2070. return html
  2071. def rootDeviceList(self):
  2072. # list of devices graphed
  2073. real = []
  2074. for phase in self.sortedPhases():
  2075. list = self.dmesg[phase]['list']
  2076. for dev in sorted(list):
  2077. if list[dev]['pid'] >= 0 and dev not in real:
  2078. real.append(dev)
  2079. # list of top-most root devices
  2080. rootlist = []
  2081. for phase in self.sortedPhases():
  2082. list = self.dmesg[phase]['list']
  2083. for dev in sorted(list):
  2084. pdev = list[dev]['par']
  2085. pid = list[dev]['pid']
  2086. if(pid < 0 or re.match(r'[0-9]*-[0-9]*\.[0-9]*[\.0-9]*\:[\.0-9]*$', pdev)):
  2087. continue
  2088. if pdev and pdev not in real and pdev not in rootlist:
  2089. rootlist.append(pdev)
  2090. return rootlist
  2091. def deviceTopology(self):
  2092. rootlist = self.rootDeviceList()
  2093. master = self.masterTopology('', rootlist, 0)
  2094. return self.printTopology(master)
  2095. def selectTimelineDevices(self, widfmt, tTotal, mindevlen):
  2096. # only select devices that will actually show up in html
  2097. self.tdevlist = dict()
  2098. for phase in self.dmesg:
  2099. devlist = []
  2100. list = self.dmesg[phase]['list']
  2101. for dev in list:
  2102. length = (list[dev]['end'] - list[dev]['start']) * 1000
  2103. width = widfmt % (((list[dev]['end']-list[dev]['start'])*100)/tTotal)
  2104. if length >= mindevlen:
  2105. devlist.append(dev)
  2106. self.tdevlist[phase] = devlist
  2107. def addHorizontalDivider(self, devname, devend):
  2108. phase = 'suspend_prepare'
  2109. self.newAction(phase, devname, -2, '', \
  2110. self.start, devend, '', ' sec', '')
  2111. if phase not in self.tdevlist:
  2112. self.tdevlist[phase] = []
  2113. self.tdevlist[phase].append(devname)
  2114. d = DevItem(0, phase, self.dmesg[phase]['list'][devname])
  2115. return d
  2116. def addProcessUsageEvent(self, name, times):
  2117. # get the start and end times for this process
  2118. cpuexec = dict()
  2119. tlast = start = end = -1
  2120. for t in sorted(times):
  2121. if tlast < 0:
  2122. tlast = t
  2123. continue
  2124. if name in self.pstl[t] and self.pstl[t][name] > 0:
  2125. if start < 0:
  2126. start = tlast
  2127. end, key = t, (tlast, t)
  2128. maxj = (t - tlast) * 1024.0
  2129. cpuexec[key] = min(1.0, float(self.pstl[t][name]) / maxj)
  2130. tlast = t
  2131. if start < 0 or end < 0:
  2132. return
  2133. # add a new action for this process and get the object
  2134. out = self.newActionGlobal(name, start, end, -3)
  2135. if out:
  2136. phase, devname = out
  2137. dev = self.dmesg[phase]['list'][devname]
  2138. dev['cpuexec'] = cpuexec
  2139. def createProcessUsageEvents(self):
  2140. # get an array of process names and times
  2141. proclist = {'sus': dict(), 'res': dict()}
  2142. tdata = {'sus': [], 'res': []}
  2143. for t in sorted(self.pstl):
  2144. dir = 'sus' if t < self.tSuspended else 'res'
  2145. for ps in sorted(self.pstl[t]):
  2146. if ps not in proclist[dir]:
  2147. proclist[dir][ps] = 0
  2148. tdata[dir].append(t)
  2149. # process the events for suspend and resume
  2150. if len(proclist['sus']) > 0 or len(proclist['res']) > 0:
  2151. sysvals.vprint('Process Execution:')
  2152. for dir in ['sus', 'res']:
  2153. for ps in sorted(proclist[dir]):
  2154. self.addProcessUsageEvent(ps, tdata[dir])
  2155. def handleEndMarker(self, time, msg=''):
  2156. dm = self.dmesg
  2157. self.setEnd(time, msg)
  2158. self.initDevicegroups()
  2159. # give suspend_prepare an end if needed
  2160. if 'suspend_prepare' in dm and dm['suspend_prepare']['end'] < 0:
  2161. dm['suspend_prepare']['end'] = time
  2162. # assume resume machine ends at next phase start
  2163. if 'resume_machine' in dm and dm['resume_machine']['end'] < 0:
  2164. np = self.nextPhase('resume_machine', 1)
  2165. if np:
  2166. dm['resume_machine']['end'] = dm[np]['start']
  2167. # if kernel resume end not found, assume its the end marker
  2168. if self.tKernRes == 0.0:
  2169. self.tKernRes = time
  2170. # if kernel suspend start not found, assume its the end marker
  2171. if self.tKernSus == 0.0:
  2172. self.tKernSus = time
  2173. # set resume complete to end at end marker
  2174. if 'resume_complete' in dm:
  2175. dm['resume_complete']['end'] = time
  2176. def initcall_debug_call(self, line, quick=False):
  2177. m = re.match(r'.*(\[ *)(?P<t>[0-9\.]*)(\]) .* (?P<f>.*)\: '+\
  2178. r'PM: *calling .* @ (?P<n>.*), parent: (?P<p>.*)', line)
  2179. if not m:
  2180. m = re.match(r'.*(\[ *)(?P<t>[0-9\.]*)(\]) .* (?P<f>.*)\: '+\
  2181. r'calling .* @ (?P<n>.*), parent: (?P<p>.*)', line)
  2182. if not m:
  2183. m = re.match(r'.*(\[ *)(?P<t>[0-9\.]*)(\]) calling '+\
  2184. r'(?P<f>.*)\+ @ (?P<n>.*), parent: (?P<p>.*)', line)
  2185. if m:
  2186. return True if quick else m.group('t', 'f', 'n', 'p')
  2187. return False if quick else ('', '', '', '')
  2188. def initcall_debug_return(self, line, quick=False):
  2189. m = re.match(r'.*(\[ *)(?P<t>[0-9\.]*)(\]) .* (?P<f>.*)\: PM: '+\
  2190. r'.* returned (?P<r>[0-9]*) after (?P<dt>[0-9]*) usecs', line)
  2191. if not m:
  2192. m = re.match(r'.*(\[ *)(?P<t>[0-9\.]*)(\]) .* (?P<f>.*)\: '+\
  2193. r'.* returned (?P<r>[0-9]*) after (?P<dt>[0-9]*) usecs', line)
  2194. if not m:
  2195. m = re.match(r'.*(\[ *)(?P<t>[0-9\.]*)(\]) call '+\
  2196. r'(?P<f>.*)\+ returned .* after (?P<dt>.*) usecs', line)
  2197. if m:
  2198. return True if quick else m.group('t', 'f', 'dt')
  2199. return False if quick else ('', '', '')
  2200. def debugPrint(self):
  2201. for p in self.sortedPhases():
  2202. list = self.dmesg[p]['list']
  2203. for devname in sorted(list):
  2204. dev = list[devname]
  2205. if 'ftrace' in dev:
  2206. dev['ftrace'].debugPrint(' [%s]' % devname)
  2207. # Class: DevFunction
  2208. # Description:
  2209. # A container for kprobe function data we want in the dev timeline
  2210. class DevFunction:
  2211. def __init__(self, name, args, caller, ret, start, end, u, proc, pid, color):
  2212. self.row = 0
  2213. self.count = 1
  2214. self.name = name
  2215. self.args = args
  2216. self.caller = caller
  2217. self.ret = ret
  2218. self.time = start
  2219. self.length = end - start
  2220. self.end = end
  2221. self.ubiquitous = u
  2222. self.proc = proc
  2223. self.pid = pid
  2224. self.color = color
  2225. def title(self):
  2226. cnt = ''
  2227. if self.count > 1:
  2228. cnt = '(x%d)' % self.count
  2229. l = '%0.3fms' % (self.length * 1000)
  2230. if self.ubiquitous:
  2231. title = '%s(%s)%s <- %s, %s(%s)' % \
  2232. (self.name, self.args, cnt, self.caller, self.ret, l)
  2233. else:
  2234. title = '%s(%s) %s%s(%s)' % (self.name, self.args, self.ret, cnt, l)
  2235. return title.replace('"', '')
  2236. def text(self):
  2237. if self.count > 1:
  2238. text = '%s(x%d)' % (self.name, self.count)
  2239. else:
  2240. text = self.name
  2241. return text
  2242. def repeat(self, tgt):
  2243. # is the tgt call just a repeat of this call (e.g. are we in a loop)
  2244. dt = self.time - tgt.end
  2245. # only combine calls if -all- attributes are identical
  2246. if tgt.caller == self.caller and \
  2247. tgt.name == self.name and tgt.args == self.args and \
  2248. tgt.proc == self.proc and tgt.pid == self.pid and \
  2249. tgt.ret == self.ret and dt >= 0 and \
  2250. dt <= sysvals.callloopmaxgap and \
  2251. self.length < sysvals.callloopmaxlen:
  2252. return True
  2253. return False
  2254. # Class: FTraceLine
  2255. # Description:
  2256. # A container for a single line of ftrace data. There are six basic types:
  2257. # callgraph line:
  2258. # call: " dpm_run_callback() {"
  2259. # return: " }"
  2260. # leaf: " dpm_run_callback();"
  2261. # trace event:
  2262. # tracing_mark_write: SUSPEND START or RESUME COMPLETE
  2263. # suspend_resume: phase or custom exec block data
  2264. # device_pm_callback: device callback info
  2265. class FTraceLine:
  2266. def __init__(self, t, m='', d=''):
  2267. self.length = 0.0
  2268. self.fcall = False
  2269. self.freturn = False
  2270. self.fevent = False
  2271. self.fkprobe = False
  2272. self.depth = 0
  2273. self.name = ''
  2274. self.type = ''
  2275. self.time = float(t)
  2276. if not m and not d:
  2277. return
  2278. # is this a trace event
  2279. if(d == 'traceevent' or re.match(r'^ *\/\* *(?P<msg>.*) \*\/ *$', m)):
  2280. if(d == 'traceevent'):
  2281. # nop format trace event
  2282. msg = m
  2283. else:
  2284. # function_graph format trace event
  2285. em = re.match(r'^ *\/\* *(?P<msg>.*) \*\/ *$', m)
  2286. msg = em.group('msg')
  2287. emm = re.match(r'^(?P<call>.*?): (?P<msg>.*)', msg)
  2288. if(emm):
  2289. self.name = emm.group('msg')
  2290. self.type = emm.group('call')
  2291. else:
  2292. self.name = msg
  2293. km = re.match(r'^(?P<n>.*)_cal$', self.type)
  2294. if km:
  2295. self.fcall = True
  2296. self.fkprobe = True
  2297. self.type = km.group('n')
  2298. return
  2299. km = re.match(r'^(?P<n>.*)_ret$', self.type)
  2300. if km:
  2301. self.freturn = True
  2302. self.fkprobe = True
  2303. self.type = km.group('n')
  2304. return
  2305. self.fevent = True
  2306. return
  2307. # convert the duration to seconds
  2308. if(d):
  2309. self.length = float(d)/1000000
  2310. # the indentation determines the depth
  2311. match = re.match(r'^(?P<d> *)(?P<o>.*)$', m)
  2312. if(not match):
  2313. return
  2314. self.depth = self.getDepth(match.group('d'))
  2315. m = match.group('o')
  2316. # function return
  2317. if(m[0] == '}'):
  2318. self.freturn = True
  2319. if(len(m) > 1):
  2320. # includes comment with function name
  2321. match = re.match(r'^} *\/\* *(?P<n>.*) *\*\/$', m)
  2322. if(match):
  2323. self.name = match.group('n').strip()
  2324. # function call
  2325. else:
  2326. self.fcall = True
  2327. # function call with children
  2328. if(m[-1] == '{'):
  2329. match = re.match(r'^(?P<n>.*) *\(.*', m)
  2330. if(match):
  2331. self.name = match.group('n').strip()
  2332. # function call with no children (leaf)
  2333. elif(m[-1] == ';'):
  2334. self.freturn = True
  2335. match = re.match(r'^(?P<n>.*) *\(.*', m)
  2336. if(match):
  2337. self.name = match.group('n').strip()
  2338. # something else (possibly a trace marker)
  2339. else:
  2340. self.name = m
  2341. def isCall(self):
  2342. return self.fcall and not self.freturn
  2343. def isReturn(self):
  2344. return self.freturn and not self.fcall
  2345. def isLeaf(self):
  2346. return self.fcall and self.freturn
  2347. def getDepth(self, str):
  2348. return len(str)/2
  2349. def debugPrint(self, info=''):
  2350. if self.isLeaf():
  2351. pprint(' -- %12.6f (depth=%02d): %s(); (%.3f us) %s' % (self.time, \
  2352. self.depth, self.name, self.length*1000000, info))
  2353. elif self.freturn:
  2354. pprint(' -- %12.6f (depth=%02d): %s} (%.3f us) %s' % (self.time, \
  2355. self.depth, self.name, self.length*1000000, info))
  2356. else:
  2357. pprint(' -- %12.6f (depth=%02d): %s() { (%.3f us) %s' % (self.time, \
  2358. self.depth, self.name, self.length*1000000, info))
  2359. def startMarker(self):
  2360. # Is this the starting line of a suspend?
  2361. if not self.fevent:
  2362. return False
  2363. if sysvals.usetracemarkers:
  2364. if(self.name.startswith('SUSPEND START')):
  2365. return True
  2366. return False
  2367. else:
  2368. if(self.type == 'suspend_resume' and
  2369. re.match(r'suspend_enter\[.*\] begin', self.name)):
  2370. return True
  2371. return False
  2372. def endMarker(self):
  2373. # Is this the ending line of a resume?
  2374. if not self.fevent:
  2375. return False
  2376. if sysvals.usetracemarkers:
  2377. if(self.name.startswith('RESUME COMPLETE')):
  2378. return True
  2379. return False
  2380. else:
  2381. if(self.type == 'suspend_resume' and
  2382. re.match(r'thaw_processes\[.*\] end', self.name)):
  2383. return True
  2384. return False
  2385. # Class: FTraceCallGraph
  2386. # Description:
  2387. # A container for the ftrace callgraph of a single recursive function.
  2388. # This can be a dpm_run_callback, dpm_prepare, or dpm_complete callgraph
  2389. # Each instance is tied to a single device in a single phase, and is
  2390. # comprised of an ordered list of FTraceLine objects
  2391. class FTraceCallGraph:
  2392. vfname = 'missing_function_name'
  2393. def __init__(self, pid, sv):
  2394. self.id = ''
  2395. self.invalid = False
  2396. self.name = ''
  2397. self.partial = False
  2398. self.ignore = False
  2399. self.start = -1.0
  2400. self.end = -1.0
  2401. self.list = []
  2402. self.depth = 0
  2403. self.pid = pid
  2404. self.sv = sv
  2405. def addLine(self, line):
  2406. # if this is already invalid, just leave
  2407. if(self.invalid):
  2408. if(line.depth == 0 and line.freturn):
  2409. return 1
  2410. return 0
  2411. # invalidate on bad depth
  2412. if(self.depth < 0):
  2413. self.invalidate(line)
  2414. return 0
  2415. # ignore data til we return to the current depth
  2416. if self.ignore:
  2417. if line.depth > self.depth:
  2418. return 0
  2419. else:
  2420. self.list[-1].freturn = True
  2421. self.list[-1].length = line.time - self.list[-1].time
  2422. self.ignore = False
  2423. # if this is a return at self.depth, no more work is needed
  2424. if line.depth == self.depth and line.isReturn():
  2425. if line.depth == 0:
  2426. self.end = line.time
  2427. return 1
  2428. return 0
  2429. # compare current depth with this lines pre-call depth
  2430. prelinedep = line.depth
  2431. if line.isReturn():
  2432. prelinedep += 1
  2433. last = 0
  2434. lasttime = line.time
  2435. if len(self.list) > 0:
  2436. last = self.list[-1]
  2437. lasttime = last.time
  2438. if last.isLeaf():
  2439. lasttime += last.length
  2440. # handle low misalignments by inserting returns
  2441. mismatch = prelinedep - self.depth
  2442. warning = self.sv.verbose and abs(mismatch) > 1
  2443. info = []
  2444. if mismatch < 0:
  2445. idx = 0
  2446. # add return calls to get the depth down
  2447. while prelinedep < self.depth:
  2448. self.depth -= 1
  2449. if idx == 0 and last and last.isCall():
  2450. # special case, turn last call into a leaf
  2451. last.depth = self.depth
  2452. last.freturn = True
  2453. last.length = line.time - last.time
  2454. if warning:
  2455. info.append(('[make leaf]', last))
  2456. else:
  2457. vline = FTraceLine(lasttime)
  2458. vline.depth = self.depth
  2459. vline.name = self.vfname
  2460. vline.freturn = True
  2461. self.list.append(vline)
  2462. if warning:
  2463. if idx == 0:
  2464. info.append(('', last))
  2465. info.append(('[add return]', vline))
  2466. idx += 1
  2467. if warning:
  2468. info.append(('', line))
  2469. # handle high misalignments by inserting calls
  2470. elif mismatch > 0:
  2471. idx = 0
  2472. if warning:
  2473. info.append(('', last))
  2474. # add calls to get the depth up
  2475. while prelinedep > self.depth:
  2476. if idx == 0 and line.isReturn():
  2477. # special case, turn this return into a leaf
  2478. line.fcall = True
  2479. prelinedep -= 1
  2480. if warning:
  2481. info.append(('[make leaf]', line))
  2482. else:
  2483. vline = FTraceLine(lasttime)
  2484. vline.depth = self.depth
  2485. vline.name = self.vfname
  2486. vline.fcall = True
  2487. self.list.append(vline)
  2488. self.depth += 1
  2489. if not last:
  2490. self.start = vline.time
  2491. if warning:
  2492. info.append(('[add call]', vline))
  2493. idx += 1
  2494. if warning and ('[make leaf]', line) not in info:
  2495. info.append(('', line))
  2496. if warning:
  2497. pprint('WARNING: ftrace data missing, corrections made:')
  2498. for i in info:
  2499. t, obj = i
  2500. if obj:
  2501. obj.debugPrint(t)
  2502. # process the call and set the new depth
  2503. skipadd = False
  2504. md = self.sv.max_graph_depth
  2505. if line.isCall():
  2506. # ignore blacklisted/overdepth funcs
  2507. if (md and self.depth >= md - 1) or (line.name in self.sv.cgblacklist):
  2508. self.ignore = True
  2509. else:
  2510. self.depth += 1
  2511. elif line.isReturn():
  2512. self.depth -= 1
  2513. # remove blacklisted/overdepth/empty funcs that slipped through
  2514. if (last and last.isCall() and last.depth == line.depth) or \
  2515. (md and last and last.depth >= md) or \
  2516. (line.name in self.sv.cgblacklist):
  2517. while len(self.list) > 0 and self.list[-1].depth > line.depth:
  2518. self.list.pop(-1)
  2519. if len(self.list) == 0:
  2520. self.invalid = True
  2521. return 1
  2522. self.list[-1].freturn = True
  2523. self.list[-1].length = line.time - self.list[-1].time
  2524. self.list[-1].name = line.name
  2525. skipadd = True
  2526. if len(self.list) < 1:
  2527. self.start = line.time
  2528. # check for a mismatch that returned all the way to callgraph end
  2529. res = 1
  2530. if mismatch < 0 and self.list[-1].depth == 0 and self.list[-1].freturn:
  2531. line = self.list[-1]
  2532. skipadd = True
  2533. res = -1
  2534. if not skipadd:
  2535. self.list.append(line)
  2536. if(line.depth == 0 and line.freturn):
  2537. if(self.start < 0):
  2538. self.start = line.time
  2539. self.end = line.time
  2540. if line.fcall:
  2541. self.end += line.length
  2542. if self.list[0].name == self.vfname:
  2543. self.invalid = True
  2544. if res == -1:
  2545. self.partial = True
  2546. return res
  2547. return 0
  2548. def invalidate(self, line):
  2549. if(len(self.list) > 0):
  2550. first = self.list[0]
  2551. self.list = []
  2552. self.list.append(first)
  2553. self.invalid = True
  2554. id = 'task %s' % (self.pid)
  2555. window = '(%f - %f)' % (self.start, line.time)
  2556. if(self.depth < 0):
  2557. pprint('Data misalignment for '+id+\
  2558. ' (buffer overflow), ignoring this callback')
  2559. else:
  2560. pprint('Too much data for '+id+\
  2561. ' '+window+', ignoring this callback')
  2562. def slice(self, dev):
  2563. minicg = FTraceCallGraph(dev['pid'], self.sv)
  2564. minicg.name = self.name
  2565. mydepth = -1
  2566. good = False
  2567. for l in self.list:
  2568. if(l.time < dev['start'] or l.time > dev['end']):
  2569. continue
  2570. if mydepth < 0:
  2571. if l.name == 'mutex_lock' and l.freturn:
  2572. mydepth = l.depth
  2573. continue
  2574. elif l.depth == mydepth and l.name == 'mutex_unlock' and l.fcall:
  2575. good = True
  2576. break
  2577. l.depth -= mydepth
  2578. minicg.addLine(l)
  2579. if not good or len(minicg.list) < 1:
  2580. return 0
  2581. return minicg
  2582. def repair(self, enddepth):
  2583. # bring the depth back to 0 with additional returns
  2584. fixed = False
  2585. last = self.list[-1]
  2586. for i in reversed(range(enddepth)):
  2587. t = FTraceLine(last.time)
  2588. t.depth = i
  2589. t.freturn = True
  2590. fixed = self.addLine(t)
  2591. if fixed != 0:
  2592. self.end = last.time
  2593. return True
  2594. return False
  2595. def postProcess(self):
  2596. if len(self.list) > 0:
  2597. self.name = self.list[0].name
  2598. stack = dict()
  2599. cnt = 0
  2600. last = 0
  2601. for l in self.list:
  2602. # ftrace bug: reported duration is not reliable
  2603. # check each leaf and clip it at max possible length
  2604. if last and last.isLeaf():
  2605. if last.length > l.time - last.time:
  2606. last.length = l.time - last.time
  2607. if l.isCall():
  2608. stack[l.depth] = l
  2609. cnt += 1
  2610. elif l.isReturn():
  2611. if(l.depth not in stack):
  2612. if self.sv.verbose:
  2613. pprint('Post Process Error: Depth missing')
  2614. l.debugPrint()
  2615. return False
  2616. # calculate call length from call/return lines
  2617. cl = stack[l.depth]
  2618. cl.length = l.time - cl.time
  2619. if cl.name == self.vfname:
  2620. cl.name = l.name
  2621. stack.pop(l.depth)
  2622. l.length = 0
  2623. cnt -= 1
  2624. last = l
  2625. if(cnt == 0):
  2626. # trace caught the whole call tree
  2627. return True
  2628. elif(cnt < 0):
  2629. if self.sv.verbose:
  2630. pprint('Post Process Error: Depth is less than 0')
  2631. return False
  2632. # trace ended before call tree finished
  2633. return self.repair(cnt)
  2634. def deviceMatch(self, pid, data):
  2635. found = ''
  2636. # add the callgraph data to the device hierarchy
  2637. borderphase = {
  2638. 'dpm_prepare': 'suspend_prepare',
  2639. 'dpm_complete': 'resume_complete'
  2640. }
  2641. if(self.name in borderphase):
  2642. p = borderphase[self.name]
  2643. list = data.dmesg[p]['list']
  2644. for devname in list:
  2645. dev = list[devname]
  2646. if(pid == dev['pid'] and
  2647. self.start <= dev['start'] and
  2648. self.end >= dev['end']):
  2649. cg = self.slice(dev)
  2650. if cg:
  2651. dev['ftrace'] = cg
  2652. found = devname
  2653. return found
  2654. for p in data.sortedPhases():
  2655. if(data.dmesg[p]['start'] <= self.start and
  2656. self.start <= data.dmesg[p]['end']):
  2657. list = data.dmesg[p]['list']
  2658. for devname in sorted(list, key=lambda k:list[k]['start']):
  2659. dev = list[devname]
  2660. if(pid == dev['pid'] and
  2661. self.start <= dev['start'] and
  2662. self.end >= dev['end']):
  2663. dev['ftrace'] = self
  2664. found = devname
  2665. break
  2666. break
  2667. return found
  2668. def newActionFromFunction(self, data):
  2669. name = self.name
  2670. if name in ['dpm_run_callback', 'dpm_prepare', 'dpm_complete']:
  2671. return
  2672. fs = self.start
  2673. fe = self.end
  2674. if fs < data.start or fe > data.end:
  2675. return
  2676. phase = ''
  2677. for p in data.sortedPhases():
  2678. if(data.dmesg[p]['start'] <= self.start and
  2679. self.start < data.dmesg[p]['end']):
  2680. phase = p
  2681. break
  2682. if not phase:
  2683. return
  2684. out = data.newActionGlobal(name, fs, fe, -2)
  2685. if out:
  2686. phase, myname = out
  2687. data.dmesg[phase]['list'][myname]['ftrace'] = self
  2688. def debugPrint(self, info=''):
  2689. pprint('%s pid=%d [%f - %f] %.3f us' % \
  2690. (self.name, self.pid, self.start, self.end,
  2691. (self.end - self.start)*1000000))
  2692. for l in self.list:
  2693. if l.isLeaf():
  2694. pprint('%f (%02d): %s(); (%.3f us)%s' % (l.time, \
  2695. l.depth, l.name, l.length*1000000, info))
  2696. elif l.freturn:
  2697. pprint('%f (%02d): %s} (%.3f us)%s' % (l.time, \
  2698. l.depth, l.name, l.length*1000000, info))
  2699. else:
  2700. pprint('%f (%02d): %s() { (%.3f us)%s' % (l.time, \
  2701. l.depth, l.name, l.length*1000000, info))
  2702. pprint(' ')
  2703. class DevItem:
  2704. def __init__(self, test, phase, dev):
  2705. self.test = test
  2706. self.phase = phase
  2707. self.dev = dev
  2708. def isa(self, cls):
  2709. if 'htmlclass' in self.dev and cls in self.dev['htmlclass']:
  2710. return True
  2711. return False
  2712. # Class: Timeline
  2713. # Description:
  2714. # A container for a device timeline which calculates
  2715. # all the html properties to display it correctly
  2716. class Timeline:
  2717. html_tblock = '<div id="block{0}" class="tblock" style="left:{1}%;width:{2}%;"><div class="tback" style="height:{3}px"></div>\n'
  2718. html_device = '<div id="{0}" title="{1}" class="thread{7}" style="left:{2}%;top:{3}px;height:{4}px;width:{5}%;{8}">{6}</div>\n'
  2719. html_phase = '<div class="phase" style="left:{0}%;width:{1}%;top:{2}px;height:{3}px;background:{4}">{5}</div>\n'
  2720. html_phaselet = '<div id="{0}" class="phaselet" style="left:{1}%;width:{2}%;background:{3}"></div>\n'
  2721. html_legend = '<div id="p{3}" class="square" style="left:{0}%;background:{1}">&nbsp;{2}</div>\n'
  2722. def __init__(self, rowheight, scaleheight):
  2723. self.html = ''
  2724. self.height = 0 # total timeline height
  2725. self.scaleH = scaleheight # timescale (top) row height
  2726. self.rowH = rowheight # device row height
  2727. self.bodyH = 0 # body height
  2728. self.rows = 0 # total timeline rows
  2729. self.rowlines = dict()
  2730. self.rowheight = dict()
  2731. def createHeader(self, sv, stamp):
  2732. if(not stamp['time']):
  2733. return
  2734. self.html += '<div class="version"><a href="https://01.org/pm-graph">%s v%s</a></div>' \
  2735. % (sv.title, sv.version)
  2736. if sv.logmsg and sv.testlog:
  2737. self.html += '<button id="showtest" class="logbtn btnfmt">log</button>'
  2738. if sv.dmesglog:
  2739. self.html += '<button id="showdmesg" class="logbtn btnfmt">dmesg</button>'
  2740. if sv.ftracelog:
  2741. self.html += '<button id="showftrace" class="logbtn btnfmt">ftrace</button>'
  2742. headline_stamp = '<div class="stamp">{0} {1} {2} {3}</div>\n'
  2743. self.html += headline_stamp.format(stamp['host'], stamp['kernel'],
  2744. stamp['mode'], stamp['time'])
  2745. if 'man' in stamp and 'plat' in stamp and 'cpu' in stamp and \
  2746. stamp['man'] and stamp['plat'] and stamp['cpu']:
  2747. headline_sysinfo = '<div class="stamp sysinfo">{0} {1} <i>with</i> {2}</div>\n'
  2748. self.html += headline_sysinfo.format(stamp['man'], stamp['plat'], stamp['cpu'])
  2749. # Function: getDeviceRows
  2750. # Description:
  2751. # determine how may rows the device funcs will take
  2752. # Arguments:
  2753. # rawlist: the list of devices/actions for a single phase
  2754. # Output:
  2755. # The total number of rows needed to display this phase of the timeline
  2756. def getDeviceRows(self, rawlist):
  2757. # clear all rows and set them to undefined
  2758. sortdict = dict()
  2759. for item in rawlist:
  2760. item.row = -1
  2761. sortdict[item] = item.length
  2762. sortlist = sorted(sortdict, key=sortdict.get, reverse=True)
  2763. remaining = len(sortlist)
  2764. rowdata = dict()
  2765. row = 1
  2766. # try to pack each row with as many ranges as possible
  2767. while(remaining > 0):
  2768. if(row not in rowdata):
  2769. rowdata[row] = []
  2770. for i in sortlist:
  2771. if(i.row >= 0):
  2772. continue
  2773. s = i.time
  2774. e = i.time + i.length
  2775. valid = True
  2776. for ritem in rowdata[row]:
  2777. rs = ritem.time
  2778. re = ritem.time + ritem.length
  2779. if(not (((s <= rs) and (e <= rs)) or
  2780. ((s >= re) and (e >= re)))):
  2781. valid = False
  2782. break
  2783. if(valid):
  2784. rowdata[row].append(i)
  2785. i.row = row
  2786. remaining -= 1
  2787. row += 1
  2788. return row
  2789. # Function: getPhaseRows
  2790. # Description:
  2791. # Organize the timeline entries into the smallest
  2792. # number of rows possible, with no entry overlapping
  2793. # Arguments:
  2794. # devlist: the list of devices/actions in a group of contiguous phases
  2795. # Output:
  2796. # The total number of rows needed to display this phase of the timeline
  2797. def getPhaseRows(self, devlist, row=0, sortby='length'):
  2798. # clear all rows and set them to undefined
  2799. remaining = len(devlist)
  2800. rowdata = dict()
  2801. sortdict = dict()
  2802. myphases = []
  2803. # initialize all device rows to -1 and calculate devrows
  2804. for item in devlist:
  2805. dev = item.dev
  2806. tp = (item.test, item.phase)
  2807. if tp not in myphases:
  2808. myphases.append(tp)
  2809. dev['row'] = -1
  2810. if sortby == 'start':
  2811. # sort by start 1st, then length 2nd
  2812. sortdict[item] = (-1*float(dev['start']), float(dev['end']) - float(dev['start']))
  2813. else:
  2814. # sort by length 1st, then name 2nd
  2815. sortdict[item] = (float(dev['end']) - float(dev['start']), item.dev['name'])
  2816. if 'src' in dev:
  2817. dev['devrows'] = self.getDeviceRows(dev['src'])
  2818. # sort the devlist by length so that large items graph on top
  2819. sortlist = sorted(sortdict, key=sortdict.get, reverse=True)
  2820. orderedlist = []
  2821. for item in sortlist:
  2822. if item.dev['pid'] == -2:
  2823. orderedlist.append(item)
  2824. for item in sortlist:
  2825. if item not in orderedlist:
  2826. orderedlist.append(item)
  2827. # try to pack each row with as many devices as possible
  2828. while(remaining > 0):
  2829. rowheight = 1
  2830. if(row not in rowdata):
  2831. rowdata[row] = []
  2832. for item in orderedlist:
  2833. dev = item.dev
  2834. if(dev['row'] < 0):
  2835. s = dev['start']
  2836. e = dev['end']
  2837. valid = True
  2838. for ritem in rowdata[row]:
  2839. rs = ritem.dev['start']
  2840. re = ritem.dev['end']
  2841. if(not (((s <= rs) and (e <= rs)) or
  2842. ((s >= re) and (e >= re)))):
  2843. valid = False
  2844. break
  2845. if(valid):
  2846. rowdata[row].append(item)
  2847. dev['row'] = row
  2848. remaining -= 1
  2849. if 'devrows' in dev and dev['devrows'] > rowheight:
  2850. rowheight = dev['devrows']
  2851. for t, p in myphases:
  2852. if t not in self.rowlines or t not in self.rowheight:
  2853. self.rowlines[t] = dict()
  2854. self.rowheight[t] = dict()
  2855. if p not in self.rowlines[t] or p not in self.rowheight[t]:
  2856. self.rowlines[t][p] = dict()
  2857. self.rowheight[t][p] = dict()
  2858. rh = self.rowH
  2859. # section headers should use a different row height
  2860. if len(rowdata[row]) == 1 and \
  2861. 'htmlclass' in rowdata[row][0].dev and \
  2862. 'sec' in rowdata[row][0].dev['htmlclass']:
  2863. rh = 15
  2864. self.rowlines[t][p][row] = rowheight
  2865. self.rowheight[t][p][row] = rowheight * rh
  2866. row += 1
  2867. if(row > self.rows):
  2868. self.rows = int(row)
  2869. return row
  2870. def phaseRowHeight(self, test, phase, row):
  2871. return self.rowheight[test][phase][row]
  2872. def phaseRowTop(self, test, phase, row):
  2873. top = 0
  2874. for i in sorted(self.rowheight[test][phase]):
  2875. if i >= row:
  2876. break
  2877. top += self.rowheight[test][phase][i]
  2878. return top
  2879. def calcTotalRows(self):
  2880. # Calculate the heights and offsets for the header and rows
  2881. maxrows = 0
  2882. standardphases = []
  2883. for t in self.rowlines:
  2884. for p in self.rowlines[t]:
  2885. total = 0
  2886. for i in sorted(self.rowlines[t][p]):
  2887. total += self.rowlines[t][p][i]
  2888. if total > maxrows:
  2889. maxrows = total
  2890. if total == len(self.rowlines[t][p]):
  2891. standardphases.append((t, p))
  2892. self.height = self.scaleH + (maxrows*self.rowH)
  2893. self.bodyH = self.height - self.scaleH
  2894. # if there is 1 line per row, draw them the standard way
  2895. for t, p in standardphases:
  2896. for i in sorted(self.rowheight[t][p]):
  2897. self.rowheight[t][p][i] = float(self.bodyH)/len(self.rowlines[t][p])
  2898. def createZoomBox(self, mode='command', testcount=1):
  2899. # Create bounding box, add buttons
  2900. html_zoombox = '<center><button id="zoomin">ZOOM IN +</button><button id="zoomout">ZOOM OUT -</button><button id="zoomdef">ZOOM 1:1</button></center>\n'
  2901. html_timeline = '<div id="dmesgzoombox" class="zoombox">\n<div id="{0}" class="timeline" style="height:{1}px">\n'
  2902. html_devlist1 = '<button id="devlist1" class="devlist" style="float:left;">Device Detail{0}</button>'
  2903. html_devlist2 = '<button id="devlist2" class="devlist" style="float:right;">Device Detail2</button>\n'
  2904. if mode != 'command':
  2905. if testcount > 1:
  2906. self.html += html_devlist2
  2907. self.html += html_devlist1.format('1')
  2908. else:
  2909. self.html += html_devlist1.format('')
  2910. self.html += html_zoombox
  2911. self.html += html_timeline.format('dmesg', self.height)
  2912. # Function: createTimeScale
  2913. # Description:
  2914. # Create the timescale for a timeline block
  2915. # Arguments:
  2916. # m0: start time (mode begin)
  2917. # mMax: end time (mode end)
  2918. # tTotal: total timeline time
  2919. # mode: suspend or resume
  2920. # Output:
  2921. # The html code needed to display the time scale
  2922. def createTimeScale(self, m0, mMax, tTotal, mode):
  2923. timescale = '<div class="t" style="right:{0}%">{1}</div>\n'
  2924. rline = '<div class="t" style="left:0;border-left:1px solid black;border-right:0;">{0}</div>\n'
  2925. output = '<div class="timescale">\n'
  2926. # set scale for timeline
  2927. mTotal = mMax - m0
  2928. tS = 0.1
  2929. if(tTotal <= 0):
  2930. return output+'</div>\n'
  2931. if(tTotal > 4):
  2932. tS = 1
  2933. divTotal = int(mTotal/tS) + 1
  2934. divEdge = (mTotal - tS*(divTotal-1))*100/mTotal
  2935. for i in range(divTotal):
  2936. htmlline = ''
  2937. if(mode == 'suspend'):
  2938. pos = '%0.3f' % (100 - ((float(i)*tS*100)/mTotal) - divEdge)
  2939. val = '%0.fms' % (float(i-divTotal+1)*tS*1000)
  2940. if(i == divTotal - 1):
  2941. val = mode
  2942. htmlline = timescale.format(pos, val)
  2943. else:
  2944. pos = '%0.3f' % (100 - ((float(i)*tS*100)/mTotal))
  2945. val = '%0.fms' % (float(i)*tS*1000)
  2946. htmlline = timescale.format(pos, val)
  2947. if(i == 0):
  2948. htmlline = rline.format(mode)
  2949. output += htmlline
  2950. self.html += output+'</div>\n'
  2951. # Class: TestProps
  2952. # Description:
  2953. # A list of values describing the properties of these test runs
  2954. class TestProps:
  2955. stampfmt = r'# [a-z]*-(?P<m>[0-9]{2})(?P<d>[0-9]{2})(?P<y>[0-9]{2})-'+\
  2956. r'(?P<H>[0-9]{2})(?P<M>[0-9]{2})(?P<S>[0-9]{2})'+\
  2957. r' (?P<host>.*) (?P<mode>.*) (?P<kernel>.*)$'
  2958. wififmt = r'^# wifi *(?P<d>\S*) *(?P<s>\S*) *(?P<t>[0-9\.]+).*'
  2959. tstatfmt = r'^# turbostat (?P<t>\S*)'
  2960. testerrfmt = r'^# enter_sleep_error (?P<e>.*)'
  2961. sysinfofmt = r'^# sysinfo .*'
  2962. cmdlinefmt = r'^# command \| (?P<cmd>.*)'
  2963. kparamsfmt = r'^# kparams \| (?P<kp>.*)'
  2964. devpropfmt = r'# Device Properties: .*'
  2965. pinfofmt = r'# platform-(?P<val>[a-z,A-Z,0-9,_]*): (?P<info>.*)'
  2966. tracertypefmt = r'# tracer: (?P<t>.*)'
  2967. firmwarefmt = r'# fwsuspend (?P<s>[0-9]*) fwresume (?P<r>[0-9]*)$'
  2968. procexecfmt = r'ps - (?P<ps>.*)$'
  2969. procmultifmt = r'@(?P<n>[0-9]*)\|(?P<ps>.*)$'
  2970. ftrace_line_fmt_fg = \
  2971. r'^ *(?P<time>[0-9\.]*) *\| *(?P<cpu>[0-9]*)\)'+\
  2972. r' *(?P<proc>.*)-(?P<pid>[0-9]*) *\|'+\
  2973. r'[ +!#\*@$]*(?P<dur>[0-9\.]*) .*\| (?P<msg>.*)'
  2974. ftrace_line_fmt_nop = \
  2975. r' *(?P<proc>.*)-(?P<pid>[0-9]*) *\[(?P<cpu>[0-9]*)\] *'+\
  2976. r'(?P<flags>\S*) *(?P<time>[0-9\.]*): *'+\
  2977. r'(?P<msg>.*)'
  2978. machinesuspend = r'machine_suspend\[.*'
  2979. multiproclist = dict()
  2980. multiproctime = 0.0
  2981. multiproccnt = 0
  2982. def __init__(self):
  2983. self.stamp = ''
  2984. self.sysinfo = ''
  2985. self.cmdline = ''
  2986. self.testerror = []
  2987. self.turbostat = []
  2988. self.wifi = []
  2989. self.fwdata = []
  2990. self.ftrace_line_fmt = self.ftrace_line_fmt_nop
  2991. self.cgformat = False
  2992. self.data = 0
  2993. self.ktemp = dict()
  2994. def setTracerType(self, tracer):
  2995. if(tracer == 'function_graph'):
  2996. self.cgformat = True
  2997. self.ftrace_line_fmt = self.ftrace_line_fmt_fg
  2998. elif(tracer == 'nop'):
  2999. self.ftrace_line_fmt = self.ftrace_line_fmt_nop
  3000. else:
  3001. doError('Invalid tracer format: [%s]' % tracer)
  3002. def stampInfo(self, line, sv):
  3003. if re.match(self.stampfmt, line):
  3004. self.stamp = line
  3005. return True
  3006. elif re.match(self.sysinfofmt, line):
  3007. self.sysinfo = line
  3008. return True
  3009. elif re.match(self.tstatfmt, line):
  3010. self.turbostat.append(line)
  3011. return True
  3012. elif re.match(self.wififmt, line):
  3013. self.wifi.append(line)
  3014. return True
  3015. elif re.match(self.testerrfmt, line):
  3016. self.testerror.append(line)
  3017. return True
  3018. elif re.match(self.firmwarefmt, line):
  3019. self.fwdata.append(line)
  3020. return True
  3021. elif(re.match(self.devpropfmt, line)):
  3022. self.parseDevprops(line, sv)
  3023. return True
  3024. elif(re.match(self.pinfofmt, line)):
  3025. self.parsePlatformInfo(line, sv)
  3026. return True
  3027. m = re.match(self.cmdlinefmt, line)
  3028. if m:
  3029. self.cmdline = m.group('cmd')
  3030. return True
  3031. m = re.match(self.tracertypefmt, line)
  3032. if(m):
  3033. self.setTracerType(m.group('t'))
  3034. return True
  3035. return False
  3036. def parseStamp(self, data, sv):
  3037. # global test data
  3038. m = re.match(self.stampfmt, self.stamp)
  3039. if not self.stamp or not m:
  3040. doError('data does not include the expected stamp')
  3041. data.stamp = {'time': '', 'host': '', 'mode': ''}
  3042. dt = datetime(int(m.group('y'))+2000, int(m.group('m')),
  3043. int(m.group('d')), int(m.group('H')), int(m.group('M')),
  3044. int(m.group('S')))
  3045. data.stamp['time'] = dt.strftime('%B %d %Y, %I:%M:%S %p')
  3046. data.stamp['host'] = m.group('host')
  3047. data.stamp['mode'] = m.group('mode')
  3048. data.stamp['kernel'] = m.group('kernel')
  3049. if re.match(self.sysinfofmt, self.sysinfo):
  3050. for f in self.sysinfo.split('|'):
  3051. if '#' in f:
  3052. continue
  3053. tmp = f.strip().split(':', 1)
  3054. key = tmp[0]
  3055. val = tmp[1]
  3056. data.stamp[key] = val
  3057. sv.hostname = data.stamp['host']
  3058. sv.suspendmode = data.stamp['mode']
  3059. if sv.suspendmode == 'freeze':
  3060. self.machinesuspend = r'timekeeping_freeze\[.*'
  3061. else:
  3062. self.machinesuspend = r'machine_suspend\[.*'
  3063. if sv.suspendmode == 'command' and sv.ftracefile != '':
  3064. modes = ['on', 'freeze', 'standby', 'mem', 'disk']
  3065. fp = sv.openlog(sv.ftracefile, 'r')
  3066. for line in fp:
  3067. m = re.match(r'.* machine_suspend\[(?P<mode>.*)\]', line)
  3068. if m and m.group('mode') in ['1', '2', '3', '4']:
  3069. sv.suspendmode = modes[int(m.group('mode'))]
  3070. data.stamp['mode'] = sv.suspendmode
  3071. break
  3072. fp.close()
  3073. sv.cmdline = self.cmdline
  3074. if not sv.stamp:
  3075. sv.stamp = data.stamp
  3076. # firmware data
  3077. if sv.suspendmode == 'mem' and len(self.fwdata) > data.testnumber:
  3078. m = re.match(self.firmwarefmt, self.fwdata[data.testnumber])
  3079. if m:
  3080. data.fwSuspend, data.fwResume = int(m.group('s')), int(m.group('r'))
  3081. if(data.fwSuspend > 0 or data.fwResume > 0):
  3082. data.fwValid = True
  3083. # turbostat data
  3084. if len(self.turbostat) > data.testnumber:
  3085. m = re.match(self.tstatfmt, self.turbostat[data.testnumber])
  3086. if m:
  3087. data.turbostat = m.group('t')
  3088. # wifi data
  3089. if len(self.wifi) > data.testnumber:
  3090. m = re.match(self.wififmt, self.wifi[data.testnumber])
  3091. if m:
  3092. data.wifi = {'dev': m.group('d'), 'stat': m.group('s'),
  3093. 'time': float(m.group('t'))}
  3094. data.stamp['wifi'] = m.group('d')
  3095. # sleep mode enter errors
  3096. if len(self.testerror) > data.testnumber:
  3097. m = re.match(self.testerrfmt, self.testerror[data.testnumber])
  3098. if m:
  3099. data.enterfail = m.group('e')
  3100. def devprops(self, data):
  3101. props = dict()
  3102. devlist = data.split(';')
  3103. for dev in devlist:
  3104. f = dev.split(',')
  3105. if len(f) < 3:
  3106. continue
  3107. dev = f[0]
  3108. props[dev] = DevProps()
  3109. props[dev].altname = f[1]
  3110. if int(f[2]):
  3111. props[dev].isasync = True
  3112. else:
  3113. props[dev].isasync = False
  3114. return props
  3115. def parseDevprops(self, line, sv):
  3116. idx = line.index(': ') + 2
  3117. if idx >= len(line):
  3118. return
  3119. props = self.devprops(line[idx:])
  3120. if sv.suspendmode == 'command' and 'testcommandstring' in props:
  3121. sv.testcommand = props['testcommandstring'].altname
  3122. sv.devprops = props
  3123. def parsePlatformInfo(self, line, sv):
  3124. m = re.match(self.pinfofmt, line)
  3125. if not m:
  3126. return
  3127. name, info = m.group('val'), m.group('info')
  3128. if name == 'devinfo':
  3129. sv.devprops = self.devprops(sv.b64unzip(info))
  3130. return
  3131. elif name == 'testcmd':
  3132. sv.testcommand = info
  3133. return
  3134. field = info.split('|')
  3135. if len(field) < 2:
  3136. return
  3137. cmdline = field[0].strip()
  3138. output = sv.b64unzip(field[1].strip())
  3139. sv.platinfo.append([name, cmdline, output])
  3140. # Class: TestRun
  3141. # Description:
  3142. # A container for a suspend/resume test run. This is necessary as
  3143. # there could be more than one, and they need to be separate.
  3144. class TestRun:
  3145. def __init__(self, dataobj):
  3146. self.data = dataobj
  3147. self.ftemp = dict()
  3148. self.ttemp = dict()
  3149. class ProcessMonitor:
  3150. maxchars = 512
  3151. def __init__(self):
  3152. self.proclist = dict()
  3153. self.running = False
  3154. def procstat(self):
  3155. c = ['cat /proc/[1-9]*/stat 2>/dev/null']
  3156. process = Popen(c, shell=True, stdout=PIPE)
  3157. running = dict()
  3158. for line in process.stdout:
  3159. data = ascii(line).split()
  3160. pid = data[0]
  3161. name = re.sub('[()]', '', data[1])
  3162. user = int(data[13])
  3163. kern = int(data[14])
  3164. kjiff = ujiff = 0
  3165. if pid not in self.proclist:
  3166. self.proclist[pid] = {'name' : name, 'user' : user, 'kern' : kern}
  3167. else:
  3168. val = self.proclist[pid]
  3169. ujiff = user - val['user']
  3170. kjiff = kern - val['kern']
  3171. val['user'] = user
  3172. val['kern'] = kern
  3173. if ujiff > 0 or kjiff > 0:
  3174. running[pid] = ujiff + kjiff
  3175. process.wait()
  3176. out = ['']
  3177. for pid in running:
  3178. jiffies = running[pid]
  3179. val = self.proclist[pid]
  3180. if len(out[-1]) > self.maxchars:
  3181. out.append('')
  3182. elif len(out[-1]) > 0:
  3183. out[-1] += ','
  3184. out[-1] += '%s-%s %d' % (val['name'], pid, jiffies)
  3185. if len(out) > 1:
  3186. for line in out:
  3187. sysvals.fsetVal('ps - @%d|%s' % (len(out), line), 'trace_marker')
  3188. else:
  3189. sysvals.fsetVal('ps - %s' % out[0], 'trace_marker')
  3190. def processMonitor(self, tid):
  3191. while self.running:
  3192. self.procstat()
  3193. def start(self):
  3194. self.thread = Thread(target=self.processMonitor, args=(0,))
  3195. self.running = True
  3196. self.thread.start()
  3197. def stop(self):
  3198. self.running = False
  3199. # ----------------- FUNCTIONS --------------------
  3200. # Function: doesTraceLogHaveTraceEvents
  3201. # Description:
  3202. # Quickly determine if the ftrace log has all of the trace events,
  3203. # markers, and/or kprobes required for primary parsing.
  3204. def doesTraceLogHaveTraceEvents():
  3205. kpcheck = ['_cal: (', '_ret: (']
  3206. techeck = ['suspend_resume', 'device_pm_callback', 'tracing_mark_write']
  3207. tmcheck = ['SUSPEND START', 'RESUME COMPLETE']
  3208. sysvals.usekprobes = False
  3209. fp = sysvals.openlog(sysvals.ftracefile, 'r')
  3210. for line in fp:
  3211. # check for kprobes
  3212. if not sysvals.usekprobes:
  3213. for i in kpcheck:
  3214. if i in line:
  3215. sysvals.usekprobes = True
  3216. # check for all necessary trace events
  3217. check = techeck[:]
  3218. for i in techeck:
  3219. if i in line:
  3220. check.remove(i)
  3221. techeck = check
  3222. # check for all necessary trace markers
  3223. check = tmcheck[:]
  3224. for i in tmcheck:
  3225. if i in line:
  3226. check.remove(i)
  3227. tmcheck = check
  3228. fp.close()
  3229. sysvals.usetraceevents = True if len(techeck) < 3 else False
  3230. sysvals.usetracemarkers = True if len(tmcheck) == 0 else False
  3231. # Function: appendIncompleteTraceLog
  3232. # Description:
  3233. # Adds callgraph data which lacks trace event data. This is only
  3234. # for timelines generated from 3.15 or older
  3235. # Arguments:
  3236. # testruns: the array of Data objects obtained from parseKernelLog
  3237. def appendIncompleteTraceLog(testruns):
  3238. # create TestRun vessels for ftrace parsing
  3239. testcnt = len(testruns)
  3240. testidx = 0
  3241. testrun = []
  3242. for data in testruns:
  3243. testrun.append(TestRun(data))
  3244. # extract the callgraph and traceevent data
  3245. sysvals.vprint('Analyzing the ftrace data (%s)...' % \
  3246. os.path.basename(sysvals.ftracefile))
  3247. tp = TestProps()
  3248. tf = sysvals.openlog(sysvals.ftracefile, 'r')
  3249. data = 0
  3250. for line in tf:
  3251. # remove any latent carriage returns
  3252. line = line.replace('\r\n', '')
  3253. if tp.stampInfo(line, sysvals):
  3254. continue
  3255. # parse only valid lines, if this is not one move on
  3256. m = re.match(tp.ftrace_line_fmt, line)
  3257. if(not m):
  3258. continue
  3259. # gather the basic message data from the line
  3260. m_time = m.group('time')
  3261. m_pid = m.group('pid')
  3262. m_msg = m.group('msg')
  3263. if(tp.cgformat):
  3264. m_param3 = m.group('dur')
  3265. else:
  3266. m_param3 = 'traceevent'
  3267. if(m_time and m_pid and m_msg):
  3268. t = FTraceLine(m_time, m_msg, m_param3)
  3269. pid = int(m_pid)
  3270. else:
  3271. continue
  3272. # the line should be a call, return, or event
  3273. if(not t.fcall and not t.freturn and not t.fevent):
  3274. continue
  3275. # look for the suspend start marker
  3276. if(t.startMarker()):
  3277. data = testrun[testidx].data
  3278. tp.parseStamp(data, sysvals)
  3279. data.setStart(t.time, t.name)
  3280. continue
  3281. if(not data):
  3282. continue
  3283. # find the end of resume
  3284. if(t.endMarker()):
  3285. data.setEnd(t.time, t.name)
  3286. testidx += 1
  3287. if(testidx >= testcnt):
  3288. break
  3289. continue
  3290. # trace event processing
  3291. if(t.fevent):
  3292. continue
  3293. # call/return processing
  3294. elif sysvals.usecallgraph:
  3295. # create a callgraph object for the data
  3296. if(pid not in testrun[testidx].ftemp):
  3297. testrun[testidx].ftemp[pid] = []
  3298. testrun[testidx].ftemp[pid].append(FTraceCallGraph(pid, sysvals))
  3299. # when the call is finished, see which device matches it
  3300. cg = testrun[testidx].ftemp[pid][-1]
  3301. res = cg.addLine(t)
  3302. if(res != 0):
  3303. testrun[testidx].ftemp[pid].append(FTraceCallGraph(pid, sysvals))
  3304. if(res == -1):
  3305. testrun[testidx].ftemp[pid][-1].addLine(t)
  3306. tf.close()
  3307. for test in testrun:
  3308. # add the callgraph data to the device hierarchy
  3309. for pid in test.ftemp:
  3310. for cg in test.ftemp[pid]:
  3311. if len(cg.list) < 1 or cg.invalid or (cg.end - cg.start == 0):
  3312. continue
  3313. if(not cg.postProcess()):
  3314. id = 'task %s cpu %s' % (pid, m.group('cpu'))
  3315. sysvals.vprint('Sanity check failed for '+\
  3316. id+', ignoring this callback')
  3317. continue
  3318. callstart = cg.start
  3319. callend = cg.end
  3320. for p in test.data.sortedPhases():
  3321. if(test.data.dmesg[p]['start'] <= callstart and
  3322. callstart <= test.data.dmesg[p]['end']):
  3323. list = test.data.dmesg[p]['list']
  3324. for devname in list:
  3325. dev = list[devname]
  3326. if(pid == dev['pid'] and
  3327. callstart <= dev['start'] and
  3328. callend >= dev['end']):
  3329. dev['ftrace'] = cg
  3330. break
  3331. # Function: loadTraceLog
  3332. # Description:
  3333. # load the ftrace file into memory and fix up any ordering issues
  3334. # Output:
  3335. # TestProps instance and an array of lines in proper order
  3336. def loadTraceLog():
  3337. tp, data, lines, trace = TestProps(), dict(), [], []
  3338. tf = sysvals.openlog(sysvals.ftracefile, 'r')
  3339. for line in tf:
  3340. # remove any latent carriage returns
  3341. line = line.replace('\r\n', '')
  3342. if tp.stampInfo(line, sysvals):
  3343. continue
  3344. # ignore all other commented lines
  3345. if line[0] == '#':
  3346. continue
  3347. # ftrace line: parse only valid lines
  3348. m = re.match(tp.ftrace_line_fmt, line)
  3349. if(not m):
  3350. continue
  3351. dur = m.group('dur') if tp.cgformat else 'traceevent'
  3352. info = (m.group('time'), m.group('proc'), m.group('pid'),
  3353. m.group('msg'), dur)
  3354. # group the data by timestamp
  3355. t = float(info[0])
  3356. if t in data:
  3357. data[t].append(info)
  3358. else:
  3359. data[t] = [info]
  3360. # we only care about trace event ordering
  3361. if (info[3].startswith('suspend_resume:') or \
  3362. info[3].startswith('tracing_mark_write:')) and t not in trace:
  3363. trace.append(t)
  3364. tf.close()
  3365. for t in sorted(data):
  3366. first, last, blk = [], [], data[t]
  3367. if len(blk) > 1 and t in trace:
  3368. # move certain lines to the start or end of a timestamp block
  3369. for i in range(len(blk)):
  3370. if 'SUSPEND START' in blk[i][3]:
  3371. first.append(i)
  3372. elif re.match(r'.* timekeeping_freeze.*begin', blk[i][3]):
  3373. last.append(i)
  3374. elif re.match(r'.* timekeeping_freeze.*end', blk[i][3]):
  3375. first.append(i)
  3376. elif 'RESUME COMPLETE' in blk[i][3]:
  3377. last.append(i)
  3378. if len(first) == 1 and len(last) == 0:
  3379. blk.insert(0, blk.pop(first[0]))
  3380. elif len(last) == 1 and len(first) == 0:
  3381. blk.append(blk.pop(last[0]))
  3382. for info in blk:
  3383. lines.append(info)
  3384. return (tp, lines)
  3385. # Function: parseTraceLog
  3386. # Description:
  3387. # Analyze an ftrace log output file generated from this app during
  3388. # the execution phase. Used when the ftrace log is the primary data source
  3389. # and includes the suspend_resume and device_pm_callback trace events
  3390. # The ftrace filename is taken from sysvals
  3391. # Output:
  3392. # An array of Data objects
  3393. def parseTraceLog(live=False):
  3394. sysvals.vprint('Analyzing the ftrace data (%s)...' % \
  3395. os.path.basename(sysvals.ftracefile))
  3396. if(os.path.exists(sysvals.ftracefile) == False):
  3397. doError('%s does not exist' % sysvals.ftracefile)
  3398. if not live:
  3399. sysvals.setupAllKprobes()
  3400. ksuscalls = ['ksys_sync', 'pm_prepare_console']
  3401. krescalls = ['pm_restore_console']
  3402. tracewatch = ['irq_wakeup']
  3403. if sysvals.usekprobes:
  3404. tracewatch += ['sync_filesystems', 'freeze_processes', 'syscore_suspend',
  3405. 'syscore_resume', 'resume_console', 'thaw_processes', 'CPU_ON',
  3406. 'CPU_OFF', 'acpi_suspend']
  3407. # extract the callgraph and traceevent data
  3408. s2idle_enter = hwsus = False
  3409. testruns, testdata = [], []
  3410. testrun, data, limbo = 0, 0, True
  3411. phase = 'suspend_prepare'
  3412. tp, tf = loadTraceLog()
  3413. for m_time, m_proc, m_pid, m_msg, m_param3 in tf:
  3414. # gather the basic message data from the line
  3415. if(m_time and m_pid and m_msg):
  3416. t = FTraceLine(m_time, m_msg, m_param3)
  3417. pid = int(m_pid)
  3418. else:
  3419. continue
  3420. # the line should be a call, return, or event
  3421. if(not t.fcall and not t.freturn and not t.fevent):
  3422. continue
  3423. # find the start of suspend
  3424. if(t.startMarker()):
  3425. data, limbo = Data(len(testdata)), False
  3426. testdata.append(data)
  3427. testrun = TestRun(data)
  3428. testruns.append(testrun)
  3429. tp.parseStamp(data, sysvals)
  3430. data.setStart(t.time, t.name)
  3431. data.first_suspend_prepare = True
  3432. phase = data.setPhase('suspend_prepare', t.time, True)
  3433. continue
  3434. if(not data or limbo):
  3435. continue
  3436. # process cpu exec line
  3437. if t.type == 'tracing_mark_write':
  3438. if t.name == 'CMD COMPLETE' and data.tKernRes == 0:
  3439. data.tKernRes = t.time
  3440. m = re.match(tp.procexecfmt, t.name)
  3441. if(m):
  3442. parts, msg = 1, m.group('ps')
  3443. m = re.match(tp.procmultifmt, msg)
  3444. if(m):
  3445. parts, msg = int(m.group('n')), m.group('ps')
  3446. if tp.multiproccnt == 0:
  3447. tp.multiproctime = t.time
  3448. tp.multiproclist = dict()
  3449. proclist = tp.multiproclist
  3450. tp.multiproccnt += 1
  3451. else:
  3452. proclist = dict()
  3453. tp.multiproccnt = 0
  3454. for ps in msg.split(','):
  3455. val = ps.split()
  3456. if not val or len(val) != 2:
  3457. continue
  3458. name = val[0].replace('--', '-')
  3459. proclist[name] = int(val[1])
  3460. if parts == 1:
  3461. data.pstl[t.time] = proclist
  3462. elif parts == tp.multiproccnt:
  3463. data.pstl[tp.multiproctime] = proclist
  3464. tp.multiproccnt = 0
  3465. continue
  3466. # find the end of resume
  3467. if(t.endMarker()):
  3468. if data.tKernRes == 0:
  3469. data.tKernRes = t.time
  3470. data.handleEndMarker(t.time, t.name)
  3471. if(not sysvals.usetracemarkers):
  3472. # no trace markers? then quit and be sure to finish recording
  3473. # the event we used to trigger resume end
  3474. if('thaw_processes' in testrun.ttemp and len(testrun.ttemp['thaw_processes']) > 0):
  3475. # if an entry exists, assume this is its end
  3476. testrun.ttemp['thaw_processes'][-1]['end'] = t.time
  3477. limbo = True
  3478. continue
  3479. # trace event processing
  3480. if(t.fevent):
  3481. if(t.type == 'suspend_resume'):
  3482. # suspend_resume trace events have two types, begin and end
  3483. if(re.match(r'(?P<name>.*) begin$', t.name)):
  3484. isbegin = True
  3485. elif(re.match(r'(?P<name>.*) end$', t.name)):
  3486. isbegin = False
  3487. else:
  3488. continue
  3489. if '[' in t.name:
  3490. m = re.match(r'(?P<name>.*)\[.*', t.name)
  3491. else:
  3492. m = re.match(r'(?P<name>.*) .*', t.name)
  3493. name = m.group('name')
  3494. # ignore these events
  3495. if(name.split('[')[0] in tracewatch):
  3496. continue
  3497. # -- phase changes --
  3498. # start of kernel suspend
  3499. if(re.match(r'suspend_enter\[.*', t.name)):
  3500. if(isbegin and data.tKernSus == 0):
  3501. data.tKernSus = t.time
  3502. continue
  3503. # suspend_prepare start
  3504. elif(re.match(r'dpm_prepare\[.*', t.name)):
  3505. if isbegin and data.first_suspend_prepare:
  3506. data.first_suspend_prepare = False
  3507. if data.tKernSus == 0:
  3508. data.tKernSus = t.time
  3509. continue
  3510. phase = data.setPhase('suspend_prepare', t.time, isbegin)
  3511. continue
  3512. # suspend start
  3513. elif(re.match(r'dpm_suspend\[.*', t.name)):
  3514. phase = data.setPhase('suspend', t.time, isbegin)
  3515. continue
  3516. # suspend_late start
  3517. elif(re.match(r'dpm_suspend_late\[.*', t.name)):
  3518. phase = data.setPhase('suspend_late', t.time, isbegin)
  3519. continue
  3520. # suspend_noirq start
  3521. elif(re.match(r'dpm_suspend_noirq\[.*', t.name)):
  3522. phase = data.setPhase('suspend_noirq', t.time, isbegin)
  3523. continue
  3524. # suspend_machine/resume_machine
  3525. elif(re.match(tp.machinesuspend, t.name)):
  3526. lp = data.lastPhase()
  3527. if(isbegin):
  3528. hwsus = True
  3529. if lp.startswith('resume_machine'):
  3530. # trim out s2idle loops, track time trying to freeze
  3531. llp = data.lastPhase(2)
  3532. if llp.startswith('suspend_machine'):
  3533. if 'waking' not in data.dmesg[llp]:
  3534. data.dmesg[llp]['waking'] = [0, 0.0]
  3535. data.dmesg[llp]['waking'][0] += 1
  3536. data.dmesg[llp]['waking'][1] += \
  3537. t.time - data.dmesg[lp]['start']
  3538. data.currphase = ''
  3539. del data.dmesg[lp]
  3540. continue
  3541. phase = data.setPhase('suspend_machine', data.dmesg[lp]['end'], True)
  3542. data.setPhase(phase, t.time, False)
  3543. if data.tSuspended == 0:
  3544. data.tSuspended = t.time
  3545. else:
  3546. if lp.startswith('resume_machine'):
  3547. data.dmesg[lp]['end'] = t.time
  3548. continue
  3549. phase = data.setPhase('resume_machine', t.time, True)
  3550. if(sysvals.suspendmode in ['mem', 'disk']):
  3551. susp = phase.replace('resume', 'suspend')
  3552. if susp in data.dmesg:
  3553. data.dmesg[susp]['end'] = t.time
  3554. data.tSuspended = t.time
  3555. data.tResumed = t.time
  3556. continue
  3557. # resume_noirq start
  3558. elif(re.match(r'dpm_resume_noirq\[.*', t.name)):
  3559. phase = data.setPhase('resume_noirq', t.time, isbegin)
  3560. continue
  3561. # resume_early start
  3562. elif(re.match(r'dpm_resume_early\[.*', t.name)):
  3563. phase = data.setPhase('resume_early', t.time, isbegin)
  3564. continue
  3565. # resume start
  3566. elif(re.match(r'dpm_resume\[.*', t.name)):
  3567. phase = data.setPhase('resume', t.time, isbegin)
  3568. continue
  3569. # resume complete start
  3570. elif(re.match(r'dpm_complete\[.*', t.name)):
  3571. phase = data.setPhase('resume_complete', t.time, isbegin)
  3572. continue
  3573. # skip trace events inside devices calls
  3574. if(not data.isTraceEventOutsideDeviceCalls(pid, t.time)):
  3575. continue
  3576. # global events (outside device calls) are graphed
  3577. if(name not in testrun.ttemp):
  3578. testrun.ttemp[name] = []
  3579. # special handling for s2idle_enter
  3580. if name == 'machine_suspend':
  3581. if hwsus:
  3582. s2idle_enter = hwsus = False
  3583. elif s2idle_enter and not isbegin:
  3584. if(len(testrun.ttemp[name]) > 0):
  3585. testrun.ttemp[name][-1]['end'] = t.time
  3586. testrun.ttemp[name][-1]['loop'] += 1
  3587. elif not s2idle_enter and isbegin:
  3588. s2idle_enter = True
  3589. testrun.ttemp[name].append({'begin': t.time,
  3590. 'end': t.time, 'pid': pid, 'loop': 0})
  3591. continue
  3592. if(isbegin):
  3593. # create a new list entry
  3594. testrun.ttemp[name].append(\
  3595. {'begin': t.time, 'end': t.time, 'pid': pid})
  3596. else:
  3597. if(len(testrun.ttemp[name]) > 0):
  3598. # if an entry exists, assume this is its end
  3599. testrun.ttemp[name][-1]['end'] = t.time
  3600. # device callback start
  3601. elif(t.type == 'device_pm_callback_start'):
  3602. if phase not in data.dmesg:
  3603. continue
  3604. m = re.match(r'(?P<drv>.*) (?P<d>.*), parent: *(?P<p>.*), .*',\
  3605. t.name);
  3606. if(not m):
  3607. continue
  3608. drv = m.group('drv')
  3609. n = m.group('d')
  3610. p = m.group('p')
  3611. if(n and p):
  3612. data.newAction(phase, n, pid, p, t.time, -1, drv)
  3613. if pid not in data.devpids:
  3614. data.devpids.append(pid)
  3615. # device callback finish
  3616. elif(t.type == 'device_pm_callback_end'):
  3617. if phase not in data.dmesg:
  3618. continue
  3619. m = re.match(r'(?P<drv>.*) (?P<d>.*), err.*', t.name);
  3620. if(not m):
  3621. continue
  3622. n = m.group('d')
  3623. dev = data.findDevice(phase, n)
  3624. if dev:
  3625. dev['length'] = t.time - dev['start']
  3626. dev['end'] = t.time
  3627. # kprobe event processing
  3628. elif(t.fkprobe):
  3629. kprobename = t.type
  3630. kprobedata = t.name
  3631. key = (kprobename, pid)
  3632. # displayname is generated from kprobe data
  3633. displayname = ''
  3634. if(t.fcall):
  3635. displayname = sysvals.kprobeDisplayName(kprobename, kprobedata)
  3636. if not displayname:
  3637. continue
  3638. if(key not in tp.ktemp):
  3639. tp.ktemp[key] = []
  3640. tp.ktemp[key].append({
  3641. 'pid': pid,
  3642. 'begin': t.time,
  3643. 'end': -1,
  3644. 'name': displayname,
  3645. 'cdata': kprobedata,
  3646. 'proc': m_proc,
  3647. })
  3648. # start of kernel resume
  3649. if(data.tKernSus == 0 and phase == 'suspend_prepare' \
  3650. and kprobename in ksuscalls):
  3651. data.tKernSus = t.time
  3652. elif(t.freturn):
  3653. if(key not in tp.ktemp) or len(tp.ktemp[key]) < 1:
  3654. continue
  3655. e = next((x for x in reversed(tp.ktemp[key]) if x['end'] < 0), 0)
  3656. if not e:
  3657. continue
  3658. if (t.time - e['begin']) * 1000 < sysvals.mindevlen:
  3659. tp.ktemp[key].pop()
  3660. continue
  3661. e['end'] = t.time
  3662. e['rdata'] = kprobedata
  3663. # end of kernel resume
  3664. if(phase != 'suspend_prepare' and kprobename in krescalls):
  3665. if phase in data.dmesg:
  3666. data.dmesg[phase]['end'] = t.time
  3667. data.tKernRes = t.time
  3668. # callgraph processing
  3669. elif sysvals.usecallgraph:
  3670. # create a callgraph object for the data
  3671. key = (m_proc, pid)
  3672. if(key not in testrun.ftemp):
  3673. testrun.ftemp[key] = []
  3674. testrun.ftemp[key].append(FTraceCallGraph(pid, sysvals))
  3675. # when the call is finished, see which device matches it
  3676. cg = testrun.ftemp[key][-1]
  3677. res = cg.addLine(t)
  3678. if(res != 0):
  3679. testrun.ftemp[key].append(FTraceCallGraph(pid, sysvals))
  3680. if(res == -1):
  3681. testrun.ftemp[key][-1].addLine(t)
  3682. if len(testdata) < 1:
  3683. sysvals.vprint('WARNING: ftrace start marker is missing')
  3684. if data and not data.devicegroups:
  3685. sysvals.vprint('WARNING: ftrace end marker is missing')
  3686. data.handleEndMarker(t.time, t.name)
  3687. if sysvals.suspendmode == 'command':
  3688. for test in testruns:
  3689. for p in test.data.sortedPhases():
  3690. if p == 'suspend_prepare':
  3691. test.data.dmesg[p]['start'] = test.data.start
  3692. test.data.dmesg[p]['end'] = test.data.end
  3693. else:
  3694. test.data.dmesg[p]['start'] = test.data.end
  3695. test.data.dmesg[p]['end'] = test.data.end
  3696. test.data.tSuspended = test.data.end
  3697. test.data.tResumed = test.data.end
  3698. test.data.fwValid = False
  3699. # dev source and procmon events can be unreadable with mixed phase height
  3700. if sysvals.usedevsrc or sysvals.useprocmon:
  3701. sysvals.mixedphaseheight = False
  3702. # expand phase boundaries so there are no gaps
  3703. for data in testdata:
  3704. lp = data.sortedPhases()[0]
  3705. for p in data.sortedPhases():
  3706. if(p != lp and not ('machine' in p and 'machine' in lp)):
  3707. data.dmesg[lp]['end'] = data.dmesg[p]['start']
  3708. lp = p
  3709. for i in range(len(testruns)):
  3710. test = testruns[i]
  3711. data = test.data
  3712. # find the total time range for this test (begin, end)
  3713. tlb, tle = data.start, data.end
  3714. if i < len(testruns) - 1:
  3715. tle = testruns[i+1].data.start
  3716. # add the process usage data to the timeline
  3717. if sysvals.useprocmon:
  3718. data.createProcessUsageEvents()
  3719. # add the traceevent data to the device hierarchy
  3720. if(sysvals.usetraceevents):
  3721. # add actual trace funcs
  3722. for name in sorted(test.ttemp):
  3723. for event in test.ttemp[name]:
  3724. if event['end'] - event['begin'] <= 0:
  3725. continue
  3726. title = name
  3727. if name == 'machine_suspend' and 'loop' in event:
  3728. title = 's2idle_enter_%dx' % event['loop']
  3729. data.newActionGlobal(title, event['begin'], event['end'], event['pid'])
  3730. # add the kprobe based virtual tracefuncs as actual devices
  3731. for key in sorted(tp.ktemp):
  3732. name, pid = key
  3733. if name not in sysvals.tracefuncs:
  3734. continue
  3735. if pid not in data.devpids:
  3736. data.devpids.append(pid)
  3737. for e in tp.ktemp[key]:
  3738. kb, ke = e['begin'], e['end']
  3739. if ke - kb < 0.000001 or tlb > kb or tle <= kb:
  3740. continue
  3741. color = sysvals.kprobeColor(name)
  3742. data.newActionGlobal(e['name'], kb, ke, pid, color)
  3743. # add config base kprobes and dev kprobes
  3744. if sysvals.usedevsrc:
  3745. for key in sorted(tp.ktemp):
  3746. name, pid = key
  3747. if name in sysvals.tracefuncs or name not in sysvals.dev_tracefuncs:
  3748. continue
  3749. for e in tp.ktemp[key]:
  3750. kb, ke = e['begin'], e['end']
  3751. if ke - kb < 0.000001 or tlb > kb or tle <= kb:
  3752. continue
  3753. data.addDeviceFunctionCall(e['name'], name, e['proc'], pid, kb,
  3754. ke, e['cdata'], e['rdata'])
  3755. if sysvals.usecallgraph:
  3756. # add the callgraph data to the device hierarchy
  3757. sortlist = dict()
  3758. for key in sorted(test.ftemp):
  3759. proc, pid = key
  3760. for cg in test.ftemp[key]:
  3761. if len(cg.list) < 1 or cg.invalid or (cg.end - cg.start == 0):
  3762. continue
  3763. if(not cg.postProcess()):
  3764. id = 'task %s' % (pid)
  3765. sysvals.vprint('Sanity check failed for '+\
  3766. id+', ignoring this callback')
  3767. continue
  3768. # match cg data to devices
  3769. devname = ''
  3770. if sysvals.suspendmode != 'command':
  3771. devname = cg.deviceMatch(pid, data)
  3772. if not devname:
  3773. sortkey = '%f%f%d' % (cg.start, cg.end, pid)
  3774. sortlist[sortkey] = cg
  3775. elif len(cg.list) > 1000000 and cg.name != sysvals.ftopfunc:
  3776. sysvals.vprint('WARNING: the callgraph for %s is massive (%d lines)' %\
  3777. (devname, len(cg.list)))
  3778. # create blocks for orphan cg data
  3779. for sortkey in sorted(sortlist):
  3780. cg = sortlist[sortkey]
  3781. name = cg.name
  3782. if sysvals.isCallgraphFunc(name):
  3783. sysvals.vprint('Callgraph found for task %d: %.3fms, %s' % (cg.pid, (cg.end - cg.start)*1000, name))
  3784. cg.newActionFromFunction(data)
  3785. if sysvals.suspendmode == 'command':
  3786. return (testdata, '')
  3787. # fill in any missing phases
  3788. error = []
  3789. for data in testdata:
  3790. tn = '' if len(testdata) == 1 else ('%d' % (data.testnumber + 1))
  3791. terr = ''
  3792. phasedef = data.phasedef
  3793. lp = 'suspend_prepare'
  3794. for p in sorted(phasedef, key=lambda k:phasedef[k]['order']):
  3795. if p not in data.dmesg:
  3796. if not terr:
  3797. ph = p if 'machine' in p else lp
  3798. if p == 'suspend_machine':
  3799. sm = sysvals.suspendmode
  3800. if sm in suspendmodename:
  3801. sm = suspendmodename[sm]
  3802. terr = 'test%s did not enter %s power mode' % (tn, sm)
  3803. else:
  3804. terr = '%s%s failed in %s phase' % (sysvals.suspendmode, tn, ph)
  3805. pprint('TEST%s FAILED: %s' % (tn, terr))
  3806. error.append(terr)
  3807. if data.tSuspended == 0:
  3808. data.tSuspended = data.dmesg[lp]['end']
  3809. if data.tResumed == 0:
  3810. data.tResumed = data.dmesg[lp]['end']
  3811. data.fwValid = False
  3812. sysvals.vprint('WARNING: phase "%s" is missing!' % p)
  3813. lp = p
  3814. if not terr and 'dev' in data.wifi and data.wifi['stat'] == 'timeout':
  3815. terr = '%s%s failed in wifi_resume <i>(%s %.0fs timeout)</i>' % \
  3816. (sysvals.suspendmode, tn, data.wifi['dev'], data.wifi['time'])
  3817. error.append(terr)
  3818. if not terr and data.enterfail:
  3819. pprint('test%s FAILED: enter %s failed with %s' % (tn, sysvals.suspendmode, data.enterfail))
  3820. terr = 'test%s failed to enter %s mode' % (tn, sysvals.suspendmode)
  3821. error.append(terr)
  3822. if data.tSuspended == 0:
  3823. data.tSuspended = data.tKernRes
  3824. if data.tResumed == 0:
  3825. data.tResumed = data.tSuspended
  3826. if(len(sysvals.devicefilter) > 0):
  3827. data.deviceFilter(sysvals.devicefilter)
  3828. data.fixupInitcallsThatDidntReturn()
  3829. if sysvals.usedevsrc:
  3830. data.optimizeDevSrc()
  3831. # x2: merge any overlapping devices between test runs
  3832. if sysvals.usedevsrc and len(testdata) > 1:
  3833. tc = len(testdata)
  3834. for i in range(tc - 1):
  3835. devlist = testdata[i].overflowDevices()
  3836. for j in range(i + 1, tc):
  3837. testdata[j].mergeOverlapDevices(devlist)
  3838. testdata[0].stitchTouchingThreads(testdata[1:])
  3839. return (testdata, ', '.join(error))
  3840. # Function: loadKernelLog
  3841. # Description:
  3842. # load the dmesg file into memory and fix up any ordering issues
  3843. # Output:
  3844. # An array of empty Data objects with only their dmesgtext attributes set
  3845. def loadKernelLog():
  3846. sysvals.vprint('Analyzing the dmesg data (%s)...' % \
  3847. os.path.basename(sysvals.dmesgfile))
  3848. if(os.path.exists(sysvals.dmesgfile) == False):
  3849. doError('%s does not exist' % sysvals.dmesgfile)
  3850. # there can be multiple test runs in a single file
  3851. tp = TestProps()
  3852. tp.stamp = datetime.now().strftime('# suspend-%m%d%y-%H%M%S localhost mem unknown')
  3853. testruns = []
  3854. data = 0
  3855. lf = sysvals.openlog(sysvals.dmesgfile, 'r')
  3856. for line in lf:
  3857. line = line.replace('\r\n', '')
  3858. idx = line.find('[')
  3859. if idx > 1:
  3860. line = line[idx:]
  3861. if tp.stampInfo(line, sysvals):
  3862. continue
  3863. m = re.match(r'[ \t]*(\[ *)(?P<ktime>[0-9\.]*)(\]) (?P<msg>.*)', line)
  3864. if(not m):
  3865. continue
  3866. msg = m.group("msg")
  3867. if re.match(r'PM: Syncing filesystems.*', msg) or \
  3868. re.match(r'PM: suspend entry.*', msg):
  3869. if(data):
  3870. testruns.append(data)
  3871. data = Data(len(testruns))
  3872. tp.parseStamp(data, sysvals)
  3873. if(not data):
  3874. continue
  3875. m = re.match(r'.* *(?P<k>[0-9]\.[0-9]{2}\.[0-9]-.*) .*', msg)
  3876. if(m):
  3877. sysvals.stamp['kernel'] = m.group('k')
  3878. m = re.match(r'PM: Preparing system for (?P<m>.*) sleep', msg)
  3879. if not m:
  3880. m = re.match(r'PM: Preparing system for sleep \((?P<m>.*)\)', msg)
  3881. if m:
  3882. sysvals.stamp['mode'] = sysvals.suspendmode = m.group('m')
  3883. data.dmesgtext.append(line)
  3884. lf.close()
  3885. if sysvals.suspendmode == 's2idle':
  3886. sysvals.suspendmode = 'freeze'
  3887. elif sysvals.suspendmode == 'deep':
  3888. sysvals.suspendmode = 'mem'
  3889. if data:
  3890. testruns.append(data)
  3891. if len(testruns) < 1:
  3892. doError('dmesg log has no suspend/resume data: %s' \
  3893. % sysvals.dmesgfile)
  3894. # fix lines with same timestamp/function with the call and return swapped
  3895. for data in testruns:
  3896. last = ''
  3897. for line in data.dmesgtext:
  3898. ct, cf, n, p = data.initcall_debug_call(line)
  3899. rt, rf, l = data.initcall_debug_return(last)
  3900. if ct and rt and ct == rt and cf == rf:
  3901. i = data.dmesgtext.index(last)
  3902. j = data.dmesgtext.index(line)
  3903. data.dmesgtext[i] = line
  3904. data.dmesgtext[j] = last
  3905. last = line
  3906. return testruns
  3907. # Function: parseKernelLog
  3908. # Description:
  3909. # Analyse a dmesg log output file generated from this app during
  3910. # the execution phase. Create a set of device structures in memory
  3911. # for subsequent formatting in the html output file
  3912. # This call is only for legacy support on kernels where the ftrace
  3913. # data lacks the suspend_resume or device_pm_callbacks trace events.
  3914. # Arguments:
  3915. # data: an empty Data object (with dmesgtext) obtained from loadKernelLog
  3916. # Output:
  3917. # The filled Data object
  3918. def parseKernelLog(data):
  3919. phase = 'suspend_runtime'
  3920. if(data.fwValid):
  3921. sysvals.vprint('Firmware Suspend = %u ns, Firmware Resume = %u ns' % \
  3922. (data.fwSuspend, data.fwResume))
  3923. # dmesg phase match table
  3924. dm = {
  3925. 'suspend_prepare': ['PM: Syncing filesystems.*', 'PM: suspend entry.*'],
  3926. 'suspend': ['PM: Entering [a-z]* sleep.*', 'Suspending console.*',
  3927. 'PM: Suspending system .*'],
  3928. 'suspend_late': ['PM: suspend of devices complete after.*',
  3929. 'PM: freeze of devices complete after.*'],
  3930. 'suspend_noirq': ['PM: late suspend of devices complete after.*',
  3931. 'PM: late freeze of devices complete after.*'],
  3932. 'suspend_machine': ['PM: suspend-to-idle',
  3933. 'PM: noirq suspend of devices complete after.*',
  3934. 'PM: noirq freeze of devices complete after.*'],
  3935. 'resume_machine': ['[PM: ]*Timekeeping suspended for.*',
  3936. 'ACPI: Low-level resume complete.*',
  3937. 'ACPI: resume from mwait',
  3938. r'Suspended for [0-9\.]* seconds'],
  3939. 'resume_noirq': ['PM: resume from suspend-to-idle',
  3940. 'ACPI: Waking up from system sleep state.*'],
  3941. 'resume_early': ['PM: noirq resume of devices complete after.*',
  3942. 'PM: noirq restore of devices complete after.*'],
  3943. 'resume': ['PM: early resume of devices complete after.*',
  3944. 'PM: early restore of devices complete after.*'],
  3945. 'resume_complete': ['PM: resume of devices complete after.*',
  3946. 'PM: restore of devices complete after.*'],
  3947. 'post_resume': [r'.*Restarting tasks \.\.\..*'],
  3948. }
  3949. # action table (expected events that occur and show up in dmesg)
  3950. at = {
  3951. 'sync_filesystems': {
  3952. 'smsg': '.*[Ff]+ilesystems.*',
  3953. 'emsg': 'PM: Preparing system for[a-z]* sleep.*' },
  3954. 'freeze_user_processes': {
  3955. 'smsg': 'Freezing user space processes.*',
  3956. 'emsg': 'Freezing remaining freezable tasks.*' },
  3957. 'freeze_tasks': {
  3958. 'smsg': 'Freezing remaining freezable tasks.*',
  3959. 'emsg': 'PM: Suspending system.*' },
  3960. 'ACPI prepare': {
  3961. 'smsg': 'ACPI: Preparing to enter system sleep state.*',
  3962. 'emsg': 'PM: Saving platform NVS memory.*' },
  3963. 'PM vns': {
  3964. 'smsg': 'PM: Saving platform NVS memory.*',
  3965. 'emsg': 'Disabling non-boot CPUs .*' },
  3966. }
  3967. t0 = -1.0
  3968. cpu_start = -1.0
  3969. prevktime = -1.0
  3970. actions = dict()
  3971. for line in data.dmesgtext:
  3972. # parse each dmesg line into the time and message
  3973. m = re.match(r'[ \t]*(\[ *)(?P<ktime>[0-9\.]*)(\]) (?P<msg>.*)', line)
  3974. if(m):
  3975. val = m.group('ktime')
  3976. try:
  3977. ktime = float(val)
  3978. except:
  3979. continue
  3980. msg = m.group('msg')
  3981. # initialize data start to first line time
  3982. if t0 < 0:
  3983. data.setStart(ktime)
  3984. t0 = ktime
  3985. else:
  3986. continue
  3987. # check for a phase change line
  3988. phasechange = False
  3989. for p in dm:
  3990. for s in dm[p]:
  3991. if(re.match(s, msg)):
  3992. phasechange, phase = True, p
  3993. dm[p] = [s]
  3994. break
  3995. # hack for determining resume_machine end for freeze
  3996. if(not sysvals.usetraceevents and sysvals.suspendmode == 'freeze' \
  3997. and phase == 'resume_machine' and \
  3998. data.initcall_debug_call(line, True)):
  3999. data.setPhase(phase, ktime, False)
  4000. phase = 'resume_noirq'
  4001. data.setPhase(phase, ktime, True)
  4002. if phasechange:
  4003. if phase == 'suspend_prepare':
  4004. data.setPhase(phase, ktime, True)
  4005. data.setStart(ktime)
  4006. data.tKernSus = ktime
  4007. elif phase == 'suspend':
  4008. lp = data.lastPhase()
  4009. if lp:
  4010. data.setPhase(lp, ktime, False)
  4011. data.setPhase(phase, ktime, True)
  4012. elif phase == 'suspend_late':
  4013. lp = data.lastPhase()
  4014. if lp:
  4015. data.setPhase(lp, ktime, False)
  4016. data.setPhase(phase, ktime, True)
  4017. elif phase == 'suspend_noirq':
  4018. lp = data.lastPhase()
  4019. if lp:
  4020. data.setPhase(lp, ktime, False)
  4021. data.setPhase(phase, ktime, True)
  4022. elif phase == 'suspend_machine':
  4023. lp = data.lastPhase()
  4024. if lp:
  4025. data.setPhase(lp, ktime, False)
  4026. data.setPhase(phase, ktime, True)
  4027. elif phase == 'resume_machine':
  4028. lp = data.lastPhase()
  4029. if(sysvals.suspendmode in ['freeze', 'standby']):
  4030. data.tSuspended = prevktime
  4031. if lp:
  4032. data.setPhase(lp, prevktime, False)
  4033. else:
  4034. data.tSuspended = ktime
  4035. if lp:
  4036. data.setPhase(lp, prevktime, False)
  4037. data.tResumed = ktime
  4038. data.setPhase(phase, ktime, True)
  4039. elif phase == 'resume_noirq':
  4040. lp = data.lastPhase()
  4041. if lp:
  4042. data.setPhase(lp, ktime, False)
  4043. data.setPhase(phase, ktime, True)
  4044. elif phase == 'resume_early':
  4045. lp = data.lastPhase()
  4046. if lp:
  4047. data.setPhase(lp, ktime, False)
  4048. data.setPhase(phase, ktime, True)
  4049. elif phase == 'resume':
  4050. lp = data.lastPhase()
  4051. if lp:
  4052. data.setPhase(lp, ktime, False)
  4053. data.setPhase(phase, ktime, True)
  4054. elif phase == 'resume_complete':
  4055. lp = data.lastPhase()
  4056. if lp:
  4057. data.setPhase(lp, ktime, False)
  4058. data.setPhase(phase, ktime, True)
  4059. elif phase == 'post_resume':
  4060. lp = data.lastPhase()
  4061. if lp:
  4062. data.setPhase(lp, ktime, False)
  4063. data.setEnd(ktime)
  4064. data.tKernRes = ktime
  4065. break
  4066. # -- device callbacks --
  4067. if(phase in data.sortedPhases()):
  4068. # device init call
  4069. t, f, n, p = data.initcall_debug_call(line)
  4070. if t and f and n and p:
  4071. data.newAction(phase, f, int(n), p, ktime, -1, '')
  4072. else:
  4073. # device init return
  4074. t, f, l = data.initcall_debug_return(line)
  4075. if t and f and l:
  4076. list = data.dmesg[phase]['list']
  4077. if(f in list):
  4078. dev = list[f]
  4079. dev['length'] = int(l)
  4080. dev['end'] = ktime
  4081. # if trace events are not available, these are better than nothing
  4082. if(not sysvals.usetraceevents):
  4083. # look for known actions
  4084. for a in sorted(at):
  4085. if(re.match(at[a]['smsg'], msg)):
  4086. if(a not in actions):
  4087. actions[a] = [{'begin': ktime, 'end': ktime}]
  4088. if(re.match(at[a]['emsg'], msg)):
  4089. if(a in actions and actions[a][-1]['begin'] == actions[a][-1]['end']):
  4090. actions[a][-1]['end'] = ktime
  4091. # now look for CPU on/off events
  4092. if(re.match(r'Disabling non-boot CPUs .*', msg)):
  4093. # start of first cpu suspend
  4094. cpu_start = ktime
  4095. elif(re.match(r'Enabling non-boot CPUs .*', msg)):
  4096. # start of first cpu resume
  4097. cpu_start = ktime
  4098. elif(re.match(r'smpboot: CPU (?P<cpu>[0-9]*) is now offline', msg) \
  4099. or re.match(r'psci: CPU(?P<cpu>[0-9]*) killed.*', msg)):
  4100. # end of a cpu suspend, start of the next
  4101. m = re.match(r'smpboot: CPU (?P<cpu>[0-9]*) is now offline', msg)
  4102. if(not m):
  4103. m = re.match(r'psci: CPU(?P<cpu>[0-9]*) killed.*', msg)
  4104. cpu = 'CPU'+m.group('cpu')
  4105. if(cpu not in actions):
  4106. actions[cpu] = []
  4107. actions[cpu].append({'begin': cpu_start, 'end': ktime})
  4108. cpu_start = ktime
  4109. elif(re.match(r'CPU(?P<cpu>[0-9]*) is up', msg)):
  4110. # end of a cpu resume, start of the next
  4111. m = re.match(r'CPU(?P<cpu>[0-9]*) is up', msg)
  4112. cpu = 'CPU'+m.group('cpu')
  4113. if(cpu not in actions):
  4114. actions[cpu] = []
  4115. actions[cpu].append({'begin': cpu_start, 'end': ktime})
  4116. cpu_start = ktime
  4117. prevktime = ktime
  4118. data.initDevicegroups()
  4119. # fill in any missing phases
  4120. phasedef = data.phasedef
  4121. terr, lp = '', 'suspend_prepare'
  4122. if lp not in data.dmesg:
  4123. doError('dmesg log format has changed, could not find start of suspend')
  4124. for p in sorted(phasedef, key=lambda k:phasedef[k]['order']):
  4125. if p not in data.dmesg:
  4126. if not terr:
  4127. pprint('TEST FAILED: %s failed in %s phase' % (sysvals.suspendmode, lp))
  4128. terr = '%s failed in %s phase' % (sysvals.suspendmode, lp)
  4129. if data.tSuspended == 0:
  4130. data.tSuspended = data.dmesg[lp]['end']
  4131. if data.tResumed == 0:
  4132. data.tResumed = data.dmesg[lp]['end']
  4133. sysvals.vprint('WARNING: phase "%s" is missing!' % p)
  4134. lp = p
  4135. lp = data.sortedPhases()[0]
  4136. for p in data.sortedPhases():
  4137. if(p != lp and not ('machine' in p and 'machine' in lp)):
  4138. data.dmesg[lp]['end'] = data.dmesg[p]['start']
  4139. lp = p
  4140. if data.tSuspended == 0:
  4141. data.tSuspended = data.tKernRes
  4142. if data.tResumed == 0:
  4143. data.tResumed = data.tSuspended
  4144. # fill in any actions we've found
  4145. for name in sorted(actions):
  4146. for event in actions[name]:
  4147. data.newActionGlobal(name, event['begin'], event['end'])
  4148. if(len(sysvals.devicefilter) > 0):
  4149. data.deviceFilter(sysvals.devicefilter)
  4150. data.fixupInitcallsThatDidntReturn()
  4151. return True
  4152. def callgraphHTML(sv, hf, num, cg, title, color, devid):
  4153. html_func_top = '<article id="{0}" class="atop" style="background:{1}">\n<input type="checkbox" class="pf" id="f{2}" checked/><label for="f{2}">{3} {4}</label>\n'
  4154. html_func_start = '<article>\n<input type="checkbox" class="pf" id="f{0}" checked/><label for="f{0}">{1} {2}</label>\n'
  4155. html_func_end = '</article>\n'
  4156. html_func_leaf = '<article>{0} {1}</article>\n'
  4157. cgid = devid
  4158. if cg.id:
  4159. cgid += cg.id
  4160. cglen = (cg.end - cg.start) * 1000
  4161. if cglen < sv.mincglen:
  4162. return num
  4163. fmt = '<r>(%.3f ms @ '+sv.timeformat+' to '+sv.timeformat+')</r>'
  4164. flen = fmt % (cglen, cg.start, cg.end)
  4165. hf.write(html_func_top.format(cgid, color, num, title, flen))
  4166. num += 1
  4167. for line in cg.list:
  4168. if(line.length < 0.000000001):
  4169. flen = ''
  4170. else:
  4171. fmt = '<n>(%.3f ms @ '+sv.timeformat+')</n>'
  4172. flen = fmt % (line.length*1000, line.time)
  4173. if line.isLeaf():
  4174. if line.length * 1000 < sv.mincglen:
  4175. continue
  4176. hf.write(html_func_leaf.format(line.name, flen))
  4177. elif line.freturn:
  4178. hf.write(html_func_end)
  4179. else:
  4180. hf.write(html_func_start.format(num, line.name, flen))
  4181. num += 1
  4182. hf.write(html_func_end)
  4183. return num
  4184. def addCallgraphs(sv, hf, data):
  4185. hf.write('<section id="callgraphs" class="callgraph">\n')
  4186. # write out the ftrace data converted to html
  4187. num = 0
  4188. for p in data.sortedPhases():
  4189. if sv.cgphase and p != sv.cgphase:
  4190. continue
  4191. list = data.dmesg[p]['list']
  4192. for d in data.sortedDevices(p):
  4193. if len(sv.cgfilter) > 0 and d not in sv.cgfilter:
  4194. continue
  4195. dev = list[d]
  4196. color = 'white'
  4197. if 'color' in data.dmesg[p]:
  4198. color = data.dmesg[p]['color']
  4199. if 'color' in dev:
  4200. color = dev['color']
  4201. name = d if '[' not in d else d.split('[')[0]
  4202. if(d in sv.devprops):
  4203. name = sv.devprops[d].altName(d)
  4204. if 'drv' in dev and dev['drv']:
  4205. name += ' {%s}' % dev['drv']
  4206. if sv.suspendmode in suspendmodename:
  4207. name += ' '+p
  4208. if('ftrace' in dev):
  4209. cg = dev['ftrace']
  4210. if cg.name == sv.ftopfunc:
  4211. name = 'top level suspend/resume call'
  4212. num = callgraphHTML(sv, hf, num, cg,
  4213. name, color, dev['id'])
  4214. if('ftraces' in dev):
  4215. for cg in dev['ftraces']:
  4216. num = callgraphHTML(sv, hf, num, cg,
  4217. name+' &rarr; '+cg.name, color, dev['id'])
  4218. hf.write('\n\n </section>\n')
  4219. def summaryCSS(title, center=True):
  4220. tdcenter = 'text-align:center;' if center else ''
  4221. out = '<!DOCTYPE html>\n<html>\n<head>\n\
  4222. <meta http-equiv="content-type" content="text/html; charset=UTF-8">\n\
  4223. <title>'+title+'</title>\n\
  4224. <style type=\'text/css\'>\n\
  4225. .stamp {width: 100%;text-align:center;background:#888;line-height:30px;color:white;font: 25px Arial;}\n\
  4226. table {width:100%;border-collapse: collapse;border:1px solid;}\n\
  4227. th {border: 1px solid black;background:#222;color:white;}\n\
  4228. td {font: 14px "Times New Roman";'+tdcenter+'}\n\
  4229. tr.head td {border: 1px solid black;background:#aaa;}\n\
  4230. tr.alt {background-color:#ddd;}\n\
  4231. tr.notice {color:red;}\n\
  4232. .minval {background-color:#BBFFBB;}\n\
  4233. .medval {background-color:#BBBBFF;}\n\
  4234. .maxval {background-color:#FFBBBB;}\n\
  4235. .head a {color:#000;text-decoration: none;}\n\
  4236. </style>\n</head>\n<body>\n'
  4237. return out
  4238. # Function: createHTMLSummarySimple
  4239. # Description:
  4240. # Create summary html file for a series of tests
  4241. # Arguments:
  4242. # testruns: array of Data objects from parseTraceLog
  4243. def createHTMLSummarySimple(testruns, htmlfile, title):
  4244. # write the html header first (html head, css code, up to body start)
  4245. html = summaryCSS('Summary - SleepGraph')
  4246. # extract the test data into list
  4247. list = dict()
  4248. tAvg, tMin, tMax, tMed = [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [dict(), dict()]
  4249. iMin, iMed, iMax = [0, 0], [0, 0], [0, 0]
  4250. num = 0
  4251. useturbo = usewifi = False
  4252. lastmode = ''
  4253. cnt = dict()
  4254. for data in sorted(testruns, key=lambda v:(v['mode'], v['host'], v['kernel'], v['time'])):
  4255. mode = data['mode']
  4256. if mode not in list:
  4257. list[mode] = {'data': [], 'avg': [0,0], 'min': [0,0], 'max': [0,0], 'med': [0,0]}
  4258. if lastmode and lastmode != mode and num > 0:
  4259. for i in range(2):
  4260. s = sorted(tMed[i])
  4261. list[lastmode]['med'][i] = s[int(len(s)//2)]
  4262. iMed[i] = tMed[i][list[lastmode]['med'][i]]
  4263. list[lastmode]['avg'] = [tAvg[0] / num, tAvg[1] / num]
  4264. list[lastmode]['min'] = tMin
  4265. list[lastmode]['max'] = tMax
  4266. list[lastmode]['idx'] = (iMin, iMed, iMax)
  4267. tAvg, tMin, tMax, tMed = [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [dict(), dict()]
  4268. iMin, iMed, iMax = [0, 0], [0, 0], [0, 0]
  4269. num = 0
  4270. pkgpc10 = syslpi = wifi = ''
  4271. if 'pkgpc10' in data and 'syslpi' in data:
  4272. pkgpc10, syslpi, useturbo = data['pkgpc10'], data['syslpi'], True
  4273. if 'wifi' in data:
  4274. wifi, usewifi = data['wifi'], True
  4275. res = data['result']
  4276. tVal = [float(data['suspend']), float(data['resume'])]
  4277. list[mode]['data'].append([data['host'], data['kernel'],
  4278. data['time'], tVal[0], tVal[1], data['url'], res,
  4279. data['issues'], data['sus_worst'], data['sus_worsttime'],
  4280. data['res_worst'], data['res_worsttime'], pkgpc10, syslpi, wifi,
  4281. (data['fullmode'] if 'fullmode' in data else mode)])
  4282. idx = len(list[mode]['data']) - 1
  4283. if res.startswith('fail in'):
  4284. res = 'fail'
  4285. if res not in cnt:
  4286. cnt[res] = 1
  4287. else:
  4288. cnt[res] += 1
  4289. if res == 'pass':
  4290. for i in range(2):
  4291. tMed[i][tVal[i]] = idx
  4292. tAvg[i] += tVal[i]
  4293. if tMin[i] == 0 or tVal[i] < tMin[i]:
  4294. iMin[i] = idx
  4295. tMin[i] = tVal[i]
  4296. if tMax[i] == 0 or tVal[i] > tMax[i]:
  4297. iMax[i] = idx
  4298. tMax[i] = tVal[i]
  4299. num += 1
  4300. lastmode = mode
  4301. if lastmode and num > 0:
  4302. for i in range(2):
  4303. s = sorted(tMed[i])
  4304. list[lastmode]['med'][i] = s[int(len(s)//2)]
  4305. iMed[i] = tMed[i][list[lastmode]['med'][i]]
  4306. list[lastmode]['avg'] = [tAvg[0] / num, tAvg[1] / num]
  4307. list[lastmode]['min'] = tMin
  4308. list[lastmode]['max'] = tMax
  4309. list[lastmode]['idx'] = (iMin, iMed, iMax)
  4310. # group test header
  4311. desc = []
  4312. for ilk in sorted(cnt, reverse=True):
  4313. if cnt[ilk] > 0:
  4314. desc.append('%d %s' % (cnt[ilk], ilk))
  4315. html += '<div class="stamp">%s (%d tests: %s)</div>\n' % (title, len(testruns), ', '.join(desc))
  4316. th = '\t<th>{0}</th>\n'
  4317. td = '\t<td>{0}</td>\n'
  4318. tdh = '\t<td{1}>{0}</td>\n'
  4319. tdlink = '\t<td><a href="{0}">html</a></td>\n'
  4320. cols = 12
  4321. if useturbo:
  4322. cols += 2
  4323. if usewifi:
  4324. cols += 1
  4325. colspan = '%d' % cols
  4326. # table header
  4327. html += '<table>\n<tr>\n' + th.format('#') +\
  4328. th.format('Mode') + th.format('Host') + th.format('Kernel') +\
  4329. th.format('Test Time') + th.format('Result') + th.format('Issues') +\
  4330. th.format('Suspend') + th.format('Resume') +\
  4331. th.format('Worst Suspend Device') + th.format('SD Time') +\
  4332. th.format('Worst Resume Device') + th.format('RD Time')
  4333. if useturbo:
  4334. html += th.format('PkgPC10') + th.format('SysLPI')
  4335. if usewifi:
  4336. html += th.format('Wifi')
  4337. html += th.format('Detail')+'</tr>\n'
  4338. # export list into html
  4339. head = '<tr class="head"><td>{0}</td><td>{1}</td>'+\
  4340. '<td colspan='+colspan+' class="sus">Suspend Avg={2} '+\
  4341. '<span class=minval><a href="#s{10}min">Min={3}</a></span> '+\
  4342. '<span class=medval><a href="#s{10}med">Med={4}</a></span> '+\
  4343. '<span class=maxval><a href="#s{10}max">Max={5}</a></span> '+\
  4344. 'Resume Avg={6} '+\
  4345. '<span class=minval><a href="#r{10}min">Min={7}</a></span> '+\
  4346. '<span class=medval><a href="#r{10}med">Med={8}</a></span> '+\
  4347. '<span class=maxval><a href="#r{10}max">Max={9}</a></span></td>'+\
  4348. '</tr>\n'
  4349. headnone = '<tr class="head"><td>{0}</td><td>{1}</td><td colspan='+\
  4350. colspan+'></td></tr>\n'
  4351. for mode in sorted(list):
  4352. # header line for each suspend mode
  4353. num = 0
  4354. tAvg, tMin, tMax, tMed = list[mode]['avg'], list[mode]['min'],\
  4355. list[mode]['max'], list[mode]['med']
  4356. count = len(list[mode]['data'])
  4357. if 'idx' in list[mode]:
  4358. iMin, iMed, iMax = list[mode]['idx']
  4359. html += head.format('%d' % count, mode.upper(),
  4360. '%.3f' % tAvg[0], '%.3f' % tMin[0], '%.3f' % tMed[0], '%.3f' % tMax[0],
  4361. '%.3f' % tAvg[1], '%.3f' % tMin[1], '%.3f' % tMed[1], '%.3f' % tMax[1],
  4362. mode.lower()
  4363. )
  4364. else:
  4365. iMin = iMed = iMax = [-1, -1, -1]
  4366. html += headnone.format('%d' % count, mode.upper())
  4367. for d in list[mode]['data']:
  4368. # row classes - alternate row color
  4369. rcls = ['alt'] if num % 2 == 1 else []
  4370. if d[6] != 'pass':
  4371. rcls.append('notice')
  4372. html += '<tr class="'+(' '.join(rcls))+'">\n' if len(rcls) > 0 else '<tr>\n'
  4373. # figure out if the line has sus or res highlighted
  4374. idx = list[mode]['data'].index(d)
  4375. tHigh = ['', '']
  4376. for i in range(2):
  4377. tag = 's%s' % mode if i == 0 else 'r%s' % mode
  4378. if idx == iMin[i]:
  4379. tHigh[i] = ' id="%smin" class=minval title="Minimum"' % tag
  4380. elif idx == iMax[i]:
  4381. tHigh[i] = ' id="%smax" class=maxval title="Maximum"' % tag
  4382. elif idx == iMed[i]:
  4383. tHigh[i] = ' id="%smed" class=medval title="Median"' % tag
  4384. html += td.format("%d" % (list[mode]['data'].index(d) + 1)) # row
  4385. html += td.format(d[15]) # mode
  4386. html += td.format(d[0]) # host
  4387. html += td.format(d[1]) # kernel
  4388. html += td.format(d[2]) # time
  4389. html += td.format(d[6]) # result
  4390. html += td.format(d[7]) # issues
  4391. html += tdh.format('%.3f ms' % d[3], tHigh[0]) if d[3] else td.format('') # suspend
  4392. html += tdh.format('%.3f ms' % d[4], tHigh[1]) if d[4] else td.format('') # resume
  4393. html += td.format(d[8]) # sus_worst
  4394. html += td.format('%.3f ms' % d[9]) if d[9] else td.format('') # sus_worst time
  4395. html += td.format(d[10]) # res_worst
  4396. html += td.format('%.3f ms' % d[11]) if d[11] else td.format('') # res_worst time
  4397. if useturbo:
  4398. html += td.format(d[12]) # pkg_pc10
  4399. html += td.format(d[13]) # syslpi
  4400. if usewifi:
  4401. html += td.format(d[14]) # wifi
  4402. html += tdlink.format(d[5]) if d[5] else td.format('') # url
  4403. html += '</tr>\n'
  4404. num += 1
  4405. # flush the data to file
  4406. hf = open(htmlfile, 'w')
  4407. hf.write(html+'</table>\n</body>\n</html>\n')
  4408. hf.close()
  4409. def createHTMLDeviceSummary(testruns, htmlfile, title):
  4410. html = summaryCSS('Device Summary - SleepGraph', False)
  4411. # create global device list from all tests
  4412. devall = dict()
  4413. for data in testruns:
  4414. host, url, devlist = data['host'], data['url'], data['devlist']
  4415. for type in devlist:
  4416. if type not in devall:
  4417. devall[type] = dict()
  4418. mdevlist, devlist = devall[type], data['devlist'][type]
  4419. for name in devlist:
  4420. length = devlist[name]
  4421. if name not in mdevlist:
  4422. mdevlist[name] = {'name': name, 'host': host,
  4423. 'worst': length, 'total': length, 'count': 1,
  4424. 'url': url}
  4425. else:
  4426. if length > mdevlist[name]['worst']:
  4427. mdevlist[name]['worst'] = length
  4428. mdevlist[name]['url'] = url
  4429. mdevlist[name]['host'] = host
  4430. mdevlist[name]['total'] += length
  4431. mdevlist[name]['count'] += 1
  4432. # generate the html
  4433. th = '\t<th>{0}</th>\n'
  4434. td = '\t<td align=center>{0}</td>\n'
  4435. tdr = '\t<td align=right>{0}</td>\n'
  4436. tdlink = '\t<td align=center><a href="{0}">html</a></td>\n'
  4437. limit = 1
  4438. for type in sorted(devall, reverse=True):
  4439. num = 0
  4440. devlist = devall[type]
  4441. # table header
  4442. html += '<div class="stamp">%s (%s devices > %d ms)</div><table>\n' % \
  4443. (title, type.upper(), limit)
  4444. html += '<tr>\n' + '<th align=right>Device Name</th>' +\
  4445. th.format('Average Time') + th.format('Count') +\
  4446. th.format('Worst Time') + th.format('Host (worst time)') +\
  4447. th.format('Link (worst time)') + '</tr>\n'
  4448. for name in sorted(devlist, key=lambda k:(devlist[k]['worst'], \
  4449. devlist[k]['total'], devlist[k]['name']), reverse=True):
  4450. data = devall[type][name]
  4451. data['average'] = data['total'] / data['count']
  4452. if data['average'] < limit:
  4453. continue
  4454. # row classes - alternate row color
  4455. rcls = ['alt'] if num % 2 == 1 else []
  4456. html += '<tr class="'+(' '.join(rcls))+'">\n' if len(rcls) > 0 else '<tr>\n'
  4457. html += tdr.format(data['name']) # name
  4458. html += td.format('%.3f ms' % data['average']) # average
  4459. html += td.format(data['count']) # count
  4460. html += td.format('%.3f ms' % data['worst']) # worst
  4461. html += td.format(data['host']) # host
  4462. html += tdlink.format(data['url']) # url
  4463. html += '</tr>\n'
  4464. num += 1
  4465. html += '</table>\n'
  4466. # flush the data to file
  4467. hf = open(htmlfile, 'w')
  4468. hf.write(html+'</body>\n</html>\n')
  4469. hf.close()
  4470. return devall
  4471. def createHTMLIssuesSummary(testruns, issues, htmlfile, title, extra=''):
  4472. multihost = len([e for e in issues if len(e['urls']) > 1]) > 0
  4473. html = summaryCSS('Issues Summary - SleepGraph', False)
  4474. total = len(testruns)
  4475. # generate the html
  4476. th = '\t<th>{0}</th>\n'
  4477. td = '\t<td align={0}>{1}</td>\n'
  4478. tdlink = '<a href="{1}">{0}</a>'
  4479. subtitle = '%d issues' % len(issues) if len(issues) > 0 else 'no issues'
  4480. html += '<div class="stamp">%s (%s)</div><table>\n' % (title, subtitle)
  4481. html += '<tr>\n' + th.format('Issue') + th.format('Count')
  4482. if multihost:
  4483. html += th.format('Hosts')
  4484. html += th.format('Tests') + th.format('Fail Rate') +\
  4485. th.format('First Instance') + '</tr>\n'
  4486. num = 0
  4487. for e in sorted(issues, key=lambda v:v['count'], reverse=True):
  4488. testtotal = 0
  4489. links = []
  4490. for host in sorted(e['urls']):
  4491. links.append(tdlink.format(host, e['urls'][host][0]))
  4492. testtotal += len(e['urls'][host])
  4493. rate = '%d/%d (%.2f%%)' % (testtotal, total, 100*float(testtotal)/float(total))
  4494. # row classes - alternate row color
  4495. rcls = ['alt'] if num % 2 == 1 else []
  4496. html += '<tr class="'+(' '.join(rcls))+'">\n' if len(rcls) > 0 else '<tr>\n'
  4497. html += td.format('left', e['line']) # issue
  4498. html += td.format('center', e['count']) # count
  4499. if multihost:
  4500. html += td.format('center', len(e['urls'])) # hosts
  4501. html += td.format('center', testtotal) # test count
  4502. html += td.format('center', rate) # test rate
  4503. html += td.format('center nowrap', '<br>'.join(links)) # links
  4504. html += '</tr>\n'
  4505. num += 1
  4506. # flush the data to file
  4507. hf = open(htmlfile, 'w')
  4508. hf.write(html+'</table>\n'+extra+'</body>\n</html>\n')
  4509. hf.close()
  4510. return issues
  4511. def ordinal(value):
  4512. suffix = 'th'
  4513. if value < 10 or value > 19:
  4514. if value % 10 == 1:
  4515. suffix = 'st'
  4516. elif value % 10 == 2:
  4517. suffix = 'nd'
  4518. elif value % 10 == 3:
  4519. suffix = 'rd'
  4520. return '%d%s' % (value, suffix)
  4521. # Function: createHTML
  4522. # Description:
  4523. # Create the output html file from the resident test data
  4524. # Arguments:
  4525. # testruns: array of Data objects from parseKernelLog or parseTraceLog
  4526. # Output:
  4527. # True if the html file was created, false if it failed
  4528. def createHTML(testruns, testfail):
  4529. if len(testruns) < 1:
  4530. pprint('ERROR: Not enough test data to build a timeline')
  4531. return
  4532. kerror = False
  4533. for data in testruns:
  4534. if data.kerror:
  4535. kerror = True
  4536. if(sysvals.suspendmode in ['freeze', 'standby']):
  4537. data.trimFreezeTime(testruns[-1].tSuspended)
  4538. else:
  4539. data.getMemTime()
  4540. # html function templates
  4541. html_error = '<div id="{1}" title="kernel error/warning" class="err" style="right:{0}%">{2}&rarr;</div>\n'
  4542. html_traceevent = '<div title="{0}" class="traceevent{6}" style="left:{1}%;top:{2}px;height:{3}px;width:{4}%;line-height:{3}px;{7}">{5}</div>\n'
  4543. html_cpuexec = '<div class="jiffie" style="left:{0}%;top:{1}px;height:{2}px;width:{3}%;background:{4};"></div>\n'
  4544. html_timetotal = '<table class="time1">\n<tr>'\
  4545. '<td class="green" title="{3}">{2} Suspend Time: <b>{0} ms</b></td>'\
  4546. '<td class="yellow" title="{4}">{2} Resume Time: <b>{1} ms</b></td>'\
  4547. '</tr>\n</table>\n'
  4548. html_timetotal2 = '<table class="time1">\n<tr>'\
  4549. '<td class="green" title="{4}">{3} Suspend Time: <b>{0} ms</b></td>'\
  4550. '<td class="gray" title="time spent in low-power mode with clock running">'+sysvals.suspendmode+' time: <b>{1} ms</b></td>'\
  4551. '<td class="yellow" title="{5}">{3} Resume Time: <b>{2} ms</b></td>'\
  4552. '</tr>\n</table>\n'
  4553. html_timetotal3 = '<table class="time1">\n<tr>'\
  4554. '<td class="green">Execution Time: <b>{0} ms</b></td>'\
  4555. '<td class="yellow">Command: <b>{1}</b></td>'\
  4556. '</tr>\n</table>\n'
  4557. html_fail = '<table class="testfail"><tr><td>{0}</td></tr></table>\n'
  4558. html_kdesc = '<td class="{3}" title="time spent in kernel execution">{0}Kernel {2}: {1} ms</td>'
  4559. html_fwdesc = '<td class="{3}" title="time spent in firmware">{0}Firmware {2}: {1} ms</td>'
  4560. html_wifdesc = '<td class="yellow" title="time for wifi to reconnect after resume complete ({2})">{0}Wifi Resume: {1}</td>'
  4561. # html format variables
  4562. scaleH = 20
  4563. if kerror:
  4564. scaleH = 40
  4565. # device timeline
  4566. devtl = Timeline(30, scaleH)
  4567. # write the test title and general info header
  4568. devtl.createHeader(sysvals, testruns[0].stamp)
  4569. # Generate the header for this timeline
  4570. for data in testruns:
  4571. tTotal = data.end - data.start
  4572. if(tTotal == 0):
  4573. doError('No timeline data')
  4574. if sysvals.suspendmode == 'command':
  4575. run_time = '%.0f' % (tTotal * 1000)
  4576. if sysvals.testcommand:
  4577. testdesc = sysvals.testcommand
  4578. else:
  4579. testdesc = 'unknown'
  4580. if(len(testruns) > 1):
  4581. testdesc = ordinal(data.testnumber+1)+' '+testdesc
  4582. thtml = html_timetotal3.format(run_time, testdesc)
  4583. devtl.html += thtml
  4584. continue
  4585. # typical full suspend/resume header
  4586. stot, rtot = sktime, rktime = data.getTimeValues()
  4587. ssrc, rsrc, testdesc, testdesc2 = ['kernel'], ['kernel'], 'Kernel', ''
  4588. if data.fwValid:
  4589. stot += (data.fwSuspend/1000000.0)
  4590. rtot += (data.fwResume/1000000.0)
  4591. ssrc.append('firmware')
  4592. rsrc.append('firmware')
  4593. testdesc = 'Total'
  4594. if 'time' in data.wifi and data.wifi['stat'] != 'timeout':
  4595. rtot += data.end - data.tKernRes + (data.wifi['time'] * 1000.0)
  4596. rsrc.append('wifi')
  4597. testdesc = 'Total'
  4598. suspend_time, resume_time = '%.3f' % stot, '%.3f' % rtot
  4599. stitle = 'time from kernel suspend start to %s mode [%s time]' % \
  4600. (sysvals.suspendmode, ' & '.join(ssrc))
  4601. rtitle = 'time from %s mode to kernel resume complete [%s time]' % \
  4602. (sysvals.suspendmode, ' & '.join(rsrc))
  4603. if(len(testruns) > 1):
  4604. testdesc = testdesc2 = ordinal(data.testnumber+1)
  4605. testdesc2 += ' '
  4606. if(len(data.tLow) == 0):
  4607. thtml = html_timetotal.format(suspend_time, \
  4608. resume_time, testdesc, stitle, rtitle)
  4609. else:
  4610. low_time = '+'.join(data.tLow)
  4611. thtml = html_timetotal2.format(suspend_time, low_time, \
  4612. resume_time, testdesc, stitle, rtitle)
  4613. devtl.html += thtml
  4614. if not data.fwValid and 'dev' not in data.wifi:
  4615. continue
  4616. # extra detail when the times come from multiple sources
  4617. thtml = '<table class="time2">\n<tr>'
  4618. thtml += html_kdesc.format(testdesc2, '%.3f'%sktime, 'Suspend', 'green')
  4619. if data.fwValid:
  4620. sftime = '%.3f'%(data.fwSuspend / 1000000.0)
  4621. rftime = '%.3f'%(data.fwResume / 1000000.0)
  4622. thtml += html_fwdesc.format(testdesc2, sftime, 'Suspend', 'green')
  4623. thtml += html_fwdesc.format(testdesc2, rftime, 'Resume', 'yellow')
  4624. thtml += html_kdesc.format(testdesc2, '%.3f'%rktime, 'Resume', 'yellow')
  4625. if 'time' in data.wifi:
  4626. if data.wifi['stat'] != 'timeout':
  4627. wtime = '%.0f ms'%(data.end - data.tKernRes + (data.wifi['time'] * 1000.0))
  4628. else:
  4629. wtime = 'TIMEOUT'
  4630. thtml += html_wifdesc.format(testdesc2, wtime, data.wifi['dev'])
  4631. thtml += '</tr>\n</table>\n'
  4632. devtl.html += thtml
  4633. if testfail:
  4634. devtl.html += html_fail.format(testfail)
  4635. # time scale for potentially multiple datasets
  4636. t0 = testruns[0].start
  4637. tMax = testruns[-1].end
  4638. tTotal = tMax - t0
  4639. # determine the maximum number of rows we need to draw
  4640. fulllist = []
  4641. threadlist = []
  4642. pscnt = 0
  4643. devcnt = 0
  4644. for data in testruns:
  4645. data.selectTimelineDevices('%f', tTotal, sysvals.mindevlen)
  4646. for group in data.devicegroups:
  4647. devlist = []
  4648. for phase in group:
  4649. for devname in sorted(data.tdevlist[phase]):
  4650. d = DevItem(data.testnumber, phase, data.dmesg[phase]['list'][devname])
  4651. devlist.append(d)
  4652. if d.isa('kth'):
  4653. threadlist.append(d)
  4654. else:
  4655. if d.isa('ps'):
  4656. pscnt += 1
  4657. else:
  4658. devcnt += 1
  4659. fulllist.append(d)
  4660. if sysvals.mixedphaseheight:
  4661. devtl.getPhaseRows(devlist)
  4662. if not sysvals.mixedphaseheight:
  4663. if len(threadlist) > 0 and len(fulllist) > 0:
  4664. if pscnt > 0 and devcnt > 0:
  4665. msg = 'user processes & device pm callbacks'
  4666. elif pscnt > 0:
  4667. msg = 'user processes'
  4668. else:
  4669. msg = 'device pm callbacks'
  4670. d = testruns[0].addHorizontalDivider(msg, testruns[-1].end)
  4671. fulllist.insert(0, d)
  4672. devtl.getPhaseRows(fulllist)
  4673. if len(threadlist) > 0:
  4674. d = testruns[0].addHorizontalDivider('asynchronous kernel threads', testruns[-1].end)
  4675. threadlist.insert(0, d)
  4676. devtl.getPhaseRows(threadlist, devtl.rows)
  4677. devtl.calcTotalRows()
  4678. # draw the full timeline
  4679. devtl.createZoomBox(sysvals.suspendmode, len(testruns))
  4680. for data in testruns:
  4681. # draw each test run and block chronologically
  4682. phases = {'suspend':[],'resume':[]}
  4683. for phase in data.sortedPhases():
  4684. if data.dmesg[phase]['start'] >= data.tSuspended:
  4685. phases['resume'].append(phase)
  4686. else:
  4687. phases['suspend'].append(phase)
  4688. # now draw the actual timeline blocks
  4689. for dir in phases:
  4690. # draw suspend and resume blocks separately
  4691. bname = '%s%d' % (dir[0], data.testnumber)
  4692. if dir == 'suspend':
  4693. m0 = data.start
  4694. mMax = data.tSuspended
  4695. left = '%f' % (((m0-t0)*100.0)/tTotal)
  4696. else:
  4697. m0 = data.tSuspended
  4698. mMax = data.end
  4699. # in an x2 run, remove any gap between blocks
  4700. if len(testruns) > 1 and data.testnumber == 0:
  4701. mMax = testruns[1].start
  4702. left = '%f' % ((((m0-t0)*100.0)+sysvals.srgap/2)/tTotal)
  4703. mTotal = mMax - m0
  4704. # if a timeline block is 0 length, skip altogether
  4705. if mTotal == 0:
  4706. continue
  4707. width = '%f' % (((mTotal*100.0)-sysvals.srgap/2)/tTotal)
  4708. devtl.html += devtl.html_tblock.format(bname, left, width, devtl.scaleH)
  4709. for b in phases[dir]:
  4710. # draw the phase color background
  4711. phase = data.dmesg[b]
  4712. length = phase['end']-phase['start']
  4713. left = '%f' % (((phase['start']-m0)*100.0)/mTotal)
  4714. width = '%f' % ((length*100.0)/mTotal)
  4715. devtl.html += devtl.html_phase.format(left, width, \
  4716. '%.3f'%devtl.scaleH, '%.3f'%devtl.bodyH, \
  4717. data.dmesg[b]['color'], '')
  4718. for e in data.errorinfo[dir]:
  4719. # draw red lines for any kernel errors found
  4720. type, t, idx1, idx2 = e
  4721. id = '%d_%d' % (idx1, idx2)
  4722. right = '%f' % (((mMax-t)*100.0)/mTotal)
  4723. devtl.html += html_error.format(right, id, type)
  4724. for b in phases[dir]:
  4725. # draw the devices for this phase
  4726. phaselist = data.dmesg[b]['list']
  4727. for d in sorted(data.tdevlist[b]):
  4728. dname = d if ('[' not in d or 'CPU' in d) else d.split('[')[0]
  4729. name, dev = dname, phaselist[d]
  4730. drv = xtraclass = xtrainfo = xtrastyle = ''
  4731. if 'htmlclass' in dev:
  4732. xtraclass = dev['htmlclass']
  4733. if 'color' in dev:
  4734. xtrastyle = 'background:%s;' % dev['color']
  4735. if(d in sysvals.devprops):
  4736. name = sysvals.devprops[d].altName(d)
  4737. xtraclass = sysvals.devprops[d].xtraClass()
  4738. xtrainfo = sysvals.devprops[d].xtraInfo()
  4739. elif xtraclass == ' kth':
  4740. xtrainfo = ' kernel_thread'
  4741. if('drv' in dev and dev['drv']):
  4742. drv = ' {%s}' % dev['drv']
  4743. rowheight = devtl.phaseRowHeight(data.testnumber, b, dev['row'])
  4744. rowtop = devtl.phaseRowTop(data.testnumber, b, dev['row'])
  4745. top = '%.3f' % (rowtop + devtl.scaleH)
  4746. left = '%f' % (((dev['start']-m0)*100)/mTotal)
  4747. width = '%f' % (((dev['end']-dev['start'])*100)/mTotal)
  4748. length = ' (%0.3f ms) ' % ((dev['end']-dev['start'])*1000)
  4749. title = name+drv+xtrainfo+length
  4750. if sysvals.suspendmode == 'command':
  4751. title += sysvals.testcommand
  4752. elif xtraclass == ' ps':
  4753. if 'suspend' in b:
  4754. title += 'pre_suspend_process'
  4755. else:
  4756. title += 'post_resume_process'
  4757. else:
  4758. title += b
  4759. devtl.html += devtl.html_device.format(dev['id'], \
  4760. title, left, top, '%.3f'%rowheight, width, \
  4761. dname+drv, xtraclass, xtrastyle)
  4762. if('cpuexec' in dev):
  4763. for t in sorted(dev['cpuexec']):
  4764. start, end = t
  4765. height = '%.3f' % (rowheight/3)
  4766. top = '%.3f' % (rowtop + devtl.scaleH + 2*rowheight/3)
  4767. left = '%f' % (((start-m0)*100)/mTotal)
  4768. width = '%f' % ((end-start)*100/mTotal)
  4769. color = 'rgba(255, 0, 0, %f)' % dev['cpuexec'][t]
  4770. devtl.html += \
  4771. html_cpuexec.format(left, top, height, width, color)
  4772. if('src' not in dev):
  4773. continue
  4774. # draw any trace events for this device
  4775. for e in dev['src']:
  4776. if e.length == 0:
  4777. continue
  4778. height = '%.3f' % devtl.rowH
  4779. top = '%.3f' % (rowtop + devtl.scaleH + (e.row*devtl.rowH))
  4780. left = '%f' % (((e.time-m0)*100)/mTotal)
  4781. width = '%f' % (e.length*100/mTotal)
  4782. xtrastyle = ''
  4783. if e.color:
  4784. xtrastyle = 'background:%s;' % e.color
  4785. devtl.html += \
  4786. html_traceevent.format(e.title(), \
  4787. left, top, height, width, e.text(), '', xtrastyle)
  4788. # draw the time scale, try to make the number of labels readable
  4789. devtl.createTimeScale(m0, mMax, tTotal, dir)
  4790. devtl.html += '</div>\n'
  4791. # timeline is finished
  4792. devtl.html += '</div>\n</div>\n'
  4793. # draw a legend which describes the phases by color
  4794. if sysvals.suspendmode != 'command':
  4795. phasedef = testruns[-1].phasedef
  4796. devtl.html += '<div class="legend">\n'
  4797. pdelta = 100.0/len(phasedef.keys())
  4798. pmargin = pdelta / 4.0
  4799. for phase in sorted(phasedef, key=lambda k:phasedef[k]['order']):
  4800. id, p = '', phasedef[phase]
  4801. for word in phase.split('_'):
  4802. id += word[0]
  4803. order = '%.2f' % ((p['order'] * pdelta) + pmargin)
  4804. name = phase.replace('_', ' &nbsp;')
  4805. devtl.html += devtl.html_legend.format(order, p['color'], name, id)
  4806. devtl.html += '</div>\n'
  4807. hf = open(sysvals.htmlfile, 'w')
  4808. addCSS(hf, sysvals, len(testruns), kerror)
  4809. # write the device timeline
  4810. hf.write(devtl.html)
  4811. hf.write('<div id="devicedetailtitle"></div>\n')
  4812. hf.write('<div id="devicedetail" style="display:none;">\n')
  4813. # draw the colored boxes for the device detail section
  4814. for data in testruns:
  4815. hf.write('<div id="devicedetail%d">\n' % data.testnumber)
  4816. pscolor = 'linear-gradient(to top left, #ccc, #eee)'
  4817. hf.write(devtl.html_phaselet.format('pre_suspend_process', \
  4818. '0', '0', pscolor))
  4819. for b in data.sortedPhases():
  4820. phase = data.dmesg[b]
  4821. length = phase['end']-phase['start']
  4822. left = '%.3f' % (((phase['start']-t0)*100.0)/tTotal)
  4823. width = '%.3f' % ((length*100.0)/tTotal)
  4824. hf.write(devtl.html_phaselet.format(b, left, width, \
  4825. data.dmesg[b]['color']))
  4826. hf.write(devtl.html_phaselet.format('post_resume_process', \
  4827. '0', '0', pscolor))
  4828. if sysvals.suspendmode == 'command':
  4829. hf.write(devtl.html_phaselet.format('cmdexec', '0', '0', pscolor))
  4830. hf.write('</div>\n')
  4831. hf.write('</div>\n')
  4832. # write the ftrace data (callgraph)
  4833. if sysvals.cgtest >= 0 and len(testruns) > sysvals.cgtest:
  4834. data = testruns[sysvals.cgtest]
  4835. else:
  4836. data = testruns[-1]
  4837. if sysvals.usecallgraph:
  4838. addCallgraphs(sysvals, hf, data)
  4839. # add the test log as a hidden div
  4840. if sysvals.testlog and sysvals.logmsg:
  4841. hf.write('<div id="testlog" style="display:none;">\n'+sysvals.logmsg+'</div>\n')
  4842. # add the dmesg log as a hidden div
  4843. if sysvals.dmesglog and sysvals.dmesgfile:
  4844. hf.write('<div id="dmesglog" style="display:none;">\n')
  4845. lf = sysvals.openlog(sysvals.dmesgfile, 'r')
  4846. for line in lf:
  4847. line = line.replace('<', '&lt').replace('>', '&gt')
  4848. hf.write(line)
  4849. lf.close()
  4850. hf.write('</div>\n')
  4851. # add the ftrace log as a hidden div
  4852. if sysvals.ftracelog and sysvals.ftracefile:
  4853. hf.write('<div id="ftracelog" style="display:none;">\n')
  4854. lf = sysvals.openlog(sysvals.ftracefile, 'r')
  4855. for line in lf:
  4856. hf.write(line)
  4857. lf.close()
  4858. hf.write('</div>\n')
  4859. # write the footer and close
  4860. addScriptCode(hf, testruns)
  4861. hf.write('</body>\n</html>\n')
  4862. hf.close()
  4863. return True
  4864. def addCSS(hf, sv, testcount=1, kerror=False, extra=''):
  4865. kernel = sv.stamp['kernel']
  4866. host = sv.hostname[0].upper()+sv.hostname[1:]
  4867. mode = sv.suspendmode
  4868. if sv.suspendmode in suspendmodename:
  4869. mode = suspendmodename[sv.suspendmode]
  4870. title = host+' '+mode+' '+kernel
  4871. # various format changes by flags
  4872. cgchk = 'checked'
  4873. cgnchk = 'not(:checked)'
  4874. if sv.cgexp:
  4875. cgchk = 'not(:checked)'
  4876. cgnchk = 'checked'
  4877. hoverZ = 'z-index:8;'
  4878. if sv.usedevsrc:
  4879. hoverZ = ''
  4880. devlistpos = 'absolute'
  4881. if testcount > 1:
  4882. devlistpos = 'relative'
  4883. scaleTH = 20
  4884. if kerror:
  4885. scaleTH = 60
  4886. # write the html header first (html head, css code, up to body start)
  4887. html_header = '<!DOCTYPE html>\n<html>\n<head>\n\
  4888. <meta http-equiv="content-type" content="text/html; charset=UTF-8">\n\
  4889. <title>'+title+'</title>\n\
  4890. <style type=\'text/css\'>\n\
  4891. body {overflow-y:scroll;}\n\
  4892. .stamp {width:100%;text-align:center;background:gray;line-height:30px;color:white;font:25px Arial;}\n\
  4893. .stamp.sysinfo {font:10px Arial;}\n\
  4894. .callgraph {margin-top:30px;box-shadow:5px 5px 20px black;}\n\
  4895. .callgraph article * {padding-left:28px;}\n\
  4896. h1 {color:black;font:bold 30px Times;}\n\
  4897. t0 {color:black;font:bold 30px Times;}\n\
  4898. t1 {color:black;font:30px Times;}\n\
  4899. t2 {color:black;font:25px Times;}\n\
  4900. t3 {color:black;font:20px Times;white-space:nowrap;}\n\
  4901. t4 {color:black;font:bold 30px Times;line-height:60px;white-space:nowrap;}\n\
  4902. cS {font:bold 13px Times;}\n\
  4903. table {width:100%;}\n\
  4904. .gray {background:rgba(80,80,80,0.1);}\n\
  4905. .green {background:rgba(204,255,204,0.4);}\n\
  4906. .purple {background:rgba(128,0,128,0.2);}\n\
  4907. .yellow {background:rgba(255,255,204,0.4);}\n\
  4908. .blue {background:rgba(169,208,245,0.4);}\n\
  4909. .time1 {font:22px Arial;border:1px solid;}\n\
  4910. .time2 {font:15px Arial;border-bottom:1px solid;border-left:1px solid;border-right:1px solid;}\n\
  4911. .testfail {font:bold 22px Arial;color:red;border:1px dashed;}\n\
  4912. td {text-align:center;}\n\
  4913. r {color:#500000;font:15px Tahoma;}\n\
  4914. n {color:#505050;font:15px Tahoma;}\n\
  4915. .tdhl {color:red;}\n\
  4916. .hide {display:none;}\n\
  4917. .pf {display:none;}\n\
  4918. .pf:'+cgchk+' + label {background:url(\'data:image/svg+xml;utf,<?xml version="1.0" standalone="no"?><svg xmlns="http://www.w3.org/2000/svg" height="18" width="18" version="1.1"><circle cx="9" cy="9" r="8" stroke="black" stroke-width="1" fill="white"/><rect x="4" y="8" width="10" height="2" style="fill:black;stroke-width:0"/><rect x="8" y="4" width="2" height="10" style="fill:black;stroke-width:0"/></svg>\') no-repeat left center;}\n\
  4919. .pf:'+cgnchk+' ~ label {background:url(\'data:image/svg+xml;utf,<?xml version="1.0" standalone="no"?><svg xmlns="http://www.w3.org/2000/svg" height="18" width="18" version="1.1"><circle cx="9" cy="9" r="8" stroke="black" stroke-width="1" fill="white"/><rect x="4" y="8" width="10" height="2" style="fill:black;stroke-width:0"/></svg>\') no-repeat left center;}\n\
  4920. .pf:'+cgchk+' ~ *:not(:nth-child(2)) {display:none;}\n\
  4921. .zoombox {position:relative;width:100%;overflow-x:scroll;-webkit-user-select:none;-moz-user-select:none;user-select:none;}\n\
  4922. .timeline {position:relative;font-size:14px;cursor:pointer;width:100%; overflow:hidden;background:linear-gradient(#cccccc, white);}\n\
  4923. .thread {position:absolute;height:0%;overflow:hidden;z-index:7;line-height:30px;font-size:14px;border:1px solid;text-align:center;white-space:nowrap;}\n\
  4924. .thread.ps {border-radius:3px;background:linear-gradient(to top, #ccc, #eee);}\n\
  4925. .thread:hover {background:white;border:1px solid red;'+hoverZ+'}\n\
  4926. .thread.sec,.thread.sec:hover {background:black;border:0;color:white;line-height:15px;font-size:10px;}\n\
  4927. .hover {background:white;border:1px solid red;'+hoverZ+'}\n\
  4928. .hover.sync {background:white;}\n\
  4929. .hover.bg,.hover.kth,.hover.sync,.hover.ps {background:white;}\n\
  4930. .jiffie {position:absolute;pointer-events: none;z-index:8;}\n\
  4931. .traceevent {position:absolute;font-size:10px;z-index:7;overflow:hidden;color:black;text-align:center;white-space:nowrap;border-radius:5px;border:1px solid black;background:linear-gradient(to bottom right,#CCC,#969696);}\n\
  4932. .traceevent:hover {color:white;font-weight:bold;border:1px solid white;}\n\
  4933. .phase {position:absolute;overflow:hidden;border:0px;text-align:center;}\n\
  4934. .phaselet {float:left;overflow:hidden;border:0px;text-align:center;min-height:100px;font-size:24px;}\n\
  4935. .t {position:absolute;line-height:'+('%d'%scaleTH)+'px;pointer-events:none;top:0;height:100%;border-right:1px solid black;z-index:6;}\n\
  4936. .err {position:absolute;top:0%;height:100%;border-right:3px solid red;color:red;font:bold 14px Times;line-height:18px;}\n\
  4937. .legend {position:relative; width:100%; height:40px; text-align:center;margin-bottom:20px}\n\
  4938. .legend .square {position:absolute;cursor:pointer;top:10px; width:0px;height:20px;border:1px solid;padding-left:20px;}\n\
  4939. button {height:40px;width:200px;margin-bottom:20px;margin-top:20px;font-size:24px;}\n\
  4940. .btnfmt {position:relative;float:right;height:25px;width:auto;margin-top:3px;margin-bottom:0;font-size:10px;text-align:center;}\n\
  4941. .devlist {position:'+devlistpos+';width:190px;}\n\
  4942. a:link {color:white;text-decoration:none;}\n\
  4943. a:visited {color:white;}\n\
  4944. a:hover {color:white;}\n\
  4945. a:active {color:white;}\n\
  4946. .version {position:relative;float:left;color:white;font-size:10px;line-height:30px;margin-left:10px;}\n\
  4947. #devicedetail {min-height:100px;box-shadow:5px 5px 20px black;}\n\
  4948. .tblock {position:absolute;height:100%;background:#ddd;}\n\
  4949. .tback {position:absolute;width:100%;background:linear-gradient(#ccc, #ddd);}\n\
  4950. .bg {z-index:1;}\n\
  4951. '+extra+'\
  4952. </style>\n</head>\n<body>\n'
  4953. hf.write(html_header)
  4954. # Function: addScriptCode
  4955. # Description:
  4956. # Adds the javascript code to the output html
  4957. # Arguments:
  4958. # hf: the open html file pointer
  4959. # testruns: array of Data objects from parseKernelLog or parseTraceLog
  4960. def addScriptCode(hf, testruns):
  4961. t0 = testruns[0].start * 1000
  4962. tMax = testruns[-1].end * 1000
  4963. hf.write('<script type="text/javascript">\n');
  4964. # create an array in javascript memory with the device details
  4965. detail = ' var devtable = [];\n'
  4966. for data in testruns:
  4967. topo = data.deviceTopology()
  4968. detail += ' devtable[%d] = "%s";\n' % (data.testnumber, topo)
  4969. detail += ' var bounds = [%f,%f];\n' % (t0, tMax)
  4970. # add the code which will manipulate the data in the browser
  4971. hf.write(detail);
  4972. script_code = r""" var resolution = -1;
  4973. var dragval = [0, 0];
  4974. function redrawTimescale(t0, tMax, tS) {
  4975. var rline = '<div class="t" style="left:0;border-left:1px solid black;border-right:0;">';
  4976. var tTotal = tMax - t0;
  4977. var list = document.getElementsByClassName("tblock");
  4978. for (var i = 0; i < list.length; i++) {
  4979. var timescale = list[i].getElementsByClassName("timescale")[0];
  4980. var m0 = t0 + (tTotal*parseFloat(list[i].style.left)/100);
  4981. var mTotal = tTotal*parseFloat(list[i].style.width)/100;
  4982. var mMax = m0 + mTotal;
  4983. var html = "";
  4984. var divTotal = Math.floor(mTotal/tS) + 1;
  4985. if(divTotal > 1000) continue;
  4986. var divEdge = (mTotal - tS*(divTotal-1))*100/mTotal;
  4987. var pos = 0.0, val = 0.0;
  4988. for (var j = 0; j < divTotal; j++) {
  4989. var htmlline = "";
  4990. var mode = list[i].id[5];
  4991. if(mode == "s") {
  4992. pos = 100 - (((j)*tS*100)/mTotal) - divEdge;
  4993. val = (j-divTotal+1)*tS;
  4994. if(j == divTotal - 1)
  4995. htmlline = '<div class="t" style="right:'+pos+'%"><cS>S&rarr;</cS></div>';
  4996. else
  4997. htmlline = '<div class="t" style="right:'+pos+'%">'+val+'ms</div>';
  4998. } else {
  4999. pos = 100 - (((j)*tS*100)/mTotal);
  5000. val = (j)*tS;
  5001. htmlline = '<div class="t" style="right:'+pos+'%">'+val+'ms</div>';
  5002. if(j == 0)
  5003. if(mode == "r")
  5004. htmlline = rline+"<cS>&larr;R</cS></div>";
  5005. else
  5006. htmlline = rline+"<cS>0ms</div>";
  5007. }
  5008. html += htmlline;
  5009. }
  5010. timescale.innerHTML = html;
  5011. }
  5012. }
  5013. function zoomTimeline() {
  5014. var dmesg = document.getElementById("dmesg");
  5015. var zoombox = document.getElementById("dmesgzoombox");
  5016. var left = zoombox.scrollLeft;
  5017. var val = parseFloat(dmesg.style.width);
  5018. var newval = 100;
  5019. var sh = window.outerWidth / 2;
  5020. if(this.id == "zoomin") {
  5021. newval = val * 1.2;
  5022. if(newval > 910034) newval = 910034;
  5023. dmesg.style.width = newval+"%";
  5024. zoombox.scrollLeft = ((left + sh) * newval / val) - sh;
  5025. } else if (this.id == "zoomout") {
  5026. newval = val / 1.2;
  5027. if(newval < 100) newval = 100;
  5028. dmesg.style.width = newval+"%";
  5029. zoombox.scrollLeft = ((left + sh) * newval / val) - sh;
  5030. } else {
  5031. zoombox.scrollLeft = 0;
  5032. dmesg.style.width = "100%";
  5033. }
  5034. var tS = [10000, 5000, 2000, 1000, 500, 200, 100, 50, 20, 10, 5, 2, 1];
  5035. var t0 = bounds[0];
  5036. var tMax = bounds[1];
  5037. var tTotal = tMax - t0;
  5038. var wTotal = tTotal * 100.0 / newval;
  5039. var idx = 7*window.innerWidth/1100;
  5040. for(var i = 0; (i < tS.length)&&((wTotal / tS[i]) < idx); i++);
  5041. if(i >= tS.length) i = tS.length - 1;
  5042. if(tS[i] == resolution) return;
  5043. resolution = tS[i];
  5044. redrawTimescale(t0, tMax, tS[i]);
  5045. }
  5046. function deviceName(title) {
  5047. var name = title.slice(0, title.indexOf(" ("));
  5048. return name;
  5049. }
  5050. function deviceHover() {
  5051. var name = deviceName(this.title);
  5052. var dmesg = document.getElementById("dmesg");
  5053. var dev = dmesg.getElementsByClassName("thread");
  5054. var cpu = -1;
  5055. if(name.match("CPU_ON\[[0-9]*\]"))
  5056. cpu = parseInt(name.slice(7));
  5057. else if(name.match("CPU_OFF\[[0-9]*\]"))
  5058. cpu = parseInt(name.slice(8));
  5059. for (var i = 0; i < dev.length; i++) {
  5060. dname = deviceName(dev[i].title);
  5061. var cname = dev[i].className.slice(dev[i].className.indexOf("thread"));
  5062. if((cpu >= 0 && dname.match("CPU_O[NF]*\\[*"+cpu+"\\]")) ||
  5063. (name == dname))
  5064. {
  5065. dev[i].className = "hover "+cname;
  5066. } else {
  5067. dev[i].className = cname;
  5068. }
  5069. }
  5070. }
  5071. function deviceUnhover() {
  5072. var dmesg = document.getElementById("dmesg");
  5073. var dev = dmesg.getElementsByClassName("thread");
  5074. for (var i = 0; i < dev.length; i++) {
  5075. dev[i].className = dev[i].className.slice(dev[i].className.indexOf("thread"));
  5076. }
  5077. }
  5078. function deviceTitle(title, total, cpu) {
  5079. var prefix = "Total";
  5080. if(total.length > 3) {
  5081. prefix = "Average";
  5082. total[1] = (total[1]+total[3])/2;
  5083. total[2] = (total[2]+total[4])/2;
  5084. }
  5085. var devtitle = document.getElementById("devicedetailtitle");
  5086. var name = deviceName(title);
  5087. if(cpu >= 0) name = "CPU"+cpu;
  5088. var driver = "";
  5089. var tS = "<t2>(</t2>";
  5090. var tR = "<t2>)</t2>";
  5091. if(total[1] > 0)
  5092. tS = "<t2>("+prefix+" Suspend:</t2><t0> "+total[1].toFixed(3)+" ms</t0> ";
  5093. if(total[2] > 0)
  5094. tR = " <t2>"+prefix+" Resume:</t2><t0> "+total[2].toFixed(3)+" ms<t2>)</t2></t0>";
  5095. var s = title.indexOf("{");
  5096. var e = title.indexOf("}");
  5097. if((s >= 0) && (e >= 0))
  5098. driver = title.slice(s+1, e) + " <t1>@</t1> ";
  5099. if(total[1] > 0 && total[2] > 0)
  5100. devtitle.innerHTML = "<t0>"+driver+name+"</t0> "+tS+tR;
  5101. else
  5102. devtitle.innerHTML = "<t0>"+title+"</t0>";
  5103. return name;
  5104. }
  5105. function deviceDetail() {
  5106. var devinfo = document.getElementById("devicedetail");
  5107. devinfo.style.display = "block";
  5108. var name = deviceName(this.title);
  5109. var cpu = -1;
  5110. if(name.match("CPU_ON\[[0-9]*\]"))
  5111. cpu = parseInt(name.slice(7));
  5112. else if(name.match("CPU_OFF\[[0-9]*\]"))
  5113. cpu = parseInt(name.slice(8));
  5114. var dmesg = document.getElementById("dmesg");
  5115. var dev = dmesg.getElementsByClassName("thread");
  5116. var idlist = [];
  5117. var pdata = [[]];
  5118. if(document.getElementById("devicedetail1"))
  5119. pdata = [[], []];
  5120. var pd = pdata[0];
  5121. var total = [0.0, 0.0, 0.0];
  5122. for (var i = 0; i < dev.length; i++) {
  5123. dname = deviceName(dev[i].title);
  5124. if((cpu >= 0 && dname.match("CPU_O[NF]*\\[*"+cpu+"\\]")) ||
  5125. (name == dname))
  5126. {
  5127. idlist[idlist.length] = dev[i].id;
  5128. var tidx = 1;
  5129. if(dev[i].id[0] == "a") {
  5130. pd = pdata[0];
  5131. } else {
  5132. if(pdata.length == 1) pdata[1] = [];
  5133. if(total.length == 3) total[3]=total[4]=0.0;
  5134. pd = pdata[1];
  5135. tidx = 3;
  5136. }
  5137. var info = dev[i].title.split(" ");
  5138. var pname = info[info.length-1];
  5139. pd[pname] = parseFloat(info[info.length-3].slice(1));
  5140. total[0] += pd[pname];
  5141. if(pname.indexOf("suspend") >= 0)
  5142. total[tidx] += pd[pname];
  5143. else
  5144. total[tidx+1] += pd[pname];
  5145. }
  5146. }
  5147. var devname = deviceTitle(this.title, total, cpu);
  5148. var left = 0.0;
  5149. for (var t = 0; t < pdata.length; t++) {
  5150. pd = pdata[t];
  5151. devinfo = document.getElementById("devicedetail"+t);
  5152. var phases = devinfo.getElementsByClassName("phaselet");
  5153. for (var i = 0; i < phases.length; i++) {
  5154. if(phases[i].id in pd) {
  5155. var w = 100.0*pd[phases[i].id]/total[0];
  5156. var fs = 32;
  5157. if(w < 8) fs = 4*w | 0;
  5158. var fs2 = fs*3/4;
  5159. phases[i].style.width = w+"%";
  5160. phases[i].style.left = left+"%";
  5161. phases[i].title = phases[i].id+" "+pd[phases[i].id]+" ms";
  5162. left += w;
  5163. var time = "<t4 style=\"font-size:"+fs+"px\">"+pd[phases[i].id]+" ms<br></t4>";
  5164. var pname = "<t3 style=\"font-size:"+fs2+"px\">"+phases[i].id.replace(new RegExp("_", "g"), " ")+"</t3>";
  5165. phases[i].innerHTML = time+pname;
  5166. } else {
  5167. phases[i].style.width = "0%";
  5168. phases[i].style.left = left+"%";
  5169. }
  5170. }
  5171. }
  5172. if(typeof devstats !== 'undefined')
  5173. callDetail(this.id, this.title);
  5174. var cglist = document.getElementById("callgraphs");
  5175. if(!cglist) return;
  5176. var cg = cglist.getElementsByClassName("atop");
  5177. if(cg.length < 10) return;
  5178. for (var i = 0; i < cg.length; i++) {
  5179. cgid = cg[i].id.split("x")[0]
  5180. if(idlist.indexOf(cgid) >= 0) {
  5181. cg[i].style.display = "block";
  5182. } else {
  5183. cg[i].style.display = "none";
  5184. }
  5185. }
  5186. }
  5187. function callDetail(devid, devtitle) {
  5188. if(!(devid in devstats) || devstats[devid].length < 1)
  5189. return;
  5190. var list = devstats[devid];
  5191. var tmp = devtitle.split(" ");
  5192. var name = tmp[0], phase = tmp[tmp.length-1];
  5193. var dd = document.getElementById(phase);
  5194. var total = parseFloat(tmp[1].slice(1));
  5195. var mlist = [];
  5196. var maxlen = 0;
  5197. var info = []
  5198. for(var i in list) {
  5199. if(list[i][0] == "@") {
  5200. info = list[i].split("|");
  5201. continue;
  5202. }
  5203. var tmp = list[i].split("|");
  5204. var t = parseFloat(tmp[0]), f = tmp[1], c = parseInt(tmp[2]);
  5205. var p = (t*100.0/total).toFixed(2);
  5206. mlist[mlist.length] = [f, c, t.toFixed(2), p+"%"];
  5207. if(f.length > maxlen)
  5208. maxlen = f.length;
  5209. }
  5210. var pad = 5;
  5211. if(mlist.length == 0) pad = 30;
  5212. var html = '<div style="padding-top:'+pad+'px"><t3> <b>'+name+':</b>';
  5213. if(info.length > 2)
  5214. html += " start=<b>"+info[1]+"</b>, end=<b>"+info[2]+"</b>";
  5215. if(info.length > 3)
  5216. html += ", length<i>(w/o overhead)</i>=<b>"+info[3]+" ms</b>";
  5217. if(info.length > 4)
  5218. html += ", return=<b>"+info[4]+"</b>";
  5219. html += "</t3></div>";
  5220. if(mlist.length > 0) {
  5221. html += '<table class=fstat style="padding-top:'+(maxlen*5)+'px;"><tr><th>Function</th>';
  5222. for(var i in mlist)
  5223. html += "<td class=vt>"+mlist[i][0]+"</td>";
  5224. html += "</tr><tr><th>Calls</th>";
  5225. for(var i in mlist)
  5226. html += "<td>"+mlist[i][1]+"</td>";
  5227. html += "</tr><tr><th>Time(ms)</th>";
  5228. for(var i in mlist)
  5229. html += "<td>"+mlist[i][2]+"</td>";
  5230. html += "</tr><tr><th>Percent</th>";
  5231. for(var i in mlist)
  5232. html += "<td>"+mlist[i][3]+"</td>";
  5233. html += "</tr></table>";
  5234. }
  5235. dd.innerHTML = html;
  5236. var height = (maxlen*5)+100;
  5237. dd.style.height = height+"px";
  5238. document.getElementById("devicedetail").style.height = height+"px";
  5239. }
  5240. function callSelect() {
  5241. var cglist = document.getElementById("callgraphs");
  5242. if(!cglist) return;
  5243. var cg = cglist.getElementsByClassName("atop");
  5244. for (var i = 0; i < cg.length; i++) {
  5245. if(this.id == cg[i].id) {
  5246. cg[i].style.display = "block";
  5247. } else {
  5248. cg[i].style.display = "none";
  5249. }
  5250. }
  5251. }
  5252. function devListWindow(e) {
  5253. var win = window.open();
  5254. var html = "<title>"+e.target.innerHTML+"</title>"+
  5255. "<style type=\"text/css\">"+
  5256. " ul {list-style-type:circle;padding-left:10px;margin-left:10px;}"+
  5257. "</style>"
  5258. var dt = devtable[0];
  5259. if(e.target.id != "devlist1")
  5260. dt = devtable[1];
  5261. win.document.write(html+dt);
  5262. }
  5263. function errWindow() {
  5264. var range = this.id.split("_");
  5265. var idx1 = parseInt(range[0]);
  5266. var idx2 = parseInt(range[1]);
  5267. var win = window.open();
  5268. var log = document.getElementById("dmesglog");
  5269. var title = "<title>dmesg log</title>";
  5270. var text = log.innerHTML.split("\n");
  5271. var html = "";
  5272. for(var i = 0; i < text.length; i++) {
  5273. if(i == idx1) {
  5274. html += "<e id=target>"+text[i]+"</e>\n";
  5275. } else if(i > idx1 && i <= idx2) {
  5276. html += "<e>"+text[i]+"</e>\n";
  5277. } else {
  5278. html += text[i]+"\n";
  5279. }
  5280. }
  5281. win.document.write("<style>e{color:red}</style>"+title+"<pre>"+html+"</pre>");
  5282. win.location.hash = "#target";
  5283. win.document.close();
  5284. }
  5285. function logWindow(e) {
  5286. var name = e.target.id.slice(4);
  5287. var win = window.open();
  5288. var log = document.getElementById(name+"log");
  5289. var title = "<title>"+document.title.split(" ")[0]+" "+name+" log</title>";
  5290. win.document.write(title+"<pre>"+log.innerHTML+"</pre>");
  5291. win.document.close();
  5292. }
  5293. function onMouseDown(e) {
  5294. dragval[0] = e.clientX;
  5295. dragval[1] = document.getElementById("dmesgzoombox").scrollLeft;
  5296. document.onmousemove = onMouseMove;
  5297. }
  5298. function onMouseMove(e) {
  5299. var zoombox = document.getElementById("dmesgzoombox");
  5300. zoombox.scrollLeft = dragval[1] + dragval[0] - e.clientX;
  5301. }
  5302. function onMouseUp(e) {
  5303. document.onmousemove = null;
  5304. }
  5305. function onKeyPress(e) {
  5306. var c = e.charCode;
  5307. if(c != 42 && c != 43 && c != 45) return;
  5308. var click = document.createEvent("Events");
  5309. click.initEvent("click", true, false);
  5310. if(c == 43)
  5311. document.getElementById("zoomin").dispatchEvent(click);
  5312. else if(c == 45)
  5313. document.getElementById("zoomout").dispatchEvent(click);
  5314. else if(c == 42)
  5315. document.getElementById("zoomdef").dispatchEvent(click);
  5316. }
  5317. window.addEventListener("resize", function () {zoomTimeline();});
  5318. window.addEventListener("load", function () {
  5319. var dmesg = document.getElementById("dmesg");
  5320. dmesg.style.width = "100%"
  5321. dmesg.onmousedown = onMouseDown;
  5322. document.onmouseup = onMouseUp;
  5323. document.onkeypress = onKeyPress;
  5324. document.getElementById("zoomin").onclick = zoomTimeline;
  5325. document.getElementById("zoomout").onclick = zoomTimeline;
  5326. document.getElementById("zoomdef").onclick = zoomTimeline;
  5327. var list = document.getElementsByClassName("err");
  5328. for (var i = 0; i < list.length; i++)
  5329. list[i].onclick = errWindow;
  5330. var list = document.getElementsByClassName("logbtn");
  5331. for (var i = 0; i < list.length; i++)
  5332. list[i].onclick = logWindow;
  5333. list = document.getElementsByClassName("devlist");
  5334. for (var i = 0; i < list.length; i++)
  5335. list[i].onclick = devListWindow;
  5336. var dev = dmesg.getElementsByClassName("thread");
  5337. for (var i = 0; i < dev.length; i++) {
  5338. dev[i].onclick = deviceDetail;
  5339. dev[i].onmouseover = deviceHover;
  5340. dev[i].onmouseout = deviceUnhover;
  5341. }
  5342. var dev = dmesg.getElementsByClassName("srccall");
  5343. for (var i = 0; i < dev.length; i++)
  5344. dev[i].onclick = callSelect;
  5345. zoomTimeline();
  5346. });
  5347. </script> """
  5348. hf.write(script_code);
  5349. # Function: executeSuspend
  5350. # Description:
  5351. # Execute system suspend through the sysfs interface, then copy the output
  5352. # dmesg and ftrace files to the test output directory.
  5353. def executeSuspend(quiet=False):
  5354. sv, tp, pm = sysvals, sysvals.tpath, ProcessMonitor()
  5355. if sv.wifi:
  5356. wifi = sv.checkWifi()
  5357. sv.dlog('wifi check, connected device is "%s"' % wifi)
  5358. testdata = []
  5359. # run these commands to prepare the system for suspend
  5360. if sv.display:
  5361. if not quiet:
  5362. pprint('SET DISPLAY TO %s' % sv.display.upper())
  5363. ret = sv.displayControl(sv.display)
  5364. sv.dlog('xset display %s, ret = %d' % (sv.display, ret))
  5365. time.sleep(1)
  5366. if sv.sync:
  5367. if not quiet:
  5368. pprint('SYNCING FILESYSTEMS')
  5369. sv.dlog('syncing filesystems')
  5370. call('sync', shell=True)
  5371. sv.dlog('read dmesg')
  5372. sv.initdmesg()
  5373. sv.dlog('cmdinfo before')
  5374. sv.cmdinfo(True)
  5375. sv.start(pm)
  5376. # execute however many s/r runs requested
  5377. for count in range(1,sv.execcount+1):
  5378. # x2delay in between test runs
  5379. if(count > 1 and sv.x2delay > 0):
  5380. sv.fsetVal('WAIT %d' % sv.x2delay, 'trace_marker')
  5381. time.sleep(sv.x2delay/1000.0)
  5382. sv.fsetVal('WAIT END', 'trace_marker')
  5383. # start message
  5384. if sv.testcommand != '':
  5385. pprint('COMMAND START')
  5386. else:
  5387. if(sv.rtcwake):
  5388. pprint('SUSPEND START')
  5389. else:
  5390. pprint('SUSPEND START (press a key to resume)')
  5391. # set rtcwake
  5392. if(sv.rtcwake):
  5393. if not quiet:
  5394. pprint('will issue an rtcwake in %d seconds' % sv.rtcwaketime)
  5395. sv.dlog('enable RTC wake alarm')
  5396. sv.rtcWakeAlarmOn()
  5397. # start of suspend trace marker
  5398. sv.fsetVal(datetime.now().strftime(sv.tmstart), 'trace_marker')
  5399. # predelay delay
  5400. if(count == 1 and sv.predelay > 0):
  5401. sv.fsetVal('WAIT %d' % sv.predelay, 'trace_marker')
  5402. time.sleep(sv.predelay/1000.0)
  5403. sv.fsetVal('WAIT END', 'trace_marker')
  5404. # initiate suspend or command
  5405. sv.dlog('system executing a suspend')
  5406. tdata = {'error': ''}
  5407. if sv.testcommand != '':
  5408. res = call(sv.testcommand+' 2>&1', shell=True);
  5409. if res != 0:
  5410. tdata['error'] = 'cmd returned %d' % res
  5411. else:
  5412. s0ixready = sv.s0ixSupport()
  5413. mode = sv.suspendmode
  5414. if sv.memmode and os.path.exists(sv.mempowerfile):
  5415. mode = 'mem'
  5416. sv.testVal(sv.mempowerfile, 'radio', sv.memmode)
  5417. if sv.diskmode and os.path.exists(sv.diskpowerfile):
  5418. mode = 'disk'
  5419. sv.testVal(sv.diskpowerfile, 'radio', sv.diskmode)
  5420. if sv.acpidebug:
  5421. sv.testVal(sv.acpipath, 'acpi', '0xe')
  5422. if ((mode == 'freeze') or (sv.memmode == 's2idle')) \
  5423. and sv.haveTurbostat():
  5424. # execution will pause here
  5425. retval, turbo = sv.turbostat(s0ixready)
  5426. if retval != 0:
  5427. tdata['error'] ='turbostat returned %d' % retval
  5428. if turbo:
  5429. tdata['turbo'] = turbo
  5430. else:
  5431. pf = open(sv.powerfile, 'w')
  5432. pf.write(mode)
  5433. # execution will pause here
  5434. try:
  5435. pf.flush()
  5436. pf.close()
  5437. except Exception as e:
  5438. tdata['error'] = str(e)
  5439. sv.fsetVal('CMD COMPLETE', 'trace_marker')
  5440. sv.dlog('system returned')
  5441. # reset everything
  5442. sv.testVal('restoreall')
  5443. if(sv.rtcwake):
  5444. sv.dlog('disable RTC wake alarm')
  5445. sv.rtcWakeAlarmOff()
  5446. # postdelay delay
  5447. if(count == sv.execcount and sv.postdelay > 0):
  5448. sv.fsetVal('WAIT %d' % sv.postdelay, 'trace_marker')
  5449. time.sleep(sv.postdelay/1000.0)
  5450. sv.fsetVal('WAIT END', 'trace_marker')
  5451. # return from suspend
  5452. pprint('RESUME COMPLETE')
  5453. if(count < sv.execcount):
  5454. sv.fsetVal(datetime.now().strftime(sv.tmend), 'trace_marker')
  5455. elif(not sv.wifitrace):
  5456. sv.fsetVal(datetime.now().strftime(sv.tmend), 'trace_marker')
  5457. sv.stop(pm)
  5458. if sv.wifi and wifi:
  5459. tdata['wifi'] = sv.pollWifi(wifi)
  5460. sv.dlog('wifi check, %s' % tdata['wifi'])
  5461. if(count == sv.execcount and sv.wifitrace):
  5462. sv.fsetVal(datetime.now().strftime(sv.tmend), 'trace_marker')
  5463. sv.stop(pm)
  5464. if sv.netfix:
  5465. tdata['netfix'] = sv.netfixon()
  5466. sv.dlog('netfix, %s' % tdata['netfix'])
  5467. if(sv.suspendmode == 'mem' or sv.suspendmode == 'command'):
  5468. sv.dlog('read the ACPI FPDT')
  5469. tdata['fw'] = getFPDT(False)
  5470. testdata.append(tdata)
  5471. sv.dlog('cmdinfo after')
  5472. cmdafter = sv.cmdinfo(False)
  5473. # grab a copy of the dmesg output
  5474. if not quiet:
  5475. pprint('CAPTURING DMESG')
  5476. sv.getdmesg(testdata)
  5477. # grab a copy of the ftrace output
  5478. if sv.useftrace:
  5479. if not quiet:
  5480. pprint('CAPTURING TRACE')
  5481. op = sv.writeDatafileHeader(sv.ftracefile, testdata)
  5482. fp = open(tp+'trace', 'rb')
  5483. op.write(ascii(fp.read()))
  5484. op.close()
  5485. sv.fsetVal('', 'trace')
  5486. sv.platforminfo(cmdafter)
  5487. def readFile(file):
  5488. if os.path.islink(file):
  5489. return os.readlink(file).split('/')[-1]
  5490. else:
  5491. return sysvals.getVal(file).strip()
  5492. # Function: ms2nice
  5493. # Description:
  5494. # Print out a very concise time string in minutes and seconds
  5495. # Output:
  5496. # The time string, e.g. "1901m16s"
  5497. def ms2nice(val):
  5498. val = int(val)
  5499. h = val // 3600000
  5500. m = (val // 60000) % 60
  5501. s = (val // 1000) % 60
  5502. if h > 0:
  5503. return '%d:%02d:%02d' % (h, m, s)
  5504. if m > 0:
  5505. return '%02d:%02d' % (m, s)
  5506. return '%ds' % s
  5507. def yesno(val):
  5508. list = {'enabled':'A', 'disabled':'S', 'auto':'E', 'on':'D',
  5509. 'active':'A', 'suspended':'S', 'suspending':'S'}
  5510. if val not in list:
  5511. return ' '
  5512. return list[val]
  5513. # Function: deviceInfo
  5514. # Description:
  5515. # Detect all the USB hosts and devices currently connected and add
  5516. # a list of USB device names to sysvals for better timeline readability
  5517. def deviceInfo(output=''):
  5518. if not output:
  5519. pprint('LEGEND\n'\
  5520. '---------------------------------------------------------------------------------------------\n'\
  5521. ' A = async/sync PM queue (A/S) C = runtime active children\n'\
  5522. ' R = runtime suspend enabled/disabled (E/D) rACTIVE = runtime active (min/sec)\n'\
  5523. ' S = runtime status active/suspended (A/S) rSUSPEND = runtime suspend (min/sec)\n'\
  5524. ' U = runtime usage count\n'\
  5525. '---------------------------------------------------------------------------------------------\n'\
  5526. 'DEVICE NAME A R S U C rACTIVE rSUSPEND\n'\
  5527. '---------------------------------------------------------------------------------------------')
  5528. res = []
  5529. tgtval = 'runtime_status'
  5530. lines = dict()
  5531. for dirname, dirnames, filenames in os.walk('/sys/devices'):
  5532. if(not re.match(r'.*/power', dirname) or
  5533. 'control' not in filenames or
  5534. tgtval not in filenames):
  5535. continue
  5536. name = ''
  5537. dirname = dirname[:-6]
  5538. device = dirname.split('/')[-1]
  5539. power = dict()
  5540. power[tgtval] = readFile('%s/power/%s' % (dirname, tgtval))
  5541. # only list devices which support runtime suspend
  5542. if power[tgtval] not in ['active', 'suspended', 'suspending']:
  5543. continue
  5544. for i in ['product', 'driver', 'subsystem']:
  5545. file = '%s/%s' % (dirname, i)
  5546. if os.path.exists(file):
  5547. name = readFile(file)
  5548. break
  5549. for i in ['async', 'control', 'runtime_status', 'runtime_usage',
  5550. 'runtime_active_kids', 'runtime_active_time',
  5551. 'runtime_suspended_time']:
  5552. if i in filenames:
  5553. power[i] = readFile('%s/power/%s' % (dirname, i))
  5554. if output:
  5555. if power['control'] == output:
  5556. res.append('%s/power/control' % dirname)
  5557. continue
  5558. lines[dirname] = '%-26s %-26s %1s %1s %1s %1s %1s %10s %10s' % \
  5559. (device[:26], name[:26],
  5560. yesno(power['async']), \
  5561. yesno(power['control']), \
  5562. yesno(power['runtime_status']), \
  5563. power['runtime_usage'], \
  5564. power['runtime_active_kids'], \
  5565. ms2nice(power['runtime_active_time']), \
  5566. ms2nice(power['runtime_suspended_time']))
  5567. for i in sorted(lines):
  5568. print(lines[i])
  5569. return res
  5570. # Function: getModes
  5571. # Description:
  5572. # Determine the supported power modes on this system
  5573. # Output:
  5574. # A string list of the available modes
  5575. def getModes():
  5576. modes = []
  5577. if(os.path.exists(sysvals.powerfile)):
  5578. fp = open(sysvals.powerfile, 'r')
  5579. modes = fp.read().split()
  5580. fp.close()
  5581. if(os.path.exists(sysvals.mempowerfile)):
  5582. deep = False
  5583. fp = open(sysvals.mempowerfile, 'r')
  5584. for m in fp.read().split():
  5585. memmode = m.strip('[]')
  5586. if memmode == 'deep':
  5587. deep = True
  5588. else:
  5589. modes.append('mem-%s' % memmode)
  5590. fp.close()
  5591. if 'mem' in modes and not deep:
  5592. modes.remove('mem')
  5593. if('disk' in modes and os.path.exists(sysvals.diskpowerfile)):
  5594. fp = open(sysvals.diskpowerfile, 'r')
  5595. for m in fp.read().split():
  5596. modes.append('disk-%s' % m.strip('[]'))
  5597. fp.close()
  5598. return modes
  5599. def dmidecode_backup(out, fatal=False):
  5600. cpath, spath, info = '/proc/cpuinfo', '/sys/class/dmi/id', {
  5601. 'bios-vendor': 'bios_vendor',
  5602. 'bios-version': 'bios_version',
  5603. 'bios-release-date': 'bios_date',
  5604. 'system-manufacturer': 'sys_vendor',
  5605. 'system-product-name': 'product_name',
  5606. 'system-version': 'product_version',
  5607. 'system-serial-number': 'product_serial',
  5608. 'baseboard-manufacturer': 'board_vendor',
  5609. 'baseboard-product-name': 'board_name',
  5610. 'baseboard-version': 'board_version',
  5611. 'baseboard-serial-number': 'board_serial',
  5612. 'chassis-manufacturer': 'chassis_vendor',
  5613. 'chassis-version': 'chassis_version',
  5614. 'chassis-serial-number': 'chassis_serial',
  5615. }
  5616. for key in info:
  5617. if key not in out:
  5618. val = sysvals.getVal(os.path.join(spath, info[key])).strip()
  5619. if val and val.lower() != 'to be filled by o.e.m.':
  5620. out[key] = val
  5621. if 'processor-version' not in out and os.path.exists(cpath):
  5622. with open(cpath, 'r') as fp:
  5623. for line in fp:
  5624. m = re.match(r'^model\s*name\s*\:\s*(?P<c>.*)', line)
  5625. if m:
  5626. out['processor-version'] = m.group('c').strip()
  5627. break
  5628. if fatal and len(out) < 1:
  5629. doError('dmidecode failed to get info from %s or %s' % \
  5630. (sysvals.mempath, spath))
  5631. return out
  5632. # Function: dmidecode
  5633. # Description:
  5634. # Read the bios tables and pull out system info
  5635. # Arguments:
  5636. # mempath: /dev/mem or custom mem path
  5637. # fatal: True to exit on error, False to return empty dict
  5638. # Output:
  5639. # A dict object with all available key/values
  5640. def dmidecode(mempath, fatal=False):
  5641. out = dict()
  5642. if(not (os.path.exists(mempath) and os.access(mempath, os.R_OK))):
  5643. return dmidecode_backup(out, fatal)
  5644. # the list of values to retrieve, with hardcoded (type, idx)
  5645. info = {
  5646. 'bios-vendor': (0, 4),
  5647. 'bios-version': (0, 5),
  5648. 'bios-release-date': (0, 8),
  5649. 'system-manufacturer': (1, 4),
  5650. 'system-product-name': (1, 5),
  5651. 'system-version': (1, 6),
  5652. 'system-serial-number': (1, 7),
  5653. 'baseboard-manufacturer': (2, 4),
  5654. 'baseboard-product-name': (2, 5),
  5655. 'baseboard-version': (2, 6),
  5656. 'baseboard-serial-number': (2, 7),
  5657. 'chassis-manufacturer': (3, 4),
  5658. 'chassis-version': (3, 6),
  5659. 'chassis-serial-number': (3, 7),
  5660. 'processor-manufacturer': (4, 7),
  5661. 'processor-version': (4, 16),
  5662. }
  5663. # by default use legacy scan, but try to use EFI first
  5664. memaddr, memsize = 0xf0000, 0x10000
  5665. for ep in ['/sys/firmware/efi/systab', '/proc/efi/systab']:
  5666. if not os.path.exists(ep) or not os.access(ep, os.R_OK):
  5667. continue
  5668. fp = open(ep, 'r')
  5669. buf = fp.read()
  5670. fp.close()
  5671. i = buf.find('SMBIOS=')
  5672. if i >= 0:
  5673. try:
  5674. memaddr = int(buf[i+7:], 16)
  5675. memsize = 0x20
  5676. except:
  5677. continue
  5678. # read in the memory for scanning
  5679. try:
  5680. fp = open(mempath, 'rb')
  5681. fp.seek(memaddr)
  5682. buf = fp.read(memsize)
  5683. except:
  5684. return dmidecode_backup(out, fatal)
  5685. fp.close()
  5686. # search for either an SM table or DMI table
  5687. i = base = length = num = 0
  5688. while(i < memsize):
  5689. if buf[i:i+4] == b'_SM_' and i < memsize - 16:
  5690. length = struct.unpack('H', buf[i+22:i+24])[0]
  5691. base, num = struct.unpack('IH', buf[i+24:i+30])
  5692. break
  5693. elif buf[i:i+5] == b'_DMI_':
  5694. length = struct.unpack('H', buf[i+6:i+8])[0]
  5695. base, num = struct.unpack('IH', buf[i+8:i+14])
  5696. break
  5697. i += 16
  5698. if base == 0 and length == 0 and num == 0:
  5699. return dmidecode_backup(out, fatal)
  5700. # read in the SM or DMI table
  5701. try:
  5702. fp = open(mempath, 'rb')
  5703. fp.seek(base)
  5704. buf = fp.read(length)
  5705. except:
  5706. return dmidecode_backup(out, fatal)
  5707. fp.close()
  5708. # scan the table for the values we want
  5709. count = i = 0
  5710. while(count < num and i <= len(buf) - 4):
  5711. type, size, handle = struct.unpack('BBH', buf[i:i+4])
  5712. n = i + size
  5713. while n < len(buf) - 1:
  5714. if 0 == struct.unpack('H', buf[n:n+2])[0]:
  5715. break
  5716. n += 1
  5717. data = buf[i+size:n+2].split(b'\0')
  5718. for name in info:
  5719. itype, idxadr = info[name]
  5720. if itype == type:
  5721. idx = struct.unpack('B', buf[i+idxadr:i+idxadr+1])[0]
  5722. if idx > 0 and idx < len(data) - 1:
  5723. s = data[idx-1].decode('utf-8')
  5724. if s.strip() and s.strip().lower() != 'to be filled by o.e.m.':
  5725. out[name] = s
  5726. i = n + 2
  5727. count += 1
  5728. return out
  5729. # Function: getFPDT
  5730. # Description:
  5731. # Read the acpi bios tables and pull out FPDT, the firmware data
  5732. # Arguments:
  5733. # output: True to output the info to stdout, False otherwise
  5734. def getFPDT(output):
  5735. rectype = {}
  5736. rectype[0] = 'Firmware Basic Boot Performance Record'
  5737. rectype[1] = 'S3 Performance Table Record'
  5738. prectype = {}
  5739. prectype[0] = 'Basic S3 Resume Performance Record'
  5740. prectype[1] = 'Basic S3 Suspend Performance Record'
  5741. sysvals.rootCheck(True)
  5742. if(not os.path.exists(sysvals.fpdtpath)):
  5743. if(output):
  5744. doError('file does not exist: %s' % sysvals.fpdtpath)
  5745. return False
  5746. if(not os.access(sysvals.fpdtpath, os.R_OK)):
  5747. if(output):
  5748. doError('file is not readable: %s' % sysvals.fpdtpath)
  5749. return False
  5750. if(not os.path.exists(sysvals.mempath)):
  5751. if(output):
  5752. doError('file does not exist: %s' % sysvals.mempath)
  5753. return False
  5754. if(not os.access(sysvals.mempath, os.R_OK)):
  5755. if(output):
  5756. doError('file is not readable: %s' % sysvals.mempath)
  5757. return False
  5758. fp = open(sysvals.fpdtpath, 'rb')
  5759. buf = fp.read()
  5760. fp.close()
  5761. if(len(buf) < 36):
  5762. if(output):
  5763. doError('Invalid FPDT table data, should '+\
  5764. 'be at least 36 bytes')
  5765. return False
  5766. table = struct.unpack('4sIBB6s8sI4sI', buf[0:36])
  5767. if(output):
  5768. pprint('\n'\
  5769. 'Firmware Performance Data Table (%s)\n'\
  5770. ' Signature : %s\n'\
  5771. ' Table Length : %u\n'\
  5772. ' Revision : %u\n'\
  5773. ' Checksum : 0x%x\n'\
  5774. ' OEM ID : %s\n'\
  5775. ' OEM Table ID : %s\n'\
  5776. ' OEM Revision : %u\n'\
  5777. ' Creator ID : %s\n'\
  5778. ' Creator Revision : 0x%x\n'\
  5779. '' % (ascii(table[0]), ascii(table[0]), table[1], table[2],
  5780. table[3], ascii(table[4]), ascii(table[5]), table[6],
  5781. ascii(table[7]), table[8]))
  5782. if(table[0] != b'FPDT'):
  5783. if(output):
  5784. doError('Invalid FPDT table')
  5785. return False
  5786. if(len(buf) <= 36):
  5787. return False
  5788. i = 0
  5789. fwData = [0, 0]
  5790. records = buf[36:]
  5791. try:
  5792. fp = open(sysvals.mempath, 'rb')
  5793. except:
  5794. pprint('WARNING: /dev/mem is not readable, ignoring the FPDT data')
  5795. return False
  5796. while(i < len(records)):
  5797. header = struct.unpack('HBB', records[i:i+4])
  5798. if(header[0] not in rectype):
  5799. i += header[1]
  5800. continue
  5801. if(header[1] != 16):
  5802. i += header[1]
  5803. continue
  5804. addr = struct.unpack('Q', records[i+8:i+16])[0]
  5805. try:
  5806. fp.seek(addr)
  5807. first = fp.read(8)
  5808. except:
  5809. if(output):
  5810. pprint('Bad address 0x%x in %s' % (addr, sysvals.mempath))
  5811. return [0, 0]
  5812. rechead = struct.unpack('4sI', first)
  5813. recdata = fp.read(rechead[1]-8)
  5814. if(rechead[0] == b'FBPT'):
  5815. record = struct.unpack('HBBIQQQQQ', recdata[:48])
  5816. if(output):
  5817. pprint('%s (%s)\n'\
  5818. ' Reset END : %u ns\n'\
  5819. ' OS Loader LoadImage Start : %u ns\n'\
  5820. ' OS Loader StartImage Start : %u ns\n'\
  5821. ' ExitBootServices Entry : %u ns\n'\
  5822. ' ExitBootServices Exit : %u ns'\
  5823. '' % (rectype[header[0]], ascii(rechead[0]), record[4], record[5],
  5824. record[6], record[7], record[8]))
  5825. elif(rechead[0] == b'S3PT'):
  5826. if(output):
  5827. pprint('%s (%s)' % (rectype[header[0]], ascii(rechead[0])))
  5828. j = 0
  5829. while(j < len(recdata)):
  5830. prechead = struct.unpack('HBB', recdata[j:j+4])
  5831. if(prechead[0] not in prectype):
  5832. continue
  5833. if(prechead[0] == 0):
  5834. record = struct.unpack('IIQQ', recdata[j:j+prechead[1]])
  5835. fwData[1] = record[2]
  5836. if(output):
  5837. pprint(' %s\n'\
  5838. ' Resume Count : %u\n'\
  5839. ' FullResume : %u ns\n'\
  5840. ' AverageResume : %u ns'\
  5841. '' % (prectype[prechead[0]], record[1],
  5842. record[2], record[3]))
  5843. elif(prechead[0] == 1):
  5844. record = struct.unpack('QQ', recdata[j+4:j+prechead[1]])
  5845. fwData[0] = record[1] - record[0]
  5846. if(output):
  5847. pprint(' %s\n'\
  5848. ' SuspendStart : %u ns\n'\
  5849. ' SuspendEnd : %u ns\n'\
  5850. ' SuspendTime : %u ns'\
  5851. '' % (prectype[prechead[0]], record[0],
  5852. record[1], fwData[0]))
  5853. j += prechead[1]
  5854. if(output):
  5855. pprint('')
  5856. i += header[1]
  5857. fp.close()
  5858. return fwData
  5859. # Function: statusCheck
  5860. # Description:
  5861. # Verify that the requested command and options will work, and
  5862. # print the results to the terminal
  5863. # Output:
  5864. # True if the test will work, False if not
  5865. def statusCheck(probecheck=False):
  5866. status = ''
  5867. pprint('Checking this system (%s)...' % platform.node())
  5868. # check we have root access
  5869. res = sysvals.colorText('NO (No features of this tool will work!)')
  5870. if(sysvals.rootCheck(False)):
  5871. res = 'YES'
  5872. pprint(' have root access: %s' % res)
  5873. if(res != 'YES'):
  5874. pprint(' Try running this script with sudo')
  5875. return 'missing root access'
  5876. # check sysfs is mounted
  5877. res = sysvals.colorText('NO (No features of this tool will work!)')
  5878. if(os.path.exists(sysvals.powerfile)):
  5879. res = 'YES'
  5880. pprint(' is sysfs mounted: %s' % res)
  5881. if(res != 'YES'):
  5882. return 'sysfs is missing'
  5883. # check target mode is a valid mode
  5884. if sysvals.suspendmode != 'command':
  5885. res = sysvals.colorText('NO')
  5886. modes = getModes()
  5887. if(sysvals.suspendmode in modes):
  5888. res = 'YES'
  5889. else:
  5890. status = '%s mode is not supported' % sysvals.suspendmode
  5891. pprint(' is "%s" a valid power mode: %s' % (sysvals.suspendmode, res))
  5892. if(res == 'NO'):
  5893. pprint(' valid power modes are: %s' % modes)
  5894. pprint(' please choose one with -m')
  5895. # check if ftrace is available
  5896. if sysvals.useftrace:
  5897. res = sysvals.colorText('NO')
  5898. sysvals.useftrace = sysvals.verifyFtrace()
  5899. efmt = '"{0}" uses ftrace, and it is not properly supported'
  5900. if sysvals.useftrace:
  5901. res = 'YES'
  5902. elif sysvals.usecallgraph:
  5903. status = efmt.format('-f')
  5904. elif sysvals.usedevsrc:
  5905. status = efmt.format('-dev')
  5906. elif sysvals.useprocmon:
  5907. status = efmt.format('-proc')
  5908. pprint(' is ftrace supported: %s' % res)
  5909. # check if kprobes are available
  5910. if sysvals.usekprobes:
  5911. res = sysvals.colorText('NO')
  5912. sysvals.usekprobes = sysvals.verifyKprobes()
  5913. if(sysvals.usekprobes):
  5914. res = 'YES'
  5915. else:
  5916. sysvals.usedevsrc = False
  5917. pprint(' are kprobes supported: %s' % res)
  5918. # what data source are we using
  5919. res = 'DMESG (very limited, ftrace is preferred)'
  5920. if sysvals.useftrace:
  5921. sysvals.usetraceevents = True
  5922. for e in sysvals.traceevents:
  5923. if not os.path.exists(sysvals.epath+e):
  5924. sysvals.usetraceevents = False
  5925. if(sysvals.usetraceevents):
  5926. res = 'FTRACE (all trace events found)'
  5927. pprint(' timeline data source: %s' % res)
  5928. # check if rtcwake
  5929. res = sysvals.colorText('NO')
  5930. if(sysvals.rtcpath != ''):
  5931. res = 'YES'
  5932. elif(sysvals.rtcwake):
  5933. status = 'rtcwake is not properly supported'
  5934. pprint(' is rtcwake supported: %s' % res)
  5935. # check info commands
  5936. pprint(' optional commands this tool may use for info:')
  5937. no = sysvals.colorText('MISSING')
  5938. yes = sysvals.colorText('FOUND', 32)
  5939. for c in ['turbostat', 'mcelog', 'lspci', 'lsusb', 'netfix']:
  5940. if c == 'turbostat':
  5941. res = yes if sysvals.haveTurbostat() else no
  5942. else:
  5943. res = yes if sysvals.getExec(c) else no
  5944. pprint(' %s: %s' % (c, res))
  5945. if not probecheck:
  5946. return status
  5947. # verify kprobes
  5948. if sysvals.usekprobes:
  5949. for name in sysvals.tracefuncs:
  5950. sysvals.defaultKprobe(name, sysvals.tracefuncs[name])
  5951. if sysvals.usedevsrc:
  5952. for name in sysvals.dev_tracefuncs:
  5953. sysvals.defaultKprobe(name, sysvals.dev_tracefuncs[name])
  5954. sysvals.addKprobes(True)
  5955. return status
  5956. # Function: doError
  5957. # Description:
  5958. # generic error function for catastrphic failures
  5959. # Arguments:
  5960. # msg: the error message to print
  5961. # help: True if printHelp should be called after, False otherwise
  5962. def doError(msg, help=False):
  5963. if(help == True):
  5964. printHelp()
  5965. pprint('ERROR: %s\n' % msg)
  5966. sysvals.outputResult({'error':msg})
  5967. sys.exit(1)
  5968. # Function: getArgInt
  5969. # Description:
  5970. # pull out an integer argument from the command line with checks
  5971. def getArgInt(name, args, min, max, main=True):
  5972. if main:
  5973. try:
  5974. arg = next(args)
  5975. except:
  5976. doError(name+': no argument supplied', True)
  5977. else:
  5978. arg = args
  5979. try:
  5980. val = int(arg)
  5981. except:
  5982. doError(name+': non-integer value given', True)
  5983. if(val < min or val > max):
  5984. doError(name+': value should be between %d and %d' % (min, max), True)
  5985. return val
  5986. # Function: getArgFloat
  5987. # Description:
  5988. # pull out a float argument from the command line with checks
  5989. def getArgFloat(name, args, min, max, main=True):
  5990. if main:
  5991. try:
  5992. arg = next(args)
  5993. except:
  5994. doError(name+': no argument supplied', True)
  5995. else:
  5996. arg = args
  5997. try:
  5998. val = float(arg)
  5999. except:
  6000. doError(name+': non-numerical value given', True)
  6001. if(val < min or val > max):
  6002. doError(name+': value should be between %f and %f' % (min, max), True)
  6003. return val
  6004. def processData(live=False, quiet=False):
  6005. if not quiet:
  6006. pprint('PROCESSING: %s' % sysvals.htmlfile)
  6007. sysvals.vprint('usetraceevents=%s, usetracemarkers=%s, usekprobes=%s' % \
  6008. (sysvals.usetraceevents, sysvals.usetracemarkers, sysvals.usekprobes))
  6009. error = ''
  6010. if(sysvals.usetraceevents):
  6011. testruns, error = parseTraceLog(live)
  6012. if sysvals.dmesgfile:
  6013. for data in testruns:
  6014. data.extractErrorInfo()
  6015. else:
  6016. testruns = loadKernelLog()
  6017. for data in testruns:
  6018. parseKernelLog(data)
  6019. if(sysvals.ftracefile and (sysvals.usecallgraph or sysvals.usetraceevents)):
  6020. appendIncompleteTraceLog(testruns)
  6021. if not sysvals.stamp:
  6022. pprint('ERROR: data does not include the expected stamp')
  6023. return (testruns, {'error': 'timeline generation failed'})
  6024. shown = ['os', 'bios', 'biosdate', 'cpu', 'host', 'kernel', 'man', 'memfr',
  6025. 'memsz', 'mode', 'numcpu', 'plat', 'time', 'wifi']
  6026. sysvals.vprint('System Info:')
  6027. for key in sorted(sysvals.stamp):
  6028. if key in shown:
  6029. sysvals.vprint(' %-8s : %s' % (key.upper(), sysvals.stamp[key]))
  6030. sysvals.vprint('Command:\n %s' % sysvals.cmdline)
  6031. for data in testruns:
  6032. if data.turbostat:
  6033. idx, s = 0, 'Turbostat:\n '
  6034. for val in data.turbostat.split('|'):
  6035. idx += len(val) + 1
  6036. if idx >= 80:
  6037. idx = 0
  6038. s += '\n '
  6039. s += val + ' '
  6040. sysvals.vprint(s)
  6041. data.printDetails()
  6042. if len(sysvals.platinfo) > 0:
  6043. sysvals.vprint('\nPlatform Info:')
  6044. for info in sysvals.platinfo:
  6045. sysvals.vprint('[%s - %s]' % (info[0], info[1]))
  6046. sysvals.vprint(info[2])
  6047. sysvals.vprint('')
  6048. if sysvals.cgdump:
  6049. for data in testruns:
  6050. data.debugPrint()
  6051. sys.exit(0)
  6052. if len(testruns) < 1:
  6053. pprint('ERROR: Not enough test data to build a timeline')
  6054. return (testruns, {'error': 'timeline generation failed'})
  6055. sysvals.vprint('Creating the html timeline (%s)...' % sysvals.htmlfile)
  6056. createHTML(testruns, error)
  6057. if not quiet:
  6058. pprint('DONE: %s' % sysvals.htmlfile)
  6059. data = testruns[0]
  6060. stamp = data.stamp
  6061. stamp['suspend'], stamp['resume'] = data.getTimeValues()
  6062. if data.fwValid:
  6063. stamp['fwsuspend'], stamp['fwresume'] = data.fwSuspend, data.fwResume
  6064. if error:
  6065. stamp['error'] = error
  6066. return (testruns, stamp)
  6067. # Function: rerunTest
  6068. # Description:
  6069. # generate an output from an existing set of ftrace/dmesg logs
  6070. def rerunTest(htmlfile=''):
  6071. if sysvals.ftracefile:
  6072. doesTraceLogHaveTraceEvents()
  6073. if not sysvals.dmesgfile and not sysvals.usetraceevents:
  6074. doError('recreating this html output requires a dmesg file')
  6075. if htmlfile:
  6076. sysvals.htmlfile = htmlfile
  6077. else:
  6078. sysvals.setOutputFile()
  6079. if os.path.exists(sysvals.htmlfile):
  6080. if not os.path.isfile(sysvals.htmlfile):
  6081. doError('a directory already exists with this name: %s' % sysvals.htmlfile)
  6082. elif not os.access(sysvals.htmlfile, os.W_OK):
  6083. doError('missing permission to write to %s' % sysvals.htmlfile)
  6084. testruns, stamp = processData()
  6085. sysvals.resetlog()
  6086. return stamp
  6087. # Function: runTest
  6088. # Description:
  6089. # execute a suspend/resume, gather the logs, and generate the output
  6090. def runTest(n=0, quiet=False):
  6091. # prepare for the test
  6092. sysvals.initTestOutput('suspend')
  6093. op = sysvals.writeDatafileHeader(sysvals.dmesgfile, [])
  6094. op.write('# EXECUTION TRACE START\n')
  6095. op.close()
  6096. if n <= 1:
  6097. if sysvals.rs != 0:
  6098. sysvals.dlog('%sabling runtime suspend' % ('en' if sysvals.rs > 0 else 'dis'))
  6099. sysvals.setRuntimeSuspend(True)
  6100. if sysvals.display:
  6101. ret = sysvals.displayControl('init')
  6102. sysvals.dlog('xset display init, ret = %d' % ret)
  6103. sysvals.testVal(sysvals.pmdpath, 'basic', '1')
  6104. sysvals.testVal(sysvals.s0ixpath, 'basic', 'Y')
  6105. sysvals.dlog('initialize ftrace')
  6106. sysvals.initFtrace(quiet)
  6107. # execute the test
  6108. executeSuspend(quiet)
  6109. sysvals.cleanupFtrace()
  6110. if sysvals.skiphtml:
  6111. sysvals.outputResult({}, n)
  6112. sysvals.sudoUserchown(sysvals.testdir)
  6113. return
  6114. testruns, stamp = processData(True, quiet)
  6115. for data in testruns:
  6116. del data
  6117. sysvals.sudoUserchown(sysvals.testdir)
  6118. sysvals.outputResult(stamp, n)
  6119. if 'error' in stamp:
  6120. return 2
  6121. return 0
  6122. def find_in_html(html, start, end, firstonly=True):
  6123. cnt, out, list = len(html), [], []
  6124. if firstonly:
  6125. m = re.search(start, html)
  6126. if m:
  6127. list.append(m)
  6128. else:
  6129. list = re.finditer(start, html)
  6130. for match in list:
  6131. s = match.end()
  6132. e = cnt if (len(out) < 1 or s + 10000 > cnt) else s + 10000
  6133. m = re.search(end, html[s:e])
  6134. if not m:
  6135. break
  6136. e = s + m.start()
  6137. str = html[s:e]
  6138. if end == 'ms':
  6139. num = re.search(r'[-+]?\d*\.\d+|\d+', str)
  6140. str = num.group() if num else 'NaN'
  6141. if firstonly:
  6142. return str
  6143. out.append(str)
  6144. if firstonly:
  6145. return ''
  6146. return out
  6147. def data_from_html(file, outpath, issues, fulldetail=False):
  6148. try:
  6149. html = open(file, 'r').read()
  6150. except:
  6151. html = ascii(open(file, 'rb').read())
  6152. sysvals.htmlfile = os.path.relpath(file, outpath)
  6153. # extract general info
  6154. suspend = find_in_html(html, 'Kernel Suspend', 'ms')
  6155. resume = find_in_html(html, 'Kernel Resume', 'ms')
  6156. sysinfo = find_in_html(html, '<div class="stamp sysinfo">', '</div>')
  6157. line = find_in_html(html, '<div class="stamp">', '</div>')
  6158. stmp = line.split()
  6159. if not suspend or not resume or len(stmp) != 8:
  6160. return False
  6161. try:
  6162. dt = datetime.strptime(' '.join(stmp[3:]), '%B %d %Y, %I:%M:%S %p')
  6163. except:
  6164. return False
  6165. sysvals.hostname = stmp[0]
  6166. tstr = dt.strftime('%Y/%m/%d %H:%M:%S')
  6167. error = find_in_html(html, '<table class="testfail"><tr><td>', '</td>')
  6168. if error:
  6169. m = re.match(r'[a-z0-9]* failed in (?P<p>\S*).*', error)
  6170. if m:
  6171. result = 'fail in %s' % m.group('p')
  6172. else:
  6173. result = 'fail'
  6174. else:
  6175. result = 'pass'
  6176. # extract error info
  6177. tp, ilist = False, []
  6178. extra = dict()
  6179. log = find_in_html(html, '<div id="dmesglog" style="display:none;">',
  6180. '</div>').strip()
  6181. if log:
  6182. d = Data(0)
  6183. d.end = 999999999
  6184. d.dmesgtext = log.split('\n')
  6185. tp = d.extractErrorInfo()
  6186. if len(issues) < 100:
  6187. for msg in tp.msglist:
  6188. sysvals.errorSummary(issues, msg)
  6189. if stmp[2] == 'freeze':
  6190. extra = d.turbostatInfo()
  6191. elist = dict()
  6192. for dir in d.errorinfo:
  6193. for err in d.errorinfo[dir]:
  6194. if err[0] not in elist:
  6195. elist[err[0]] = 0
  6196. elist[err[0]] += 1
  6197. for i in elist:
  6198. ilist.append('%sx%d' % (i, elist[i]) if elist[i] > 1 else i)
  6199. line = find_in_html(log, '# wifi ', '\n')
  6200. if line:
  6201. extra['wifi'] = line
  6202. line = find_in_html(log, '# netfix ', '\n')
  6203. if line:
  6204. extra['netfix'] = line
  6205. line = find_in_html(log, '# command ', '\n')
  6206. if line:
  6207. m = re.match(r'.* -m (?P<m>\S*).*', line)
  6208. if m:
  6209. extra['fullmode'] = m.group('m')
  6210. low = find_in_html(html, 'freeze time: <b>', ' ms</b>')
  6211. for lowstr in ['waking', '+']:
  6212. if not low:
  6213. break
  6214. if lowstr not in low:
  6215. continue
  6216. if lowstr == '+':
  6217. issue = 'S2LOOPx%d' % len(low.split('+'))
  6218. else:
  6219. m = re.match(r'.*waking *(?P<n>[0-9]*) *times.*', low)
  6220. issue = 'S2WAKEx%s' % m.group('n') if m else 'S2WAKExNaN'
  6221. match = [i for i in issues if i['match'] == issue]
  6222. if len(match) > 0:
  6223. match[0]['count'] += 1
  6224. if sysvals.hostname not in match[0]['urls']:
  6225. match[0]['urls'][sysvals.hostname] = [sysvals.htmlfile]
  6226. elif sysvals.htmlfile not in match[0]['urls'][sysvals.hostname]:
  6227. match[0]['urls'][sysvals.hostname].append(sysvals.htmlfile)
  6228. else:
  6229. issues.append({
  6230. 'match': issue, 'count': 1, 'line': issue,
  6231. 'urls': {sysvals.hostname: [sysvals.htmlfile]},
  6232. })
  6233. ilist.append(issue)
  6234. # extract device info
  6235. devices = dict()
  6236. for line in html.split('\n'):
  6237. m = re.match(r' *<div id=\"[a,0-9]*\" *title=\"(?P<title>.*)\" class=\"thread.*', line)
  6238. if not m or 'thread kth' in line or 'thread sec' in line:
  6239. continue
  6240. m = re.match(r'(?P<n>.*) \((?P<t>[0-9,\.]*) ms\) (?P<p>.*)', m.group('title'))
  6241. if not m:
  6242. continue
  6243. name, time, phase = m.group('n'), m.group('t'), m.group('p')
  6244. if name == 'async_synchronize_full':
  6245. continue
  6246. if ' async' in name or ' sync' in name:
  6247. name = ' '.join(name.split(' ')[:-1])
  6248. if phase.startswith('suspend'):
  6249. d = 'suspend'
  6250. elif phase.startswith('resume'):
  6251. d = 'resume'
  6252. else:
  6253. continue
  6254. if d not in devices:
  6255. devices[d] = dict()
  6256. if name not in devices[d]:
  6257. devices[d][name] = 0.0
  6258. devices[d][name] += float(time)
  6259. # create worst device info
  6260. worst = dict()
  6261. for d in ['suspend', 'resume']:
  6262. worst[d] = {'name':'', 'time': 0.0}
  6263. dev = devices[d] if d in devices else 0
  6264. if dev and len(dev.keys()) > 0:
  6265. n = sorted(dev, key=lambda k:(dev[k], k), reverse=True)[0]
  6266. worst[d]['name'], worst[d]['time'] = n, dev[n]
  6267. data = {
  6268. 'mode': stmp[2],
  6269. 'host': stmp[0],
  6270. 'kernel': stmp[1],
  6271. 'sysinfo': sysinfo,
  6272. 'time': tstr,
  6273. 'result': result,
  6274. 'issues': ' '.join(ilist),
  6275. 'suspend': suspend,
  6276. 'resume': resume,
  6277. 'devlist': devices,
  6278. 'sus_worst': worst['suspend']['name'],
  6279. 'sus_worsttime': worst['suspend']['time'],
  6280. 'res_worst': worst['resume']['name'],
  6281. 'res_worsttime': worst['resume']['time'],
  6282. 'url': sysvals.htmlfile,
  6283. }
  6284. for key in extra:
  6285. data[key] = extra[key]
  6286. if fulldetail:
  6287. data['funclist'] = find_in_html(html, '<div title="', '" class="traceevent"', False)
  6288. if tp:
  6289. for arg in ['-multi ', '-info ']:
  6290. if arg in tp.cmdline:
  6291. data['target'] = tp.cmdline[tp.cmdline.find(arg):].split()[1]
  6292. break
  6293. return data
  6294. def genHtml(subdir, force=False):
  6295. for dirname, dirnames, filenames in os.walk(subdir):
  6296. sysvals.dmesgfile = sysvals.ftracefile = sysvals.htmlfile = ''
  6297. for filename in filenames:
  6298. file = os.path.join(dirname, filename)
  6299. if sysvals.usable(file):
  6300. if(re.match(r'.*_dmesg.txt', filename)):
  6301. sysvals.dmesgfile = file
  6302. elif(re.match(r'.*_ftrace.txt', filename)):
  6303. sysvals.ftracefile = file
  6304. sysvals.setOutputFile()
  6305. if (sysvals.dmesgfile or sysvals.ftracefile) and sysvals.htmlfile and \
  6306. (force or not sysvals.usable(sysvals.htmlfile, True)):
  6307. pprint('FTRACE: %s' % sysvals.ftracefile)
  6308. if sysvals.dmesgfile:
  6309. pprint('DMESG : %s' % sysvals.dmesgfile)
  6310. rerunTest()
  6311. # Function: runSummary
  6312. # Description:
  6313. # create a summary of tests in a sub-directory
  6314. def runSummary(subdir, local=True, genhtml=False):
  6315. inpath = os.path.abspath(subdir)
  6316. outpath = os.path.abspath('.') if local else inpath
  6317. pprint('Generating a summary of folder:\n %s' % inpath)
  6318. if genhtml:
  6319. genHtml(subdir)
  6320. target, issues, testruns = '', [], []
  6321. desc = {'host':[],'mode':[],'kernel':[]}
  6322. for dirname, dirnames, filenames in os.walk(subdir):
  6323. for filename in filenames:
  6324. if(not re.match(r'.*.html', filename)):
  6325. continue
  6326. data = data_from_html(os.path.join(dirname, filename), outpath, issues)
  6327. if(not data):
  6328. continue
  6329. if 'target' in data:
  6330. target = data['target']
  6331. testruns.append(data)
  6332. for key in desc:
  6333. if data[key] not in desc[key]:
  6334. desc[key].append(data[key])
  6335. pprint('Summary files:')
  6336. if len(desc['host']) == len(desc['mode']) == len(desc['kernel']) == 1:
  6337. title = '%s %s %s' % (desc['host'][0], desc['kernel'][0], desc['mode'][0])
  6338. if target:
  6339. title += ' %s' % target
  6340. else:
  6341. title = inpath
  6342. createHTMLSummarySimple(testruns, os.path.join(outpath, 'summary.html'), title)
  6343. pprint(' summary.html - tabular list of test data found')
  6344. createHTMLDeviceSummary(testruns, os.path.join(outpath, 'summary-devices.html'), title)
  6345. pprint(' summary-devices.html - kernel device list sorted by total execution time')
  6346. createHTMLIssuesSummary(testruns, issues, os.path.join(outpath, 'summary-issues.html'), title)
  6347. pprint(' summary-issues.html - kernel issues found sorted by frequency')
  6348. # Function: checkArgBool
  6349. # Description:
  6350. # check if a boolean string value is true or false
  6351. def checkArgBool(name, value):
  6352. if value in switchvalues:
  6353. if value in switchoff:
  6354. return False
  6355. return True
  6356. doError('invalid boolean --> (%s: %s), use "true/false" or "1/0"' % (name, value), True)
  6357. return False
  6358. # Function: configFromFile
  6359. # Description:
  6360. # Configure the script via the info in a config file
  6361. def configFromFile(file):
  6362. Config = configparser.ConfigParser()
  6363. Config.read(file)
  6364. sections = Config.sections()
  6365. overridekprobes = False
  6366. overridedevkprobes = False
  6367. if 'Settings' in sections:
  6368. for opt in Config.options('Settings'):
  6369. value = Config.get('Settings', opt).lower()
  6370. option = opt.lower()
  6371. if(option == 'verbose'):
  6372. sysvals.verbose = checkArgBool(option, value)
  6373. elif(option == 'addlogs'):
  6374. sysvals.dmesglog = sysvals.ftracelog = checkArgBool(option, value)
  6375. elif(option == 'dev'):
  6376. sysvals.usedevsrc = checkArgBool(option, value)
  6377. elif(option == 'proc'):
  6378. sysvals.useprocmon = checkArgBool(option, value)
  6379. elif(option == 'x2'):
  6380. if checkArgBool(option, value):
  6381. sysvals.execcount = 2
  6382. elif(option == 'callgraph'):
  6383. sysvals.usecallgraph = checkArgBool(option, value)
  6384. elif(option == 'override-timeline-functions'):
  6385. overridekprobes = checkArgBool(option, value)
  6386. elif(option == 'override-dev-timeline-functions'):
  6387. overridedevkprobes = checkArgBool(option, value)
  6388. elif(option == 'skiphtml'):
  6389. sysvals.skiphtml = checkArgBool(option, value)
  6390. elif(option == 'sync'):
  6391. sysvals.sync = checkArgBool(option, value)
  6392. elif(option == 'rs' or option == 'runtimesuspend'):
  6393. if value in switchvalues:
  6394. if value in switchoff:
  6395. sysvals.rs = -1
  6396. else:
  6397. sysvals.rs = 1
  6398. else:
  6399. doError('invalid value --> (%s: %s), use "enable/disable"' % (option, value), True)
  6400. elif(option == 'display'):
  6401. disopt = ['on', 'off', 'standby', 'suspend']
  6402. if value not in disopt:
  6403. doError('invalid value --> (%s: %s), use %s' % (option, value, disopt), True)
  6404. sysvals.display = value
  6405. elif(option == 'gzip'):
  6406. sysvals.gzip = checkArgBool(option, value)
  6407. elif(option == 'cgfilter'):
  6408. sysvals.setCallgraphFilter(value)
  6409. elif(option == 'cgskip'):
  6410. if value in switchoff:
  6411. sysvals.cgskip = ''
  6412. else:
  6413. sysvals.cgskip = sysvals.configFile(val)
  6414. if(not sysvals.cgskip):
  6415. doError('%s does not exist' % sysvals.cgskip)
  6416. elif(option == 'cgtest'):
  6417. sysvals.cgtest = getArgInt('cgtest', value, 0, 1, False)
  6418. elif(option == 'cgphase'):
  6419. d = Data(0)
  6420. if value not in d.phasedef:
  6421. doError('invalid phase --> (%s: %s), valid phases are %s'\
  6422. % (option, value, d.phasedef.keys()), True)
  6423. sysvals.cgphase = value
  6424. elif(option == 'fadd'):
  6425. file = sysvals.configFile(value)
  6426. if(not file):
  6427. doError('%s does not exist' % value)
  6428. sysvals.addFtraceFilterFunctions(file)
  6429. elif(option == 'result'):
  6430. sysvals.result = value
  6431. elif(option == 'multi'):
  6432. nums = value.split()
  6433. if len(nums) != 2:
  6434. doError('multi requires 2 integers (exec_count and delay)', True)
  6435. sysvals.multiinit(nums[0], nums[1])
  6436. elif(option == 'devicefilter'):
  6437. sysvals.setDeviceFilter(value)
  6438. elif(option == 'expandcg'):
  6439. sysvals.cgexp = checkArgBool(option, value)
  6440. elif(option == 'srgap'):
  6441. if checkArgBool(option, value):
  6442. sysvals.srgap = 5
  6443. elif(option == 'mode'):
  6444. sysvals.suspendmode = value
  6445. elif(option == 'command' or option == 'cmd'):
  6446. sysvals.testcommand = value
  6447. elif(option == 'x2delay'):
  6448. sysvals.x2delay = getArgInt('x2delay', value, 0, 60000, False)
  6449. elif(option == 'predelay'):
  6450. sysvals.predelay = getArgInt('predelay', value, 0, 60000, False)
  6451. elif(option == 'postdelay'):
  6452. sysvals.postdelay = getArgInt('postdelay', value, 0, 60000, False)
  6453. elif(option == 'maxdepth'):
  6454. sysvals.max_graph_depth = getArgInt('maxdepth', value, 0, 1000, False)
  6455. elif(option == 'rtcwake'):
  6456. if value in switchoff:
  6457. sysvals.rtcwake = False
  6458. else:
  6459. sysvals.rtcwake = True
  6460. sysvals.rtcwaketime = getArgInt('rtcwake', value, 0, 3600, False)
  6461. elif(option == 'timeprec'):
  6462. sysvals.setPrecision(getArgInt('timeprec', value, 0, 6, False))
  6463. elif(option == 'mindev'):
  6464. sysvals.mindevlen = getArgFloat('mindev', value, 0.0, 10000.0, False)
  6465. elif(option == 'callloop-maxgap'):
  6466. sysvals.callloopmaxgap = getArgFloat('callloop-maxgap', value, 0.0, 1.0, False)
  6467. elif(option == 'callloop-maxlen'):
  6468. sysvals.callloopmaxgap = getArgFloat('callloop-maxlen', value, 0.0, 1.0, False)
  6469. elif(option == 'mincg'):
  6470. sysvals.mincglen = getArgFloat('mincg', value, 0.0, 10000.0, False)
  6471. elif(option == 'bufsize'):
  6472. sysvals.bufsize = getArgInt('bufsize', value, 1, 1024*1024*8, False)
  6473. elif(option == 'output-dir'):
  6474. sysvals.outdir = sysvals.setOutputFolder(value)
  6475. if sysvals.suspendmode == 'command' and not sysvals.testcommand:
  6476. doError('No command supplied for mode "command"')
  6477. # compatibility errors
  6478. if sysvals.usedevsrc and sysvals.usecallgraph:
  6479. doError('-dev is not compatible with -f')
  6480. if sysvals.usecallgraph and sysvals.useprocmon:
  6481. doError('-proc is not compatible with -f')
  6482. if overridekprobes:
  6483. sysvals.tracefuncs = dict()
  6484. if overridedevkprobes:
  6485. sysvals.dev_tracefuncs = dict()
  6486. kprobes = dict()
  6487. kprobesec = 'dev_timeline_functions_'+platform.machine()
  6488. if kprobesec in sections:
  6489. for name in Config.options(kprobesec):
  6490. text = Config.get(kprobesec, name)
  6491. kprobes[name] = (text, True)
  6492. kprobesec = 'timeline_functions_'+platform.machine()
  6493. if kprobesec in sections:
  6494. for name in Config.options(kprobesec):
  6495. if name in kprobes:
  6496. doError('Duplicate timeline function found "%s"' % (name))
  6497. text = Config.get(kprobesec, name)
  6498. kprobes[name] = (text, False)
  6499. for name in kprobes:
  6500. function = name
  6501. format = name
  6502. color = ''
  6503. args = dict()
  6504. text, dev = kprobes[name]
  6505. data = text.split()
  6506. i = 0
  6507. for val in data:
  6508. # bracketted strings are special formatting, read them separately
  6509. if val[0] == '[' and val[-1] == ']':
  6510. for prop in val[1:-1].split(','):
  6511. p = prop.split('=')
  6512. if p[0] == 'color':
  6513. try:
  6514. color = int(p[1], 16)
  6515. color = '#'+p[1]
  6516. except:
  6517. color = p[1]
  6518. continue
  6519. # first real arg should be the format string
  6520. if i == 0:
  6521. format = val
  6522. # all other args are actual function args
  6523. else:
  6524. d = val.split('=')
  6525. args[d[0]] = d[1]
  6526. i += 1
  6527. if not function or not format:
  6528. doError('Invalid kprobe: %s' % name)
  6529. for arg in re.findall('{(?P<n>[a-z,A-Z,0-9]*)}', format):
  6530. if arg not in args:
  6531. doError('Kprobe "%s" is missing argument "%s"' % (name, arg))
  6532. if (dev and name in sysvals.dev_tracefuncs) or (not dev and name in sysvals.tracefuncs):
  6533. doError('Duplicate timeline function found "%s"' % (name))
  6534. kp = {
  6535. 'name': name,
  6536. 'func': function,
  6537. 'format': format,
  6538. sysvals.archargs: args
  6539. }
  6540. if color:
  6541. kp['color'] = color
  6542. if dev:
  6543. sysvals.dev_tracefuncs[name] = kp
  6544. else:
  6545. sysvals.tracefuncs[name] = kp
  6546. # Function: printHelp
  6547. # Description:
  6548. # print out the help text
  6549. def printHelp():
  6550. pprint('\n%s v%s\n'\
  6551. 'Usage: sudo sleepgraph <options> <commands>\n'\
  6552. '\n'\
  6553. 'Description:\n'\
  6554. ' This tool is designed to assist kernel and OS developers in optimizing\n'\
  6555. ' their linux stack\'s suspend/resume time. Using a kernel image built\n'\
  6556. ' with a few extra options enabled, the tool will execute a suspend and\n'\
  6557. ' capture dmesg and ftrace data until resume is complete. This data is\n'\
  6558. ' transformed into a device timeline and an optional callgraph to give\n'\
  6559. ' a detailed view of which devices/subsystems are taking the most\n'\
  6560. ' time in suspend/resume.\n'\
  6561. '\n'\
  6562. ' If no specific command is given, the default behavior is to initiate\n'\
  6563. ' a suspend/resume and capture the dmesg/ftrace output as an html timeline.\n'\
  6564. '\n'\
  6565. ' Generates output files in subdirectory: suspend-yymmdd-HHMMSS\n'\
  6566. ' HTML output: <hostname>_<mode>.html\n'\
  6567. ' raw dmesg output: <hostname>_<mode>_dmesg.txt\n'\
  6568. ' raw ftrace output: <hostname>_<mode>_ftrace.txt\n'\
  6569. '\n'\
  6570. 'Options:\n'\
  6571. ' -h Print this help text\n'\
  6572. ' -v Print the current tool version\n'\
  6573. ' -config fn Pull arguments and config options from file fn\n'\
  6574. ' -verbose Print extra information during execution and analysis\n'\
  6575. ' -m mode Mode to initiate for suspend (default: %s)\n'\
  6576. ' -o name Overrides the output subdirectory name when running a new test\n'\
  6577. ' default: suspend-{date}-{time}\n'\
  6578. ' -rtcwake t Wakeup t seconds after suspend, set t to "off" to disable (default: 15)\n'\
  6579. ' -addlogs Add the dmesg and ftrace logs to the html output\n'\
  6580. ' -noturbostat Dont use turbostat in freeze mode (default: disabled)\n'\
  6581. ' -srgap Add a visible gap in the timeline between sus/res (default: disabled)\n'\
  6582. ' -skiphtml Run the test and capture the trace logs, but skip the timeline (default: disabled)\n'\
  6583. ' -result fn Export a results table to a text file for parsing.\n'\
  6584. ' -wifi If a wifi connection is available, check that it reconnects after resume.\n'\
  6585. ' -wifitrace Trace kernel execution through wifi reconnect.\n'\
  6586. ' -netfix Use netfix to reset the network in the event it fails to resume.\n'\
  6587. ' [testprep]\n'\
  6588. ' -sync Sync the filesystems before starting the test\n'\
  6589. ' -rs on/off Enable/disable runtime suspend for all devices, restore all after test\n'\
  6590. ' -display m Change the display mode to m for the test (on/off/standby/suspend)\n'\
  6591. ' [advanced]\n'\
  6592. ' -gzip Gzip the trace and dmesg logs to save space\n'\
  6593. ' -cmd {s} Run the timeline over a custom command, e.g. "sync -d"\n'\
  6594. ' -proc Add usermode process info into the timeline (default: disabled)\n'\
  6595. ' -dev Add kernel function calls and threads to the timeline (default: disabled)\n'\
  6596. ' -x2 Run two suspend/resumes back to back (default: disabled)\n'\
  6597. ' -x2delay t Include t ms delay between multiple test runs (default: 0 ms)\n'\
  6598. ' -predelay t Include t ms delay before 1st suspend (default: 0 ms)\n'\
  6599. ' -postdelay t Include t ms delay after last resume (default: 0 ms)\n'\
  6600. ' -mindev ms Discard all device blocks shorter than ms milliseconds (e.g. 0.001 for us)\n'\
  6601. ' -multi n d Execute <n> consecutive tests at <d> seconds intervals. If <n> is followed\n'\
  6602. ' by a "d", "h", or "m" execute for <n> days, hours, or mins instead.\n'\
  6603. ' The outputs will be created in a new subdirectory with a summary page.\n'\
  6604. ' -maxfail n Abort a -multi run after n consecutive fails (default is 0 = never abort)\n'\
  6605. ' [debug]\n'\
  6606. ' -f Use ftrace to create device callgraphs (default: disabled)\n'\
  6607. ' -ftop Use ftrace on the top level call: "%s" (default: disabled)\n'\
  6608. ' -maxdepth N limit the callgraph data to N call levels (default: 0=all)\n'\
  6609. ' -expandcg pre-expand the callgraph data in the html output (default: disabled)\n'\
  6610. ' -fadd file Add functions to be graphed in the timeline from a list in a text file\n'\
  6611. ' -filter "d1,d2,..." Filter out all but this comma-delimited list of device names\n'\
  6612. ' -mincg ms Discard all callgraphs shorter than ms milliseconds (e.g. 0.001 for us)\n'\
  6613. ' -cgphase P Only show callgraph data for phase P (e.g. suspend_late)\n'\
  6614. ' -cgtest N Only show callgraph data for test N (e.g. 0 or 1 in an x2 run)\n'\
  6615. ' -timeprec N Number of significant digits in timestamps (0:S, [3:ms], 6:us)\n'\
  6616. ' -cgfilter S Filter the callgraph output in the timeline\n'\
  6617. ' -cgskip file Callgraph functions to skip, off to disable (default: cgskip.txt)\n'\
  6618. ' -bufsize N Set trace buffer size to N kilo-bytes (default: all of free memory)\n'\
  6619. ' -devdump Print out all the raw device data for each phase\n'\
  6620. ' -cgdump Print out all the raw callgraph data\n'\
  6621. '\n'\
  6622. 'Other commands:\n'\
  6623. ' -modes List available suspend modes\n'\
  6624. ' -status Test to see if the system is enabled to run this tool\n'\
  6625. ' -fpdt Print out the contents of the ACPI Firmware Performance Data Table\n'\
  6626. ' -wificheck Print out wifi connection info\n'\
  6627. ' -x<mode> Test xset by toggling the given mode (on/off/standby/suspend)\n'\
  6628. ' -sysinfo Print out system info extracted from BIOS\n'\
  6629. ' -devinfo Print out the pm settings of all devices which support runtime suspend\n'\
  6630. ' -cmdinfo Print out all the platform info collected before and after suspend/resume\n'\
  6631. ' -flist Print the list of functions currently being captured in ftrace\n'\
  6632. ' -flistall Print all functions capable of being captured in ftrace\n'\
  6633. ' -summary dir Create a summary of tests in this dir [-genhtml builds missing html]\n'\
  6634. ' [redo]\n'\
  6635. ' -ftrace ftracefile Create HTML output using ftrace input (used with -dmesg)\n'\
  6636. ' -dmesg dmesgfile Create HTML output using dmesg (used with -ftrace)\n'\
  6637. '' % (sysvals.title, sysvals.version, sysvals.suspendmode, sysvals.ftopfunc))
  6638. return True
  6639. # ----------------- MAIN --------------------
  6640. # exec start (skipped if script is loaded as library)
  6641. if __name__ == '__main__':
  6642. genhtml = False
  6643. cmd = ''
  6644. simplecmds = ['-sysinfo', '-modes', '-fpdt', '-flist', '-flistall',
  6645. '-devinfo', '-status', '-xon', '-xoff', '-xstandby', '-xsuspend',
  6646. '-xinit', '-xreset', '-xstat', '-wificheck', '-cmdinfo']
  6647. if '-f' in sys.argv:
  6648. sysvals.cgskip = sysvals.configFile('cgskip.txt')
  6649. # loop through the command line arguments
  6650. args = iter(sys.argv[1:])
  6651. for arg in args:
  6652. if(arg == '-m'):
  6653. try:
  6654. val = next(args)
  6655. except:
  6656. doError('No mode supplied', True)
  6657. if val == 'command' and not sysvals.testcommand:
  6658. doError('No command supplied for mode "command"', True)
  6659. sysvals.suspendmode = val
  6660. elif(arg in simplecmds):
  6661. cmd = arg[1:]
  6662. elif(arg == '-h'):
  6663. printHelp()
  6664. sys.exit(0)
  6665. elif(arg == '-v'):
  6666. pprint("Version %s" % sysvals.version)
  6667. sys.exit(0)
  6668. elif(arg == '-debugtiming'):
  6669. debugtiming = True
  6670. elif(arg == '-x2'):
  6671. sysvals.execcount = 2
  6672. elif(arg == '-x2delay'):
  6673. sysvals.x2delay = getArgInt('-x2delay', args, 0, 60000)
  6674. elif(arg == '-predelay'):
  6675. sysvals.predelay = getArgInt('-predelay', args, 0, 60000)
  6676. elif(arg == '-postdelay'):
  6677. sysvals.postdelay = getArgInt('-postdelay', args, 0, 60000)
  6678. elif(arg == '-f'):
  6679. sysvals.usecallgraph = True
  6680. elif(arg == '-ftop'):
  6681. sysvals.usecallgraph = True
  6682. sysvals.ftop = True
  6683. sysvals.usekprobes = False
  6684. elif(arg == '-skiphtml'):
  6685. sysvals.skiphtml = True
  6686. elif(arg == '-cgdump'):
  6687. sysvals.cgdump = True
  6688. elif(arg == '-devdump'):
  6689. sysvals.devdump = True
  6690. elif(arg == '-genhtml'):
  6691. genhtml = True
  6692. elif(arg == '-addlogs'):
  6693. sysvals.dmesglog = sysvals.ftracelog = True
  6694. elif(arg == '-nologs'):
  6695. sysvals.dmesglog = sysvals.ftracelog = False
  6696. elif(arg == '-addlogdmesg'):
  6697. sysvals.dmesglog = True
  6698. elif(arg == '-addlogftrace'):
  6699. sysvals.ftracelog = True
  6700. elif(arg == '-noturbostat'):
  6701. sysvals.tstat = False
  6702. elif(arg == '-verbose'):
  6703. sysvals.verbose = True
  6704. elif(arg == '-proc'):
  6705. sysvals.useprocmon = True
  6706. elif(arg == '-dev'):
  6707. sysvals.usedevsrc = True
  6708. elif(arg == '-sync'):
  6709. sysvals.sync = True
  6710. elif(arg == '-wifi'):
  6711. sysvals.wifi = True
  6712. elif(arg == '-wifitrace'):
  6713. sysvals.wifitrace = True
  6714. elif(arg == '-netfix'):
  6715. sysvals.netfix = True
  6716. elif(arg == '-gzip'):
  6717. sysvals.gzip = True
  6718. elif(arg == '-info'):
  6719. try:
  6720. val = next(args)
  6721. except:
  6722. doError('-info requires one string argument', True)
  6723. elif(arg == '-desc'):
  6724. try:
  6725. val = next(args)
  6726. except:
  6727. doError('-desc requires one string argument', True)
  6728. elif(arg == '-rs'):
  6729. try:
  6730. val = next(args)
  6731. except:
  6732. doError('-rs requires "enable" or "disable"', True)
  6733. if val.lower() in switchvalues:
  6734. if val.lower() in switchoff:
  6735. sysvals.rs = -1
  6736. else:
  6737. sysvals.rs = 1
  6738. else:
  6739. doError('invalid option: %s, use "enable/disable" or "on/off"' % val, True)
  6740. elif(arg == '-display'):
  6741. try:
  6742. val = next(args)
  6743. except:
  6744. doError('-display requires an mode value', True)
  6745. disopt = ['on', 'off', 'standby', 'suspend']
  6746. if val.lower() not in disopt:
  6747. doError('valid display mode values are %s' % disopt, True)
  6748. sysvals.display = val.lower()
  6749. elif(arg == '-maxdepth'):
  6750. sysvals.max_graph_depth = getArgInt('-maxdepth', args, 0, 1000)
  6751. elif(arg == '-rtcwake'):
  6752. try:
  6753. val = next(args)
  6754. except:
  6755. doError('No rtcwake time supplied', True)
  6756. if val.lower() in switchoff:
  6757. sysvals.rtcwake = False
  6758. else:
  6759. sysvals.rtcwake = True
  6760. sysvals.rtcwaketime = getArgInt('-rtcwake', val, 0, 3600, False)
  6761. elif(arg == '-timeprec'):
  6762. sysvals.setPrecision(getArgInt('-timeprec', args, 0, 6))
  6763. elif(arg == '-mindev'):
  6764. sysvals.mindevlen = getArgFloat('-mindev', args, 0.0, 10000.0)
  6765. elif(arg == '-mincg'):
  6766. sysvals.mincglen = getArgFloat('-mincg', args, 0.0, 10000.0)
  6767. elif(arg == '-bufsize'):
  6768. sysvals.bufsize = getArgInt('-bufsize', args, 1, 1024*1024*8)
  6769. elif(arg == '-cgtest'):
  6770. sysvals.cgtest = getArgInt('-cgtest', args, 0, 1)
  6771. elif(arg == '-cgphase'):
  6772. try:
  6773. val = next(args)
  6774. except:
  6775. doError('No phase name supplied', True)
  6776. d = Data(0)
  6777. if val not in d.phasedef:
  6778. doError('invalid phase --> (%s: %s), valid phases are %s'\
  6779. % (arg, val, d.phasedef.keys()), True)
  6780. sysvals.cgphase = val
  6781. elif(arg == '-cgfilter'):
  6782. try:
  6783. val = next(args)
  6784. except:
  6785. doError('No callgraph functions supplied', True)
  6786. sysvals.setCallgraphFilter(val)
  6787. elif(arg == '-skipkprobe'):
  6788. try:
  6789. val = next(args)
  6790. except:
  6791. doError('No kprobe functions supplied', True)
  6792. sysvals.skipKprobes(val)
  6793. elif(arg == '-cgskip'):
  6794. try:
  6795. val = next(args)
  6796. except:
  6797. doError('No file supplied', True)
  6798. if val.lower() in switchoff:
  6799. sysvals.cgskip = ''
  6800. else:
  6801. sysvals.cgskip = sysvals.configFile(val)
  6802. if(not sysvals.cgskip):
  6803. doError('%s does not exist' % sysvals.cgskip)
  6804. elif(arg == '-callloop-maxgap'):
  6805. sysvals.callloopmaxgap = getArgFloat('-callloop-maxgap', args, 0.0, 1.0)
  6806. elif(arg == '-callloop-maxlen'):
  6807. sysvals.callloopmaxlen = getArgFloat('-callloop-maxlen', args, 0.0, 1.0)
  6808. elif(arg == '-cmd'):
  6809. try:
  6810. val = next(args)
  6811. except:
  6812. doError('No command string supplied', True)
  6813. sysvals.testcommand = val
  6814. sysvals.suspendmode = 'command'
  6815. elif(arg == '-expandcg'):
  6816. sysvals.cgexp = True
  6817. elif(arg == '-srgap'):
  6818. sysvals.srgap = 5
  6819. elif(arg == '-maxfail'):
  6820. sysvals.maxfail = getArgInt('-maxfail', args, 0, 1000000)
  6821. elif(arg == '-multi'):
  6822. try:
  6823. c, d = next(args), next(args)
  6824. except:
  6825. doError('-multi requires two values', True)
  6826. sysvals.multiinit(c, d)
  6827. elif(arg == '-o'):
  6828. try:
  6829. val = next(args)
  6830. except:
  6831. doError('No subdirectory name supplied', True)
  6832. sysvals.outdir = sysvals.setOutputFolder(val)
  6833. elif(arg == '-config'):
  6834. try:
  6835. val = next(args)
  6836. except:
  6837. doError('No text file supplied', True)
  6838. file = sysvals.configFile(val)
  6839. if(not file):
  6840. doError('%s does not exist' % val)
  6841. configFromFile(file)
  6842. elif(arg == '-fadd'):
  6843. try:
  6844. val = next(args)
  6845. except:
  6846. doError('No text file supplied', True)
  6847. file = sysvals.configFile(val)
  6848. if(not file):
  6849. doError('%s does not exist' % val)
  6850. sysvals.addFtraceFilterFunctions(file)
  6851. elif(arg == '-dmesg'):
  6852. try:
  6853. val = next(args)
  6854. except:
  6855. doError('No dmesg file supplied', True)
  6856. sysvals.notestrun = True
  6857. sysvals.dmesgfile = val
  6858. if(os.path.exists(sysvals.dmesgfile) == False):
  6859. doError('%s does not exist' % sysvals.dmesgfile)
  6860. elif(arg == '-ftrace'):
  6861. try:
  6862. val = next(args)
  6863. except:
  6864. doError('No ftrace file supplied', True)
  6865. sysvals.notestrun = True
  6866. sysvals.ftracefile = val
  6867. if(os.path.exists(sysvals.ftracefile) == False):
  6868. doError('%s does not exist' % sysvals.ftracefile)
  6869. elif(arg == '-summary'):
  6870. try:
  6871. val = next(args)
  6872. except:
  6873. doError('No directory supplied', True)
  6874. cmd = 'summary'
  6875. sysvals.outdir = val
  6876. sysvals.notestrun = True
  6877. if(os.path.isdir(val) == False):
  6878. doError('%s is not accesible' % val)
  6879. elif(arg == '-filter'):
  6880. try:
  6881. val = next(args)
  6882. except:
  6883. doError('No devnames supplied', True)
  6884. sysvals.setDeviceFilter(val)
  6885. elif(arg == '-result'):
  6886. try:
  6887. val = next(args)
  6888. except:
  6889. doError('No result file supplied', True)
  6890. sysvals.result = val
  6891. sysvals.signalHandlerInit()
  6892. else:
  6893. doError('Invalid argument: '+arg, True)
  6894. # compatibility errors
  6895. if(sysvals.usecallgraph and sysvals.usedevsrc):
  6896. doError('-dev is not compatible with -f')
  6897. if(sysvals.usecallgraph and sysvals.useprocmon):
  6898. doError('-proc is not compatible with -f')
  6899. if sysvals.usecallgraph and sysvals.cgskip:
  6900. sysvals.vprint('Using cgskip file: %s' % sysvals.cgskip)
  6901. sysvals.setCallgraphBlacklist(sysvals.cgskip)
  6902. # callgraph size cannot exceed device size
  6903. if sysvals.mincglen < sysvals.mindevlen:
  6904. sysvals.mincglen = sysvals.mindevlen
  6905. # remove existing buffers before calculating memory
  6906. if(sysvals.usecallgraph or sysvals.usedevsrc):
  6907. sysvals.fsetVal('16', 'buffer_size_kb')
  6908. sysvals.cpuInfo()
  6909. # just run a utility command and exit
  6910. if(cmd != ''):
  6911. ret = 0
  6912. if(cmd == 'status'):
  6913. if not statusCheck(True):
  6914. ret = 1
  6915. elif(cmd == 'fpdt'):
  6916. if not getFPDT(True):
  6917. ret = 1
  6918. elif(cmd == 'sysinfo'):
  6919. sysvals.printSystemInfo(True)
  6920. elif(cmd == 'devinfo'):
  6921. deviceInfo()
  6922. elif(cmd == 'modes'):
  6923. pprint(getModes())
  6924. elif(cmd == 'flist'):
  6925. sysvals.getFtraceFilterFunctions(True)
  6926. elif(cmd == 'flistall'):
  6927. sysvals.getFtraceFilterFunctions(False)
  6928. elif(cmd == 'summary'):
  6929. runSummary(sysvals.outdir, True, genhtml)
  6930. elif(cmd in ['xon', 'xoff', 'xstandby', 'xsuspend', 'xinit', 'xreset']):
  6931. sysvals.verbose = True
  6932. ret = sysvals.displayControl(cmd[1:])
  6933. elif(cmd == 'xstat'):
  6934. pprint('Display Status: %s' % sysvals.displayControl('stat').upper())
  6935. elif(cmd == 'wificheck'):
  6936. dev = sysvals.checkWifi()
  6937. if dev:
  6938. print('%s is connected' % sysvals.wifiDetails(dev))
  6939. else:
  6940. print('No wifi connection found')
  6941. elif(cmd == 'cmdinfo'):
  6942. for out in sysvals.cmdinfo(False, True):
  6943. print('[%s - %s]\n%s\n' % out)
  6944. sys.exit(ret)
  6945. # if instructed, re-analyze existing data files
  6946. if(sysvals.notestrun):
  6947. stamp = rerunTest(sysvals.outdir)
  6948. sysvals.outputResult(stamp)
  6949. sys.exit(0)
  6950. # verify that we can run a test
  6951. error = statusCheck()
  6952. if(error):
  6953. doError(error)
  6954. # extract mem/disk extra modes and convert
  6955. mode = sysvals.suspendmode
  6956. if mode.startswith('mem'):
  6957. memmode = mode.split('-', 1)[-1] if '-' in mode else 'deep'
  6958. if memmode == 'shallow':
  6959. mode = 'standby'
  6960. elif memmode == 's2idle':
  6961. mode = 'freeze'
  6962. else:
  6963. mode = 'mem'
  6964. sysvals.memmode = memmode
  6965. sysvals.suspendmode = mode
  6966. if mode.startswith('disk-'):
  6967. sysvals.diskmode = mode.split('-', 1)[-1]
  6968. sysvals.suspendmode = 'disk'
  6969. sysvals.systemInfo(dmidecode(sysvals.mempath))
  6970. failcnt, ret = 0, 0
  6971. if sysvals.multitest['run']:
  6972. # run multiple tests in a separate subdirectory
  6973. if not sysvals.outdir:
  6974. if 'time' in sysvals.multitest:
  6975. s = '-%dm' % sysvals.multitest['time']
  6976. else:
  6977. s = '-x%d' % sysvals.multitest['count']
  6978. sysvals.outdir = datetime.now().strftime('suspend-%y%m%d-%H%M%S'+s)
  6979. if not os.path.isdir(sysvals.outdir):
  6980. os.makedirs(sysvals.outdir)
  6981. sysvals.sudoUserchown(sysvals.outdir)
  6982. finish = datetime.now()
  6983. if 'time' in sysvals.multitest:
  6984. finish += timedelta(minutes=sysvals.multitest['time'])
  6985. for i in range(sysvals.multitest['count']):
  6986. sysvals.multistat(True, i, finish)
  6987. if i != 0 and sysvals.multitest['delay'] > 0:
  6988. pprint('Waiting %d seconds...' % (sysvals.multitest['delay']))
  6989. time.sleep(sysvals.multitest['delay'])
  6990. fmt = 'suspend-%y%m%d-%H%M%S'
  6991. sysvals.testdir = os.path.join(sysvals.outdir, datetime.now().strftime(fmt))
  6992. ret = runTest(i+1, not sysvals.verbose)
  6993. failcnt = 0 if not ret else failcnt + 1
  6994. if sysvals.maxfail > 0 and failcnt >= sysvals.maxfail:
  6995. pprint('Maximum fail count of %d reached, aborting multitest' % (sysvals.maxfail))
  6996. break
  6997. sysvals.resetlog()
  6998. sysvals.multistat(False, i, finish)
  6999. if 'time' in sysvals.multitest and datetime.now() >= finish:
  7000. break
  7001. if not sysvals.skiphtml:
  7002. runSummary(sysvals.outdir, False, False)
  7003. sysvals.sudoUserchown(sysvals.outdir)
  7004. else:
  7005. if sysvals.outdir:
  7006. sysvals.testdir = sysvals.outdir
  7007. # run the test in the current directory
  7008. ret = runTest()
  7009. # reset to default values after testing
  7010. if sysvals.display:
  7011. sysvals.displayControl('reset')
  7012. if sysvals.rs != 0:
  7013. sysvals.setRuntimeSuspend(False)
  7014. sys.exit(ret)