builtin-lock.c 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000
  1. // SPDX-License-Identifier: GPL-2.0
  2. #include <errno.h>
  3. #include <inttypes.h>
  4. #include "builtin.h"
  5. #include "perf.h"
  6. #include "util/evlist.h" // for struct evsel_str_handler
  7. #include "util/evsel.h"
  8. #include "util/symbol.h"
  9. #include "util/thread.h"
  10. #include "util/header.h"
  11. #include "util/target.h"
  12. #include "util/callchain.h"
  13. #include "util/lock-contention.h"
  14. #include <subcmd/pager.h>
  15. #include <subcmd/parse-options.h>
  16. #include "util/trace-event.h"
  17. #include "util/tracepoint.h"
  18. #include "util/debug.h"
  19. #include "util/session.h"
  20. #include "util/tool.h"
  21. #include "util/data.h"
  22. #include "util/string2.h"
  23. #include "util/map.h"
  24. #include <sys/types.h>
  25. #include <sys/prctl.h>
  26. #include <semaphore.h>
  27. #include <math.h>
  28. #include <limits.h>
  29. #include <linux/list.h>
  30. #include <linux/hash.h>
  31. #include <linux/kernel.h>
  32. #include <linux/zalloc.h>
  33. #include <linux/err.h>
  34. #include <linux/stringify.h>
  35. static struct perf_session *session;
  36. static struct target target;
  37. /* based on kernel/lockdep.c */
  38. #define LOCKHASH_BITS 12
  39. #define LOCKHASH_SIZE (1UL << LOCKHASH_BITS)
  40. static struct hlist_head lockhash_table[LOCKHASH_SIZE];
  41. #define __lockhashfn(key) hash_long((unsigned long)key, LOCKHASH_BITS)
  42. #define lockhashentry(key) (lockhash_table + __lockhashfn((key)))
  43. static struct rb_root thread_stats;
  44. static bool combine_locks;
  45. static bool show_thread_stats;
  46. static bool use_bpf;
  47. static unsigned long bpf_map_entries = 10240;
  48. static int max_stack_depth = CONTENTION_STACK_DEPTH;
  49. static int stack_skip = CONTENTION_STACK_SKIP;
  50. static int print_nr_entries = INT_MAX / 2;
  51. static enum {
  52. LOCK_AGGR_ADDR,
  53. LOCK_AGGR_TASK,
  54. LOCK_AGGR_CALLER,
  55. } aggr_mode = LOCK_AGGR_ADDR;
  56. static u64 sched_text_start;
  57. static u64 sched_text_end;
  58. static u64 lock_text_start;
  59. static u64 lock_text_end;
  60. static struct thread_stat *thread_stat_find(u32 tid)
  61. {
  62. struct rb_node *node;
  63. struct thread_stat *st;
  64. node = thread_stats.rb_node;
  65. while (node) {
  66. st = container_of(node, struct thread_stat, rb);
  67. if (st->tid == tid)
  68. return st;
  69. else if (tid < st->tid)
  70. node = node->rb_left;
  71. else
  72. node = node->rb_right;
  73. }
  74. return NULL;
  75. }
  76. static void thread_stat_insert(struct thread_stat *new)
  77. {
  78. struct rb_node **rb = &thread_stats.rb_node;
  79. struct rb_node *parent = NULL;
  80. struct thread_stat *p;
  81. while (*rb) {
  82. p = container_of(*rb, struct thread_stat, rb);
  83. parent = *rb;
  84. if (new->tid < p->tid)
  85. rb = &(*rb)->rb_left;
  86. else if (new->tid > p->tid)
  87. rb = &(*rb)->rb_right;
  88. else
  89. BUG_ON("inserting invalid thread_stat\n");
  90. }
  91. rb_link_node(&new->rb, parent, rb);
  92. rb_insert_color(&new->rb, &thread_stats);
  93. }
  94. static struct thread_stat *thread_stat_findnew_after_first(u32 tid)
  95. {
  96. struct thread_stat *st;
  97. st = thread_stat_find(tid);
  98. if (st)
  99. return st;
  100. st = zalloc(sizeof(struct thread_stat));
  101. if (!st) {
  102. pr_err("memory allocation failed\n");
  103. return NULL;
  104. }
  105. st->tid = tid;
  106. INIT_LIST_HEAD(&st->seq_list);
  107. thread_stat_insert(st);
  108. return st;
  109. }
  110. static struct thread_stat *thread_stat_findnew_first(u32 tid);
  111. static struct thread_stat *(*thread_stat_findnew)(u32 tid) =
  112. thread_stat_findnew_first;
  113. static struct thread_stat *thread_stat_findnew_first(u32 tid)
  114. {
  115. struct thread_stat *st;
  116. st = zalloc(sizeof(struct thread_stat));
  117. if (!st) {
  118. pr_err("memory allocation failed\n");
  119. return NULL;
  120. }
  121. st->tid = tid;
  122. INIT_LIST_HEAD(&st->seq_list);
  123. rb_link_node(&st->rb, NULL, &thread_stats.rb_node);
  124. rb_insert_color(&st->rb, &thread_stats);
  125. thread_stat_findnew = thread_stat_findnew_after_first;
  126. return st;
  127. }
  128. /* build simple key function one is bigger than two */
  129. #define SINGLE_KEY(member) \
  130. static int lock_stat_key_ ## member(struct lock_stat *one, \
  131. struct lock_stat *two) \
  132. { \
  133. return one->member > two->member; \
  134. }
  135. SINGLE_KEY(nr_acquired)
  136. SINGLE_KEY(nr_contended)
  137. SINGLE_KEY(avg_wait_time)
  138. SINGLE_KEY(wait_time_total)
  139. SINGLE_KEY(wait_time_max)
  140. static int lock_stat_key_wait_time_min(struct lock_stat *one,
  141. struct lock_stat *two)
  142. {
  143. u64 s1 = one->wait_time_min;
  144. u64 s2 = two->wait_time_min;
  145. if (s1 == ULLONG_MAX)
  146. s1 = 0;
  147. if (s2 == ULLONG_MAX)
  148. s2 = 0;
  149. return s1 > s2;
  150. }
  151. struct lock_key {
  152. /*
  153. * name: the value for specify by user
  154. * this should be simpler than raw name of member
  155. * e.g. nr_acquired -> acquired, wait_time_total -> wait_total
  156. */
  157. const char *name;
  158. /* header: the string printed on the header line */
  159. const char *header;
  160. /* len: the printing width of the field */
  161. int len;
  162. /* key: a pointer to function to compare two lock stats for sorting */
  163. int (*key)(struct lock_stat*, struct lock_stat*);
  164. /* print: a pointer to function to print a given lock stats */
  165. void (*print)(struct lock_key*, struct lock_stat*);
  166. /* list: list entry to link this */
  167. struct list_head list;
  168. };
  169. static void lock_stat_key_print_time(unsigned long long nsec, int len)
  170. {
  171. static const struct {
  172. float base;
  173. const char *unit;
  174. } table[] = {
  175. { 1e9 * 3600, "h " },
  176. { 1e9 * 60, "m " },
  177. { 1e9, "s " },
  178. { 1e6, "ms" },
  179. { 1e3, "us" },
  180. { 0, NULL },
  181. };
  182. for (int i = 0; table[i].unit; i++) {
  183. if (nsec < table[i].base)
  184. continue;
  185. pr_info("%*.2f %s", len - 3, nsec / table[i].base, table[i].unit);
  186. return;
  187. }
  188. pr_info("%*llu %s", len - 3, nsec, "ns");
  189. }
  190. #define PRINT_KEY(member) \
  191. static void lock_stat_key_print_ ## member(struct lock_key *key, \
  192. struct lock_stat *ls) \
  193. { \
  194. pr_info("%*llu", key->len, (unsigned long long)ls->member); \
  195. }
  196. #define PRINT_TIME(member) \
  197. static void lock_stat_key_print_ ## member(struct lock_key *key, \
  198. struct lock_stat *ls) \
  199. { \
  200. lock_stat_key_print_time((unsigned long long)ls->member, key->len); \
  201. }
  202. PRINT_KEY(nr_acquired)
  203. PRINT_KEY(nr_contended)
  204. PRINT_TIME(avg_wait_time)
  205. PRINT_TIME(wait_time_total)
  206. PRINT_TIME(wait_time_max)
  207. static void lock_stat_key_print_wait_time_min(struct lock_key *key,
  208. struct lock_stat *ls)
  209. {
  210. u64 wait_time = ls->wait_time_min;
  211. if (wait_time == ULLONG_MAX)
  212. wait_time = 0;
  213. lock_stat_key_print_time(wait_time, key->len);
  214. }
  215. static const char *sort_key = "acquired";
  216. static int (*compare)(struct lock_stat *, struct lock_stat *);
  217. static struct rb_root sorted; /* place to store intermediate data */
  218. static struct rb_root result; /* place to store sorted data */
  219. static LIST_HEAD(lock_keys);
  220. static const char *output_fields;
  221. #define DEF_KEY_LOCK(name, header, fn_suffix, len) \
  222. { #name, header, len, lock_stat_key_ ## fn_suffix, lock_stat_key_print_ ## fn_suffix, {} }
  223. static struct lock_key report_keys[] = {
  224. DEF_KEY_LOCK(acquired, "acquired", nr_acquired, 10),
  225. DEF_KEY_LOCK(contended, "contended", nr_contended, 10),
  226. DEF_KEY_LOCK(avg_wait, "avg wait", avg_wait_time, 12),
  227. DEF_KEY_LOCK(wait_total, "total wait", wait_time_total, 12),
  228. DEF_KEY_LOCK(wait_max, "max wait", wait_time_max, 12),
  229. DEF_KEY_LOCK(wait_min, "min wait", wait_time_min, 12),
  230. /* extra comparisons much complicated should be here */
  231. { }
  232. };
  233. static struct lock_key contention_keys[] = {
  234. DEF_KEY_LOCK(contended, "contended", nr_contended, 10),
  235. DEF_KEY_LOCK(wait_total, "total wait", wait_time_total, 12),
  236. DEF_KEY_LOCK(wait_max, "max wait", wait_time_max, 12),
  237. DEF_KEY_LOCK(wait_min, "min wait", wait_time_min, 12),
  238. DEF_KEY_LOCK(avg_wait, "avg wait", avg_wait_time, 12),
  239. /* extra comparisons much complicated should be here */
  240. { }
  241. };
  242. static int select_key(bool contention)
  243. {
  244. int i;
  245. struct lock_key *keys = report_keys;
  246. if (contention)
  247. keys = contention_keys;
  248. for (i = 0; keys[i].name; i++) {
  249. if (!strcmp(keys[i].name, sort_key)) {
  250. compare = keys[i].key;
  251. /* selected key should be in the output fields */
  252. if (list_empty(&keys[i].list))
  253. list_add_tail(&keys[i].list, &lock_keys);
  254. return 0;
  255. }
  256. }
  257. pr_err("Unknown compare key: %s\n", sort_key);
  258. return -1;
  259. }
  260. static int add_output_field(bool contention, char *name)
  261. {
  262. int i;
  263. struct lock_key *keys = report_keys;
  264. if (contention)
  265. keys = contention_keys;
  266. for (i = 0; keys[i].name; i++) {
  267. if (strcmp(keys[i].name, name))
  268. continue;
  269. /* prevent double link */
  270. if (list_empty(&keys[i].list))
  271. list_add_tail(&keys[i].list, &lock_keys);
  272. return 0;
  273. }
  274. pr_err("Unknown output field: %s\n", name);
  275. return -1;
  276. }
  277. static int setup_output_field(bool contention, const char *str)
  278. {
  279. char *tok, *tmp, *orig;
  280. int i, ret = 0;
  281. struct lock_key *keys = report_keys;
  282. if (contention)
  283. keys = contention_keys;
  284. /* no output field given: use all of them */
  285. if (str == NULL) {
  286. for (i = 0; keys[i].name; i++)
  287. list_add_tail(&keys[i].list, &lock_keys);
  288. return 0;
  289. }
  290. for (i = 0; keys[i].name; i++)
  291. INIT_LIST_HEAD(&keys[i].list);
  292. orig = tmp = strdup(str);
  293. if (orig == NULL)
  294. return -ENOMEM;
  295. while ((tok = strsep(&tmp, ",")) != NULL){
  296. ret = add_output_field(contention, tok);
  297. if (ret < 0)
  298. break;
  299. }
  300. free(orig);
  301. return ret;
  302. }
  303. static void combine_lock_stats(struct lock_stat *st)
  304. {
  305. struct rb_node **rb = &sorted.rb_node;
  306. struct rb_node *parent = NULL;
  307. struct lock_stat *p;
  308. int ret;
  309. while (*rb) {
  310. p = container_of(*rb, struct lock_stat, rb);
  311. parent = *rb;
  312. if (st->name && p->name)
  313. ret = strcmp(st->name, p->name);
  314. else
  315. ret = !!st->name - !!p->name;
  316. if (ret == 0) {
  317. p->nr_acquired += st->nr_acquired;
  318. p->nr_contended += st->nr_contended;
  319. p->wait_time_total += st->wait_time_total;
  320. if (p->nr_contended)
  321. p->avg_wait_time = p->wait_time_total / p->nr_contended;
  322. if (p->wait_time_min > st->wait_time_min)
  323. p->wait_time_min = st->wait_time_min;
  324. if (p->wait_time_max < st->wait_time_max)
  325. p->wait_time_max = st->wait_time_max;
  326. p->broken |= st->broken;
  327. st->combined = 1;
  328. return;
  329. }
  330. if (ret < 0)
  331. rb = &(*rb)->rb_left;
  332. else
  333. rb = &(*rb)->rb_right;
  334. }
  335. rb_link_node(&st->rb, parent, rb);
  336. rb_insert_color(&st->rb, &sorted);
  337. }
  338. static void insert_to_result(struct lock_stat *st,
  339. int (*bigger)(struct lock_stat *, struct lock_stat *))
  340. {
  341. struct rb_node **rb = &result.rb_node;
  342. struct rb_node *parent = NULL;
  343. struct lock_stat *p;
  344. if (combine_locks && st->combined)
  345. return;
  346. while (*rb) {
  347. p = container_of(*rb, struct lock_stat, rb);
  348. parent = *rb;
  349. if (bigger(st, p))
  350. rb = &(*rb)->rb_left;
  351. else
  352. rb = &(*rb)->rb_right;
  353. }
  354. rb_link_node(&st->rb, parent, rb);
  355. rb_insert_color(&st->rb, &result);
  356. }
  357. /* returns left most element of result, and erase it */
  358. static struct lock_stat *pop_from_result(void)
  359. {
  360. struct rb_node *node = result.rb_node;
  361. if (!node)
  362. return NULL;
  363. while (node->rb_left)
  364. node = node->rb_left;
  365. rb_erase(node, &result);
  366. return container_of(node, struct lock_stat, rb);
  367. }
  368. static struct lock_stat *lock_stat_find(u64 addr)
  369. {
  370. struct hlist_head *entry = lockhashentry(addr);
  371. struct lock_stat *ret;
  372. hlist_for_each_entry(ret, entry, hash_entry) {
  373. if (ret->addr == addr)
  374. return ret;
  375. }
  376. return NULL;
  377. }
  378. static struct lock_stat *lock_stat_findnew(u64 addr, const char *name, int flags)
  379. {
  380. struct hlist_head *entry = lockhashentry(addr);
  381. struct lock_stat *ret, *new;
  382. hlist_for_each_entry(ret, entry, hash_entry) {
  383. if (ret->addr == addr)
  384. return ret;
  385. }
  386. new = zalloc(sizeof(struct lock_stat));
  387. if (!new)
  388. goto alloc_failed;
  389. new->addr = addr;
  390. new->name = strdup(name);
  391. if (!new->name) {
  392. free(new);
  393. goto alloc_failed;
  394. }
  395. new->flags = flags;
  396. new->wait_time_min = ULLONG_MAX;
  397. hlist_add_head(&new->hash_entry, entry);
  398. return new;
  399. alloc_failed:
  400. pr_err("memory allocation failed\n");
  401. return NULL;
  402. }
  403. struct trace_lock_handler {
  404. /* it's used on CONFIG_LOCKDEP */
  405. int (*acquire_event)(struct evsel *evsel,
  406. struct perf_sample *sample);
  407. /* it's used on CONFIG_LOCKDEP && CONFIG_LOCK_STAT */
  408. int (*acquired_event)(struct evsel *evsel,
  409. struct perf_sample *sample);
  410. /* it's used on CONFIG_LOCKDEP && CONFIG_LOCK_STAT */
  411. int (*contended_event)(struct evsel *evsel,
  412. struct perf_sample *sample);
  413. /* it's used on CONFIG_LOCKDEP */
  414. int (*release_event)(struct evsel *evsel,
  415. struct perf_sample *sample);
  416. /* it's used when CONFIG_LOCKDEP is off */
  417. int (*contention_begin_event)(struct evsel *evsel,
  418. struct perf_sample *sample);
  419. /* it's used when CONFIG_LOCKDEP is off */
  420. int (*contention_end_event)(struct evsel *evsel,
  421. struct perf_sample *sample);
  422. };
  423. static struct lock_seq_stat *get_seq(struct thread_stat *ts, u64 addr)
  424. {
  425. struct lock_seq_stat *seq;
  426. list_for_each_entry(seq, &ts->seq_list, list) {
  427. if (seq->addr == addr)
  428. return seq;
  429. }
  430. seq = zalloc(sizeof(struct lock_seq_stat));
  431. if (!seq) {
  432. pr_err("memory allocation failed\n");
  433. return NULL;
  434. }
  435. seq->state = SEQ_STATE_UNINITIALIZED;
  436. seq->addr = addr;
  437. list_add(&seq->list, &ts->seq_list);
  438. return seq;
  439. }
  440. enum broken_state {
  441. BROKEN_ACQUIRE,
  442. BROKEN_ACQUIRED,
  443. BROKEN_CONTENDED,
  444. BROKEN_RELEASE,
  445. BROKEN_MAX,
  446. };
  447. static int bad_hist[BROKEN_MAX];
  448. enum acquire_flags {
  449. TRY_LOCK = 1,
  450. READ_LOCK = 2,
  451. };
  452. static int get_key_by_aggr_mode_simple(u64 *key, u64 addr, u32 tid)
  453. {
  454. switch (aggr_mode) {
  455. case LOCK_AGGR_ADDR:
  456. *key = addr;
  457. break;
  458. case LOCK_AGGR_TASK:
  459. *key = tid;
  460. break;
  461. case LOCK_AGGR_CALLER:
  462. default:
  463. pr_err("Invalid aggregation mode: %d\n", aggr_mode);
  464. return -EINVAL;
  465. }
  466. return 0;
  467. }
  468. static u64 callchain_id(struct evsel *evsel, struct perf_sample *sample);
  469. static int get_key_by_aggr_mode(u64 *key, u64 addr, struct evsel *evsel,
  470. struct perf_sample *sample)
  471. {
  472. if (aggr_mode == LOCK_AGGR_CALLER) {
  473. *key = callchain_id(evsel, sample);
  474. return 0;
  475. }
  476. return get_key_by_aggr_mode_simple(key, addr, sample->tid);
  477. }
  478. static int report_lock_acquire_event(struct evsel *evsel,
  479. struct perf_sample *sample)
  480. {
  481. struct lock_stat *ls;
  482. struct thread_stat *ts;
  483. struct lock_seq_stat *seq;
  484. const char *name = evsel__strval(evsel, sample, "name");
  485. u64 addr = evsel__intval(evsel, sample, "lockdep_addr");
  486. int flag = evsel__intval(evsel, sample, "flags");
  487. u64 key;
  488. int ret;
  489. ret = get_key_by_aggr_mode_simple(&key, addr, sample->tid);
  490. if (ret < 0)
  491. return ret;
  492. ls = lock_stat_findnew(key, name, 0);
  493. if (!ls)
  494. return -ENOMEM;
  495. ts = thread_stat_findnew(sample->tid);
  496. if (!ts)
  497. return -ENOMEM;
  498. seq = get_seq(ts, addr);
  499. if (!seq)
  500. return -ENOMEM;
  501. switch (seq->state) {
  502. case SEQ_STATE_UNINITIALIZED:
  503. case SEQ_STATE_RELEASED:
  504. if (!flag) {
  505. seq->state = SEQ_STATE_ACQUIRING;
  506. } else {
  507. if (flag & TRY_LOCK)
  508. ls->nr_trylock++;
  509. if (flag & READ_LOCK)
  510. ls->nr_readlock++;
  511. seq->state = SEQ_STATE_READ_ACQUIRED;
  512. seq->read_count = 1;
  513. ls->nr_acquired++;
  514. }
  515. break;
  516. case SEQ_STATE_READ_ACQUIRED:
  517. if (flag & READ_LOCK) {
  518. seq->read_count++;
  519. ls->nr_acquired++;
  520. goto end;
  521. } else {
  522. goto broken;
  523. }
  524. break;
  525. case SEQ_STATE_ACQUIRED:
  526. case SEQ_STATE_ACQUIRING:
  527. case SEQ_STATE_CONTENDED:
  528. broken:
  529. /* broken lock sequence */
  530. if (!ls->broken) {
  531. ls->broken = 1;
  532. bad_hist[BROKEN_ACQUIRE]++;
  533. }
  534. list_del_init(&seq->list);
  535. free(seq);
  536. goto end;
  537. default:
  538. BUG_ON("Unknown state of lock sequence found!\n");
  539. break;
  540. }
  541. ls->nr_acquire++;
  542. seq->prev_event_time = sample->time;
  543. end:
  544. return 0;
  545. }
  546. static int report_lock_acquired_event(struct evsel *evsel,
  547. struct perf_sample *sample)
  548. {
  549. struct lock_stat *ls;
  550. struct thread_stat *ts;
  551. struct lock_seq_stat *seq;
  552. u64 contended_term;
  553. const char *name = evsel__strval(evsel, sample, "name");
  554. u64 addr = evsel__intval(evsel, sample, "lockdep_addr");
  555. u64 key;
  556. int ret;
  557. ret = get_key_by_aggr_mode_simple(&key, addr, sample->tid);
  558. if (ret < 0)
  559. return ret;
  560. ls = lock_stat_findnew(key, name, 0);
  561. if (!ls)
  562. return -ENOMEM;
  563. ts = thread_stat_findnew(sample->tid);
  564. if (!ts)
  565. return -ENOMEM;
  566. seq = get_seq(ts, addr);
  567. if (!seq)
  568. return -ENOMEM;
  569. switch (seq->state) {
  570. case SEQ_STATE_UNINITIALIZED:
  571. /* orphan event, do nothing */
  572. return 0;
  573. case SEQ_STATE_ACQUIRING:
  574. break;
  575. case SEQ_STATE_CONTENDED:
  576. contended_term = sample->time - seq->prev_event_time;
  577. ls->wait_time_total += contended_term;
  578. if (contended_term < ls->wait_time_min)
  579. ls->wait_time_min = contended_term;
  580. if (ls->wait_time_max < contended_term)
  581. ls->wait_time_max = contended_term;
  582. break;
  583. case SEQ_STATE_RELEASED:
  584. case SEQ_STATE_ACQUIRED:
  585. case SEQ_STATE_READ_ACQUIRED:
  586. /* broken lock sequence */
  587. if (!ls->broken) {
  588. ls->broken = 1;
  589. bad_hist[BROKEN_ACQUIRED]++;
  590. }
  591. list_del_init(&seq->list);
  592. free(seq);
  593. goto end;
  594. default:
  595. BUG_ON("Unknown state of lock sequence found!\n");
  596. break;
  597. }
  598. seq->state = SEQ_STATE_ACQUIRED;
  599. ls->nr_acquired++;
  600. ls->avg_wait_time = ls->nr_contended ? ls->wait_time_total/ls->nr_contended : 0;
  601. seq->prev_event_time = sample->time;
  602. end:
  603. return 0;
  604. }
  605. static int report_lock_contended_event(struct evsel *evsel,
  606. struct perf_sample *sample)
  607. {
  608. struct lock_stat *ls;
  609. struct thread_stat *ts;
  610. struct lock_seq_stat *seq;
  611. const char *name = evsel__strval(evsel, sample, "name");
  612. u64 addr = evsel__intval(evsel, sample, "lockdep_addr");
  613. u64 key;
  614. int ret;
  615. ret = get_key_by_aggr_mode_simple(&key, addr, sample->tid);
  616. if (ret < 0)
  617. return ret;
  618. ls = lock_stat_findnew(key, name, 0);
  619. if (!ls)
  620. return -ENOMEM;
  621. ts = thread_stat_findnew(sample->tid);
  622. if (!ts)
  623. return -ENOMEM;
  624. seq = get_seq(ts, addr);
  625. if (!seq)
  626. return -ENOMEM;
  627. switch (seq->state) {
  628. case SEQ_STATE_UNINITIALIZED:
  629. /* orphan event, do nothing */
  630. return 0;
  631. case SEQ_STATE_ACQUIRING:
  632. break;
  633. case SEQ_STATE_RELEASED:
  634. case SEQ_STATE_ACQUIRED:
  635. case SEQ_STATE_READ_ACQUIRED:
  636. case SEQ_STATE_CONTENDED:
  637. /* broken lock sequence */
  638. if (!ls->broken) {
  639. ls->broken = 1;
  640. bad_hist[BROKEN_CONTENDED]++;
  641. }
  642. list_del_init(&seq->list);
  643. free(seq);
  644. goto end;
  645. default:
  646. BUG_ON("Unknown state of lock sequence found!\n");
  647. break;
  648. }
  649. seq->state = SEQ_STATE_CONTENDED;
  650. ls->nr_contended++;
  651. ls->avg_wait_time = ls->wait_time_total/ls->nr_contended;
  652. seq->prev_event_time = sample->time;
  653. end:
  654. return 0;
  655. }
  656. static int report_lock_release_event(struct evsel *evsel,
  657. struct perf_sample *sample)
  658. {
  659. struct lock_stat *ls;
  660. struct thread_stat *ts;
  661. struct lock_seq_stat *seq;
  662. const char *name = evsel__strval(evsel, sample, "name");
  663. u64 addr = evsel__intval(evsel, sample, "lockdep_addr");
  664. u64 key;
  665. int ret;
  666. ret = get_key_by_aggr_mode_simple(&key, addr, sample->tid);
  667. if (ret < 0)
  668. return ret;
  669. ls = lock_stat_findnew(key, name, 0);
  670. if (!ls)
  671. return -ENOMEM;
  672. ts = thread_stat_findnew(sample->tid);
  673. if (!ts)
  674. return -ENOMEM;
  675. seq = get_seq(ts, addr);
  676. if (!seq)
  677. return -ENOMEM;
  678. switch (seq->state) {
  679. case SEQ_STATE_UNINITIALIZED:
  680. goto end;
  681. case SEQ_STATE_ACQUIRED:
  682. break;
  683. case SEQ_STATE_READ_ACQUIRED:
  684. seq->read_count--;
  685. BUG_ON(seq->read_count < 0);
  686. if (seq->read_count) {
  687. ls->nr_release++;
  688. goto end;
  689. }
  690. break;
  691. case SEQ_STATE_ACQUIRING:
  692. case SEQ_STATE_CONTENDED:
  693. case SEQ_STATE_RELEASED:
  694. /* broken lock sequence */
  695. if (!ls->broken) {
  696. ls->broken = 1;
  697. bad_hist[BROKEN_RELEASE]++;
  698. }
  699. goto free_seq;
  700. default:
  701. BUG_ON("Unknown state of lock sequence found!\n");
  702. break;
  703. }
  704. ls->nr_release++;
  705. free_seq:
  706. list_del_init(&seq->list);
  707. free(seq);
  708. end:
  709. return 0;
  710. }
  711. bool is_lock_function(struct machine *machine, u64 addr)
  712. {
  713. if (!sched_text_start) {
  714. struct map *kmap;
  715. struct symbol *sym;
  716. sym = machine__find_kernel_symbol_by_name(machine,
  717. "__sched_text_start",
  718. &kmap);
  719. if (!sym) {
  720. /* to avoid retry */
  721. sched_text_start = 1;
  722. return false;
  723. }
  724. sched_text_start = kmap->unmap_ip(kmap, sym->start);
  725. /* should not fail from here */
  726. sym = machine__find_kernel_symbol_by_name(machine,
  727. "__sched_text_end",
  728. &kmap);
  729. sched_text_end = kmap->unmap_ip(kmap, sym->start);
  730. sym = machine__find_kernel_symbol_by_name(machine,
  731. "__lock_text_start",
  732. &kmap);
  733. lock_text_start = kmap->unmap_ip(kmap, sym->start);
  734. sym = machine__find_kernel_symbol_by_name(machine,
  735. "__lock_text_end",
  736. &kmap);
  737. lock_text_end = kmap->unmap_ip(kmap, sym->start);
  738. }
  739. /* failed to get kernel symbols */
  740. if (sched_text_start == 1)
  741. return false;
  742. /* mutex and rwsem functions are in sched text section */
  743. if (sched_text_start <= addr && addr < sched_text_end)
  744. return true;
  745. /* spinlock functions are in lock text section */
  746. if (lock_text_start <= addr && addr < lock_text_end)
  747. return true;
  748. return false;
  749. }
  750. static int get_symbol_name_offset(struct map *map, struct symbol *sym, u64 ip,
  751. char *buf, int size)
  752. {
  753. u64 offset;
  754. if (map == NULL || sym == NULL) {
  755. buf[0] = '\0';
  756. return 0;
  757. }
  758. offset = map->map_ip(map, ip) - sym->start;
  759. if (offset)
  760. return scnprintf(buf, size, "%s+%#lx", sym->name, offset);
  761. else
  762. return strlcpy(buf, sym->name, size);
  763. }
  764. static int lock_contention_caller(struct evsel *evsel, struct perf_sample *sample,
  765. char *buf, int size)
  766. {
  767. struct thread *thread;
  768. struct callchain_cursor *cursor = &callchain_cursor;
  769. struct machine *machine = &session->machines.host;
  770. struct symbol *sym;
  771. int skip = 0;
  772. int ret;
  773. /* lock names will be replaced to task name later */
  774. if (show_thread_stats)
  775. return -1;
  776. thread = machine__findnew_thread(machine, -1, sample->pid);
  777. if (thread == NULL)
  778. return -1;
  779. /* use caller function name from the callchain */
  780. ret = thread__resolve_callchain(thread, cursor, evsel, sample,
  781. NULL, NULL, max_stack_depth);
  782. if (ret != 0) {
  783. thread__put(thread);
  784. return -1;
  785. }
  786. callchain_cursor_commit(cursor);
  787. thread__put(thread);
  788. while (true) {
  789. struct callchain_cursor_node *node;
  790. node = callchain_cursor_current(cursor);
  791. if (node == NULL)
  792. break;
  793. /* skip first few entries - for lock functions */
  794. if (++skip <= stack_skip)
  795. goto next;
  796. sym = node->ms.sym;
  797. if (sym && !is_lock_function(machine, node->ip)) {
  798. get_symbol_name_offset(node->ms.map, sym, node->ip,
  799. buf, size);
  800. return 0;
  801. }
  802. next:
  803. callchain_cursor_advance(cursor);
  804. }
  805. return -1;
  806. }
  807. static u64 callchain_id(struct evsel *evsel, struct perf_sample *sample)
  808. {
  809. struct callchain_cursor *cursor = &callchain_cursor;
  810. struct machine *machine = &session->machines.host;
  811. struct thread *thread;
  812. u64 hash = 0;
  813. int skip = 0;
  814. int ret;
  815. thread = machine__findnew_thread(machine, -1, sample->pid);
  816. if (thread == NULL)
  817. return -1;
  818. /* use caller function name from the callchain */
  819. ret = thread__resolve_callchain(thread, cursor, evsel, sample,
  820. NULL, NULL, max_stack_depth);
  821. thread__put(thread);
  822. if (ret != 0)
  823. return -1;
  824. callchain_cursor_commit(cursor);
  825. while (true) {
  826. struct callchain_cursor_node *node;
  827. node = callchain_cursor_current(cursor);
  828. if (node == NULL)
  829. break;
  830. /* skip first few entries - for lock functions */
  831. if (++skip <= stack_skip)
  832. goto next;
  833. if (node->ms.sym && is_lock_function(machine, node->ip))
  834. goto next;
  835. hash ^= hash_long((unsigned long)node->ip, 64);
  836. next:
  837. callchain_cursor_advance(cursor);
  838. }
  839. return hash;
  840. }
  841. static u64 *get_callstack(struct perf_sample *sample, int max_stack)
  842. {
  843. u64 *callstack;
  844. u64 i;
  845. int c;
  846. callstack = calloc(max_stack, sizeof(*callstack));
  847. if (callstack == NULL)
  848. return NULL;
  849. for (i = 0, c = 0; i < sample->callchain->nr && c < max_stack; i++) {
  850. u64 ip = sample->callchain->ips[i];
  851. if (ip >= PERF_CONTEXT_MAX)
  852. continue;
  853. callstack[c++] = ip;
  854. }
  855. return callstack;
  856. }
  857. static int report_lock_contention_begin_event(struct evsel *evsel,
  858. struct perf_sample *sample)
  859. {
  860. struct lock_stat *ls;
  861. struct thread_stat *ts;
  862. struct lock_seq_stat *seq;
  863. u64 addr = evsel__intval(evsel, sample, "lock_addr");
  864. u64 key;
  865. int ret;
  866. ret = get_key_by_aggr_mode(&key, addr, evsel, sample);
  867. if (ret < 0)
  868. return ret;
  869. ls = lock_stat_find(key);
  870. if (!ls) {
  871. char buf[128];
  872. const char *caller = buf;
  873. unsigned int flags = evsel__intval(evsel, sample, "flags");
  874. if (lock_contention_caller(evsel, sample, buf, sizeof(buf)) < 0)
  875. caller = "Unknown";
  876. ls = lock_stat_findnew(key, caller, flags);
  877. if (!ls)
  878. return -ENOMEM;
  879. if (aggr_mode == LOCK_AGGR_CALLER && verbose) {
  880. ls->callstack = get_callstack(sample, max_stack_depth);
  881. if (ls->callstack == NULL)
  882. return -ENOMEM;
  883. }
  884. }
  885. ts = thread_stat_findnew(sample->tid);
  886. if (!ts)
  887. return -ENOMEM;
  888. seq = get_seq(ts, addr);
  889. if (!seq)
  890. return -ENOMEM;
  891. switch (seq->state) {
  892. case SEQ_STATE_UNINITIALIZED:
  893. case SEQ_STATE_ACQUIRED:
  894. break;
  895. case SEQ_STATE_CONTENDED:
  896. /*
  897. * It can have nested contention begin with mutex spinning,
  898. * then we would use the original contention begin event and
  899. * ignore the second one.
  900. */
  901. goto end;
  902. case SEQ_STATE_ACQUIRING:
  903. case SEQ_STATE_READ_ACQUIRED:
  904. case SEQ_STATE_RELEASED:
  905. /* broken lock sequence */
  906. if (!ls->broken) {
  907. ls->broken = 1;
  908. bad_hist[BROKEN_CONTENDED]++;
  909. }
  910. list_del_init(&seq->list);
  911. free(seq);
  912. goto end;
  913. default:
  914. BUG_ON("Unknown state of lock sequence found!\n");
  915. break;
  916. }
  917. if (seq->state != SEQ_STATE_CONTENDED) {
  918. seq->state = SEQ_STATE_CONTENDED;
  919. seq->prev_event_time = sample->time;
  920. ls->nr_contended++;
  921. }
  922. end:
  923. return 0;
  924. }
  925. static int report_lock_contention_end_event(struct evsel *evsel,
  926. struct perf_sample *sample)
  927. {
  928. struct lock_stat *ls;
  929. struct thread_stat *ts;
  930. struct lock_seq_stat *seq;
  931. u64 contended_term;
  932. u64 addr = evsel__intval(evsel, sample, "lock_addr");
  933. u64 key;
  934. int ret;
  935. ret = get_key_by_aggr_mode(&key, addr, evsel, sample);
  936. if (ret < 0)
  937. return ret;
  938. ls = lock_stat_find(key);
  939. if (!ls)
  940. return 0;
  941. ts = thread_stat_find(sample->tid);
  942. if (!ts)
  943. return 0;
  944. seq = get_seq(ts, addr);
  945. if (!seq)
  946. return -ENOMEM;
  947. switch (seq->state) {
  948. case SEQ_STATE_UNINITIALIZED:
  949. goto end;
  950. case SEQ_STATE_CONTENDED:
  951. contended_term = sample->time - seq->prev_event_time;
  952. ls->wait_time_total += contended_term;
  953. if (contended_term < ls->wait_time_min)
  954. ls->wait_time_min = contended_term;
  955. if (ls->wait_time_max < contended_term)
  956. ls->wait_time_max = contended_term;
  957. break;
  958. case SEQ_STATE_ACQUIRING:
  959. case SEQ_STATE_ACQUIRED:
  960. case SEQ_STATE_READ_ACQUIRED:
  961. case SEQ_STATE_RELEASED:
  962. /* broken lock sequence */
  963. if (!ls->broken) {
  964. ls->broken = 1;
  965. bad_hist[BROKEN_ACQUIRED]++;
  966. }
  967. list_del_init(&seq->list);
  968. free(seq);
  969. goto end;
  970. default:
  971. BUG_ON("Unknown state of lock sequence found!\n");
  972. break;
  973. }
  974. seq->state = SEQ_STATE_ACQUIRED;
  975. ls->nr_acquired++;
  976. ls->avg_wait_time = ls->wait_time_total/ls->nr_acquired;
  977. end:
  978. return 0;
  979. }
  980. /* lock oriented handlers */
  981. /* TODO: handlers for CPU oriented, thread oriented */
  982. static struct trace_lock_handler report_lock_ops = {
  983. .acquire_event = report_lock_acquire_event,
  984. .acquired_event = report_lock_acquired_event,
  985. .contended_event = report_lock_contended_event,
  986. .release_event = report_lock_release_event,
  987. .contention_begin_event = report_lock_contention_begin_event,
  988. .contention_end_event = report_lock_contention_end_event,
  989. };
  990. static struct trace_lock_handler contention_lock_ops = {
  991. .contention_begin_event = report_lock_contention_begin_event,
  992. .contention_end_event = report_lock_contention_end_event,
  993. };
  994. static struct trace_lock_handler *trace_handler;
  995. static int evsel__process_lock_acquire(struct evsel *evsel, struct perf_sample *sample)
  996. {
  997. if (trace_handler->acquire_event)
  998. return trace_handler->acquire_event(evsel, sample);
  999. return 0;
  1000. }
  1001. static int evsel__process_lock_acquired(struct evsel *evsel, struct perf_sample *sample)
  1002. {
  1003. if (trace_handler->acquired_event)
  1004. return trace_handler->acquired_event(evsel, sample);
  1005. return 0;
  1006. }
  1007. static int evsel__process_lock_contended(struct evsel *evsel, struct perf_sample *sample)
  1008. {
  1009. if (trace_handler->contended_event)
  1010. return trace_handler->contended_event(evsel, sample);
  1011. return 0;
  1012. }
  1013. static int evsel__process_lock_release(struct evsel *evsel, struct perf_sample *sample)
  1014. {
  1015. if (trace_handler->release_event)
  1016. return trace_handler->release_event(evsel, sample);
  1017. return 0;
  1018. }
  1019. static int evsel__process_contention_begin(struct evsel *evsel, struct perf_sample *sample)
  1020. {
  1021. if (trace_handler->contention_begin_event)
  1022. return trace_handler->contention_begin_event(evsel, sample);
  1023. return 0;
  1024. }
  1025. static int evsel__process_contention_end(struct evsel *evsel, struct perf_sample *sample)
  1026. {
  1027. if (trace_handler->contention_end_event)
  1028. return trace_handler->contention_end_event(evsel, sample);
  1029. return 0;
  1030. }
  1031. static void print_bad_events(int bad, int total)
  1032. {
  1033. /* Output for debug, this have to be removed */
  1034. int i;
  1035. int broken = 0;
  1036. const char *name[4] =
  1037. { "acquire", "acquired", "contended", "release" };
  1038. for (i = 0; i < BROKEN_MAX; i++)
  1039. broken += bad_hist[i];
  1040. if (quiet || (broken == 0 && !verbose))
  1041. return;
  1042. pr_info("\n=== output for debug===\n\n");
  1043. pr_info("bad: %d, total: %d\n", bad, total);
  1044. pr_info("bad rate: %.2f %%\n", (double)bad / (double)total * 100);
  1045. pr_info("histogram of events caused bad sequence\n");
  1046. for (i = 0; i < BROKEN_MAX; i++)
  1047. pr_info(" %10s: %d\n", name[i], bad_hist[i]);
  1048. }
  1049. /* TODO: various way to print, coloring, nano or milli sec */
  1050. static void print_result(void)
  1051. {
  1052. struct lock_stat *st;
  1053. struct lock_key *key;
  1054. char cut_name[20];
  1055. int bad, total, printed;
  1056. if (!quiet) {
  1057. pr_info("%20s ", "Name");
  1058. list_for_each_entry(key, &lock_keys, list)
  1059. pr_info("%*s ", key->len, key->header);
  1060. pr_info("\n\n");
  1061. }
  1062. bad = total = printed = 0;
  1063. while ((st = pop_from_result())) {
  1064. total++;
  1065. if (st->broken)
  1066. bad++;
  1067. if (!st->nr_acquired)
  1068. continue;
  1069. bzero(cut_name, 20);
  1070. if (strlen(st->name) < 20) {
  1071. /* output raw name */
  1072. const char *name = st->name;
  1073. if (show_thread_stats) {
  1074. struct thread *t;
  1075. /* st->addr contains tid of thread */
  1076. t = perf_session__findnew(session, st->addr);
  1077. name = thread__comm_str(t);
  1078. }
  1079. pr_info("%20s ", name);
  1080. } else {
  1081. strncpy(cut_name, st->name, 16);
  1082. cut_name[16] = '.';
  1083. cut_name[17] = '.';
  1084. cut_name[18] = '.';
  1085. cut_name[19] = '\0';
  1086. /* cut off name for saving output style */
  1087. pr_info("%20s ", cut_name);
  1088. }
  1089. list_for_each_entry(key, &lock_keys, list) {
  1090. key->print(key, st);
  1091. pr_info(" ");
  1092. }
  1093. pr_info("\n");
  1094. if (++printed >= print_nr_entries)
  1095. break;
  1096. }
  1097. print_bad_events(bad, total);
  1098. }
  1099. static bool info_threads, info_map;
  1100. static void dump_threads(void)
  1101. {
  1102. struct thread_stat *st;
  1103. struct rb_node *node;
  1104. struct thread *t;
  1105. pr_info("%10s: comm\n", "Thread ID");
  1106. node = rb_first(&thread_stats);
  1107. while (node) {
  1108. st = container_of(node, struct thread_stat, rb);
  1109. t = perf_session__findnew(session, st->tid);
  1110. pr_info("%10d: %s\n", st->tid, thread__comm_str(t));
  1111. node = rb_next(node);
  1112. thread__put(t);
  1113. }
  1114. }
  1115. static int compare_maps(struct lock_stat *a, struct lock_stat *b)
  1116. {
  1117. int ret;
  1118. if (a->name && b->name)
  1119. ret = strcmp(a->name, b->name);
  1120. else
  1121. ret = !!a->name - !!b->name;
  1122. if (!ret)
  1123. return a->addr < b->addr;
  1124. else
  1125. return ret < 0;
  1126. }
  1127. static void dump_map(void)
  1128. {
  1129. unsigned int i;
  1130. struct lock_stat *st;
  1131. pr_info("Address of instance: name of class\n");
  1132. for (i = 0; i < LOCKHASH_SIZE; i++) {
  1133. hlist_for_each_entry(st, &lockhash_table[i], hash_entry) {
  1134. insert_to_result(st, compare_maps);
  1135. }
  1136. }
  1137. while ((st = pop_from_result()))
  1138. pr_info(" %#llx: %s\n", (unsigned long long)st->addr, st->name);
  1139. }
  1140. static int dump_info(void)
  1141. {
  1142. int rc = 0;
  1143. if (info_threads)
  1144. dump_threads();
  1145. else if (info_map)
  1146. dump_map();
  1147. else {
  1148. rc = -1;
  1149. pr_err("Unknown type of information\n");
  1150. }
  1151. return rc;
  1152. }
  1153. typedef int (*tracepoint_handler)(struct evsel *evsel,
  1154. struct perf_sample *sample);
  1155. static int process_sample_event(struct perf_tool *tool __maybe_unused,
  1156. union perf_event *event,
  1157. struct perf_sample *sample,
  1158. struct evsel *evsel,
  1159. struct machine *machine)
  1160. {
  1161. int err = 0;
  1162. struct thread *thread = machine__findnew_thread(machine, sample->pid,
  1163. sample->tid);
  1164. if (thread == NULL) {
  1165. pr_debug("problem processing %d event, skipping it.\n",
  1166. event->header.type);
  1167. return -1;
  1168. }
  1169. if (evsel->handler != NULL) {
  1170. tracepoint_handler f = evsel->handler;
  1171. err = f(evsel, sample);
  1172. }
  1173. thread__put(thread);
  1174. return err;
  1175. }
  1176. static void combine_result(void)
  1177. {
  1178. unsigned int i;
  1179. struct lock_stat *st;
  1180. if (!combine_locks)
  1181. return;
  1182. for (i = 0; i < LOCKHASH_SIZE; i++) {
  1183. hlist_for_each_entry(st, &lockhash_table[i], hash_entry) {
  1184. combine_lock_stats(st);
  1185. }
  1186. }
  1187. }
  1188. static void sort_result(void)
  1189. {
  1190. unsigned int i;
  1191. struct lock_stat *st;
  1192. for (i = 0; i < LOCKHASH_SIZE; i++) {
  1193. hlist_for_each_entry(st, &lockhash_table[i], hash_entry) {
  1194. insert_to_result(st, compare);
  1195. }
  1196. }
  1197. }
  1198. static const char *get_type_str(struct lock_stat *st)
  1199. {
  1200. static const struct {
  1201. unsigned int flags;
  1202. const char *name;
  1203. } table[] = {
  1204. { 0, "semaphore" },
  1205. { LCB_F_SPIN, "spinlock" },
  1206. { LCB_F_SPIN | LCB_F_READ, "rwlock:R" },
  1207. { LCB_F_SPIN | LCB_F_WRITE, "rwlock:W"},
  1208. { LCB_F_READ, "rwsem:R" },
  1209. { LCB_F_WRITE, "rwsem:W" },
  1210. { LCB_F_RT, "rtmutex" },
  1211. { LCB_F_RT | LCB_F_READ, "rwlock-rt:R" },
  1212. { LCB_F_RT | LCB_F_WRITE, "rwlock-rt:W"},
  1213. { LCB_F_PERCPU | LCB_F_READ, "pcpu-sem:R" },
  1214. { LCB_F_PERCPU | LCB_F_WRITE, "pcpu-sem:W" },
  1215. { LCB_F_MUTEX, "mutex" },
  1216. { LCB_F_MUTEX | LCB_F_SPIN, "mutex" },
  1217. };
  1218. for (unsigned int i = 0; i < ARRAY_SIZE(table); i++) {
  1219. if (table[i].flags == st->flags)
  1220. return table[i].name;
  1221. }
  1222. return "unknown";
  1223. }
  1224. static void sort_contention_result(void)
  1225. {
  1226. sort_result();
  1227. }
  1228. static void print_contention_result(struct lock_contention *con)
  1229. {
  1230. struct lock_stat *st;
  1231. struct lock_key *key;
  1232. int bad, total, printed;
  1233. if (!quiet) {
  1234. list_for_each_entry(key, &lock_keys, list)
  1235. pr_info("%*s ", key->len, key->header);
  1236. if (show_thread_stats)
  1237. pr_info(" %10s %s\n\n", "pid", "comm");
  1238. else
  1239. pr_info(" %10s %s\n\n", "type", "caller");
  1240. }
  1241. bad = total = printed = 0;
  1242. if (use_bpf)
  1243. bad = bad_hist[BROKEN_CONTENDED];
  1244. while ((st = pop_from_result())) {
  1245. total += use_bpf ? st->nr_contended : 1;
  1246. if (st->broken)
  1247. bad++;
  1248. list_for_each_entry(key, &lock_keys, list) {
  1249. key->print(key, st);
  1250. pr_info(" ");
  1251. }
  1252. if (show_thread_stats) {
  1253. struct thread *t;
  1254. int pid = st->addr;
  1255. /* st->addr contains tid of thread */
  1256. t = perf_session__findnew(session, pid);
  1257. pr_info(" %10d %s\n", pid, thread__comm_str(t));
  1258. goto next;
  1259. }
  1260. pr_info(" %10s %s\n", get_type_str(st), st->name);
  1261. if (verbose) {
  1262. struct map *kmap;
  1263. struct symbol *sym;
  1264. char buf[128];
  1265. u64 ip;
  1266. for (int i = 0; i < max_stack_depth; i++) {
  1267. if (!st->callstack || !st->callstack[i])
  1268. break;
  1269. ip = st->callstack[i];
  1270. sym = machine__find_kernel_symbol(con->machine, ip, &kmap);
  1271. get_symbol_name_offset(kmap, sym, ip, buf, sizeof(buf));
  1272. pr_info("\t\t\t%#lx %s\n", (unsigned long)ip, buf);
  1273. }
  1274. }
  1275. next:
  1276. if (++printed >= print_nr_entries)
  1277. break;
  1278. }
  1279. print_bad_events(bad, total);
  1280. }
  1281. static const struct evsel_str_handler lock_tracepoints[] = {
  1282. { "lock:lock_acquire", evsel__process_lock_acquire, }, /* CONFIG_LOCKDEP */
  1283. { "lock:lock_acquired", evsel__process_lock_acquired, }, /* CONFIG_LOCKDEP, CONFIG_LOCK_STAT */
  1284. { "lock:lock_contended", evsel__process_lock_contended, }, /* CONFIG_LOCKDEP, CONFIG_LOCK_STAT */
  1285. { "lock:lock_release", evsel__process_lock_release, }, /* CONFIG_LOCKDEP */
  1286. };
  1287. static const struct evsel_str_handler contention_tracepoints[] = {
  1288. { "lock:contention_begin", evsel__process_contention_begin, },
  1289. { "lock:contention_end", evsel__process_contention_end, },
  1290. };
  1291. static bool force;
  1292. static int __cmd_report(bool display_info)
  1293. {
  1294. int err = -EINVAL;
  1295. struct perf_tool eops = {
  1296. .sample = process_sample_event,
  1297. .comm = perf_event__process_comm,
  1298. .mmap = perf_event__process_mmap,
  1299. .namespaces = perf_event__process_namespaces,
  1300. .ordered_events = true,
  1301. };
  1302. struct perf_data data = {
  1303. .path = input_name,
  1304. .mode = PERF_DATA_MODE_READ,
  1305. .force = force,
  1306. };
  1307. session = perf_session__new(&data, &eops);
  1308. if (IS_ERR(session)) {
  1309. pr_err("Initializing perf session failed\n");
  1310. return PTR_ERR(session);
  1311. }
  1312. /* for lock function check */
  1313. symbol_conf.sort_by_name = true;
  1314. symbol_conf.allow_aliases = true;
  1315. symbol__init(&session->header.env);
  1316. if (!perf_session__has_traces(session, "lock record"))
  1317. goto out_delete;
  1318. if (perf_session__set_tracepoints_handlers(session, lock_tracepoints)) {
  1319. pr_err("Initializing perf session tracepoint handlers failed\n");
  1320. goto out_delete;
  1321. }
  1322. if (perf_session__set_tracepoints_handlers(session, contention_tracepoints)) {
  1323. pr_err("Initializing perf session tracepoint handlers failed\n");
  1324. goto out_delete;
  1325. }
  1326. if (setup_output_field(false, output_fields))
  1327. goto out_delete;
  1328. if (select_key(false))
  1329. goto out_delete;
  1330. if (show_thread_stats)
  1331. aggr_mode = LOCK_AGGR_TASK;
  1332. err = perf_session__process_events(session);
  1333. if (err)
  1334. goto out_delete;
  1335. setup_pager();
  1336. if (display_info) /* used for info subcommand */
  1337. err = dump_info();
  1338. else {
  1339. combine_result();
  1340. sort_result();
  1341. print_result();
  1342. }
  1343. out_delete:
  1344. perf_session__delete(session);
  1345. return err;
  1346. }
  1347. static void sighandler(int sig __maybe_unused)
  1348. {
  1349. }
  1350. static int __cmd_contention(int argc, const char **argv)
  1351. {
  1352. int err = -EINVAL;
  1353. struct perf_tool eops = {
  1354. .sample = process_sample_event,
  1355. .comm = perf_event__process_comm,
  1356. .mmap = perf_event__process_mmap,
  1357. .ordered_events = true,
  1358. };
  1359. struct perf_data data = {
  1360. .path = input_name,
  1361. .mode = PERF_DATA_MODE_READ,
  1362. .force = force,
  1363. };
  1364. struct lock_contention con = {
  1365. .target = &target,
  1366. .result = &lockhash_table[0],
  1367. .map_nr_entries = bpf_map_entries,
  1368. .max_stack = max_stack_depth,
  1369. .stack_skip = stack_skip,
  1370. };
  1371. session = perf_session__new(use_bpf ? NULL : &data, &eops);
  1372. if (IS_ERR(session)) {
  1373. pr_err("Initializing perf session failed\n");
  1374. return PTR_ERR(session);
  1375. }
  1376. con.machine = &session->machines.host;
  1377. /* for lock function check */
  1378. symbol_conf.sort_by_name = true;
  1379. symbol_conf.allow_aliases = true;
  1380. symbol__init(&session->header.env);
  1381. if (use_bpf) {
  1382. err = target__validate(&target);
  1383. if (err) {
  1384. char errbuf[512];
  1385. target__strerror(&target, err, errbuf, 512);
  1386. pr_err("%s\n", errbuf);
  1387. goto out_delete;
  1388. }
  1389. signal(SIGINT, sighandler);
  1390. signal(SIGCHLD, sighandler);
  1391. signal(SIGTERM, sighandler);
  1392. con.evlist = evlist__new();
  1393. if (con.evlist == NULL) {
  1394. err = -ENOMEM;
  1395. goto out_delete;
  1396. }
  1397. err = evlist__create_maps(con.evlist, &target);
  1398. if (err < 0)
  1399. goto out_delete;
  1400. if (argc) {
  1401. err = evlist__prepare_workload(con.evlist, &target,
  1402. argv, false, NULL);
  1403. if (err < 0)
  1404. goto out_delete;
  1405. }
  1406. if (lock_contention_prepare(&con) < 0) {
  1407. pr_err("lock contention BPF setup failed\n");
  1408. goto out_delete;
  1409. }
  1410. } else {
  1411. if (!perf_session__has_traces(session, "lock record"))
  1412. goto out_delete;
  1413. if (!evlist__find_evsel_by_str(session->evlist,
  1414. "lock:contention_begin")) {
  1415. pr_err("lock contention evsel not found\n");
  1416. goto out_delete;
  1417. }
  1418. if (perf_session__set_tracepoints_handlers(session,
  1419. contention_tracepoints)) {
  1420. pr_err("Initializing perf session tracepoint handlers failed\n");
  1421. goto out_delete;
  1422. }
  1423. }
  1424. if (setup_output_field(true, output_fields))
  1425. goto out_delete;
  1426. if (select_key(true))
  1427. goto out_delete;
  1428. if (show_thread_stats)
  1429. aggr_mode = LOCK_AGGR_TASK;
  1430. else
  1431. aggr_mode = LOCK_AGGR_CALLER;
  1432. if (use_bpf) {
  1433. lock_contention_start();
  1434. if (argc)
  1435. evlist__start_workload(con.evlist);
  1436. /* wait for signal */
  1437. pause();
  1438. lock_contention_stop();
  1439. lock_contention_read(&con);
  1440. /* abuse bad hist stats for lost entries */
  1441. bad_hist[BROKEN_CONTENDED] = con.lost;
  1442. } else {
  1443. err = perf_session__process_events(session);
  1444. if (err)
  1445. goto out_delete;
  1446. }
  1447. setup_pager();
  1448. sort_contention_result();
  1449. print_contention_result(&con);
  1450. out_delete:
  1451. evlist__delete(con.evlist);
  1452. lock_contention_finish();
  1453. perf_session__delete(session);
  1454. return err;
  1455. }
  1456. static int __cmd_record(int argc, const char **argv)
  1457. {
  1458. const char *record_args[] = {
  1459. "record", "-R", "-m", "1024", "-c", "1", "--synth", "task",
  1460. };
  1461. const char *callgraph_args[] = {
  1462. "--call-graph", "fp," __stringify(CONTENTION_STACK_DEPTH),
  1463. };
  1464. unsigned int rec_argc, i, j, ret;
  1465. unsigned int nr_tracepoints;
  1466. unsigned int nr_callgraph_args = 0;
  1467. const char **rec_argv;
  1468. bool has_lock_stat = true;
  1469. for (i = 0; i < ARRAY_SIZE(lock_tracepoints); i++) {
  1470. if (!is_valid_tracepoint(lock_tracepoints[i].name)) {
  1471. pr_debug("tracepoint %s is not enabled. "
  1472. "Are CONFIG_LOCKDEP and CONFIG_LOCK_STAT enabled?\n",
  1473. lock_tracepoints[i].name);
  1474. has_lock_stat = false;
  1475. break;
  1476. }
  1477. }
  1478. if (has_lock_stat)
  1479. goto setup_args;
  1480. for (i = 0; i < ARRAY_SIZE(contention_tracepoints); i++) {
  1481. if (!is_valid_tracepoint(contention_tracepoints[i].name)) {
  1482. pr_err("tracepoint %s is not enabled.\n",
  1483. contention_tracepoints[i].name);
  1484. return 1;
  1485. }
  1486. }
  1487. nr_callgraph_args = ARRAY_SIZE(callgraph_args);
  1488. setup_args:
  1489. rec_argc = ARRAY_SIZE(record_args) + nr_callgraph_args + argc - 1;
  1490. if (has_lock_stat)
  1491. nr_tracepoints = ARRAY_SIZE(lock_tracepoints);
  1492. else
  1493. nr_tracepoints = ARRAY_SIZE(contention_tracepoints);
  1494. /* factor of 2 is for -e in front of each tracepoint */
  1495. rec_argc += 2 * nr_tracepoints;
  1496. rec_argv = calloc(rec_argc + 1, sizeof(char *));
  1497. if (!rec_argv)
  1498. return -ENOMEM;
  1499. for (i = 0; i < ARRAY_SIZE(record_args); i++)
  1500. rec_argv[i] = strdup(record_args[i]);
  1501. for (j = 0; j < nr_tracepoints; j++) {
  1502. const char *ev_name;
  1503. if (has_lock_stat)
  1504. ev_name = strdup(lock_tracepoints[j].name);
  1505. else
  1506. ev_name = strdup(contention_tracepoints[j].name);
  1507. if (!ev_name)
  1508. return -ENOMEM;
  1509. rec_argv[i++] = "-e";
  1510. rec_argv[i++] = ev_name;
  1511. }
  1512. for (j = 0; j < nr_callgraph_args; j++, i++)
  1513. rec_argv[i] = callgraph_args[j];
  1514. for (j = 1; j < (unsigned int)argc; j++, i++)
  1515. rec_argv[i] = argv[j];
  1516. BUG_ON(i != rec_argc);
  1517. ret = cmd_record(i, rec_argv);
  1518. free(rec_argv);
  1519. return ret;
  1520. }
  1521. static int parse_map_entry(const struct option *opt, const char *str,
  1522. int unset __maybe_unused)
  1523. {
  1524. unsigned long *len = (unsigned long *)opt->value;
  1525. unsigned long val;
  1526. char *endptr;
  1527. errno = 0;
  1528. val = strtoul(str, &endptr, 0);
  1529. if (*endptr != '\0' || errno != 0) {
  1530. pr_err("invalid BPF map length: %s\n", str);
  1531. return -1;
  1532. }
  1533. *len = val;
  1534. return 0;
  1535. }
  1536. int cmd_lock(int argc, const char **argv)
  1537. {
  1538. const struct option lock_options[] = {
  1539. OPT_STRING('i', "input", &input_name, "file", "input file name"),
  1540. OPT_INCR('v', "verbose", &verbose, "be more verbose (show symbol address, etc)"),
  1541. OPT_BOOLEAN('D', "dump-raw-trace", &dump_trace, "dump raw trace in ASCII"),
  1542. OPT_BOOLEAN('f', "force", &force, "don't complain, do it"),
  1543. OPT_STRING(0, "vmlinux", &symbol_conf.vmlinux_name,
  1544. "file", "vmlinux pathname"),
  1545. OPT_STRING(0, "kallsyms", &symbol_conf.kallsyms_name,
  1546. "file", "kallsyms pathname"),
  1547. OPT_BOOLEAN('q', "quiet", &quiet, "Do not show any warnings or messages"),
  1548. OPT_END()
  1549. };
  1550. const struct option info_options[] = {
  1551. OPT_BOOLEAN('t', "threads", &info_threads,
  1552. "dump thread list in perf.data"),
  1553. OPT_BOOLEAN('m', "map", &info_map,
  1554. "map of lock instances (address:name table)"),
  1555. OPT_PARENT(lock_options)
  1556. };
  1557. const struct option report_options[] = {
  1558. OPT_STRING('k', "key", &sort_key, "acquired",
  1559. "key for sorting (acquired / contended / avg_wait / wait_total / wait_max / wait_min)"),
  1560. OPT_STRING('F', "field", &output_fields, NULL,
  1561. "output fields (acquired / contended / avg_wait / wait_total / wait_max / wait_min)"),
  1562. /* TODO: type */
  1563. OPT_BOOLEAN('c', "combine-locks", &combine_locks,
  1564. "combine locks in the same class"),
  1565. OPT_BOOLEAN('t', "threads", &show_thread_stats,
  1566. "show per-thread lock stats"),
  1567. OPT_INTEGER('E', "entries", &print_nr_entries, "display this many functions"),
  1568. OPT_PARENT(lock_options)
  1569. };
  1570. struct option contention_options[] = {
  1571. OPT_STRING('k', "key", &sort_key, "wait_total",
  1572. "key for sorting (contended / wait_total / wait_max / wait_min / avg_wait)"),
  1573. OPT_STRING('F', "field", &output_fields, "contended,wait_total,wait_max,avg_wait",
  1574. "output fields (contended / wait_total / wait_max / wait_min / avg_wait)"),
  1575. OPT_BOOLEAN('t', "threads", &show_thread_stats,
  1576. "show per-thread lock stats"),
  1577. OPT_BOOLEAN('b', "use-bpf", &use_bpf, "use BPF program to collect lock contention stats"),
  1578. OPT_BOOLEAN('a', "all-cpus", &target.system_wide,
  1579. "System-wide collection from all CPUs"),
  1580. OPT_STRING('C', "cpu", &target.cpu_list, "cpu",
  1581. "List of cpus to monitor"),
  1582. OPT_STRING('p', "pid", &target.pid, "pid",
  1583. "Trace on existing process id"),
  1584. OPT_STRING(0, "tid", &target.tid, "tid",
  1585. "Trace on existing thread id (exclusive to --pid)"),
  1586. OPT_CALLBACK(0, "map-nr-entries", &bpf_map_entries, "num",
  1587. "Max number of BPF map entries", parse_map_entry),
  1588. OPT_INTEGER(0, "max-stack", &max_stack_depth,
  1589. "Set the maximum stack depth when collecting lock contention, "
  1590. "Default: " __stringify(CONTENTION_STACK_DEPTH)),
  1591. OPT_INTEGER(0, "stack-skip", &stack_skip,
  1592. "Set the number of stack depth to skip when finding a lock caller, "
  1593. "Default: " __stringify(CONTENTION_STACK_SKIP)),
  1594. OPT_INTEGER('E', "entries", &print_nr_entries, "display this many functions"),
  1595. OPT_PARENT(lock_options)
  1596. };
  1597. const char * const info_usage[] = {
  1598. "perf lock info [<options>]",
  1599. NULL
  1600. };
  1601. const char *const lock_subcommands[] = { "record", "report", "script",
  1602. "info", "contention", NULL };
  1603. const char *lock_usage[] = {
  1604. NULL,
  1605. NULL
  1606. };
  1607. const char * const report_usage[] = {
  1608. "perf lock report [<options>]",
  1609. NULL
  1610. };
  1611. const char * const contention_usage[] = {
  1612. "perf lock contention [<options>]",
  1613. NULL
  1614. };
  1615. unsigned int i;
  1616. int rc = 0;
  1617. for (i = 0; i < LOCKHASH_SIZE; i++)
  1618. INIT_HLIST_HEAD(lockhash_table + i);
  1619. argc = parse_options_subcommand(argc, argv, lock_options, lock_subcommands,
  1620. lock_usage, PARSE_OPT_STOP_AT_NON_OPTION);
  1621. if (!argc)
  1622. usage_with_options(lock_usage, lock_options);
  1623. if (strlen(argv[0]) > 2 && strstarts("record", argv[0])) {
  1624. return __cmd_record(argc, argv);
  1625. } else if (strlen(argv[0]) > 2 && strstarts("report", argv[0])) {
  1626. trace_handler = &report_lock_ops;
  1627. if (argc) {
  1628. argc = parse_options(argc, argv,
  1629. report_options, report_usage, 0);
  1630. if (argc)
  1631. usage_with_options(report_usage, report_options);
  1632. }
  1633. rc = __cmd_report(false);
  1634. } else if (!strcmp(argv[0], "script")) {
  1635. /* Aliased to 'perf script' */
  1636. return cmd_script(argc, argv);
  1637. } else if (!strcmp(argv[0], "info")) {
  1638. if (argc) {
  1639. argc = parse_options(argc, argv,
  1640. info_options, info_usage, 0);
  1641. if (argc)
  1642. usage_with_options(info_usage, info_options);
  1643. }
  1644. /* recycling report_lock_ops */
  1645. trace_handler = &report_lock_ops;
  1646. rc = __cmd_report(true);
  1647. } else if (strlen(argv[0]) > 2 && strstarts("contention", argv[0])) {
  1648. trace_handler = &contention_lock_ops;
  1649. sort_key = "wait_total";
  1650. output_fields = "contended,wait_total,wait_max,avg_wait";
  1651. #ifndef HAVE_BPF_SKEL
  1652. set_option_nobuild(contention_options, 'b', "use-bpf",
  1653. "no BUILD_BPF_SKEL=1", false);
  1654. #endif
  1655. if (argc) {
  1656. argc = parse_options(argc, argv, contention_options,
  1657. contention_usage, 0);
  1658. }
  1659. rc = __cmd_contention(argc, argv);
  1660. } else {
  1661. usage_with_options(lock_usage, lock_options);
  1662. }
  1663. return rc;
  1664. }