perf_event.c 42 KB

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