builtin-sched.c 86 KB

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