builtin-sched.c 87 KB

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