builtin-sched.c 88 KB

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