builtin-sched.c 85 KB

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