perf_event.c 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890
  1. /*
  2. * Performance events x86 architecture code
  3. *
  4. * Copyright (C) 2008 Thomas Gleixner <tglx@linutronix.de>
  5. * Copyright (C) 2008-2009 Red Hat, Inc., Ingo Molnar
  6. * Copyright (C) 2009 Jaswinder Singh Rajput
  7. * Copyright (C) 2009 Advanced Micro Devices, Inc., Robert Richter
  8. * Copyright (C) 2008-2009 Red Hat, Inc., Peter Zijlstra <pzijlstr@redhat.com>
  9. * Copyright (C) 2009 Intel Corporation, <markus.t.metzger@intel.com>
  10. * Copyright (C) 2009 Google, Inc., Stephane Eranian
  11. *
  12. * For licencing details see kernel-base/COPYING
  13. */
  14. #include <linux/perf_event.h>
  15. #include <linux/capability.h>
  16. #include <linux/notifier.h>
  17. #include <linux/hardirq.h>
  18. #include <linux/kprobes.h>
  19. #include <linux/module.h>
  20. #include <linux/kdebug.h>
  21. #include <linux/sched.h>
  22. #include <linux/uaccess.h>
  23. #include <linux/slab.h>
  24. #include <linux/cpu.h>
  25. #include <linux/bitops.h>
  26. #include <linux/device.h>
  27. #include <asm/apic.h>
  28. #include <asm/stacktrace.h>
  29. #include <asm/nmi.h>
  30. #include <asm/smp.h>
  31. #include <asm/alternative.h>
  32. #include <asm/timer.h>
  33. #include "perf_event.h"
  34. #if 0
  35. #undef wrmsrl
  36. #define wrmsrl(msr, val) \
  37. do { \
  38. trace_printk("wrmsrl(%lx, %lx)\n", (unsigned long)(msr),\
  39. (unsigned long)(val)); \
  40. native_write_msr((msr), (u32)((u64)(val)), \
  41. (u32)((u64)(val) >> 32)); \
  42. } while (0)
  43. #endif
  44. struct x86_pmu x86_pmu __read_mostly;
  45. DEFINE_PER_CPU(struct cpu_hw_events, cpu_hw_events) = {
  46. .enabled = 1,
  47. };
  48. u64 __read_mostly hw_cache_event_ids
  49. [PERF_COUNT_HW_CACHE_MAX]
  50. [PERF_COUNT_HW_CACHE_OP_MAX]
  51. [PERF_COUNT_HW_CACHE_RESULT_MAX];
  52. u64 __read_mostly hw_cache_extra_regs
  53. [PERF_COUNT_HW_CACHE_MAX]
  54. [PERF_COUNT_HW_CACHE_OP_MAX]
  55. [PERF_COUNT_HW_CACHE_RESULT_MAX];
  56. /*
  57. * Propagate event elapsed time into the generic event.
  58. * Can only be executed on the CPU where the event is active.
  59. * Returns the delta events processed.
  60. */
  61. u64 x86_perf_event_update(struct perf_event *event)
  62. {
  63. struct hw_perf_event *hwc = &event->hw;
  64. int shift = 64 - x86_pmu.cntval_bits;
  65. u64 prev_raw_count, new_raw_count;
  66. int idx = hwc->idx;
  67. s64 delta;
  68. if (idx == X86_PMC_IDX_FIXED_BTS)
  69. return 0;
  70. /*
  71. * Careful: an NMI might modify the previous event value.
  72. *
  73. * Our tactic to handle this is to first atomically read and
  74. * exchange a new raw count - then add that new-prev delta
  75. * count to the generic event atomically:
  76. */
  77. again:
  78. prev_raw_count = local64_read(&hwc->prev_count);
  79. rdmsrl(hwc->event_base, new_raw_count);
  80. if (local64_cmpxchg(&hwc->prev_count, prev_raw_count,
  81. new_raw_count) != prev_raw_count)
  82. goto again;
  83. /*
  84. * Now we have the new raw value and have updated the prev
  85. * timestamp already. We can now calculate the elapsed delta
  86. * (event-)time and add that to the generic event.
  87. *
  88. * Careful, not all hw sign-extends above the physical width
  89. * of the count.
  90. */
  91. delta = (new_raw_count << shift) - (prev_raw_count << shift);
  92. delta >>= shift;
  93. local64_add(delta, &event->count);
  94. local64_sub(delta, &hwc->period_left);
  95. return new_raw_count;
  96. }
  97. /*
  98. * Find and validate any extra registers to set up.
  99. */
  100. static int x86_pmu_extra_regs(u64 config, struct perf_event *event)
  101. {
  102. struct hw_perf_event_extra *reg;
  103. struct extra_reg *er;
  104. reg = &event->hw.extra_reg;
  105. if (!x86_pmu.extra_regs)
  106. return 0;
  107. for (er = x86_pmu.extra_regs; er->msr; er++) {
  108. if (er->event != (config & er->config_mask))
  109. continue;
  110. if (event->attr.config1 & ~er->valid_mask)
  111. return -EINVAL;
  112. reg->idx = er->idx;
  113. reg->config = event->attr.config1;
  114. reg->reg = er->msr;
  115. break;
  116. }
  117. return 0;
  118. }
  119. static atomic_t active_events;
  120. static DEFINE_MUTEX(pmc_reserve_mutex);
  121. #ifdef CONFIG_X86_LOCAL_APIC
  122. static bool reserve_pmc_hardware(void)
  123. {
  124. int i;
  125. for (i = 0; i < x86_pmu.num_counters; i++) {
  126. if (!reserve_perfctr_nmi(x86_pmu_event_addr(i)))
  127. goto perfctr_fail;
  128. }
  129. for (i = 0; i < x86_pmu.num_counters; i++) {
  130. if (!reserve_evntsel_nmi(x86_pmu_config_addr(i)))
  131. goto eventsel_fail;
  132. }
  133. return true;
  134. eventsel_fail:
  135. for (i--; i >= 0; i--)
  136. release_evntsel_nmi(x86_pmu_config_addr(i));
  137. i = x86_pmu.num_counters;
  138. perfctr_fail:
  139. for (i--; i >= 0; i--)
  140. release_perfctr_nmi(x86_pmu_event_addr(i));
  141. return false;
  142. }
  143. static void release_pmc_hardware(void)
  144. {
  145. int i;
  146. for (i = 0; i < x86_pmu.num_counters; i++) {
  147. release_perfctr_nmi(x86_pmu_event_addr(i));
  148. release_evntsel_nmi(x86_pmu_config_addr(i));
  149. }
  150. }
  151. #else
  152. static bool reserve_pmc_hardware(void) { return true; }
  153. static void release_pmc_hardware(void) {}
  154. #endif
  155. static bool check_hw_exists(void)
  156. {
  157. u64 val, val_new = 0;
  158. int i, reg, ret = 0;
  159. /*
  160. * Check to see if the BIOS enabled any of the counters, if so
  161. * complain and bail.
  162. */
  163. for (i = 0; i < x86_pmu.num_counters; i++) {
  164. reg = x86_pmu_config_addr(i);
  165. ret = rdmsrl_safe(reg, &val);
  166. if (ret)
  167. goto msr_fail;
  168. if (val & ARCH_PERFMON_EVENTSEL_ENABLE)
  169. goto bios_fail;
  170. }
  171. if (x86_pmu.num_counters_fixed) {
  172. reg = MSR_ARCH_PERFMON_FIXED_CTR_CTRL;
  173. ret = rdmsrl_safe(reg, &val);
  174. if (ret)
  175. goto msr_fail;
  176. for (i = 0; i < x86_pmu.num_counters_fixed; i++) {
  177. if (val & (0x03 << i*4))
  178. goto bios_fail;
  179. }
  180. }
  181. /*
  182. * Now write a value and read it back to see if it matches,
  183. * this is needed to detect certain hardware emulators (qemu/kvm)
  184. * that don't trap on the MSR access and always return 0s.
  185. */
  186. val = 0xabcdUL;
  187. ret = checking_wrmsrl(x86_pmu_event_addr(0), val);
  188. ret |= rdmsrl_safe(x86_pmu_event_addr(0), &val_new);
  189. if (ret || val != val_new)
  190. goto msr_fail;
  191. return true;
  192. bios_fail:
  193. /*
  194. * We still allow the PMU driver to operate:
  195. */
  196. printk(KERN_CONT "Broken BIOS detected, complain to your hardware vendor.\n");
  197. printk(KERN_ERR FW_BUG "the BIOS has corrupted hw-PMU resources (MSR %x is %Lx)\n", reg, val);
  198. return true;
  199. msr_fail:
  200. printk(KERN_CONT "Broken PMU hardware detected, using software events only.\n");
  201. return false;
  202. }
  203. static void hw_perf_event_destroy(struct perf_event *event)
  204. {
  205. if (atomic_dec_and_mutex_lock(&active_events, &pmc_reserve_mutex)) {
  206. release_pmc_hardware();
  207. release_ds_buffers();
  208. mutex_unlock(&pmc_reserve_mutex);
  209. }
  210. }
  211. static inline int x86_pmu_initialized(void)
  212. {
  213. return x86_pmu.handle_irq != NULL;
  214. }
  215. static inline int
  216. set_ext_hw_attr(struct hw_perf_event *hwc, struct perf_event *event)
  217. {
  218. struct perf_event_attr *attr = &event->attr;
  219. unsigned int cache_type, cache_op, cache_result;
  220. u64 config, val;
  221. config = attr->config;
  222. cache_type = (config >> 0) & 0xff;
  223. if (cache_type >= PERF_COUNT_HW_CACHE_MAX)
  224. return -EINVAL;
  225. cache_op = (config >> 8) & 0xff;
  226. if (cache_op >= PERF_COUNT_HW_CACHE_OP_MAX)
  227. return -EINVAL;
  228. cache_result = (config >> 16) & 0xff;
  229. if (cache_result >= PERF_COUNT_HW_CACHE_RESULT_MAX)
  230. return -EINVAL;
  231. val = hw_cache_event_ids[cache_type][cache_op][cache_result];
  232. if (val == 0)
  233. return -ENOENT;
  234. if (val == -1)
  235. return -EINVAL;
  236. hwc->config |= val;
  237. attr->config1 = hw_cache_extra_regs[cache_type][cache_op][cache_result];
  238. return x86_pmu_extra_regs(val, event);
  239. }
  240. int x86_setup_perfctr(struct perf_event *event)
  241. {
  242. struct perf_event_attr *attr = &event->attr;
  243. struct hw_perf_event *hwc = &event->hw;
  244. u64 config;
  245. if (!is_sampling_event(event)) {
  246. hwc->sample_period = x86_pmu.max_period;
  247. hwc->last_period = hwc->sample_period;
  248. local64_set(&hwc->period_left, hwc->sample_period);
  249. } else {
  250. /*
  251. * If we have a PMU initialized but no APIC
  252. * interrupts, we cannot sample hardware
  253. * events (user-space has to fall back and
  254. * sample via a hrtimer based software event):
  255. */
  256. if (!x86_pmu.apic)
  257. return -EOPNOTSUPP;
  258. }
  259. if (attr->type == PERF_TYPE_RAW)
  260. return x86_pmu_extra_regs(event->attr.config, event);
  261. if (attr->type == PERF_TYPE_HW_CACHE)
  262. return set_ext_hw_attr(hwc, event);
  263. if (attr->config >= x86_pmu.max_events)
  264. return -EINVAL;
  265. /*
  266. * The generic map:
  267. */
  268. config = x86_pmu.event_map(attr->config);
  269. if (config == 0)
  270. return -ENOENT;
  271. if (config == -1LL)
  272. return -EINVAL;
  273. /*
  274. * Branch tracing:
  275. */
  276. if (attr->config == PERF_COUNT_HW_BRANCH_INSTRUCTIONS &&
  277. !attr->freq && hwc->sample_period == 1) {
  278. /* BTS is not supported by this architecture. */
  279. if (!x86_pmu.bts_active)
  280. return -EOPNOTSUPP;
  281. /* BTS is currently only allowed for user-mode. */
  282. if (!attr->exclude_kernel)
  283. return -EOPNOTSUPP;
  284. }
  285. hwc->config |= config;
  286. return 0;
  287. }
  288. /*
  289. * check that branch_sample_type is compatible with
  290. * settings needed for precise_ip > 1 which implies
  291. * using the LBR to capture ALL taken branches at the
  292. * priv levels of the measurement
  293. */
  294. static inline int precise_br_compat(struct perf_event *event)
  295. {
  296. u64 m = event->attr.branch_sample_type;
  297. u64 b = 0;
  298. /* must capture all branches */
  299. if (!(m & PERF_SAMPLE_BRANCH_ANY))
  300. return 0;
  301. m &= PERF_SAMPLE_BRANCH_KERNEL | PERF_SAMPLE_BRANCH_USER;
  302. if (!event->attr.exclude_user)
  303. b |= PERF_SAMPLE_BRANCH_USER;
  304. if (!event->attr.exclude_kernel)
  305. b |= PERF_SAMPLE_BRANCH_KERNEL;
  306. /*
  307. * ignore PERF_SAMPLE_BRANCH_HV, not supported on x86
  308. */
  309. return m == b;
  310. }
  311. int x86_pmu_hw_config(struct perf_event *event)
  312. {
  313. if (event->attr.precise_ip) {
  314. int precise = 0;
  315. /* Support for constant skid */
  316. if (x86_pmu.pebs_active) {
  317. precise++;
  318. /* Support for IP fixup */
  319. if (x86_pmu.lbr_nr)
  320. precise++;
  321. }
  322. if (event->attr.precise_ip > precise)
  323. return -EOPNOTSUPP;
  324. /*
  325. * check that PEBS LBR correction does not conflict with
  326. * whatever the user is asking with attr->branch_sample_type
  327. */
  328. if (event->attr.precise_ip > 1) {
  329. u64 *br_type = &event->attr.branch_sample_type;
  330. if (has_branch_stack(event)) {
  331. if (!precise_br_compat(event))
  332. return -EOPNOTSUPP;
  333. /* branch_sample_type is compatible */
  334. } else {
  335. /*
  336. * user did not specify branch_sample_type
  337. *
  338. * For PEBS fixups, we capture all
  339. * the branches at the priv level of the
  340. * event.
  341. */
  342. *br_type = PERF_SAMPLE_BRANCH_ANY;
  343. if (!event->attr.exclude_user)
  344. *br_type |= PERF_SAMPLE_BRANCH_USER;
  345. if (!event->attr.exclude_kernel)
  346. *br_type |= PERF_SAMPLE_BRANCH_KERNEL;
  347. }
  348. }
  349. }
  350. /*
  351. * Generate PMC IRQs:
  352. * (keep 'enabled' bit clear for now)
  353. */
  354. event->hw.config = ARCH_PERFMON_EVENTSEL_INT;
  355. /*
  356. * Count user and OS events unless requested not to
  357. */
  358. if (!event->attr.exclude_user)
  359. event->hw.config |= ARCH_PERFMON_EVENTSEL_USR;
  360. if (!event->attr.exclude_kernel)
  361. event->hw.config |= ARCH_PERFMON_EVENTSEL_OS;
  362. if (event->attr.type == PERF_TYPE_RAW)
  363. event->hw.config |= event->attr.config & X86_RAW_EVENT_MASK;
  364. return x86_setup_perfctr(event);
  365. }
  366. /*
  367. * Setup the hardware configuration for a given attr_type
  368. */
  369. static int __x86_pmu_event_init(struct perf_event *event)
  370. {
  371. int err;
  372. if (!x86_pmu_initialized())
  373. return -ENODEV;
  374. err = 0;
  375. if (!atomic_inc_not_zero(&active_events)) {
  376. mutex_lock(&pmc_reserve_mutex);
  377. if (atomic_read(&active_events) == 0) {
  378. if (!reserve_pmc_hardware())
  379. err = -EBUSY;
  380. else
  381. reserve_ds_buffers();
  382. }
  383. if (!err)
  384. atomic_inc(&active_events);
  385. mutex_unlock(&pmc_reserve_mutex);
  386. }
  387. if (err)
  388. return err;
  389. event->destroy = hw_perf_event_destroy;
  390. event->hw.idx = -1;
  391. event->hw.last_cpu = -1;
  392. event->hw.last_tag = ~0ULL;
  393. /* mark unused */
  394. event->hw.extra_reg.idx = EXTRA_REG_NONE;
  395. /* mark not used */
  396. event->hw.extra_reg.idx = EXTRA_REG_NONE;
  397. event->hw.branch_reg.idx = EXTRA_REG_NONE;
  398. return x86_pmu.hw_config(event);
  399. }
  400. void x86_pmu_disable_all(void)
  401. {
  402. struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
  403. int idx;
  404. for (idx = 0; idx < x86_pmu.num_counters; idx++) {
  405. u64 val;
  406. if (!test_bit(idx, cpuc->active_mask))
  407. continue;
  408. rdmsrl(x86_pmu_config_addr(idx), val);
  409. if (!(val & ARCH_PERFMON_EVENTSEL_ENABLE))
  410. continue;
  411. val &= ~ARCH_PERFMON_EVENTSEL_ENABLE;
  412. wrmsrl(x86_pmu_config_addr(idx), val);
  413. }
  414. }
  415. static void x86_pmu_disable(struct pmu *pmu)
  416. {
  417. struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
  418. if (!x86_pmu_initialized())
  419. return;
  420. if (!cpuc->enabled)
  421. return;
  422. cpuc->n_added = 0;
  423. cpuc->enabled = 0;
  424. barrier();
  425. x86_pmu.disable_all();
  426. }
  427. void x86_pmu_enable_all(int added)
  428. {
  429. struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
  430. int idx;
  431. for (idx = 0; idx < x86_pmu.num_counters; idx++) {
  432. struct hw_perf_event *hwc = &cpuc->events[idx]->hw;
  433. if (!test_bit(idx, cpuc->active_mask))
  434. continue;
  435. __x86_pmu_enable_event(hwc, ARCH_PERFMON_EVENTSEL_ENABLE);
  436. }
  437. }
  438. static struct pmu pmu;
  439. static inline int is_x86_event(struct perf_event *event)
  440. {
  441. return event->pmu == &pmu;
  442. }
  443. /*
  444. * Event scheduler state:
  445. *
  446. * Assign events iterating over all events and counters, beginning
  447. * with events with least weights first. Keep the current iterator
  448. * state in struct sched_state.
  449. */
  450. struct sched_state {
  451. int weight;
  452. int event; /* event index */
  453. int counter; /* counter index */
  454. int unassigned; /* number of events to be assigned left */
  455. unsigned long used[BITS_TO_LONGS(X86_PMC_IDX_MAX)];
  456. };
  457. /* Total max is X86_PMC_IDX_MAX, but we are O(n!) limited */
  458. #define SCHED_STATES_MAX 2
  459. struct perf_sched {
  460. int max_weight;
  461. int max_events;
  462. struct event_constraint **constraints;
  463. struct sched_state state;
  464. int saved_states;
  465. struct sched_state saved[SCHED_STATES_MAX];
  466. };
  467. /*
  468. * Initialize interator that runs through all events and counters.
  469. */
  470. static void perf_sched_init(struct perf_sched *sched, struct event_constraint **c,
  471. int num, int wmin, int wmax)
  472. {
  473. int idx;
  474. memset(sched, 0, sizeof(*sched));
  475. sched->max_events = num;
  476. sched->max_weight = wmax;
  477. sched->constraints = c;
  478. for (idx = 0; idx < num; idx++) {
  479. if (c[idx]->weight == wmin)
  480. break;
  481. }
  482. sched->state.event = idx; /* start with min weight */
  483. sched->state.weight = wmin;
  484. sched->state.unassigned = num;
  485. }
  486. static void perf_sched_save_state(struct perf_sched *sched)
  487. {
  488. if (WARN_ON_ONCE(sched->saved_states >= SCHED_STATES_MAX))
  489. return;
  490. sched->saved[sched->saved_states] = sched->state;
  491. sched->saved_states++;
  492. }
  493. static bool perf_sched_restore_state(struct perf_sched *sched)
  494. {
  495. if (!sched->saved_states)
  496. return false;
  497. sched->saved_states--;
  498. sched->state = sched->saved[sched->saved_states];
  499. /* continue with next counter: */
  500. clear_bit(sched->state.counter++, sched->state.used);
  501. return true;
  502. }
  503. /*
  504. * Select a counter for the current event to schedule. Return true on
  505. * success.
  506. */
  507. static bool __perf_sched_find_counter(struct perf_sched *sched)
  508. {
  509. struct event_constraint *c;
  510. int idx;
  511. if (!sched->state.unassigned)
  512. return false;
  513. if (sched->state.event >= sched->max_events)
  514. return false;
  515. c = sched->constraints[sched->state.event];
  516. /* Prefer fixed purpose counters */
  517. if (x86_pmu.num_counters_fixed) {
  518. idx = X86_PMC_IDX_FIXED;
  519. for_each_set_bit_from(idx, c->idxmsk, X86_PMC_IDX_MAX) {
  520. if (!__test_and_set_bit(idx, sched->state.used))
  521. goto done;
  522. }
  523. }
  524. /* Grab the first unused counter starting with idx */
  525. idx = sched->state.counter;
  526. for_each_set_bit_from(idx, c->idxmsk, X86_PMC_IDX_FIXED) {
  527. if (!__test_and_set_bit(idx, sched->state.used))
  528. goto done;
  529. }
  530. return false;
  531. done:
  532. sched->state.counter = idx;
  533. if (c->overlap)
  534. perf_sched_save_state(sched);
  535. return true;
  536. }
  537. static bool perf_sched_find_counter(struct perf_sched *sched)
  538. {
  539. while (!__perf_sched_find_counter(sched)) {
  540. if (!perf_sched_restore_state(sched))
  541. return false;
  542. }
  543. return true;
  544. }
  545. /*
  546. * Go through all unassigned events and find the next one to schedule.
  547. * Take events with the least weight first. Return true on success.
  548. */
  549. static bool perf_sched_next_event(struct perf_sched *sched)
  550. {
  551. struct event_constraint *c;
  552. if (!sched->state.unassigned || !--sched->state.unassigned)
  553. return false;
  554. do {
  555. /* next event */
  556. sched->state.event++;
  557. if (sched->state.event >= sched->max_events) {
  558. /* next weight */
  559. sched->state.event = 0;
  560. sched->state.weight++;
  561. if (sched->state.weight > sched->max_weight)
  562. return false;
  563. }
  564. c = sched->constraints[sched->state.event];
  565. } while (c->weight != sched->state.weight);
  566. sched->state.counter = 0; /* start with first counter */
  567. return true;
  568. }
  569. /*
  570. * Assign a counter for each event.
  571. */
  572. static int perf_assign_events(struct event_constraint **constraints, int n,
  573. int wmin, int wmax, int *assign)
  574. {
  575. struct perf_sched sched;
  576. perf_sched_init(&sched, constraints, n, wmin, wmax);
  577. do {
  578. if (!perf_sched_find_counter(&sched))
  579. break; /* failed */
  580. if (assign)
  581. assign[sched.state.event] = sched.state.counter;
  582. } while (perf_sched_next_event(&sched));
  583. return sched.state.unassigned;
  584. }
  585. int x86_schedule_events(struct cpu_hw_events *cpuc, int n, int *assign)
  586. {
  587. struct event_constraint *c, *constraints[X86_PMC_IDX_MAX];
  588. unsigned long used_mask[BITS_TO_LONGS(X86_PMC_IDX_MAX)];
  589. int i, wmin, wmax, num = 0;
  590. struct hw_perf_event *hwc;
  591. bitmap_zero(used_mask, X86_PMC_IDX_MAX);
  592. for (i = 0, wmin = X86_PMC_IDX_MAX, wmax = 0; i < n; i++) {
  593. c = x86_pmu.get_event_constraints(cpuc, cpuc->event_list[i]);
  594. constraints[i] = c;
  595. wmin = min(wmin, c->weight);
  596. wmax = max(wmax, c->weight);
  597. }
  598. /*
  599. * fastpath, try to reuse previous register
  600. */
  601. for (i = 0; i < n; i++) {
  602. hwc = &cpuc->event_list[i]->hw;
  603. c = constraints[i];
  604. /* never assigned */
  605. if (hwc->idx == -1)
  606. break;
  607. /* constraint still honored */
  608. if (!test_bit(hwc->idx, c->idxmsk))
  609. break;
  610. /* not already used */
  611. if (test_bit(hwc->idx, used_mask))
  612. break;
  613. __set_bit(hwc->idx, used_mask);
  614. if (assign)
  615. assign[i] = hwc->idx;
  616. }
  617. /* slow path */
  618. if (i != n)
  619. num = perf_assign_events(constraints, n, wmin, wmax, assign);
  620. /*
  621. * scheduling failed or is just a simulation,
  622. * free resources if necessary
  623. */
  624. if (!assign || num) {
  625. for (i = 0; i < n; i++) {
  626. if (x86_pmu.put_event_constraints)
  627. x86_pmu.put_event_constraints(cpuc, cpuc->event_list[i]);
  628. }
  629. }
  630. return num ? -EINVAL : 0;
  631. }
  632. /*
  633. * dogrp: true if must collect siblings events (group)
  634. * returns total number of events and error code
  635. */
  636. static int collect_events(struct cpu_hw_events *cpuc, struct perf_event *leader, bool dogrp)
  637. {
  638. struct perf_event *event;
  639. int n, max_count;
  640. max_count = x86_pmu.num_counters + x86_pmu.num_counters_fixed;
  641. /* current number of events already accepted */
  642. n = cpuc->n_events;
  643. if (is_x86_event(leader)) {
  644. if (n >= max_count)
  645. return -EINVAL;
  646. cpuc->event_list[n] = leader;
  647. n++;
  648. }
  649. if (!dogrp)
  650. return n;
  651. list_for_each_entry(event, &leader->sibling_list, group_entry) {
  652. if (!is_x86_event(event) ||
  653. event->state <= PERF_EVENT_STATE_OFF)
  654. continue;
  655. if (n >= max_count)
  656. return -EINVAL;
  657. cpuc->event_list[n] = event;
  658. n++;
  659. }
  660. return n;
  661. }
  662. static inline void x86_assign_hw_event(struct perf_event *event,
  663. struct cpu_hw_events *cpuc, int i)
  664. {
  665. struct hw_perf_event *hwc = &event->hw;
  666. hwc->idx = cpuc->assign[i];
  667. hwc->last_cpu = smp_processor_id();
  668. hwc->last_tag = ++cpuc->tags[i];
  669. if (hwc->idx == X86_PMC_IDX_FIXED_BTS) {
  670. hwc->config_base = 0;
  671. hwc->event_base = 0;
  672. } else if (hwc->idx >= X86_PMC_IDX_FIXED) {
  673. hwc->config_base = MSR_ARCH_PERFMON_FIXED_CTR_CTRL;
  674. hwc->event_base = MSR_ARCH_PERFMON_FIXED_CTR0 + (hwc->idx - X86_PMC_IDX_FIXED);
  675. } else {
  676. hwc->config_base = x86_pmu_config_addr(hwc->idx);
  677. hwc->event_base = x86_pmu_event_addr(hwc->idx);
  678. }
  679. }
  680. static inline int match_prev_assignment(struct hw_perf_event *hwc,
  681. struct cpu_hw_events *cpuc,
  682. int i)
  683. {
  684. return hwc->idx == cpuc->assign[i] &&
  685. hwc->last_cpu == smp_processor_id() &&
  686. hwc->last_tag == cpuc->tags[i];
  687. }
  688. static void x86_pmu_start(struct perf_event *event, int flags);
  689. static void x86_pmu_enable(struct pmu *pmu)
  690. {
  691. struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
  692. struct perf_event *event;
  693. struct hw_perf_event *hwc;
  694. int i, added = cpuc->n_added;
  695. if (!x86_pmu_initialized())
  696. return;
  697. if (cpuc->enabled)
  698. return;
  699. if (cpuc->n_added) {
  700. int n_running = cpuc->n_events - cpuc->n_added;
  701. /*
  702. * apply assignment obtained either from
  703. * hw_perf_group_sched_in() or x86_pmu_enable()
  704. *
  705. * step1: save events moving to new counters
  706. * step2: reprogram moved events into new counters
  707. */
  708. for (i = 0; i < n_running; i++) {
  709. event = cpuc->event_list[i];
  710. hwc = &event->hw;
  711. /*
  712. * we can avoid reprogramming counter if:
  713. * - assigned same counter as last time
  714. * - running on same CPU as last time
  715. * - no other event has used the counter since
  716. */
  717. if (hwc->idx == -1 ||
  718. match_prev_assignment(hwc, cpuc, i))
  719. continue;
  720. /*
  721. * Ensure we don't accidentally enable a stopped
  722. * counter simply because we rescheduled.
  723. */
  724. if (hwc->state & PERF_HES_STOPPED)
  725. hwc->state |= PERF_HES_ARCH;
  726. x86_pmu_stop(event, PERF_EF_UPDATE);
  727. }
  728. for (i = 0; i < cpuc->n_events; i++) {
  729. event = cpuc->event_list[i];
  730. hwc = &event->hw;
  731. if (!match_prev_assignment(hwc, cpuc, i))
  732. x86_assign_hw_event(event, cpuc, i);
  733. else if (i < n_running)
  734. continue;
  735. if (hwc->state & PERF_HES_ARCH)
  736. continue;
  737. x86_pmu_start(event, PERF_EF_RELOAD);
  738. }
  739. cpuc->n_added = 0;
  740. perf_events_lapic_init();
  741. }
  742. cpuc->enabled = 1;
  743. barrier();
  744. x86_pmu.enable_all(added);
  745. }
  746. static DEFINE_PER_CPU(u64 [X86_PMC_IDX_MAX], pmc_prev_left);
  747. /*
  748. * Set the next IRQ period, based on the hwc->period_left value.
  749. * To be called with the event disabled in hw:
  750. */
  751. int x86_perf_event_set_period(struct perf_event *event)
  752. {
  753. struct hw_perf_event *hwc = &event->hw;
  754. s64 left = local64_read(&hwc->period_left);
  755. s64 period = hwc->sample_period;
  756. int ret = 0, idx = hwc->idx;
  757. if (idx == X86_PMC_IDX_FIXED_BTS)
  758. return 0;
  759. /*
  760. * If we are way outside a reasonable range then just skip forward:
  761. */
  762. if (unlikely(left <= -period)) {
  763. left = period;
  764. local64_set(&hwc->period_left, left);
  765. hwc->last_period = period;
  766. ret = 1;
  767. }
  768. if (unlikely(left <= 0)) {
  769. left += period;
  770. local64_set(&hwc->period_left, left);
  771. hwc->last_period = period;
  772. ret = 1;
  773. }
  774. /*
  775. * Quirk: certain CPUs dont like it if just 1 hw_event is left:
  776. */
  777. if (unlikely(left < 2))
  778. left = 2;
  779. if (left > x86_pmu.max_period)
  780. left = x86_pmu.max_period;
  781. per_cpu(pmc_prev_left[idx], smp_processor_id()) = left;
  782. /*
  783. * The hw event starts counting from this event offset,
  784. * mark it to be able to extra future deltas:
  785. */
  786. local64_set(&hwc->prev_count, (u64)-left);
  787. wrmsrl(hwc->event_base, (u64)(-left) & x86_pmu.cntval_mask);
  788. /*
  789. * Due to erratum on certan cpu we need
  790. * a second write to be sure the register
  791. * is updated properly
  792. */
  793. if (x86_pmu.perfctr_second_write) {
  794. wrmsrl(hwc->event_base,
  795. (u64)(-left) & x86_pmu.cntval_mask);
  796. }
  797. perf_event_update_userpage(event);
  798. return ret;
  799. }
  800. void x86_pmu_enable_event(struct perf_event *event)
  801. {
  802. if (__this_cpu_read(cpu_hw_events.enabled))
  803. __x86_pmu_enable_event(&event->hw,
  804. ARCH_PERFMON_EVENTSEL_ENABLE);
  805. }
  806. /*
  807. * Add a single event to the PMU.
  808. *
  809. * The event is added to the group of enabled events
  810. * but only if it can be scehduled with existing events.
  811. */
  812. static int x86_pmu_add(struct perf_event *event, int flags)
  813. {
  814. struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
  815. struct hw_perf_event *hwc;
  816. int assign[X86_PMC_IDX_MAX];
  817. int n, n0, ret;
  818. hwc = &event->hw;
  819. perf_pmu_disable(event->pmu);
  820. n0 = cpuc->n_events;
  821. ret = n = collect_events(cpuc, event, false);
  822. if (ret < 0)
  823. goto out;
  824. hwc->state = PERF_HES_UPTODATE | PERF_HES_STOPPED;
  825. if (!(flags & PERF_EF_START))
  826. hwc->state |= PERF_HES_ARCH;
  827. /*
  828. * If group events scheduling transaction was started,
  829. * skip the schedulability test here, it will be performed
  830. * at commit time (->commit_txn) as a whole
  831. */
  832. if (cpuc->group_flag & PERF_EVENT_TXN)
  833. goto done_collect;
  834. ret = x86_pmu.schedule_events(cpuc, n, assign);
  835. if (ret)
  836. goto out;
  837. /*
  838. * copy new assignment, now we know it is possible
  839. * will be used by hw_perf_enable()
  840. */
  841. memcpy(cpuc->assign, assign, n*sizeof(int));
  842. done_collect:
  843. cpuc->n_events = n;
  844. cpuc->n_added += n - n0;
  845. cpuc->n_txn += n - n0;
  846. ret = 0;
  847. out:
  848. perf_pmu_enable(event->pmu);
  849. return ret;
  850. }
  851. static void x86_pmu_start(struct perf_event *event, int flags)
  852. {
  853. struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
  854. int idx = event->hw.idx;
  855. if (WARN_ON_ONCE(!(event->hw.state & PERF_HES_STOPPED)))
  856. return;
  857. if (WARN_ON_ONCE(idx == -1))
  858. return;
  859. if (flags & PERF_EF_RELOAD) {
  860. WARN_ON_ONCE(!(event->hw.state & PERF_HES_UPTODATE));
  861. x86_perf_event_set_period(event);
  862. }
  863. event->hw.state = 0;
  864. cpuc->events[idx] = event;
  865. __set_bit(idx, cpuc->active_mask);
  866. __set_bit(idx, cpuc->running);
  867. x86_pmu.enable(event);
  868. perf_event_update_userpage(event);
  869. }
  870. void perf_event_print_debug(void)
  871. {
  872. u64 ctrl, status, overflow, pmc_ctrl, pmc_count, prev_left, fixed;
  873. u64 pebs;
  874. struct cpu_hw_events *cpuc;
  875. unsigned long flags;
  876. int cpu, idx;
  877. if (!x86_pmu.num_counters)
  878. return;
  879. local_irq_save(flags);
  880. cpu = smp_processor_id();
  881. cpuc = &per_cpu(cpu_hw_events, cpu);
  882. if (x86_pmu.version >= 2) {
  883. rdmsrl(MSR_CORE_PERF_GLOBAL_CTRL, ctrl);
  884. rdmsrl(MSR_CORE_PERF_GLOBAL_STATUS, status);
  885. rdmsrl(MSR_CORE_PERF_GLOBAL_OVF_CTRL, overflow);
  886. rdmsrl(MSR_ARCH_PERFMON_FIXED_CTR_CTRL, fixed);
  887. rdmsrl(MSR_IA32_PEBS_ENABLE, pebs);
  888. pr_info("\n");
  889. pr_info("CPU#%d: ctrl: %016llx\n", cpu, ctrl);
  890. pr_info("CPU#%d: status: %016llx\n", cpu, status);
  891. pr_info("CPU#%d: overflow: %016llx\n", cpu, overflow);
  892. pr_info("CPU#%d: fixed: %016llx\n", cpu, fixed);
  893. pr_info("CPU#%d: pebs: %016llx\n", cpu, pebs);
  894. }
  895. pr_info("CPU#%d: active: %016llx\n", cpu, *(u64 *)cpuc->active_mask);
  896. for (idx = 0; idx < x86_pmu.num_counters; idx++) {
  897. rdmsrl(x86_pmu_config_addr(idx), pmc_ctrl);
  898. rdmsrl(x86_pmu_event_addr(idx), pmc_count);
  899. prev_left = per_cpu(pmc_prev_left[idx], cpu);
  900. pr_info("CPU#%d: gen-PMC%d ctrl: %016llx\n",
  901. cpu, idx, pmc_ctrl);
  902. pr_info("CPU#%d: gen-PMC%d count: %016llx\n",
  903. cpu, idx, pmc_count);
  904. pr_info("CPU#%d: gen-PMC%d left: %016llx\n",
  905. cpu, idx, prev_left);
  906. }
  907. for (idx = 0; idx < x86_pmu.num_counters_fixed; idx++) {
  908. rdmsrl(MSR_ARCH_PERFMON_FIXED_CTR0 + idx, pmc_count);
  909. pr_info("CPU#%d: fixed-PMC%d count: %016llx\n",
  910. cpu, idx, pmc_count);
  911. }
  912. local_irq_restore(flags);
  913. }
  914. void x86_pmu_stop(struct perf_event *event, int flags)
  915. {
  916. struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
  917. struct hw_perf_event *hwc = &event->hw;
  918. if (__test_and_clear_bit(hwc->idx, cpuc->active_mask)) {
  919. x86_pmu.disable(event);
  920. cpuc->events[hwc->idx] = NULL;
  921. WARN_ON_ONCE(hwc->state & PERF_HES_STOPPED);
  922. hwc->state |= PERF_HES_STOPPED;
  923. }
  924. if ((flags & PERF_EF_UPDATE) && !(hwc->state & PERF_HES_UPTODATE)) {
  925. /*
  926. * Drain the remaining delta count out of a event
  927. * that we are disabling:
  928. */
  929. x86_perf_event_update(event);
  930. hwc->state |= PERF_HES_UPTODATE;
  931. }
  932. }
  933. static void x86_pmu_del(struct perf_event *event, int flags)
  934. {
  935. struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
  936. int i;
  937. /*
  938. * If we're called during a txn, we don't need to do anything.
  939. * The events never got scheduled and ->cancel_txn will truncate
  940. * the event_list.
  941. */
  942. if (cpuc->group_flag & PERF_EVENT_TXN)
  943. return;
  944. x86_pmu_stop(event, PERF_EF_UPDATE);
  945. for (i = 0; i < cpuc->n_events; i++) {
  946. if (event == cpuc->event_list[i]) {
  947. if (i >= cpuc->n_events - cpuc->n_added)
  948. --cpuc->n_added;
  949. if (x86_pmu.put_event_constraints)
  950. x86_pmu.put_event_constraints(cpuc, event);
  951. while (++i < cpuc->n_events)
  952. cpuc->event_list[i-1] = cpuc->event_list[i];
  953. --cpuc->n_events;
  954. break;
  955. }
  956. }
  957. perf_event_update_userpage(event);
  958. }
  959. int x86_pmu_handle_irq(struct pt_regs *regs)
  960. {
  961. struct perf_sample_data data;
  962. struct cpu_hw_events *cpuc;
  963. struct perf_event *event;
  964. int idx, handled = 0;
  965. u64 val;
  966. perf_sample_data_init(&data, 0);
  967. cpuc = &__get_cpu_var(cpu_hw_events);
  968. /*
  969. * Some chipsets need to unmask the LVTPC in a particular spot
  970. * inside the nmi handler. As a result, the unmasking was pushed
  971. * into all the nmi handlers.
  972. *
  973. * This generic handler doesn't seem to have any issues where the
  974. * unmasking occurs so it was left at the top.
  975. */
  976. apic_write(APIC_LVTPC, APIC_DM_NMI);
  977. for (idx = 0; idx < x86_pmu.num_counters; idx++) {
  978. if (!test_bit(idx, cpuc->active_mask)) {
  979. /*
  980. * Though we deactivated the counter some cpus
  981. * might still deliver spurious interrupts still
  982. * in flight. Catch them:
  983. */
  984. if (__test_and_clear_bit(idx, cpuc->running))
  985. handled++;
  986. continue;
  987. }
  988. event = cpuc->events[idx];
  989. val = x86_perf_event_update(event);
  990. if (val & (1ULL << (x86_pmu.cntval_bits - 1)))
  991. continue;
  992. /*
  993. * event overflow
  994. */
  995. handled++;
  996. data.period = event->hw.last_period;
  997. if (!x86_perf_event_set_period(event))
  998. continue;
  999. if (perf_event_overflow(event, &data, regs))
  1000. x86_pmu_stop(event, 0);
  1001. }
  1002. if (handled)
  1003. inc_irq_stat(apic_perf_irqs);
  1004. return handled;
  1005. }
  1006. void perf_events_lapic_init(void)
  1007. {
  1008. if (!x86_pmu.apic || !x86_pmu_initialized())
  1009. return;
  1010. /*
  1011. * Always use NMI for PMU
  1012. */
  1013. apic_write(APIC_LVTPC, APIC_DM_NMI);
  1014. }
  1015. static int __kprobes
  1016. perf_event_nmi_handler(unsigned int cmd, struct pt_regs *regs)
  1017. {
  1018. if (!atomic_read(&active_events))
  1019. return NMI_DONE;
  1020. return x86_pmu.handle_irq(regs);
  1021. }
  1022. struct event_constraint emptyconstraint;
  1023. struct event_constraint unconstrained;
  1024. static int __cpuinit
  1025. x86_pmu_notifier(struct notifier_block *self, unsigned long action, void *hcpu)
  1026. {
  1027. unsigned int cpu = (long)hcpu;
  1028. struct cpu_hw_events *cpuc = &per_cpu(cpu_hw_events, cpu);
  1029. int ret = NOTIFY_OK;
  1030. switch (action & ~CPU_TASKS_FROZEN) {
  1031. case CPU_UP_PREPARE:
  1032. cpuc->kfree_on_online = NULL;
  1033. if (x86_pmu.cpu_prepare)
  1034. ret = x86_pmu.cpu_prepare(cpu);
  1035. break;
  1036. case CPU_STARTING:
  1037. if (x86_pmu.attr_rdpmc)
  1038. set_in_cr4(X86_CR4_PCE);
  1039. if (x86_pmu.cpu_starting)
  1040. x86_pmu.cpu_starting(cpu);
  1041. break;
  1042. case CPU_ONLINE:
  1043. kfree(cpuc->kfree_on_online);
  1044. break;
  1045. case CPU_DYING:
  1046. if (x86_pmu.cpu_dying)
  1047. x86_pmu.cpu_dying(cpu);
  1048. break;
  1049. case CPU_UP_CANCELED:
  1050. case CPU_DEAD:
  1051. if (x86_pmu.cpu_dead)
  1052. x86_pmu.cpu_dead(cpu);
  1053. break;
  1054. default:
  1055. break;
  1056. }
  1057. return ret;
  1058. }
  1059. static void __init pmu_check_apic(void)
  1060. {
  1061. if (cpu_has_apic)
  1062. return;
  1063. x86_pmu.apic = 0;
  1064. pr_info("no APIC, boot with the \"lapic\" boot parameter to force-enable it.\n");
  1065. pr_info("no hardware sampling interrupt available.\n");
  1066. }
  1067. static struct attribute_group x86_pmu_format_group = {
  1068. .name = "format",
  1069. .attrs = NULL,
  1070. };
  1071. static int __init init_hw_perf_events(void)
  1072. {
  1073. struct x86_pmu_quirk *quirk;
  1074. struct event_constraint *c;
  1075. int err;
  1076. pr_info("Performance Events: ");
  1077. switch (boot_cpu_data.x86_vendor) {
  1078. case X86_VENDOR_INTEL:
  1079. err = intel_pmu_init();
  1080. break;
  1081. case X86_VENDOR_AMD:
  1082. err = amd_pmu_init();
  1083. break;
  1084. default:
  1085. return 0;
  1086. }
  1087. if (err != 0) {
  1088. pr_cont("no PMU driver, software events only.\n");
  1089. return 0;
  1090. }
  1091. pmu_check_apic();
  1092. /* sanity check that the hardware exists or is emulated */
  1093. if (!check_hw_exists())
  1094. return 0;
  1095. pr_cont("%s PMU driver.\n", x86_pmu.name);
  1096. for (quirk = x86_pmu.quirks; quirk; quirk = quirk->next)
  1097. quirk->func();
  1098. if (x86_pmu.num_counters > X86_PMC_MAX_GENERIC) {
  1099. WARN(1, KERN_ERR "hw perf events %d > max(%d), clipping!",
  1100. x86_pmu.num_counters, X86_PMC_MAX_GENERIC);
  1101. x86_pmu.num_counters = X86_PMC_MAX_GENERIC;
  1102. }
  1103. x86_pmu.intel_ctrl = (1 << x86_pmu.num_counters) - 1;
  1104. if (x86_pmu.num_counters_fixed > X86_PMC_MAX_FIXED) {
  1105. WARN(1, KERN_ERR "hw perf events fixed %d > max(%d), clipping!",
  1106. x86_pmu.num_counters_fixed, X86_PMC_MAX_FIXED);
  1107. x86_pmu.num_counters_fixed = X86_PMC_MAX_FIXED;
  1108. }
  1109. x86_pmu.intel_ctrl |=
  1110. ((1LL << x86_pmu.num_counters_fixed)-1) << X86_PMC_IDX_FIXED;
  1111. perf_events_lapic_init();
  1112. register_nmi_handler(NMI_LOCAL, perf_event_nmi_handler, 0, "PMI");
  1113. unconstrained = (struct event_constraint)
  1114. __EVENT_CONSTRAINT(0, (1ULL << x86_pmu.num_counters) - 1,
  1115. 0, x86_pmu.num_counters, 0);
  1116. if (x86_pmu.event_constraints) {
  1117. /*
  1118. * event on fixed counter2 (REF_CYCLES) only works on this
  1119. * counter, so do not extend mask to generic counters
  1120. */
  1121. for_each_event_constraint(c, x86_pmu.event_constraints) {
  1122. if (c->cmask != X86_RAW_EVENT_MASK
  1123. || c->idxmsk64 == X86_PMC_MSK_FIXED_REF_CYCLES) {
  1124. continue;
  1125. }
  1126. c->idxmsk64 |= (1ULL << x86_pmu.num_counters) - 1;
  1127. c->weight += x86_pmu.num_counters;
  1128. }
  1129. }
  1130. x86_pmu.attr_rdpmc = 1; /* enable userspace RDPMC usage by default */
  1131. x86_pmu_format_group.attrs = x86_pmu.format_attrs;
  1132. pr_info("... version: %d\n", x86_pmu.version);
  1133. pr_info("... bit width: %d\n", x86_pmu.cntval_bits);
  1134. pr_info("... generic registers: %d\n", x86_pmu.num_counters);
  1135. pr_info("... value mask: %016Lx\n", x86_pmu.cntval_mask);
  1136. pr_info("... max period: %016Lx\n", x86_pmu.max_period);
  1137. pr_info("... fixed-purpose events: %d\n", x86_pmu.num_counters_fixed);
  1138. pr_info("... event mask: %016Lx\n", x86_pmu.intel_ctrl);
  1139. perf_pmu_register(&pmu, "cpu", PERF_TYPE_RAW);
  1140. perf_cpu_notifier(x86_pmu_notifier);
  1141. return 0;
  1142. }
  1143. early_initcall(init_hw_perf_events);
  1144. static inline void x86_pmu_read(struct perf_event *event)
  1145. {
  1146. x86_perf_event_update(event);
  1147. }
  1148. /*
  1149. * Start group events scheduling transaction
  1150. * Set the flag to make pmu::enable() not perform the
  1151. * schedulability test, it will be performed at commit time
  1152. */
  1153. static void x86_pmu_start_txn(struct pmu *pmu)
  1154. {
  1155. perf_pmu_disable(pmu);
  1156. __this_cpu_or(cpu_hw_events.group_flag, PERF_EVENT_TXN);
  1157. __this_cpu_write(cpu_hw_events.n_txn, 0);
  1158. }
  1159. /*
  1160. * Stop group events scheduling transaction
  1161. * Clear the flag and pmu::enable() will perform the
  1162. * schedulability test.
  1163. */
  1164. static void x86_pmu_cancel_txn(struct pmu *pmu)
  1165. {
  1166. __this_cpu_and(cpu_hw_events.group_flag, ~PERF_EVENT_TXN);
  1167. /*
  1168. * Truncate the collected events.
  1169. */
  1170. __this_cpu_sub(cpu_hw_events.n_added, __this_cpu_read(cpu_hw_events.n_txn));
  1171. __this_cpu_sub(cpu_hw_events.n_events, __this_cpu_read(cpu_hw_events.n_txn));
  1172. perf_pmu_enable(pmu);
  1173. }
  1174. /*
  1175. * Commit group events scheduling transaction
  1176. * Perform the group schedulability test as a whole
  1177. * Return 0 if success
  1178. */
  1179. static int x86_pmu_commit_txn(struct pmu *pmu)
  1180. {
  1181. struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
  1182. int assign[X86_PMC_IDX_MAX];
  1183. int n, ret;
  1184. n = cpuc->n_events;
  1185. if (!x86_pmu_initialized())
  1186. return -EAGAIN;
  1187. ret = x86_pmu.schedule_events(cpuc, n, assign);
  1188. if (ret)
  1189. return ret;
  1190. /*
  1191. * copy new assignment, now we know it is possible
  1192. * will be used by hw_perf_enable()
  1193. */
  1194. memcpy(cpuc->assign, assign, n*sizeof(int));
  1195. cpuc->group_flag &= ~PERF_EVENT_TXN;
  1196. perf_pmu_enable(pmu);
  1197. return 0;
  1198. }
  1199. /*
  1200. * a fake_cpuc is used to validate event groups. Due to
  1201. * the extra reg logic, we need to also allocate a fake
  1202. * per_core and per_cpu structure. Otherwise, group events
  1203. * using extra reg may conflict without the kernel being
  1204. * able to catch this when the last event gets added to
  1205. * the group.
  1206. */
  1207. static void free_fake_cpuc(struct cpu_hw_events *cpuc)
  1208. {
  1209. kfree(cpuc->shared_regs);
  1210. kfree(cpuc);
  1211. }
  1212. static struct cpu_hw_events *allocate_fake_cpuc(void)
  1213. {
  1214. struct cpu_hw_events *cpuc;
  1215. int cpu = raw_smp_processor_id();
  1216. cpuc = kzalloc(sizeof(*cpuc), GFP_KERNEL);
  1217. if (!cpuc)
  1218. return ERR_PTR(-ENOMEM);
  1219. /* only needed, if we have extra_regs */
  1220. if (x86_pmu.extra_regs) {
  1221. cpuc->shared_regs = allocate_shared_regs(cpu);
  1222. if (!cpuc->shared_regs)
  1223. goto error;
  1224. }
  1225. return cpuc;
  1226. error:
  1227. free_fake_cpuc(cpuc);
  1228. return ERR_PTR(-ENOMEM);
  1229. }
  1230. /*
  1231. * validate that we can schedule this event
  1232. */
  1233. static int validate_event(struct perf_event *event)
  1234. {
  1235. struct cpu_hw_events *fake_cpuc;
  1236. struct event_constraint *c;
  1237. int ret = 0;
  1238. fake_cpuc = allocate_fake_cpuc();
  1239. if (IS_ERR(fake_cpuc))
  1240. return PTR_ERR(fake_cpuc);
  1241. c = x86_pmu.get_event_constraints(fake_cpuc, event);
  1242. if (!c || !c->weight)
  1243. ret = -EINVAL;
  1244. if (x86_pmu.put_event_constraints)
  1245. x86_pmu.put_event_constraints(fake_cpuc, event);
  1246. free_fake_cpuc(fake_cpuc);
  1247. return ret;
  1248. }
  1249. /*
  1250. * validate a single event group
  1251. *
  1252. * validation include:
  1253. * - check events are compatible which each other
  1254. * - events do not compete for the same counter
  1255. * - number of events <= number of counters
  1256. *
  1257. * validation ensures the group can be loaded onto the
  1258. * PMU if it was the only group available.
  1259. */
  1260. static int validate_group(struct perf_event *event)
  1261. {
  1262. struct perf_event *leader = event->group_leader;
  1263. struct cpu_hw_events *fake_cpuc;
  1264. int ret = -EINVAL, n;
  1265. fake_cpuc = allocate_fake_cpuc();
  1266. if (IS_ERR(fake_cpuc))
  1267. return PTR_ERR(fake_cpuc);
  1268. /*
  1269. * the event is not yet connected with its
  1270. * siblings therefore we must first collect
  1271. * existing siblings, then add the new event
  1272. * before we can simulate the scheduling
  1273. */
  1274. n = collect_events(fake_cpuc, leader, true);
  1275. if (n < 0)
  1276. goto out;
  1277. fake_cpuc->n_events = n;
  1278. n = collect_events(fake_cpuc, event, false);
  1279. if (n < 0)
  1280. goto out;
  1281. fake_cpuc->n_events = n;
  1282. ret = x86_pmu.schedule_events(fake_cpuc, n, NULL);
  1283. out:
  1284. free_fake_cpuc(fake_cpuc);
  1285. return ret;
  1286. }
  1287. static int x86_pmu_event_init(struct perf_event *event)
  1288. {
  1289. struct pmu *tmp;
  1290. int err;
  1291. switch (event->attr.type) {
  1292. case PERF_TYPE_RAW:
  1293. case PERF_TYPE_HARDWARE:
  1294. case PERF_TYPE_HW_CACHE:
  1295. break;
  1296. default:
  1297. return -ENOENT;
  1298. }
  1299. err = __x86_pmu_event_init(event);
  1300. if (!err) {
  1301. /*
  1302. * we temporarily connect event to its pmu
  1303. * such that validate_group() can classify
  1304. * it as an x86 event using is_x86_event()
  1305. */
  1306. tmp = event->pmu;
  1307. event->pmu = &pmu;
  1308. if (event->group_leader != event)
  1309. err = validate_group(event);
  1310. else
  1311. err = validate_event(event);
  1312. event->pmu = tmp;
  1313. }
  1314. if (err) {
  1315. if (event->destroy)
  1316. event->destroy(event);
  1317. }
  1318. return err;
  1319. }
  1320. static int x86_pmu_event_idx(struct perf_event *event)
  1321. {
  1322. int idx = event->hw.idx;
  1323. if (!x86_pmu.attr_rdpmc)
  1324. return 0;
  1325. if (x86_pmu.num_counters_fixed && idx >= X86_PMC_IDX_FIXED) {
  1326. idx -= X86_PMC_IDX_FIXED;
  1327. idx |= 1 << 30;
  1328. }
  1329. return idx + 1;
  1330. }
  1331. static ssize_t get_attr_rdpmc(struct device *cdev,
  1332. struct device_attribute *attr,
  1333. char *buf)
  1334. {
  1335. return snprintf(buf, 40, "%d\n", x86_pmu.attr_rdpmc);
  1336. }
  1337. static void change_rdpmc(void *info)
  1338. {
  1339. bool enable = !!(unsigned long)info;
  1340. if (enable)
  1341. set_in_cr4(X86_CR4_PCE);
  1342. else
  1343. clear_in_cr4(X86_CR4_PCE);
  1344. }
  1345. static ssize_t set_attr_rdpmc(struct device *cdev,
  1346. struct device_attribute *attr,
  1347. const char *buf, size_t count)
  1348. {
  1349. unsigned long val = simple_strtoul(buf, NULL, 0);
  1350. if (!!val != !!x86_pmu.attr_rdpmc) {
  1351. x86_pmu.attr_rdpmc = !!val;
  1352. smp_call_function(change_rdpmc, (void *)val, 1);
  1353. }
  1354. return count;
  1355. }
  1356. static DEVICE_ATTR(rdpmc, S_IRUSR | S_IWUSR, get_attr_rdpmc, set_attr_rdpmc);
  1357. static struct attribute *x86_pmu_attrs[] = {
  1358. &dev_attr_rdpmc.attr,
  1359. NULL,
  1360. };
  1361. static struct attribute_group x86_pmu_attr_group = {
  1362. .attrs = x86_pmu_attrs,
  1363. };
  1364. static const struct attribute_group *x86_pmu_attr_groups[] = {
  1365. &x86_pmu_attr_group,
  1366. &x86_pmu_format_group,
  1367. NULL,
  1368. };
  1369. static void x86_pmu_flush_branch_stack(void)
  1370. {
  1371. if (x86_pmu.flush_branch_stack)
  1372. x86_pmu.flush_branch_stack();
  1373. }
  1374. static struct pmu pmu = {
  1375. .pmu_enable = x86_pmu_enable,
  1376. .pmu_disable = x86_pmu_disable,
  1377. .attr_groups = x86_pmu_attr_groups,
  1378. .event_init = x86_pmu_event_init,
  1379. .add = x86_pmu_add,
  1380. .del = x86_pmu_del,
  1381. .start = x86_pmu_start,
  1382. .stop = x86_pmu_stop,
  1383. .read = x86_pmu_read,
  1384. .start_txn = x86_pmu_start_txn,
  1385. .cancel_txn = x86_pmu_cancel_txn,
  1386. .commit_txn = x86_pmu_commit_txn,
  1387. .event_idx = x86_pmu_event_idx,
  1388. .flush_branch_stack = x86_pmu_flush_branch_stack,
  1389. };
  1390. void arch_perf_update_userpage(struct perf_event_mmap_page *userpg, u64 now)
  1391. {
  1392. userpg->cap_usr_time = 0;
  1393. userpg->cap_usr_rdpmc = x86_pmu.attr_rdpmc;
  1394. userpg->pmc_width = x86_pmu.cntval_bits;
  1395. if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
  1396. return;
  1397. if (!boot_cpu_has(X86_FEATURE_NONSTOP_TSC))
  1398. return;
  1399. userpg->cap_usr_time = 1;
  1400. userpg->time_mult = this_cpu_read(cyc2ns);
  1401. userpg->time_shift = CYC2NS_SCALE_FACTOR;
  1402. userpg->time_offset = this_cpu_read(cyc2ns_offset) - now;
  1403. }
  1404. /*
  1405. * callchain support
  1406. */
  1407. static int backtrace_stack(void *data, char *name)
  1408. {
  1409. return 0;
  1410. }
  1411. static void backtrace_address(void *data, unsigned long addr, int reliable)
  1412. {
  1413. struct perf_callchain_entry *entry = data;
  1414. perf_callchain_store(entry, addr);
  1415. }
  1416. static const struct stacktrace_ops backtrace_ops = {
  1417. .stack = backtrace_stack,
  1418. .address = backtrace_address,
  1419. .walk_stack = print_context_stack_bp,
  1420. };
  1421. void
  1422. perf_callchain_kernel(struct perf_callchain_entry *entry, struct pt_regs *regs)
  1423. {
  1424. if (perf_guest_cbs && perf_guest_cbs->is_in_guest()) {
  1425. /* TODO: We don't support guest os callchain now */
  1426. return;
  1427. }
  1428. perf_callchain_store(entry, regs->ip);
  1429. dump_trace(NULL, regs, NULL, 0, &backtrace_ops, entry);
  1430. }
  1431. #ifdef CONFIG_COMPAT
  1432. #include <asm/compat.h>
  1433. static inline int
  1434. perf_callchain_user32(struct pt_regs *regs, struct perf_callchain_entry *entry)
  1435. {
  1436. /* 32-bit process in 64-bit kernel. */
  1437. struct stack_frame_ia32 frame;
  1438. const void __user *fp;
  1439. if (!test_thread_flag(TIF_IA32))
  1440. return 0;
  1441. fp = compat_ptr(regs->bp);
  1442. while (entry->nr < PERF_MAX_STACK_DEPTH) {
  1443. unsigned long bytes;
  1444. frame.next_frame = 0;
  1445. frame.return_address = 0;
  1446. bytes = copy_from_user_nmi(&frame, fp, sizeof(frame));
  1447. if (bytes != sizeof(frame))
  1448. break;
  1449. if (fp < compat_ptr(regs->sp))
  1450. break;
  1451. perf_callchain_store(entry, frame.return_address);
  1452. fp = compat_ptr(frame.next_frame);
  1453. }
  1454. return 1;
  1455. }
  1456. #else
  1457. static inline int
  1458. perf_callchain_user32(struct pt_regs *regs, struct perf_callchain_entry *entry)
  1459. {
  1460. return 0;
  1461. }
  1462. #endif
  1463. void
  1464. perf_callchain_user(struct perf_callchain_entry *entry, struct pt_regs *regs)
  1465. {
  1466. struct stack_frame frame;
  1467. const void __user *fp;
  1468. if (perf_guest_cbs && perf_guest_cbs->is_in_guest()) {
  1469. /* TODO: We don't support guest os callchain now */
  1470. return;
  1471. }
  1472. fp = (void __user *)regs->bp;
  1473. perf_callchain_store(entry, regs->ip);
  1474. if (!current->mm)
  1475. return;
  1476. if (perf_callchain_user32(regs, entry))
  1477. return;
  1478. while (entry->nr < PERF_MAX_STACK_DEPTH) {
  1479. unsigned long bytes;
  1480. frame.next_frame = NULL;
  1481. frame.return_address = 0;
  1482. bytes = copy_from_user_nmi(&frame, fp, sizeof(frame));
  1483. if (bytes != sizeof(frame))
  1484. break;
  1485. if ((unsigned long)fp < regs->sp)
  1486. break;
  1487. perf_callchain_store(entry, frame.return_address);
  1488. fp = frame.next_frame;
  1489. }
  1490. }
  1491. unsigned long perf_instruction_pointer(struct pt_regs *regs)
  1492. {
  1493. unsigned long ip;
  1494. if (perf_guest_cbs && perf_guest_cbs->is_in_guest())
  1495. ip = perf_guest_cbs->get_guest_ip();
  1496. else
  1497. ip = instruction_pointer(regs);
  1498. return ip;
  1499. }
  1500. unsigned long perf_misc_flags(struct pt_regs *regs)
  1501. {
  1502. int misc = 0;
  1503. if (perf_guest_cbs && perf_guest_cbs->is_in_guest()) {
  1504. if (perf_guest_cbs->is_user_mode())
  1505. misc |= PERF_RECORD_MISC_GUEST_USER;
  1506. else
  1507. misc |= PERF_RECORD_MISC_GUEST_KERNEL;
  1508. } else {
  1509. if (user_mode(regs))
  1510. misc |= PERF_RECORD_MISC_USER;
  1511. else
  1512. misc |= PERF_RECORD_MISC_KERNEL;
  1513. }
  1514. if (regs->flags & PERF_EFLAGS_EXACT)
  1515. misc |= PERF_RECORD_MISC_EXACT_IP;
  1516. return misc;
  1517. }
  1518. void perf_get_x86_pmu_capability(struct x86_pmu_capability *cap)
  1519. {
  1520. cap->version = x86_pmu.version;
  1521. cap->num_counters_gp = x86_pmu.num_counters;
  1522. cap->num_counters_fixed = x86_pmu.num_counters_fixed;
  1523. cap->bit_width_gp = x86_pmu.cntval_bits;
  1524. cap->bit_width_fixed = x86_pmu.cntval_bits;
  1525. cap->events_mask = (unsigned int)x86_pmu.events_maskl;
  1526. cap->events_mask_len = x86_pmu.events_mask_len;
  1527. }
  1528. EXPORT_SYMBOL_GPL(perf_get_x86_pmu_capability);