builtin-sched.c 87 KB

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