builtin-sched.c 101 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006
  1. // SPDX-License-Identifier: GPL-2.0
  2. #include "builtin.h"
  3. #include "perf-sys.h"
  4. #include "util/cpumap.h"
  5. #include "util/evlist.h"
  6. #include "util/evsel.h"
  7. #include "util/evsel_fprintf.h"
  8. #include "util/mutex.h"
  9. #include "util/symbol.h"
  10. #include "util/thread.h"
  11. #include "util/header.h"
  12. #include "util/session.h"
  13. #include "util/tool.h"
  14. #include "util/cloexec.h"
  15. #include "util/thread_map.h"
  16. #include "util/color.h"
  17. #include "util/stat.h"
  18. #include "util/string2.h"
  19. #include "util/callchain.h"
  20. #include "util/time-utils.h"
  21. #include <subcmd/pager.h>
  22. #include <subcmd/parse-options.h>
  23. #include "util/trace-event.h"
  24. #include "util/debug.h"
  25. #include "util/event.h"
  26. #include "util/util.h"
  27. #include <linux/kernel.h>
  28. #include <linux/log2.h>
  29. #include <linux/zalloc.h>
  30. #include <sys/prctl.h>
  31. #include <sys/resource.h>
  32. #include <inttypes.h>
  33. #include <errno.h>
  34. #include <semaphore.h>
  35. #include <pthread.h>
  36. #include <math.h>
  37. #include <api/fs/fs.h>
  38. #include <perf/cpumap.h>
  39. #include <linux/time64.h>
  40. #include <linux/err.h>
  41. #include <linux/ctype.h>
  42. #define PR_SET_NAME 15 /* Set process name */
  43. #define MAX_CPUS 4096
  44. #define COMM_LEN 20
  45. #define SYM_LEN 129
  46. #define MAX_PID 1024000
  47. #define MAX_PRIO 140
  48. static const char *cpu_list;
  49. static DECLARE_BITMAP(cpu_bitmap, MAX_NR_CPUS);
  50. struct sched_atom;
  51. struct task_desc {
  52. unsigned long nr;
  53. unsigned long pid;
  54. char comm[COMM_LEN];
  55. unsigned long nr_events;
  56. unsigned long curr_event;
  57. struct sched_atom **atoms;
  58. pthread_t thread;
  59. sem_t sleep_sem;
  60. sem_t ready_for_work;
  61. sem_t work_done_sem;
  62. u64 cpu_usage;
  63. };
  64. enum sched_event_type {
  65. SCHED_EVENT_RUN,
  66. SCHED_EVENT_SLEEP,
  67. SCHED_EVENT_WAKEUP,
  68. SCHED_EVENT_MIGRATION,
  69. };
  70. struct sched_atom {
  71. enum sched_event_type type;
  72. int specific_wait;
  73. u64 timestamp;
  74. u64 duration;
  75. unsigned long nr;
  76. sem_t *wait_sem;
  77. struct task_desc *wakee;
  78. };
  79. enum thread_state {
  80. THREAD_SLEEPING = 0,
  81. THREAD_WAIT_CPU,
  82. THREAD_SCHED_IN,
  83. THREAD_IGNORE
  84. };
  85. struct work_atom {
  86. struct list_head list;
  87. enum thread_state state;
  88. u64 sched_out_time;
  89. u64 wake_up_time;
  90. u64 sched_in_time;
  91. u64 runtime;
  92. };
  93. struct work_atoms {
  94. struct list_head work_list;
  95. struct thread *thread;
  96. struct rb_node node;
  97. u64 max_lat;
  98. u64 max_lat_start;
  99. u64 max_lat_end;
  100. u64 total_lat;
  101. u64 nb_atoms;
  102. u64 total_runtime;
  103. int num_merged;
  104. };
  105. typedef int (*sort_fn_t)(struct work_atoms *, struct work_atoms *);
  106. struct perf_sched;
  107. struct trace_sched_handler {
  108. int (*switch_event)(struct perf_sched *sched, struct evsel *evsel,
  109. struct perf_sample *sample, struct machine *machine);
  110. int (*runtime_event)(struct perf_sched *sched, struct evsel *evsel,
  111. struct perf_sample *sample, struct machine *machine);
  112. int (*wakeup_event)(struct perf_sched *sched, struct evsel *evsel,
  113. struct perf_sample *sample, struct machine *machine);
  114. /* PERF_RECORD_FORK event, not sched_process_fork tracepoint */
  115. int (*fork_event)(struct perf_sched *sched, union perf_event *event,
  116. struct machine *machine);
  117. int (*migrate_task_event)(struct perf_sched *sched,
  118. struct evsel *evsel,
  119. struct perf_sample *sample,
  120. struct machine *machine);
  121. };
  122. #define COLOR_PIDS PERF_COLOR_BLUE
  123. #define COLOR_CPUS PERF_COLOR_BG_RED
  124. struct perf_sched_map {
  125. DECLARE_BITMAP(comp_cpus_mask, MAX_CPUS);
  126. struct perf_cpu *comp_cpus;
  127. bool comp;
  128. struct perf_thread_map *color_pids;
  129. const char *color_pids_str;
  130. struct perf_cpu_map *color_cpus;
  131. const char *color_cpus_str;
  132. const char *task_name;
  133. struct strlist *task_names;
  134. bool fuzzy;
  135. struct perf_cpu_map *cpus;
  136. const char *cpus_str;
  137. };
  138. struct perf_sched {
  139. struct perf_tool tool;
  140. const char *sort_order;
  141. unsigned long nr_tasks;
  142. struct task_desc **pid_to_task;
  143. struct task_desc **tasks;
  144. const struct trace_sched_handler *tp_handler;
  145. struct mutex start_work_mutex;
  146. struct mutex work_done_wait_mutex;
  147. int profile_cpu;
  148. /*
  149. * Track the current task - that way we can know whether there's any
  150. * weird events, such as a task being switched away that is not current.
  151. */
  152. struct perf_cpu max_cpu;
  153. u32 *curr_pid;
  154. struct thread **curr_thread;
  155. struct thread **curr_out_thread;
  156. char next_shortname1;
  157. char next_shortname2;
  158. unsigned int replay_repeat;
  159. unsigned long nr_run_events;
  160. unsigned long nr_sleep_events;
  161. unsigned long nr_wakeup_events;
  162. unsigned long nr_sleep_corrections;
  163. unsigned long nr_run_events_optimized;
  164. unsigned long targetless_wakeups;
  165. unsigned long multitarget_wakeups;
  166. unsigned long nr_runs;
  167. unsigned long nr_timestamps;
  168. unsigned long nr_unordered_timestamps;
  169. unsigned long nr_context_switch_bugs;
  170. unsigned long nr_events;
  171. unsigned long nr_lost_chunks;
  172. unsigned long nr_lost_events;
  173. u64 run_measurement_overhead;
  174. u64 sleep_measurement_overhead;
  175. u64 start_time;
  176. u64 cpu_usage;
  177. u64 runavg_cpu_usage;
  178. u64 parent_cpu_usage;
  179. u64 runavg_parent_cpu_usage;
  180. u64 sum_runtime;
  181. u64 sum_fluct;
  182. u64 run_avg;
  183. u64 all_runtime;
  184. u64 all_count;
  185. u64 *cpu_last_switched;
  186. struct rb_root_cached atom_root, sorted_atom_root, merged_atom_root;
  187. struct list_head sort_list, cmp_pid;
  188. bool force;
  189. bool skip_merge;
  190. struct perf_sched_map map;
  191. /* options for timehist command */
  192. bool summary;
  193. bool summary_only;
  194. bool idle_hist;
  195. bool show_callchain;
  196. unsigned int max_stack;
  197. bool show_cpu_visual;
  198. bool show_wakeups;
  199. bool show_next;
  200. bool show_migrations;
  201. bool show_state;
  202. bool show_prio;
  203. u64 skipped_samples;
  204. const char *time_str;
  205. struct perf_time_interval ptime;
  206. struct perf_time_interval hist_time;
  207. volatile bool thread_funcs_exit;
  208. const char *prio_str;
  209. DECLARE_BITMAP(prio_bitmap, MAX_PRIO);
  210. };
  211. /* per thread run time data */
  212. struct thread_runtime {
  213. u64 last_time; /* time of previous sched in/out event */
  214. u64 dt_run; /* run time */
  215. u64 dt_sleep; /* time between CPU access by sleep (off cpu) */
  216. u64 dt_iowait; /* time between CPU access by iowait (off cpu) */
  217. u64 dt_preempt; /* time between CPU access by preempt (off cpu) */
  218. u64 dt_delay; /* time between wakeup and sched-in */
  219. u64 ready_to_run; /* time of wakeup */
  220. struct stats run_stats;
  221. u64 total_run_time;
  222. u64 total_sleep_time;
  223. u64 total_iowait_time;
  224. u64 total_preempt_time;
  225. u64 total_delay_time;
  226. char last_state;
  227. char shortname[3];
  228. bool comm_changed;
  229. u64 migrations;
  230. int prio;
  231. };
  232. /* per event run time data */
  233. struct evsel_runtime {
  234. u64 *last_time; /* time this event was last seen per cpu */
  235. u32 ncpu; /* highest cpu slot allocated */
  236. };
  237. /* per cpu idle time data */
  238. struct idle_thread_runtime {
  239. struct thread_runtime tr;
  240. struct thread *last_thread;
  241. struct rb_root_cached sorted_root;
  242. struct callchain_root callchain;
  243. struct callchain_cursor cursor;
  244. };
  245. /* track idle times per cpu */
  246. static struct thread **idle_threads;
  247. static int idle_max_cpu;
  248. static char idle_comm[] = "<idle>";
  249. static u64 get_nsecs(void)
  250. {
  251. struct timespec ts;
  252. clock_gettime(CLOCK_MONOTONIC, &ts);
  253. return ts.tv_sec * NSEC_PER_SEC + ts.tv_nsec;
  254. }
  255. static void burn_nsecs(struct perf_sched *sched, u64 nsecs)
  256. {
  257. u64 T0 = get_nsecs(), T1;
  258. do {
  259. T1 = get_nsecs();
  260. } while (T1 + sched->run_measurement_overhead < T0 + nsecs);
  261. }
  262. static void sleep_nsecs(u64 nsecs)
  263. {
  264. struct timespec ts;
  265. ts.tv_nsec = nsecs % 999999999;
  266. ts.tv_sec = nsecs / 999999999;
  267. nanosleep(&ts, NULL);
  268. }
  269. static void calibrate_run_measurement_overhead(struct perf_sched *sched)
  270. {
  271. u64 T0, T1, delta, min_delta = NSEC_PER_SEC;
  272. int i;
  273. for (i = 0; i < 10; i++) {
  274. T0 = get_nsecs();
  275. burn_nsecs(sched, 0);
  276. T1 = get_nsecs();
  277. delta = T1-T0;
  278. min_delta = min(min_delta, delta);
  279. }
  280. sched->run_measurement_overhead = min_delta;
  281. printf("run measurement overhead: %" PRIu64 " nsecs\n", min_delta);
  282. }
  283. static void calibrate_sleep_measurement_overhead(struct perf_sched *sched)
  284. {
  285. u64 T0, T1, delta, min_delta = NSEC_PER_SEC;
  286. int i;
  287. for (i = 0; i < 10; i++) {
  288. T0 = get_nsecs();
  289. sleep_nsecs(10000);
  290. T1 = get_nsecs();
  291. delta = T1-T0;
  292. min_delta = min(min_delta, delta);
  293. }
  294. min_delta -= 10000;
  295. sched->sleep_measurement_overhead = min_delta;
  296. printf("sleep measurement overhead: %" PRIu64 " nsecs\n", min_delta);
  297. }
  298. static struct sched_atom *
  299. get_new_event(struct task_desc *task, u64 timestamp)
  300. {
  301. struct sched_atom *event = zalloc(sizeof(*event));
  302. unsigned long idx = task->nr_events;
  303. size_t size;
  304. event->timestamp = timestamp;
  305. event->nr = idx;
  306. task->nr_events++;
  307. size = sizeof(struct sched_atom *) * task->nr_events;
  308. task->atoms = realloc(task->atoms, size);
  309. BUG_ON(!task->atoms);
  310. task->atoms[idx] = event;
  311. return event;
  312. }
  313. static struct sched_atom *last_event(struct task_desc *task)
  314. {
  315. if (!task->nr_events)
  316. return NULL;
  317. return task->atoms[task->nr_events - 1];
  318. }
  319. static void add_sched_event_run(struct perf_sched *sched, struct task_desc *task,
  320. u64 timestamp, u64 duration)
  321. {
  322. struct sched_atom *event, *curr_event = last_event(task);
  323. /*
  324. * optimize an existing RUN event by merging this one
  325. * to it:
  326. */
  327. if (curr_event && curr_event->type == SCHED_EVENT_RUN) {
  328. sched->nr_run_events_optimized++;
  329. curr_event->duration += duration;
  330. return;
  331. }
  332. event = get_new_event(task, timestamp);
  333. event->type = SCHED_EVENT_RUN;
  334. event->duration = duration;
  335. sched->nr_run_events++;
  336. }
  337. static void add_sched_event_wakeup(struct perf_sched *sched, struct task_desc *task,
  338. u64 timestamp, struct task_desc *wakee)
  339. {
  340. struct sched_atom *event, *wakee_event;
  341. event = get_new_event(task, timestamp);
  342. event->type = SCHED_EVENT_WAKEUP;
  343. event->wakee = wakee;
  344. wakee_event = last_event(wakee);
  345. if (!wakee_event || wakee_event->type != SCHED_EVENT_SLEEP) {
  346. sched->targetless_wakeups++;
  347. return;
  348. }
  349. if (wakee_event->wait_sem) {
  350. sched->multitarget_wakeups++;
  351. return;
  352. }
  353. wakee_event->wait_sem = zalloc(sizeof(*wakee_event->wait_sem));
  354. sem_init(wakee_event->wait_sem, 0, 0);
  355. wakee_event->specific_wait = 1;
  356. event->wait_sem = wakee_event->wait_sem;
  357. sched->nr_wakeup_events++;
  358. }
  359. static void add_sched_event_sleep(struct perf_sched *sched, struct task_desc *task,
  360. u64 timestamp, const char task_state __maybe_unused)
  361. {
  362. struct sched_atom *event = get_new_event(task, timestamp);
  363. event->type = SCHED_EVENT_SLEEP;
  364. sched->nr_sleep_events++;
  365. }
  366. static struct task_desc *register_pid(struct perf_sched *sched,
  367. unsigned long pid, const char *comm)
  368. {
  369. struct task_desc *task;
  370. static int pid_max;
  371. if (sched->pid_to_task == NULL) {
  372. if (sysctl__read_int("kernel/pid_max", &pid_max) < 0)
  373. pid_max = MAX_PID;
  374. BUG_ON((sched->pid_to_task = calloc(pid_max, sizeof(struct task_desc *))) == NULL);
  375. }
  376. if (pid >= (unsigned long)pid_max) {
  377. BUG_ON((sched->pid_to_task = realloc(sched->pid_to_task, (pid + 1) *
  378. sizeof(struct task_desc *))) == NULL);
  379. while (pid >= (unsigned long)pid_max)
  380. sched->pid_to_task[pid_max++] = NULL;
  381. }
  382. task = sched->pid_to_task[pid];
  383. if (task)
  384. return task;
  385. task = zalloc(sizeof(*task));
  386. task->pid = pid;
  387. task->nr = sched->nr_tasks;
  388. strcpy(task->comm, comm);
  389. /*
  390. * every task starts in sleeping state - this gets ignored
  391. * if there's no wakeup pointing to this sleep state:
  392. */
  393. add_sched_event_sleep(sched, task, 0, 0);
  394. sched->pid_to_task[pid] = task;
  395. sched->nr_tasks++;
  396. sched->tasks = realloc(sched->tasks, sched->nr_tasks * sizeof(struct task_desc *));
  397. BUG_ON(!sched->tasks);
  398. sched->tasks[task->nr] = task;
  399. if (verbose > 0)
  400. printf("registered task #%ld, PID %ld (%s)\n", sched->nr_tasks, pid, comm);
  401. return task;
  402. }
  403. static void print_task_traces(struct perf_sched *sched)
  404. {
  405. struct task_desc *task;
  406. unsigned long i;
  407. for (i = 0; i < sched->nr_tasks; i++) {
  408. task = sched->tasks[i];
  409. printf("task %6ld (%20s:%10ld), nr_events: %ld\n",
  410. task->nr, task->comm, task->pid, task->nr_events);
  411. }
  412. }
  413. static void add_cross_task_wakeups(struct perf_sched *sched)
  414. {
  415. struct task_desc *task1, *task2;
  416. unsigned long i, j;
  417. for (i = 0; i < sched->nr_tasks; i++) {
  418. task1 = sched->tasks[i];
  419. j = i + 1;
  420. if (j == sched->nr_tasks)
  421. j = 0;
  422. task2 = sched->tasks[j];
  423. add_sched_event_wakeup(sched, task1, 0, task2);
  424. }
  425. }
  426. static void perf_sched__process_event(struct perf_sched *sched,
  427. struct sched_atom *atom)
  428. {
  429. int ret = 0;
  430. switch (atom->type) {
  431. case SCHED_EVENT_RUN:
  432. burn_nsecs(sched, atom->duration);
  433. break;
  434. case SCHED_EVENT_SLEEP:
  435. if (atom->wait_sem)
  436. ret = sem_wait(atom->wait_sem);
  437. BUG_ON(ret);
  438. break;
  439. case SCHED_EVENT_WAKEUP:
  440. if (atom->wait_sem)
  441. ret = sem_post(atom->wait_sem);
  442. BUG_ON(ret);
  443. break;
  444. case SCHED_EVENT_MIGRATION:
  445. break;
  446. default:
  447. BUG_ON(1);
  448. }
  449. }
  450. static u64 get_cpu_usage_nsec_parent(void)
  451. {
  452. struct rusage ru;
  453. u64 sum;
  454. int err;
  455. err = getrusage(RUSAGE_SELF, &ru);
  456. BUG_ON(err);
  457. sum = ru.ru_utime.tv_sec * NSEC_PER_SEC + ru.ru_utime.tv_usec * NSEC_PER_USEC;
  458. sum += ru.ru_stime.tv_sec * NSEC_PER_SEC + ru.ru_stime.tv_usec * NSEC_PER_USEC;
  459. return sum;
  460. }
  461. static int self_open_counters(struct perf_sched *sched, unsigned long cur_task)
  462. {
  463. struct perf_event_attr attr;
  464. char sbuf[STRERR_BUFSIZE], info[STRERR_BUFSIZE];
  465. int fd;
  466. struct rlimit limit;
  467. bool need_privilege = false;
  468. memset(&attr, 0, sizeof(attr));
  469. attr.type = PERF_TYPE_SOFTWARE;
  470. attr.config = PERF_COUNT_SW_TASK_CLOCK;
  471. force_again:
  472. fd = sys_perf_event_open(&attr, 0, -1, -1,
  473. perf_event_open_cloexec_flag());
  474. if (fd < 0) {
  475. if (errno == EMFILE) {
  476. if (sched->force) {
  477. BUG_ON(getrlimit(RLIMIT_NOFILE, &limit) == -1);
  478. limit.rlim_cur += sched->nr_tasks - cur_task;
  479. if (limit.rlim_cur > limit.rlim_max) {
  480. limit.rlim_max = limit.rlim_cur;
  481. need_privilege = true;
  482. }
  483. if (setrlimit(RLIMIT_NOFILE, &limit) == -1) {
  484. if (need_privilege && errno == EPERM)
  485. strcpy(info, "Need privilege\n");
  486. } else
  487. goto force_again;
  488. } else
  489. strcpy(info, "Have a try with -f option\n");
  490. }
  491. pr_err("Error: sys_perf_event_open() syscall returned "
  492. "with %d (%s)\n%s", fd,
  493. str_error_r(errno, sbuf, sizeof(sbuf)), info);
  494. exit(EXIT_FAILURE);
  495. }
  496. return fd;
  497. }
  498. static u64 get_cpu_usage_nsec_self(int fd)
  499. {
  500. u64 runtime;
  501. int ret;
  502. ret = read(fd, &runtime, sizeof(runtime));
  503. BUG_ON(ret != sizeof(runtime));
  504. return runtime;
  505. }
  506. struct sched_thread_parms {
  507. struct task_desc *task;
  508. struct perf_sched *sched;
  509. int fd;
  510. };
  511. static void *thread_func(void *ctx)
  512. {
  513. struct sched_thread_parms *parms = ctx;
  514. struct task_desc *this_task = parms->task;
  515. struct perf_sched *sched = parms->sched;
  516. u64 cpu_usage_0, cpu_usage_1;
  517. unsigned long i, ret;
  518. char comm2[22];
  519. int fd = parms->fd;
  520. zfree(&parms);
  521. sprintf(comm2, ":%s", this_task->comm);
  522. prctl(PR_SET_NAME, comm2);
  523. if (fd < 0)
  524. return NULL;
  525. while (!sched->thread_funcs_exit) {
  526. ret = sem_post(&this_task->ready_for_work);
  527. BUG_ON(ret);
  528. mutex_lock(&sched->start_work_mutex);
  529. mutex_unlock(&sched->start_work_mutex);
  530. cpu_usage_0 = get_cpu_usage_nsec_self(fd);
  531. for (i = 0; i < this_task->nr_events; i++) {
  532. this_task->curr_event = i;
  533. perf_sched__process_event(sched, this_task->atoms[i]);
  534. }
  535. cpu_usage_1 = get_cpu_usage_nsec_self(fd);
  536. this_task->cpu_usage = cpu_usage_1 - cpu_usage_0;
  537. ret = sem_post(&this_task->work_done_sem);
  538. BUG_ON(ret);
  539. mutex_lock(&sched->work_done_wait_mutex);
  540. mutex_unlock(&sched->work_done_wait_mutex);
  541. }
  542. return NULL;
  543. }
  544. static void create_tasks(struct perf_sched *sched)
  545. EXCLUSIVE_LOCK_FUNCTION(sched->start_work_mutex)
  546. EXCLUSIVE_LOCK_FUNCTION(sched->work_done_wait_mutex)
  547. {
  548. struct task_desc *task;
  549. pthread_attr_t attr;
  550. unsigned long i;
  551. int err;
  552. err = pthread_attr_init(&attr);
  553. BUG_ON(err);
  554. err = pthread_attr_setstacksize(&attr,
  555. (size_t) max(16 * 1024, (int)PTHREAD_STACK_MIN));
  556. BUG_ON(err);
  557. mutex_lock(&sched->start_work_mutex);
  558. mutex_lock(&sched->work_done_wait_mutex);
  559. for (i = 0; i < sched->nr_tasks; i++) {
  560. struct sched_thread_parms *parms = malloc(sizeof(*parms));
  561. BUG_ON(parms == NULL);
  562. parms->task = task = sched->tasks[i];
  563. parms->sched = sched;
  564. parms->fd = self_open_counters(sched, i);
  565. sem_init(&task->sleep_sem, 0, 0);
  566. sem_init(&task->ready_for_work, 0, 0);
  567. sem_init(&task->work_done_sem, 0, 0);
  568. task->curr_event = 0;
  569. err = pthread_create(&task->thread, &attr, thread_func, parms);
  570. BUG_ON(err);
  571. }
  572. }
  573. static void destroy_tasks(struct perf_sched *sched)
  574. UNLOCK_FUNCTION(sched->start_work_mutex)
  575. UNLOCK_FUNCTION(sched->work_done_wait_mutex)
  576. {
  577. struct task_desc *task;
  578. unsigned long i;
  579. int err;
  580. mutex_unlock(&sched->start_work_mutex);
  581. mutex_unlock(&sched->work_done_wait_mutex);
  582. /* Get rid of threads so they won't be upset by mutex destrunction */
  583. for (i = 0; i < sched->nr_tasks; i++) {
  584. task = sched->tasks[i];
  585. err = pthread_join(task->thread, NULL);
  586. BUG_ON(err);
  587. sem_destroy(&task->sleep_sem);
  588. sem_destroy(&task->ready_for_work);
  589. sem_destroy(&task->work_done_sem);
  590. }
  591. }
  592. static void wait_for_tasks(struct perf_sched *sched)
  593. EXCLUSIVE_LOCKS_REQUIRED(sched->work_done_wait_mutex)
  594. EXCLUSIVE_LOCKS_REQUIRED(sched->start_work_mutex)
  595. {
  596. u64 cpu_usage_0, cpu_usage_1;
  597. struct task_desc *task;
  598. unsigned long i, ret;
  599. sched->start_time = get_nsecs();
  600. sched->cpu_usage = 0;
  601. mutex_unlock(&sched->work_done_wait_mutex);
  602. for (i = 0; i < sched->nr_tasks; i++) {
  603. task = sched->tasks[i];
  604. ret = sem_wait(&task->ready_for_work);
  605. BUG_ON(ret);
  606. sem_init(&task->ready_for_work, 0, 0);
  607. }
  608. mutex_lock(&sched->work_done_wait_mutex);
  609. cpu_usage_0 = get_cpu_usage_nsec_parent();
  610. mutex_unlock(&sched->start_work_mutex);
  611. for (i = 0; i < sched->nr_tasks; i++) {
  612. task = sched->tasks[i];
  613. ret = sem_wait(&task->work_done_sem);
  614. BUG_ON(ret);
  615. sem_init(&task->work_done_sem, 0, 0);
  616. sched->cpu_usage += task->cpu_usage;
  617. task->cpu_usage = 0;
  618. }
  619. cpu_usage_1 = get_cpu_usage_nsec_parent();
  620. if (!sched->runavg_cpu_usage)
  621. sched->runavg_cpu_usage = sched->cpu_usage;
  622. sched->runavg_cpu_usage = (sched->runavg_cpu_usage * (sched->replay_repeat - 1) + sched->cpu_usage) / sched->replay_repeat;
  623. sched->parent_cpu_usage = cpu_usage_1 - cpu_usage_0;
  624. if (!sched->runavg_parent_cpu_usage)
  625. sched->runavg_parent_cpu_usage = sched->parent_cpu_usage;
  626. sched->runavg_parent_cpu_usage = (sched->runavg_parent_cpu_usage * (sched->replay_repeat - 1) +
  627. sched->parent_cpu_usage)/sched->replay_repeat;
  628. mutex_lock(&sched->start_work_mutex);
  629. for (i = 0; i < sched->nr_tasks; i++) {
  630. task = sched->tasks[i];
  631. sem_init(&task->sleep_sem, 0, 0);
  632. task->curr_event = 0;
  633. }
  634. }
  635. static void run_one_test(struct perf_sched *sched)
  636. EXCLUSIVE_LOCKS_REQUIRED(sched->work_done_wait_mutex)
  637. EXCLUSIVE_LOCKS_REQUIRED(sched->start_work_mutex)
  638. {
  639. u64 T0, T1, delta, avg_delta, fluct;
  640. T0 = get_nsecs();
  641. wait_for_tasks(sched);
  642. T1 = get_nsecs();
  643. delta = T1 - T0;
  644. sched->sum_runtime += delta;
  645. sched->nr_runs++;
  646. avg_delta = sched->sum_runtime / sched->nr_runs;
  647. if (delta < avg_delta)
  648. fluct = avg_delta - delta;
  649. else
  650. fluct = delta - avg_delta;
  651. sched->sum_fluct += fluct;
  652. if (!sched->run_avg)
  653. sched->run_avg = delta;
  654. sched->run_avg = (sched->run_avg * (sched->replay_repeat - 1) + delta) / sched->replay_repeat;
  655. printf("#%-3ld: %0.3f, ", sched->nr_runs, (double)delta / NSEC_PER_MSEC);
  656. printf("ravg: %0.2f, ", (double)sched->run_avg / NSEC_PER_MSEC);
  657. printf("cpu: %0.2f / %0.2f",
  658. (double)sched->cpu_usage / NSEC_PER_MSEC, (double)sched->runavg_cpu_usage / NSEC_PER_MSEC);
  659. #if 0
  660. /*
  661. * rusage statistics done by the parent, these are less
  662. * accurate than the sched->sum_exec_runtime based statistics:
  663. */
  664. printf(" [%0.2f / %0.2f]",
  665. (double)sched->parent_cpu_usage / NSEC_PER_MSEC,
  666. (double)sched->runavg_parent_cpu_usage / NSEC_PER_MSEC);
  667. #endif
  668. printf("\n");
  669. if (sched->nr_sleep_corrections)
  670. printf(" (%ld sleep corrections)\n", sched->nr_sleep_corrections);
  671. sched->nr_sleep_corrections = 0;
  672. }
  673. static void test_calibrations(struct perf_sched *sched)
  674. {
  675. u64 T0, T1;
  676. T0 = get_nsecs();
  677. burn_nsecs(sched, NSEC_PER_MSEC);
  678. T1 = get_nsecs();
  679. printf("the run test took %" PRIu64 " nsecs\n", T1 - T0);
  680. T0 = get_nsecs();
  681. sleep_nsecs(NSEC_PER_MSEC);
  682. T1 = get_nsecs();
  683. printf("the sleep test took %" PRIu64 " nsecs\n", T1 - T0);
  684. }
  685. static int
  686. replay_wakeup_event(struct perf_sched *sched,
  687. struct evsel *evsel, struct perf_sample *sample,
  688. struct machine *machine __maybe_unused)
  689. {
  690. const char *comm = evsel__strval(evsel, sample, "comm");
  691. const u32 pid = evsel__intval(evsel, sample, "pid");
  692. struct task_desc *waker, *wakee;
  693. if (verbose > 0) {
  694. printf("sched_wakeup event %p\n", evsel);
  695. printf(" ... pid %d woke up %s/%d\n", sample->tid, comm, pid);
  696. }
  697. waker = register_pid(sched, sample->tid, "<unknown>");
  698. wakee = register_pid(sched, pid, comm);
  699. add_sched_event_wakeup(sched, waker, sample->time, wakee);
  700. return 0;
  701. }
  702. static int replay_switch_event(struct perf_sched *sched,
  703. struct evsel *evsel,
  704. struct perf_sample *sample,
  705. struct machine *machine __maybe_unused)
  706. {
  707. const char *prev_comm = evsel__strval(evsel, sample, "prev_comm"),
  708. *next_comm = evsel__strval(evsel, sample, "next_comm");
  709. const u32 prev_pid = evsel__intval(evsel, sample, "prev_pid"),
  710. next_pid = evsel__intval(evsel, sample, "next_pid");
  711. const char prev_state = evsel__taskstate(evsel, sample, "prev_state");
  712. struct task_desc *prev, __maybe_unused *next;
  713. u64 timestamp0, timestamp = sample->time;
  714. int cpu = sample->cpu;
  715. s64 delta;
  716. if (verbose > 0)
  717. printf("sched_switch event %p\n", evsel);
  718. if (cpu >= MAX_CPUS || cpu < 0)
  719. return 0;
  720. timestamp0 = sched->cpu_last_switched[cpu];
  721. if (timestamp0)
  722. delta = timestamp - timestamp0;
  723. else
  724. delta = 0;
  725. if (delta < 0) {
  726. pr_err("hm, delta: %" PRIu64 " < 0 ?\n", delta);
  727. return -1;
  728. }
  729. pr_debug(" ... switch from %s/%d to %s/%d [ran %" PRIu64 " nsecs]\n",
  730. prev_comm, prev_pid, next_comm, next_pid, delta);
  731. prev = register_pid(sched, prev_pid, prev_comm);
  732. next = register_pid(sched, next_pid, next_comm);
  733. sched->cpu_last_switched[cpu] = timestamp;
  734. add_sched_event_run(sched, prev, timestamp, delta);
  735. add_sched_event_sleep(sched, prev, timestamp, prev_state);
  736. return 0;
  737. }
  738. static int replay_fork_event(struct perf_sched *sched,
  739. union perf_event *event,
  740. struct machine *machine)
  741. {
  742. struct thread *child, *parent;
  743. child = machine__findnew_thread(machine, event->fork.pid,
  744. event->fork.tid);
  745. parent = machine__findnew_thread(machine, event->fork.ppid,
  746. event->fork.ptid);
  747. if (child == NULL || parent == NULL) {
  748. pr_debug("thread does not exist on fork event: child %p, parent %p\n",
  749. child, parent);
  750. goto out_put;
  751. }
  752. if (verbose > 0) {
  753. printf("fork event\n");
  754. printf("... parent: %s/%d\n", thread__comm_str(parent), thread__tid(parent));
  755. printf("... child: %s/%d\n", thread__comm_str(child), thread__tid(child));
  756. }
  757. register_pid(sched, thread__tid(parent), thread__comm_str(parent));
  758. register_pid(sched, thread__tid(child), thread__comm_str(child));
  759. out_put:
  760. thread__put(child);
  761. thread__put(parent);
  762. return 0;
  763. }
  764. struct sort_dimension {
  765. const char *name;
  766. sort_fn_t cmp;
  767. struct list_head list;
  768. };
  769. static inline void init_prio(struct thread_runtime *r)
  770. {
  771. r->prio = -1;
  772. }
  773. /*
  774. * handle runtime stats saved per thread
  775. */
  776. static struct thread_runtime *thread__init_runtime(struct thread *thread)
  777. {
  778. struct thread_runtime *r;
  779. r = zalloc(sizeof(struct thread_runtime));
  780. if (!r)
  781. return NULL;
  782. init_stats(&r->run_stats);
  783. init_prio(r);
  784. thread__set_priv(thread, r);
  785. return r;
  786. }
  787. static struct thread_runtime *thread__get_runtime(struct thread *thread)
  788. {
  789. struct thread_runtime *tr;
  790. tr = thread__priv(thread);
  791. if (tr == NULL) {
  792. tr = thread__init_runtime(thread);
  793. if (tr == NULL)
  794. pr_debug("Failed to malloc memory for runtime data.\n");
  795. }
  796. return tr;
  797. }
  798. static int
  799. thread_lat_cmp(struct list_head *list, struct work_atoms *l, struct work_atoms *r)
  800. {
  801. struct sort_dimension *sort;
  802. int ret = 0;
  803. BUG_ON(list_empty(list));
  804. list_for_each_entry(sort, list, list) {
  805. ret = sort->cmp(l, r);
  806. if (ret)
  807. return ret;
  808. }
  809. return ret;
  810. }
  811. static struct work_atoms *
  812. thread_atoms_search(struct rb_root_cached *root, struct thread *thread,
  813. struct list_head *sort_list)
  814. {
  815. struct rb_node *node = root->rb_root.rb_node;
  816. struct work_atoms key = { .thread = thread };
  817. while (node) {
  818. struct work_atoms *atoms;
  819. int cmp;
  820. atoms = container_of(node, struct work_atoms, node);
  821. cmp = thread_lat_cmp(sort_list, &key, atoms);
  822. if (cmp > 0)
  823. node = node->rb_left;
  824. else if (cmp < 0)
  825. node = node->rb_right;
  826. else {
  827. BUG_ON(!RC_CHK_EQUAL(thread, atoms->thread));
  828. return atoms;
  829. }
  830. }
  831. return NULL;
  832. }
  833. static void
  834. __thread_latency_insert(struct rb_root_cached *root, struct work_atoms *data,
  835. struct list_head *sort_list)
  836. {
  837. struct rb_node **new = &(root->rb_root.rb_node), *parent = NULL;
  838. bool leftmost = true;
  839. while (*new) {
  840. struct work_atoms *this;
  841. int cmp;
  842. this = container_of(*new, struct work_atoms, node);
  843. parent = *new;
  844. cmp = thread_lat_cmp(sort_list, data, this);
  845. if (cmp > 0)
  846. new = &((*new)->rb_left);
  847. else {
  848. new = &((*new)->rb_right);
  849. leftmost = false;
  850. }
  851. }
  852. rb_link_node(&data->node, parent, new);
  853. rb_insert_color_cached(&data->node, root, leftmost);
  854. }
  855. static int thread_atoms_insert(struct perf_sched *sched, struct thread *thread)
  856. {
  857. struct work_atoms *atoms = zalloc(sizeof(*atoms));
  858. if (!atoms) {
  859. pr_err("No memory at %s\n", __func__);
  860. return -1;
  861. }
  862. atoms->thread = thread__get(thread);
  863. INIT_LIST_HEAD(&atoms->work_list);
  864. __thread_latency_insert(&sched->atom_root, atoms, &sched->cmp_pid);
  865. return 0;
  866. }
  867. static int
  868. add_sched_out_event(struct work_atoms *atoms,
  869. char run_state,
  870. u64 timestamp)
  871. {
  872. struct work_atom *atom = zalloc(sizeof(*atom));
  873. if (!atom) {
  874. pr_err("Non memory at %s", __func__);
  875. return -1;
  876. }
  877. atom->sched_out_time = timestamp;
  878. if (run_state == 'R') {
  879. atom->state = THREAD_WAIT_CPU;
  880. atom->wake_up_time = atom->sched_out_time;
  881. }
  882. list_add_tail(&atom->list, &atoms->work_list);
  883. return 0;
  884. }
  885. static void
  886. add_runtime_event(struct work_atoms *atoms, u64 delta,
  887. u64 timestamp __maybe_unused)
  888. {
  889. struct work_atom *atom;
  890. BUG_ON(list_empty(&atoms->work_list));
  891. atom = list_entry(atoms->work_list.prev, struct work_atom, list);
  892. atom->runtime += delta;
  893. atoms->total_runtime += delta;
  894. }
  895. static void
  896. add_sched_in_event(struct work_atoms *atoms, u64 timestamp)
  897. {
  898. struct work_atom *atom;
  899. u64 delta;
  900. if (list_empty(&atoms->work_list))
  901. return;
  902. atom = list_entry(atoms->work_list.prev, struct work_atom, list);
  903. if (atom->state != THREAD_WAIT_CPU)
  904. return;
  905. if (timestamp < atom->wake_up_time) {
  906. atom->state = THREAD_IGNORE;
  907. return;
  908. }
  909. atom->state = THREAD_SCHED_IN;
  910. atom->sched_in_time = timestamp;
  911. delta = atom->sched_in_time - atom->wake_up_time;
  912. atoms->total_lat += delta;
  913. if (delta > atoms->max_lat) {
  914. atoms->max_lat = delta;
  915. atoms->max_lat_start = atom->wake_up_time;
  916. atoms->max_lat_end = timestamp;
  917. }
  918. atoms->nb_atoms++;
  919. }
  920. static void free_work_atoms(struct work_atoms *atoms)
  921. {
  922. struct work_atom *atom, *tmp;
  923. if (atoms == NULL)
  924. return;
  925. list_for_each_entry_safe(atom, tmp, &atoms->work_list, list) {
  926. list_del(&atom->list);
  927. free(atom);
  928. }
  929. thread__zput(atoms->thread);
  930. free(atoms);
  931. }
  932. static int latency_switch_event(struct perf_sched *sched,
  933. struct evsel *evsel,
  934. struct perf_sample *sample,
  935. struct machine *machine)
  936. {
  937. const u32 prev_pid = evsel__intval(evsel, sample, "prev_pid"),
  938. next_pid = evsel__intval(evsel, sample, "next_pid");
  939. const char prev_state = evsel__taskstate(evsel, sample, "prev_state");
  940. struct work_atoms *out_events, *in_events;
  941. struct thread *sched_out, *sched_in;
  942. u64 timestamp0, timestamp = sample->time;
  943. int cpu = sample->cpu, err = -1;
  944. s64 delta;
  945. BUG_ON(cpu >= MAX_CPUS || cpu < 0);
  946. timestamp0 = sched->cpu_last_switched[cpu];
  947. sched->cpu_last_switched[cpu] = timestamp;
  948. if (timestamp0)
  949. delta = timestamp - timestamp0;
  950. else
  951. delta = 0;
  952. if (delta < 0) {
  953. pr_err("hm, delta: %" PRIu64 " < 0 ?\n", delta);
  954. return -1;
  955. }
  956. sched_out = machine__findnew_thread(machine, -1, prev_pid);
  957. sched_in = machine__findnew_thread(machine, -1, next_pid);
  958. if (sched_out == NULL || sched_in == NULL)
  959. goto out_put;
  960. out_events = thread_atoms_search(&sched->atom_root, sched_out, &sched->cmp_pid);
  961. if (!out_events) {
  962. if (thread_atoms_insert(sched, sched_out))
  963. goto out_put;
  964. out_events = thread_atoms_search(&sched->atom_root, sched_out, &sched->cmp_pid);
  965. if (!out_events) {
  966. pr_err("out-event: Internal tree error");
  967. goto out_put;
  968. }
  969. }
  970. if (add_sched_out_event(out_events, prev_state, timestamp))
  971. return -1;
  972. in_events = thread_atoms_search(&sched->atom_root, sched_in, &sched->cmp_pid);
  973. if (!in_events) {
  974. if (thread_atoms_insert(sched, sched_in))
  975. goto out_put;
  976. in_events = thread_atoms_search(&sched->atom_root, sched_in, &sched->cmp_pid);
  977. if (!in_events) {
  978. pr_err("in-event: Internal tree error");
  979. goto out_put;
  980. }
  981. /*
  982. * Take came in we have not heard about yet,
  983. * add in an initial atom in runnable state:
  984. */
  985. if (add_sched_out_event(in_events, 'R', timestamp))
  986. goto out_put;
  987. }
  988. add_sched_in_event(in_events, timestamp);
  989. err = 0;
  990. out_put:
  991. thread__put(sched_out);
  992. thread__put(sched_in);
  993. return err;
  994. }
  995. static int latency_runtime_event(struct perf_sched *sched,
  996. struct evsel *evsel,
  997. struct perf_sample *sample,
  998. struct machine *machine)
  999. {
  1000. const u32 pid = evsel__intval(evsel, sample, "pid");
  1001. const u64 runtime = evsel__intval(evsel, sample, "runtime");
  1002. struct thread *thread = machine__findnew_thread(machine, -1, pid);
  1003. struct work_atoms *atoms = thread_atoms_search(&sched->atom_root, thread, &sched->cmp_pid);
  1004. u64 timestamp = sample->time;
  1005. int cpu = sample->cpu, err = -1;
  1006. if (thread == NULL)
  1007. return -1;
  1008. BUG_ON(cpu >= MAX_CPUS || cpu < 0);
  1009. if (!atoms) {
  1010. if (thread_atoms_insert(sched, thread))
  1011. goto out_put;
  1012. atoms = thread_atoms_search(&sched->atom_root, thread, &sched->cmp_pid);
  1013. if (!atoms) {
  1014. pr_err("in-event: Internal tree error");
  1015. goto out_put;
  1016. }
  1017. if (add_sched_out_event(atoms, 'R', timestamp))
  1018. goto out_put;
  1019. }
  1020. add_runtime_event(atoms, runtime, timestamp);
  1021. err = 0;
  1022. out_put:
  1023. thread__put(thread);
  1024. return err;
  1025. }
  1026. static int latency_wakeup_event(struct perf_sched *sched,
  1027. struct evsel *evsel,
  1028. struct perf_sample *sample,
  1029. struct machine *machine)
  1030. {
  1031. const u32 pid = evsel__intval(evsel, sample, "pid");
  1032. struct work_atoms *atoms;
  1033. struct work_atom *atom;
  1034. struct thread *wakee;
  1035. u64 timestamp = sample->time;
  1036. int err = -1;
  1037. wakee = machine__findnew_thread(machine, -1, pid);
  1038. if (wakee == NULL)
  1039. return -1;
  1040. atoms = thread_atoms_search(&sched->atom_root, wakee, &sched->cmp_pid);
  1041. if (!atoms) {
  1042. if (thread_atoms_insert(sched, wakee))
  1043. goto out_put;
  1044. atoms = thread_atoms_search(&sched->atom_root, wakee, &sched->cmp_pid);
  1045. if (!atoms) {
  1046. pr_err("wakeup-event: Internal tree error");
  1047. goto out_put;
  1048. }
  1049. if (add_sched_out_event(atoms, 'S', timestamp))
  1050. goto out_put;
  1051. }
  1052. BUG_ON(list_empty(&atoms->work_list));
  1053. atom = list_entry(atoms->work_list.prev, struct work_atom, list);
  1054. /*
  1055. * As we do not guarantee the wakeup event happens when
  1056. * task is out of run queue, also may happen when task is
  1057. * on run queue and wakeup only change ->state to TASK_RUNNING,
  1058. * then we should not set the ->wake_up_time when wake up a
  1059. * task which is on run queue.
  1060. *
  1061. * You WILL be missing events if you've recorded only
  1062. * one CPU, or are only looking at only one, so don't
  1063. * skip in this case.
  1064. */
  1065. if (sched->profile_cpu == -1 && atom->state != THREAD_SLEEPING)
  1066. goto out_ok;
  1067. sched->nr_timestamps++;
  1068. if (atom->sched_out_time > timestamp) {
  1069. sched->nr_unordered_timestamps++;
  1070. goto out_ok;
  1071. }
  1072. atom->state = THREAD_WAIT_CPU;
  1073. atom->wake_up_time = timestamp;
  1074. out_ok:
  1075. err = 0;
  1076. out_put:
  1077. thread__put(wakee);
  1078. return err;
  1079. }
  1080. static int latency_migrate_task_event(struct perf_sched *sched,
  1081. struct evsel *evsel,
  1082. struct perf_sample *sample,
  1083. struct machine *machine)
  1084. {
  1085. const u32 pid = evsel__intval(evsel, sample, "pid");
  1086. u64 timestamp = sample->time;
  1087. struct work_atoms *atoms;
  1088. struct work_atom *atom;
  1089. struct thread *migrant;
  1090. int err = -1;
  1091. /*
  1092. * Only need to worry about migration when profiling one CPU.
  1093. */
  1094. if (sched->profile_cpu == -1)
  1095. return 0;
  1096. migrant = machine__findnew_thread(machine, -1, pid);
  1097. if (migrant == NULL)
  1098. return -1;
  1099. atoms = thread_atoms_search(&sched->atom_root, migrant, &sched->cmp_pid);
  1100. if (!atoms) {
  1101. if (thread_atoms_insert(sched, migrant))
  1102. goto out_put;
  1103. register_pid(sched, thread__tid(migrant), thread__comm_str(migrant));
  1104. atoms = thread_atoms_search(&sched->atom_root, migrant, &sched->cmp_pid);
  1105. if (!atoms) {
  1106. pr_err("migration-event: Internal tree error");
  1107. goto out_put;
  1108. }
  1109. if (add_sched_out_event(atoms, 'R', timestamp))
  1110. goto out_put;
  1111. }
  1112. BUG_ON(list_empty(&atoms->work_list));
  1113. atom = list_entry(atoms->work_list.prev, struct work_atom, list);
  1114. atom->sched_in_time = atom->sched_out_time = atom->wake_up_time = timestamp;
  1115. sched->nr_timestamps++;
  1116. if (atom->sched_out_time > timestamp)
  1117. sched->nr_unordered_timestamps++;
  1118. err = 0;
  1119. out_put:
  1120. thread__put(migrant);
  1121. return err;
  1122. }
  1123. static void output_lat_thread(struct perf_sched *sched, struct work_atoms *work_list)
  1124. {
  1125. int i;
  1126. int ret;
  1127. u64 avg;
  1128. char max_lat_start[32], max_lat_end[32];
  1129. if (!work_list->nb_atoms)
  1130. return;
  1131. /*
  1132. * Ignore idle threads:
  1133. */
  1134. if (!strcmp(thread__comm_str(work_list->thread), "swapper"))
  1135. return;
  1136. sched->all_runtime += work_list->total_runtime;
  1137. sched->all_count += work_list->nb_atoms;
  1138. if (work_list->num_merged > 1) {
  1139. ret = printf(" %s:(%d) ", thread__comm_str(work_list->thread),
  1140. work_list->num_merged);
  1141. } else {
  1142. ret = printf(" %s:%d ", thread__comm_str(work_list->thread),
  1143. thread__tid(work_list->thread));
  1144. }
  1145. for (i = 0; i < 24 - ret; i++)
  1146. printf(" ");
  1147. avg = work_list->total_lat / work_list->nb_atoms;
  1148. timestamp__scnprintf_usec(work_list->max_lat_start, max_lat_start, sizeof(max_lat_start));
  1149. timestamp__scnprintf_usec(work_list->max_lat_end, max_lat_end, sizeof(max_lat_end));
  1150. printf("|%11.3f ms |%9" PRIu64 " | avg:%8.3f ms | max:%8.3f ms | max start: %12s s | max end: %12s s\n",
  1151. (double)work_list->total_runtime / NSEC_PER_MSEC,
  1152. work_list->nb_atoms, (double)avg / NSEC_PER_MSEC,
  1153. (double)work_list->max_lat / NSEC_PER_MSEC,
  1154. max_lat_start, max_lat_end);
  1155. }
  1156. static int pid_cmp(struct work_atoms *l, struct work_atoms *r)
  1157. {
  1158. pid_t l_tid, r_tid;
  1159. if (RC_CHK_EQUAL(l->thread, r->thread))
  1160. return 0;
  1161. l_tid = thread__tid(l->thread);
  1162. r_tid = thread__tid(r->thread);
  1163. if (l_tid < r_tid)
  1164. return -1;
  1165. if (l_tid > r_tid)
  1166. return 1;
  1167. return (int)(RC_CHK_ACCESS(l->thread) - RC_CHK_ACCESS(r->thread));
  1168. }
  1169. static int avg_cmp(struct work_atoms *l, struct work_atoms *r)
  1170. {
  1171. u64 avgl, avgr;
  1172. if (!l->nb_atoms)
  1173. return -1;
  1174. if (!r->nb_atoms)
  1175. return 1;
  1176. avgl = l->total_lat / l->nb_atoms;
  1177. avgr = r->total_lat / r->nb_atoms;
  1178. if (avgl < avgr)
  1179. return -1;
  1180. if (avgl > avgr)
  1181. return 1;
  1182. return 0;
  1183. }
  1184. static int max_cmp(struct work_atoms *l, struct work_atoms *r)
  1185. {
  1186. if (l->max_lat < r->max_lat)
  1187. return -1;
  1188. if (l->max_lat > r->max_lat)
  1189. return 1;
  1190. return 0;
  1191. }
  1192. static int switch_cmp(struct work_atoms *l, struct work_atoms *r)
  1193. {
  1194. if (l->nb_atoms < r->nb_atoms)
  1195. return -1;
  1196. if (l->nb_atoms > r->nb_atoms)
  1197. return 1;
  1198. return 0;
  1199. }
  1200. static int runtime_cmp(struct work_atoms *l, struct work_atoms *r)
  1201. {
  1202. if (l->total_runtime < r->total_runtime)
  1203. return -1;
  1204. if (l->total_runtime > r->total_runtime)
  1205. return 1;
  1206. return 0;
  1207. }
  1208. static int sort_dimension__add(const char *tok, struct list_head *list)
  1209. {
  1210. size_t i;
  1211. static struct sort_dimension avg_sort_dimension = {
  1212. .name = "avg",
  1213. .cmp = avg_cmp,
  1214. };
  1215. static struct sort_dimension max_sort_dimension = {
  1216. .name = "max",
  1217. .cmp = max_cmp,
  1218. };
  1219. static struct sort_dimension pid_sort_dimension = {
  1220. .name = "pid",
  1221. .cmp = pid_cmp,
  1222. };
  1223. static struct sort_dimension runtime_sort_dimension = {
  1224. .name = "runtime",
  1225. .cmp = runtime_cmp,
  1226. };
  1227. static struct sort_dimension switch_sort_dimension = {
  1228. .name = "switch",
  1229. .cmp = switch_cmp,
  1230. };
  1231. struct sort_dimension *available_sorts[] = {
  1232. &pid_sort_dimension,
  1233. &avg_sort_dimension,
  1234. &max_sort_dimension,
  1235. &switch_sort_dimension,
  1236. &runtime_sort_dimension,
  1237. };
  1238. for (i = 0; i < ARRAY_SIZE(available_sorts); i++) {
  1239. if (!strcmp(available_sorts[i]->name, tok)) {
  1240. list_add_tail(&available_sorts[i]->list, list);
  1241. return 0;
  1242. }
  1243. }
  1244. return -1;
  1245. }
  1246. static void perf_sched__sort_lat(struct perf_sched *sched)
  1247. {
  1248. struct rb_node *node;
  1249. struct rb_root_cached *root = &sched->atom_root;
  1250. again:
  1251. for (;;) {
  1252. struct work_atoms *data;
  1253. node = rb_first_cached(root);
  1254. if (!node)
  1255. break;
  1256. rb_erase_cached(node, root);
  1257. data = rb_entry(node, struct work_atoms, node);
  1258. __thread_latency_insert(&sched->sorted_atom_root, data, &sched->sort_list);
  1259. }
  1260. if (root == &sched->atom_root) {
  1261. root = &sched->merged_atom_root;
  1262. goto again;
  1263. }
  1264. }
  1265. static int process_sched_wakeup_event(const struct perf_tool *tool,
  1266. struct evsel *evsel,
  1267. struct perf_sample *sample,
  1268. struct machine *machine)
  1269. {
  1270. struct perf_sched *sched = container_of(tool, struct perf_sched, tool);
  1271. if (sched->tp_handler->wakeup_event)
  1272. return sched->tp_handler->wakeup_event(sched, evsel, sample, machine);
  1273. return 0;
  1274. }
  1275. static int process_sched_wakeup_ignore(const struct perf_tool *tool __maybe_unused,
  1276. struct evsel *evsel __maybe_unused,
  1277. struct perf_sample *sample __maybe_unused,
  1278. struct machine *machine __maybe_unused)
  1279. {
  1280. return 0;
  1281. }
  1282. union map_priv {
  1283. void *ptr;
  1284. bool color;
  1285. };
  1286. static bool thread__has_color(struct thread *thread)
  1287. {
  1288. union map_priv priv = {
  1289. .ptr = thread__priv(thread),
  1290. };
  1291. return priv.color;
  1292. }
  1293. static struct thread*
  1294. map__findnew_thread(struct perf_sched *sched, struct machine *machine, pid_t pid, pid_t tid)
  1295. {
  1296. struct thread *thread = machine__findnew_thread(machine, pid, tid);
  1297. union map_priv priv = {
  1298. .color = false,
  1299. };
  1300. if (!sched->map.color_pids || !thread || thread__priv(thread))
  1301. return thread;
  1302. if (thread_map__has(sched->map.color_pids, tid))
  1303. priv.color = true;
  1304. thread__set_priv(thread, priv.ptr);
  1305. return thread;
  1306. }
  1307. static bool sched_match_task(struct perf_sched *sched, const char *comm_str)
  1308. {
  1309. bool fuzzy_match = sched->map.fuzzy;
  1310. struct strlist *task_names = sched->map.task_names;
  1311. struct str_node *node;
  1312. strlist__for_each_entry(node, task_names) {
  1313. bool match_found = fuzzy_match ? !!strstr(comm_str, node->s) :
  1314. !strcmp(comm_str, node->s);
  1315. if (match_found)
  1316. return true;
  1317. }
  1318. return false;
  1319. }
  1320. static void print_sched_map(struct perf_sched *sched, struct perf_cpu this_cpu, int cpus_nr,
  1321. const char *color, bool sched_out)
  1322. {
  1323. for (int i = 0; i < cpus_nr; i++) {
  1324. struct perf_cpu cpu = {
  1325. .cpu = sched->map.comp ? sched->map.comp_cpus[i].cpu : i,
  1326. };
  1327. struct thread *curr_thread = sched->curr_thread[cpu.cpu];
  1328. struct thread *curr_out_thread = sched->curr_out_thread[cpu.cpu];
  1329. struct thread_runtime *curr_tr;
  1330. const char *pid_color = color;
  1331. const char *cpu_color = color;
  1332. char symbol = ' ';
  1333. struct thread *thread_to_check = sched_out ? curr_out_thread : curr_thread;
  1334. if (thread_to_check && thread__has_color(thread_to_check))
  1335. pid_color = COLOR_PIDS;
  1336. if (sched->map.color_cpus && perf_cpu_map__has(sched->map.color_cpus, cpu))
  1337. cpu_color = COLOR_CPUS;
  1338. if (cpu.cpu == this_cpu.cpu)
  1339. symbol = '*';
  1340. color_fprintf(stdout, cpu.cpu != this_cpu.cpu ? color : cpu_color, "%c", symbol);
  1341. thread_to_check = sched_out ? sched->curr_out_thread[cpu.cpu] :
  1342. sched->curr_thread[cpu.cpu];
  1343. if (thread_to_check) {
  1344. curr_tr = thread__get_runtime(thread_to_check);
  1345. if (curr_tr == NULL)
  1346. return;
  1347. if (sched_out) {
  1348. if (cpu.cpu == this_cpu.cpu)
  1349. color_fprintf(stdout, color, "- ");
  1350. else {
  1351. curr_tr = thread__get_runtime(sched->curr_thread[cpu.cpu]);
  1352. if (curr_tr != NULL)
  1353. color_fprintf(stdout, pid_color, "%2s ",
  1354. curr_tr->shortname);
  1355. }
  1356. } else
  1357. color_fprintf(stdout, pid_color, "%2s ", curr_tr->shortname);
  1358. } else
  1359. color_fprintf(stdout, color, " ");
  1360. }
  1361. }
  1362. static int map_switch_event(struct perf_sched *sched, struct evsel *evsel,
  1363. struct perf_sample *sample, struct machine *machine)
  1364. {
  1365. const u32 next_pid = evsel__intval(evsel, sample, "next_pid");
  1366. const u32 prev_pid = evsel__intval(evsel, sample, "prev_pid");
  1367. struct thread *sched_in, *sched_out;
  1368. struct thread_runtime *tr;
  1369. int new_shortname;
  1370. u64 timestamp0, timestamp = sample->time;
  1371. s64 delta;
  1372. struct perf_cpu this_cpu = {
  1373. .cpu = sample->cpu,
  1374. };
  1375. int cpus_nr;
  1376. int proceed;
  1377. bool new_cpu = false;
  1378. const char *color = PERF_COLOR_NORMAL;
  1379. char stimestamp[32];
  1380. const char *str;
  1381. int ret = -1;
  1382. BUG_ON(this_cpu.cpu >= MAX_CPUS || this_cpu.cpu < 0);
  1383. if (this_cpu.cpu > sched->max_cpu.cpu)
  1384. sched->max_cpu = this_cpu;
  1385. if (sched->map.comp) {
  1386. cpus_nr = bitmap_weight(sched->map.comp_cpus_mask, MAX_CPUS);
  1387. if (!__test_and_set_bit(this_cpu.cpu, sched->map.comp_cpus_mask)) {
  1388. sched->map.comp_cpus[cpus_nr++] = this_cpu;
  1389. new_cpu = true;
  1390. }
  1391. } else
  1392. cpus_nr = sched->max_cpu.cpu;
  1393. timestamp0 = sched->cpu_last_switched[this_cpu.cpu];
  1394. sched->cpu_last_switched[this_cpu.cpu] = timestamp;
  1395. if (timestamp0)
  1396. delta = timestamp - timestamp0;
  1397. else
  1398. delta = 0;
  1399. if (delta < 0) {
  1400. pr_err("hm, delta: %" PRIu64 " < 0 ?\n", delta);
  1401. return -1;
  1402. }
  1403. sched_in = map__findnew_thread(sched, machine, -1, next_pid);
  1404. sched_out = map__findnew_thread(sched, machine, -1, prev_pid);
  1405. if (sched_in == NULL || sched_out == NULL)
  1406. goto out;
  1407. tr = thread__get_runtime(sched_in);
  1408. if (tr == NULL)
  1409. goto out;
  1410. thread__put(sched->curr_thread[this_cpu.cpu]);
  1411. thread__put(sched->curr_out_thread[this_cpu.cpu]);
  1412. sched->curr_thread[this_cpu.cpu] = thread__get(sched_in);
  1413. sched->curr_out_thread[this_cpu.cpu] = thread__get(sched_out);
  1414. ret = 0;
  1415. str = thread__comm_str(sched_in);
  1416. new_shortname = 0;
  1417. if (!tr->shortname[0]) {
  1418. if (!strcmp(thread__comm_str(sched_in), "swapper")) {
  1419. /*
  1420. * Don't allocate a letter-number for swapper:0
  1421. * as a shortname. Instead, we use '.' for it.
  1422. */
  1423. tr->shortname[0] = '.';
  1424. tr->shortname[1] = ' ';
  1425. } else if (!sched->map.task_name || sched_match_task(sched, str)) {
  1426. tr->shortname[0] = sched->next_shortname1;
  1427. tr->shortname[1] = sched->next_shortname2;
  1428. if (sched->next_shortname1 < 'Z') {
  1429. sched->next_shortname1++;
  1430. } else {
  1431. sched->next_shortname1 = 'A';
  1432. if (sched->next_shortname2 < '9')
  1433. sched->next_shortname2++;
  1434. else
  1435. sched->next_shortname2 = '0';
  1436. }
  1437. } else {
  1438. tr->shortname[0] = '-';
  1439. tr->shortname[1] = ' ';
  1440. }
  1441. new_shortname = 1;
  1442. }
  1443. if (sched->map.cpus && !perf_cpu_map__has(sched->map.cpus, this_cpu))
  1444. goto out;
  1445. proceed = 0;
  1446. str = thread__comm_str(sched_in);
  1447. /*
  1448. * Check which of sched_in and sched_out matches the passed --task-name
  1449. * arguments and call the corresponding print_sched_map.
  1450. */
  1451. if (sched->map.task_name && !sched_match_task(sched, str)) {
  1452. if (!sched_match_task(sched, thread__comm_str(sched_out)))
  1453. goto out;
  1454. else
  1455. goto sched_out;
  1456. } else {
  1457. str = thread__comm_str(sched_out);
  1458. if (!(sched->map.task_name && !sched_match_task(sched, str)))
  1459. proceed = 1;
  1460. }
  1461. printf(" ");
  1462. print_sched_map(sched, this_cpu, cpus_nr, color, false);
  1463. timestamp__scnprintf_usec(timestamp, stimestamp, sizeof(stimestamp));
  1464. color_fprintf(stdout, color, " %12s secs ", stimestamp);
  1465. if (new_shortname || tr->comm_changed || (verbose > 0 && thread__tid(sched_in))) {
  1466. const char *pid_color = color;
  1467. if (thread__has_color(sched_in))
  1468. pid_color = COLOR_PIDS;
  1469. color_fprintf(stdout, pid_color, "%s => %s:%d",
  1470. tr->shortname, thread__comm_str(sched_in), thread__tid(sched_in));
  1471. tr->comm_changed = false;
  1472. }
  1473. if (sched->map.comp && new_cpu)
  1474. color_fprintf(stdout, color, " (CPU %d)", this_cpu);
  1475. if (proceed != 1) {
  1476. color_fprintf(stdout, color, "\n");
  1477. goto out;
  1478. }
  1479. sched_out:
  1480. if (sched->map.task_name) {
  1481. tr = thread__get_runtime(sched->curr_out_thread[this_cpu.cpu]);
  1482. if (strcmp(tr->shortname, "") == 0)
  1483. goto out;
  1484. if (proceed == 1)
  1485. color_fprintf(stdout, color, "\n");
  1486. printf(" ");
  1487. print_sched_map(sched, this_cpu, cpus_nr, color, true);
  1488. timestamp__scnprintf_usec(timestamp, stimestamp, sizeof(stimestamp));
  1489. color_fprintf(stdout, color, " %12s secs ", stimestamp);
  1490. }
  1491. color_fprintf(stdout, color, "\n");
  1492. out:
  1493. thread__put(sched_out);
  1494. thread__put(sched_in);
  1495. return ret;
  1496. }
  1497. static int process_sched_switch_event(const struct perf_tool *tool,
  1498. struct evsel *evsel,
  1499. struct perf_sample *sample,
  1500. struct machine *machine)
  1501. {
  1502. struct perf_sched *sched = container_of(tool, struct perf_sched, tool);
  1503. int this_cpu = sample->cpu, err = 0;
  1504. u32 prev_pid = evsel__intval(evsel, sample, "prev_pid"),
  1505. next_pid = evsel__intval(evsel, sample, "next_pid");
  1506. if (sched->curr_pid[this_cpu] != (u32)-1) {
  1507. /*
  1508. * Are we trying to switch away a PID that is
  1509. * not current?
  1510. */
  1511. if (sched->curr_pid[this_cpu] != prev_pid)
  1512. sched->nr_context_switch_bugs++;
  1513. }
  1514. if (sched->tp_handler->switch_event)
  1515. err = sched->tp_handler->switch_event(sched, evsel, sample, machine);
  1516. sched->curr_pid[this_cpu] = next_pid;
  1517. return err;
  1518. }
  1519. static int process_sched_runtime_event(const struct perf_tool *tool,
  1520. struct evsel *evsel,
  1521. struct perf_sample *sample,
  1522. struct machine *machine)
  1523. {
  1524. struct perf_sched *sched = container_of(tool, struct perf_sched, tool);
  1525. if (sched->tp_handler->runtime_event)
  1526. return sched->tp_handler->runtime_event(sched, evsel, sample, machine);
  1527. return 0;
  1528. }
  1529. static int perf_sched__process_fork_event(const struct perf_tool *tool,
  1530. union perf_event *event,
  1531. struct perf_sample *sample,
  1532. struct machine *machine)
  1533. {
  1534. struct perf_sched *sched = container_of(tool, struct perf_sched, tool);
  1535. /* run the fork event through the perf machinery */
  1536. perf_event__process_fork(tool, event, sample, machine);
  1537. /* and then run additional processing needed for this command */
  1538. if (sched->tp_handler->fork_event)
  1539. return sched->tp_handler->fork_event(sched, event, machine);
  1540. return 0;
  1541. }
  1542. static int process_sched_migrate_task_event(const struct perf_tool *tool,
  1543. struct evsel *evsel,
  1544. struct perf_sample *sample,
  1545. struct machine *machine)
  1546. {
  1547. struct perf_sched *sched = container_of(tool, struct perf_sched, tool);
  1548. if (sched->tp_handler->migrate_task_event)
  1549. return sched->tp_handler->migrate_task_event(sched, evsel, sample, machine);
  1550. return 0;
  1551. }
  1552. typedef int (*tracepoint_handler)(const struct perf_tool *tool,
  1553. struct evsel *evsel,
  1554. struct perf_sample *sample,
  1555. struct machine *machine);
  1556. static int perf_sched__process_tracepoint_sample(const struct perf_tool *tool __maybe_unused,
  1557. union perf_event *event __maybe_unused,
  1558. struct perf_sample *sample,
  1559. struct evsel *evsel,
  1560. struct machine *machine)
  1561. {
  1562. int err = 0;
  1563. if (evsel->handler != NULL) {
  1564. tracepoint_handler f = evsel->handler;
  1565. err = f(tool, evsel, sample, machine);
  1566. }
  1567. return err;
  1568. }
  1569. static int perf_sched__process_comm(const struct perf_tool *tool __maybe_unused,
  1570. union perf_event *event,
  1571. struct perf_sample *sample,
  1572. struct machine *machine)
  1573. {
  1574. struct thread *thread;
  1575. struct thread_runtime *tr;
  1576. int err;
  1577. err = perf_event__process_comm(tool, event, sample, machine);
  1578. if (err)
  1579. return err;
  1580. thread = machine__find_thread(machine, sample->pid, sample->tid);
  1581. if (!thread) {
  1582. pr_err("Internal error: can't find thread\n");
  1583. return -1;
  1584. }
  1585. tr = thread__get_runtime(thread);
  1586. if (tr == NULL) {
  1587. thread__put(thread);
  1588. return -1;
  1589. }
  1590. tr->comm_changed = true;
  1591. thread__put(thread);
  1592. return 0;
  1593. }
  1594. static int perf_sched__read_events(struct perf_sched *sched)
  1595. {
  1596. struct evsel_str_handler handlers[] = {
  1597. { "sched:sched_switch", process_sched_switch_event, },
  1598. { "sched:sched_stat_runtime", process_sched_runtime_event, },
  1599. { "sched:sched_wakeup", process_sched_wakeup_event, },
  1600. { "sched:sched_waking", process_sched_wakeup_event, },
  1601. { "sched:sched_wakeup_new", process_sched_wakeup_event, },
  1602. { "sched:sched_migrate_task", process_sched_migrate_task_event, },
  1603. };
  1604. struct perf_session *session;
  1605. struct perf_data data = {
  1606. .path = input_name,
  1607. .mode = PERF_DATA_MODE_READ,
  1608. .force = sched->force,
  1609. };
  1610. int rc = -1;
  1611. session = perf_session__new(&data, &sched->tool);
  1612. if (IS_ERR(session)) {
  1613. pr_debug("Error creating perf session");
  1614. return PTR_ERR(session);
  1615. }
  1616. symbol__init(&session->header.env);
  1617. /* prefer sched_waking if it is captured */
  1618. if (evlist__find_tracepoint_by_name(session->evlist, "sched:sched_waking"))
  1619. handlers[2].handler = process_sched_wakeup_ignore;
  1620. if (perf_session__set_tracepoints_handlers(session, handlers))
  1621. goto out_delete;
  1622. if (perf_session__has_traces(session, "record -R")) {
  1623. int err = perf_session__process_events(session);
  1624. if (err) {
  1625. pr_err("Failed to process events, error %d", err);
  1626. goto out_delete;
  1627. }
  1628. sched->nr_events = session->evlist->stats.nr_events[0];
  1629. sched->nr_lost_events = session->evlist->stats.total_lost;
  1630. sched->nr_lost_chunks = session->evlist->stats.nr_events[PERF_RECORD_LOST];
  1631. }
  1632. rc = 0;
  1633. out_delete:
  1634. perf_session__delete(session);
  1635. return rc;
  1636. }
  1637. /*
  1638. * scheduling times are printed as msec.usec
  1639. */
  1640. static inline void print_sched_time(unsigned long long nsecs, int width)
  1641. {
  1642. unsigned long msecs;
  1643. unsigned long usecs;
  1644. msecs = nsecs / NSEC_PER_MSEC;
  1645. nsecs -= msecs * NSEC_PER_MSEC;
  1646. usecs = nsecs / NSEC_PER_USEC;
  1647. printf("%*lu.%03lu ", width, msecs, usecs);
  1648. }
  1649. /*
  1650. * returns runtime data for event, allocating memory for it the
  1651. * first time it is used.
  1652. */
  1653. static struct evsel_runtime *evsel__get_runtime(struct evsel *evsel)
  1654. {
  1655. struct evsel_runtime *r = evsel->priv;
  1656. if (r == NULL) {
  1657. r = zalloc(sizeof(struct evsel_runtime));
  1658. evsel->priv = r;
  1659. }
  1660. return r;
  1661. }
  1662. /*
  1663. * save last time event was seen per cpu
  1664. */
  1665. static void evsel__save_time(struct evsel *evsel, u64 timestamp, u32 cpu)
  1666. {
  1667. struct evsel_runtime *r = evsel__get_runtime(evsel);
  1668. if (r == NULL)
  1669. return;
  1670. if ((cpu >= r->ncpu) || (r->last_time == NULL)) {
  1671. int i, n = __roundup_pow_of_two(cpu+1);
  1672. void *p = r->last_time;
  1673. p = realloc(r->last_time, n * sizeof(u64));
  1674. if (!p)
  1675. return;
  1676. r->last_time = p;
  1677. for (i = r->ncpu; i < n; ++i)
  1678. r->last_time[i] = (u64) 0;
  1679. r->ncpu = n;
  1680. }
  1681. r->last_time[cpu] = timestamp;
  1682. }
  1683. /* returns last time this event was seen on the given cpu */
  1684. static u64 evsel__get_time(struct evsel *evsel, u32 cpu)
  1685. {
  1686. struct evsel_runtime *r = evsel__get_runtime(evsel);
  1687. if ((r == NULL) || (r->last_time == NULL) || (cpu >= r->ncpu))
  1688. return 0;
  1689. return r->last_time[cpu];
  1690. }
  1691. static void timehist__evsel_priv_destructor(void *priv)
  1692. {
  1693. struct evsel_runtime *r = priv;
  1694. if (r) {
  1695. free(r->last_time);
  1696. free(r);
  1697. }
  1698. }
  1699. static int comm_width = 30;
  1700. static char *timehist_get_commstr(struct thread *thread)
  1701. {
  1702. static char str[32];
  1703. const char *comm = thread__comm_str(thread);
  1704. pid_t tid = thread__tid(thread);
  1705. pid_t pid = thread__pid(thread);
  1706. int n;
  1707. if (pid == 0)
  1708. n = scnprintf(str, sizeof(str), "%s", comm);
  1709. else if (tid != pid)
  1710. n = scnprintf(str, sizeof(str), "%s[%d/%d]", comm, tid, pid);
  1711. else
  1712. n = scnprintf(str, sizeof(str), "%s[%d]", comm, tid);
  1713. if (n > comm_width)
  1714. comm_width = n;
  1715. return str;
  1716. }
  1717. /* prio field format: xxx or xxx->yyy */
  1718. #define MAX_PRIO_STR_LEN 8
  1719. static char *timehist_get_priostr(struct evsel *evsel,
  1720. struct thread *thread,
  1721. struct perf_sample *sample)
  1722. {
  1723. static char prio_str[16];
  1724. int prev_prio = (int)evsel__intval(evsel, sample, "prev_prio");
  1725. struct thread_runtime *tr = thread__priv(thread);
  1726. if (tr->prio != prev_prio && tr->prio != -1)
  1727. scnprintf(prio_str, sizeof(prio_str), "%d->%d", tr->prio, prev_prio);
  1728. else
  1729. scnprintf(prio_str, sizeof(prio_str), "%d", prev_prio);
  1730. return prio_str;
  1731. }
  1732. static void timehist_header(struct perf_sched *sched)
  1733. {
  1734. u32 ncpus = sched->max_cpu.cpu + 1;
  1735. u32 i, j;
  1736. printf("%15s %6s ", "time", "cpu");
  1737. if (sched->show_cpu_visual) {
  1738. printf(" ");
  1739. for (i = 0, j = 0; i < ncpus; ++i) {
  1740. printf("%x", j++);
  1741. if (j > 15)
  1742. j = 0;
  1743. }
  1744. printf(" ");
  1745. }
  1746. if (sched->show_prio) {
  1747. printf(" %-*s %-*s %9s %9s %9s",
  1748. comm_width, "task name", MAX_PRIO_STR_LEN, "prio",
  1749. "wait time", "sch delay", "run time");
  1750. } else {
  1751. printf(" %-*s %9s %9s %9s", comm_width,
  1752. "task name", "wait time", "sch delay", "run time");
  1753. }
  1754. if (sched->show_state)
  1755. printf(" %s", "state");
  1756. printf("\n");
  1757. /*
  1758. * units row
  1759. */
  1760. printf("%15s %-6s ", "", "");
  1761. if (sched->show_cpu_visual)
  1762. printf(" %*s ", ncpus, "");
  1763. if (sched->show_prio) {
  1764. printf(" %-*s %-*s %9s %9s %9s",
  1765. comm_width, "[tid/pid]", MAX_PRIO_STR_LEN, "",
  1766. "(msec)", "(msec)", "(msec)");
  1767. } else {
  1768. printf(" %-*s %9s %9s %9s", comm_width,
  1769. "[tid/pid]", "(msec)", "(msec)", "(msec)");
  1770. }
  1771. if (sched->show_state)
  1772. printf(" %5s", "");
  1773. printf("\n");
  1774. /*
  1775. * separator
  1776. */
  1777. printf("%.15s %.6s ", graph_dotted_line, graph_dotted_line);
  1778. if (sched->show_cpu_visual)
  1779. printf(" %.*s ", ncpus, graph_dotted_line);
  1780. if (sched->show_prio) {
  1781. printf(" %.*s %.*s %.9s %.9s %.9s",
  1782. comm_width, graph_dotted_line, MAX_PRIO_STR_LEN, graph_dotted_line,
  1783. graph_dotted_line, graph_dotted_line, graph_dotted_line);
  1784. } else {
  1785. printf(" %.*s %.9s %.9s %.9s", comm_width,
  1786. graph_dotted_line, graph_dotted_line, graph_dotted_line,
  1787. graph_dotted_line);
  1788. }
  1789. if (sched->show_state)
  1790. printf(" %.5s", graph_dotted_line);
  1791. printf("\n");
  1792. }
  1793. static void timehist_print_sample(struct perf_sched *sched,
  1794. struct evsel *evsel,
  1795. struct perf_sample *sample,
  1796. struct addr_location *al,
  1797. struct thread *thread,
  1798. u64 t, const char state)
  1799. {
  1800. struct thread_runtime *tr = thread__priv(thread);
  1801. const char *next_comm = evsel__strval(evsel, sample, "next_comm");
  1802. const u32 next_pid = evsel__intval(evsel, sample, "next_pid");
  1803. u32 max_cpus = sched->max_cpu.cpu + 1;
  1804. char tstr[64];
  1805. char nstr[30];
  1806. u64 wait_time;
  1807. if (cpu_list && !test_bit(sample->cpu, cpu_bitmap))
  1808. return;
  1809. timestamp__scnprintf_usec(t, tstr, sizeof(tstr));
  1810. printf("%15s [%04d] ", tstr, sample->cpu);
  1811. if (sched->show_cpu_visual) {
  1812. u32 i;
  1813. char c;
  1814. printf(" ");
  1815. for (i = 0; i < max_cpus; ++i) {
  1816. /* flag idle times with 'i'; others are sched events */
  1817. if (i == sample->cpu)
  1818. c = (thread__tid(thread) == 0) ? 'i' : 's';
  1819. else
  1820. c = ' ';
  1821. printf("%c", c);
  1822. }
  1823. printf(" ");
  1824. }
  1825. printf(" %-*s ", comm_width, timehist_get_commstr(thread));
  1826. if (sched->show_prio)
  1827. printf(" %-*s ", MAX_PRIO_STR_LEN, timehist_get_priostr(evsel, thread, sample));
  1828. wait_time = tr->dt_sleep + tr->dt_iowait + tr->dt_preempt;
  1829. print_sched_time(wait_time, 6);
  1830. print_sched_time(tr->dt_delay, 6);
  1831. print_sched_time(tr->dt_run, 6);
  1832. if (sched->show_state)
  1833. printf(" %5c ", thread__tid(thread) == 0 ? 'I' : state);
  1834. if (sched->show_next) {
  1835. snprintf(nstr, sizeof(nstr), "next: %s[%d]", next_comm, next_pid);
  1836. printf(" %-*s", comm_width, nstr);
  1837. }
  1838. if (sched->show_wakeups && !sched->show_next)
  1839. printf(" %-*s", comm_width, "");
  1840. if (thread__tid(thread) == 0)
  1841. goto out;
  1842. if (sched->show_callchain)
  1843. printf(" ");
  1844. sample__fprintf_sym(sample, al, 0,
  1845. EVSEL__PRINT_SYM | EVSEL__PRINT_ONELINE |
  1846. EVSEL__PRINT_CALLCHAIN_ARROW |
  1847. EVSEL__PRINT_SKIP_IGNORED,
  1848. get_tls_callchain_cursor(), symbol_conf.bt_stop_list, stdout);
  1849. out:
  1850. printf("\n");
  1851. }
  1852. /*
  1853. * Explanation of delta-time stats:
  1854. *
  1855. * t = time of current schedule out event
  1856. * tprev = time of previous sched out event
  1857. * also time of schedule-in event for current task
  1858. * last_time = time of last sched change event for current task
  1859. * (i.e, time process was last scheduled out)
  1860. * ready_to_run = time of wakeup for current task
  1861. *
  1862. * -----|------------|------------|------------|------
  1863. * last ready tprev t
  1864. * time to run
  1865. *
  1866. * |-------- dt_wait --------|
  1867. * |- dt_delay -|-- dt_run --|
  1868. *
  1869. * dt_run = run time of current task
  1870. * dt_wait = time between last schedule out event for task and tprev
  1871. * represents time spent off the cpu
  1872. * dt_delay = time between wakeup and schedule-in of task
  1873. */
  1874. static void timehist_update_runtime_stats(struct thread_runtime *r,
  1875. u64 t, u64 tprev)
  1876. {
  1877. r->dt_delay = 0;
  1878. r->dt_sleep = 0;
  1879. r->dt_iowait = 0;
  1880. r->dt_preempt = 0;
  1881. r->dt_run = 0;
  1882. if (tprev) {
  1883. r->dt_run = t - tprev;
  1884. if (r->ready_to_run) {
  1885. if (r->ready_to_run > tprev)
  1886. pr_debug("time travel: wakeup time for task > previous sched_switch event\n");
  1887. else
  1888. r->dt_delay = tprev - r->ready_to_run;
  1889. }
  1890. if (r->last_time > tprev)
  1891. pr_debug("time travel: last sched out time for task > previous sched_switch event\n");
  1892. else if (r->last_time) {
  1893. u64 dt_wait = tprev - r->last_time;
  1894. if (r->last_state == 'R')
  1895. r->dt_preempt = dt_wait;
  1896. else if (r->last_state == 'D')
  1897. r->dt_iowait = dt_wait;
  1898. else
  1899. r->dt_sleep = dt_wait;
  1900. }
  1901. }
  1902. update_stats(&r->run_stats, r->dt_run);
  1903. r->total_run_time += r->dt_run;
  1904. r->total_delay_time += r->dt_delay;
  1905. r->total_sleep_time += r->dt_sleep;
  1906. r->total_iowait_time += r->dt_iowait;
  1907. r->total_preempt_time += r->dt_preempt;
  1908. }
  1909. static bool is_idle_sample(struct perf_sample *sample,
  1910. struct evsel *evsel)
  1911. {
  1912. /* pid 0 == swapper == idle task */
  1913. if (evsel__name_is(evsel, "sched:sched_switch"))
  1914. return evsel__intval(evsel, sample, "prev_pid") == 0;
  1915. return sample->pid == 0;
  1916. }
  1917. static void save_task_callchain(struct perf_sched *sched,
  1918. struct perf_sample *sample,
  1919. struct evsel *evsel,
  1920. struct machine *machine)
  1921. {
  1922. struct callchain_cursor *cursor;
  1923. struct thread *thread;
  1924. /* want main thread for process - has maps */
  1925. thread = machine__findnew_thread(machine, sample->pid, sample->pid);
  1926. if (thread == NULL) {
  1927. pr_debug("Failed to get thread for pid %d.\n", sample->pid);
  1928. return;
  1929. }
  1930. if (!sched->show_callchain || sample->callchain == NULL)
  1931. return;
  1932. cursor = get_tls_callchain_cursor();
  1933. if (thread__resolve_callchain(thread, cursor, evsel, sample,
  1934. NULL, NULL, sched->max_stack + 2) != 0) {
  1935. if (verbose > 0)
  1936. pr_err("Failed to resolve callchain. Skipping\n");
  1937. return;
  1938. }
  1939. callchain_cursor_commit(cursor);
  1940. while (true) {
  1941. struct callchain_cursor_node *node;
  1942. struct symbol *sym;
  1943. node = callchain_cursor_current(cursor);
  1944. if (node == NULL)
  1945. break;
  1946. sym = node->ms.sym;
  1947. if (sym) {
  1948. if (!strcmp(sym->name, "schedule") ||
  1949. !strcmp(sym->name, "__schedule") ||
  1950. !strcmp(sym->name, "preempt_schedule"))
  1951. sym->ignore = 1;
  1952. }
  1953. callchain_cursor_advance(cursor);
  1954. }
  1955. }
  1956. static int init_idle_thread(struct thread *thread)
  1957. {
  1958. struct idle_thread_runtime *itr;
  1959. thread__set_comm(thread, idle_comm, 0);
  1960. itr = zalloc(sizeof(*itr));
  1961. if (itr == NULL)
  1962. return -ENOMEM;
  1963. init_prio(&itr->tr);
  1964. init_stats(&itr->tr.run_stats);
  1965. callchain_init(&itr->callchain);
  1966. callchain_cursor_reset(&itr->cursor);
  1967. thread__set_priv(thread, itr);
  1968. return 0;
  1969. }
  1970. /*
  1971. * Track idle stats per cpu by maintaining a local thread
  1972. * struct for the idle task on each cpu.
  1973. */
  1974. static int init_idle_threads(int ncpu)
  1975. {
  1976. int i, ret;
  1977. idle_threads = zalloc(ncpu * sizeof(struct thread *));
  1978. if (!idle_threads)
  1979. return -ENOMEM;
  1980. idle_max_cpu = ncpu;
  1981. /* allocate the actual thread struct if needed */
  1982. for (i = 0; i < ncpu; ++i) {
  1983. idle_threads[i] = thread__new(0, 0);
  1984. if (idle_threads[i] == NULL)
  1985. return -ENOMEM;
  1986. ret = init_idle_thread(idle_threads[i]);
  1987. if (ret < 0)
  1988. return ret;
  1989. }
  1990. return 0;
  1991. }
  1992. static void free_idle_threads(void)
  1993. {
  1994. int i;
  1995. if (idle_threads == NULL)
  1996. return;
  1997. for (i = 0; i < idle_max_cpu; ++i) {
  1998. if ((idle_threads[i]))
  1999. thread__delete(idle_threads[i]);
  2000. }
  2001. free(idle_threads);
  2002. }
  2003. static struct thread *get_idle_thread(int cpu)
  2004. {
  2005. /*
  2006. * expand/allocate array of pointers to local thread
  2007. * structs if needed
  2008. */
  2009. if ((cpu >= idle_max_cpu) || (idle_threads == NULL)) {
  2010. int i, j = __roundup_pow_of_two(cpu+1);
  2011. void *p;
  2012. p = realloc(idle_threads, j * sizeof(struct thread *));
  2013. if (!p)
  2014. return NULL;
  2015. idle_threads = (struct thread **) p;
  2016. for (i = idle_max_cpu; i < j; ++i)
  2017. idle_threads[i] = NULL;
  2018. idle_max_cpu = j;
  2019. }
  2020. /* allocate a new thread struct if needed */
  2021. if (idle_threads[cpu] == NULL) {
  2022. idle_threads[cpu] = thread__new(0, 0);
  2023. if (idle_threads[cpu]) {
  2024. if (init_idle_thread(idle_threads[cpu]) < 0)
  2025. return NULL;
  2026. }
  2027. }
  2028. return idle_threads[cpu];
  2029. }
  2030. static void save_idle_callchain(struct perf_sched *sched,
  2031. struct idle_thread_runtime *itr,
  2032. struct perf_sample *sample)
  2033. {
  2034. struct callchain_cursor *cursor;
  2035. if (!sched->show_callchain || sample->callchain == NULL)
  2036. return;
  2037. cursor = get_tls_callchain_cursor();
  2038. if (cursor == NULL)
  2039. return;
  2040. callchain_cursor__copy(&itr->cursor, cursor);
  2041. }
  2042. static struct thread *timehist_get_thread(struct perf_sched *sched,
  2043. struct perf_sample *sample,
  2044. struct machine *machine,
  2045. struct evsel *evsel)
  2046. {
  2047. struct thread *thread;
  2048. if (is_idle_sample(sample, evsel)) {
  2049. thread = get_idle_thread(sample->cpu);
  2050. if (thread == NULL)
  2051. pr_err("Failed to get idle thread for cpu %d.\n", sample->cpu);
  2052. } else {
  2053. /* there were samples with tid 0 but non-zero pid */
  2054. thread = machine__findnew_thread(machine, sample->pid,
  2055. sample->tid ?: sample->pid);
  2056. if (thread == NULL) {
  2057. pr_debug("Failed to get thread for tid %d. skipping sample.\n",
  2058. sample->tid);
  2059. }
  2060. save_task_callchain(sched, sample, evsel, machine);
  2061. if (sched->idle_hist) {
  2062. struct thread *idle;
  2063. struct idle_thread_runtime *itr;
  2064. idle = get_idle_thread(sample->cpu);
  2065. if (idle == NULL) {
  2066. pr_err("Failed to get idle thread for cpu %d.\n", sample->cpu);
  2067. return NULL;
  2068. }
  2069. itr = thread__priv(idle);
  2070. if (itr == NULL)
  2071. return NULL;
  2072. itr->last_thread = thread;
  2073. /* copy task callchain when entering to idle */
  2074. if (evsel__intval(evsel, sample, "next_pid") == 0)
  2075. save_idle_callchain(sched, itr, sample);
  2076. }
  2077. }
  2078. return thread;
  2079. }
  2080. static bool timehist_skip_sample(struct perf_sched *sched,
  2081. struct thread *thread,
  2082. struct evsel *evsel,
  2083. struct perf_sample *sample)
  2084. {
  2085. bool rc = false;
  2086. int prio = -1;
  2087. struct thread_runtime *tr = NULL;
  2088. if (thread__is_filtered(thread)) {
  2089. rc = true;
  2090. sched->skipped_samples++;
  2091. }
  2092. if (sched->prio_str) {
  2093. /*
  2094. * Because priority may be changed during task execution,
  2095. * first read priority from prev sched_in event for current task.
  2096. * If prev sched_in event is not saved, then read priority from
  2097. * current task sched_out event.
  2098. */
  2099. tr = thread__get_runtime(thread);
  2100. if (tr && tr->prio != -1)
  2101. prio = tr->prio;
  2102. else if (evsel__name_is(evsel, "sched:sched_switch"))
  2103. prio = evsel__intval(evsel, sample, "prev_prio");
  2104. if (prio != -1 && !test_bit(prio, sched->prio_bitmap)) {
  2105. rc = true;
  2106. sched->skipped_samples++;
  2107. }
  2108. }
  2109. if (sched->idle_hist) {
  2110. if (!evsel__name_is(evsel, "sched:sched_switch"))
  2111. rc = true;
  2112. else if (evsel__intval(evsel, sample, "prev_pid") != 0 &&
  2113. evsel__intval(evsel, sample, "next_pid") != 0)
  2114. rc = true;
  2115. }
  2116. return rc;
  2117. }
  2118. static void timehist_print_wakeup_event(struct perf_sched *sched,
  2119. struct evsel *evsel,
  2120. struct perf_sample *sample,
  2121. struct machine *machine,
  2122. struct thread *awakened)
  2123. {
  2124. struct thread *thread;
  2125. char tstr[64];
  2126. thread = machine__findnew_thread(machine, sample->pid, sample->tid);
  2127. if (thread == NULL)
  2128. return;
  2129. /* show wakeup unless both awakee and awaker are filtered */
  2130. if (timehist_skip_sample(sched, thread, evsel, sample) &&
  2131. timehist_skip_sample(sched, awakened, evsel, sample)) {
  2132. return;
  2133. }
  2134. timestamp__scnprintf_usec(sample->time, tstr, sizeof(tstr));
  2135. printf("%15s [%04d] ", tstr, sample->cpu);
  2136. if (sched->show_cpu_visual)
  2137. printf(" %*s ", sched->max_cpu.cpu + 1, "");
  2138. printf(" %-*s ", comm_width, timehist_get_commstr(thread));
  2139. /* dt spacer */
  2140. printf(" %9s %9s %9s ", "", "", "");
  2141. printf("awakened: %s", timehist_get_commstr(awakened));
  2142. printf("\n");
  2143. }
  2144. static int timehist_sched_wakeup_ignore(const struct perf_tool *tool __maybe_unused,
  2145. union perf_event *event __maybe_unused,
  2146. struct evsel *evsel __maybe_unused,
  2147. struct perf_sample *sample __maybe_unused,
  2148. struct machine *machine __maybe_unused)
  2149. {
  2150. return 0;
  2151. }
  2152. static int timehist_sched_wakeup_event(const struct perf_tool *tool,
  2153. union perf_event *event __maybe_unused,
  2154. struct evsel *evsel,
  2155. struct perf_sample *sample,
  2156. struct machine *machine)
  2157. {
  2158. struct perf_sched *sched = container_of(tool, struct perf_sched, tool);
  2159. struct thread *thread;
  2160. struct thread_runtime *tr = NULL;
  2161. /* want pid of awakened task not pid in sample */
  2162. const u32 pid = evsel__intval(evsel, sample, "pid");
  2163. thread = machine__findnew_thread(machine, 0, pid);
  2164. if (thread == NULL)
  2165. return -1;
  2166. tr = thread__get_runtime(thread);
  2167. if (tr == NULL)
  2168. return -1;
  2169. if (tr->ready_to_run == 0)
  2170. tr->ready_to_run = sample->time;
  2171. /* show wakeups if requested */
  2172. if (sched->show_wakeups &&
  2173. !perf_time__skip_sample(&sched->ptime, sample->time))
  2174. timehist_print_wakeup_event(sched, evsel, sample, machine, thread);
  2175. return 0;
  2176. }
  2177. static void timehist_print_migration_event(struct perf_sched *sched,
  2178. struct evsel *evsel,
  2179. struct perf_sample *sample,
  2180. struct machine *machine,
  2181. struct thread *migrated)
  2182. {
  2183. struct thread *thread;
  2184. char tstr[64];
  2185. u32 max_cpus;
  2186. u32 ocpu, dcpu;
  2187. if (sched->summary_only)
  2188. return;
  2189. max_cpus = sched->max_cpu.cpu + 1;
  2190. ocpu = evsel__intval(evsel, sample, "orig_cpu");
  2191. dcpu = evsel__intval(evsel, sample, "dest_cpu");
  2192. thread = machine__findnew_thread(machine, sample->pid, sample->tid);
  2193. if (thread == NULL)
  2194. return;
  2195. if (timehist_skip_sample(sched, thread, evsel, sample) &&
  2196. timehist_skip_sample(sched, migrated, evsel, sample)) {
  2197. return;
  2198. }
  2199. timestamp__scnprintf_usec(sample->time, tstr, sizeof(tstr));
  2200. printf("%15s [%04d] ", tstr, sample->cpu);
  2201. if (sched->show_cpu_visual) {
  2202. u32 i;
  2203. char c;
  2204. printf(" ");
  2205. for (i = 0; i < max_cpus; ++i) {
  2206. c = (i == sample->cpu) ? 'm' : ' ';
  2207. printf("%c", c);
  2208. }
  2209. printf(" ");
  2210. }
  2211. printf(" %-*s ", comm_width, timehist_get_commstr(thread));
  2212. /* dt spacer */
  2213. printf(" %9s %9s %9s ", "", "", "");
  2214. printf("migrated: %s", timehist_get_commstr(migrated));
  2215. printf(" cpu %d => %d", ocpu, dcpu);
  2216. printf("\n");
  2217. }
  2218. static int timehist_migrate_task_event(const struct perf_tool *tool,
  2219. union perf_event *event __maybe_unused,
  2220. struct evsel *evsel,
  2221. struct perf_sample *sample,
  2222. struct machine *machine)
  2223. {
  2224. struct perf_sched *sched = container_of(tool, struct perf_sched, tool);
  2225. struct thread *thread;
  2226. struct thread_runtime *tr = NULL;
  2227. /* want pid of migrated task not pid in sample */
  2228. const u32 pid = evsel__intval(evsel, sample, "pid");
  2229. thread = machine__findnew_thread(machine, 0, pid);
  2230. if (thread == NULL)
  2231. return -1;
  2232. tr = thread__get_runtime(thread);
  2233. if (tr == NULL)
  2234. return -1;
  2235. tr->migrations++;
  2236. /* show migrations if requested */
  2237. timehist_print_migration_event(sched, evsel, sample, machine, thread);
  2238. return 0;
  2239. }
  2240. static void timehist_update_task_prio(struct evsel *evsel,
  2241. struct perf_sample *sample,
  2242. struct machine *machine)
  2243. {
  2244. struct thread *thread;
  2245. struct thread_runtime *tr = NULL;
  2246. const u32 next_pid = evsel__intval(evsel, sample, "next_pid");
  2247. const u32 next_prio = evsel__intval(evsel, sample, "next_prio");
  2248. if (next_pid == 0)
  2249. thread = get_idle_thread(sample->cpu);
  2250. else
  2251. thread = machine__findnew_thread(machine, -1, next_pid);
  2252. if (thread == NULL)
  2253. return;
  2254. tr = thread__get_runtime(thread);
  2255. if (tr == NULL)
  2256. return;
  2257. tr->prio = next_prio;
  2258. }
  2259. static int timehist_sched_change_event(const struct perf_tool *tool,
  2260. union perf_event *event,
  2261. struct evsel *evsel,
  2262. struct perf_sample *sample,
  2263. struct machine *machine)
  2264. {
  2265. struct perf_sched *sched = container_of(tool, struct perf_sched, tool);
  2266. struct perf_time_interval *ptime = &sched->ptime;
  2267. struct addr_location al;
  2268. struct thread *thread;
  2269. struct thread_runtime *tr = NULL;
  2270. u64 tprev, t = sample->time;
  2271. int rc = 0;
  2272. const char state = evsel__taskstate(evsel, sample, "prev_state");
  2273. addr_location__init(&al);
  2274. if (machine__resolve(machine, &al, sample) < 0) {
  2275. pr_err("problem processing %d event. skipping it\n",
  2276. event->header.type);
  2277. rc = -1;
  2278. goto out;
  2279. }
  2280. if (sched->show_prio || sched->prio_str)
  2281. timehist_update_task_prio(evsel, sample, machine);
  2282. thread = timehist_get_thread(sched, sample, machine, evsel);
  2283. if (thread == NULL) {
  2284. rc = -1;
  2285. goto out;
  2286. }
  2287. if (timehist_skip_sample(sched, thread, evsel, sample))
  2288. goto out;
  2289. tr = thread__get_runtime(thread);
  2290. if (tr == NULL) {
  2291. rc = -1;
  2292. goto out;
  2293. }
  2294. tprev = evsel__get_time(evsel, sample->cpu);
  2295. /*
  2296. * If start time given:
  2297. * - sample time is under window user cares about - skip sample
  2298. * - tprev is under window user cares about - reset to start of window
  2299. */
  2300. if (ptime->start && ptime->start > t)
  2301. goto out;
  2302. if (tprev && ptime->start > tprev)
  2303. tprev = ptime->start;
  2304. /*
  2305. * If end time given:
  2306. * - previous sched event is out of window - we are done
  2307. * - sample time is beyond window user cares about - reset it
  2308. * to close out stats for time window interest
  2309. * - If tprev is 0, that is, sched_in event for current task is
  2310. * not recorded, cannot determine whether sched_in event is
  2311. * within time window interest - ignore it
  2312. */
  2313. if (ptime->end) {
  2314. if (!tprev || tprev > ptime->end)
  2315. goto out;
  2316. if (t > ptime->end)
  2317. t = ptime->end;
  2318. }
  2319. if (!sched->idle_hist || thread__tid(thread) == 0) {
  2320. if (!cpu_list || test_bit(sample->cpu, cpu_bitmap))
  2321. timehist_update_runtime_stats(tr, t, tprev);
  2322. if (sched->idle_hist) {
  2323. struct idle_thread_runtime *itr = (void *)tr;
  2324. struct thread_runtime *last_tr;
  2325. if (itr->last_thread == NULL)
  2326. goto out;
  2327. /* add current idle time as last thread's runtime */
  2328. last_tr = thread__get_runtime(itr->last_thread);
  2329. if (last_tr == NULL)
  2330. goto out;
  2331. timehist_update_runtime_stats(last_tr, t, tprev);
  2332. /*
  2333. * remove delta time of last thread as it's not updated
  2334. * and otherwise it will show an invalid value next
  2335. * time. we only care total run time and run stat.
  2336. */
  2337. last_tr->dt_run = 0;
  2338. last_tr->dt_delay = 0;
  2339. last_tr->dt_sleep = 0;
  2340. last_tr->dt_iowait = 0;
  2341. last_tr->dt_preempt = 0;
  2342. if (itr->cursor.nr)
  2343. callchain_append(&itr->callchain, &itr->cursor, t - tprev);
  2344. itr->last_thread = NULL;
  2345. }
  2346. if (!sched->summary_only)
  2347. timehist_print_sample(sched, evsel, sample, &al, thread, t, state);
  2348. }
  2349. out:
  2350. if (sched->hist_time.start == 0 && t >= ptime->start)
  2351. sched->hist_time.start = t;
  2352. if (ptime->end == 0 || t <= ptime->end)
  2353. sched->hist_time.end = t;
  2354. if (tr) {
  2355. /* time of this sched_switch event becomes last time task seen */
  2356. tr->last_time = sample->time;
  2357. /* last state is used to determine where to account wait time */
  2358. tr->last_state = state;
  2359. /* sched out event for task so reset ready to run time */
  2360. if (state == 'R')
  2361. tr->ready_to_run = t;
  2362. else
  2363. tr->ready_to_run = 0;
  2364. }
  2365. evsel__save_time(evsel, sample->time, sample->cpu);
  2366. addr_location__exit(&al);
  2367. return rc;
  2368. }
  2369. static int timehist_sched_switch_event(const struct perf_tool *tool,
  2370. union perf_event *event,
  2371. struct evsel *evsel,
  2372. struct perf_sample *sample,
  2373. struct machine *machine __maybe_unused)
  2374. {
  2375. return timehist_sched_change_event(tool, event, evsel, sample, machine);
  2376. }
  2377. static int process_lost(const struct perf_tool *tool __maybe_unused,
  2378. union perf_event *event,
  2379. struct perf_sample *sample,
  2380. struct machine *machine __maybe_unused)
  2381. {
  2382. char tstr[64];
  2383. timestamp__scnprintf_usec(sample->time, tstr, sizeof(tstr));
  2384. printf("%15s ", tstr);
  2385. printf("lost %" PRI_lu64 " events on cpu %d\n", event->lost.lost, sample->cpu);
  2386. return 0;
  2387. }
  2388. static void print_thread_runtime(struct thread *t,
  2389. struct thread_runtime *r)
  2390. {
  2391. double mean = avg_stats(&r->run_stats);
  2392. float stddev;
  2393. printf("%*s %5d %9" PRIu64 " ",
  2394. comm_width, timehist_get_commstr(t), thread__ppid(t),
  2395. (u64) r->run_stats.n);
  2396. print_sched_time(r->total_run_time, 8);
  2397. stddev = rel_stddev_stats(stddev_stats(&r->run_stats), mean);
  2398. print_sched_time(r->run_stats.min, 6);
  2399. printf(" ");
  2400. print_sched_time((u64) mean, 6);
  2401. printf(" ");
  2402. print_sched_time(r->run_stats.max, 6);
  2403. printf(" ");
  2404. printf("%5.2f", stddev);
  2405. printf(" %5" PRIu64, r->migrations);
  2406. printf("\n");
  2407. }
  2408. static void print_thread_waittime(struct thread *t,
  2409. struct thread_runtime *r)
  2410. {
  2411. printf("%*s %5d %9" PRIu64 " ",
  2412. comm_width, timehist_get_commstr(t), thread__ppid(t),
  2413. (u64) r->run_stats.n);
  2414. print_sched_time(r->total_run_time, 8);
  2415. print_sched_time(r->total_sleep_time, 6);
  2416. printf(" ");
  2417. print_sched_time(r->total_iowait_time, 6);
  2418. printf(" ");
  2419. print_sched_time(r->total_preempt_time, 6);
  2420. printf(" ");
  2421. print_sched_time(r->total_delay_time, 6);
  2422. printf("\n");
  2423. }
  2424. struct total_run_stats {
  2425. struct perf_sched *sched;
  2426. u64 sched_count;
  2427. u64 task_count;
  2428. u64 total_run_time;
  2429. };
  2430. static int show_thread_runtime(struct thread *t, void *priv)
  2431. {
  2432. struct total_run_stats *stats = priv;
  2433. struct thread_runtime *r;
  2434. if (thread__is_filtered(t))
  2435. return 0;
  2436. r = thread__priv(t);
  2437. if (r && r->run_stats.n) {
  2438. stats->task_count++;
  2439. stats->sched_count += r->run_stats.n;
  2440. stats->total_run_time += r->total_run_time;
  2441. if (stats->sched->show_state)
  2442. print_thread_waittime(t, r);
  2443. else
  2444. print_thread_runtime(t, r);
  2445. }
  2446. return 0;
  2447. }
  2448. static size_t callchain__fprintf_folded(FILE *fp, struct callchain_node *node)
  2449. {
  2450. const char *sep = " <- ";
  2451. struct callchain_list *chain;
  2452. size_t ret = 0;
  2453. char bf[1024];
  2454. bool first;
  2455. if (node == NULL)
  2456. return 0;
  2457. ret = callchain__fprintf_folded(fp, node->parent);
  2458. first = (ret == 0);
  2459. list_for_each_entry(chain, &node->val, list) {
  2460. if (chain->ip >= PERF_CONTEXT_MAX)
  2461. continue;
  2462. if (chain->ms.sym && chain->ms.sym->ignore)
  2463. continue;
  2464. ret += fprintf(fp, "%s%s", first ? "" : sep,
  2465. callchain_list__sym_name(chain, bf, sizeof(bf),
  2466. false));
  2467. first = false;
  2468. }
  2469. return ret;
  2470. }
  2471. static size_t timehist_print_idlehist_callchain(struct rb_root_cached *root)
  2472. {
  2473. size_t ret = 0;
  2474. FILE *fp = stdout;
  2475. struct callchain_node *chain;
  2476. struct rb_node *rb_node = rb_first_cached(root);
  2477. printf(" %16s %8s %s\n", "Idle time (msec)", "Count", "Callchains");
  2478. printf(" %.16s %.8s %.50s\n", graph_dotted_line, graph_dotted_line,
  2479. graph_dotted_line);
  2480. while (rb_node) {
  2481. chain = rb_entry(rb_node, struct callchain_node, rb_node);
  2482. rb_node = rb_next(rb_node);
  2483. ret += fprintf(fp, " ");
  2484. print_sched_time(chain->hit, 12);
  2485. ret += 16; /* print_sched_time returns 2nd arg + 4 */
  2486. ret += fprintf(fp, " %8d ", chain->count);
  2487. ret += callchain__fprintf_folded(fp, chain);
  2488. ret += fprintf(fp, "\n");
  2489. }
  2490. return ret;
  2491. }
  2492. static void timehist_print_summary(struct perf_sched *sched,
  2493. struct perf_session *session)
  2494. {
  2495. struct machine *m = &session->machines.host;
  2496. struct total_run_stats totals;
  2497. u64 task_count;
  2498. struct thread *t;
  2499. struct thread_runtime *r;
  2500. int i;
  2501. u64 hist_time = sched->hist_time.end - sched->hist_time.start;
  2502. memset(&totals, 0, sizeof(totals));
  2503. totals.sched = sched;
  2504. if (sched->idle_hist) {
  2505. printf("\nIdle-time summary\n");
  2506. printf("%*s parent sched-out ", comm_width, "comm");
  2507. printf(" idle-time min-idle avg-idle max-idle stddev migrations\n");
  2508. } else if (sched->show_state) {
  2509. printf("\nWait-time summary\n");
  2510. printf("%*s parent sched-in ", comm_width, "comm");
  2511. printf(" run-time sleep iowait preempt delay\n");
  2512. } else {
  2513. printf("\nRuntime summary\n");
  2514. printf("%*s parent sched-in ", comm_width, "comm");
  2515. printf(" run-time min-run avg-run max-run stddev migrations\n");
  2516. }
  2517. printf("%*s (count) ", comm_width, "");
  2518. printf(" (msec) (msec) (msec) (msec) %s\n",
  2519. sched->show_state ? "(msec)" : "%");
  2520. printf("%.117s\n", graph_dotted_line);
  2521. machine__for_each_thread(m, show_thread_runtime, &totals);
  2522. task_count = totals.task_count;
  2523. if (!task_count)
  2524. printf("<no still running tasks>\n");
  2525. /* CPU idle stats not tracked when samples were skipped */
  2526. if (sched->skipped_samples && !sched->idle_hist)
  2527. return;
  2528. printf("\nIdle stats:\n");
  2529. for (i = 0; i < idle_max_cpu; ++i) {
  2530. if (cpu_list && !test_bit(i, cpu_bitmap))
  2531. continue;
  2532. t = idle_threads[i];
  2533. if (!t)
  2534. continue;
  2535. r = thread__priv(t);
  2536. if (r && r->run_stats.n) {
  2537. totals.sched_count += r->run_stats.n;
  2538. printf(" CPU %2d idle for ", i);
  2539. print_sched_time(r->total_run_time, 6);
  2540. printf(" msec (%6.2f%%)\n", 100.0 * r->total_run_time / hist_time);
  2541. } else
  2542. printf(" CPU %2d idle entire time window\n", i);
  2543. }
  2544. if (sched->idle_hist && sched->show_callchain) {
  2545. callchain_param.mode = CHAIN_FOLDED;
  2546. callchain_param.value = CCVAL_PERIOD;
  2547. callchain_register_param(&callchain_param);
  2548. printf("\nIdle stats by callchain:\n");
  2549. for (i = 0; i < idle_max_cpu; ++i) {
  2550. struct idle_thread_runtime *itr;
  2551. t = idle_threads[i];
  2552. if (!t)
  2553. continue;
  2554. itr = thread__priv(t);
  2555. if (itr == NULL)
  2556. continue;
  2557. callchain_param.sort(&itr->sorted_root.rb_root, &itr->callchain,
  2558. 0, &callchain_param);
  2559. printf(" CPU %2d:", i);
  2560. print_sched_time(itr->tr.total_run_time, 6);
  2561. printf(" msec\n");
  2562. timehist_print_idlehist_callchain(&itr->sorted_root);
  2563. printf("\n");
  2564. }
  2565. }
  2566. printf("\n"
  2567. " Total number of unique tasks: %" PRIu64 "\n"
  2568. "Total number of context switches: %" PRIu64 "\n",
  2569. totals.task_count, totals.sched_count);
  2570. printf(" Total run time (msec): ");
  2571. print_sched_time(totals.total_run_time, 2);
  2572. printf("\n");
  2573. printf(" Total scheduling time (msec): ");
  2574. print_sched_time(hist_time, 2);
  2575. printf(" (x %d)\n", sched->max_cpu.cpu);
  2576. }
  2577. typedef int (*sched_handler)(const struct perf_tool *tool,
  2578. union perf_event *event,
  2579. struct evsel *evsel,
  2580. struct perf_sample *sample,
  2581. struct machine *machine);
  2582. static int perf_timehist__process_sample(const struct perf_tool *tool,
  2583. union perf_event *event,
  2584. struct perf_sample *sample,
  2585. struct evsel *evsel,
  2586. struct machine *machine)
  2587. {
  2588. struct perf_sched *sched = container_of(tool, struct perf_sched, tool);
  2589. int err = 0;
  2590. struct perf_cpu this_cpu = {
  2591. .cpu = sample->cpu,
  2592. };
  2593. if (this_cpu.cpu > sched->max_cpu.cpu)
  2594. sched->max_cpu = this_cpu;
  2595. if (evsel->handler != NULL) {
  2596. sched_handler f = evsel->handler;
  2597. err = f(tool, event, evsel, sample, machine);
  2598. }
  2599. return err;
  2600. }
  2601. static int timehist_check_attr(struct perf_sched *sched,
  2602. struct evlist *evlist)
  2603. {
  2604. struct evsel *evsel;
  2605. struct evsel_runtime *er;
  2606. list_for_each_entry(evsel, &evlist->core.entries, core.node) {
  2607. er = evsel__get_runtime(evsel);
  2608. if (er == NULL) {
  2609. pr_err("Failed to allocate memory for evsel runtime data\n");
  2610. return -1;
  2611. }
  2612. /* only need to save callchain related to sched_switch event */
  2613. if (sched->show_callchain &&
  2614. evsel__name_is(evsel, "sched:sched_switch") &&
  2615. !evsel__has_callchain(evsel)) {
  2616. pr_info("Samples of sched_switch event do not have callchains.\n");
  2617. sched->show_callchain = 0;
  2618. symbol_conf.use_callchain = 0;
  2619. }
  2620. }
  2621. return 0;
  2622. }
  2623. static int timehist_parse_prio_str(struct perf_sched *sched)
  2624. {
  2625. char *p;
  2626. unsigned long start_prio, end_prio;
  2627. const char *str = sched->prio_str;
  2628. if (!str)
  2629. return 0;
  2630. while (isdigit(*str)) {
  2631. p = NULL;
  2632. start_prio = strtoul(str, &p, 0);
  2633. if (start_prio >= MAX_PRIO || (*p != '\0' && *p != ',' && *p != '-'))
  2634. return -1;
  2635. if (*p == '-') {
  2636. str = ++p;
  2637. p = NULL;
  2638. end_prio = strtoul(str, &p, 0);
  2639. if (end_prio >= MAX_PRIO || (*p != '\0' && *p != ','))
  2640. return -1;
  2641. if (end_prio < start_prio)
  2642. return -1;
  2643. } else {
  2644. end_prio = start_prio;
  2645. }
  2646. for (; start_prio <= end_prio; start_prio++)
  2647. __set_bit(start_prio, sched->prio_bitmap);
  2648. if (*p)
  2649. ++p;
  2650. str = p;
  2651. }
  2652. return 0;
  2653. }
  2654. static int perf_sched__timehist(struct perf_sched *sched)
  2655. {
  2656. struct evsel_str_handler handlers[] = {
  2657. { "sched:sched_switch", timehist_sched_switch_event, },
  2658. { "sched:sched_wakeup", timehist_sched_wakeup_event, },
  2659. { "sched:sched_waking", timehist_sched_wakeup_event, },
  2660. { "sched:sched_wakeup_new", timehist_sched_wakeup_event, },
  2661. };
  2662. const struct evsel_str_handler migrate_handlers[] = {
  2663. { "sched:sched_migrate_task", timehist_migrate_task_event, },
  2664. };
  2665. struct perf_data data = {
  2666. .path = input_name,
  2667. .mode = PERF_DATA_MODE_READ,
  2668. .force = sched->force,
  2669. };
  2670. struct perf_session *session;
  2671. struct evlist *evlist;
  2672. int err = -1;
  2673. /*
  2674. * event handlers for timehist option
  2675. */
  2676. sched->tool.sample = perf_timehist__process_sample;
  2677. sched->tool.mmap = perf_event__process_mmap;
  2678. sched->tool.comm = perf_event__process_comm;
  2679. sched->tool.exit = perf_event__process_exit;
  2680. sched->tool.fork = perf_event__process_fork;
  2681. sched->tool.lost = process_lost;
  2682. sched->tool.attr = perf_event__process_attr;
  2683. sched->tool.tracing_data = perf_event__process_tracing_data;
  2684. sched->tool.build_id = perf_event__process_build_id;
  2685. sched->tool.ordering_requires_timestamps = true;
  2686. symbol_conf.use_callchain = sched->show_callchain;
  2687. session = perf_session__new(&data, &sched->tool);
  2688. if (IS_ERR(session))
  2689. return PTR_ERR(session);
  2690. if (cpu_list) {
  2691. err = perf_session__cpu_bitmap(session, cpu_list, cpu_bitmap);
  2692. if (err < 0)
  2693. goto out;
  2694. }
  2695. evlist = session->evlist;
  2696. symbol__init(&session->header.env);
  2697. if (perf_time__parse_str(&sched->ptime, sched->time_str) != 0) {
  2698. pr_err("Invalid time string\n");
  2699. err = -EINVAL;
  2700. goto out;
  2701. }
  2702. if (timehist_check_attr(sched, evlist) != 0)
  2703. goto out;
  2704. if (timehist_parse_prio_str(sched) != 0) {
  2705. pr_err("Invalid prio string\n");
  2706. goto out;
  2707. }
  2708. setup_pager();
  2709. evsel__set_priv_destructor(timehist__evsel_priv_destructor);
  2710. /* prefer sched_waking if it is captured */
  2711. if (evlist__find_tracepoint_by_name(session->evlist, "sched:sched_waking"))
  2712. handlers[1].handler = timehist_sched_wakeup_ignore;
  2713. /* setup per-evsel handlers */
  2714. if (perf_session__set_tracepoints_handlers(session, handlers))
  2715. goto out;
  2716. /* sched_switch event at a minimum needs to exist */
  2717. if (!evlist__find_tracepoint_by_name(session->evlist, "sched:sched_switch")) {
  2718. pr_err("No sched_switch events found. Have you run 'perf sched record'?\n");
  2719. goto out;
  2720. }
  2721. if (sched->show_migrations &&
  2722. perf_session__set_tracepoints_handlers(session, migrate_handlers))
  2723. goto out;
  2724. /* pre-allocate struct for per-CPU idle stats */
  2725. sched->max_cpu.cpu = session->header.env.nr_cpus_online;
  2726. if (sched->max_cpu.cpu == 0)
  2727. sched->max_cpu.cpu = 4;
  2728. if (init_idle_threads(sched->max_cpu.cpu))
  2729. goto out;
  2730. /* summary_only implies summary option, but don't overwrite summary if set */
  2731. if (sched->summary_only)
  2732. sched->summary = sched->summary_only;
  2733. if (!sched->summary_only)
  2734. timehist_header(sched);
  2735. err = perf_session__process_events(session);
  2736. if (err) {
  2737. pr_err("Failed to process events, error %d", err);
  2738. goto out;
  2739. }
  2740. sched->nr_events = evlist->stats.nr_events[0];
  2741. sched->nr_lost_events = evlist->stats.total_lost;
  2742. sched->nr_lost_chunks = evlist->stats.nr_events[PERF_RECORD_LOST];
  2743. if (sched->summary)
  2744. timehist_print_summary(sched, session);
  2745. out:
  2746. free_idle_threads();
  2747. perf_session__delete(session);
  2748. return err;
  2749. }
  2750. static void print_bad_events(struct perf_sched *sched)
  2751. {
  2752. if (sched->nr_unordered_timestamps && sched->nr_timestamps) {
  2753. printf(" INFO: %.3f%% unordered timestamps (%ld out of %ld)\n",
  2754. (double)sched->nr_unordered_timestamps/(double)sched->nr_timestamps*100.0,
  2755. sched->nr_unordered_timestamps, sched->nr_timestamps);
  2756. }
  2757. if (sched->nr_lost_events && sched->nr_events) {
  2758. printf(" INFO: %.3f%% lost events (%ld out of %ld, in %ld chunks)\n",
  2759. (double)sched->nr_lost_events/(double)sched->nr_events * 100.0,
  2760. sched->nr_lost_events, sched->nr_events, sched->nr_lost_chunks);
  2761. }
  2762. if (sched->nr_context_switch_bugs && sched->nr_timestamps) {
  2763. printf(" INFO: %.3f%% context switch bugs (%ld out of %ld)",
  2764. (double)sched->nr_context_switch_bugs/(double)sched->nr_timestamps*100.0,
  2765. sched->nr_context_switch_bugs, sched->nr_timestamps);
  2766. if (sched->nr_lost_events)
  2767. printf(" (due to lost events?)");
  2768. printf("\n");
  2769. }
  2770. }
  2771. static void __merge_work_atoms(struct rb_root_cached *root, struct work_atoms *data)
  2772. {
  2773. struct rb_node **new = &(root->rb_root.rb_node), *parent = NULL;
  2774. struct work_atoms *this;
  2775. const char *comm = thread__comm_str(data->thread), *this_comm;
  2776. bool leftmost = true;
  2777. while (*new) {
  2778. int cmp;
  2779. this = container_of(*new, struct work_atoms, node);
  2780. parent = *new;
  2781. this_comm = thread__comm_str(this->thread);
  2782. cmp = strcmp(comm, this_comm);
  2783. if (cmp > 0) {
  2784. new = &((*new)->rb_left);
  2785. } else if (cmp < 0) {
  2786. new = &((*new)->rb_right);
  2787. leftmost = false;
  2788. } else {
  2789. this->num_merged++;
  2790. this->total_runtime += data->total_runtime;
  2791. this->nb_atoms += data->nb_atoms;
  2792. this->total_lat += data->total_lat;
  2793. list_splice_init(&data->work_list, &this->work_list);
  2794. if (this->max_lat < data->max_lat) {
  2795. this->max_lat = data->max_lat;
  2796. this->max_lat_start = data->max_lat_start;
  2797. this->max_lat_end = data->max_lat_end;
  2798. }
  2799. free_work_atoms(data);
  2800. return;
  2801. }
  2802. }
  2803. data->num_merged++;
  2804. rb_link_node(&data->node, parent, new);
  2805. rb_insert_color_cached(&data->node, root, leftmost);
  2806. }
  2807. static void perf_sched__merge_lat(struct perf_sched *sched)
  2808. {
  2809. struct work_atoms *data;
  2810. struct rb_node *node;
  2811. if (sched->skip_merge)
  2812. return;
  2813. while ((node = rb_first_cached(&sched->atom_root))) {
  2814. rb_erase_cached(node, &sched->atom_root);
  2815. data = rb_entry(node, struct work_atoms, node);
  2816. __merge_work_atoms(&sched->merged_atom_root, data);
  2817. }
  2818. }
  2819. static int setup_cpus_switch_event(struct perf_sched *sched)
  2820. {
  2821. unsigned int i;
  2822. sched->cpu_last_switched = calloc(MAX_CPUS, sizeof(*(sched->cpu_last_switched)));
  2823. if (!sched->cpu_last_switched)
  2824. return -1;
  2825. sched->curr_pid = malloc(MAX_CPUS * sizeof(*(sched->curr_pid)));
  2826. if (!sched->curr_pid) {
  2827. zfree(&sched->cpu_last_switched);
  2828. return -1;
  2829. }
  2830. for (i = 0; i < MAX_CPUS; i++)
  2831. sched->curr_pid[i] = -1;
  2832. return 0;
  2833. }
  2834. static void free_cpus_switch_event(struct perf_sched *sched)
  2835. {
  2836. zfree(&sched->curr_pid);
  2837. zfree(&sched->cpu_last_switched);
  2838. }
  2839. static int perf_sched__lat(struct perf_sched *sched)
  2840. {
  2841. int rc = -1;
  2842. struct rb_node *next;
  2843. setup_pager();
  2844. if (setup_cpus_switch_event(sched))
  2845. return rc;
  2846. if (perf_sched__read_events(sched))
  2847. goto out_free_cpus_switch_event;
  2848. perf_sched__merge_lat(sched);
  2849. perf_sched__sort_lat(sched);
  2850. printf("\n -------------------------------------------------------------------------------------------------------------------------------------------\n");
  2851. printf(" Task | Runtime ms | Count | Avg delay ms | Max delay ms | Max delay start | Max delay end |\n");
  2852. printf(" -------------------------------------------------------------------------------------------------------------------------------------------\n");
  2853. next = rb_first_cached(&sched->sorted_atom_root);
  2854. while (next) {
  2855. struct work_atoms *work_list;
  2856. work_list = rb_entry(next, struct work_atoms, node);
  2857. output_lat_thread(sched, work_list);
  2858. next = rb_next(next);
  2859. }
  2860. printf(" -----------------------------------------------------------------------------------------------------------------\n");
  2861. printf(" TOTAL: |%11.3f ms |%9" PRIu64 " |\n",
  2862. (double)sched->all_runtime / NSEC_PER_MSEC, sched->all_count);
  2863. printf(" ---------------------------------------------------\n");
  2864. print_bad_events(sched);
  2865. printf("\n");
  2866. rc = 0;
  2867. while ((next = rb_first_cached(&sched->sorted_atom_root))) {
  2868. struct work_atoms *data;
  2869. data = rb_entry(next, struct work_atoms, node);
  2870. rb_erase_cached(next, &sched->sorted_atom_root);
  2871. free_work_atoms(data);
  2872. }
  2873. out_free_cpus_switch_event:
  2874. free_cpus_switch_event(sched);
  2875. return rc;
  2876. }
  2877. static int setup_map_cpus(struct perf_sched *sched)
  2878. {
  2879. sched->max_cpu.cpu = sysconf(_SC_NPROCESSORS_CONF);
  2880. if (sched->map.comp) {
  2881. sched->map.comp_cpus = zalloc(sched->max_cpu.cpu * sizeof(int));
  2882. if (!sched->map.comp_cpus)
  2883. return -1;
  2884. }
  2885. if (sched->map.cpus_str) {
  2886. sched->map.cpus = perf_cpu_map__new(sched->map.cpus_str);
  2887. if (!sched->map.cpus) {
  2888. pr_err("failed to get cpus map from %s\n", sched->map.cpus_str);
  2889. zfree(&sched->map.comp_cpus);
  2890. return -1;
  2891. }
  2892. }
  2893. return 0;
  2894. }
  2895. static int setup_color_pids(struct perf_sched *sched)
  2896. {
  2897. struct perf_thread_map *map;
  2898. if (!sched->map.color_pids_str)
  2899. return 0;
  2900. map = thread_map__new_by_tid_str(sched->map.color_pids_str);
  2901. if (!map) {
  2902. pr_err("failed to get thread map from %s\n", sched->map.color_pids_str);
  2903. return -1;
  2904. }
  2905. sched->map.color_pids = map;
  2906. return 0;
  2907. }
  2908. static int setup_color_cpus(struct perf_sched *sched)
  2909. {
  2910. struct perf_cpu_map *map;
  2911. if (!sched->map.color_cpus_str)
  2912. return 0;
  2913. map = perf_cpu_map__new(sched->map.color_cpus_str);
  2914. if (!map) {
  2915. pr_err("failed to get thread map from %s\n", sched->map.color_cpus_str);
  2916. return -1;
  2917. }
  2918. sched->map.color_cpus = map;
  2919. return 0;
  2920. }
  2921. static int perf_sched__map(struct perf_sched *sched)
  2922. {
  2923. int rc = -1;
  2924. sched->curr_thread = calloc(MAX_CPUS, sizeof(*(sched->curr_thread)));
  2925. if (!sched->curr_thread)
  2926. return rc;
  2927. sched->curr_out_thread = calloc(MAX_CPUS, sizeof(*(sched->curr_out_thread)));
  2928. if (!sched->curr_out_thread)
  2929. goto out_free_curr_thread;
  2930. if (setup_cpus_switch_event(sched))
  2931. goto out_free_curr_out_thread;
  2932. if (setup_map_cpus(sched))
  2933. goto out_free_cpus_switch_event;
  2934. if (setup_color_pids(sched))
  2935. goto out_put_map_cpus;
  2936. if (setup_color_cpus(sched))
  2937. goto out_put_color_pids;
  2938. setup_pager();
  2939. if (perf_sched__read_events(sched))
  2940. goto out_put_color_cpus;
  2941. rc = 0;
  2942. print_bad_events(sched);
  2943. out_put_color_cpus:
  2944. perf_cpu_map__put(sched->map.color_cpus);
  2945. out_put_color_pids:
  2946. perf_thread_map__put(sched->map.color_pids);
  2947. out_put_map_cpus:
  2948. zfree(&sched->map.comp_cpus);
  2949. perf_cpu_map__put(sched->map.cpus);
  2950. out_free_cpus_switch_event:
  2951. free_cpus_switch_event(sched);
  2952. out_free_curr_out_thread:
  2953. for (int i = 0; i < MAX_CPUS; i++)
  2954. thread__put(sched->curr_out_thread[i]);
  2955. zfree(&sched->curr_out_thread);
  2956. out_free_curr_thread:
  2957. for (int i = 0; i < MAX_CPUS; i++)
  2958. thread__put(sched->curr_thread[i]);
  2959. zfree(&sched->curr_thread);
  2960. return rc;
  2961. }
  2962. static int perf_sched__replay(struct perf_sched *sched)
  2963. {
  2964. int ret;
  2965. unsigned long i;
  2966. mutex_init(&sched->start_work_mutex);
  2967. mutex_init(&sched->work_done_wait_mutex);
  2968. ret = setup_cpus_switch_event(sched);
  2969. if (ret)
  2970. goto out_mutex_destroy;
  2971. calibrate_run_measurement_overhead(sched);
  2972. calibrate_sleep_measurement_overhead(sched);
  2973. test_calibrations(sched);
  2974. ret = perf_sched__read_events(sched);
  2975. if (ret)
  2976. goto out_free_cpus_switch_event;
  2977. printf("nr_run_events: %ld\n", sched->nr_run_events);
  2978. printf("nr_sleep_events: %ld\n", sched->nr_sleep_events);
  2979. printf("nr_wakeup_events: %ld\n", sched->nr_wakeup_events);
  2980. if (sched->targetless_wakeups)
  2981. printf("target-less wakeups: %ld\n", sched->targetless_wakeups);
  2982. if (sched->multitarget_wakeups)
  2983. printf("multi-target wakeups: %ld\n", sched->multitarget_wakeups);
  2984. if (sched->nr_run_events_optimized)
  2985. printf("run atoms optimized: %ld\n",
  2986. sched->nr_run_events_optimized);
  2987. print_task_traces(sched);
  2988. add_cross_task_wakeups(sched);
  2989. sched->thread_funcs_exit = false;
  2990. create_tasks(sched);
  2991. printf("------------------------------------------------------------\n");
  2992. if (sched->replay_repeat == 0)
  2993. sched->replay_repeat = UINT_MAX;
  2994. for (i = 0; i < sched->replay_repeat; i++)
  2995. run_one_test(sched);
  2996. sched->thread_funcs_exit = true;
  2997. destroy_tasks(sched);
  2998. out_free_cpus_switch_event:
  2999. free_cpus_switch_event(sched);
  3000. out_mutex_destroy:
  3001. mutex_destroy(&sched->start_work_mutex);
  3002. mutex_destroy(&sched->work_done_wait_mutex);
  3003. return ret;
  3004. }
  3005. static void setup_sorting(struct perf_sched *sched, const struct option *options,
  3006. const char * const usage_msg[])
  3007. {
  3008. char *tmp, *tok, *str = strdup(sched->sort_order);
  3009. for (tok = strtok_r(str, ", ", &tmp);
  3010. tok; tok = strtok_r(NULL, ", ", &tmp)) {
  3011. if (sort_dimension__add(tok, &sched->sort_list) < 0) {
  3012. usage_with_options_msg(usage_msg, options,
  3013. "Unknown --sort key: `%s'", tok);
  3014. }
  3015. }
  3016. free(str);
  3017. sort_dimension__add("pid", &sched->cmp_pid);
  3018. }
  3019. static bool schedstat_events_exposed(void)
  3020. {
  3021. /*
  3022. * Select "sched:sched_stat_wait" event to check
  3023. * whether schedstat tracepoints are exposed.
  3024. */
  3025. return IS_ERR(trace_event__tp_format("sched", "sched_stat_wait")) ?
  3026. false : true;
  3027. }
  3028. static int __cmd_record(int argc, const char **argv)
  3029. {
  3030. unsigned int rec_argc, i, j;
  3031. char **rec_argv;
  3032. const char **rec_argv_copy;
  3033. const char * const record_args[] = {
  3034. "record",
  3035. "-a",
  3036. "-R",
  3037. "-m", "1024",
  3038. "-c", "1",
  3039. "-e", "sched:sched_switch",
  3040. "-e", "sched:sched_stat_runtime",
  3041. "-e", "sched:sched_process_fork",
  3042. "-e", "sched:sched_wakeup_new",
  3043. "-e", "sched:sched_migrate_task",
  3044. };
  3045. /*
  3046. * The tracepoints trace_sched_stat_{wait, sleep, iowait}
  3047. * are not exposed to user if CONFIG_SCHEDSTATS is not set,
  3048. * to prevent "perf sched record" execution failure, determine
  3049. * whether to record schedstat events according to actual situation.
  3050. */
  3051. const char * const schedstat_args[] = {
  3052. "-e", "sched:sched_stat_wait",
  3053. "-e", "sched:sched_stat_sleep",
  3054. "-e", "sched:sched_stat_iowait",
  3055. };
  3056. unsigned int schedstat_argc = schedstat_events_exposed() ?
  3057. ARRAY_SIZE(schedstat_args) : 0;
  3058. struct tep_event *waking_event;
  3059. int ret;
  3060. /*
  3061. * +2 for either "-e", "sched:sched_wakeup" or
  3062. * "-e", "sched:sched_waking"
  3063. */
  3064. rec_argc = ARRAY_SIZE(record_args) + 2 + schedstat_argc + argc - 1;
  3065. rec_argv = calloc(rec_argc + 1, sizeof(char *));
  3066. if (rec_argv == NULL)
  3067. return -ENOMEM;
  3068. rec_argv_copy = calloc(rec_argc + 1, sizeof(char *));
  3069. if (rec_argv_copy == NULL) {
  3070. free(rec_argv);
  3071. return -ENOMEM;
  3072. }
  3073. for (i = 0; i < ARRAY_SIZE(record_args); i++)
  3074. rec_argv[i] = strdup(record_args[i]);
  3075. rec_argv[i++] = strdup("-e");
  3076. waking_event = trace_event__tp_format("sched", "sched_waking");
  3077. if (!IS_ERR(waking_event))
  3078. rec_argv[i++] = strdup("sched:sched_waking");
  3079. else
  3080. rec_argv[i++] = strdup("sched:sched_wakeup");
  3081. for (j = 0; j < schedstat_argc; j++)
  3082. rec_argv[i++] = strdup(schedstat_args[j]);
  3083. for (j = 1; j < (unsigned int)argc; j++, i++)
  3084. rec_argv[i] = strdup(argv[j]);
  3085. BUG_ON(i != rec_argc);
  3086. memcpy(rec_argv_copy, rec_argv, sizeof(char *) * rec_argc);
  3087. ret = cmd_record(rec_argc, rec_argv_copy);
  3088. for (i = 0; i < rec_argc; i++)
  3089. free(rec_argv[i]);
  3090. free(rec_argv);
  3091. free(rec_argv_copy);
  3092. return ret;
  3093. }
  3094. int cmd_sched(int argc, const char **argv)
  3095. {
  3096. static const char default_sort_order[] = "avg, max, switch, runtime";
  3097. struct perf_sched sched = {
  3098. .cmp_pid = LIST_HEAD_INIT(sched.cmp_pid),
  3099. .sort_list = LIST_HEAD_INIT(sched.sort_list),
  3100. .sort_order = default_sort_order,
  3101. .replay_repeat = 10,
  3102. .profile_cpu = -1,
  3103. .next_shortname1 = 'A',
  3104. .next_shortname2 = '0',
  3105. .skip_merge = 0,
  3106. .show_callchain = 1,
  3107. .max_stack = 5,
  3108. };
  3109. const struct option sched_options[] = {
  3110. OPT_STRING('i', "input", &input_name, "file",
  3111. "input file name"),
  3112. OPT_INCR('v', "verbose", &verbose,
  3113. "be more verbose (show symbol address, etc)"),
  3114. OPT_BOOLEAN('D', "dump-raw-trace", &dump_trace,
  3115. "dump raw trace in ASCII"),
  3116. OPT_BOOLEAN('f', "force", &sched.force, "don't complain, do it"),
  3117. OPT_END()
  3118. };
  3119. const struct option latency_options[] = {
  3120. OPT_STRING('s', "sort", &sched.sort_order, "key[,key2...]",
  3121. "sort by key(s): runtime, switch, avg, max"),
  3122. OPT_INTEGER('C', "CPU", &sched.profile_cpu,
  3123. "CPU to profile on"),
  3124. OPT_BOOLEAN('p', "pids", &sched.skip_merge,
  3125. "latency stats per pid instead of per comm"),
  3126. OPT_PARENT(sched_options)
  3127. };
  3128. const struct option replay_options[] = {
  3129. OPT_UINTEGER('r', "repeat", &sched.replay_repeat,
  3130. "repeat the workload replay N times (0: infinite)"),
  3131. OPT_PARENT(sched_options)
  3132. };
  3133. const struct option map_options[] = {
  3134. OPT_BOOLEAN(0, "compact", &sched.map.comp,
  3135. "map output in compact mode"),
  3136. OPT_STRING(0, "color-pids", &sched.map.color_pids_str, "pids",
  3137. "highlight given pids in map"),
  3138. OPT_STRING(0, "color-cpus", &sched.map.color_cpus_str, "cpus",
  3139. "highlight given CPUs in map"),
  3140. OPT_STRING(0, "cpus", &sched.map.cpus_str, "cpus",
  3141. "display given CPUs in map"),
  3142. OPT_STRING(0, "task-name", &sched.map.task_name, "task",
  3143. "map output only for the given task name(s)."),
  3144. OPT_BOOLEAN(0, "fuzzy-name", &sched.map.fuzzy,
  3145. "given command name can be partially matched (fuzzy matching)"),
  3146. OPT_PARENT(sched_options)
  3147. };
  3148. const struct option timehist_options[] = {
  3149. OPT_STRING('k', "vmlinux", &symbol_conf.vmlinux_name,
  3150. "file", "vmlinux pathname"),
  3151. OPT_STRING(0, "kallsyms", &symbol_conf.kallsyms_name,
  3152. "file", "kallsyms pathname"),
  3153. OPT_BOOLEAN('g', "call-graph", &sched.show_callchain,
  3154. "Display call chains if present (default on)"),
  3155. OPT_UINTEGER(0, "max-stack", &sched.max_stack,
  3156. "Maximum number of functions to display backtrace."),
  3157. OPT_STRING(0, "symfs", &symbol_conf.symfs, "directory",
  3158. "Look for files with symbols relative to this directory"),
  3159. OPT_BOOLEAN('s', "summary", &sched.summary_only,
  3160. "Show only syscall summary with statistics"),
  3161. OPT_BOOLEAN('S', "with-summary", &sched.summary,
  3162. "Show all syscalls and summary with statistics"),
  3163. OPT_BOOLEAN('w', "wakeups", &sched.show_wakeups, "Show wakeup events"),
  3164. OPT_BOOLEAN('n', "next", &sched.show_next, "Show next task"),
  3165. OPT_BOOLEAN('M', "migrations", &sched.show_migrations, "Show migration events"),
  3166. OPT_BOOLEAN('V', "cpu-visual", &sched.show_cpu_visual, "Add CPU visual"),
  3167. OPT_BOOLEAN('I', "idle-hist", &sched.idle_hist, "Show idle events only"),
  3168. OPT_STRING(0, "time", &sched.time_str, "str",
  3169. "Time span for analysis (start,stop)"),
  3170. OPT_BOOLEAN(0, "state", &sched.show_state, "Show task state when sched-out"),
  3171. OPT_STRING('p', "pid", &symbol_conf.pid_list_str, "pid[,pid...]",
  3172. "analyze events only for given process id(s)"),
  3173. OPT_STRING('t', "tid", &symbol_conf.tid_list_str, "tid[,tid...]",
  3174. "analyze events only for given thread id(s)"),
  3175. OPT_STRING('C', "cpu", &cpu_list, "cpu", "list of cpus to profile"),
  3176. OPT_BOOLEAN(0, "show-prio", &sched.show_prio, "Show task priority"),
  3177. OPT_STRING(0, "prio", &sched.prio_str, "prio",
  3178. "analyze events only for given task priority(ies)"),
  3179. OPT_PARENT(sched_options)
  3180. };
  3181. const char * const latency_usage[] = {
  3182. "perf sched latency [<options>]",
  3183. NULL
  3184. };
  3185. const char * const replay_usage[] = {
  3186. "perf sched replay [<options>]",
  3187. NULL
  3188. };
  3189. const char * const map_usage[] = {
  3190. "perf sched map [<options>]",
  3191. NULL
  3192. };
  3193. const char * const timehist_usage[] = {
  3194. "perf sched timehist [<options>]",
  3195. NULL
  3196. };
  3197. const char *const sched_subcommands[] = { "record", "latency", "map",
  3198. "replay", "script",
  3199. "timehist", NULL };
  3200. const char *sched_usage[] = {
  3201. NULL,
  3202. NULL
  3203. };
  3204. struct trace_sched_handler lat_ops = {
  3205. .wakeup_event = latency_wakeup_event,
  3206. .switch_event = latency_switch_event,
  3207. .runtime_event = latency_runtime_event,
  3208. .migrate_task_event = latency_migrate_task_event,
  3209. };
  3210. struct trace_sched_handler map_ops = {
  3211. .switch_event = map_switch_event,
  3212. };
  3213. struct trace_sched_handler replay_ops = {
  3214. .wakeup_event = replay_wakeup_event,
  3215. .switch_event = replay_switch_event,
  3216. .fork_event = replay_fork_event,
  3217. };
  3218. int ret;
  3219. perf_tool__init(&sched.tool, /*ordered_events=*/true);
  3220. sched.tool.sample = perf_sched__process_tracepoint_sample;
  3221. sched.tool.comm = perf_sched__process_comm;
  3222. sched.tool.namespaces = perf_event__process_namespaces;
  3223. sched.tool.lost = perf_event__process_lost;
  3224. sched.tool.fork = perf_sched__process_fork_event;
  3225. argc = parse_options_subcommand(argc, argv, sched_options, sched_subcommands,
  3226. sched_usage, PARSE_OPT_STOP_AT_NON_OPTION);
  3227. if (!argc)
  3228. usage_with_options(sched_usage, sched_options);
  3229. thread__set_priv_destructor(free);
  3230. /*
  3231. * Aliased to 'perf script' for now:
  3232. */
  3233. if (!strcmp(argv[0], "script")) {
  3234. ret = cmd_script(argc, argv);
  3235. } else if (strlen(argv[0]) > 2 && strstarts("record", argv[0])) {
  3236. ret = __cmd_record(argc, argv);
  3237. } else if (strlen(argv[0]) > 2 && strstarts("latency", argv[0])) {
  3238. sched.tp_handler = &lat_ops;
  3239. if (argc > 1) {
  3240. argc = parse_options(argc, argv, latency_options, latency_usage, 0);
  3241. if (argc)
  3242. usage_with_options(latency_usage, latency_options);
  3243. }
  3244. setup_sorting(&sched, latency_options, latency_usage);
  3245. ret = perf_sched__lat(&sched);
  3246. } else if (!strcmp(argv[0], "map")) {
  3247. if (argc) {
  3248. argc = parse_options(argc, argv, map_options, map_usage, 0);
  3249. if (argc)
  3250. usage_with_options(map_usage, map_options);
  3251. if (sched.map.task_name) {
  3252. sched.map.task_names = strlist__new(sched.map.task_name, NULL);
  3253. if (sched.map.task_names == NULL) {
  3254. fprintf(stderr, "Failed to parse task names\n");
  3255. ret = -1;
  3256. goto out;
  3257. }
  3258. }
  3259. }
  3260. sched.tp_handler = &map_ops;
  3261. setup_sorting(&sched, latency_options, latency_usage);
  3262. ret = perf_sched__map(&sched);
  3263. } else if (strlen(argv[0]) > 2 && strstarts("replay", argv[0])) {
  3264. sched.tp_handler = &replay_ops;
  3265. if (argc) {
  3266. argc = parse_options(argc, argv, replay_options, replay_usage, 0);
  3267. if (argc)
  3268. usage_with_options(replay_usage, replay_options);
  3269. }
  3270. ret = perf_sched__replay(&sched);
  3271. } else if (!strcmp(argv[0], "timehist")) {
  3272. if (argc) {
  3273. argc = parse_options(argc, argv, timehist_options,
  3274. timehist_usage, 0);
  3275. if (argc)
  3276. usage_with_options(timehist_usage, timehist_options);
  3277. }
  3278. if ((sched.show_wakeups || sched.show_next) &&
  3279. sched.summary_only) {
  3280. pr_err(" Error: -s and -[n|w] are mutually exclusive.\n");
  3281. parse_options_usage(timehist_usage, timehist_options, "s", true);
  3282. if (sched.show_wakeups)
  3283. parse_options_usage(NULL, timehist_options, "w", true);
  3284. if (sched.show_next)
  3285. parse_options_usage(NULL, timehist_options, "n", true);
  3286. ret = -EINVAL;
  3287. goto out;
  3288. }
  3289. ret = symbol__validate_sym_arguments();
  3290. if (!ret)
  3291. ret = perf_sched__timehist(&sched);
  3292. } else {
  3293. usage_with_options(sched_usage, sched_options);
  3294. }
  3295. out:
  3296. /* free usage string allocated by parse_options_subcommand */
  3297. free((void *)sched_usage[0]);
  3298. return ret;
  3299. }