builtin-sched.c 86 KB

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