sleepgraph.py 234 KB

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