perf_event.c 43 KB

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