builtin-sched.c 91 KB

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