analyze_suspend.py 157 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899
  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. # You should have received a copy of the GNU General Public License along with
  16. # this program; if not, write to the Free Software Foundation, Inc.,
  17. # 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
  18. #
  19. # Authors:
  20. # Todd Brandt <todd.e.brandt@linux.intel.com>
  21. #
  22. # Links:
  23. # Home Page
  24. # https://01.org/suspendresume
  25. # Source repo
  26. # https://github.com/01org/suspendresume
  27. # Documentation
  28. # Getting Started
  29. # https://01.org/suspendresume/documentation/getting-started
  30. # Command List:
  31. # https://01.org/suspendresume/documentation/command-list
  32. #
  33. # Description:
  34. # This tool is designed to assist kernel and OS developers in optimizing
  35. # their linux stack's suspend/resume time. Using a kernel image built
  36. # with a few extra options enabled, the tool will execute a suspend and
  37. # will capture dmesg and ftrace data until resume is complete. This data
  38. # is transformed into a device timeline and a callgraph to give a quick
  39. # and detailed view of which devices and callbacks are taking the most
  40. # time in suspend/resume. The output is a single html file which can be
  41. # viewed in firefox or chrome.
  42. #
  43. # The following kernel build options are required:
  44. # CONFIG_PM_DEBUG=y
  45. # CONFIG_PM_SLEEP_DEBUG=y
  46. # CONFIG_FTRACE=y
  47. # CONFIG_FUNCTION_TRACER=y
  48. # CONFIG_FUNCTION_GRAPH_TRACER=y
  49. # CONFIG_KPROBES=y
  50. # CONFIG_KPROBES_ON_FTRACE=y
  51. #
  52. # For kernel versions older than 3.15:
  53. # The following additional kernel parameters are required:
  54. # (e.g. in file /etc/default/grub)
  55. # GRUB_CMDLINE_LINUX_DEFAULT="... initcall_debug log_buf_len=16M ..."
  56. #
  57. # ----------------- LIBRARIES --------------------
  58. import sys
  59. import time
  60. import os
  61. import string
  62. import re
  63. import platform
  64. from datetime import datetime
  65. import struct
  66. import ConfigParser
  67. # ----------------- CLASSES --------------------
  68. # Class: SystemValues
  69. # Description:
  70. # A global, single-instance container used to
  71. # store system values and test parameters
  72. class SystemValues:
  73. ansi = False
  74. version = '4.2'
  75. verbose = False
  76. addlogs = False
  77. mindevlen = 0.001
  78. mincglen = 1.0
  79. srgap = 0
  80. cgexp = False
  81. outdir = ''
  82. testdir = '.'
  83. tpath = '/sys/kernel/debug/tracing/'
  84. fpdtpath = '/sys/firmware/acpi/tables/FPDT'
  85. epath = '/sys/kernel/debug/tracing/events/power/'
  86. traceevents = [
  87. 'suspend_resume',
  88. 'device_pm_callback_end',
  89. 'device_pm_callback_start'
  90. ]
  91. testcommand = ''
  92. mempath = '/dev/mem'
  93. powerfile = '/sys/power/state'
  94. suspendmode = 'mem'
  95. hostname = 'localhost'
  96. prefix = 'test'
  97. teststamp = ''
  98. dmesgstart = 0.0
  99. dmesgfile = ''
  100. ftracefile = ''
  101. htmlfile = ''
  102. embedded = False
  103. rtcwake = False
  104. rtcwaketime = 10
  105. rtcpath = ''
  106. devicefilter = []
  107. stamp = 0
  108. execcount = 1
  109. x2delay = 0
  110. usecallgraph = False
  111. usetraceevents = False
  112. usetraceeventsonly = False
  113. usetracemarkers = True
  114. usekprobes = True
  115. usedevsrc = False
  116. notestrun = False
  117. devprops = dict()
  118. postresumetime = 0
  119. devpropfmt = '# Device Properties: .*'
  120. tracertypefmt = '# tracer: (?P<t>.*)'
  121. firmwarefmt = '# fwsuspend (?P<s>[0-9]*) fwresume (?P<r>[0-9]*)$'
  122. postresumefmt = '# post resume time (?P<t>[0-9]*)$'
  123. stampfmt = '# suspend-(?P<m>[0-9]{2})(?P<d>[0-9]{2})(?P<y>[0-9]{2})-'+\
  124. '(?P<H>[0-9]{2})(?P<M>[0-9]{2})(?P<S>[0-9]{2})'+\
  125. ' (?P<host>.*) (?P<mode>.*) (?P<kernel>.*)$'
  126. kprobecolor = 'rgba(204,204,204,0.5)'
  127. synccolor = 'rgba(204,204,204,0.5)'
  128. debugfuncs = []
  129. tracefuncs = {
  130. 'sys_sync': dict(),
  131. 'pm_prepare_console': dict(),
  132. 'pm_notifier_call_chain': dict(),
  133. 'freeze_processes': dict(),
  134. 'freeze_kernel_threads': dict(),
  135. 'pm_restrict_gfp_mask': dict(),
  136. 'acpi_suspend_begin': dict(),
  137. 'suspend_console': dict(),
  138. 'acpi_pm_prepare': dict(),
  139. 'syscore_suspend': dict(),
  140. 'arch_enable_nonboot_cpus_end': dict(),
  141. 'syscore_resume': dict(),
  142. 'acpi_pm_finish': dict(),
  143. 'resume_console': dict(),
  144. 'acpi_pm_end': dict(),
  145. 'pm_restore_gfp_mask': dict(),
  146. 'thaw_processes': dict(),
  147. 'pm_restore_console': dict(),
  148. 'CPU_OFF': {
  149. 'func':'_cpu_down',
  150. 'args_x86_64': {'cpu':'%di:s32'},
  151. 'format': 'CPU_OFF[{cpu}]',
  152. 'mask': 'CPU_.*_DOWN'
  153. },
  154. 'CPU_ON': {
  155. 'func':'_cpu_up',
  156. 'args_x86_64': {'cpu':'%di:s32'},
  157. 'format': 'CPU_ON[{cpu}]',
  158. 'mask': 'CPU_.*_UP'
  159. },
  160. }
  161. dev_tracefuncs = {
  162. # general wait/delay/sleep
  163. 'msleep': { 'args_x86_64': {'time':'%di:s32'} },
  164. 'udelay': { 'func':'__const_udelay', 'args_x86_64': {'loops':'%di:s32'} },
  165. 'acpi_os_stall': dict(),
  166. # ACPI
  167. 'acpi_resume_power_resources': dict(),
  168. 'acpi_ps_parse_aml': dict(),
  169. # filesystem
  170. 'ext4_sync_fs': dict(),
  171. # ATA
  172. 'ata_eh_recover': { 'args_x86_64': {'port':'+36(%di):s32'} },
  173. # i915
  174. 'i915_gem_restore_gtt_mappings': dict(),
  175. 'intel_opregion_setup': dict(),
  176. 'intel_dp_detect': dict(),
  177. 'intel_hdmi_detect': dict(),
  178. 'intel_opregion_init': dict(),
  179. }
  180. kprobes_postresume = [
  181. {
  182. 'name': 'ataportrst',
  183. 'func': 'ata_eh_recover',
  184. 'args': {'port':'+36(%di):s32'},
  185. 'format': 'ata{port}_port_reset',
  186. 'mask': 'ata.*_port_reset'
  187. }
  188. ]
  189. kprobes = dict()
  190. timeformat = '%.3f'
  191. def __init__(self):
  192. # if this is a phoronix test run, set some default options
  193. if('LOG_FILE' in os.environ and 'TEST_RESULTS_IDENTIFIER' in os.environ):
  194. self.embedded = True
  195. self.addlogs = True
  196. self.htmlfile = os.environ['LOG_FILE']
  197. self.hostname = platform.node()
  198. if(self.hostname == ''):
  199. self.hostname = 'localhost'
  200. rtc = "rtc0"
  201. if os.path.exists('/dev/rtc'):
  202. rtc = os.readlink('/dev/rtc')
  203. rtc = '/sys/class/rtc/'+rtc
  204. if os.path.exists(rtc) and os.path.exists(rtc+'/date') and \
  205. os.path.exists(rtc+'/time') and os.path.exists(rtc+'/wakealarm'):
  206. self.rtcpath = rtc
  207. if (hasattr(sys.stdout, 'isatty') and sys.stdout.isatty()):
  208. self.ansi = True
  209. def setPrecision(self, num):
  210. if num < 0 or num > 6:
  211. return
  212. self.timeformat = '%.{0}f'.format(num)
  213. def setOutputFile(self):
  214. if((self.htmlfile == '') and (self.dmesgfile != '')):
  215. m = re.match('(?P<name>.*)_dmesg\.txt$', self.dmesgfile)
  216. if(m):
  217. self.htmlfile = m.group('name')+'.html'
  218. if((self.htmlfile == '') and (self.ftracefile != '')):
  219. m = re.match('(?P<name>.*)_ftrace\.txt$', self.ftracefile)
  220. if(m):
  221. self.htmlfile = m.group('name')+'.html'
  222. if(self.htmlfile == ''):
  223. self.htmlfile = 'output.html'
  224. def initTestOutput(self, subdir, testpath=''):
  225. self.prefix = self.hostname
  226. v = open('/proc/version', 'r').read().strip()
  227. kver = string.split(v)[2]
  228. n = datetime.now()
  229. testtime = n.strftime('suspend-%m%d%y-%H%M%S')
  230. if not testpath:
  231. testpath = n.strftime('suspend-%y%m%d-%H%M%S')
  232. if(subdir != "."):
  233. self.testdir = subdir+"/"+testpath
  234. else:
  235. self.testdir = testpath
  236. self.teststamp = \
  237. '# '+testtime+' '+self.prefix+' '+self.suspendmode+' '+kver
  238. if(self.embedded):
  239. self.dmesgfile = \
  240. '/tmp/'+testtime+'_'+self.suspendmode+'_dmesg.txt'
  241. self.ftracefile = \
  242. '/tmp/'+testtime+'_'+self.suspendmode+'_ftrace.txt'
  243. return
  244. self.dmesgfile = \
  245. self.testdir+'/'+self.prefix+'_'+self.suspendmode+'_dmesg.txt'
  246. self.ftracefile = \
  247. self.testdir+'/'+self.prefix+'_'+self.suspendmode+'_ftrace.txt'
  248. self.htmlfile = \
  249. self.testdir+'/'+self.prefix+'_'+self.suspendmode+'.html'
  250. if not os.path.isdir(self.testdir):
  251. os.mkdir(self.testdir)
  252. def setDeviceFilter(self, devnames):
  253. self.devicefilter = string.split(devnames)
  254. def rtcWakeAlarmOn(self):
  255. os.system('echo 0 > '+self.rtcpath+'/wakealarm')
  256. outD = open(self.rtcpath+'/date', 'r').read().strip()
  257. outT = open(self.rtcpath+'/time', 'r').read().strip()
  258. mD = re.match('^(?P<y>[0-9]*)-(?P<m>[0-9]*)-(?P<d>[0-9]*)', outD)
  259. mT = re.match('^(?P<h>[0-9]*):(?P<m>[0-9]*):(?P<s>[0-9]*)', outT)
  260. if(mD and mT):
  261. # get the current time from hardware
  262. utcoffset = int((datetime.now() - datetime.utcnow()).total_seconds())
  263. dt = datetime(\
  264. int(mD.group('y')), int(mD.group('m')), int(mD.group('d')),
  265. int(mT.group('h')), int(mT.group('m')), int(mT.group('s')))
  266. nowtime = int(dt.strftime('%s')) + utcoffset
  267. else:
  268. # if hardware time fails, use the software time
  269. nowtime = int(datetime.now().strftime('%s'))
  270. alarm = nowtime + self.rtcwaketime
  271. os.system('echo %d > %s/wakealarm' % (alarm, self.rtcpath))
  272. def rtcWakeAlarmOff(self):
  273. os.system('echo 0 > %s/wakealarm' % self.rtcpath)
  274. def initdmesg(self):
  275. # get the latest time stamp from the dmesg log
  276. fp = os.popen('dmesg')
  277. ktime = '0'
  278. for line in fp:
  279. line = line.replace('\r\n', '')
  280. idx = line.find('[')
  281. if idx > 1:
  282. line = line[idx:]
  283. m = re.match('[ \t]*(\[ *)(?P<ktime>[0-9\.]*)(\]) (?P<msg>.*)', line)
  284. if(m):
  285. ktime = m.group('ktime')
  286. fp.close()
  287. self.dmesgstart = float(ktime)
  288. def getdmesg(self):
  289. # store all new dmesg lines since initdmesg was called
  290. fp = os.popen('dmesg')
  291. op = open(self.dmesgfile, 'a')
  292. for line in fp:
  293. line = line.replace('\r\n', '')
  294. idx = line.find('[')
  295. if idx > 1:
  296. line = line[idx:]
  297. m = re.match('[ \t]*(\[ *)(?P<ktime>[0-9\.]*)(\]) (?P<msg>.*)', line)
  298. if(not m):
  299. continue
  300. ktime = float(m.group('ktime'))
  301. if ktime > self.dmesgstart:
  302. op.write(line)
  303. fp.close()
  304. op.close()
  305. def addFtraceFilterFunctions(self, file):
  306. fp = open(file)
  307. list = fp.read().split('\n')
  308. fp.close()
  309. for i in list:
  310. if len(i) < 2:
  311. continue
  312. self.tracefuncs[i] = dict()
  313. def getFtraceFilterFunctions(self, current):
  314. rootCheck(True)
  315. if not current:
  316. os.system('cat '+self.tpath+'available_filter_functions')
  317. return
  318. fp = open(self.tpath+'available_filter_functions')
  319. master = fp.read().split('\n')
  320. fp.close()
  321. if len(self.debugfuncs) > 0:
  322. for i in self.debugfuncs:
  323. if i in master:
  324. print i
  325. else:
  326. print self.colorText(i)
  327. else:
  328. for i in self.tracefuncs:
  329. if 'func' in self.tracefuncs[i]:
  330. i = self.tracefuncs[i]['func']
  331. if i in master:
  332. print i
  333. else:
  334. print self.colorText(i)
  335. def setFtraceFilterFunctions(self, list):
  336. fp = open(self.tpath+'available_filter_functions')
  337. master = fp.read().split('\n')
  338. fp.close()
  339. flist = ''
  340. for i in list:
  341. if i not in master:
  342. continue
  343. if ' [' in i:
  344. flist += i.split(' ')[0]+'\n'
  345. else:
  346. flist += i+'\n'
  347. fp = open(self.tpath+'set_graph_function', 'w')
  348. fp.write(flist)
  349. fp.close()
  350. def kprobeMatch(self, name, target):
  351. if name not in self.kprobes:
  352. return False
  353. if re.match(self.kprobes[name]['mask'], target):
  354. return True
  355. return False
  356. def basicKprobe(self, name):
  357. self.kprobes[name] = {'name': name,'func': name,'args': dict(),'format': name,'mask': name}
  358. def defaultKprobe(self, name, kdata):
  359. k = kdata
  360. for field in ['name', 'format', 'mask', 'func']:
  361. if field not in k:
  362. k[field] = name
  363. archargs = 'args_'+platform.machine()
  364. if archargs in k:
  365. k['args'] = k[archargs]
  366. else:
  367. k['args'] = dict()
  368. k['format'] = name
  369. self.kprobes[name] = k
  370. def kprobeColor(self, name):
  371. if name not in self.kprobes or 'color' not in self.kprobes[name]:
  372. return ''
  373. return self.kprobes[name]['color']
  374. def kprobeDisplayName(self, name, dataraw):
  375. if name not in self.kprobes:
  376. self.basicKprobe(name)
  377. data = ''
  378. quote=0
  379. # first remvoe any spaces inside quotes, and the quotes
  380. for c in dataraw:
  381. if c == '"':
  382. quote = (quote + 1) % 2
  383. if quote and c == ' ':
  384. data += '_'
  385. elif c != '"':
  386. data += c
  387. fmt, args = self.kprobes[name]['format'], self.kprobes[name]['args']
  388. arglist = dict()
  389. # now process the args
  390. for arg in sorted(args):
  391. arglist[arg] = ''
  392. m = re.match('.* '+arg+'=(?P<arg>.*) ', data);
  393. if m:
  394. arglist[arg] = m.group('arg')
  395. else:
  396. m = re.match('.* '+arg+'=(?P<arg>.*)', data);
  397. if m:
  398. arglist[arg] = m.group('arg')
  399. out = fmt.format(**arglist)
  400. out = out.replace(' ', '_').replace('"', '')
  401. return out
  402. def kprobeText(self, kprobe):
  403. name, fmt, func, args = kprobe['name'], kprobe['format'], kprobe['func'], kprobe['args']
  404. if re.findall('{(?P<n>[a-z,A-Z,0-9]*)}', func):
  405. doError('Kprobe "%s" has format info in the function name "%s"' % (name, func), False)
  406. for arg in re.findall('{(?P<n>[a-z,A-Z,0-9]*)}', fmt):
  407. if arg not in args:
  408. doError('Kprobe "%s" is missing argument "%s"' % (name, arg), False)
  409. val = 'p:%s_cal %s' % (name, func)
  410. for i in sorted(args):
  411. val += ' %s=%s' % (i, args[i])
  412. val += '\nr:%s_ret %s $retval\n' % (name, func)
  413. return val
  414. def addKprobes(self):
  415. # first test each kprobe
  416. print('INITIALIZING KPROBES...')
  417. rejects = []
  418. for name in sorted(self.kprobes):
  419. if not self.testKprobe(self.kprobes[name]):
  420. rejects.append(name)
  421. # remove all failed ones from the list
  422. for name in rejects:
  423. vprint('Skipping KPROBE: %s' % name)
  424. self.kprobes.pop(name)
  425. self.fsetVal('', 'kprobe_events')
  426. kprobeevents = ''
  427. # set the kprobes all at once
  428. for kp in self.kprobes:
  429. val = self.kprobeText(self.kprobes[kp])
  430. vprint('Adding KPROBE: %s\n%s' % (kp, val.strip()))
  431. kprobeevents += self.kprobeText(self.kprobes[kp])
  432. self.fsetVal(kprobeevents, 'kprobe_events')
  433. # verify that the kprobes were set as ordered
  434. check = self.fgetVal('kprobe_events')
  435. linesout = len(kprobeevents.split('\n'))
  436. linesack = len(check.split('\n'))
  437. if linesack < linesout:
  438. # if not, try appending the kprobes 1 by 1
  439. for kp in self.kprobes:
  440. kprobeevents = self.kprobeText(self.kprobes[kp])
  441. self.fsetVal(kprobeevents, 'kprobe_events', 'a')
  442. self.fsetVal('1', 'events/kprobes/enable')
  443. def testKprobe(self, kprobe):
  444. kprobeevents = self.kprobeText(kprobe)
  445. if not kprobeevents:
  446. return False
  447. try:
  448. self.fsetVal(kprobeevents, 'kprobe_events')
  449. check = self.fgetVal('kprobe_events')
  450. except:
  451. return False
  452. linesout = len(kprobeevents.split('\n'))
  453. linesack = len(check.split('\n'))
  454. if linesack < linesout:
  455. return False
  456. return True
  457. def fsetVal(self, val, path, mode='w'):
  458. file = self.tpath+path
  459. if not os.path.exists(file):
  460. return False
  461. try:
  462. fp = open(file, mode)
  463. fp.write(val)
  464. fp.close()
  465. except:
  466. pass
  467. return True
  468. def fgetVal(self, path):
  469. file = self.tpath+path
  470. res = ''
  471. if not os.path.exists(file):
  472. return res
  473. try:
  474. fp = open(file, 'r')
  475. res = fp.read()
  476. fp.close()
  477. except:
  478. pass
  479. return res
  480. def cleanupFtrace(self):
  481. if(self.usecallgraph or self.usetraceevents):
  482. self.fsetVal('0', 'events/kprobes/enable')
  483. self.fsetVal('', 'kprobe_events')
  484. def setupAllKprobes(self):
  485. for name in self.tracefuncs:
  486. self.defaultKprobe(name, self.tracefuncs[name])
  487. for name in self.dev_tracefuncs:
  488. self.defaultKprobe(name, self.dev_tracefuncs[name])
  489. def isCallgraphFunc(self, name):
  490. if len(self.debugfuncs) < 1 and self.suspendmode == 'command':
  491. return True
  492. if name in self.debugfuncs:
  493. return True
  494. funclist = []
  495. for i in self.tracefuncs:
  496. if 'func' in self.tracefuncs[i]:
  497. funclist.append(self.tracefuncs[i]['func'])
  498. else:
  499. funclist.append(i)
  500. if name in funclist:
  501. return True
  502. return False
  503. def initFtrace(self, testing=False):
  504. tp = self.tpath
  505. print('INITIALIZING FTRACE...')
  506. # turn trace off
  507. self.fsetVal('0', 'tracing_on')
  508. self.cleanupFtrace()
  509. # set the trace clock to global
  510. self.fsetVal('global', 'trace_clock')
  511. # set trace buffer to a huge value
  512. self.fsetVal('nop', 'current_tracer')
  513. self.fsetVal('100000', 'buffer_size_kb')
  514. # go no further if this is just a status check
  515. if testing:
  516. return
  517. if self.usekprobes:
  518. # add tracefunc kprobes so long as were not using full callgraph
  519. if(not self.usecallgraph or len(self.debugfuncs) > 0):
  520. for name in self.tracefuncs:
  521. self.defaultKprobe(name, self.tracefuncs[name])
  522. if self.usedevsrc:
  523. for name in self.dev_tracefuncs:
  524. self.defaultKprobe(name, self.dev_tracefuncs[name])
  525. else:
  526. self.usedevsrc = False
  527. self.addKprobes()
  528. # initialize the callgraph trace, unless this is an x2 run
  529. if(self.usecallgraph):
  530. # set trace type
  531. self.fsetVal('function_graph', 'current_tracer')
  532. self.fsetVal('', 'set_ftrace_filter')
  533. # set trace format options
  534. self.fsetVal('print-parent', 'trace_options')
  535. self.fsetVal('funcgraph-abstime', 'trace_options')
  536. self.fsetVal('funcgraph-cpu', 'trace_options')
  537. self.fsetVal('funcgraph-duration', 'trace_options')
  538. self.fsetVal('funcgraph-proc', 'trace_options')
  539. self.fsetVal('funcgraph-tail', 'trace_options')
  540. self.fsetVal('nofuncgraph-overhead', 'trace_options')
  541. self.fsetVal('context-info', 'trace_options')
  542. self.fsetVal('graph-time', 'trace_options')
  543. self.fsetVal('0', 'max_graph_depth')
  544. if len(self.debugfuncs) > 0:
  545. self.setFtraceFilterFunctions(self.debugfuncs)
  546. elif self.suspendmode == 'command':
  547. self.fsetVal('', 'set_graph_function')
  548. else:
  549. cf = ['dpm_run_callback']
  550. if(self.usetraceeventsonly):
  551. cf += ['dpm_prepare', 'dpm_complete']
  552. for fn in self.tracefuncs:
  553. if 'func' in self.tracefuncs[fn]:
  554. cf.append(self.tracefuncs[fn]['func'])
  555. else:
  556. cf.append(fn)
  557. self.setFtraceFilterFunctions(cf)
  558. if(self.usetraceevents):
  559. # turn trace events on
  560. events = iter(self.traceevents)
  561. for e in events:
  562. self.fsetVal('1', 'events/power/'+e+'/enable')
  563. # clear the trace buffer
  564. self.fsetVal('', 'trace')
  565. def verifyFtrace(self):
  566. # files needed for any trace data
  567. files = ['buffer_size_kb', 'current_tracer', 'trace', 'trace_clock',
  568. 'trace_marker', 'trace_options', 'tracing_on']
  569. # files needed for callgraph trace data
  570. tp = self.tpath
  571. if(self.usecallgraph):
  572. files += [
  573. 'available_filter_functions',
  574. 'set_ftrace_filter',
  575. 'set_graph_function'
  576. ]
  577. for f in files:
  578. if(os.path.exists(tp+f) == False):
  579. return False
  580. return True
  581. def verifyKprobes(self):
  582. # files needed for kprobes to work
  583. files = ['kprobe_events', 'events']
  584. tp = self.tpath
  585. for f in files:
  586. if(os.path.exists(tp+f) == False):
  587. return False
  588. return True
  589. def colorText(self, str):
  590. if not self.ansi:
  591. return str
  592. return '\x1B[31;40m'+str+'\x1B[m'
  593. sysvals = SystemValues()
  594. # Class: DevProps
  595. # Description:
  596. # Simple class which holds property values collected
  597. # for all the devices used in the timeline.
  598. class DevProps:
  599. syspath = ''
  600. altname = ''
  601. async = True
  602. xtraclass = ''
  603. xtrainfo = ''
  604. def out(self, dev):
  605. return '%s,%s,%d;' % (dev, self.altname, self.async)
  606. def debug(self, dev):
  607. print '%s:\n\taltname = %s\n\t async = %s' % (dev, self.altname, self.async)
  608. def altName(self, dev):
  609. if not self.altname or self.altname == dev:
  610. return dev
  611. return '%s [%s]' % (self.altname, dev)
  612. def xtraClass(self):
  613. if self.xtraclass:
  614. return ' '+self.xtraclass
  615. if not self.async:
  616. return ' sync'
  617. return ''
  618. def xtraInfo(self):
  619. if self.xtraclass:
  620. return ' '+self.xtraclass
  621. if self.async:
  622. return ' async'
  623. return ' sync'
  624. # Class: DeviceNode
  625. # Description:
  626. # A container used to create a device hierachy, with a single root node
  627. # and a tree of child nodes. Used by Data.deviceTopology()
  628. class DeviceNode:
  629. name = ''
  630. children = 0
  631. depth = 0
  632. def __init__(self, nodename, nodedepth):
  633. self.name = nodename
  634. self.children = []
  635. self.depth = nodedepth
  636. # Class: Data
  637. # Description:
  638. # The primary container for suspend/resume test data. There is one for
  639. # each test run. The data is organized into a cronological hierarchy:
  640. # Data.dmesg {
  641. # root structure, started as dmesg & ftrace, but now only ftrace
  642. # contents: times for suspend start/end, resume start/end, fwdata
  643. # phases {
  644. # 10 sequential, non-overlapping phases of S/R
  645. # contents: times for phase start/end, order/color data for html
  646. # devlist {
  647. # device callback or action list for this phase
  648. # device {
  649. # a single device callback or generic action
  650. # contents: start/stop times, pid/cpu/driver info
  651. # parents/children, html id for timeline/callgraph
  652. # optionally includes an ftrace callgraph
  653. # optionally includes intradev trace events
  654. # }
  655. # }
  656. # }
  657. # }
  658. #
  659. class Data:
  660. dmesg = {} # root data structure
  661. phases = [] # ordered list of phases
  662. start = 0.0 # test start
  663. end = 0.0 # test end
  664. tSuspended = 0.0 # low-level suspend start
  665. tResumed = 0.0 # low-level resume start
  666. tLow = 0.0 # time spent in low-level suspend (standby/freeze)
  667. fwValid = False # is firmware data available
  668. fwSuspend = 0 # time spent in firmware suspend
  669. fwResume = 0 # time spent in firmware resume
  670. dmesgtext = [] # dmesg text file in memory
  671. testnumber = 0
  672. idstr = ''
  673. html_device_id = 0
  674. stamp = 0
  675. outfile = ''
  676. dev_ubiquitous = ['msleep', 'udelay']
  677. def __init__(self, num):
  678. idchar = 'abcdefghijklmnopqrstuvwxyz'
  679. self.testnumber = num
  680. self.idstr = idchar[num]
  681. self.dmesgtext = []
  682. self.phases = []
  683. self.dmesg = { # fixed list of 10 phases
  684. 'suspend_prepare': {'list': dict(), 'start': -1.0, 'end': -1.0,
  685. 'row': 0, 'color': '#CCFFCC', 'order': 0},
  686. 'suspend': {'list': dict(), 'start': -1.0, 'end': -1.0,
  687. 'row': 0, 'color': '#88FF88', 'order': 1},
  688. 'suspend_late': {'list': dict(), 'start': -1.0, 'end': -1.0,
  689. 'row': 0, 'color': '#00AA00', 'order': 2},
  690. 'suspend_noirq': {'list': dict(), 'start': -1.0, 'end': -1.0,
  691. 'row': 0, 'color': '#008888', 'order': 3},
  692. 'suspend_machine': {'list': dict(), 'start': -1.0, 'end': -1.0,
  693. 'row': 0, 'color': '#0000FF', 'order': 4},
  694. 'resume_machine': {'list': dict(), 'start': -1.0, 'end': -1.0,
  695. 'row': 0, 'color': '#FF0000', 'order': 5},
  696. 'resume_noirq': {'list': dict(), 'start': -1.0, 'end': -1.0,
  697. 'row': 0, 'color': '#FF9900', 'order': 6},
  698. 'resume_early': {'list': dict(), 'start': -1.0, 'end': -1.0,
  699. 'row': 0, 'color': '#FFCC00', 'order': 7},
  700. 'resume': {'list': dict(), 'start': -1.0, 'end': -1.0,
  701. 'row': 0, 'color': '#FFFF88', 'order': 8},
  702. 'resume_complete': {'list': dict(), 'start': -1.0, 'end': -1.0,
  703. 'row': 0, 'color': '#FFFFCC', 'order': 9}
  704. }
  705. self.phases = self.sortedPhases()
  706. self.devicegroups = []
  707. for phase in self.phases:
  708. self.devicegroups.append([phase])
  709. def getStart(self):
  710. return self.dmesg[self.phases[0]]['start']
  711. def setStart(self, time):
  712. self.start = time
  713. self.dmesg[self.phases[0]]['start'] = time
  714. def getEnd(self):
  715. return self.dmesg[self.phases[-1]]['end']
  716. def setEnd(self, time):
  717. self.end = time
  718. self.dmesg[self.phases[-1]]['end'] = time
  719. def isTraceEventOutsideDeviceCalls(self, pid, time):
  720. for phase in self.phases:
  721. list = self.dmesg[phase]['list']
  722. for dev in list:
  723. d = list[dev]
  724. if(d['pid'] == pid and time >= d['start'] and
  725. time < d['end']):
  726. return False
  727. return True
  728. def targetDevice(self, phaselist, start, end, pid=-1):
  729. tgtdev = ''
  730. for phase in phaselist:
  731. list = self.dmesg[phase]['list']
  732. for devname in list:
  733. dev = list[devname]
  734. if(pid >= 0 and dev['pid'] != pid):
  735. continue
  736. devS = dev['start']
  737. devE = dev['end']
  738. if(start < devS or start >= devE or end <= devS or end > devE):
  739. continue
  740. tgtdev = dev
  741. break
  742. return tgtdev
  743. def addDeviceFunctionCall(self, displayname, kprobename, proc, pid, start, end, cdata, rdata):
  744. machstart = self.dmesg['suspend_machine']['start']
  745. machend = self.dmesg['resume_machine']['end']
  746. tgtdev = self.targetDevice(self.phases, start, end, pid)
  747. if not tgtdev and start >= machstart and end < machend:
  748. # device calls in machine phases should be serial
  749. tgtdev = self.targetDevice(['suspend_machine', 'resume_machine'], start, end)
  750. if not tgtdev:
  751. if 'scsi_eh' in proc:
  752. self.newActionGlobal(proc, start, end, pid)
  753. self.addDeviceFunctionCall(displayname, kprobename, proc, pid, start, end, cdata, rdata)
  754. else:
  755. vprint('IGNORE: %s[%s](%d) [%f - %f] | %s | %s | %s' % (displayname, kprobename,
  756. pid, start, end, cdata, rdata, proc))
  757. return False
  758. # detail block fits within tgtdev
  759. if('src' not in tgtdev):
  760. tgtdev['src'] = []
  761. title = cdata+' '+rdata
  762. mstr = '\(.*\) *(?P<args>.*) *\((?P<caller>.*)\+.* arg1=(?P<ret>.*)'
  763. m = re.match(mstr, title)
  764. if m:
  765. c = m.group('caller')
  766. a = m.group('args').strip()
  767. r = m.group('ret')
  768. if len(r) > 6:
  769. r = ''
  770. else:
  771. r = 'ret=%s ' % r
  772. l = '%0.3fms' % ((end - start) * 1000)
  773. if kprobename in self.dev_ubiquitous:
  774. title = '%s(%s) <- %s, %s(%s)' % (displayname, a, c, r, l)
  775. else:
  776. title = '%s(%s) %s(%s)' % (displayname, a, r, l)
  777. e = TraceEvent(title, kprobename, start, end - start)
  778. tgtdev['src'].append(e)
  779. return True
  780. def trimTimeVal(self, t, t0, dT, left):
  781. if left:
  782. if(t > t0):
  783. if(t - dT < t0):
  784. return t0
  785. return t - dT
  786. else:
  787. return t
  788. else:
  789. if(t < t0 + dT):
  790. if(t > t0):
  791. return t0 + dT
  792. return t + dT
  793. else:
  794. return t
  795. def trimTime(self, t0, dT, left):
  796. self.tSuspended = self.trimTimeVal(self.tSuspended, t0, dT, left)
  797. self.tResumed = self.trimTimeVal(self.tResumed, t0, dT, left)
  798. self.start = self.trimTimeVal(self.start, t0, dT, left)
  799. self.end = self.trimTimeVal(self.end, t0, dT, left)
  800. for phase in self.phases:
  801. p = self.dmesg[phase]
  802. p['start'] = self.trimTimeVal(p['start'], t0, dT, left)
  803. p['end'] = self.trimTimeVal(p['end'], t0, dT, left)
  804. list = p['list']
  805. for name in list:
  806. d = list[name]
  807. d['start'] = self.trimTimeVal(d['start'], t0, dT, left)
  808. d['end'] = self.trimTimeVal(d['end'], t0, dT, left)
  809. if('ftrace' in d):
  810. cg = d['ftrace']
  811. cg.start = self.trimTimeVal(cg.start, t0, dT, left)
  812. cg.end = self.trimTimeVal(cg.end, t0, dT, left)
  813. for line in cg.list:
  814. line.time = self.trimTimeVal(line.time, t0, dT, left)
  815. if('src' in d):
  816. for e in d['src']:
  817. e.time = self.trimTimeVal(e.time, t0, dT, left)
  818. def normalizeTime(self, tZero):
  819. # trim out any standby or freeze clock time
  820. if(self.tSuspended != self.tResumed):
  821. if(self.tResumed > tZero):
  822. self.trimTime(self.tSuspended, \
  823. self.tResumed-self.tSuspended, True)
  824. else:
  825. self.trimTime(self.tSuspended, \
  826. self.tResumed-self.tSuspended, False)
  827. def newPhaseWithSingleAction(self, phasename, devname, start, end, color):
  828. for phase in self.phases:
  829. self.dmesg[phase]['order'] += 1
  830. self.html_device_id += 1
  831. devid = '%s%d' % (self.idstr, self.html_device_id)
  832. list = dict()
  833. list[devname] = \
  834. {'start': start, 'end': end, 'pid': 0, 'par': '',
  835. 'length': (end-start), 'row': 0, 'id': devid, 'drv': '' };
  836. self.dmesg[phasename] = \
  837. {'list': list, 'start': start, 'end': end,
  838. 'row': 0, 'color': color, 'order': 0}
  839. self.phases = self.sortedPhases()
  840. def newPhase(self, phasename, start, end, color, order):
  841. if(order < 0):
  842. order = len(self.phases)
  843. for phase in self.phases[order:]:
  844. self.dmesg[phase]['order'] += 1
  845. if(order > 0):
  846. p = self.phases[order-1]
  847. self.dmesg[p]['end'] = start
  848. if(order < len(self.phases)):
  849. p = self.phases[order]
  850. self.dmesg[p]['start'] = end
  851. list = dict()
  852. self.dmesg[phasename] = \
  853. {'list': list, 'start': start, 'end': end,
  854. 'row': 0, 'color': color, 'order': order}
  855. self.phases = self.sortedPhases()
  856. self.devicegroups.append([phasename])
  857. def setPhase(self, phase, ktime, isbegin):
  858. if(isbegin):
  859. self.dmesg[phase]['start'] = ktime
  860. else:
  861. self.dmesg[phase]['end'] = ktime
  862. def dmesgSortVal(self, phase):
  863. return self.dmesg[phase]['order']
  864. def sortedPhases(self):
  865. return sorted(self.dmesg, key=self.dmesgSortVal)
  866. def sortedDevices(self, phase):
  867. list = self.dmesg[phase]['list']
  868. slist = []
  869. tmp = dict()
  870. for devname in list:
  871. dev = list[devname]
  872. tmp[dev['start']] = devname
  873. for t in sorted(tmp):
  874. slist.append(tmp[t])
  875. return slist
  876. def fixupInitcalls(self, phase, end):
  877. # if any calls never returned, clip them at system resume end
  878. phaselist = self.dmesg[phase]['list']
  879. for devname in phaselist:
  880. dev = phaselist[devname]
  881. if(dev['end'] < 0):
  882. for p in self.phases:
  883. if self.dmesg[p]['end'] > dev['start']:
  884. dev['end'] = self.dmesg[p]['end']
  885. break
  886. vprint('%s (%s): callback didnt return' % (devname, phase))
  887. def deviceFilter(self, devicefilter):
  888. # remove all by the relatives of the filter devnames
  889. filter = []
  890. for phase in self.phases:
  891. list = self.dmesg[phase]['list']
  892. for name in devicefilter:
  893. dev = name
  894. while(dev in list):
  895. if(dev not in filter):
  896. filter.append(dev)
  897. dev = list[dev]['par']
  898. children = self.deviceDescendants(name, phase)
  899. for dev in children:
  900. if(dev not in filter):
  901. filter.append(dev)
  902. for phase in self.phases:
  903. list = self.dmesg[phase]['list']
  904. rmlist = []
  905. for name in list:
  906. pid = list[name]['pid']
  907. if(name not in filter and pid >= 0):
  908. rmlist.append(name)
  909. for name in rmlist:
  910. del list[name]
  911. def fixupInitcallsThatDidntReturn(self):
  912. # if any calls never returned, clip them at system resume end
  913. for phase in self.phases:
  914. self.fixupInitcalls(phase, self.getEnd())
  915. def isInsideTimeline(self, start, end):
  916. if(self.start <= start and self.end > start):
  917. return True
  918. return False
  919. def phaseOverlap(self, phases):
  920. rmgroups = []
  921. newgroup = []
  922. for group in self.devicegroups:
  923. for phase in phases:
  924. if phase not in group:
  925. continue
  926. for p in group:
  927. if p not in newgroup:
  928. newgroup.append(p)
  929. if group not in rmgroups:
  930. rmgroups.append(group)
  931. for group in rmgroups:
  932. self.devicegroups.remove(group)
  933. self.devicegroups.append(newgroup)
  934. def newActionGlobal(self, name, start, end, pid=-1, color=''):
  935. # if event starts before timeline start, expand timeline
  936. if(start < self.start):
  937. self.setStart(start)
  938. # if event ends after timeline end, expand the timeline
  939. if(end > self.end):
  940. self.setEnd(end)
  941. # which phase is this device callback or action "in"
  942. targetphase = "none"
  943. htmlclass = ''
  944. overlap = 0.0
  945. phases = []
  946. for phase in self.phases:
  947. pstart = self.dmesg[phase]['start']
  948. pend = self.dmesg[phase]['end']
  949. o = max(0, min(end, pend) - max(start, pstart))
  950. if o > 0:
  951. phases.append(phase)
  952. if o > overlap:
  953. if overlap > 0 and phase == 'post_resume':
  954. continue
  955. targetphase = phase
  956. overlap = o
  957. if pid == -2:
  958. htmlclass = ' bg'
  959. if len(phases) > 1:
  960. htmlclass = ' bg'
  961. self.phaseOverlap(phases)
  962. if targetphase in self.phases:
  963. newname = self.newAction(targetphase, name, pid, '', start, end, '', htmlclass, color)
  964. return (targetphase, newname)
  965. return False
  966. def newAction(self, phase, name, pid, parent, start, end, drv, htmlclass='', color=''):
  967. # new device callback for a specific phase
  968. self.html_device_id += 1
  969. devid = '%s%d' % (self.idstr, self.html_device_id)
  970. list = self.dmesg[phase]['list']
  971. length = -1.0
  972. if(start >= 0 and end >= 0):
  973. length = end - start
  974. if pid == -2:
  975. i = 2
  976. origname = name
  977. while(name in list):
  978. name = '%s[%d]' % (origname, i)
  979. i += 1
  980. list[name] = {'start': start, 'end': end, 'pid': pid, 'par': parent,
  981. 'length': length, 'row': 0, 'id': devid, 'drv': drv }
  982. if htmlclass:
  983. list[name]['htmlclass'] = htmlclass
  984. if color:
  985. list[name]['color'] = color
  986. return name
  987. def deviceIDs(self, devlist, phase):
  988. idlist = []
  989. list = self.dmesg[phase]['list']
  990. for devname in list:
  991. if devname in devlist:
  992. idlist.append(list[devname]['id'])
  993. return idlist
  994. def deviceParentID(self, devname, phase):
  995. pdev = ''
  996. pdevid = ''
  997. list = self.dmesg[phase]['list']
  998. if devname in list:
  999. pdev = list[devname]['par']
  1000. if pdev in list:
  1001. return list[pdev]['id']
  1002. return pdev
  1003. def deviceChildren(self, devname, phase):
  1004. devlist = []
  1005. list = self.dmesg[phase]['list']
  1006. for child in list:
  1007. if(list[child]['par'] == devname):
  1008. devlist.append(child)
  1009. return devlist
  1010. def deviceDescendants(self, devname, phase):
  1011. children = self.deviceChildren(devname, phase)
  1012. family = children
  1013. for child in children:
  1014. family += self.deviceDescendants(child, phase)
  1015. return family
  1016. def deviceChildrenIDs(self, devname, phase):
  1017. devlist = self.deviceChildren(devname, phase)
  1018. return self.deviceIDs(devlist, phase)
  1019. def printDetails(self):
  1020. vprint(' test start: %f' % self.start)
  1021. for phase in self.phases:
  1022. dc = len(self.dmesg[phase]['list'])
  1023. vprint(' %16s: %f - %f (%d devices)' % (phase, \
  1024. self.dmesg[phase]['start'], self.dmesg[phase]['end'], dc))
  1025. vprint(' test end: %f' % self.end)
  1026. def deviceChildrenAllPhases(self, devname):
  1027. devlist = []
  1028. for phase in self.phases:
  1029. list = self.deviceChildren(devname, phase)
  1030. for dev in list:
  1031. if dev not in devlist:
  1032. devlist.append(dev)
  1033. return devlist
  1034. def masterTopology(self, name, list, depth):
  1035. node = DeviceNode(name, depth)
  1036. for cname in list:
  1037. # avoid recursions
  1038. if name == cname:
  1039. continue
  1040. clist = self.deviceChildrenAllPhases(cname)
  1041. cnode = self.masterTopology(cname, clist, depth+1)
  1042. node.children.append(cnode)
  1043. return node
  1044. def printTopology(self, node):
  1045. html = ''
  1046. if node.name:
  1047. info = ''
  1048. drv = ''
  1049. for phase in self.phases:
  1050. list = self.dmesg[phase]['list']
  1051. if node.name in list:
  1052. s = list[node.name]['start']
  1053. e = list[node.name]['end']
  1054. if list[node.name]['drv']:
  1055. drv = ' {'+list[node.name]['drv']+'}'
  1056. info += ('<li>%s: %.3fms</li>' % (phase, (e-s)*1000))
  1057. html += '<li><b>'+node.name+drv+'</b>'
  1058. if info:
  1059. html += '<ul>'+info+'</ul>'
  1060. html += '</li>'
  1061. if len(node.children) > 0:
  1062. html += '<ul>'
  1063. for cnode in node.children:
  1064. html += self.printTopology(cnode)
  1065. html += '</ul>'
  1066. return html
  1067. def rootDeviceList(self):
  1068. # list of devices graphed
  1069. real = []
  1070. for phase in self.dmesg:
  1071. list = self.dmesg[phase]['list']
  1072. for dev in list:
  1073. if list[dev]['pid'] >= 0 and dev not in real:
  1074. real.append(dev)
  1075. # list of top-most root devices
  1076. rootlist = []
  1077. for phase in self.dmesg:
  1078. list = self.dmesg[phase]['list']
  1079. for dev in list:
  1080. pdev = list[dev]['par']
  1081. pid = list[dev]['pid']
  1082. if(pid < 0 or re.match('[0-9]*-[0-9]*\.[0-9]*[\.0-9]*\:[\.0-9]*$', pdev)):
  1083. continue
  1084. if pdev and pdev not in real and pdev not in rootlist:
  1085. rootlist.append(pdev)
  1086. return rootlist
  1087. def deviceTopology(self):
  1088. rootlist = self.rootDeviceList()
  1089. master = self.masterTopology('', rootlist, 0)
  1090. return self.printTopology(master)
  1091. def selectTimelineDevices(self, widfmt, tTotal, mindevlen):
  1092. # only select devices that will actually show up in html
  1093. self.tdevlist = dict()
  1094. for phase in self.dmesg:
  1095. devlist = []
  1096. list = self.dmesg[phase]['list']
  1097. for dev in list:
  1098. length = (list[dev]['end'] - list[dev]['start']) * 1000
  1099. width = widfmt % (((list[dev]['end']-list[dev]['start'])*100)/tTotal)
  1100. if width != '0.000000' and length >= mindevlen:
  1101. devlist.append(dev)
  1102. self.tdevlist[phase] = devlist
  1103. # Class: TraceEvent
  1104. # Description:
  1105. # A container for trace event data found in the ftrace file
  1106. class TraceEvent:
  1107. text = ''
  1108. time = 0.0
  1109. length = 0.0
  1110. title = ''
  1111. row = 0
  1112. def __init__(self, a, n, t, l):
  1113. self.title = a
  1114. self.text = n
  1115. self.time = t
  1116. self.length = l
  1117. # Class: FTraceLine
  1118. # Description:
  1119. # A container for a single line of ftrace data. There are six basic types:
  1120. # callgraph line:
  1121. # call: " dpm_run_callback() {"
  1122. # return: " }"
  1123. # leaf: " dpm_run_callback();"
  1124. # trace event:
  1125. # tracing_mark_write: SUSPEND START or RESUME COMPLETE
  1126. # suspend_resume: phase or custom exec block data
  1127. # device_pm_callback: device callback info
  1128. class FTraceLine:
  1129. time = 0.0
  1130. length = 0.0
  1131. fcall = False
  1132. freturn = False
  1133. fevent = False
  1134. fkprobe = False
  1135. depth = 0
  1136. name = ''
  1137. type = ''
  1138. def __init__(self, t, m='', d=''):
  1139. self.time = float(t)
  1140. if not m and not d:
  1141. return
  1142. # is this a trace event
  1143. if(d == 'traceevent' or re.match('^ *\/\* *(?P<msg>.*) \*\/ *$', m)):
  1144. if(d == 'traceevent'):
  1145. # nop format trace event
  1146. msg = m
  1147. else:
  1148. # function_graph format trace event
  1149. em = re.match('^ *\/\* *(?P<msg>.*) \*\/ *$', m)
  1150. msg = em.group('msg')
  1151. emm = re.match('^(?P<call>.*?): (?P<msg>.*)', msg)
  1152. if(emm):
  1153. self.name = emm.group('msg')
  1154. self.type = emm.group('call')
  1155. else:
  1156. self.name = msg
  1157. km = re.match('^(?P<n>.*)_cal$', self.type)
  1158. if km:
  1159. self.fcall = True
  1160. self.fkprobe = True
  1161. self.type = km.group('n')
  1162. return
  1163. km = re.match('^(?P<n>.*)_ret$', self.type)
  1164. if km:
  1165. self.freturn = True
  1166. self.fkprobe = True
  1167. self.type = km.group('n')
  1168. return
  1169. self.fevent = True
  1170. return
  1171. # convert the duration to seconds
  1172. if(d):
  1173. self.length = float(d)/1000000
  1174. # the indentation determines the depth
  1175. match = re.match('^(?P<d> *)(?P<o>.*)$', m)
  1176. if(not match):
  1177. return
  1178. self.depth = self.getDepth(match.group('d'))
  1179. m = match.group('o')
  1180. # function return
  1181. if(m[0] == '}'):
  1182. self.freturn = True
  1183. if(len(m) > 1):
  1184. # includes comment with function name
  1185. match = re.match('^} *\/\* *(?P<n>.*) *\*\/$', m)
  1186. if(match):
  1187. self.name = match.group('n').strip()
  1188. # function call
  1189. else:
  1190. self.fcall = True
  1191. # function call with children
  1192. if(m[-1] == '{'):
  1193. match = re.match('^(?P<n>.*) *\(.*', m)
  1194. if(match):
  1195. self.name = match.group('n').strip()
  1196. # function call with no children (leaf)
  1197. elif(m[-1] == ';'):
  1198. self.freturn = True
  1199. match = re.match('^(?P<n>.*) *\(.*', m)
  1200. if(match):
  1201. self.name = match.group('n').strip()
  1202. # something else (possibly a trace marker)
  1203. else:
  1204. self.name = m
  1205. def getDepth(self, str):
  1206. return len(str)/2
  1207. def debugPrint(self, dev=''):
  1208. if(self.freturn and self.fcall):
  1209. print('%s -- %f (%02d): %s(); (%.3f us)' % (dev, self.time, \
  1210. self.depth, self.name, self.length*1000000))
  1211. elif(self.freturn):
  1212. print('%s -- %f (%02d): %s} (%.3f us)' % (dev, self.time, \
  1213. self.depth, self.name, self.length*1000000))
  1214. else:
  1215. print('%s -- %f (%02d): %s() { (%.3f us)' % (dev, self.time, \
  1216. self.depth, self.name, self.length*1000000))
  1217. def startMarker(self):
  1218. global sysvals
  1219. # Is this the starting line of a suspend?
  1220. if not self.fevent:
  1221. return False
  1222. if sysvals.usetracemarkers:
  1223. if(self.name == 'SUSPEND START'):
  1224. return True
  1225. return False
  1226. else:
  1227. if(self.type == 'suspend_resume' and
  1228. re.match('suspend_enter\[.*\] begin', self.name)):
  1229. return True
  1230. return False
  1231. def endMarker(self):
  1232. # Is this the ending line of a resume?
  1233. if not self.fevent:
  1234. return False
  1235. if sysvals.usetracemarkers:
  1236. if(self.name == 'RESUME COMPLETE'):
  1237. return True
  1238. return False
  1239. else:
  1240. if(self.type == 'suspend_resume' and
  1241. re.match('thaw_processes\[.*\] end', self.name)):
  1242. return True
  1243. return False
  1244. # Class: FTraceCallGraph
  1245. # Description:
  1246. # A container for the ftrace callgraph of a single recursive function.
  1247. # This can be a dpm_run_callback, dpm_prepare, or dpm_complete callgraph
  1248. # Each instance is tied to a single device in a single phase, and is
  1249. # comprised of an ordered list of FTraceLine objects
  1250. class FTraceCallGraph:
  1251. start = -1.0
  1252. end = -1.0
  1253. list = []
  1254. invalid = False
  1255. depth = 0
  1256. pid = 0
  1257. def __init__(self, pid):
  1258. self.start = -1.0
  1259. self.end = -1.0
  1260. self.list = []
  1261. self.depth = 0
  1262. self.pid = pid
  1263. def addLine(self, line, debug=False):
  1264. # if this is already invalid, just leave
  1265. if(self.invalid):
  1266. return False
  1267. # invalidate on too much data or bad depth
  1268. if(len(self.list) >= 1000000 or self.depth < 0):
  1269. self.invalidate(line)
  1270. return False
  1271. # compare current depth with this lines pre-call depth
  1272. prelinedep = line.depth
  1273. if(line.freturn and not line.fcall):
  1274. prelinedep += 1
  1275. last = 0
  1276. lasttime = line.time
  1277. virtualfname = 'execution_misalignment'
  1278. if len(self.list) > 0:
  1279. last = self.list[-1]
  1280. lasttime = last.time
  1281. # handle low misalignments by inserting returns
  1282. if prelinedep < self.depth:
  1283. if debug and last:
  1284. print '-------- task %d --------' % self.pid
  1285. last.debugPrint()
  1286. idx = 0
  1287. # add return calls to get the depth down
  1288. while prelinedep < self.depth:
  1289. if debug:
  1290. print 'MISALIGN LOW (add returns): C%d - eC%d' % (self.depth, prelinedep)
  1291. self.depth -= 1
  1292. if idx == 0 and last and last.fcall and not last.freturn:
  1293. # special case, turn last call into a leaf
  1294. last.depth = self.depth
  1295. last.freturn = True
  1296. last.length = line.time - last.time
  1297. if debug:
  1298. last.debugPrint()
  1299. else:
  1300. vline = FTraceLine(lasttime)
  1301. vline.depth = self.depth
  1302. vline.name = virtualfname
  1303. vline.freturn = True
  1304. self.list.append(vline)
  1305. if debug:
  1306. vline.debugPrint()
  1307. idx += 1
  1308. if debug:
  1309. line.debugPrint()
  1310. print ''
  1311. # handle high misalignments by inserting calls
  1312. elif prelinedep > self.depth:
  1313. if debug and last:
  1314. print '-------- task %d --------' % self.pid
  1315. last.debugPrint()
  1316. idx = 0
  1317. # add calls to get the depth up
  1318. while prelinedep > self.depth:
  1319. if debug:
  1320. print 'MISALIGN HIGH (add calls): C%d - eC%d' % (self.depth, prelinedep)
  1321. if idx == 0 and line.freturn and not line.fcall:
  1322. # special case, turn this return into a leaf
  1323. line.fcall = True
  1324. prelinedep -= 1
  1325. else:
  1326. vline = FTraceLine(lasttime)
  1327. vline.depth = self.depth
  1328. vline.name = virtualfname
  1329. vline.fcall = True
  1330. if debug:
  1331. vline.debugPrint()
  1332. self.list.append(vline)
  1333. self.depth += 1
  1334. if not last:
  1335. self.start = vline.time
  1336. idx += 1
  1337. if debug:
  1338. line.debugPrint()
  1339. print ''
  1340. # process the call and set the new depth
  1341. if(line.fcall and not line.freturn):
  1342. self.depth += 1
  1343. elif(line.freturn and not line.fcall):
  1344. self.depth -= 1
  1345. if len(self.list) < 1:
  1346. self.start = line.time
  1347. self.list.append(line)
  1348. if(line.depth == 0 and line.freturn):
  1349. if(self.start < 0):
  1350. self.start = line.time
  1351. self.end = line.time
  1352. if line.fcall:
  1353. self.end += line.length
  1354. if self.list[0].name == virtualfname:
  1355. self.invalid = True
  1356. return True
  1357. return False
  1358. def invalidate(self, line):
  1359. if(len(self.list) > 0):
  1360. first = self.list[0]
  1361. self.list = []
  1362. self.list.append(first)
  1363. self.invalid = True
  1364. id = 'task %s' % (self.pid)
  1365. window = '(%f - %f)' % (self.start, line.time)
  1366. if(self.depth < 0):
  1367. vprint('Too much data for '+id+\
  1368. ' (buffer overflow), ignoring this callback')
  1369. else:
  1370. vprint('Too much data for '+id+\
  1371. ' '+window+', ignoring this callback')
  1372. def slice(self, t0, tN):
  1373. minicg = FTraceCallGraph(0)
  1374. count = -1
  1375. firstdepth = 0
  1376. for l in self.list:
  1377. if(l.time < t0 or l.time > tN):
  1378. continue
  1379. if(count < 0):
  1380. if(not l.fcall or l.name == 'dev_driver_string'):
  1381. continue
  1382. firstdepth = l.depth
  1383. count = 0
  1384. l.depth -= firstdepth
  1385. minicg.addLine(l)
  1386. if((count == 0 and l.freturn and l.fcall) or
  1387. (count > 0 and l.depth <= 0)):
  1388. break
  1389. count += 1
  1390. return minicg
  1391. def repair(self, enddepth):
  1392. # bring the depth back to 0 with additional returns
  1393. fixed = False
  1394. last = self.list[-1]
  1395. for i in reversed(range(enddepth)):
  1396. t = FTraceLine(last.time)
  1397. t.depth = i
  1398. t.freturn = True
  1399. fixed = self.addLine(t)
  1400. if fixed:
  1401. self.end = last.time
  1402. return True
  1403. return False
  1404. def postProcess(self, debug=False):
  1405. stack = dict()
  1406. cnt = 0
  1407. for l in self.list:
  1408. if(l.fcall and not l.freturn):
  1409. stack[l.depth] = l
  1410. cnt += 1
  1411. elif(l.freturn and not l.fcall):
  1412. if(l.depth not in stack):
  1413. if debug:
  1414. print 'Post Process Error: Depth missing'
  1415. l.debugPrint()
  1416. return False
  1417. # transfer total time from return line to call line
  1418. stack[l.depth].length = l.length
  1419. stack.pop(l.depth)
  1420. l.length = 0
  1421. cnt -= 1
  1422. if(cnt == 0):
  1423. # trace caught the whole call tree
  1424. return True
  1425. elif(cnt < 0):
  1426. if debug:
  1427. print 'Post Process Error: Depth is less than 0'
  1428. return False
  1429. # trace ended before call tree finished
  1430. return self.repair(cnt)
  1431. def deviceMatch(self, pid, data):
  1432. found = False
  1433. # add the callgraph data to the device hierarchy
  1434. borderphase = {
  1435. 'dpm_prepare': 'suspend_prepare',
  1436. 'dpm_complete': 'resume_complete'
  1437. }
  1438. if(self.list[0].name in borderphase):
  1439. p = borderphase[self.list[0].name]
  1440. list = data.dmesg[p]['list']
  1441. for devname in list:
  1442. dev = list[devname]
  1443. if(pid == dev['pid'] and
  1444. self.start <= dev['start'] and
  1445. self.end >= dev['end']):
  1446. dev['ftrace'] = self.slice(dev['start'], dev['end'])
  1447. found = True
  1448. return found
  1449. for p in data.phases:
  1450. if(data.dmesg[p]['start'] <= self.start and
  1451. self.start <= data.dmesg[p]['end']):
  1452. list = data.dmesg[p]['list']
  1453. for devname in list:
  1454. dev = list[devname]
  1455. if(pid == dev['pid'] and
  1456. self.start <= dev['start'] and
  1457. self.end >= dev['end']):
  1458. dev['ftrace'] = self
  1459. found = True
  1460. break
  1461. break
  1462. return found
  1463. def newActionFromFunction(self, data):
  1464. name = self.list[0].name
  1465. if name in ['dpm_run_callback', 'dpm_prepare', 'dpm_complete']:
  1466. return
  1467. fs = self.start
  1468. fe = self.end
  1469. if fs < data.start or fe > data.end:
  1470. return
  1471. phase = ''
  1472. for p in data.phases:
  1473. if(data.dmesg[p]['start'] <= self.start and
  1474. self.start < data.dmesg[p]['end']):
  1475. phase = p
  1476. break
  1477. if not phase:
  1478. return
  1479. out = data.newActionGlobal(name, fs, fe, -2)
  1480. if out:
  1481. phase, myname = out
  1482. data.dmesg[phase]['list'][myname]['ftrace'] = self
  1483. def debugPrint(self):
  1484. print('[%f - %f] %s (%d)') % (self.start, self.end, self.list[0].name, self.pid)
  1485. for l in self.list:
  1486. if(l.freturn and l.fcall):
  1487. print('%f (%02d): %s(); (%.3f us)' % (l.time, \
  1488. l.depth, l.name, l.length*1000000))
  1489. elif(l.freturn):
  1490. print('%f (%02d): %s} (%.3f us)' % (l.time, \
  1491. l.depth, l.name, l.length*1000000))
  1492. else:
  1493. print('%f (%02d): %s() { (%.3f us)' % (l.time, \
  1494. l.depth, l.name, l.length*1000000))
  1495. print(' ')
  1496. # Class: Timeline
  1497. # Description:
  1498. # A container for a device timeline which calculates
  1499. # all the html properties to display it correctly
  1500. class Timeline:
  1501. html = {}
  1502. height = 0 # total timeline height
  1503. scaleH = 20 # timescale (top) row height
  1504. rowH = 30 # device row height
  1505. bodyH = 0 # body height
  1506. rows = 0 # total timeline rows
  1507. phases = []
  1508. rowmaxlines = dict()
  1509. rowcount = dict()
  1510. rowheight = dict()
  1511. def __init__(self, rowheight):
  1512. self.rowH = rowheight
  1513. self.html = {
  1514. 'header': '',
  1515. 'timeline': '',
  1516. 'legend': '',
  1517. }
  1518. # Function: getDeviceRows
  1519. # Description:
  1520. # determine how may rows the device funcs will take
  1521. # Arguments:
  1522. # rawlist: the list of devices/actions for a single phase
  1523. # Output:
  1524. # The total number of rows needed to display this phase of the timeline
  1525. def getDeviceRows(self, rawlist):
  1526. # clear all rows and set them to undefined
  1527. lendict = dict()
  1528. for item in rawlist:
  1529. item.row = -1
  1530. lendict[item] = item.length
  1531. list = []
  1532. for i in sorted(lendict, key=lendict.get, reverse=True):
  1533. list.append(i)
  1534. remaining = len(list)
  1535. rowdata = dict()
  1536. row = 1
  1537. # try to pack each row with as many ranges as possible
  1538. while(remaining > 0):
  1539. if(row not in rowdata):
  1540. rowdata[row] = []
  1541. for i in list:
  1542. if(i.row >= 0):
  1543. continue
  1544. s = i.time
  1545. e = i.time + i.length
  1546. valid = True
  1547. for ritem in rowdata[row]:
  1548. rs = ritem.time
  1549. re = ritem.time + ritem.length
  1550. if(not (((s <= rs) and (e <= rs)) or
  1551. ((s >= re) and (e >= re)))):
  1552. valid = False
  1553. break
  1554. if(valid):
  1555. rowdata[row].append(i)
  1556. i.row = row
  1557. remaining -= 1
  1558. row += 1
  1559. return row
  1560. # Function: getPhaseRows
  1561. # Description:
  1562. # Organize the timeline entries into the smallest
  1563. # number of rows possible, with no entry overlapping
  1564. # Arguments:
  1565. # list: the list of devices/actions for a single phase
  1566. # devlist: string list of device names to use
  1567. # Output:
  1568. # The total number of rows needed to display this phase of the timeline
  1569. def getPhaseRows(self, dmesg, devlist):
  1570. # clear all rows and set them to undefined
  1571. remaining = len(devlist)
  1572. rowdata = dict()
  1573. row = 0
  1574. lendict = dict()
  1575. myphases = []
  1576. for item in devlist:
  1577. if item[0] not in self.phases:
  1578. self.phases.append(item[0])
  1579. if item[0] not in myphases:
  1580. myphases.append(item[0])
  1581. self.rowmaxlines[item[0]] = dict()
  1582. self.rowheight[item[0]] = dict()
  1583. dev = dmesg[item[0]]['list'][item[1]]
  1584. dev['row'] = -1
  1585. lendict[item] = float(dev['end']) - float(dev['start'])
  1586. if 'src' in dev:
  1587. dev['devrows'] = self.getDeviceRows(dev['src'])
  1588. lenlist = []
  1589. for i in sorted(lendict, key=lendict.get, reverse=True):
  1590. lenlist.append(i)
  1591. orderedlist = []
  1592. for item in lenlist:
  1593. dev = dmesg[item[0]]['list'][item[1]]
  1594. if dev['pid'] == -2:
  1595. orderedlist.append(item)
  1596. for item in lenlist:
  1597. if item not in orderedlist:
  1598. orderedlist.append(item)
  1599. # try to pack each row with as many ranges as possible
  1600. while(remaining > 0):
  1601. rowheight = 1
  1602. if(row not in rowdata):
  1603. rowdata[row] = []
  1604. for item in orderedlist:
  1605. dev = dmesg[item[0]]['list'][item[1]]
  1606. if(dev['row'] < 0):
  1607. s = dev['start']
  1608. e = dev['end']
  1609. valid = True
  1610. for ritem in rowdata[row]:
  1611. rs = ritem['start']
  1612. re = ritem['end']
  1613. if(not (((s <= rs) and (e <= rs)) or
  1614. ((s >= re) and (e >= re)))):
  1615. valid = False
  1616. break
  1617. if(valid):
  1618. rowdata[row].append(dev)
  1619. dev['row'] = row
  1620. remaining -= 1
  1621. if 'devrows' in dev and dev['devrows'] > rowheight:
  1622. rowheight = dev['devrows']
  1623. for phase in myphases:
  1624. self.rowmaxlines[phase][row] = rowheight
  1625. self.rowheight[phase][row] = rowheight * self.rowH
  1626. row += 1
  1627. if(row > self.rows):
  1628. self.rows = int(row)
  1629. for phase in myphases:
  1630. self.rowcount[phase] = row
  1631. return row
  1632. def phaseRowHeight(self, phase, row):
  1633. return self.rowheight[phase][row]
  1634. def phaseRowTop(self, phase, row):
  1635. top = 0
  1636. for i in sorted(self.rowheight[phase]):
  1637. if i >= row:
  1638. break
  1639. top += self.rowheight[phase][i]
  1640. return top
  1641. # Function: calcTotalRows
  1642. # Description:
  1643. # Calculate the heights and offsets for the header and rows
  1644. def calcTotalRows(self):
  1645. maxrows = 0
  1646. standardphases = []
  1647. for phase in self.phases:
  1648. total = 0
  1649. for i in sorted(self.rowmaxlines[phase]):
  1650. total += self.rowmaxlines[phase][i]
  1651. if total > maxrows:
  1652. maxrows = total
  1653. if total == self.rowcount[phase]:
  1654. standardphases.append(phase)
  1655. self.height = self.scaleH + (maxrows*self.rowH)
  1656. self.bodyH = self.height - self.scaleH
  1657. for phase in standardphases:
  1658. for i in sorted(self.rowheight[phase]):
  1659. self.rowheight[phase][i] = self.bodyH/self.rowcount[phase]
  1660. # Function: createTimeScale
  1661. # Description:
  1662. # Create the timescale for a timeline block
  1663. # Arguments:
  1664. # m0: start time (mode begin)
  1665. # mMax: end time (mode end)
  1666. # tTotal: total timeline time
  1667. # mode: suspend or resume
  1668. # Output:
  1669. # The html code needed to display the time scale
  1670. def createTimeScale(self, m0, mMax, tTotal, mode):
  1671. timescale = '<div class="t" style="right:{0}%">{1}</div>\n'
  1672. rline = '<div class="t" style="left:0;border-left:1px solid black;border-right:0;">Resume</div>\n'
  1673. output = '<div class="timescale">\n'
  1674. # set scale for timeline
  1675. mTotal = mMax - m0
  1676. tS = 0.1
  1677. if(tTotal <= 0):
  1678. return output+'</div>\n'
  1679. if(tTotal > 4):
  1680. tS = 1
  1681. divTotal = int(mTotal/tS) + 1
  1682. divEdge = (mTotal - tS*(divTotal-1))*100/mTotal
  1683. for i in range(divTotal):
  1684. htmlline = ''
  1685. if(mode == 'resume'):
  1686. pos = '%0.3f' % (100 - ((float(i)*tS*100)/mTotal))
  1687. val = '%0.fms' % (float(i)*tS*1000)
  1688. htmlline = timescale.format(pos, val)
  1689. if(i == 0):
  1690. htmlline = rline
  1691. else:
  1692. pos = '%0.3f' % (100 - ((float(i)*tS*100)/mTotal) - divEdge)
  1693. val = '%0.fms' % (float(i-divTotal+1)*tS*1000)
  1694. if(i == divTotal - 1):
  1695. val = 'Suspend'
  1696. htmlline = timescale.format(pos, val)
  1697. output += htmlline
  1698. output += '</div>\n'
  1699. return output
  1700. # Class: TestProps
  1701. # Description:
  1702. # A list of values describing the properties of these test runs
  1703. class TestProps:
  1704. stamp = ''
  1705. tracertype = ''
  1706. S0i3 = False
  1707. fwdata = []
  1708. ftrace_line_fmt_fg = \
  1709. '^ *(?P<time>[0-9\.]*) *\| *(?P<cpu>[0-9]*)\)'+\
  1710. ' *(?P<proc>.*)-(?P<pid>[0-9]*) *\|'+\
  1711. '[ +!#\*@$]*(?P<dur>[0-9\.]*) .*\| (?P<msg>.*)'
  1712. ftrace_line_fmt_nop = \
  1713. ' *(?P<proc>.*)-(?P<pid>[0-9]*) *\[(?P<cpu>[0-9]*)\] *'+\
  1714. '(?P<flags>.{4}) *(?P<time>[0-9\.]*): *'+\
  1715. '(?P<msg>.*)'
  1716. ftrace_line_fmt = ftrace_line_fmt_nop
  1717. cgformat = False
  1718. data = 0
  1719. ktemp = dict()
  1720. def __init__(self):
  1721. self.ktemp = dict()
  1722. def setTracerType(self, tracer):
  1723. self.tracertype = tracer
  1724. if(tracer == 'function_graph'):
  1725. self.cgformat = True
  1726. self.ftrace_line_fmt = self.ftrace_line_fmt_fg
  1727. elif(tracer == 'nop'):
  1728. self.ftrace_line_fmt = self.ftrace_line_fmt_nop
  1729. else:
  1730. doError('Invalid tracer format: [%s]' % tracer, False)
  1731. # Class: TestRun
  1732. # Description:
  1733. # A container for a suspend/resume test run. This is necessary as
  1734. # there could be more than one, and they need to be separate.
  1735. class TestRun:
  1736. ftemp = dict()
  1737. ttemp = dict()
  1738. data = 0
  1739. def __init__(self, dataobj):
  1740. self.data = dataobj
  1741. self.ftemp = dict()
  1742. self.ttemp = dict()
  1743. # ----------------- FUNCTIONS --------------------
  1744. # Function: vprint
  1745. # Description:
  1746. # verbose print (prints only with -verbose option)
  1747. # Arguments:
  1748. # msg: the debug/log message to print
  1749. def vprint(msg):
  1750. global sysvals
  1751. if(sysvals.verbose):
  1752. print(msg)
  1753. # Function: parseStamp
  1754. # Description:
  1755. # Pull in the stamp comment line from the data file(s),
  1756. # create the stamp, and add it to the global sysvals object
  1757. # Arguments:
  1758. # m: the valid re.match output for the stamp line
  1759. def parseStamp(line, data):
  1760. global sysvals
  1761. m = re.match(sysvals.stampfmt, line)
  1762. data.stamp = {'time': '', 'host': '', 'mode': ''}
  1763. dt = datetime(int(m.group('y'))+2000, int(m.group('m')),
  1764. int(m.group('d')), int(m.group('H')), int(m.group('M')),
  1765. int(m.group('S')))
  1766. data.stamp['time'] = dt.strftime('%B %d %Y, %I:%M:%S %p')
  1767. data.stamp['host'] = m.group('host')
  1768. data.stamp['mode'] = m.group('mode')
  1769. data.stamp['kernel'] = m.group('kernel')
  1770. sysvals.hostname = data.stamp['host']
  1771. sysvals.suspendmode = data.stamp['mode']
  1772. if not sysvals.stamp:
  1773. sysvals.stamp = data.stamp
  1774. # Function: diffStamp
  1775. # Description:
  1776. # compare the host, kernel, and mode fields in 3 stamps
  1777. # Arguments:
  1778. # stamp1: string array with mode, kernel, and host
  1779. # stamp2: string array with mode, kernel, and host
  1780. # Return:
  1781. # True if stamps differ, False if they're the same
  1782. def diffStamp(stamp1, stamp2):
  1783. if 'host' in stamp1 and 'host' in stamp2:
  1784. if stamp1['host'] != stamp2['host']:
  1785. return True
  1786. if 'kernel' in stamp1 and 'kernel' in stamp2:
  1787. if stamp1['kernel'] != stamp2['kernel']:
  1788. return True
  1789. if 'mode' in stamp1 and 'mode' in stamp2:
  1790. if stamp1['mode'] != stamp2['mode']:
  1791. return True
  1792. return False
  1793. # Function: doesTraceLogHaveTraceEvents
  1794. # Description:
  1795. # Quickly determine if the ftrace log has some or all of the trace events
  1796. # required for primary parsing. Set the usetraceevents and/or
  1797. # usetraceeventsonly flags in the global sysvals object
  1798. def doesTraceLogHaveTraceEvents():
  1799. global sysvals
  1800. # check for kprobes
  1801. sysvals.usekprobes = False
  1802. out = os.system('grep -q "_cal: (" '+sysvals.ftracefile)
  1803. if(out == 0):
  1804. sysvals.usekprobes = True
  1805. # check for callgraph data on trace event blocks
  1806. out = os.system('grep -q "_cpu_down()" '+sysvals.ftracefile)
  1807. if(out == 0):
  1808. sysvals.usekprobes = True
  1809. out = os.popen('head -1 '+sysvals.ftracefile).read().replace('\n', '')
  1810. m = re.match(sysvals.stampfmt, out)
  1811. if m and m.group('mode') == 'command':
  1812. sysvals.usetraceeventsonly = True
  1813. sysvals.usetraceevents = True
  1814. return
  1815. # figure out what level of trace events are supported
  1816. sysvals.usetraceeventsonly = True
  1817. sysvals.usetraceevents = False
  1818. for e in sysvals.traceevents:
  1819. out = os.system('grep -q "'+e+': " '+sysvals.ftracefile)
  1820. if(out != 0):
  1821. sysvals.usetraceeventsonly = False
  1822. if(e == 'suspend_resume' and out == 0):
  1823. sysvals.usetraceevents = True
  1824. # determine is this log is properly formatted
  1825. for e in ['SUSPEND START', 'RESUME COMPLETE']:
  1826. out = os.system('grep -q "'+e+'" '+sysvals.ftracefile)
  1827. if(out != 0):
  1828. sysvals.usetracemarkers = False
  1829. # Function: appendIncompleteTraceLog
  1830. # Description:
  1831. # [deprecated for kernel 3.15 or newer]
  1832. # Legacy support of ftrace outputs that lack the device_pm_callback
  1833. # and/or suspend_resume trace events. The primary data should be
  1834. # taken from dmesg, and this ftrace is used only for callgraph data
  1835. # or custom actions in the timeline. The data is appended to the Data
  1836. # objects provided.
  1837. # Arguments:
  1838. # testruns: the array of Data objects obtained from parseKernelLog
  1839. def appendIncompleteTraceLog(testruns):
  1840. global sysvals
  1841. # create TestRun vessels for ftrace parsing
  1842. testcnt = len(testruns)
  1843. testidx = 0
  1844. testrun = []
  1845. for data in testruns:
  1846. testrun.append(TestRun(data))
  1847. # extract the callgraph and traceevent data
  1848. vprint('Analyzing the ftrace data...')
  1849. tp = TestProps()
  1850. tf = open(sysvals.ftracefile, 'r')
  1851. data = 0
  1852. for line in tf:
  1853. # remove any latent carriage returns
  1854. line = line.replace('\r\n', '')
  1855. # grab the time stamp
  1856. m = re.match(sysvals.stampfmt, line)
  1857. if(m):
  1858. tp.stamp = line
  1859. continue
  1860. # determine the trace data type (required for further parsing)
  1861. m = re.match(sysvals.tracertypefmt, line)
  1862. if(m):
  1863. tp.setTracerType(m.group('t'))
  1864. continue
  1865. # device properties line
  1866. if(re.match(sysvals.devpropfmt, line)):
  1867. devProps(line)
  1868. continue
  1869. # parse only valid lines, if this is not one move on
  1870. m = re.match(tp.ftrace_line_fmt, line)
  1871. if(not m):
  1872. continue
  1873. # gather the basic message data from the line
  1874. m_time = m.group('time')
  1875. m_pid = m.group('pid')
  1876. m_msg = m.group('msg')
  1877. if(tp.cgformat):
  1878. m_param3 = m.group('dur')
  1879. else:
  1880. m_param3 = 'traceevent'
  1881. if(m_time and m_pid and m_msg):
  1882. t = FTraceLine(m_time, m_msg, m_param3)
  1883. pid = int(m_pid)
  1884. else:
  1885. continue
  1886. # the line should be a call, return, or event
  1887. if(not t.fcall and not t.freturn and not t.fevent):
  1888. continue
  1889. # look for the suspend start marker
  1890. if(t.startMarker()):
  1891. data = testrun[testidx].data
  1892. parseStamp(tp.stamp, data)
  1893. data.setStart(t.time)
  1894. continue
  1895. if(not data):
  1896. continue
  1897. # find the end of resume
  1898. if(t.endMarker()):
  1899. data.setEnd(t.time)
  1900. testidx += 1
  1901. if(testidx >= testcnt):
  1902. break
  1903. continue
  1904. # trace event processing
  1905. if(t.fevent):
  1906. # general trace events have two types, begin and end
  1907. if(re.match('(?P<name>.*) begin$', t.name)):
  1908. isbegin = True
  1909. elif(re.match('(?P<name>.*) end$', t.name)):
  1910. isbegin = False
  1911. else:
  1912. continue
  1913. m = re.match('(?P<name>.*)\[(?P<val>[0-9]*)\] .*', t.name)
  1914. if(m):
  1915. val = m.group('val')
  1916. if val == '0':
  1917. name = m.group('name')
  1918. else:
  1919. name = m.group('name')+'['+val+']'
  1920. else:
  1921. m = re.match('(?P<name>.*) .*', t.name)
  1922. name = m.group('name')
  1923. # special processing for trace events
  1924. if re.match('dpm_prepare\[.*', name):
  1925. continue
  1926. elif re.match('machine_suspend.*', name):
  1927. continue
  1928. elif re.match('suspend_enter\[.*', name):
  1929. if(not isbegin):
  1930. data.dmesg['suspend_prepare']['end'] = t.time
  1931. continue
  1932. elif re.match('dpm_suspend\[.*', name):
  1933. if(not isbegin):
  1934. data.dmesg['suspend']['end'] = t.time
  1935. continue
  1936. elif re.match('dpm_suspend_late\[.*', name):
  1937. if(isbegin):
  1938. data.dmesg['suspend_late']['start'] = t.time
  1939. else:
  1940. data.dmesg['suspend_late']['end'] = t.time
  1941. continue
  1942. elif re.match('dpm_suspend_noirq\[.*', name):
  1943. if(isbegin):
  1944. data.dmesg['suspend_noirq']['start'] = t.time
  1945. else:
  1946. data.dmesg['suspend_noirq']['end'] = t.time
  1947. continue
  1948. elif re.match('dpm_resume_noirq\[.*', name):
  1949. if(isbegin):
  1950. data.dmesg['resume_machine']['end'] = t.time
  1951. data.dmesg['resume_noirq']['start'] = t.time
  1952. else:
  1953. data.dmesg['resume_noirq']['end'] = t.time
  1954. continue
  1955. elif re.match('dpm_resume_early\[.*', name):
  1956. if(isbegin):
  1957. data.dmesg['resume_early']['start'] = t.time
  1958. else:
  1959. data.dmesg['resume_early']['end'] = t.time
  1960. continue
  1961. elif re.match('dpm_resume\[.*', name):
  1962. if(isbegin):
  1963. data.dmesg['resume']['start'] = t.time
  1964. else:
  1965. data.dmesg['resume']['end'] = t.time
  1966. continue
  1967. elif re.match('dpm_complete\[.*', name):
  1968. if(isbegin):
  1969. data.dmesg['resume_complete']['start'] = t.time
  1970. else:
  1971. data.dmesg['resume_complete']['end'] = t.time
  1972. continue
  1973. # skip trace events inside devices calls
  1974. if(not data.isTraceEventOutsideDeviceCalls(pid, t.time)):
  1975. continue
  1976. # global events (outside device calls) are simply graphed
  1977. if(isbegin):
  1978. # store each trace event in ttemp
  1979. if(name not in testrun[testidx].ttemp):
  1980. testrun[testidx].ttemp[name] = []
  1981. testrun[testidx].ttemp[name].append(\
  1982. {'begin': t.time, 'end': t.time})
  1983. else:
  1984. # finish off matching trace event in ttemp
  1985. if(name in testrun[testidx].ttemp):
  1986. testrun[testidx].ttemp[name][-1]['end'] = t.time
  1987. # call/return processing
  1988. elif sysvals.usecallgraph:
  1989. # create a callgraph object for the data
  1990. if(pid not in testrun[testidx].ftemp):
  1991. testrun[testidx].ftemp[pid] = []
  1992. testrun[testidx].ftemp[pid].append(FTraceCallGraph(pid))
  1993. # when the call is finished, see which device matches it
  1994. cg = testrun[testidx].ftemp[pid][-1]
  1995. if(cg.addLine(t)):
  1996. testrun[testidx].ftemp[pid].append(FTraceCallGraph(pid))
  1997. tf.close()
  1998. for test in testrun:
  1999. # add the traceevent data to the device hierarchy
  2000. if(sysvals.usetraceevents):
  2001. for name in test.ttemp:
  2002. for event in test.ttemp[name]:
  2003. test.data.newActionGlobal(name, event['begin'], event['end'])
  2004. # add the callgraph data to the device hierarchy
  2005. for pid in test.ftemp:
  2006. for cg in test.ftemp[pid]:
  2007. if len(cg.list) < 1 or cg.invalid:
  2008. continue
  2009. if(not cg.postProcess()):
  2010. id = 'task %s cpu %s' % (pid, m.group('cpu'))
  2011. vprint('Sanity check failed for '+\
  2012. id+', ignoring this callback')
  2013. continue
  2014. callstart = cg.start
  2015. callend = cg.end
  2016. for p in test.data.phases:
  2017. if(test.data.dmesg[p]['start'] <= callstart and
  2018. callstart <= test.data.dmesg[p]['end']):
  2019. list = test.data.dmesg[p]['list']
  2020. for devname in list:
  2021. dev = list[devname]
  2022. if(pid == dev['pid'] and
  2023. callstart <= dev['start'] and
  2024. callend >= dev['end']):
  2025. dev['ftrace'] = cg
  2026. break
  2027. if(sysvals.verbose):
  2028. test.data.printDetails()
  2029. # Function: parseTraceLog
  2030. # Description:
  2031. # Analyze an ftrace log output file generated from this app during
  2032. # the execution phase. Used when the ftrace log is the primary data source
  2033. # and includes the suspend_resume and device_pm_callback trace events
  2034. # The ftrace filename is taken from sysvals
  2035. # Output:
  2036. # An array of Data objects
  2037. def parseTraceLog():
  2038. global sysvals
  2039. vprint('Analyzing the ftrace data...')
  2040. if(os.path.exists(sysvals.ftracefile) == False):
  2041. doError('%s does not exist' % sysvals.ftracefile, False)
  2042. sysvals.setupAllKprobes()
  2043. tracewatch = ['suspend_enter']
  2044. if sysvals.usekprobes:
  2045. tracewatch += ['sync_filesystems', 'freeze_processes', 'syscore_suspend',
  2046. 'syscore_resume', 'resume_console', 'thaw_processes', 'CPU_ON', 'CPU_OFF']
  2047. # extract the callgraph and traceevent data
  2048. tp = TestProps()
  2049. testruns = []
  2050. testdata = []
  2051. testrun = 0
  2052. data = 0
  2053. tf = open(sysvals.ftracefile, 'r')
  2054. phase = 'suspend_prepare'
  2055. for line in tf:
  2056. # remove any latent carriage returns
  2057. line = line.replace('\r\n', '')
  2058. # stamp line: each stamp means a new test run
  2059. m = re.match(sysvals.stampfmt, line)
  2060. if(m):
  2061. tp.stamp = line
  2062. continue
  2063. # firmware line: pull out any firmware data
  2064. m = re.match(sysvals.firmwarefmt, line)
  2065. if(m):
  2066. tp.fwdata.append((int(m.group('s')), int(m.group('r'))))
  2067. continue
  2068. # tracer type line: determine the trace data type
  2069. m = re.match(sysvals.tracertypefmt, line)
  2070. if(m):
  2071. tp.setTracerType(m.group('t'))
  2072. continue
  2073. # post resume time line: did this test run include post-resume data
  2074. m = re.match(sysvals.postresumefmt, line)
  2075. if(m):
  2076. t = int(m.group('t'))
  2077. if(t > 0):
  2078. sysvals.postresumetime = t
  2079. continue
  2080. # device properties line
  2081. if(re.match(sysvals.devpropfmt, line)):
  2082. devProps(line)
  2083. continue
  2084. # ftrace line: parse only valid lines
  2085. m = re.match(tp.ftrace_line_fmt, line)
  2086. if(not m):
  2087. continue
  2088. # gather the basic message data from the line
  2089. m_time = m.group('time')
  2090. m_proc = m.group('proc')
  2091. m_pid = m.group('pid')
  2092. m_msg = m.group('msg')
  2093. if(tp.cgformat):
  2094. m_param3 = m.group('dur')
  2095. else:
  2096. m_param3 = 'traceevent'
  2097. if(m_time and m_pid and m_msg):
  2098. t = FTraceLine(m_time, m_msg, m_param3)
  2099. pid = int(m_pid)
  2100. else:
  2101. continue
  2102. # the line should be a call, return, or event
  2103. if(not t.fcall and not t.freturn and not t.fevent):
  2104. continue
  2105. # find the start of suspend
  2106. if(t.startMarker()):
  2107. phase = 'suspend_prepare'
  2108. data = Data(len(testdata))
  2109. testdata.append(data)
  2110. testrun = TestRun(data)
  2111. testruns.append(testrun)
  2112. parseStamp(tp.stamp, data)
  2113. if len(tp.fwdata) > data.testnumber:
  2114. data.fwSuspend, data.fwResume = tp.fwdata[data.testnumber]
  2115. if(data.fwSuspend > 0 or data.fwResume > 0):
  2116. data.fwValid = True
  2117. data.setStart(t.time)
  2118. continue
  2119. if(not data):
  2120. continue
  2121. # find the end of resume
  2122. if(t.endMarker()):
  2123. if(sysvals.usetracemarkers and sysvals.postresumetime > 0):
  2124. phase = 'post_resume'
  2125. data.newPhase(phase, t.time, t.time, '#F0F0F0', -1)
  2126. data.setEnd(t.time)
  2127. if(not sysvals.usetracemarkers):
  2128. # no trace markers? then quit and be sure to finish recording
  2129. # the event we used to trigger resume end
  2130. if(len(testrun.ttemp['thaw_processes']) > 0):
  2131. # if an entry exists, assume this is its end
  2132. testrun.ttemp['thaw_processes'][-1]['end'] = t.time
  2133. break
  2134. continue
  2135. # trace event processing
  2136. if(t.fevent):
  2137. if(phase == 'post_resume'):
  2138. data.setEnd(t.time)
  2139. if(t.type == 'suspend_resume'):
  2140. # suspend_resume trace events have two types, begin and end
  2141. if(re.match('(?P<name>.*) begin$', t.name)):
  2142. isbegin = True
  2143. elif(re.match('(?P<name>.*) end$', t.name)):
  2144. isbegin = False
  2145. else:
  2146. continue
  2147. m = re.match('(?P<name>.*)\[(?P<val>[0-9]*)\] .*', t.name)
  2148. if(m):
  2149. val = m.group('val')
  2150. if val == '0':
  2151. name = m.group('name')
  2152. else:
  2153. name = m.group('name')+'['+val+']'
  2154. else:
  2155. m = re.match('(?P<name>.*) .*', t.name)
  2156. name = m.group('name')
  2157. # ignore these events
  2158. if(name.split('[')[0] in tracewatch):
  2159. continue
  2160. # -- phase changes --
  2161. # suspend_prepare start
  2162. if(re.match('dpm_prepare\[.*', t.name)):
  2163. phase = 'suspend_prepare'
  2164. if(not isbegin):
  2165. data.dmesg[phase]['end'] = t.time
  2166. continue
  2167. # suspend start
  2168. elif(re.match('dpm_suspend\[.*', t.name)):
  2169. phase = 'suspend'
  2170. data.setPhase(phase, t.time, isbegin)
  2171. continue
  2172. # suspend_late start
  2173. elif(re.match('dpm_suspend_late\[.*', t.name)):
  2174. phase = 'suspend_late'
  2175. data.setPhase(phase, t.time, isbegin)
  2176. continue
  2177. # suspend_noirq start
  2178. elif(re.match('dpm_suspend_noirq\[.*', t.name)):
  2179. phase = 'suspend_noirq'
  2180. data.setPhase(phase, t.time, isbegin)
  2181. if(not isbegin):
  2182. phase = 'suspend_machine'
  2183. data.dmesg[phase]['start'] = t.time
  2184. continue
  2185. # suspend_machine/resume_machine
  2186. elif(re.match('machine_suspend\[.*', t.name)):
  2187. if(isbegin):
  2188. phase = 'suspend_machine'
  2189. data.dmesg[phase]['end'] = t.time
  2190. data.tSuspended = t.time
  2191. else:
  2192. if(sysvals.suspendmode in ['mem', 'disk'] and not tp.S0i3):
  2193. data.dmesg['suspend_machine']['end'] = t.time
  2194. data.tSuspended = t.time
  2195. phase = 'resume_machine'
  2196. data.dmesg[phase]['start'] = t.time
  2197. data.tResumed = t.time
  2198. data.tLow = data.tResumed - data.tSuspended
  2199. continue
  2200. # acpi_suspend
  2201. elif(re.match('acpi_suspend\[.*', t.name)):
  2202. # acpi_suspend[0] S0i3
  2203. if(re.match('acpi_suspend\[0\] begin', t.name)):
  2204. if(sysvals.suspendmode == 'mem'):
  2205. tp.S0i3 = True
  2206. data.dmesg['suspend_machine']['end'] = t.time
  2207. data.tSuspended = t.time
  2208. continue
  2209. # resume_noirq start
  2210. elif(re.match('dpm_resume_noirq\[.*', t.name)):
  2211. phase = 'resume_noirq'
  2212. data.setPhase(phase, t.time, isbegin)
  2213. if(isbegin):
  2214. data.dmesg['resume_machine']['end'] = t.time
  2215. continue
  2216. # resume_early start
  2217. elif(re.match('dpm_resume_early\[.*', t.name)):
  2218. phase = 'resume_early'
  2219. data.setPhase(phase, t.time, isbegin)
  2220. continue
  2221. # resume start
  2222. elif(re.match('dpm_resume\[.*', t.name)):
  2223. phase = 'resume'
  2224. data.setPhase(phase, t.time, isbegin)
  2225. continue
  2226. # resume complete start
  2227. elif(re.match('dpm_complete\[.*', t.name)):
  2228. phase = 'resume_complete'
  2229. if(isbegin):
  2230. data.dmesg[phase]['start'] = t.time
  2231. continue
  2232. # skip trace events inside devices calls
  2233. if(not data.isTraceEventOutsideDeviceCalls(pid, t.time)):
  2234. continue
  2235. # global events (outside device calls) are graphed
  2236. if(name not in testrun.ttemp):
  2237. testrun.ttemp[name] = []
  2238. if(isbegin):
  2239. # create a new list entry
  2240. testrun.ttemp[name].append(\
  2241. {'begin': t.time, 'end': t.time, 'pid': pid})
  2242. else:
  2243. if(len(testrun.ttemp[name]) > 0):
  2244. # if an entry exists, assume this is its end
  2245. testrun.ttemp[name][-1]['end'] = t.time
  2246. elif(phase == 'post_resume'):
  2247. # post resume events can just have ends
  2248. testrun.ttemp[name].append({
  2249. 'begin': data.dmesg[phase]['start'],
  2250. 'end': t.time})
  2251. # device callback start
  2252. elif(t.type == 'device_pm_callback_start'):
  2253. m = re.match('(?P<drv>.*) (?P<d>.*), parent: *(?P<p>.*), .*',\
  2254. t.name);
  2255. if(not m):
  2256. continue
  2257. drv = m.group('drv')
  2258. n = m.group('d')
  2259. p = m.group('p')
  2260. if(n and p):
  2261. data.newAction(phase, n, pid, p, t.time, -1, drv)
  2262. # device callback finish
  2263. elif(t.type == 'device_pm_callback_end'):
  2264. m = re.match('(?P<drv>.*) (?P<d>.*), err.*', t.name);
  2265. if(not m):
  2266. continue
  2267. n = m.group('d')
  2268. list = data.dmesg[phase]['list']
  2269. if(n in list):
  2270. dev = list[n]
  2271. dev['length'] = t.time - dev['start']
  2272. dev['end'] = t.time
  2273. # kprobe event processing
  2274. elif(t.fkprobe):
  2275. kprobename = t.type
  2276. kprobedata = t.name
  2277. key = (kprobename, pid)
  2278. # displayname is generated from kprobe data
  2279. displayname = ''
  2280. if(t.fcall):
  2281. displayname = sysvals.kprobeDisplayName(kprobename, kprobedata)
  2282. if not displayname:
  2283. continue
  2284. if(key not in tp.ktemp):
  2285. tp.ktemp[key] = []
  2286. tp.ktemp[key].append({
  2287. 'pid': pid,
  2288. 'begin': t.time,
  2289. 'end': t.time,
  2290. 'name': displayname,
  2291. 'cdata': kprobedata,
  2292. 'proc': m_proc,
  2293. })
  2294. elif(t.freturn):
  2295. if(key not in tp.ktemp) or len(tp.ktemp[key]) < 1:
  2296. continue
  2297. e = tp.ktemp[key][-1]
  2298. if e['begin'] < 0.0 or t.time - e['begin'] < 0.000001:
  2299. tp.ktemp[key].pop()
  2300. else:
  2301. e['end'] = t.time
  2302. e['rdata'] = kprobedata
  2303. # callgraph processing
  2304. elif sysvals.usecallgraph:
  2305. # create a callgraph object for the data
  2306. key = (m_proc, pid)
  2307. if(key not in testrun.ftemp):
  2308. testrun.ftemp[key] = []
  2309. testrun.ftemp[key].append(FTraceCallGraph(pid))
  2310. # when the call is finished, see which device matches it
  2311. cg = testrun.ftemp[key][-1]
  2312. if(cg.addLine(t)):
  2313. testrun.ftemp[key].append(FTraceCallGraph(pid))
  2314. tf.close()
  2315. if sysvals.suspendmode == 'command':
  2316. for test in testruns:
  2317. for p in test.data.phases:
  2318. if p == 'resume_complete':
  2319. test.data.dmesg[p]['start'] = test.data.start
  2320. test.data.dmesg[p]['end'] = test.data.end
  2321. else:
  2322. test.data.dmesg[p]['start'] = test.data.start
  2323. test.data.dmesg[p]['end'] = test.data.start
  2324. test.data.tSuspended = test.data.start
  2325. test.data.tResumed = test.data.start
  2326. test.data.tLow = 0
  2327. test.data.fwValid = False
  2328. for test in testruns:
  2329. # add the traceevent data to the device hierarchy
  2330. if(sysvals.usetraceevents):
  2331. # add actual trace funcs
  2332. for name in test.ttemp:
  2333. for event in test.ttemp[name]:
  2334. test.data.newActionGlobal(name, event['begin'], event['end'], event['pid'])
  2335. # add the kprobe based virtual tracefuncs as actual devices
  2336. for key in tp.ktemp:
  2337. name, pid = key
  2338. if name not in sysvals.tracefuncs:
  2339. continue
  2340. for e in tp.ktemp[key]:
  2341. kb, ke = e['begin'], e['end']
  2342. if kb == ke or not test.data.isInsideTimeline(kb, ke):
  2343. continue
  2344. test.data.newActionGlobal(e['name'], kb, ke, pid)
  2345. # add config base kprobes and dev kprobes
  2346. for key in tp.ktemp:
  2347. name, pid = key
  2348. if name in sysvals.tracefuncs:
  2349. continue
  2350. for e in tp.ktemp[key]:
  2351. kb, ke = e['begin'], e['end']
  2352. if kb == ke or not test.data.isInsideTimeline(kb, ke):
  2353. continue
  2354. color = sysvals.kprobeColor(e['name'])
  2355. if name not in sysvals.dev_tracefuncs:
  2356. # config base kprobe
  2357. test.data.newActionGlobal(e['name'], kb, ke, -2, color)
  2358. elif sysvals.usedevsrc:
  2359. # dev kprobe
  2360. data.addDeviceFunctionCall(e['name'], name, e['proc'], pid, kb,
  2361. ke, e['cdata'], e['rdata'])
  2362. if sysvals.usecallgraph:
  2363. # add the callgraph data to the device hierarchy
  2364. sortlist = dict()
  2365. for key in test.ftemp:
  2366. proc, pid = key
  2367. for cg in test.ftemp[key]:
  2368. if len(cg.list) < 1 or cg.invalid:
  2369. continue
  2370. if(not cg.postProcess()):
  2371. id = 'task %s' % (pid)
  2372. vprint('Sanity check failed for '+\
  2373. id+', ignoring this callback')
  2374. continue
  2375. # match cg data to devices
  2376. if sysvals.suspendmode == 'command' or not cg.deviceMatch(pid, test.data):
  2377. sortkey = '%f%f%d' % (cg.start, cg.end, pid)
  2378. sortlist[sortkey] = cg
  2379. # create blocks for orphan cg data
  2380. for sortkey in sorted(sortlist):
  2381. cg = sortlist[sortkey]
  2382. name = cg.list[0].name
  2383. if sysvals.isCallgraphFunc(name):
  2384. vprint('Callgraph found for task %d: %.3fms, %s' % (cg.pid, (cg.end - cg.start)*1000, name))
  2385. cg.newActionFromFunction(test.data)
  2386. if sysvals.suspendmode == 'command':
  2387. if(sysvals.verbose):
  2388. for data in testdata:
  2389. data.printDetails()
  2390. return testdata
  2391. # fill in any missing phases
  2392. for data in testdata:
  2393. lp = data.phases[0]
  2394. for p in data.phases:
  2395. if(data.dmesg[p]['start'] < 0 and data.dmesg[p]['end'] < 0):
  2396. print('WARNING: phase "%s" is missing!' % p)
  2397. if(data.dmesg[p]['start'] < 0):
  2398. data.dmesg[p]['start'] = data.dmesg[lp]['end']
  2399. if(p == 'resume_machine'):
  2400. data.tSuspended = data.dmesg[lp]['end']
  2401. data.tResumed = data.dmesg[lp]['end']
  2402. data.tLow = 0
  2403. if(data.dmesg[p]['end'] < 0):
  2404. data.dmesg[p]['end'] = data.dmesg[p]['start']
  2405. lp = p
  2406. if(len(sysvals.devicefilter) > 0):
  2407. data.deviceFilter(sysvals.devicefilter)
  2408. data.fixupInitcallsThatDidntReturn()
  2409. if(sysvals.verbose):
  2410. data.printDetails()
  2411. return testdata
  2412. # Function: loadRawKernelLog
  2413. # Description:
  2414. # Load a raw kernel log that wasn't created by this tool, it might be
  2415. # possible to extract a valid suspend/resume log
  2416. def loadRawKernelLog(dmesgfile):
  2417. global sysvals
  2418. stamp = {'time': '', 'host': '', 'mode': 'mem', 'kernel': ''}
  2419. stamp['time'] = datetime.now().strftime('%B %d %Y, %I:%M:%S %p')
  2420. stamp['host'] = sysvals.hostname
  2421. testruns = []
  2422. data = 0
  2423. lf = open(dmesgfile, 'r')
  2424. for line in lf:
  2425. line = line.replace('\r\n', '')
  2426. idx = line.find('[')
  2427. if idx > 1:
  2428. line = line[idx:]
  2429. m = re.match('[ \t]*(\[ *)(?P<ktime>[0-9\.]*)(\]) (?P<msg>.*)', line)
  2430. if(not m):
  2431. continue
  2432. msg = m.group("msg")
  2433. m = re.match('PM: Syncing filesystems.*', msg)
  2434. if(m):
  2435. if(data):
  2436. testruns.append(data)
  2437. data = Data(len(testruns))
  2438. data.stamp = stamp
  2439. if(data):
  2440. m = re.match('.* *(?P<k>[0-9]\.[0-9]{2}\.[0-9]-.*) .*', msg)
  2441. if(m):
  2442. stamp['kernel'] = m.group('k')
  2443. m = re.match('PM: Preparing system for (?P<m>.*) sleep', msg)
  2444. if(m):
  2445. stamp['mode'] = m.group('m')
  2446. data.dmesgtext.append(line)
  2447. if(data):
  2448. testruns.append(data)
  2449. sysvals.stamp = stamp
  2450. sysvals.suspendmode = stamp['mode']
  2451. lf.close()
  2452. return testruns
  2453. # Function: loadKernelLog
  2454. # Description:
  2455. # [deprecated for kernel 3.15.0 or newer]
  2456. # load the dmesg file into memory and fix up any ordering issues
  2457. # The dmesg filename is taken from sysvals
  2458. # Output:
  2459. # An array of empty Data objects with only their dmesgtext attributes set
  2460. def loadKernelLog():
  2461. global sysvals
  2462. vprint('Analyzing the dmesg data...')
  2463. if(os.path.exists(sysvals.dmesgfile) == False):
  2464. doError('%s does not exist' % sysvals.dmesgfile, False)
  2465. # there can be multiple test runs in a single file
  2466. tp = TestProps()
  2467. testruns = []
  2468. data = 0
  2469. lf = open(sysvals.dmesgfile, 'r')
  2470. for line in lf:
  2471. line = line.replace('\r\n', '')
  2472. idx = line.find('[')
  2473. if idx > 1:
  2474. line = line[idx:]
  2475. m = re.match(sysvals.stampfmt, line)
  2476. if(m):
  2477. tp.stamp = line
  2478. continue
  2479. m = re.match(sysvals.firmwarefmt, line)
  2480. if(m):
  2481. tp.fwdata.append((int(m.group('s')), int(m.group('r'))))
  2482. continue
  2483. m = re.match('[ \t]*(\[ *)(?P<ktime>[0-9\.]*)(\]) (?P<msg>.*)', line)
  2484. if(not m):
  2485. continue
  2486. msg = m.group("msg")
  2487. if(re.match('PM: Syncing filesystems.*', msg)):
  2488. if(data):
  2489. testruns.append(data)
  2490. data = Data(len(testruns))
  2491. parseStamp(tp.stamp, data)
  2492. if len(tp.fwdata) > data.testnumber:
  2493. data.fwSuspend, data.fwResume = tp.fwdata[data.testnumber]
  2494. if(data.fwSuspend > 0 or data.fwResume > 0):
  2495. data.fwValid = True
  2496. if(re.match('ACPI: resume from mwait', msg)):
  2497. print('NOTE: This suspend appears to be freeze rather than'+\
  2498. ' %s, it will be treated as such' % sysvals.suspendmode)
  2499. sysvals.suspendmode = 'freeze'
  2500. if(not data):
  2501. continue
  2502. data.dmesgtext.append(line)
  2503. if(data):
  2504. testruns.append(data)
  2505. lf.close()
  2506. if(len(testruns) < 1):
  2507. # bad log, but see if you can extract something meaningful anyway
  2508. testruns = loadRawKernelLog(sysvals.dmesgfile)
  2509. if(len(testruns) < 1):
  2510. doError(' dmesg log is completely unreadable: %s' \
  2511. % sysvals.dmesgfile, False)
  2512. # fix lines with same timestamp/function with the call and return swapped
  2513. for data in testruns:
  2514. last = ''
  2515. for line in data.dmesgtext:
  2516. mc = re.match('.*(\[ *)(?P<t>[0-9\.]*)(\]) calling '+\
  2517. '(?P<f>.*)\+ @ .*, parent: .*', line)
  2518. mr = re.match('.*(\[ *)(?P<t>[0-9\.]*)(\]) call '+\
  2519. '(?P<f>.*)\+ returned .* after (?P<dt>.*) usecs', last)
  2520. if(mc and mr and (mc.group('t') == mr.group('t')) and
  2521. (mc.group('f') == mr.group('f'))):
  2522. i = data.dmesgtext.index(last)
  2523. j = data.dmesgtext.index(line)
  2524. data.dmesgtext[i] = line
  2525. data.dmesgtext[j] = last
  2526. last = line
  2527. return testruns
  2528. # Function: parseKernelLog
  2529. # Description:
  2530. # [deprecated for kernel 3.15.0 or newer]
  2531. # Analyse a dmesg log output file generated from this app during
  2532. # the execution phase. Create a set of device structures in memory
  2533. # for subsequent formatting in the html output file
  2534. # This call is only for legacy support on kernels where the ftrace
  2535. # data lacks the suspend_resume or device_pm_callbacks trace events.
  2536. # Arguments:
  2537. # data: an empty Data object (with dmesgtext) obtained from loadKernelLog
  2538. # Output:
  2539. # The filled Data object
  2540. def parseKernelLog(data):
  2541. global sysvals
  2542. phase = 'suspend_runtime'
  2543. if(data.fwValid):
  2544. vprint('Firmware Suspend = %u ns, Firmware Resume = %u ns' % \
  2545. (data.fwSuspend, data.fwResume))
  2546. # dmesg phase match table
  2547. dm = {
  2548. 'suspend_prepare': 'PM: Syncing filesystems.*',
  2549. 'suspend': 'PM: Entering [a-z]* sleep.*',
  2550. 'suspend_late': 'PM: suspend of devices complete after.*',
  2551. 'suspend_noirq': 'PM: late suspend of devices complete after.*',
  2552. 'suspend_machine': 'PM: noirq suspend of devices complete after.*',
  2553. 'resume_machine': 'ACPI: Low-level resume complete.*',
  2554. 'resume_noirq': 'ACPI: Waking up from system sleep state.*',
  2555. 'resume_early': 'PM: noirq resume of devices complete after.*',
  2556. 'resume': 'PM: early resume of devices complete after.*',
  2557. 'resume_complete': 'PM: resume of devices complete after.*',
  2558. 'post_resume': '.*Restarting tasks \.\.\..*',
  2559. }
  2560. if(sysvals.suspendmode == 'standby'):
  2561. dm['resume_machine'] = 'PM: Restoring platform NVS memory'
  2562. elif(sysvals.suspendmode == 'disk'):
  2563. dm['suspend_late'] = 'PM: freeze of devices complete after.*'
  2564. dm['suspend_noirq'] = 'PM: late freeze of devices complete after.*'
  2565. dm['suspend_machine'] = 'PM: noirq freeze of devices complete after.*'
  2566. dm['resume_machine'] = 'PM: Restoring platform NVS memory'
  2567. dm['resume_early'] = 'PM: noirq restore of devices complete after.*'
  2568. dm['resume'] = 'PM: early restore of devices complete after.*'
  2569. dm['resume_complete'] = 'PM: restore of devices complete after.*'
  2570. elif(sysvals.suspendmode == 'freeze'):
  2571. dm['resume_machine'] = 'ACPI: resume from mwait'
  2572. # action table (expected events that occur and show up in dmesg)
  2573. at = {
  2574. 'sync_filesystems': {
  2575. 'smsg': 'PM: Syncing filesystems.*',
  2576. 'emsg': 'PM: Preparing system for mem sleep.*' },
  2577. 'freeze_user_processes': {
  2578. 'smsg': 'Freezing user space processes .*',
  2579. 'emsg': 'Freezing remaining freezable tasks.*' },
  2580. 'freeze_tasks': {
  2581. 'smsg': 'Freezing remaining freezable tasks.*',
  2582. 'emsg': 'PM: Entering (?P<mode>[a-z,A-Z]*) sleep.*' },
  2583. 'ACPI prepare': {
  2584. 'smsg': 'ACPI: Preparing to enter system sleep state.*',
  2585. 'emsg': 'PM: Saving platform NVS memory.*' },
  2586. 'PM vns': {
  2587. 'smsg': 'PM: Saving platform NVS memory.*',
  2588. 'emsg': 'Disabling non-boot CPUs .*' },
  2589. }
  2590. t0 = -1.0
  2591. cpu_start = -1.0
  2592. prevktime = -1.0
  2593. actions = dict()
  2594. for line in data.dmesgtext:
  2595. # -- preprocessing --
  2596. # parse each dmesg line into the time and message
  2597. m = re.match('[ \t]*(\[ *)(?P<ktime>[0-9\.]*)(\]) (?P<msg>.*)', line)
  2598. if(m):
  2599. val = m.group('ktime')
  2600. try:
  2601. ktime = float(val)
  2602. except:
  2603. doWarning('INVALID DMESG LINE: '+\
  2604. line.replace('\n', ''), 'dmesg')
  2605. continue
  2606. msg = m.group('msg')
  2607. # initialize data start to first line time
  2608. if t0 < 0:
  2609. data.setStart(ktime)
  2610. t0 = ktime
  2611. else:
  2612. continue
  2613. # hack for determining resume_machine end for freeze
  2614. if(not sysvals.usetraceevents and sysvals.suspendmode == 'freeze' \
  2615. and phase == 'resume_machine' and \
  2616. re.match('calling (?P<f>.*)\+ @ .*, parent: .*', msg)):
  2617. data.dmesg['resume_machine']['end'] = ktime
  2618. phase = 'resume_noirq'
  2619. data.dmesg[phase]['start'] = ktime
  2620. # -- phase changes --
  2621. # suspend start
  2622. if(re.match(dm['suspend_prepare'], msg)):
  2623. phase = 'suspend_prepare'
  2624. data.dmesg[phase]['start'] = ktime
  2625. data.setStart(ktime)
  2626. # suspend start
  2627. elif(re.match(dm['suspend'], msg)):
  2628. data.dmesg['suspend_prepare']['end'] = ktime
  2629. phase = 'suspend'
  2630. data.dmesg[phase]['start'] = ktime
  2631. # suspend_late start
  2632. elif(re.match(dm['suspend_late'], msg)):
  2633. data.dmesg['suspend']['end'] = ktime
  2634. phase = 'suspend_late'
  2635. data.dmesg[phase]['start'] = ktime
  2636. # suspend_noirq start
  2637. elif(re.match(dm['suspend_noirq'], msg)):
  2638. data.dmesg['suspend_late']['end'] = ktime
  2639. phase = 'suspend_noirq'
  2640. data.dmesg[phase]['start'] = ktime
  2641. # suspend_machine start
  2642. elif(re.match(dm['suspend_machine'], msg)):
  2643. data.dmesg['suspend_noirq']['end'] = ktime
  2644. phase = 'suspend_machine'
  2645. data.dmesg[phase]['start'] = ktime
  2646. # resume_machine start
  2647. elif(re.match(dm['resume_machine'], msg)):
  2648. if(sysvals.suspendmode in ['freeze', 'standby']):
  2649. data.tSuspended = prevktime
  2650. data.dmesg['suspend_machine']['end'] = prevktime
  2651. else:
  2652. data.tSuspended = ktime
  2653. data.dmesg['suspend_machine']['end'] = ktime
  2654. phase = 'resume_machine'
  2655. data.tResumed = ktime
  2656. data.tLow = data.tResumed - data.tSuspended
  2657. data.dmesg[phase]['start'] = ktime
  2658. # resume_noirq start
  2659. elif(re.match(dm['resume_noirq'], msg)):
  2660. data.dmesg['resume_machine']['end'] = ktime
  2661. phase = 'resume_noirq'
  2662. data.dmesg[phase]['start'] = ktime
  2663. # resume_early start
  2664. elif(re.match(dm['resume_early'], msg)):
  2665. data.dmesg['resume_noirq']['end'] = ktime
  2666. phase = 'resume_early'
  2667. data.dmesg[phase]['start'] = ktime
  2668. # resume start
  2669. elif(re.match(dm['resume'], msg)):
  2670. data.dmesg['resume_early']['end'] = ktime
  2671. phase = 'resume'
  2672. data.dmesg[phase]['start'] = ktime
  2673. # resume complete start
  2674. elif(re.match(dm['resume_complete'], msg)):
  2675. data.dmesg['resume']['end'] = ktime
  2676. phase = 'resume_complete'
  2677. data.dmesg[phase]['start'] = ktime
  2678. # post resume start
  2679. elif(re.match(dm['post_resume'], msg)):
  2680. data.dmesg['resume_complete']['end'] = ktime
  2681. data.setEnd(ktime)
  2682. phase = 'post_resume'
  2683. break
  2684. # -- device callbacks --
  2685. if(phase in data.phases):
  2686. # device init call
  2687. if(re.match('calling (?P<f>.*)\+ @ .*, parent: .*', msg)):
  2688. sm = re.match('calling (?P<f>.*)\+ @ '+\
  2689. '(?P<n>.*), parent: (?P<p>.*)', msg);
  2690. f = sm.group('f')
  2691. n = sm.group('n')
  2692. p = sm.group('p')
  2693. if(f and n and p):
  2694. data.newAction(phase, f, int(n), p, ktime, -1, '')
  2695. # device init return
  2696. elif(re.match('call (?P<f>.*)\+ returned .* after '+\
  2697. '(?P<t>.*) usecs', msg)):
  2698. sm = re.match('call (?P<f>.*)\+ returned .* after '+\
  2699. '(?P<t>.*) usecs(?P<a>.*)', msg);
  2700. f = sm.group('f')
  2701. t = sm.group('t')
  2702. list = data.dmesg[phase]['list']
  2703. if(f in list):
  2704. dev = list[f]
  2705. dev['length'] = int(t)
  2706. dev['end'] = ktime
  2707. # -- non-devicecallback actions --
  2708. # if trace events are not available, these are better than nothing
  2709. if(not sysvals.usetraceevents):
  2710. # look for known actions
  2711. for a in at:
  2712. if(re.match(at[a]['smsg'], msg)):
  2713. if(a not in actions):
  2714. actions[a] = []
  2715. actions[a].append({'begin': ktime, 'end': ktime})
  2716. if(re.match(at[a]['emsg'], msg)):
  2717. if(a in actions):
  2718. actions[a][-1]['end'] = ktime
  2719. # now look for CPU on/off events
  2720. if(re.match('Disabling non-boot CPUs .*', msg)):
  2721. # start of first cpu suspend
  2722. cpu_start = ktime
  2723. elif(re.match('Enabling non-boot CPUs .*', msg)):
  2724. # start of first cpu resume
  2725. cpu_start = ktime
  2726. elif(re.match('smpboot: CPU (?P<cpu>[0-9]*) is now offline', msg)):
  2727. # end of a cpu suspend, start of the next
  2728. m = re.match('smpboot: CPU (?P<cpu>[0-9]*) is now offline', msg)
  2729. cpu = 'CPU'+m.group('cpu')
  2730. if(cpu not in actions):
  2731. actions[cpu] = []
  2732. actions[cpu].append({'begin': cpu_start, 'end': ktime})
  2733. cpu_start = ktime
  2734. elif(re.match('CPU(?P<cpu>[0-9]*) is up', msg)):
  2735. # end of a cpu resume, start of the next
  2736. m = re.match('CPU(?P<cpu>[0-9]*) is up', msg)
  2737. cpu = 'CPU'+m.group('cpu')
  2738. if(cpu not in actions):
  2739. actions[cpu] = []
  2740. actions[cpu].append({'begin': cpu_start, 'end': ktime})
  2741. cpu_start = ktime
  2742. prevktime = ktime
  2743. # fill in any missing phases
  2744. lp = data.phases[0]
  2745. for p in data.phases:
  2746. if(data.dmesg[p]['start'] < 0 and data.dmesg[p]['end'] < 0):
  2747. print('WARNING: phase "%s" is missing, something went wrong!' % p)
  2748. print(' In %s, this dmesg line denotes the start of %s:' % \
  2749. (sysvals.suspendmode, p))
  2750. print(' "%s"' % dm[p])
  2751. if(data.dmesg[p]['start'] < 0):
  2752. data.dmesg[p]['start'] = data.dmesg[lp]['end']
  2753. if(p == 'resume_machine'):
  2754. data.tSuspended = data.dmesg[lp]['end']
  2755. data.tResumed = data.dmesg[lp]['end']
  2756. data.tLow = 0
  2757. if(data.dmesg[p]['end'] < 0):
  2758. data.dmesg[p]['end'] = data.dmesg[p]['start']
  2759. lp = p
  2760. # fill in any actions we've found
  2761. for name in actions:
  2762. for event in actions[name]:
  2763. data.newActionGlobal(name, event['begin'], event['end'])
  2764. if(sysvals.verbose):
  2765. data.printDetails()
  2766. if(len(sysvals.devicefilter) > 0):
  2767. data.deviceFilter(sysvals.devicefilter)
  2768. data.fixupInitcallsThatDidntReturn()
  2769. return True
  2770. # Function: createHTMLSummarySimple
  2771. # Description:
  2772. # Create summary html file for a series of tests
  2773. # Arguments:
  2774. # testruns: array of Data objects from parseTraceLog
  2775. def createHTMLSummarySimple(testruns, htmlfile):
  2776. global sysvals
  2777. # print out the basic summary of all the tests
  2778. hf = open(htmlfile, 'w')
  2779. # write the html header first (html head, css code, up to body start)
  2780. html = '<!DOCTYPE html>\n<html>\n<head>\n\
  2781. <meta http-equiv="content-type" content="text/html; charset=UTF-8">\n\
  2782. <title>AnalyzeSuspend Summary</title>\n\
  2783. <style type=\'text/css\'>\n\
  2784. body {overflow-y: scroll;}\n\
  2785. .stamp {width: 100%;text-align:center;background-color:#495E09;line-height:30px;color:white;font: 25px Arial;}\n\
  2786. table {width:100%;border-collapse: collapse;}\n\
  2787. .summary {font: 22px Arial;border:1px solid;}\n\
  2788. th {border: 1px solid black;background-color:#A7C942;color:white;}\n\
  2789. td {text-align: center;}\n\
  2790. tr.alt td {background-color:#EAF2D3;}\n\
  2791. tr.avg td {background-color:#BDE34C;}\n\
  2792. a:link {color: #90B521;}\n\
  2793. a:visited {color: #495E09;}\n\
  2794. a:hover {color: #B1DF28;}\n\
  2795. a:active {color: #FFFFFF;}\n\
  2796. </style>\n</head>\n<body>\n'
  2797. # group test header
  2798. count = len(testruns)
  2799. headline_stamp = '<div class="stamp">{0} {1} {2} {3} ({4} tests)</div>\n'
  2800. html += headline_stamp.format(sysvals.stamp['host'],
  2801. sysvals.stamp['kernel'], sysvals.stamp['mode'],
  2802. sysvals.stamp['time'], count)
  2803. # check to see if all the tests have the same value
  2804. stampcolumns = False
  2805. for data in testruns:
  2806. if diffStamp(sysvals.stamp, data.stamp):
  2807. stampcolumns = True
  2808. break
  2809. th = '\t<th>{0}</th>\n'
  2810. td = '\t<td>{0}</td>\n'
  2811. tdlink = '\t<td><a href="{0}">Click Here</a></td>\n'
  2812. # table header
  2813. html += '<table class="summary">\n<tr>\n'
  2814. html += th.format("Test #")
  2815. if stampcolumns:
  2816. html += th.format("Hostname")
  2817. html += th.format("Kernel Version")
  2818. html += th.format("Suspend Mode")
  2819. html += th.format("Test Time")
  2820. html += th.format("Suspend Time")
  2821. html += th.format("Resume Time")
  2822. html += th.format("Detail")
  2823. html += '</tr>\n'
  2824. # test data, 1 row per test
  2825. sTimeAvg = 0.0
  2826. rTimeAvg = 0.0
  2827. num = 1
  2828. for data in testruns:
  2829. # data.end is the end of post_resume
  2830. resumeEnd = data.dmesg['resume_complete']['end']
  2831. if num % 2 == 1:
  2832. html += '<tr class="alt">\n'
  2833. else:
  2834. html += '<tr>\n'
  2835. # test num
  2836. html += td.format("test %d" % num)
  2837. num += 1
  2838. if stampcolumns:
  2839. # host name
  2840. val = "unknown"
  2841. if('host' in data.stamp):
  2842. val = data.stamp['host']
  2843. html += td.format(val)
  2844. # host kernel
  2845. val = "unknown"
  2846. if('kernel' in data.stamp):
  2847. val = data.stamp['kernel']
  2848. html += td.format(val)
  2849. # suspend mode
  2850. val = "unknown"
  2851. if('mode' in data.stamp):
  2852. val = data.stamp['mode']
  2853. html += td.format(val)
  2854. # test time
  2855. val = "unknown"
  2856. if('time' in data.stamp):
  2857. val = data.stamp['time']
  2858. html += td.format(val)
  2859. # suspend time
  2860. sTime = (data.tSuspended - data.start)*1000
  2861. sTimeAvg += sTime
  2862. html += td.format("%3.3f ms" % sTime)
  2863. # resume time
  2864. rTime = (resumeEnd - data.tResumed)*1000
  2865. rTimeAvg += rTime
  2866. html += td.format("%3.3f ms" % rTime)
  2867. # link to the output html
  2868. html += tdlink.format(data.outfile)
  2869. html += '</tr>\n'
  2870. # last line: test average
  2871. if(count > 0):
  2872. sTimeAvg /= count
  2873. rTimeAvg /= count
  2874. html += '<tr class="avg">\n'
  2875. html += td.format('Average') # name
  2876. if stampcolumns:
  2877. html += td.format('') # host
  2878. html += td.format('') # kernel
  2879. html += td.format('') # mode
  2880. html += td.format('') # time
  2881. html += td.format("%3.3f ms" % sTimeAvg) # suspend time
  2882. html += td.format("%3.3f ms" % rTimeAvg) # resume time
  2883. html += td.format('') # output link
  2884. html += '</tr>\n'
  2885. # flush the data to file
  2886. hf.write(html+'</table>\n')
  2887. hf.write('</body>\n</html>\n')
  2888. hf.close()
  2889. def htmlTitle():
  2890. global sysvals
  2891. modename = {
  2892. 'freeze': 'Freeze (S0)',
  2893. 'standby': 'Standby (S1)',
  2894. 'mem': 'Suspend (S3)',
  2895. 'disk': 'Hibernate (S4)'
  2896. }
  2897. kernel = sysvals.stamp['kernel']
  2898. host = sysvals.hostname[0].upper()+sysvals.hostname[1:]
  2899. mode = sysvals.suspendmode
  2900. if sysvals.suspendmode in modename:
  2901. mode = modename[sysvals.suspendmode]
  2902. return host+' '+mode+' '+kernel
  2903. def ordinal(value):
  2904. suffix = 'th'
  2905. if value < 10 or value > 19:
  2906. if value % 10 == 1:
  2907. suffix = 'st'
  2908. elif value % 10 == 2:
  2909. suffix = 'nd'
  2910. elif value % 10 == 3:
  2911. suffix = 'rd'
  2912. return '%d%s' % (value, suffix)
  2913. # Function: createHTML
  2914. # Description:
  2915. # Create the output html file from the resident test data
  2916. # Arguments:
  2917. # testruns: array of Data objects from parseKernelLog or parseTraceLog
  2918. # Output:
  2919. # True if the html file was created, false if it failed
  2920. def createHTML(testruns):
  2921. global sysvals
  2922. if len(testruns) < 1:
  2923. print('ERROR: Not enough test data to build a timeline')
  2924. return
  2925. for data in testruns:
  2926. data.normalizeTime(testruns[-1].tSuspended)
  2927. x2changes = ['', 'absolute']
  2928. if len(testruns) > 1:
  2929. x2changes = ['1', 'relative']
  2930. # html function templates
  2931. headline_version = '<div class="version"><a href="https://01.org/suspendresume">AnalyzeSuspend v%s</a></div>' % sysvals.version
  2932. headline_stamp = '<div class="stamp">{0} {1} {2} {3}</div>\n'
  2933. html_devlist1 = '<button id="devlist1" class="devlist" style="float:left;">Device Detail%s</button>' % x2changes[0]
  2934. html_zoombox = '<center><button id="zoomin">ZOOM IN</button><button id="zoomout">ZOOM OUT</button><button id="zoomdef">ZOOM 1:1</button></center>\n'
  2935. html_devlist2 = '<button id="devlist2" class="devlist" style="float:right;">Device Detail2</button>\n'
  2936. html_timeline = '<div id="dmesgzoombox" class="zoombox">\n<div id="{0}" class="timeline" style="height:{1}px">\n'
  2937. html_tblock = '<div id="block{0}" class="tblock" style="left:{1}%;width:{2}%;">\n'
  2938. 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'
  2939. html_traceevent = '<div title="{0}" class="traceevent" style="left:{1}%;top:{2}px;height:{3}px;width:{4}%;line-height:{3}px;">{5}</div>\n'
  2940. html_phase = '<div class="phase" style="left:{0}%;width:{1}%;top:{2}px;height:{3}px;background-color:{4}">{5}</div>\n'
  2941. html_phaselet = '<div id="{0}" class="phaselet" style="left:{1}%;width:{2}%;background-color:{3}"></div>\n'
  2942. html_legend = '<div id="p{3}" class="square" style="left:{0}%;background-color:{1}">&nbsp;{2}</div>\n'
  2943. html_timetotal = '<table class="time1">\n<tr>'\
  2944. '<td class="green">{2} Suspend Time: <b>{0} ms</b></td>'\
  2945. '<td class="yellow">{2} Resume Time: <b>{1} ms</b></td>'\
  2946. '</tr>\n</table>\n'
  2947. html_timetotal2 = '<table class="time1">\n<tr>'\
  2948. '<td class="green">{3} Suspend Time: <b>{0} ms</b></td>'\
  2949. '<td class="gray">'+sysvals.suspendmode+' time: <b>{1} ms</b></td>'\
  2950. '<td class="yellow">{3} Resume Time: <b>{2} ms</b></td>'\
  2951. '</tr>\n</table>\n'
  2952. html_timetotal3 = '<table class="time1">\n<tr>'\
  2953. '<td class="green">Execution Time: <b>{0} ms</b></td>'\
  2954. '<td class="yellow">Command: <b>{1}</b></td>'\
  2955. '</tr>\n</table>\n'
  2956. html_timegroups = '<table class="time2">\n<tr>'\
  2957. '<td class="green">{4}Kernel Suspend: {0} ms</td>'\
  2958. '<td class="purple">{4}Firmware Suspend: {1} ms</td>'\
  2959. '<td class="purple">{4}Firmware Resume: {2} ms</td>'\
  2960. '<td class="yellow">{4}Kernel Resume: {3} ms</td>'\
  2961. '</tr>\n</table>\n'
  2962. # html format variables
  2963. rowheight = 30
  2964. devtextS = '14px'
  2965. devtextH = '30px'
  2966. hoverZ = 'z-index:10;'
  2967. if sysvals.usedevsrc:
  2968. hoverZ = ''
  2969. # device timeline
  2970. vprint('Creating Device Timeline...')
  2971. devtl = Timeline(rowheight)
  2972. # Generate the header for this timeline
  2973. for data in testruns:
  2974. tTotal = data.end - data.start
  2975. tEnd = data.dmesg['resume_complete']['end']
  2976. if(tTotal == 0):
  2977. print('ERROR: No timeline data')
  2978. sys.exit()
  2979. if(data.tLow > 0):
  2980. low_time = '%.0f'%(data.tLow*1000)
  2981. if sysvals.suspendmode == 'command':
  2982. run_time = '%.0f'%((data.end-data.start)*1000)
  2983. if sysvals.testcommand:
  2984. testdesc = sysvals.testcommand
  2985. else:
  2986. testdesc = 'unknown'
  2987. if(len(testruns) > 1):
  2988. testdesc = ordinal(data.testnumber+1)+' '+testdesc
  2989. thtml = html_timetotal3.format(run_time, testdesc)
  2990. devtl.html['header'] += thtml
  2991. elif data.fwValid:
  2992. suspend_time = '%.0f'%((data.tSuspended-data.start)*1000 + \
  2993. (data.fwSuspend/1000000.0))
  2994. resume_time = '%.0f'%((tEnd-data.tSuspended)*1000 + \
  2995. (data.fwResume/1000000.0))
  2996. testdesc1 = 'Total'
  2997. testdesc2 = ''
  2998. if(len(testruns) > 1):
  2999. testdesc1 = testdesc2 = ordinal(data.testnumber+1)
  3000. testdesc2 += ' '
  3001. if(data.tLow == 0):
  3002. thtml = html_timetotal.format(suspend_time, \
  3003. resume_time, testdesc1)
  3004. else:
  3005. thtml = html_timetotal2.format(suspend_time, low_time, \
  3006. resume_time, testdesc1)
  3007. devtl.html['header'] += thtml
  3008. sktime = '%.3f'%((data.dmesg['suspend_machine']['end'] - \
  3009. data.getStart())*1000)
  3010. sftime = '%.3f'%(data.fwSuspend / 1000000.0)
  3011. rftime = '%.3f'%(data.fwResume / 1000000.0)
  3012. rktime = '%.3f'%((data.dmesg['resume_complete']['end'] - \
  3013. data.dmesg['resume_machine']['start'])*1000)
  3014. devtl.html['header'] += html_timegroups.format(sktime, \
  3015. sftime, rftime, rktime, testdesc2)
  3016. else:
  3017. suspend_time = '%.0f'%((data.tSuspended-data.start)*1000)
  3018. resume_time = '%.0f'%((tEnd-data.tSuspended)*1000)
  3019. testdesc = 'Kernel'
  3020. if(len(testruns) > 1):
  3021. testdesc = ordinal(data.testnumber+1)+' '+testdesc
  3022. if(data.tLow == 0):
  3023. thtml = html_timetotal.format(suspend_time, \
  3024. resume_time, testdesc)
  3025. else:
  3026. thtml = html_timetotal2.format(suspend_time, low_time, \
  3027. resume_time, testdesc)
  3028. devtl.html['header'] += thtml
  3029. # time scale for potentially multiple datasets
  3030. t0 = testruns[0].start
  3031. tMax = testruns[-1].end
  3032. tSuspended = testruns[-1].tSuspended
  3033. tTotal = tMax - t0
  3034. # determine the maximum number of rows we need to draw
  3035. for data in testruns:
  3036. data.selectTimelineDevices('%f', tTotal, sysvals.mindevlen)
  3037. for group in data.devicegroups:
  3038. devlist = []
  3039. for phase in group:
  3040. for devname in data.tdevlist[phase]:
  3041. devlist.append((phase,devname))
  3042. devtl.getPhaseRows(data.dmesg, devlist)
  3043. devtl.calcTotalRows()
  3044. # create bounding box, add buttons
  3045. if sysvals.suspendmode != 'command':
  3046. devtl.html['timeline'] += html_devlist1
  3047. if len(testruns) > 1:
  3048. devtl.html['timeline'] += html_devlist2
  3049. devtl.html['timeline'] += html_zoombox
  3050. devtl.html['timeline'] += html_timeline.format('dmesg', devtl.height)
  3051. # draw the full timeline
  3052. phases = {'suspend':[],'resume':[]}
  3053. for phase in data.dmesg:
  3054. if 'resume' in phase:
  3055. phases['resume'].append(phase)
  3056. else:
  3057. phases['suspend'].append(phase)
  3058. # draw each test run chronologically
  3059. for data in testruns:
  3060. # if nore than one test, draw a block to represent user mode
  3061. if(data.testnumber > 0):
  3062. m0 = testruns[data.testnumber-1].end
  3063. mMax = testruns[data.testnumber].start
  3064. mTotal = mMax - m0
  3065. name = 'usermode%d' % data.testnumber
  3066. top = '%d' % devtl.scaleH
  3067. left = '%f' % (((m0-t0)*100.0)/tTotal)
  3068. width = '%f' % ((mTotal*100.0)/tTotal)
  3069. title = 'user mode (%0.3f ms) ' % (mTotal*1000)
  3070. devtl.html['timeline'] += html_device.format(name, \
  3071. title, left, top, '%d'%devtl.bodyH, width, '', '', '')
  3072. # now draw the actual timeline blocks
  3073. for dir in phases:
  3074. # draw suspend and resume blocks separately
  3075. bname = '%s%d' % (dir[0], data.testnumber)
  3076. if dir == 'suspend':
  3077. m0 = testruns[data.testnumber].start
  3078. mMax = testruns[data.testnumber].tSuspended
  3079. mTotal = mMax - m0
  3080. left = '%f' % (((m0-t0)*100.0)/tTotal)
  3081. else:
  3082. m0 = testruns[data.testnumber].tSuspended
  3083. mMax = testruns[data.testnumber].end
  3084. mTotal = mMax - m0
  3085. left = '%f' % ((((m0-t0)*100.0)+sysvals.srgap/2)/tTotal)
  3086. # if a timeline block is 0 length, skip altogether
  3087. if mTotal == 0:
  3088. continue
  3089. width = '%f' % (((mTotal*100.0)-sysvals.srgap/2)/tTotal)
  3090. devtl.html['timeline'] += html_tblock.format(bname, left, width)
  3091. for b in sorted(phases[dir]):
  3092. # draw the phase color background
  3093. phase = data.dmesg[b]
  3094. length = phase['end']-phase['start']
  3095. left = '%f' % (((phase['start']-m0)*100.0)/mTotal)
  3096. width = '%f' % ((length*100.0)/mTotal)
  3097. devtl.html['timeline'] += html_phase.format(left, width, \
  3098. '%.3f'%devtl.scaleH, '%.3f'%devtl.bodyH, \
  3099. data.dmesg[b]['color'], '')
  3100. # draw the devices for this phase
  3101. phaselist = data.dmesg[b]['list']
  3102. for d in data.tdevlist[b]:
  3103. name = d
  3104. drv = ''
  3105. dev = phaselist[d]
  3106. xtraclass = ''
  3107. xtrainfo = ''
  3108. xtrastyle = ''
  3109. if 'htmlclass' in dev:
  3110. xtraclass = dev['htmlclass']
  3111. xtrainfo = dev['htmlclass']
  3112. if 'color' in dev:
  3113. xtrastyle = 'background-color:%s;' % dev['color']
  3114. if(d in sysvals.devprops):
  3115. name = sysvals.devprops[d].altName(d)
  3116. xtraclass = sysvals.devprops[d].xtraClass()
  3117. xtrainfo = sysvals.devprops[d].xtraInfo()
  3118. if('drv' in dev and dev['drv']):
  3119. drv = ' {%s}' % dev['drv']
  3120. rowheight = devtl.phaseRowHeight(b, dev['row'])
  3121. rowtop = devtl.phaseRowTop(b, dev['row'])
  3122. top = '%.3f' % (rowtop + devtl.scaleH)
  3123. left = '%f' % (((dev['start']-m0)*100)/mTotal)
  3124. width = '%f' % (((dev['end']-dev['start'])*100)/mTotal)
  3125. length = ' (%0.3f ms) ' % ((dev['end']-dev['start'])*1000)
  3126. if sysvals.suspendmode == 'command':
  3127. title = name+drv+xtrainfo+length+'cmdexec'
  3128. else:
  3129. title = name+drv+xtrainfo+length+b
  3130. devtl.html['timeline'] += html_device.format(dev['id'], \
  3131. title, left, top, '%.3f'%rowheight, width, \
  3132. d+drv, xtraclass, xtrastyle)
  3133. if('src' not in dev):
  3134. continue
  3135. # draw any trace events for this device
  3136. vprint('Debug trace events found for device %s' % d)
  3137. vprint('%20s %20s %10s %8s' % ('title', \
  3138. 'name', 'time(ms)', 'length(ms)'))
  3139. for e in dev['src']:
  3140. vprint('%20s %20s %10.3f %8.3f' % (e.title, \
  3141. e.text, e.time*1000, e.length*1000))
  3142. height = devtl.rowH
  3143. top = '%.3f' % (rowtop + devtl.scaleH + (e.row*devtl.rowH))
  3144. left = '%f' % (((e.time-m0)*100)/mTotal)
  3145. width = '%f' % (e.length*100/mTotal)
  3146. color = 'rgba(204,204,204,0.5)'
  3147. devtl.html['timeline'] += \
  3148. html_traceevent.format(e.title, \
  3149. left, top, '%.3f'%height, \
  3150. width, e.text)
  3151. # draw the time scale, try to make the number of labels readable
  3152. devtl.html['timeline'] += devtl.createTimeScale(m0, mMax, tTotal, dir)
  3153. devtl.html['timeline'] += '</div>\n'
  3154. # timeline is finished
  3155. devtl.html['timeline'] += '</div>\n</div>\n'
  3156. # draw a legend which describes the phases by color
  3157. if sysvals.suspendmode != 'command':
  3158. data = testruns[-1]
  3159. devtl.html['legend'] = '<div class="legend">\n'
  3160. pdelta = 100.0/len(data.phases)
  3161. pmargin = pdelta / 4.0
  3162. for phase in data.phases:
  3163. tmp = phase.split('_')
  3164. id = tmp[0][0]
  3165. if(len(tmp) > 1):
  3166. id += tmp[1][0]
  3167. order = '%.2f' % ((data.dmesg[phase]['order'] * pdelta) + pmargin)
  3168. name = string.replace(phase, '_', ' &nbsp;')
  3169. devtl.html['legend'] += html_legend.format(order, \
  3170. data.dmesg[phase]['color'], name, id)
  3171. devtl.html['legend'] += '</div>\n'
  3172. hf = open(sysvals.htmlfile, 'w')
  3173. if not sysvals.cgexp:
  3174. cgchk = 'checked'
  3175. cgnchk = 'not(:checked)'
  3176. else:
  3177. cgchk = 'not(:checked)'
  3178. cgnchk = 'checked'
  3179. # write the html header first (html head, css code, up to body start)
  3180. html_header = '<!DOCTYPE html>\n<html>\n<head>\n\
  3181. <meta http-equiv="content-type" content="text/html; charset=UTF-8">\n\
  3182. <title>'+htmlTitle()+'</title>\n\
  3183. <style type=\'text/css\'>\n\
  3184. body {overflow-y:scroll;}\n\
  3185. .stamp {width:100%;text-align:center;background-color:gray;line-height:30px;color:white;font:25px Arial;}\n\
  3186. .callgraph {margin-top:30px;box-shadow:5px 5px 20px black;}\n\
  3187. .callgraph article * {padding-left:28px;}\n\
  3188. h1 {color:black;font:bold 30px Times;}\n\
  3189. t0 {color:black;font:bold 30px Times;}\n\
  3190. t1 {color:black;font:30px Times;}\n\
  3191. t2 {color:black;font:25px Times;}\n\
  3192. t3 {color:black;font:20px Times;white-space:nowrap;}\n\
  3193. t4 {color:black;font:bold 30px Times;line-height:60px;white-space:nowrap;}\n\
  3194. cS {color:blue;font:bold 11px Times;}\n\
  3195. cR {color:red;font:bold 11px Times;}\n\
  3196. table {width:100%;}\n\
  3197. .gray {background-color:rgba(80,80,80,0.1);}\n\
  3198. .green {background-color:rgba(204,255,204,0.4);}\n\
  3199. .purple {background-color:rgba(128,0,128,0.2);}\n\
  3200. .yellow {background-color:rgba(255,255,204,0.4);}\n\
  3201. .time1 {font:22px Arial;border:1px solid;}\n\
  3202. .time2 {font:15px Arial;border-bottom:1px solid;border-left:1px solid;border-right:1px solid;}\n\
  3203. td {text-align:center;}\n\
  3204. r {color:#500000;font:15px Tahoma;}\n\
  3205. n {color:#505050;font:15px Tahoma;}\n\
  3206. .tdhl {color:red;}\n\
  3207. .hide {display:none;}\n\
  3208. .pf {display:none;}\n\
  3209. .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\
  3210. .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\
  3211. .pf:'+cgchk+' ~ *:not(:nth-child(2)) {display:none;}\n\
  3212. .zoombox {position:relative;width:100%;overflow-x:scroll;}\n\
  3213. .timeline {position:relative;font-size:14px;cursor:pointer;width:100%; overflow:hidden;background:linear-gradient(#cccccc, white);}\n\
  3214. .thread {position:absolute;height:0%;overflow:hidden;line-height:'+devtextH+';font-size:'+devtextS+';border:1px solid;text-align:center;white-space:nowrap;background-color:rgba(204,204,204,0.5);}\n\
  3215. .thread.sync {background-color:'+sysvals.synccolor+';}\n\
  3216. .thread.bg {background-color:'+sysvals.kprobecolor+';}\n\
  3217. .thread:hover {background-color:white;border:1px solid red;'+hoverZ+'}\n\
  3218. .hover {background-color:white;border:1px solid red;'+hoverZ+'}\n\
  3219. .hover.sync {background-color:white;}\n\
  3220. .hover.bg {background-color:white;}\n\
  3221. .traceevent {position:absolute;font-size:10px;overflow:hidden;color:black;text-align:center;white-space:nowrap;border-radius:5px;border:1px solid black;background:linear-gradient(to bottom right,rgba(204,204,204,1),rgba(150,150,150,1));}\n\
  3222. .traceevent:hover {background:white;}\n\
  3223. .phase {position:absolute;overflow:hidden;border:0px;text-align:center;}\n\
  3224. .phaselet {position:absolute;overflow:hidden;border:0px;text-align:center;height:100px;font-size:24px;}\n\
  3225. .t {z-index:2;position:absolute;pointer-events:none;top:0%;height:100%;border-right:1px solid black;}\n\
  3226. .legend {position:relative; width:100%; height:40px; text-align:center;margin-bottom:20px}\n\
  3227. .legend .square {position:absolute;cursor:pointer;top:10px; width:0px;height:20px;border:1px solid;padding-left:20px;}\n\
  3228. button {height:40px;width:200px;margin-bottom:20px;margin-top:20px;font-size:24px;}\n\
  3229. .logbtn {position:relative;float:right;height:25px;width:50px;margin-top:3px;margin-bottom:0;font-size:10px;text-align:center;}\n\
  3230. .devlist {position:'+x2changes[1]+';width:190px;}\n\
  3231. a:link {color:white;text-decoration:none;}\n\
  3232. a:visited {color:white;}\n\
  3233. a:hover {color:white;}\n\
  3234. a:active {color:white;}\n\
  3235. .version {position:relative;float:left;color:white;font-size:10px;line-height:30px;margin-left:10px;}\n\
  3236. #devicedetail {height:100px;box-shadow:5px 5px 20px black;}\n\
  3237. .tblock {position:absolute;height:100%;}\n\
  3238. .bg {z-index:1;}\n\
  3239. </style>\n</head>\n<body>\n'
  3240. # no header or css if its embedded
  3241. if(sysvals.embedded):
  3242. hf.write('pass True tSus %.3f tRes %.3f tLow %.3f fwvalid %s tSus %.3f tRes %.3f\n' %
  3243. (data.tSuspended-data.start, data.end-data.tSuspended, data.tLow, data.fwValid, \
  3244. data.fwSuspend/1000000, data.fwResume/1000000))
  3245. else:
  3246. hf.write(html_header)
  3247. # write the test title and general info header
  3248. if(sysvals.stamp['time'] != ""):
  3249. hf.write(headline_version)
  3250. if sysvals.addlogs and sysvals.dmesgfile:
  3251. hf.write('<button id="showdmesg" class="logbtn">dmesg</button>')
  3252. if sysvals.addlogs and sysvals.ftracefile:
  3253. hf.write('<button id="showftrace" class="logbtn">ftrace</button>')
  3254. hf.write(headline_stamp.format(sysvals.stamp['host'],
  3255. sysvals.stamp['kernel'], sysvals.stamp['mode'], \
  3256. sysvals.stamp['time']))
  3257. # write the device timeline
  3258. hf.write(devtl.html['header'])
  3259. hf.write(devtl.html['timeline'])
  3260. hf.write(devtl.html['legend'])
  3261. hf.write('<div id="devicedetailtitle"></div>\n')
  3262. hf.write('<div id="devicedetail" style="display:none;">\n')
  3263. # draw the colored boxes for the device detail section
  3264. for data in testruns:
  3265. hf.write('<div id="devicedetail%d">\n' % data.testnumber)
  3266. for b in data.phases:
  3267. phase = data.dmesg[b]
  3268. length = phase['end']-phase['start']
  3269. left = '%.3f' % (((phase['start']-t0)*100.0)/tTotal)
  3270. width = '%.3f' % ((length*100.0)/tTotal)
  3271. hf.write(html_phaselet.format(b, left, width, \
  3272. data.dmesg[b]['color']))
  3273. if sysvals.suspendmode == 'command':
  3274. hf.write(html_phaselet.format('cmdexec', '0', '0', \
  3275. data.dmesg['resume_complete']['color']))
  3276. hf.write('</div>\n')
  3277. hf.write('</div>\n')
  3278. # write the ftrace data (callgraph)
  3279. data = testruns[-1]
  3280. if(sysvals.usecallgraph and not sysvals.embedded):
  3281. hf.write('<section id="callgraphs" class="callgraph">\n')
  3282. # write out the ftrace data converted to html
  3283. html_func_top = '<article id="{0}" class="atop" style="background-color:{1}">\n<input type="checkbox" class="pf" id="f{2}" checked/><label for="f{2}">{3} {4}</label>\n'
  3284. html_func_start = '<article>\n<input type="checkbox" class="pf" id="f{0}" checked/><label for="f{0}">{1} {2}</label>\n'
  3285. html_func_end = '</article>\n'
  3286. html_func_leaf = '<article>{0} {1}</article>\n'
  3287. num = 0
  3288. for p in data.phases:
  3289. list = data.dmesg[p]['list']
  3290. for devname in data.sortedDevices(p):
  3291. if('ftrace' not in list[devname]):
  3292. continue
  3293. devid = list[devname]['id']
  3294. cg = list[devname]['ftrace']
  3295. clen = (cg.end - cg.start) * 1000
  3296. if clen < sysvals.mincglen:
  3297. continue
  3298. fmt = '<r>(%.3f ms @ '+sysvals.timeformat+' to '+sysvals.timeformat+')</r>'
  3299. flen = fmt % (clen, cg.start, cg.end)
  3300. name = devname
  3301. if(devname in sysvals.devprops):
  3302. name = sysvals.devprops[devname].altName(devname)
  3303. if sysvals.suspendmode == 'command':
  3304. ftitle = name
  3305. else:
  3306. ftitle = name+' '+p
  3307. hf.write(html_func_top.format(devid, data.dmesg[p]['color'], \
  3308. num, ftitle, flen))
  3309. num += 1
  3310. for line in cg.list:
  3311. if(line.length < 0.000000001):
  3312. flen = ''
  3313. else:
  3314. fmt = '<n>(%.3f ms @ '+sysvals.timeformat+')</n>'
  3315. flen = fmt % (line.length*1000, line.time)
  3316. if(line.freturn and line.fcall):
  3317. hf.write(html_func_leaf.format(line.name, flen))
  3318. elif(line.freturn):
  3319. hf.write(html_func_end)
  3320. else:
  3321. hf.write(html_func_start.format(num, line.name, flen))
  3322. num += 1
  3323. hf.write(html_func_end)
  3324. hf.write('\n\n </section>\n')
  3325. # add the dmesg log as a hidden div
  3326. if sysvals.addlogs and sysvals.dmesgfile:
  3327. hf.write('<div id="dmesglog" style="display:none;">\n')
  3328. lf = open(sysvals.dmesgfile, 'r')
  3329. for line in lf:
  3330. hf.write(line)
  3331. lf.close()
  3332. hf.write('</div>\n')
  3333. # add the ftrace log as a hidden div
  3334. if sysvals.addlogs and sysvals.ftracefile:
  3335. hf.write('<div id="ftracelog" style="display:none;">\n')
  3336. lf = open(sysvals.ftracefile, 'r')
  3337. for line in lf:
  3338. hf.write(line)
  3339. lf.close()
  3340. hf.write('</div>\n')
  3341. if(not sysvals.embedded):
  3342. # write the footer and close
  3343. addScriptCode(hf, testruns)
  3344. hf.write('</body>\n</html>\n')
  3345. else:
  3346. # embedded out will be loaded in a page, skip the js
  3347. t0 = (testruns[0].start - testruns[-1].tSuspended) * 1000
  3348. tMax = (testruns[-1].end - testruns[-1].tSuspended) * 1000
  3349. # add js code in a div entry for later evaluation
  3350. detail = 'var bounds = [%f,%f];\n' % (t0, tMax)
  3351. detail += 'var devtable = [\n'
  3352. for data in testruns:
  3353. topo = data.deviceTopology()
  3354. detail += '\t"%s",\n' % (topo)
  3355. detail += '];\n'
  3356. hf.write('<div id=customcode style=display:none>\n'+detail+'</div>\n')
  3357. hf.close()
  3358. return True
  3359. # Function: addScriptCode
  3360. # Description:
  3361. # Adds the javascript code to the output html
  3362. # Arguments:
  3363. # hf: the open html file pointer
  3364. # testruns: array of Data objects from parseKernelLog or parseTraceLog
  3365. def addScriptCode(hf, testruns):
  3366. t0 = testruns[0].start * 1000
  3367. tMax = testruns[-1].end * 1000
  3368. # create an array in javascript memory with the device details
  3369. detail = ' var devtable = [];\n'
  3370. for data in testruns:
  3371. topo = data.deviceTopology()
  3372. detail += ' devtable[%d] = "%s";\n' % (data.testnumber, topo)
  3373. detail += ' var bounds = [%f,%f];\n' % (t0, tMax)
  3374. # add the code which will manipulate the data in the browser
  3375. script_code = \
  3376. '<script type="text/javascript">\n'+detail+\
  3377. ' var resolution = -1;\n'\
  3378. ' function redrawTimescale(t0, tMax, tS) {\n'\
  3379. ' var rline = \'<div class="t" style="left:0;border-left:1px solid black;border-right:0;"><cR><-R</cR></div>\';\n'\
  3380. ' var tTotal = tMax - t0;\n'\
  3381. ' var list = document.getElementsByClassName("tblock");\n'\
  3382. ' for (var i = 0; i < list.length; i++) {\n'\
  3383. ' var timescale = list[i].getElementsByClassName("timescale")[0];\n'\
  3384. ' var m0 = t0 + (tTotal*parseFloat(list[i].style.left)/100);\n'\
  3385. ' var mTotal = tTotal*parseFloat(list[i].style.width)/100;\n'\
  3386. ' var mMax = m0 + mTotal;\n'\
  3387. ' var html = "";\n'\
  3388. ' var divTotal = Math.floor(mTotal/tS) + 1;\n'\
  3389. ' if(divTotal > 1000) continue;\n'\
  3390. ' var divEdge = (mTotal - tS*(divTotal-1))*100/mTotal;\n'\
  3391. ' var pos = 0.0, val = 0.0;\n'\
  3392. ' for (var j = 0; j < divTotal; j++) {\n'\
  3393. ' var htmlline = "";\n'\
  3394. ' if(list[i].id[5] == "r") {\n'\
  3395. ' pos = 100 - (((j)*tS*100)/mTotal);\n'\
  3396. ' val = (j)*tS;\n'\
  3397. ' htmlline = \'<div class="t" style="right:\'+pos+\'%">\'+val+\'ms</div>\';\n'\
  3398. ' if(j == 0)\n'\
  3399. ' htmlline = rline;\n'\
  3400. ' } else {\n'\
  3401. ' pos = 100 - (((j)*tS*100)/mTotal) - divEdge;\n'\
  3402. ' val = (j-divTotal+1)*tS;\n'\
  3403. ' if(j == divTotal - 1)\n'\
  3404. ' htmlline = \'<div class="t" style="right:\'+pos+\'%"><cS>S-></cS></div>\';\n'\
  3405. ' else\n'\
  3406. ' htmlline = \'<div class="t" style="right:\'+pos+\'%">\'+val+\'ms</div>\';\n'\
  3407. ' }\n'\
  3408. ' html += htmlline;\n'\
  3409. ' }\n'\
  3410. ' timescale.innerHTML = html;\n'\
  3411. ' }\n'\
  3412. ' }\n'\
  3413. ' function zoomTimeline() {\n'\
  3414. ' var dmesg = document.getElementById("dmesg");\n'\
  3415. ' var zoombox = document.getElementById("dmesgzoombox");\n'\
  3416. ' var val = parseFloat(dmesg.style.width);\n'\
  3417. ' var newval = 100;\n'\
  3418. ' var sh = window.outerWidth / 2;\n'\
  3419. ' if(this.id == "zoomin") {\n'\
  3420. ' newval = val * 1.2;\n'\
  3421. ' if(newval > 910034) newval = 910034;\n'\
  3422. ' dmesg.style.width = newval+"%";\n'\
  3423. ' zoombox.scrollLeft = ((zoombox.scrollLeft + sh) * newval / val) - sh;\n'\
  3424. ' } else if (this.id == "zoomout") {\n'\
  3425. ' newval = val / 1.2;\n'\
  3426. ' if(newval < 100) newval = 100;\n'\
  3427. ' dmesg.style.width = newval+"%";\n'\
  3428. ' zoombox.scrollLeft = ((zoombox.scrollLeft + sh) * newval / val) - sh;\n'\
  3429. ' } else {\n'\
  3430. ' zoombox.scrollLeft = 0;\n'\
  3431. ' dmesg.style.width = "100%";\n'\
  3432. ' }\n'\
  3433. ' var tS = [10000, 5000, 2000, 1000, 500, 200, 100, 50, 20, 10, 5, 2, 1];\n'\
  3434. ' var t0 = bounds[0];\n'\
  3435. ' var tMax = bounds[1];\n'\
  3436. ' var tTotal = tMax - t0;\n'\
  3437. ' var wTotal = tTotal * 100.0 / newval;\n'\
  3438. ' var idx = 7*window.innerWidth/1100;\n'\
  3439. ' for(var i = 0; (i < tS.length)&&((wTotal / tS[i]) < idx); i++);\n'\
  3440. ' if(i >= tS.length) i = tS.length - 1;\n'\
  3441. ' if(tS[i] == resolution) return;\n'\
  3442. ' resolution = tS[i];\n'\
  3443. ' redrawTimescale(t0, tMax, tS[i]);\n'\
  3444. ' }\n'\
  3445. ' function deviceHover() {\n'\
  3446. ' var name = this.title.slice(0, this.title.indexOf(" ("));\n'\
  3447. ' var dmesg = document.getElementById("dmesg");\n'\
  3448. ' var dev = dmesg.getElementsByClassName("thread");\n'\
  3449. ' var cpu = -1;\n'\
  3450. ' if(name.match("CPU_ON\[[0-9]*\]"))\n'\
  3451. ' cpu = parseInt(name.slice(7));\n'\
  3452. ' else if(name.match("CPU_OFF\[[0-9]*\]"))\n'\
  3453. ' cpu = parseInt(name.slice(8));\n'\
  3454. ' for (var i = 0; i < dev.length; i++) {\n'\
  3455. ' dname = dev[i].title.slice(0, dev[i].title.indexOf(" ("));\n'\
  3456. ' var cname = dev[i].className.slice(dev[i].className.indexOf("thread"));\n'\
  3457. ' if((cpu >= 0 && dname.match("CPU_O[NF]*\\\[*"+cpu+"\\\]")) ||\n'\
  3458. ' (name == dname))\n'\
  3459. ' {\n'\
  3460. ' dev[i].className = "hover "+cname;\n'\
  3461. ' } else {\n'\
  3462. ' dev[i].className = cname;\n'\
  3463. ' }\n'\
  3464. ' }\n'\
  3465. ' }\n'\
  3466. ' function deviceUnhover() {\n'\
  3467. ' var dmesg = document.getElementById("dmesg");\n'\
  3468. ' var dev = dmesg.getElementsByClassName("thread");\n'\
  3469. ' for (var i = 0; i < dev.length; i++) {\n'\
  3470. ' dev[i].className = dev[i].className.slice(dev[i].className.indexOf("thread"));\n'\
  3471. ' }\n'\
  3472. ' }\n'\
  3473. ' function deviceTitle(title, total, cpu) {\n'\
  3474. ' var prefix = "Total";\n'\
  3475. ' if(total.length > 3) {\n'\
  3476. ' prefix = "Average";\n'\
  3477. ' total[1] = (total[1]+total[3])/2;\n'\
  3478. ' total[2] = (total[2]+total[4])/2;\n'\
  3479. ' }\n'\
  3480. ' var devtitle = document.getElementById("devicedetailtitle");\n'\
  3481. ' var name = title.slice(0, title.indexOf(" ("));\n'\
  3482. ' if(cpu >= 0) name = "CPU"+cpu;\n'\
  3483. ' var driver = "";\n'\
  3484. ' var tS = "<t2>(</t2>";\n'\
  3485. ' var tR = "<t2>)</t2>";\n'\
  3486. ' if(total[1] > 0)\n'\
  3487. ' tS = "<t2>("+prefix+" Suspend:</t2><t0> "+total[1].toFixed(3)+" ms</t0> ";\n'\
  3488. ' if(total[2] > 0)\n'\
  3489. ' tR = " <t2>"+prefix+" Resume:</t2><t0> "+total[2].toFixed(3)+" ms<t2>)</t2></t0>";\n'\
  3490. ' var s = title.indexOf("{");\n'\
  3491. ' var e = title.indexOf("}");\n'\
  3492. ' if((s >= 0) && (e >= 0))\n'\
  3493. ' driver = title.slice(s+1, e) + " <t1>@</t1> ";\n'\
  3494. ' if(total[1] > 0 && total[2] > 0)\n'\
  3495. ' devtitle.innerHTML = "<t0>"+driver+name+"</t0> "+tS+tR;\n'\
  3496. ' else\n'\
  3497. ' devtitle.innerHTML = "<t0>"+title+"</t0>";\n'\
  3498. ' return name;\n'\
  3499. ' }\n'\
  3500. ' function deviceDetail() {\n'\
  3501. ' var devinfo = document.getElementById("devicedetail");\n'\
  3502. ' devinfo.style.display = "block";\n'\
  3503. ' var name = this.title.slice(0, this.title.indexOf(" ("));\n'\
  3504. ' var cpu = -1;\n'\
  3505. ' if(name.match("CPU_ON\[[0-9]*\]"))\n'\
  3506. ' cpu = parseInt(name.slice(7));\n'\
  3507. ' else if(name.match("CPU_OFF\[[0-9]*\]"))\n'\
  3508. ' cpu = parseInt(name.slice(8));\n'\
  3509. ' var dmesg = document.getElementById("dmesg");\n'\
  3510. ' var dev = dmesg.getElementsByClassName("thread");\n'\
  3511. ' var idlist = [];\n'\
  3512. ' var pdata = [[]];\n'\
  3513. ' if(document.getElementById("devicedetail1"))\n'\
  3514. ' pdata = [[], []];\n'\
  3515. ' var pd = pdata[0];\n'\
  3516. ' var total = [0.0, 0.0, 0.0];\n'\
  3517. ' for (var i = 0; i < dev.length; i++) {\n'\
  3518. ' dname = dev[i].title.slice(0, dev[i].title.indexOf(" ("));\n'\
  3519. ' if((cpu >= 0 && dname.match("CPU_O[NF]*\\\[*"+cpu+"\\\]")) ||\n'\
  3520. ' (name == dname))\n'\
  3521. ' {\n'\
  3522. ' idlist[idlist.length] = dev[i].id;\n'\
  3523. ' var tidx = 1;\n'\
  3524. ' if(dev[i].id[0] == "a") {\n'\
  3525. ' pd = pdata[0];\n'\
  3526. ' } else {\n'\
  3527. ' if(pdata.length == 1) pdata[1] = [];\n'\
  3528. ' if(total.length == 3) total[3]=total[4]=0.0;\n'\
  3529. ' pd = pdata[1];\n'\
  3530. ' tidx = 3;\n'\
  3531. ' }\n'\
  3532. ' var info = dev[i].title.split(" ");\n'\
  3533. ' var pname = info[info.length-1];\n'\
  3534. ' pd[pname] = parseFloat(info[info.length-3].slice(1));\n'\
  3535. ' total[0] += pd[pname];\n'\
  3536. ' if(pname.indexOf("suspend") >= 0)\n'\
  3537. ' total[tidx] += pd[pname];\n'\
  3538. ' else\n'\
  3539. ' total[tidx+1] += pd[pname];\n'\
  3540. ' }\n'\
  3541. ' }\n'\
  3542. ' var devname = deviceTitle(this.title, total, cpu);\n'\
  3543. ' var left = 0.0;\n'\
  3544. ' for (var t = 0; t < pdata.length; t++) {\n'\
  3545. ' pd = pdata[t];\n'\
  3546. ' devinfo = document.getElementById("devicedetail"+t);\n'\
  3547. ' var phases = devinfo.getElementsByClassName("phaselet");\n'\
  3548. ' for (var i = 0; i < phases.length; i++) {\n'\
  3549. ' if(phases[i].id in pd) {\n'\
  3550. ' var w = 100.0*pd[phases[i].id]/total[0];\n'\
  3551. ' var fs = 32;\n'\
  3552. ' if(w < 8) fs = 4*w | 0;\n'\
  3553. ' var fs2 = fs*3/4;\n'\
  3554. ' phases[i].style.width = w+"%";\n'\
  3555. ' phases[i].style.left = left+"%";\n'\
  3556. ' phases[i].title = phases[i].id+" "+pd[phases[i].id]+" ms";\n'\
  3557. ' left += w;\n'\
  3558. ' var time = "<t4 style=\\"font-size:"+fs+"px\\">"+pd[phases[i].id]+" ms<br></t4>";\n'\
  3559. ' var pname = "<t3 style=\\"font-size:"+fs2+"px\\">"+phases[i].id.replace("_", " ")+"</t3>";\n'\
  3560. ' phases[i].innerHTML = time+pname;\n'\
  3561. ' } else {\n'\
  3562. ' phases[i].style.width = "0%";\n'\
  3563. ' phases[i].style.left = left+"%";\n'\
  3564. ' }\n'\
  3565. ' }\n'\
  3566. ' }\n'\
  3567. ' var cglist = document.getElementById("callgraphs");\n'\
  3568. ' if(!cglist) return;\n'\
  3569. ' var cg = cglist.getElementsByClassName("atop");\n'\
  3570. ' if(cg.length < 10) return;\n'\
  3571. ' for (var i = 0; i < cg.length; i++) {\n'\
  3572. ' if(idlist.indexOf(cg[i].id) >= 0) {\n'\
  3573. ' cg[i].style.display = "block";\n'\
  3574. ' } else {\n'\
  3575. ' cg[i].style.display = "none";\n'\
  3576. ' }\n'\
  3577. ' }\n'\
  3578. ' }\n'\
  3579. ' function devListWindow(e) {\n'\
  3580. ' var sx = e.clientX;\n'\
  3581. ' if(sx > window.innerWidth - 440)\n'\
  3582. ' sx = window.innerWidth - 440;\n'\
  3583. ' var cfg="top="+e.screenY+", left="+sx+", width=440, height=720, scrollbars=yes";\n'\
  3584. ' var win = window.open("", "_blank", cfg);\n'\
  3585. ' if(window.chrome) win.moveBy(sx, 0);\n'\
  3586. ' var html = "<title>"+e.target.innerHTML+"</title>"+\n'\
  3587. ' "<style type=\\"text/css\\">"+\n'\
  3588. ' " ul {list-style-type:circle;padding-left:10px;margin-left:10px;}"+\n'\
  3589. ' "</style>"\n'\
  3590. ' var dt = devtable[0];\n'\
  3591. ' if(e.target.id != "devlist1")\n'\
  3592. ' dt = devtable[1];\n'\
  3593. ' win.document.write(html+dt);\n'\
  3594. ' }\n'\
  3595. ' function logWindow(e) {\n'\
  3596. ' var name = e.target.id.slice(4);\n'\
  3597. ' var win = window.open();\n'\
  3598. ' var log = document.getElementById(name+"log");\n'\
  3599. ' var title = "<title>"+document.title.split(" ")[0]+" "+name+" log</title>";\n'\
  3600. ' win.document.write(title+"<pre>"+log.innerHTML+"</pre>");\n'\
  3601. ' win.document.close();\n'\
  3602. ' }\n'\
  3603. ' function onClickPhase(e) {\n'\
  3604. ' }\n'\
  3605. ' window.addEventListener("resize", function () {zoomTimeline();});\n'\
  3606. ' window.addEventListener("load", function () {\n'\
  3607. ' var dmesg = document.getElementById("dmesg");\n'\
  3608. ' dmesg.style.width = "100%"\n'\
  3609. ' document.getElementById("zoomin").onclick = zoomTimeline;\n'\
  3610. ' document.getElementById("zoomout").onclick = zoomTimeline;\n'\
  3611. ' document.getElementById("zoomdef").onclick = zoomTimeline;\n'\
  3612. ' var list = document.getElementsByClassName("square");\n'\
  3613. ' for (var i = 0; i < list.length; i++)\n'\
  3614. ' list[i].onclick = onClickPhase;\n'\
  3615. ' var list = document.getElementsByClassName("logbtn");\n'\
  3616. ' for (var i = 0; i < list.length; i++)\n'\
  3617. ' list[i].onclick = logWindow;\n'\
  3618. ' list = document.getElementsByClassName("devlist");\n'\
  3619. ' for (var i = 0; i < list.length; i++)\n'\
  3620. ' list[i].onclick = devListWindow;\n'\
  3621. ' var dev = dmesg.getElementsByClassName("thread");\n'\
  3622. ' for (var i = 0; i < dev.length; i++) {\n'\
  3623. ' dev[i].onclick = deviceDetail;\n'\
  3624. ' dev[i].onmouseover = deviceHover;\n'\
  3625. ' dev[i].onmouseout = deviceUnhover;\n'\
  3626. ' }\n'\
  3627. ' zoomTimeline();\n'\
  3628. ' });\n'\
  3629. '</script>\n'
  3630. hf.write(script_code);
  3631. # Function: executeSuspend
  3632. # Description:
  3633. # Execute system suspend through the sysfs interface, then copy the output
  3634. # dmesg and ftrace files to the test output directory.
  3635. def executeSuspend():
  3636. global sysvals
  3637. t0 = time.time()*1000
  3638. tp = sysvals.tpath
  3639. fwdata = []
  3640. # mark the start point in the kernel ring buffer just as we start
  3641. sysvals.initdmesg()
  3642. # start ftrace
  3643. if(sysvals.usecallgraph or sysvals.usetraceevents):
  3644. print('START TRACING')
  3645. sysvals.fsetVal('1', 'tracing_on')
  3646. # execute however many s/r runs requested
  3647. for count in range(1,sysvals.execcount+1):
  3648. # if this is test2 and there's a delay, start here
  3649. if(count > 1 and sysvals.x2delay > 0):
  3650. tN = time.time()*1000
  3651. while (tN - t0) < sysvals.x2delay:
  3652. tN = time.time()*1000
  3653. time.sleep(0.001)
  3654. # initiate suspend
  3655. if(sysvals.usecallgraph or sysvals.usetraceevents):
  3656. sysvals.fsetVal('SUSPEND START', 'trace_marker')
  3657. if sysvals.suspendmode == 'command':
  3658. print('COMMAND START')
  3659. if(sysvals.rtcwake):
  3660. print('will issue an rtcwake in %d seconds' % sysvals.rtcwaketime)
  3661. sysvals.rtcWakeAlarmOn()
  3662. os.system(sysvals.testcommand)
  3663. else:
  3664. if(sysvals.rtcwake):
  3665. print('SUSPEND START')
  3666. print('will autoresume in %d seconds' % sysvals.rtcwaketime)
  3667. sysvals.rtcWakeAlarmOn()
  3668. else:
  3669. print('SUSPEND START (press a key to resume)')
  3670. pf = open(sysvals.powerfile, 'w')
  3671. pf.write(sysvals.suspendmode)
  3672. # execution will pause here
  3673. try:
  3674. pf.close()
  3675. except:
  3676. pass
  3677. t0 = time.time()*1000
  3678. if(sysvals.rtcwake):
  3679. sysvals.rtcWakeAlarmOff()
  3680. # return from suspend
  3681. print('RESUME COMPLETE')
  3682. if(sysvals.usecallgraph or sysvals.usetraceevents):
  3683. sysvals.fsetVal('RESUME COMPLETE', 'trace_marker')
  3684. if(sysvals.suspendmode == 'mem'):
  3685. fwdata.append(getFPDT(False))
  3686. # look for post resume events after the last test run
  3687. t = sysvals.postresumetime
  3688. if(t > 0):
  3689. print('Waiting %d seconds for POST-RESUME trace events...' % t)
  3690. time.sleep(t)
  3691. # stop ftrace
  3692. if(sysvals.usecallgraph or sysvals.usetraceevents):
  3693. sysvals.fsetVal('0', 'tracing_on')
  3694. print('CAPTURING TRACE')
  3695. writeDatafileHeader(sysvals.ftracefile, fwdata)
  3696. os.system('cat '+tp+'trace >> '+sysvals.ftracefile)
  3697. sysvals.fsetVal('', 'trace')
  3698. devProps()
  3699. # grab a copy of the dmesg output
  3700. print('CAPTURING DMESG')
  3701. writeDatafileHeader(sysvals.dmesgfile, fwdata)
  3702. sysvals.getdmesg()
  3703. def writeDatafileHeader(filename, fwdata):
  3704. global sysvals
  3705. prt = sysvals.postresumetime
  3706. fp = open(filename, 'a')
  3707. fp.write(sysvals.teststamp+'\n')
  3708. if(sysvals.suspendmode == 'mem'):
  3709. for fw in fwdata:
  3710. if(fw):
  3711. fp.write('# fwsuspend %u fwresume %u\n' % (fw[0], fw[1]))
  3712. if(prt > 0):
  3713. fp.write('# post resume time %u\n' % prt)
  3714. fp.close()
  3715. # Function: setUSBDevicesAuto
  3716. # Description:
  3717. # Set the autosuspend control parameter of all USB devices to auto
  3718. # This can be dangerous, so use at your own risk, most devices are set
  3719. # to always-on since the kernel cant determine if the device can
  3720. # properly autosuspend
  3721. def setUSBDevicesAuto():
  3722. global sysvals
  3723. rootCheck(True)
  3724. for dirname, dirnames, filenames in os.walk('/sys/devices'):
  3725. if(re.match('.*/usb[0-9]*.*', dirname) and
  3726. 'idVendor' in filenames and 'idProduct' in filenames):
  3727. os.system('echo auto > %s/power/control' % dirname)
  3728. name = dirname.split('/')[-1]
  3729. desc = os.popen('cat %s/product 2>/dev/null' % \
  3730. dirname).read().replace('\n', '')
  3731. ctrl = os.popen('cat %s/power/control 2>/dev/null' % \
  3732. dirname).read().replace('\n', '')
  3733. print('control is %s for %6s: %s' % (ctrl, name, desc))
  3734. # Function: yesno
  3735. # Description:
  3736. # Print out an equivalent Y or N for a set of known parameter values
  3737. # Output:
  3738. # 'Y', 'N', or ' ' if the value is unknown
  3739. def yesno(val):
  3740. yesvals = ['auto', 'enabled', 'active', '1']
  3741. novals = ['on', 'disabled', 'suspended', 'forbidden', 'unsupported']
  3742. if val in yesvals:
  3743. return 'Y'
  3744. elif val in novals:
  3745. return 'N'
  3746. return ' '
  3747. # Function: ms2nice
  3748. # Description:
  3749. # Print out a very concise time string in minutes and seconds
  3750. # Output:
  3751. # The time string, e.g. "1901m16s"
  3752. def ms2nice(val):
  3753. ms = 0
  3754. try:
  3755. ms = int(val)
  3756. except:
  3757. return 0.0
  3758. m = ms / 60000
  3759. s = (ms / 1000) - (m * 60)
  3760. return '%3dm%2ds' % (m, s)
  3761. # Function: detectUSB
  3762. # Description:
  3763. # Detect all the USB hosts and devices currently connected and add
  3764. # a list of USB device names to sysvals for better timeline readability
  3765. def detectUSB():
  3766. global sysvals
  3767. field = {'idVendor':'', 'idProduct':'', 'product':'', 'speed':''}
  3768. power = {'async':'', 'autosuspend':'', 'autosuspend_delay_ms':'',
  3769. 'control':'', 'persist':'', 'runtime_enabled':'',
  3770. 'runtime_status':'', 'runtime_usage':'',
  3771. 'runtime_active_time':'',
  3772. 'runtime_suspended_time':'',
  3773. 'active_duration':'',
  3774. 'connected_duration':''}
  3775. print('LEGEND')
  3776. print('---------------------------------------------------------------------------------------------')
  3777. print(' A = async/sync PM queue Y/N D = autosuspend delay (seconds)')
  3778. print(' S = autosuspend Y/N rACTIVE = runtime active (min/sec)')
  3779. print(' P = persist across suspend Y/N rSUSPEN = runtime suspend (min/sec)')
  3780. print(' E = runtime suspend enabled/forbidden Y/N ACTIVE = active duration (min/sec)')
  3781. print(' R = runtime status active/suspended Y/N CONNECT = connected duration (min/sec)')
  3782. print(' U = runtime usage count')
  3783. print('---------------------------------------------------------------------------------------------')
  3784. print(' NAME ID DESCRIPTION SPEED A S P E R U D rACTIVE rSUSPEN ACTIVE CONNECT')
  3785. print('---------------------------------------------------------------------------------------------')
  3786. for dirname, dirnames, filenames in os.walk('/sys/devices'):
  3787. if(re.match('.*/usb[0-9]*.*', dirname) and
  3788. 'idVendor' in filenames and 'idProduct' in filenames):
  3789. for i in field:
  3790. field[i] = os.popen('cat %s/%s 2>/dev/null' % \
  3791. (dirname, i)).read().replace('\n', '')
  3792. name = dirname.split('/')[-1]
  3793. for i in power:
  3794. power[i] = os.popen('cat %s/power/%s 2>/dev/null' % \
  3795. (dirname, i)).read().replace('\n', '')
  3796. if(re.match('usb[0-9]*', name)):
  3797. first = '%-8s' % name
  3798. else:
  3799. first = '%8s' % name
  3800. print('%s [%s:%s] %-20s %-4s %1s %1s %1s %1s %1s %1s %1s %s %s %s %s' % \
  3801. (first, field['idVendor'], field['idProduct'], \
  3802. field['product'][0:20], field['speed'], \
  3803. yesno(power['async']), \
  3804. yesno(power['control']), \
  3805. yesno(power['persist']), \
  3806. yesno(power['runtime_enabled']), \
  3807. yesno(power['runtime_status']), \
  3808. power['runtime_usage'], \
  3809. power['autosuspend'], \
  3810. ms2nice(power['runtime_active_time']), \
  3811. ms2nice(power['runtime_suspended_time']), \
  3812. ms2nice(power['active_duration']), \
  3813. ms2nice(power['connected_duration'])))
  3814. # Function: devProps
  3815. # Description:
  3816. # Retrieve a list of properties for all devices in the trace log
  3817. def devProps(data=0):
  3818. global sysvals
  3819. props = dict()
  3820. if data:
  3821. idx = data.index(': ') + 2
  3822. if idx >= len(data):
  3823. return
  3824. devlist = data[idx:].split(';')
  3825. for dev in devlist:
  3826. f = dev.split(',')
  3827. if len(f) < 3:
  3828. continue
  3829. dev = f[0]
  3830. props[dev] = DevProps()
  3831. props[dev].altname = f[1]
  3832. if int(f[2]):
  3833. props[dev].async = True
  3834. else:
  3835. props[dev].async = False
  3836. sysvals.devprops = props
  3837. if sysvals.suspendmode == 'command' and 'testcommandstring' in props:
  3838. sysvals.testcommand = props['testcommandstring'].altname
  3839. return
  3840. if(os.path.exists(sysvals.ftracefile) == False):
  3841. doError('%s does not exist' % sysvals.ftracefile, False)
  3842. # first get the list of devices we need properties for
  3843. msghead = 'Additional data added by AnalyzeSuspend'
  3844. alreadystamped = False
  3845. tp = TestProps()
  3846. tf = open(sysvals.ftracefile, 'r')
  3847. for line in tf:
  3848. if msghead in line:
  3849. alreadystamped = True
  3850. continue
  3851. # determine the trace data type (required for further parsing)
  3852. m = re.match(sysvals.tracertypefmt, line)
  3853. if(m):
  3854. tp.setTracerType(m.group('t'))
  3855. continue
  3856. # parse only valid lines, if this is not one move on
  3857. m = re.match(tp.ftrace_line_fmt, line)
  3858. if(not m or 'device_pm_callback_start' not in line):
  3859. continue
  3860. m = re.match('.*: (?P<drv>.*) (?P<d>.*), parent: *(?P<p>.*), .*', m.group('msg'));
  3861. if(not m):
  3862. continue
  3863. drv, dev, par = m.group('drv'), m.group('d'), m.group('p')
  3864. if dev not in props:
  3865. props[dev] = DevProps()
  3866. tf.close()
  3867. if not alreadystamped and sysvals.suspendmode == 'command':
  3868. out = '#\n# '+msghead+'\n# Device Properties: '
  3869. out += 'testcommandstring,%s,0;' % (sysvals.testcommand)
  3870. with open(sysvals.ftracefile, 'a') as fp:
  3871. fp.write(out+'\n')
  3872. sysvals.devprops = props
  3873. return
  3874. # now get the syspath for each of our target devices
  3875. for dirname, dirnames, filenames in os.walk('/sys/devices'):
  3876. if(re.match('.*/power', dirname) and 'async' in filenames):
  3877. dev = dirname.split('/')[-2]
  3878. if dev in props and (not props[dev].syspath or len(dirname) < len(props[dev].syspath)):
  3879. props[dev].syspath = dirname[:-6]
  3880. # now fill in the properties for our target devices
  3881. for dev in props:
  3882. dirname = props[dev].syspath
  3883. if not dirname or not os.path.exists(dirname):
  3884. continue
  3885. with open(dirname+'/power/async') as fp:
  3886. text = fp.read()
  3887. props[dev].async = False
  3888. if 'enabled' in text:
  3889. props[dev].async = True
  3890. fields = os.listdir(dirname)
  3891. if 'product' in fields:
  3892. with open(dirname+'/product') as fp:
  3893. props[dev].altname = fp.read()
  3894. elif 'name' in fields:
  3895. with open(dirname+'/name') as fp:
  3896. props[dev].altname = fp.read()
  3897. elif 'model' in fields:
  3898. with open(dirname+'/model') as fp:
  3899. props[dev].altname = fp.read()
  3900. elif 'description' in fields:
  3901. with open(dirname+'/description') as fp:
  3902. props[dev].altname = fp.read()
  3903. elif 'id' in fields:
  3904. with open(dirname+'/id') as fp:
  3905. props[dev].altname = fp.read()
  3906. elif 'idVendor' in fields and 'idProduct' in fields:
  3907. idv, idp = '', ''
  3908. with open(dirname+'/idVendor') as fp:
  3909. idv = fp.read().strip()
  3910. with open(dirname+'/idProduct') as fp:
  3911. idp = fp.read().strip()
  3912. props[dev].altname = '%s:%s' % (idv, idp)
  3913. if props[dev].altname:
  3914. out = props[dev].altname.strip().replace('\n', ' ')
  3915. out = out.replace(',', ' ')
  3916. out = out.replace(';', ' ')
  3917. props[dev].altname = out
  3918. # and now write the data to the ftrace file
  3919. if not alreadystamped:
  3920. out = '#\n# '+msghead+'\n# Device Properties: '
  3921. for dev in sorted(props):
  3922. out += props[dev].out(dev)
  3923. with open(sysvals.ftracefile, 'a') as fp:
  3924. fp.write(out+'\n')
  3925. sysvals.devprops = props
  3926. # Function: getModes
  3927. # Description:
  3928. # Determine the supported power modes on this system
  3929. # Output:
  3930. # A string list of the available modes
  3931. def getModes():
  3932. global sysvals
  3933. modes = ''
  3934. if(os.path.exists(sysvals.powerfile)):
  3935. fp = open(sysvals.powerfile, 'r')
  3936. modes = string.split(fp.read())
  3937. fp.close()
  3938. return modes
  3939. # Function: getFPDT
  3940. # Description:
  3941. # Read the acpi bios tables and pull out FPDT, the firmware data
  3942. # Arguments:
  3943. # output: True to output the info to stdout, False otherwise
  3944. def getFPDT(output):
  3945. global sysvals
  3946. rectype = {}
  3947. rectype[0] = 'Firmware Basic Boot Performance Record'
  3948. rectype[1] = 'S3 Performance Table Record'
  3949. prectype = {}
  3950. prectype[0] = 'Basic S3 Resume Performance Record'
  3951. prectype[1] = 'Basic S3 Suspend Performance Record'
  3952. rootCheck(True)
  3953. if(not os.path.exists(sysvals.fpdtpath)):
  3954. if(output):
  3955. doError('file does not exist: %s' % sysvals.fpdtpath, False)
  3956. return False
  3957. if(not os.access(sysvals.fpdtpath, os.R_OK)):
  3958. if(output):
  3959. doError('file is not readable: %s' % sysvals.fpdtpath, False)
  3960. return False
  3961. if(not os.path.exists(sysvals.mempath)):
  3962. if(output):
  3963. doError('file does not exist: %s' % sysvals.mempath, False)
  3964. return False
  3965. if(not os.access(sysvals.mempath, os.R_OK)):
  3966. if(output):
  3967. doError('file is not readable: %s' % sysvals.mempath, False)
  3968. return False
  3969. fp = open(sysvals.fpdtpath, 'rb')
  3970. buf = fp.read()
  3971. fp.close()
  3972. if(len(buf) < 36):
  3973. if(output):
  3974. doError('Invalid FPDT table data, should '+\
  3975. 'be at least 36 bytes', False)
  3976. return False
  3977. table = struct.unpack('4sIBB6s8sI4sI', buf[0:36])
  3978. if(output):
  3979. print('')
  3980. print('Firmware Performance Data Table (%s)' % table[0])
  3981. print(' Signature : %s' % table[0])
  3982. print(' Table Length : %u' % table[1])
  3983. print(' Revision : %u' % table[2])
  3984. print(' Checksum : 0x%x' % table[3])
  3985. print(' OEM ID : %s' % table[4])
  3986. print(' OEM Table ID : %s' % table[5])
  3987. print(' OEM Revision : %u' % table[6])
  3988. print(' Creator ID : %s' % table[7])
  3989. print(' Creator Revision : 0x%x' % table[8])
  3990. print('')
  3991. if(table[0] != 'FPDT'):
  3992. if(output):
  3993. doError('Invalid FPDT table')
  3994. return False
  3995. if(len(buf) <= 36):
  3996. return False
  3997. i = 0
  3998. fwData = [0, 0]
  3999. records = buf[36:]
  4000. fp = open(sysvals.mempath, 'rb')
  4001. while(i < len(records)):
  4002. header = struct.unpack('HBB', records[i:i+4])
  4003. if(header[0] not in rectype):
  4004. i += header[1]
  4005. continue
  4006. if(header[1] != 16):
  4007. i += header[1]
  4008. continue
  4009. addr = struct.unpack('Q', records[i+8:i+16])[0]
  4010. try:
  4011. fp.seek(addr)
  4012. first = fp.read(8)
  4013. except:
  4014. if(output):
  4015. print('Bad address 0x%x in %s' % (addr, sysvals.mempath))
  4016. return [0, 0]
  4017. rechead = struct.unpack('4sI', first)
  4018. recdata = fp.read(rechead[1]-8)
  4019. if(rechead[0] == 'FBPT'):
  4020. record = struct.unpack('HBBIQQQQQ', recdata)
  4021. if(output):
  4022. print('%s (%s)' % (rectype[header[0]], rechead[0]))
  4023. print(' Reset END : %u ns' % record[4])
  4024. print(' OS Loader LoadImage Start : %u ns' % record[5])
  4025. print(' OS Loader StartImage Start : %u ns' % record[6])
  4026. print(' ExitBootServices Entry : %u ns' % record[7])
  4027. print(' ExitBootServices Exit : %u ns' % record[8])
  4028. elif(rechead[0] == 'S3PT'):
  4029. if(output):
  4030. print('%s (%s)' % (rectype[header[0]], rechead[0]))
  4031. j = 0
  4032. while(j < len(recdata)):
  4033. prechead = struct.unpack('HBB', recdata[j:j+4])
  4034. if(prechead[0] not in prectype):
  4035. continue
  4036. if(prechead[0] == 0):
  4037. record = struct.unpack('IIQQ', recdata[j:j+prechead[1]])
  4038. fwData[1] = record[2]
  4039. if(output):
  4040. print(' %s' % prectype[prechead[0]])
  4041. print(' Resume Count : %u' % \
  4042. record[1])
  4043. print(' FullResume : %u ns' % \
  4044. record[2])
  4045. print(' AverageResume : %u ns' % \
  4046. record[3])
  4047. elif(prechead[0] == 1):
  4048. record = struct.unpack('QQ', recdata[j+4:j+prechead[1]])
  4049. fwData[0] = record[1] - record[0]
  4050. if(output):
  4051. print(' %s' % prectype[prechead[0]])
  4052. print(' SuspendStart : %u ns' % \
  4053. record[0])
  4054. print(' SuspendEnd : %u ns' % \
  4055. record[1])
  4056. print(' SuspendTime : %u ns' % \
  4057. fwData[0])
  4058. j += prechead[1]
  4059. if(output):
  4060. print('')
  4061. i += header[1]
  4062. fp.close()
  4063. return fwData
  4064. # Function: statusCheck
  4065. # Description:
  4066. # Verify that the requested command and options will work, and
  4067. # print the results to the terminal
  4068. # Output:
  4069. # True if the test will work, False if not
  4070. def statusCheck(probecheck=False):
  4071. global sysvals
  4072. status = True
  4073. print('Checking this system (%s)...' % platform.node())
  4074. # check we have root access
  4075. res = sysvals.colorText('NO (No features of this tool will work!)')
  4076. if(rootCheck(False)):
  4077. res = 'YES'
  4078. print(' have root access: %s' % res)
  4079. if(res != 'YES'):
  4080. print(' Try running this script with sudo')
  4081. return False
  4082. # check sysfs is mounted
  4083. res = sysvals.colorText('NO (No features of this tool will work!)')
  4084. if(os.path.exists(sysvals.powerfile)):
  4085. res = 'YES'
  4086. print(' is sysfs mounted: %s' % res)
  4087. if(res != 'YES'):
  4088. return False
  4089. # check target mode is a valid mode
  4090. if sysvals.suspendmode != 'command':
  4091. res = sysvals.colorText('NO')
  4092. modes = getModes()
  4093. if(sysvals.suspendmode in modes):
  4094. res = 'YES'
  4095. else:
  4096. status = False
  4097. print(' is "%s" a valid power mode: %s' % (sysvals.suspendmode, res))
  4098. if(res == 'NO'):
  4099. print(' valid power modes are: %s' % modes)
  4100. print(' please choose one with -m')
  4101. # check if ftrace is available
  4102. res = sysvals.colorText('NO')
  4103. ftgood = sysvals.verifyFtrace()
  4104. if(ftgood):
  4105. res = 'YES'
  4106. elif(sysvals.usecallgraph):
  4107. status = False
  4108. print(' is ftrace supported: %s' % res)
  4109. # check if kprobes are available
  4110. res = sysvals.colorText('NO')
  4111. sysvals.usekprobes = sysvals.verifyKprobes()
  4112. if(sysvals.usekprobes):
  4113. res = 'YES'
  4114. else:
  4115. sysvals.usedevsrc = False
  4116. print(' are kprobes supported: %s' % res)
  4117. # what data source are we using
  4118. res = 'DMESG'
  4119. if(ftgood):
  4120. sysvals.usetraceeventsonly = True
  4121. sysvals.usetraceevents = False
  4122. for e in sysvals.traceevents:
  4123. check = False
  4124. if(os.path.exists(sysvals.epath+e)):
  4125. check = True
  4126. if(not check):
  4127. sysvals.usetraceeventsonly = False
  4128. if(e == 'suspend_resume' and check):
  4129. sysvals.usetraceevents = True
  4130. if(sysvals.usetraceevents and sysvals.usetraceeventsonly):
  4131. res = 'FTRACE (all trace events found)'
  4132. elif(sysvals.usetraceevents):
  4133. res = 'DMESG and FTRACE (suspend_resume trace event found)'
  4134. print(' timeline data source: %s' % res)
  4135. # check if rtcwake
  4136. res = sysvals.colorText('NO')
  4137. if(sysvals.rtcpath != ''):
  4138. res = 'YES'
  4139. elif(sysvals.rtcwake):
  4140. status = False
  4141. print(' is rtcwake supported: %s' % res)
  4142. if not probecheck:
  4143. return status
  4144. if (sysvals.usecallgraph and len(sysvals.debugfuncs) > 0) or len(sysvals.kprobes) > 0:
  4145. sysvals.initFtrace(True)
  4146. # verify callgraph debugfuncs
  4147. if sysvals.usecallgraph and len(sysvals.debugfuncs) > 0:
  4148. print(' verifying these ftrace callgraph functions work:')
  4149. sysvals.setFtraceFilterFunctions(sysvals.debugfuncs)
  4150. fp = open(sysvals.tpath+'set_graph_function', 'r')
  4151. flist = fp.read().split('\n')
  4152. fp.close()
  4153. for func in sysvals.debugfuncs:
  4154. res = sysvals.colorText('NO')
  4155. if func in flist:
  4156. res = 'YES'
  4157. else:
  4158. for i in flist:
  4159. if ' [' in i and func == i.split(' ')[0]:
  4160. res = 'YES'
  4161. break
  4162. print(' %s: %s' % (func, res))
  4163. # verify kprobes
  4164. if len(sysvals.kprobes) > 0:
  4165. print(' verifying these kprobes work:')
  4166. for name in sorted(sysvals.kprobes):
  4167. if name in sysvals.tracefuncs:
  4168. continue
  4169. res = sysvals.colorText('NO')
  4170. if sysvals.testKprobe(sysvals.kprobes[name]):
  4171. res = 'YES'
  4172. print(' %s: %s' % (name, res))
  4173. return status
  4174. # Function: doError
  4175. # Description:
  4176. # generic error function for catastrphic failures
  4177. # Arguments:
  4178. # msg: the error message to print
  4179. # help: True if printHelp should be called after, False otherwise
  4180. def doError(msg, help):
  4181. if(help == True):
  4182. printHelp()
  4183. print('ERROR: %s\n') % msg
  4184. sys.exit()
  4185. # Function: doWarning
  4186. # Description:
  4187. # generic warning function for non-catastrophic anomalies
  4188. # Arguments:
  4189. # msg: the warning message to print
  4190. # file: If not empty, a filename to request be sent to the owner for debug
  4191. def doWarning(msg, file=''):
  4192. print('/* %s */') % msg
  4193. if(file):
  4194. print('/* For a fix, please send this'+\
  4195. ' %s file to <todd.e.brandt@intel.com> */' % file)
  4196. # Function: rootCheck
  4197. # Description:
  4198. # quick check to see if we have root access
  4199. def rootCheck(fatal):
  4200. global sysvals
  4201. if(os.access(sysvals.powerfile, os.W_OK)):
  4202. return True
  4203. if fatal:
  4204. doError('This command must be run as root', False)
  4205. return False
  4206. # Function: getArgInt
  4207. # Description:
  4208. # pull out an integer argument from the command line with checks
  4209. def getArgInt(name, args, min, max, main=True):
  4210. if main:
  4211. try:
  4212. arg = args.next()
  4213. except:
  4214. doError(name+': no argument supplied', True)
  4215. else:
  4216. arg = args
  4217. try:
  4218. val = int(arg)
  4219. except:
  4220. doError(name+': non-integer value given', True)
  4221. if(val < min or val > max):
  4222. doError(name+': value should be between %d and %d' % (min, max), True)
  4223. return val
  4224. # Function: getArgFloat
  4225. # Description:
  4226. # pull out a float argument from the command line with checks
  4227. def getArgFloat(name, args, min, max, main=True):
  4228. if main:
  4229. try:
  4230. arg = args.next()
  4231. except:
  4232. doError(name+': no argument supplied', True)
  4233. else:
  4234. arg = args
  4235. try:
  4236. val = float(arg)
  4237. except:
  4238. doError(name+': non-numerical value given', True)
  4239. if(val < min or val > max):
  4240. doError(name+': value should be between %f and %f' % (min, max), True)
  4241. return val
  4242. # Function: rerunTest
  4243. # Description:
  4244. # generate an output from an existing set of ftrace/dmesg logs
  4245. def rerunTest():
  4246. global sysvals
  4247. if(sysvals.ftracefile != ''):
  4248. doesTraceLogHaveTraceEvents()
  4249. if(sysvals.dmesgfile == '' and not sysvals.usetraceeventsonly):
  4250. doError('recreating this html output '+\
  4251. 'requires a dmesg file', False)
  4252. sysvals.setOutputFile()
  4253. vprint('Output file: %s' % sysvals.htmlfile)
  4254. print('PROCESSING DATA')
  4255. if(sysvals.usetraceeventsonly):
  4256. testruns = parseTraceLog()
  4257. else:
  4258. testruns = loadKernelLog()
  4259. for data in testruns:
  4260. parseKernelLog(data)
  4261. if(sysvals.ftracefile != ''):
  4262. appendIncompleteTraceLog(testruns)
  4263. createHTML(testruns)
  4264. # Function: runTest
  4265. # Description:
  4266. # execute a suspend/resume, gather the logs, and generate the output
  4267. def runTest(subdir, testpath=''):
  4268. global sysvals
  4269. # prepare for the test
  4270. sysvals.initFtrace()
  4271. sysvals.initTestOutput(subdir, testpath)
  4272. vprint('Output files:\n %s' % sysvals.dmesgfile)
  4273. if(sysvals.usecallgraph or
  4274. sysvals.usetraceevents or
  4275. sysvals.usetraceeventsonly):
  4276. vprint(' %s' % sysvals.ftracefile)
  4277. vprint(' %s' % sysvals.htmlfile)
  4278. # execute the test
  4279. executeSuspend()
  4280. sysvals.cleanupFtrace()
  4281. # analyze the data and create the html output
  4282. print('PROCESSING DATA')
  4283. if(sysvals.usetraceeventsonly):
  4284. # data for kernels 3.15 or newer is entirely in ftrace
  4285. testruns = parseTraceLog()
  4286. else:
  4287. # data for kernels older than 3.15 is primarily in dmesg
  4288. testruns = loadKernelLog()
  4289. for data in testruns:
  4290. parseKernelLog(data)
  4291. if(sysvals.usecallgraph or sysvals.usetraceevents):
  4292. appendIncompleteTraceLog(testruns)
  4293. createHTML(testruns)
  4294. # Function: runSummary
  4295. # Description:
  4296. # create a summary of tests in a sub-directory
  4297. def runSummary(subdir, output):
  4298. global sysvals
  4299. # get a list of ftrace output files
  4300. files = []
  4301. for dirname, dirnames, filenames in os.walk(subdir):
  4302. for filename in filenames:
  4303. if(re.match('.*_ftrace.txt', filename)):
  4304. files.append("%s/%s" % (dirname, filename))
  4305. # process the files in order and get an array of data objects
  4306. testruns = []
  4307. for file in sorted(files):
  4308. if output:
  4309. print("Test found in %s" % os.path.dirname(file))
  4310. sysvals.ftracefile = file
  4311. sysvals.dmesgfile = file.replace('_ftrace.txt', '_dmesg.txt')
  4312. doesTraceLogHaveTraceEvents()
  4313. sysvals.usecallgraph = False
  4314. if not sysvals.usetraceeventsonly:
  4315. if(not os.path.exists(sysvals.dmesgfile)):
  4316. print("Skipping %s: not a valid test input" % file)
  4317. continue
  4318. else:
  4319. if output:
  4320. f = os.path.basename(sysvals.ftracefile)
  4321. d = os.path.basename(sysvals.dmesgfile)
  4322. print("\tInput files: %s and %s" % (f, d))
  4323. testdata = loadKernelLog()
  4324. data = testdata[0]
  4325. parseKernelLog(data)
  4326. testdata = [data]
  4327. appendIncompleteTraceLog(testdata)
  4328. else:
  4329. if output:
  4330. print("\tInput file: %s" % os.path.basename(sysvals.ftracefile))
  4331. testdata = parseTraceLog()
  4332. data = testdata[0]
  4333. data.normalizeTime(data.tSuspended)
  4334. link = file.replace(subdir+'/', '').replace('_ftrace.txt', '.html')
  4335. data.outfile = link
  4336. testruns.append(data)
  4337. createHTMLSummarySimple(testruns, subdir+'/summary.html')
  4338. # Function: checkArgBool
  4339. # Description:
  4340. # check if a boolean string value is true or false
  4341. def checkArgBool(value):
  4342. yes = ['1', 'true', 'yes', 'on']
  4343. if value.lower() in yes:
  4344. return True
  4345. return False
  4346. # Function: configFromFile
  4347. # Description:
  4348. # Configure the script via the info in a config file
  4349. def configFromFile(file):
  4350. global sysvals
  4351. Config = ConfigParser.ConfigParser()
  4352. ignorekprobes = False
  4353. Config.read(file)
  4354. sections = Config.sections()
  4355. if 'Settings' in sections:
  4356. for opt in Config.options('Settings'):
  4357. value = Config.get('Settings', opt).lower()
  4358. if(opt.lower() == 'verbose'):
  4359. sysvals.verbose = checkArgBool(value)
  4360. elif(opt.lower() == 'addlogs'):
  4361. sysvals.addlogs = checkArgBool(value)
  4362. elif(opt.lower() == 'dev'):
  4363. sysvals.usedevsrc = checkArgBool(value)
  4364. elif(opt.lower() == 'ignorekprobes'):
  4365. ignorekprobes = checkArgBool(value)
  4366. elif(opt.lower() == 'x2'):
  4367. if checkArgBool(value):
  4368. sysvals.execcount = 2
  4369. elif(opt.lower() == 'callgraph'):
  4370. sysvals.usecallgraph = checkArgBool(value)
  4371. elif(opt.lower() == 'callgraphfunc'):
  4372. sysvals.debugfuncs = []
  4373. if value:
  4374. value = value.split(',')
  4375. for i in value:
  4376. sysvals.debugfuncs.append(i.strip())
  4377. elif(opt.lower() == 'expandcg'):
  4378. sysvals.cgexp = checkArgBool(value)
  4379. elif(opt.lower() == 'srgap'):
  4380. if checkArgBool(value):
  4381. sysvals.srgap = 5
  4382. elif(opt.lower() == 'mode'):
  4383. sysvals.suspendmode = value
  4384. elif(opt.lower() == 'command'):
  4385. sysvals.testcommand = value
  4386. elif(opt.lower() == 'x2delay'):
  4387. sysvals.x2delay = getArgInt('-x2delay', value, 0, 60000, False)
  4388. elif(opt.lower() == 'postres'):
  4389. sysvals.postresumetime = getArgInt('-postres', value, 0, 3600, False)
  4390. elif(opt.lower() == 'rtcwake'):
  4391. sysvals.rtcwake = True
  4392. sysvals.rtcwaketime = getArgInt('-rtcwake', value, 0, 3600, False)
  4393. elif(opt.lower() == 'timeprec'):
  4394. sysvals.setPrecision(getArgInt('-timeprec', value, 0, 6, False))
  4395. elif(opt.lower() == 'mindev'):
  4396. sysvals.mindevlen = getArgFloat('-mindev', value, 0.0, 10000.0, False)
  4397. elif(opt.lower() == 'mincg'):
  4398. sysvals.mincglen = getArgFloat('-mincg', value, 0.0, 10000.0, False)
  4399. elif(opt.lower() == 'kprobecolor'):
  4400. try:
  4401. val = int(value, 16)
  4402. sysvals.kprobecolor = '#'+value
  4403. except:
  4404. sysvals.kprobecolor = value
  4405. elif(opt.lower() == 'synccolor'):
  4406. try:
  4407. val = int(value, 16)
  4408. sysvals.synccolor = '#'+value
  4409. except:
  4410. sysvals.synccolor = value
  4411. elif(opt.lower() == 'output-dir'):
  4412. args = dict()
  4413. n = datetime.now()
  4414. args['date'] = n.strftime('%y%m%d')
  4415. args['time'] = n.strftime('%H%M%S')
  4416. args['hostname'] = sysvals.hostname
  4417. sysvals.outdir = value.format(**args)
  4418. if sysvals.suspendmode == 'command' and not sysvals.testcommand:
  4419. doError('No command supplied for mode "command"', False)
  4420. if sysvals.usedevsrc and sysvals.usecallgraph:
  4421. doError('dev and callgraph cannot both be true', False)
  4422. if sysvals.usecallgraph and sysvals.execcount > 1:
  4423. doError('-x2 is not compatible with -f', False)
  4424. if ignorekprobes:
  4425. return
  4426. kprobes = dict()
  4427. archkprobe = 'Kprobe_'+platform.machine()
  4428. if archkprobe in sections:
  4429. for name in Config.options(archkprobe):
  4430. kprobes[name] = Config.get(archkprobe, name)
  4431. if 'Kprobe' in sections:
  4432. for name in Config.options('Kprobe'):
  4433. kprobes[name] = Config.get('Kprobe', name)
  4434. for name in kprobes:
  4435. function = name
  4436. format = name
  4437. color = ''
  4438. args = dict()
  4439. data = kprobes[name].split()
  4440. i = 0
  4441. for val in data:
  4442. # bracketted strings are special formatting, read them separately
  4443. if val[0] == '[' and val[-1] == ']':
  4444. for prop in val[1:-1].split(','):
  4445. p = prop.split('=')
  4446. if p[0] == 'color':
  4447. try:
  4448. color = int(p[1], 16)
  4449. color = '#'+p[1]
  4450. except:
  4451. color = p[1]
  4452. continue
  4453. # first real arg should be the format string
  4454. if i == 0:
  4455. format = val
  4456. # all other args are actual function args
  4457. else:
  4458. d = val.split('=')
  4459. args[d[0]] = d[1]
  4460. i += 1
  4461. if not function or not format:
  4462. doError('Invalid kprobe: %s' % name, False)
  4463. for arg in re.findall('{(?P<n>[a-z,A-Z,0-9]*)}', format):
  4464. if arg not in args:
  4465. doError('Kprobe "%s" is missing argument "%s"' % (name, arg), False)
  4466. if name in sysvals.kprobes:
  4467. doError('Duplicate kprobe found "%s"' % (name), False)
  4468. vprint('Adding KPROBE: %s %s %s %s' % (name, function, format, args))
  4469. sysvals.kprobes[name] = {
  4470. 'name': name,
  4471. 'func': function,
  4472. 'format': format,
  4473. 'args': args,
  4474. 'mask': re.sub('{(?P<n>[a-z,A-Z,0-9]*)}', '.*', format)
  4475. }
  4476. if color:
  4477. sysvals.kprobes[name]['color'] = color
  4478. # Function: printHelp
  4479. # Description:
  4480. # print out the help text
  4481. def printHelp():
  4482. global sysvals
  4483. modes = getModes()
  4484. print('')
  4485. print('AnalyzeSuspend v%s' % sysvals.version)
  4486. print('Usage: sudo analyze_suspend.py <options>')
  4487. print('')
  4488. print('Description:')
  4489. print(' This tool is designed to assist kernel and OS developers in optimizing')
  4490. print(' their linux stack\'s suspend/resume time. Using a kernel image built')
  4491. print(' with a few extra options enabled, the tool will execute a suspend and')
  4492. print(' capture dmesg and ftrace data until resume is complete. This data is')
  4493. print(' transformed into a device timeline and an optional callgraph to give')
  4494. print(' a detailed view of which devices/subsystems are taking the most')
  4495. print(' time in suspend/resume.')
  4496. print('')
  4497. print(' Generates output files in subdirectory: suspend-mmddyy-HHMMSS')
  4498. print(' HTML output: <hostname>_<mode>.html')
  4499. print(' raw dmesg output: <hostname>_<mode>_dmesg.txt')
  4500. print(' raw ftrace output: <hostname>_<mode>_ftrace.txt')
  4501. print('')
  4502. print('Options:')
  4503. print(' [general]')
  4504. print(' -h Print this help text')
  4505. print(' -v Print the current tool version')
  4506. print(' -config file Pull arguments and config options from a file')
  4507. print(' -verbose Print extra information during execution and analysis')
  4508. print(' -status Test to see if the system is enabled to run this tool')
  4509. print(' -modes List available suspend modes')
  4510. print(' -m mode Mode to initiate for suspend %s (default: %s)') % (modes, sysvals.suspendmode)
  4511. print(' -o subdir Override the output subdirectory')
  4512. print(' [advanced]')
  4513. print(' -rtcwake t Use rtcwake to autoresume after <t> seconds (default: disabled)')
  4514. print(' -addlogs Add the dmesg and ftrace logs to the html output')
  4515. print(' -multi n d Execute <n> consecutive tests at <d> seconds intervals. The outputs will')
  4516. print(' be created in a new subdirectory with a summary page.')
  4517. print(' -srgap Add a visible gap in the timeline between sus/res (default: disabled)')
  4518. print(' -cmd {s} Instead of suspend/resume, run a command, e.g. "sync -d"')
  4519. print(' -mindev ms Discard all device blocks shorter than ms milliseconds (e.g. 0.001 for us)')
  4520. print(' -mincg ms Discard all callgraphs shorter than ms milliseconds (e.g. 0.001 for us)')
  4521. print(' -timeprec N Number of significant digits in timestamps (0:S, [3:ms], 6:us)')
  4522. print(' [debug]')
  4523. print(' -f Use ftrace to create device callgraphs (default: disabled)')
  4524. print(' -expandcg pre-expand the callgraph data in the html output (default: disabled)')
  4525. print(' -flist Print the list of functions currently being captured in ftrace')
  4526. print(' -flistall Print all functions capable of being captured in ftrace')
  4527. print(' -fadd file Add functions to be graphed in the timeline from a list in a text file')
  4528. print(' -filter "d1 d2 ..." Filter out all but this list of device names')
  4529. print(' -dev Display common low level functions in the timeline')
  4530. print(' [post-resume task analysis]')
  4531. print(' -x2 Run two suspend/resumes back to back (default: disabled)')
  4532. print(' -x2delay t Minimum millisecond delay <t> between the two test runs (default: 0 ms)')
  4533. print(' -postres t Time after resume completion to wait for post-resume events (default: 0 S)')
  4534. print(' [utilities]')
  4535. print(' -fpdt Print out the contents of the ACPI Firmware Performance Data Table')
  4536. print(' -usbtopo Print out the current USB topology with power info')
  4537. print(' -usbauto Enable autosuspend for all connected USB devices')
  4538. print(' [re-analyze data from previous runs]')
  4539. print(' -ftrace ftracefile Create HTML output using ftrace input')
  4540. print(' -dmesg dmesgfile Create HTML output using dmesg (not needed for kernel >= 3.15)')
  4541. print(' -summary directory Create a summary of all test in this dir')
  4542. print('')
  4543. return True
  4544. # ----------------- MAIN --------------------
  4545. # exec start (skipped if script is loaded as library)
  4546. if __name__ == '__main__':
  4547. cmd = ''
  4548. cmdarg = ''
  4549. multitest = {'run': False, 'count': 0, 'delay': 0}
  4550. simplecmds = ['-modes', '-fpdt', '-flist', '-flistall', '-usbtopo', '-usbauto', '-status']
  4551. # loop through the command line arguments
  4552. args = iter(sys.argv[1:])
  4553. for arg in args:
  4554. if(arg == '-m'):
  4555. try:
  4556. val = args.next()
  4557. except:
  4558. doError('No mode supplied', True)
  4559. if val == 'command' and not sysvals.testcommand:
  4560. doError('No command supplied for mode "command"', True)
  4561. sysvals.suspendmode = val
  4562. elif(arg in simplecmds):
  4563. cmd = arg[1:]
  4564. elif(arg == '-h'):
  4565. printHelp()
  4566. sys.exit()
  4567. elif(arg == '-v'):
  4568. print("Version %s" % sysvals.version)
  4569. sys.exit()
  4570. elif(arg == '-x2'):
  4571. sysvals.execcount = 2
  4572. if(sysvals.usecallgraph):
  4573. doError('-x2 is not compatible with -f', False)
  4574. elif(arg == '-x2delay'):
  4575. sysvals.x2delay = getArgInt('-x2delay', args, 0, 60000)
  4576. elif(arg == '-postres'):
  4577. sysvals.postresumetime = getArgInt('-postres', args, 0, 3600)
  4578. elif(arg == '-f'):
  4579. sysvals.usecallgraph = True
  4580. if(sysvals.execcount > 1):
  4581. doError('-x2 is not compatible with -f', False)
  4582. if(sysvals.usedevsrc):
  4583. doError('-dev is not compatible with -f', False)
  4584. elif(arg == '-addlogs'):
  4585. sysvals.addlogs = True
  4586. elif(arg == '-verbose'):
  4587. sysvals.verbose = True
  4588. elif(arg == '-dev'):
  4589. sysvals.usedevsrc = True
  4590. if(sysvals.usecallgraph):
  4591. doError('-dev is not compatible with -f', False)
  4592. elif(arg == '-rtcwake'):
  4593. sysvals.rtcwake = True
  4594. sysvals.rtcwaketime = getArgInt('-rtcwake', args, 0, 3600)
  4595. elif(arg == '-timeprec'):
  4596. sysvals.setPrecision(getArgInt('-timeprec', args, 0, 6))
  4597. elif(arg == '-mindev'):
  4598. sysvals.mindevlen = getArgFloat('-mindev', args, 0.0, 10000.0)
  4599. elif(arg == '-mincg'):
  4600. sysvals.mincglen = getArgFloat('-mincg', args, 0.0, 10000.0)
  4601. elif(arg == '-cmd'):
  4602. try:
  4603. val = args.next()
  4604. except:
  4605. doError('No command string supplied', True)
  4606. sysvals.testcommand = val
  4607. sysvals.suspendmode = 'command'
  4608. elif(arg == '-expandcg'):
  4609. sysvals.cgexp = True
  4610. elif(arg == '-srgap'):
  4611. sysvals.srgap = 5
  4612. elif(arg == '-multi'):
  4613. multitest['run'] = True
  4614. multitest['count'] = getArgInt('-multi n (exec count)', args, 2, 1000000)
  4615. multitest['delay'] = getArgInt('-multi d (delay between tests)', args, 0, 3600)
  4616. elif(arg == '-o'):
  4617. try:
  4618. val = args.next()
  4619. except:
  4620. doError('No subdirectory name supplied', True)
  4621. sysvals.outdir = val
  4622. elif(arg == '-config'):
  4623. try:
  4624. val = args.next()
  4625. except:
  4626. doError('No text file supplied', True)
  4627. if(os.path.exists(val) == False):
  4628. doError('%s does not exist' % val, False)
  4629. configFromFile(val)
  4630. elif(arg == '-fadd'):
  4631. try:
  4632. val = args.next()
  4633. except:
  4634. doError('No text file supplied', True)
  4635. if(os.path.exists(val) == False):
  4636. doError('%s does not exist' % val, False)
  4637. sysvals.addFtraceFilterFunctions(val)
  4638. elif(arg == '-dmesg'):
  4639. try:
  4640. val = args.next()
  4641. except:
  4642. doError('No dmesg file supplied', True)
  4643. sysvals.notestrun = True
  4644. sysvals.dmesgfile = val
  4645. if(os.path.exists(sysvals.dmesgfile) == False):
  4646. doError('%s does not exist' % sysvals.dmesgfile, False)
  4647. elif(arg == '-ftrace'):
  4648. try:
  4649. val = args.next()
  4650. except:
  4651. doError('No ftrace file supplied', True)
  4652. sysvals.notestrun = True
  4653. sysvals.ftracefile = val
  4654. if(os.path.exists(sysvals.ftracefile) == False):
  4655. doError('%s does not exist' % sysvals.ftracefile, False)
  4656. elif(arg == '-summary'):
  4657. try:
  4658. val = args.next()
  4659. except:
  4660. doError('No directory supplied', True)
  4661. cmd = 'summary'
  4662. cmdarg = val
  4663. sysvals.notestrun = True
  4664. if(os.path.isdir(val) == False):
  4665. doError('%s is not accesible' % val, False)
  4666. elif(arg == '-filter'):
  4667. try:
  4668. val = args.next()
  4669. except:
  4670. doError('No devnames supplied', True)
  4671. sysvals.setDeviceFilter(val)
  4672. else:
  4673. doError('Invalid argument: '+arg, True)
  4674. # callgraph size cannot exceed device size
  4675. if sysvals.mincglen < sysvals.mindevlen:
  4676. sysvals.mincglen = sysvals.mindevlen
  4677. # just run a utility command and exit
  4678. if(cmd != ''):
  4679. if(cmd == 'status'):
  4680. statusCheck(True)
  4681. elif(cmd == 'fpdt'):
  4682. getFPDT(True)
  4683. elif(cmd == 'usbtopo'):
  4684. detectUSB()
  4685. elif(cmd == 'modes'):
  4686. modes = getModes()
  4687. print modes
  4688. elif(cmd == 'flist'):
  4689. sysvals.getFtraceFilterFunctions(True)
  4690. elif(cmd == 'flistall'):
  4691. sysvals.getFtraceFilterFunctions(False)
  4692. elif(cmd == 'usbauto'):
  4693. setUSBDevicesAuto()
  4694. elif(cmd == 'summary'):
  4695. print("Generating a summary of folder \"%s\"" % cmdarg)
  4696. runSummary(cmdarg, True)
  4697. sys.exit()
  4698. # if instructed, re-analyze existing data files
  4699. if(sysvals.notestrun):
  4700. rerunTest()
  4701. sys.exit()
  4702. # verify that we can run a test
  4703. if(not statusCheck()):
  4704. print('Check FAILED, aborting the test run!')
  4705. sys.exit()
  4706. if multitest['run']:
  4707. # run multiple tests in a separate subdirectory
  4708. s = 'x%d' % multitest['count']
  4709. if not sysvals.outdir:
  4710. sysvals.outdir = datetime.now().strftime('suspend-'+s+'-%m%d%y-%H%M%S')
  4711. if not os.path.isdir(sysvals.outdir):
  4712. os.mkdir(sysvals.outdir)
  4713. for i in range(multitest['count']):
  4714. if(i != 0):
  4715. print('Waiting %d seconds...' % (multitest['delay']))
  4716. time.sleep(multitest['delay'])
  4717. print('TEST (%d/%d) START' % (i+1, multitest['count']))
  4718. runTest(sysvals.outdir)
  4719. print('TEST (%d/%d) COMPLETE' % (i+1, multitest['count']))
  4720. runSummary(sysvals.outdir, False)
  4721. else:
  4722. # run the test in the current directory
  4723. runTest('.', sysvals.outdir)