sleepgraph.py 190 KB

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