perf_event.c 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419
  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
  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 <linux/nospec.h>
  28. #include <asm/apic.h>
  29. #include <asm/stacktrace.h>
  30. #include <asm/nmi.h>
  31. #include <asm/smp.h>
  32. #include <asm/alternative.h>
  33. #include <asm/mmu_context.h>
  34. #include <asm/tlbflush.h>
  35. #include <asm/timer.h>
  36. #include <asm/desc.h>
  37. #include <asm/ldt.h>
  38. #include "perf_event.h"
  39. struct x86_pmu x86_pmu __read_mostly;
  40. DEFINE_PER_CPU(struct cpu_hw_events, cpu_hw_events) = {
  41. .enabled = 1,
  42. };
  43. struct static_key rdpmc_always_available = STATIC_KEY_INIT_FALSE;
  44. u64 __read_mostly hw_cache_event_ids
  45. [PERF_COUNT_HW_CACHE_MAX]
  46. [PERF_COUNT_HW_CACHE_OP_MAX]
  47. [PERF_COUNT_HW_CACHE_RESULT_MAX];
  48. u64 __read_mostly hw_cache_extra_regs
  49. [PERF_COUNT_HW_CACHE_MAX]
  50. [PERF_COUNT_HW_CACHE_OP_MAX]
  51. [PERF_COUNT_HW_CACHE_RESULT_MAX];
  52. /*
  53. * Propagate event elapsed time into the generic event.
  54. * Can only be executed on the CPU where the event is active.
  55. * Returns the delta events processed.
  56. */
  57. u64 x86_perf_event_update(struct perf_event *event)
  58. {
  59. struct hw_perf_event *hwc = &event->hw;
  60. int shift = 64 - x86_pmu.cntval_bits;
  61. u64 prev_raw_count, new_raw_count;
  62. int idx = hwc->idx;
  63. u64 delta;
  64. if (idx == INTEL_PMC_IDX_FIXED_BTS)
  65. return 0;
  66. /*
  67. * Careful: an NMI might modify the previous event value.
  68. *
  69. * Our tactic to handle this is to first atomically read and
  70. * exchange a new raw count - then add that new-prev delta
  71. * count to the generic event atomically:
  72. */
  73. again:
  74. prev_raw_count = local64_read(&hwc->prev_count);
  75. rdpmcl(hwc->event_base_rdpmc, new_raw_count);
  76. if (local64_cmpxchg(&hwc->prev_count, prev_raw_count,
  77. new_raw_count) != prev_raw_count)
  78. goto again;
  79. /*
  80. * Now we have the new raw value and have updated the prev
  81. * timestamp already. We can now calculate the elapsed delta
  82. * (event-)time and add that to the generic event.
  83. *
  84. * Careful, not all hw sign-extends above the physical width
  85. * of the count.
  86. */
  87. delta = (new_raw_count << shift) - (prev_raw_count << shift);
  88. delta >>= shift;
  89. local64_add(delta, &event->count);
  90. local64_sub(delta, &hwc->period_left);
  91. return new_raw_count;
  92. }
  93. /*
  94. * Find and validate any extra registers to set up.
  95. */
  96. static int x86_pmu_extra_regs(u64 config, struct perf_event *event)
  97. {
  98. struct hw_perf_event_extra *reg;
  99. struct extra_reg *er;
  100. reg = &event->hw.extra_reg;
  101. if (!x86_pmu.extra_regs)
  102. return 0;
  103. for (er = x86_pmu.extra_regs; er->msr; er++) {
  104. if (er->event != (config & er->config_mask))
  105. continue;
  106. if (event->attr.config1 & ~er->valid_mask)
  107. return -EINVAL;
  108. /* Check if the extra msrs can be safely accessed*/
  109. if (!er->extra_msr_access)
  110. return -ENXIO;
  111. reg->idx = er->idx;
  112. reg->config = event->attr.config1;
  113. reg->reg = er->msr;
  114. break;
  115. }
  116. return 0;
  117. }
  118. static atomic_t active_events;
  119. static atomic_t pmc_refcount;
  120. static DEFINE_MUTEX(pmc_reserve_mutex);
  121. #ifdef CONFIG_X86_LOCAL_APIC
  122. static bool reserve_pmc_hardware(void)
  123. {
  124. int i;
  125. for (i = 0; i < x86_pmu.num_counters; i++) {
  126. if (!reserve_perfctr_nmi(x86_pmu_event_addr(i)))
  127. goto perfctr_fail;
  128. }
  129. for (i = 0; i < x86_pmu.num_counters; i++) {
  130. if (!reserve_evntsel_nmi(x86_pmu_config_addr(i)))
  131. goto eventsel_fail;
  132. }
  133. return true;
  134. eventsel_fail:
  135. for (i--; i >= 0; i--)
  136. release_evntsel_nmi(x86_pmu_config_addr(i));
  137. i = x86_pmu.num_counters;
  138. perfctr_fail:
  139. for (i--; i >= 0; i--)
  140. release_perfctr_nmi(x86_pmu_event_addr(i));
  141. return false;
  142. }
  143. static void release_pmc_hardware(void)
  144. {
  145. int i;
  146. for (i = 0; i < x86_pmu.num_counters; i++) {
  147. release_perfctr_nmi(x86_pmu_event_addr(i));
  148. release_evntsel_nmi(x86_pmu_config_addr(i));
  149. }
  150. }
  151. #else
  152. static bool reserve_pmc_hardware(void) { return true; }
  153. static void release_pmc_hardware(void) {}
  154. #endif
  155. static bool check_hw_exists(void)
  156. {
  157. u64 val, val_fail = -1, val_new= ~0;
  158. int i, reg, reg_fail = -1, ret = 0;
  159. int bios_fail = 0;
  160. int reg_safe = -1;
  161. /*
  162. * Check to see if the BIOS enabled any of the counters, if so
  163. * complain and bail.
  164. */
  165. for (i = 0; i < x86_pmu.num_counters; i++) {
  166. reg = x86_pmu_config_addr(i);
  167. ret = rdmsrl_safe(reg, &val);
  168. if (ret)
  169. goto msr_fail;
  170. if (val & ARCH_PERFMON_EVENTSEL_ENABLE) {
  171. bios_fail = 1;
  172. val_fail = val;
  173. reg_fail = reg;
  174. } else {
  175. reg_safe = i;
  176. }
  177. }
  178. if (x86_pmu.num_counters_fixed) {
  179. reg = MSR_ARCH_PERFMON_FIXED_CTR_CTRL;
  180. ret = rdmsrl_safe(reg, &val);
  181. if (ret)
  182. goto msr_fail;
  183. for (i = 0; i < x86_pmu.num_counters_fixed; i++) {
  184. if (val & (0x03 << i*4)) {
  185. bios_fail = 1;
  186. val_fail = val;
  187. reg_fail = reg;
  188. }
  189. }
  190. }
  191. /*
  192. * If all the counters are enabled, the below test will always
  193. * fail. The tools will also become useless in this scenario.
  194. * Just fail and disable the hardware counters.
  195. */
  196. if (reg_safe == -1) {
  197. reg = reg_safe;
  198. goto msr_fail;
  199. }
  200. /*
  201. * Read the current value, change it and read it back to see if it
  202. * matches, this is needed to detect certain hardware emulators
  203. * (qemu/kvm) that don't trap on the MSR access and always return 0s.
  204. */
  205. reg = x86_pmu_event_addr(reg_safe);
  206. if (rdmsrl_safe(reg, &val))
  207. goto msr_fail;
  208. val ^= 0xffffUL;
  209. ret = wrmsrl_safe(reg, val);
  210. ret |= rdmsrl_safe(reg, &val_new);
  211. if (ret || val != val_new)
  212. goto msr_fail;
  213. /*
  214. * We still allow the PMU driver to operate:
  215. */
  216. if (bios_fail) {
  217. printk(KERN_CONT "Broken BIOS detected, complain to your hardware vendor.\n");
  218. printk(KERN_ERR FW_BUG "the BIOS has corrupted hw-PMU resources (MSR %x is %Lx)\n", reg_fail, val_fail);
  219. }
  220. return true;
  221. msr_fail:
  222. printk(KERN_CONT "Broken PMU hardware detected, using software events only.\n");
  223. printk("%sFailed to access perfctr msr (MSR %x is %Lx)\n",
  224. boot_cpu_has(X86_FEATURE_HYPERVISOR) ? KERN_INFO : KERN_ERR,
  225. reg, val_new);
  226. return false;
  227. }
  228. static void hw_perf_event_destroy(struct perf_event *event)
  229. {
  230. x86_release_hardware();
  231. atomic_dec(&active_events);
  232. }
  233. void hw_perf_lbr_event_destroy(struct perf_event *event)
  234. {
  235. hw_perf_event_destroy(event);
  236. /* undo the lbr/bts event accounting */
  237. x86_del_exclusive(x86_lbr_exclusive_lbr);
  238. }
  239. static inline int x86_pmu_initialized(void)
  240. {
  241. return x86_pmu.handle_irq != NULL;
  242. }
  243. static inline int
  244. set_ext_hw_attr(struct hw_perf_event *hwc, struct perf_event *event)
  245. {
  246. struct perf_event_attr *attr = &event->attr;
  247. unsigned int cache_type, cache_op, cache_result;
  248. u64 config, val;
  249. config = attr->config;
  250. cache_type = (config >> 0) & 0xff;
  251. if (cache_type >= PERF_COUNT_HW_CACHE_MAX)
  252. return -EINVAL;
  253. cache_type = array_index_nospec(cache_type, PERF_COUNT_HW_CACHE_MAX);
  254. cache_op = (config >> 8) & 0xff;
  255. if (cache_op >= PERF_COUNT_HW_CACHE_OP_MAX)
  256. return -EINVAL;
  257. cache_op = array_index_nospec(cache_op, PERF_COUNT_HW_CACHE_OP_MAX);
  258. cache_result = (config >> 16) & 0xff;
  259. if (cache_result >= PERF_COUNT_HW_CACHE_RESULT_MAX)
  260. return -EINVAL;
  261. cache_result = array_index_nospec(cache_result, PERF_COUNT_HW_CACHE_RESULT_MAX);
  262. val = hw_cache_event_ids[cache_type][cache_op][cache_result];
  263. if (val == 0)
  264. return -ENOENT;
  265. if (val == -1)
  266. return -EINVAL;
  267. hwc->config |= val;
  268. attr->config1 = hw_cache_extra_regs[cache_type][cache_op][cache_result];
  269. return x86_pmu_extra_regs(val, event);
  270. }
  271. int x86_reserve_hardware(void)
  272. {
  273. int err = 0;
  274. if (!atomic_inc_not_zero(&pmc_refcount)) {
  275. mutex_lock(&pmc_reserve_mutex);
  276. if (atomic_read(&pmc_refcount) == 0) {
  277. if (!reserve_pmc_hardware())
  278. err = -EBUSY;
  279. else
  280. reserve_ds_buffers();
  281. }
  282. if (!err)
  283. atomic_inc(&pmc_refcount);
  284. mutex_unlock(&pmc_reserve_mutex);
  285. }
  286. return err;
  287. }
  288. void x86_release_hardware(void)
  289. {
  290. if (atomic_dec_and_mutex_lock(&pmc_refcount, &pmc_reserve_mutex)) {
  291. release_pmc_hardware();
  292. release_ds_buffers();
  293. mutex_unlock(&pmc_reserve_mutex);
  294. }
  295. }
  296. /*
  297. * Check if we can create event of a certain type (that no conflicting events
  298. * are present).
  299. */
  300. int x86_add_exclusive(unsigned int what)
  301. {
  302. int i;
  303. if (!atomic_inc_not_zero(&x86_pmu.lbr_exclusive[what])) {
  304. mutex_lock(&pmc_reserve_mutex);
  305. for (i = 0; i < ARRAY_SIZE(x86_pmu.lbr_exclusive); i++) {
  306. if (i != what && atomic_read(&x86_pmu.lbr_exclusive[i]))
  307. goto fail_unlock;
  308. }
  309. atomic_inc(&x86_pmu.lbr_exclusive[what]);
  310. mutex_unlock(&pmc_reserve_mutex);
  311. }
  312. atomic_inc(&active_events);
  313. return 0;
  314. fail_unlock:
  315. mutex_unlock(&pmc_reserve_mutex);
  316. return -EBUSY;
  317. }
  318. void x86_del_exclusive(unsigned int what)
  319. {
  320. atomic_dec(&x86_pmu.lbr_exclusive[what]);
  321. atomic_dec(&active_events);
  322. }
  323. int x86_setup_perfctr(struct perf_event *event)
  324. {
  325. struct perf_event_attr *attr = &event->attr;
  326. struct hw_perf_event *hwc = &event->hw;
  327. u64 config;
  328. if (!is_sampling_event(event)) {
  329. hwc->sample_period = x86_pmu.max_period;
  330. hwc->last_period = hwc->sample_period;
  331. local64_set(&hwc->period_left, hwc->sample_period);
  332. }
  333. if (attr->type == PERF_TYPE_RAW)
  334. return x86_pmu_extra_regs(event->attr.config, event);
  335. if (attr->type == PERF_TYPE_HW_CACHE)
  336. return set_ext_hw_attr(hwc, event);
  337. if (attr->config >= x86_pmu.max_events)
  338. return -EINVAL;
  339. attr->config = array_index_nospec((unsigned long)attr->config, x86_pmu.max_events);
  340. /*
  341. * The generic map:
  342. */
  343. config = x86_pmu.event_map(attr->config);
  344. if (config == 0)
  345. return -ENOENT;
  346. if (config == -1LL)
  347. return -EINVAL;
  348. /*
  349. * Branch tracing:
  350. */
  351. if (attr->config == PERF_COUNT_HW_BRANCH_INSTRUCTIONS &&
  352. !attr->freq && hwc->sample_period == 1) {
  353. /* BTS is not supported by this architecture. */
  354. if (!x86_pmu.bts_active)
  355. return -EOPNOTSUPP;
  356. /* BTS is currently only allowed for user-mode. */
  357. if (!attr->exclude_kernel)
  358. return -EOPNOTSUPP;
  359. /* disallow bts if conflicting events are present */
  360. if (x86_add_exclusive(x86_lbr_exclusive_lbr))
  361. return -EBUSY;
  362. event->destroy = hw_perf_lbr_event_destroy;
  363. }
  364. hwc->config |= config;
  365. return 0;
  366. }
  367. /*
  368. * check that branch_sample_type is compatible with
  369. * settings needed for precise_ip > 1 which implies
  370. * using the LBR to capture ALL taken branches at the
  371. * priv levels of the measurement
  372. */
  373. static inline int precise_br_compat(struct perf_event *event)
  374. {
  375. u64 m = event->attr.branch_sample_type;
  376. u64 b = 0;
  377. /* must capture all branches */
  378. if (!(m & PERF_SAMPLE_BRANCH_ANY))
  379. return 0;
  380. m &= PERF_SAMPLE_BRANCH_KERNEL | PERF_SAMPLE_BRANCH_USER;
  381. if (!event->attr.exclude_user)
  382. b |= PERF_SAMPLE_BRANCH_USER;
  383. if (!event->attr.exclude_kernel)
  384. b |= PERF_SAMPLE_BRANCH_KERNEL;
  385. /*
  386. * ignore PERF_SAMPLE_BRANCH_HV, not supported on x86
  387. */
  388. return m == b;
  389. }
  390. int x86_pmu_hw_config(struct perf_event *event)
  391. {
  392. if (event->attr.precise_ip) {
  393. int precise = 0;
  394. /* Support for constant skid */
  395. if (x86_pmu.pebs_active && !x86_pmu.pebs_broken) {
  396. precise++;
  397. /* Support for IP fixup */
  398. if (x86_pmu.lbr_nr || x86_pmu.intel_cap.pebs_format >= 2)
  399. precise++;
  400. }
  401. if (event->attr.precise_ip > precise)
  402. return -EOPNOTSUPP;
  403. }
  404. /*
  405. * check that PEBS LBR correction does not conflict with
  406. * whatever the user is asking with attr->branch_sample_type
  407. */
  408. if (event->attr.precise_ip > 1 && x86_pmu.intel_cap.pebs_format < 2) {
  409. u64 *br_type = &event->attr.branch_sample_type;
  410. if (has_branch_stack(event)) {
  411. if (!precise_br_compat(event))
  412. return -EOPNOTSUPP;
  413. /* branch_sample_type is compatible */
  414. } else {
  415. /*
  416. * user did not specify branch_sample_type
  417. *
  418. * For PEBS fixups, we capture all
  419. * the branches at the priv level of the
  420. * event.
  421. */
  422. *br_type = PERF_SAMPLE_BRANCH_ANY;
  423. if (!event->attr.exclude_user)
  424. *br_type |= PERF_SAMPLE_BRANCH_USER;
  425. if (!event->attr.exclude_kernel)
  426. *br_type |= PERF_SAMPLE_BRANCH_KERNEL;
  427. }
  428. }
  429. if (event->attr.branch_sample_type & PERF_SAMPLE_BRANCH_CALL_STACK)
  430. event->attach_state |= PERF_ATTACH_TASK_DATA;
  431. /*
  432. * Generate PMC IRQs:
  433. * (keep 'enabled' bit clear for now)
  434. */
  435. event->hw.config = ARCH_PERFMON_EVENTSEL_INT;
  436. /*
  437. * Count user and OS events unless requested not to
  438. */
  439. if (!event->attr.exclude_user)
  440. event->hw.config |= ARCH_PERFMON_EVENTSEL_USR;
  441. if (!event->attr.exclude_kernel)
  442. event->hw.config |= ARCH_PERFMON_EVENTSEL_OS;
  443. if (event->attr.type == PERF_TYPE_RAW)
  444. event->hw.config |= event->attr.config & X86_RAW_EVENT_MASK;
  445. if (event->attr.sample_period && x86_pmu.limit_period) {
  446. if (x86_pmu.limit_period(event, event->attr.sample_period) >
  447. event->attr.sample_period)
  448. return -EINVAL;
  449. }
  450. return x86_setup_perfctr(event);
  451. }
  452. /*
  453. * Setup the hardware configuration for a given attr_type
  454. */
  455. static int __x86_pmu_event_init(struct perf_event *event)
  456. {
  457. int err;
  458. if (!x86_pmu_initialized())
  459. return -ENODEV;
  460. err = x86_reserve_hardware();
  461. if (err)
  462. return err;
  463. atomic_inc(&active_events);
  464. event->destroy = hw_perf_event_destroy;
  465. event->hw.idx = -1;
  466. event->hw.last_cpu = -1;
  467. event->hw.last_tag = ~0ULL;
  468. /* mark unused */
  469. event->hw.extra_reg.idx = EXTRA_REG_NONE;
  470. event->hw.branch_reg.idx = EXTRA_REG_NONE;
  471. return x86_pmu.hw_config(event);
  472. }
  473. void x86_pmu_disable_all(void)
  474. {
  475. struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
  476. int idx;
  477. for (idx = 0; idx < x86_pmu.num_counters; idx++) {
  478. u64 val;
  479. if (!test_bit(idx, cpuc->active_mask))
  480. continue;
  481. rdmsrl(x86_pmu_config_addr(idx), val);
  482. if (!(val & ARCH_PERFMON_EVENTSEL_ENABLE))
  483. continue;
  484. val &= ~ARCH_PERFMON_EVENTSEL_ENABLE;
  485. wrmsrl(x86_pmu_config_addr(idx), val);
  486. }
  487. }
  488. /*
  489. * There may be PMI landing after enabled=0. The PMI hitting could be before or
  490. * after disable_all.
  491. *
  492. * If PMI hits before disable_all, the PMU will be disabled in the NMI handler.
  493. * It will not be re-enabled in the NMI handler again, because enabled=0. After
  494. * handling the NMI, disable_all will be called, which will not change the
  495. * state either. If PMI hits after disable_all, the PMU is already disabled
  496. * before entering NMI handler. The NMI handler will not change the state
  497. * either.
  498. *
  499. * So either situation is harmless.
  500. */
  501. static void x86_pmu_disable(struct pmu *pmu)
  502. {
  503. struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
  504. if (!x86_pmu_initialized())
  505. return;
  506. if (!cpuc->enabled)
  507. return;
  508. cpuc->n_added = 0;
  509. cpuc->enabled = 0;
  510. barrier();
  511. x86_pmu.disable_all();
  512. }
  513. void x86_pmu_enable_all(int added)
  514. {
  515. struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
  516. int idx;
  517. for (idx = 0; idx < x86_pmu.num_counters; idx++) {
  518. struct hw_perf_event *hwc = &cpuc->events[idx]->hw;
  519. if (!test_bit(idx, cpuc->active_mask))
  520. continue;
  521. __x86_pmu_enable_event(hwc, ARCH_PERFMON_EVENTSEL_ENABLE);
  522. }
  523. }
  524. static struct pmu pmu;
  525. static inline int is_x86_event(struct perf_event *event)
  526. {
  527. return event->pmu == &pmu;
  528. }
  529. /*
  530. * Event scheduler state:
  531. *
  532. * Assign events iterating over all events and counters, beginning
  533. * with events with least weights first. Keep the current iterator
  534. * state in struct sched_state.
  535. */
  536. struct sched_state {
  537. int weight;
  538. int event; /* event index */
  539. int counter; /* counter index */
  540. int unassigned; /* number of events to be assigned left */
  541. int nr_gp; /* number of GP counters used */
  542. unsigned long used[BITS_TO_LONGS(X86_PMC_IDX_MAX)];
  543. };
  544. /* Total max is X86_PMC_IDX_MAX, but we are O(n!) limited */
  545. #define SCHED_STATES_MAX 2
  546. struct perf_sched {
  547. int max_weight;
  548. int max_events;
  549. int max_gp;
  550. int saved_states;
  551. struct event_constraint **constraints;
  552. struct sched_state state;
  553. struct sched_state saved[SCHED_STATES_MAX];
  554. };
  555. /*
  556. * Initialize interator that runs through all events and counters.
  557. */
  558. static void perf_sched_init(struct perf_sched *sched, struct event_constraint **constraints,
  559. int num, int wmin, int wmax, int gpmax)
  560. {
  561. int idx;
  562. memset(sched, 0, sizeof(*sched));
  563. sched->max_events = num;
  564. sched->max_weight = wmax;
  565. sched->max_gp = gpmax;
  566. sched->constraints = constraints;
  567. for (idx = 0; idx < num; idx++) {
  568. if (constraints[idx]->weight == wmin)
  569. break;
  570. }
  571. sched->state.event = idx; /* start with min weight */
  572. sched->state.weight = wmin;
  573. sched->state.unassigned = num;
  574. }
  575. static void perf_sched_save_state(struct perf_sched *sched)
  576. {
  577. if (WARN_ON_ONCE(sched->saved_states >= SCHED_STATES_MAX))
  578. return;
  579. sched->saved[sched->saved_states] = sched->state;
  580. sched->saved_states++;
  581. }
  582. static bool perf_sched_restore_state(struct perf_sched *sched)
  583. {
  584. if (!sched->saved_states)
  585. return false;
  586. sched->saved_states--;
  587. sched->state = sched->saved[sched->saved_states];
  588. /* continue with next counter: */
  589. clear_bit(sched->state.counter++, sched->state.used);
  590. return true;
  591. }
  592. /*
  593. * Select a counter for the current event to schedule. Return true on
  594. * success.
  595. */
  596. static bool __perf_sched_find_counter(struct perf_sched *sched)
  597. {
  598. struct event_constraint *c;
  599. int idx;
  600. if (!sched->state.unassigned)
  601. return false;
  602. if (sched->state.event >= sched->max_events)
  603. return false;
  604. c = sched->constraints[sched->state.event];
  605. /* Prefer fixed purpose counters */
  606. if (c->idxmsk64 & (~0ULL << INTEL_PMC_IDX_FIXED)) {
  607. idx = INTEL_PMC_IDX_FIXED;
  608. for_each_set_bit_from(idx, c->idxmsk, X86_PMC_IDX_MAX) {
  609. if (!__test_and_set_bit(idx, sched->state.used))
  610. goto done;
  611. }
  612. }
  613. /* Grab the first unused counter starting with idx */
  614. idx = sched->state.counter;
  615. for_each_set_bit_from(idx, c->idxmsk, INTEL_PMC_IDX_FIXED) {
  616. if (!__test_and_set_bit(idx, sched->state.used)) {
  617. if (sched->state.nr_gp++ >= sched->max_gp)
  618. return false;
  619. goto done;
  620. }
  621. }
  622. return false;
  623. done:
  624. sched->state.counter = idx;
  625. if (c->overlap)
  626. perf_sched_save_state(sched);
  627. return true;
  628. }
  629. static bool perf_sched_find_counter(struct perf_sched *sched)
  630. {
  631. while (!__perf_sched_find_counter(sched)) {
  632. if (!perf_sched_restore_state(sched))
  633. return false;
  634. }
  635. return true;
  636. }
  637. /*
  638. * Go through all unassigned events and find the next one to schedule.
  639. * Take events with the least weight first. Return true on success.
  640. */
  641. static bool perf_sched_next_event(struct perf_sched *sched)
  642. {
  643. struct event_constraint *c;
  644. if (!sched->state.unassigned || !--sched->state.unassigned)
  645. return false;
  646. do {
  647. /* next event */
  648. sched->state.event++;
  649. if (sched->state.event >= sched->max_events) {
  650. /* next weight */
  651. sched->state.event = 0;
  652. sched->state.weight++;
  653. if (sched->state.weight > sched->max_weight)
  654. return false;
  655. }
  656. c = sched->constraints[sched->state.event];
  657. } while (c->weight != sched->state.weight);
  658. sched->state.counter = 0; /* start with first counter */
  659. return true;
  660. }
  661. /*
  662. * Assign a counter for each event.
  663. */
  664. int perf_assign_events(struct event_constraint **constraints, int n,
  665. int wmin, int wmax, int gpmax, int *assign)
  666. {
  667. struct perf_sched sched;
  668. perf_sched_init(&sched, constraints, n, wmin, wmax, gpmax);
  669. do {
  670. if (!perf_sched_find_counter(&sched))
  671. break; /* failed */
  672. if (assign)
  673. assign[sched.state.event] = sched.state.counter;
  674. } while (perf_sched_next_event(&sched));
  675. return sched.state.unassigned;
  676. }
  677. EXPORT_SYMBOL_GPL(perf_assign_events);
  678. int x86_schedule_events(struct cpu_hw_events *cpuc, int n, int *assign)
  679. {
  680. struct event_constraint *c;
  681. unsigned long used_mask[BITS_TO_LONGS(X86_PMC_IDX_MAX)];
  682. struct perf_event *e;
  683. int i, wmin, wmax, unsched = 0;
  684. struct hw_perf_event *hwc;
  685. bitmap_zero(used_mask, X86_PMC_IDX_MAX);
  686. if (x86_pmu.start_scheduling)
  687. x86_pmu.start_scheduling(cpuc);
  688. for (i = 0, wmin = X86_PMC_IDX_MAX, wmax = 0; i < n; i++) {
  689. cpuc->event_constraint[i] = NULL;
  690. c = x86_pmu.get_event_constraints(cpuc, i, cpuc->event_list[i]);
  691. cpuc->event_constraint[i] = c;
  692. wmin = min(wmin, c->weight);
  693. wmax = max(wmax, c->weight);
  694. }
  695. /*
  696. * fastpath, try to reuse previous register
  697. */
  698. for (i = 0; i < n; i++) {
  699. hwc = &cpuc->event_list[i]->hw;
  700. c = cpuc->event_constraint[i];
  701. /* never assigned */
  702. if (hwc->idx == -1)
  703. break;
  704. /* constraint still honored */
  705. if (!test_bit(hwc->idx, c->idxmsk))
  706. break;
  707. /* not already used */
  708. if (test_bit(hwc->idx, used_mask))
  709. break;
  710. __set_bit(hwc->idx, used_mask);
  711. if (assign)
  712. assign[i] = hwc->idx;
  713. }
  714. /* slow path */
  715. if (i != n) {
  716. int gpmax = x86_pmu.num_counters;
  717. /*
  718. * Do not allow scheduling of more than half the available
  719. * generic counters.
  720. *
  721. * This helps avoid counter starvation of sibling thread by
  722. * ensuring at most half the counters cannot be in exclusive
  723. * mode. There is no designated counters for the limits. Any
  724. * N/2 counters can be used. This helps with events with
  725. * specific counter constraints.
  726. */
  727. if (is_ht_workaround_enabled() && !cpuc->is_fake &&
  728. READ_ONCE(cpuc->excl_cntrs->exclusive_present))
  729. gpmax /= 2;
  730. unsched = perf_assign_events(cpuc->event_constraint, n, wmin,
  731. wmax, gpmax, assign);
  732. }
  733. /*
  734. * In case of success (unsched = 0), mark events as committed,
  735. * so we do not put_constraint() in case new events are added
  736. * and fail to be scheduled
  737. *
  738. * We invoke the lower level commit callback to lock the resource
  739. *
  740. * We do not need to do all of this in case we are called to
  741. * validate an event group (assign == NULL)
  742. */
  743. if (!unsched && assign) {
  744. for (i = 0; i < n; i++) {
  745. e = cpuc->event_list[i];
  746. e->hw.flags |= PERF_X86_EVENT_COMMITTED;
  747. if (x86_pmu.commit_scheduling)
  748. x86_pmu.commit_scheduling(cpuc, i, assign[i]);
  749. }
  750. } else {
  751. for (i = 0; i < n; i++) {
  752. e = cpuc->event_list[i];
  753. /*
  754. * do not put_constraint() on comitted events,
  755. * because they are good to go
  756. */
  757. if ((e->hw.flags & PERF_X86_EVENT_COMMITTED))
  758. continue;
  759. /*
  760. * release events that failed scheduling
  761. */
  762. if (x86_pmu.put_event_constraints)
  763. x86_pmu.put_event_constraints(cpuc, e);
  764. }
  765. }
  766. if (x86_pmu.stop_scheduling)
  767. x86_pmu.stop_scheduling(cpuc);
  768. return unsched ? -EINVAL : 0;
  769. }
  770. /*
  771. * dogrp: true if must collect siblings events (group)
  772. * returns total number of events and error code
  773. */
  774. static int collect_events(struct cpu_hw_events *cpuc, struct perf_event *leader, bool dogrp)
  775. {
  776. struct perf_event *event;
  777. int n, max_count;
  778. max_count = x86_pmu.num_counters + x86_pmu.num_counters_fixed;
  779. /* current number of events already accepted */
  780. n = cpuc->n_events;
  781. if (is_x86_event(leader)) {
  782. if (n >= max_count)
  783. return -EINVAL;
  784. cpuc->event_list[n] = leader;
  785. n++;
  786. }
  787. if (!dogrp)
  788. return n;
  789. list_for_each_entry(event, &leader->sibling_list, group_entry) {
  790. if (!is_x86_event(event) ||
  791. event->state <= PERF_EVENT_STATE_OFF)
  792. continue;
  793. if (n >= max_count)
  794. return -EINVAL;
  795. cpuc->event_list[n] = event;
  796. n++;
  797. }
  798. return n;
  799. }
  800. static inline void x86_assign_hw_event(struct perf_event *event,
  801. struct cpu_hw_events *cpuc, int i)
  802. {
  803. struct hw_perf_event *hwc = &event->hw;
  804. hwc->idx = cpuc->assign[i];
  805. hwc->last_cpu = smp_processor_id();
  806. hwc->last_tag = ++cpuc->tags[i];
  807. if (hwc->idx == INTEL_PMC_IDX_FIXED_BTS) {
  808. hwc->config_base = 0;
  809. hwc->event_base = 0;
  810. } else if (hwc->idx >= INTEL_PMC_IDX_FIXED) {
  811. hwc->config_base = MSR_ARCH_PERFMON_FIXED_CTR_CTRL;
  812. hwc->event_base = MSR_ARCH_PERFMON_FIXED_CTR0 + (hwc->idx - INTEL_PMC_IDX_FIXED);
  813. hwc->event_base_rdpmc = (hwc->idx - INTEL_PMC_IDX_FIXED) | 1<<30;
  814. } else {
  815. hwc->config_base = x86_pmu_config_addr(hwc->idx);
  816. hwc->event_base = x86_pmu_event_addr(hwc->idx);
  817. hwc->event_base_rdpmc = x86_pmu_rdpmc_index(hwc->idx);
  818. }
  819. }
  820. static inline int match_prev_assignment(struct hw_perf_event *hwc,
  821. struct cpu_hw_events *cpuc,
  822. int i)
  823. {
  824. return hwc->idx == cpuc->assign[i] &&
  825. hwc->last_cpu == smp_processor_id() &&
  826. hwc->last_tag == cpuc->tags[i];
  827. }
  828. static void x86_pmu_start(struct perf_event *event, int flags);
  829. static void x86_pmu_enable(struct pmu *pmu)
  830. {
  831. struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
  832. struct perf_event *event;
  833. struct hw_perf_event *hwc;
  834. int i, added = cpuc->n_added;
  835. if (!x86_pmu_initialized())
  836. return;
  837. if (cpuc->enabled)
  838. return;
  839. if (cpuc->n_added) {
  840. int n_running = cpuc->n_events - cpuc->n_added;
  841. /*
  842. * apply assignment obtained either from
  843. * hw_perf_group_sched_in() or x86_pmu_enable()
  844. *
  845. * step1: save events moving to new counters
  846. */
  847. for (i = 0; i < n_running; i++) {
  848. event = cpuc->event_list[i];
  849. hwc = &event->hw;
  850. /*
  851. * we can avoid reprogramming counter if:
  852. * - assigned same counter as last time
  853. * - running on same CPU as last time
  854. * - no other event has used the counter since
  855. */
  856. if (hwc->idx == -1 ||
  857. match_prev_assignment(hwc, cpuc, i))
  858. continue;
  859. /*
  860. * Ensure we don't accidentally enable a stopped
  861. * counter simply because we rescheduled.
  862. */
  863. if (hwc->state & PERF_HES_STOPPED)
  864. hwc->state |= PERF_HES_ARCH;
  865. x86_pmu_stop(event, PERF_EF_UPDATE);
  866. }
  867. /*
  868. * step2: reprogram moved events into new counters
  869. */
  870. for (i = 0; i < cpuc->n_events; i++) {
  871. event = cpuc->event_list[i];
  872. hwc = &event->hw;
  873. if (!match_prev_assignment(hwc, cpuc, i))
  874. x86_assign_hw_event(event, cpuc, i);
  875. else if (i < n_running)
  876. continue;
  877. if (hwc->state & PERF_HES_ARCH)
  878. continue;
  879. x86_pmu_start(event, PERF_EF_RELOAD);
  880. }
  881. cpuc->n_added = 0;
  882. perf_events_lapic_init();
  883. }
  884. cpuc->enabled = 1;
  885. barrier();
  886. x86_pmu.enable_all(added);
  887. }
  888. static DEFINE_PER_CPU(u64 [X86_PMC_IDX_MAX], pmc_prev_left);
  889. /*
  890. * Set the next IRQ period, based on the hwc->period_left value.
  891. * To be called with the event disabled in hw:
  892. */
  893. int x86_perf_event_set_period(struct perf_event *event)
  894. {
  895. struct hw_perf_event *hwc = &event->hw;
  896. s64 left = local64_read(&hwc->period_left);
  897. s64 period = hwc->sample_period;
  898. int ret = 0, idx = hwc->idx;
  899. if (idx == INTEL_PMC_IDX_FIXED_BTS)
  900. return 0;
  901. /*
  902. * If we are way outside a reasonable range then just skip forward:
  903. */
  904. if (unlikely(left <= -period)) {
  905. left = period;
  906. local64_set(&hwc->period_left, left);
  907. hwc->last_period = period;
  908. ret = 1;
  909. }
  910. if (unlikely(left <= 0)) {
  911. left += period;
  912. local64_set(&hwc->period_left, left);
  913. hwc->last_period = period;
  914. ret = 1;
  915. }
  916. /*
  917. * Quirk: certain CPUs dont like it if just 1 hw_event is left:
  918. */
  919. if (unlikely(left < 2))
  920. left = 2;
  921. if (left > x86_pmu.max_period)
  922. left = x86_pmu.max_period;
  923. if (x86_pmu.limit_period)
  924. left = x86_pmu.limit_period(event, left);
  925. per_cpu(pmc_prev_left[idx], smp_processor_id()) = left;
  926. if (!(hwc->flags & PERF_X86_EVENT_AUTO_RELOAD) ||
  927. local64_read(&hwc->prev_count) != (u64)-left) {
  928. /*
  929. * The hw event starts counting from this event offset,
  930. * mark it to be able to extra future deltas:
  931. */
  932. local64_set(&hwc->prev_count, (u64)-left);
  933. wrmsrl(hwc->event_base, (u64)(-left) & x86_pmu.cntval_mask);
  934. }
  935. /*
  936. * Due to erratum on certan cpu we need
  937. * a second write to be sure the register
  938. * is updated properly
  939. */
  940. if (x86_pmu.perfctr_second_write) {
  941. wrmsrl(hwc->event_base,
  942. (u64)(-left) & x86_pmu.cntval_mask);
  943. }
  944. perf_event_update_userpage(event);
  945. return ret;
  946. }
  947. void x86_pmu_enable_event(struct perf_event *event)
  948. {
  949. if (__this_cpu_read(cpu_hw_events.enabled))
  950. __x86_pmu_enable_event(&event->hw,
  951. ARCH_PERFMON_EVENTSEL_ENABLE);
  952. }
  953. /*
  954. * Add a single event to the PMU.
  955. *
  956. * The event is added to the group of enabled events
  957. * but only if it can be scehduled with existing events.
  958. */
  959. static int x86_pmu_add(struct perf_event *event, int flags)
  960. {
  961. struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
  962. struct hw_perf_event *hwc;
  963. int assign[X86_PMC_IDX_MAX];
  964. int n, n0, ret;
  965. hwc = &event->hw;
  966. n0 = cpuc->n_events;
  967. ret = n = collect_events(cpuc, event, false);
  968. if (ret < 0)
  969. goto out;
  970. hwc->state = PERF_HES_UPTODATE | PERF_HES_STOPPED;
  971. if (!(flags & PERF_EF_START))
  972. hwc->state |= PERF_HES_ARCH;
  973. /*
  974. * If group events scheduling transaction was started,
  975. * skip the schedulability test here, it will be performed
  976. * at commit time (->commit_txn) as a whole.
  977. */
  978. if (cpuc->txn_flags & PERF_PMU_TXN_ADD)
  979. goto done_collect;
  980. ret = x86_pmu.schedule_events(cpuc, n, assign);
  981. if (ret)
  982. goto out;
  983. /*
  984. * copy new assignment, now we know it is possible
  985. * will be used by hw_perf_enable()
  986. */
  987. memcpy(cpuc->assign, assign, n*sizeof(int));
  988. done_collect:
  989. /*
  990. * Commit the collect_events() state. See x86_pmu_del() and
  991. * x86_pmu_*_txn().
  992. */
  993. cpuc->n_events = n;
  994. cpuc->n_added += n - n0;
  995. cpuc->n_txn += n - n0;
  996. ret = 0;
  997. out:
  998. return ret;
  999. }
  1000. static void x86_pmu_start(struct perf_event *event, int flags)
  1001. {
  1002. struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
  1003. int idx = event->hw.idx;
  1004. if (WARN_ON_ONCE(!(event->hw.state & PERF_HES_STOPPED)))
  1005. return;
  1006. if (WARN_ON_ONCE(idx == -1))
  1007. return;
  1008. if (flags & PERF_EF_RELOAD) {
  1009. WARN_ON_ONCE(!(event->hw.state & PERF_HES_UPTODATE));
  1010. x86_perf_event_set_period(event);
  1011. }
  1012. event->hw.state = 0;
  1013. cpuc->events[idx] = event;
  1014. __set_bit(idx, cpuc->active_mask);
  1015. __set_bit(idx, cpuc->running);
  1016. x86_pmu.enable(event);
  1017. perf_event_update_userpage(event);
  1018. }
  1019. void perf_event_print_debug(void)
  1020. {
  1021. u64 ctrl, status, overflow, pmc_ctrl, pmc_count, prev_left, fixed;
  1022. u64 pebs, debugctl;
  1023. struct cpu_hw_events *cpuc;
  1024. unsigned long flags;
  1025. int cpu, idx;
  1026. if (!x86_pmu.num_counters)
  1027. return;
  1028. local_irq_save(flags);
  1029. cpu = smp_processor_id();
  1030. cpuc = &per_cpu(cpu_hw_events, cpu);
  1031. if (x86_pmu.version >= 2) {
  1032. rdmsrl(MSR_CORE_PERF_GLOBAL_CTRL, ctrl);
  1033. rdmsrl(MSR_CORE_PERF_GLOBAL_STATUS, status);
  1034. rdmsrl(MSR_CORE_PERF_GLOBAL_OVF_CTRL, overflow);
  1035. rdmsrl(MSR_ARCH_PERFMON_FIXED_CTR_CTRL, fixed);
  1036. pr_info("\n");
  1037. pr_info("CPU#%d: ctrl: %016llx\n", cpu, ctrl);
  1038. pr_info("CPU#%d: status: %016llx\n", cpu, status);
  1039. pr_info("CPU#%d: overflow: %016llx\n", cpu, overflow);
  1040. pr_info("CPU#%d: fixed: %016llx\n", cpu, fixed);
  1041. if (x86_pmu.pebs_constraints) {
  1042. rdmsrl(MSR_IA32_PEBS_ENABLE, pebs);
  1043. pr_info("CPU#%d: pebs: %016llx\n", cpu, pebs);
  1044. }
  1045. if (x86_pmu.lbr_nr) {
  1046. rdmsrl(MSR_IA32_DEBUGCTLMSR, debugctl);
  1047. pr_info("CPU#%d: debugctl: %016llx\n", cpu, debugctl);
  1048. }
  1049. }
  1050. pr_info("CPU#%d: active: %016llx\n", cpu, *(u64 *)cpuc->active_mask);
  1051. for (idx = 0; idx < x86_pmu.num_counters; idx++) {
  1052. rdmsrl(x86_pmu_config_addr(idx), pmc_ctrl);
  1053. rdmsrl(x86_pmu_event_addr(idx), pmc_count);
  1054. prev_left = per_cpu(pmc_prev_left[idx], cpu);
  1055. pr_info("CPU#%d: gen-PMC%d ctrl: %016llx\n",
  1056. cpu, idx, pmc_ctrl);
  1057. pr_info("CPU#%d: gen-PMC%d count: %016llx\n",
  1058. cpu, idx, pmc_count);
  1059. pr_info("CPU#%d: gen-PMC%d left: %016llx\n",
  1060. cpu, idx, prev_left);
  1061. }
  1062. for (idx = 0; idx < x86_pmu.num_counters_fixed; idx++) {
  1063. rdmsrl(MSR_ARCH_PERFMON_FIXED_CTR0 + idx, pmc_count);
  1064. pr_info("CPU#%d: fixed-PMC%d count: %016llx\n",
  1065. cpu, idx, pmc_count);
  1066. }
  1067. local_irq_restore(flags);
  1068. }
  1069. void x86_pmu_stop(struct perf_event *event, int flags)
  1070. {
  1071. struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
  1072. struct hw_perf_event *hwc = &event->hw;
  1073. if (__test_and_clear_bit(hwc->idx, cpuc->active_mask)) {
  1074. x86_pmu.disable(event);
  1075. cpuc->events[hwc->idx] = NULL;
  1076. WARN_ON_ONCE(hwc->state & PERF_HES_STOPPED);
  1077. hwc->state |= PERF_HES_STOPPED;
  1078. }
  1079. if ((flags & PERF_EF_UPDATE) && !(hwc->state & PERF_HES_UPTODATE)) {
  1080. /*
  1081. * Drain the remaining delta count out of a event
  1082. * that we are disabling:
  1083. */
  1084. x86_perf_event_update(event);
  1085. hwc->state |= PERF_HES_UPTODATE;
  1086. }
  1087. }
  1088. static void x86_pmu_del(struct perf_event *event, int flags)
  1089. {
  1090. struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
  1091. int i;
  1092. /*
  1093. * event is descheduled
  1094. */
  1095. event->hw.flags &= ~PERF_X86_EVENT_COMMITTED;
  1096. /*
  1097. * If we're called during a txn, we don't need to do anything.
  1098. * The events never got scheduled and ->cancel_txn will truncate
  1099. * the event_list.
  1100. *
  1101. * XXX assumes any ->del() called during a TXN will only be on
  1102. * an event added during that same TXN.
  1103. */
  1104. if (cpuc->txn_flags & PERF_PMU_TXN_ADD)
  1105. return;
  1106. /*
  1107. * Not a TXN, therefore cleanup properly.
  1108. */
  1109. x86_pmu_stop(event, PERF_EF_UPDATE);
  1110. for (i = 0; i < cpuc->n_events; i++) {
  1111. if (event == cpuc->event_list[i])
  1112. break;
  1113. }
  1114. if (WARN_ON_ONCE(i == cpuc->n_events)) /* called ->del() without ->add() ? */
  1115. return;
  1116. /* If we have a newly added event; make sure to decrease n_added. */
  1117. if (i >= cpuc->n_events - cpuc->n_added)
  1118. --cpuc->n_added;
  1119. if (x86_pmu.put_event_constraints)
  1120. x86_pmu.put_event_constraints(cpuc, event);
  1121. /* Delete the array entry. */
  1122. while (++i < cpuc->n_events) {
  1123. cpuc->event_list[i-1] = cpuc->event_list[i];
  1124. cpuc->event_constraint[i-1] = cpuc->event_constraint[i];
  1125. }
  1126. --cpuc->n_events;
  1127. perf_event_update_userpage(event);
  1128. }
  1129. int x86_pmu_handle_irq(struct pt_regs *regs)
  1130. {
  1131. struct perf_sample_data data;
  1132. struct cpu_hw_events *cpuc;
  1133. struct perf_event *event;
  1134. int idx, handled = 0;
  1135. u64 val;
  1136. cpuc = this_cpu_ptr(&cpu_hw_events);
  1137. /*
  1138. * Some chipsets need to unmask the LVTPC in a particular spot
  1139. * inside the nmi handler. As a result, the unmasking was pushed
  1140. * into all the nmi handlers.
  1141. *
  1142. * This generic handler doesn't seem to have any issues where the
  1143. * unmasking occurs so it was left at the top.
  1144. */
  1145. apic_write(APIC_LVTPC, APIC_DM_NMI);
  1146. for (idx = 0; idx < x86_pmu.num_counters; idx++) {
  1147. if (!test_bit(idx, cpuc->active_mask)) {
  1148. /*
  1149. * Though we deactivated the counter some cpus
  1150. * might still deliver spurious interrupts still
  1151. * in flight. Catch them:
  1152. */
  1153. if (__test_and_clear_bit(idx, cpuc->running))
  1154. handled++;
  1155. continue;
  1156. }
  1157. event = cpuc->events[idx];
  1158. val = x86_perf_event_update(event);
  1159. if (val & (1ULL << (x86_pmu.cntval_bits - 1)))
  1160. continue;
  1161. /*
  1162. * event overflow
  1163. */
  1164. handled++;
  1165. perf_sample_data_init(&data, 0, event->hw.last_period);
  1166. if (!x86_perf_event_set_period(event))
  1167. continue;
  1168. if (perf_event_overflow(event, &data, regs))
  1169. x86_pmu_stop(event, 0);
  1170. }
  1171. if (handled)
  1172. inc_irq_stat(apic_perf_irqs);
  1173. return handled;
  1174. }
  1175. void perf_events_lapic_init(void)
  1176. {
  1177. if (!x86_pmu.apic || !x86_pmu_initialized())
  1178. return;
  1179. /*
  1180. * Always use NMI for PMU
  1181. */
  1182. apic_write(APIC_LVTPC, APIC_DM_NMI);
  1183. }
  1184. static int
  1185. perf_event_nmi_handler(unsigned int cmd, struct pt_regs *regs)
  1186. {
  1187. u64 start_clock;
  1188. u64 finish_clock;
  1189. int ret;
  1190. /*
  1191. * All PMUs/events that share this PMI handler should make sure to
  1192. * increment active_events for their events.
  1193. */
  1194. if (!atomic_read(&active_events))
  1195. return NMI_DONE;
  1196. start_clock = sched_clock();
  1197. ret = x86_pmu.handle_irq(regs);
  1198. finish_clock = sched_clock();
  1199. perf_sample_event_took(finish_clock - start_clock);
  1200. return ret;
  1201. }
  1202. NOKPROBE_SYMBOL(perf_event_nmi_handler);
  1203. struct event_constraint emptyconstraint;
  1204. struct event_constraint unconstrained;
  1205. static int
  1206. x86_pmu_notifier(struct notifier_block *self, unsigned long action, void *hcpu)
  1207. {
  1208. unsigned int cpu = (long)hcpu;
  1209. struct cpu_hw_events *cpuc = &per_cpu(cpu_hw_events, cpu);
  1210. int i, ret = NOTIFY_OK;
  1211. switch (action & ~CPU_TASKS_FROZEN) {
  1212. case CPU_UP_PREPARE:
  1213. for (i = 0 ; i < X86_PERF_KFREE_MAX; i++)
  1214. cpuc->kfree_on_online[i] = NULL;
  1215. if (x86_pmu.cpu_prepare)
  1216. ret = x86_pmu.cpu_prepare(cpu);
  1217. break;
  1218. case CPU_STARTING:
  1219. if (x86_pmu.cpu_starting)
  1220. x86_pmu.cpu_starting(cpu);
  1221. break;
  1222. case CPU_ONLINE:
  1223. for (i = 0 ; i < X86_PERF_KFREE_MAX; i++) {
  1224. kfree(cpuc->kfree_on_online[i]);
  1225. cpuc->kfree_on_online[i] = NULL;
  1226. }
  1227. break;
  1228. case CPU_DYING:
  1229. if (x86_pmu.cpu_dying)
  1230. x86_pmu.cpu_dying(cpu);
  1231. break;
  1232. case CPU_UP_CANCELED:
  1233. case CPU_DEAD:
  1234. if (x86_pmu.cpu_dead)
  1235. x86_pmu.cpu_dead(cpu);
  1236. break;
  1237. default:
  1238. break;
  1239. }
  1240. return ret;
  1241. }
  1242. static void __init pmu_check_apic(void)
  1243. {
  1244. if (cpu_has_apic)
  1245. return;
  1246. x86_pmu.apic = 0;
  1247. pr_info("no APIC, boot with the \"lapic\" boot parameter to force-enable it.\n");
  1248. pr_info("no hardware sampling interrupt available.\n");
  1249. /*
  1250. * If we have a PMU initialized but no APIC
  1251. * interrupts, we cannot sample hardware
  1252. * events (user-space has to fall back and
  1253. * sample via a hrtimer based software event):
  1254. */
  1255. pmu.capabilities |= PERF_PMU_CAP_NO_INTERRUPT;
  1256. }
  1257. static struct attribute_group x86_pmu_format_group = {
  1258. .name = "format",
  1259. .attrs = NULL,
  1260. };
  1261. /*
  1262. * Remove all undefined events (x86_pmu.event_map(id) == 0)
  1263. * out of events_attr attributes.
  1264. */
  1265. static void __init filter_events(struct attribute **attrs)
  1266. {
  1267. struct device_attribute *d;
  1268. struct perf_pmu_events_attr *pmu_attr;
  1269. int i, j;
  1270. for (i = 0; attrs[i]; i++) {
  1271. d = (struct device_attribute *)attrs[i];
  1272. pmu_attr = container_of(d, struct perf_pmu_events_attr, attr);
  1273. /* str trumps id */
  1274. if (pmu_attr->event_str)
  1275. continue;
  1276. if (x86_pmu.event_map(i))
  1277. continue;
  1278. for (j = i; attrs[j]; j++)
  1279. attrs[j] = attrs[j + 1];
  1280. /* Check the shifted attr. */
  1281. i--;
  1282. }
  1283. }
  1284. /* Merge two pointer arrays */
  1285. __init struct attribute **merge_attr(struct attribute **a, struct attribute **b)
  1286. {
  1287. struct attribute **new;
  1288. int j, i;
  1289. for (j = 0; a[j]; j++)
  1290. ;
  1291. for (i = 0; b[i]; i++)
  1292. j++;
  1293. j++;
  1294. new = kmalloc(sizeof(struct attribute *) * j, GFP_KERNEL);
  1295. if (!new)
  1296. return NULL;
  1297. j = 0;
  1298. for (i = 0; a[i]; i++)
  1299. new[j++] = a[i];
  1300. for (i = 0; b[i]; i++)
  1301. new[j++] = b[i];
  1302. new[j] = NULL;
  1303. return new;
  1304. }
  1305. ssize_t events_sysfs_show(struct device *dev, struct device_attribute *attr,
  1306. char *page)
  1307. {
  1308. struct perf_pmu_events_attr *pmu_attr = \
  1309. container_of(attr, struct perf_pmu_events_attr, attr);
  1310. u64 config = x86_pmu.event_map(pmu_attr->id);
  1311. /* string trumps id */
  1312. if (pmu_attr->event_str)
  1313. return sprintf(page, "%s", pmu_attr->event_str);
  1314. return x86_pmu.events_sysfs_show(page, config);
  1315. }
  1316. EVENT_ATTR(cpu-cycles, CPU_CYCLES );
  1317. EVENT_ATTR(instructions, INSTRUCTIONS );
  1318. EVENT_ATTR(cache-references, CACHE_REFERENCES );
  1319. EVENT_ATTR(cache-misses, CACHE_MISSES );
  1320. EVENT_ATTR(branch-instructions, BRANCH_INSTRUCTIONS );
  1321. EVENT_ATTR(branch-misses, BRANCH_MISSES );
  1322. EVENT_ATTR(bus-cycles, BUS_CYCLES );
  1323. EVENT_ATTR(stalled-cycles-frontend, STALLED_CYCLES_FRONTEND );
  1324. EVENT_ATTR(stalled-cycles-backend, STALLED_CYCLES_BACKEND );
  1325. EVENT_ATTR(ref-cycles, REF_CPU_CYCLES );
  1326. static struct attribute *empty_attrs;
  1327. static struct attribute *events_attr[] = {
  1328. EVENT_PTR(CPU_CYCLES),
  1329. EVENT_PTR(INSTRUCTIONS),
  1330. EVENT_PTR(CACHE_REFERENCES),
  1331. EVENT_PTR(CACHE_MISSES),
  1332. EVENT_PTR(BRANCH_INSTRUCTIONS),
  1333. EVENT_PTR(BRANCH_MISSES),
  1334. EVENT_PTR(BUS_CYCLES),
  1335. EVENT_PTR(STALLED_CYCLES_FRONTEND),
  1336. EVENT_PTR(STALLED_CYCLES_BACKEND),
  1337. EVENT_PTR(REF_CPU_CYCLES),
  1338. NULL,
  1339. };
  1340. static struct attribute_group x86_pmu_events_group = {
  1341. .name = "events",
  1342. .attrs = events_attr,
  1343. };
  1344. ssize_t x86_event_sysfs_show(char *page, u64 config, u64 event)
  1345. {
  1346. u64 umask = (config & ARCH_PERFMON_EVENTSEL_UMASK) >> 8;
  1347. u64 cmask = (config & ARCH_PERFMON_EVENTSEL_CMASK) >> 24;
  1348. bool edge = (config & ARCH_PERFMON_EVENTSEL_EDGE);
  1349. bool pc = (config & ARCH_PERFMON_EVENTSEL_PIN_CONTROL);
  1350. bool any = (config & ARCH_PERFMON_EVENTSEL_ANY);
  1351. bool inv = (config & ARCH_PERFMON_EVENTSEL_INV);
  1352. ssize_t ret;
  1353. /*
  1354. * We have whole page size to spend and just little data
  1355. * to write, so we can safely use sprintf.
  1356. */
  1357. ret = sprintf(page, "event=0x%02llx", event);
  1358. if (umask)
  1359. ret += sprintf(page + ret, ",umask=0x%02llx", umask);
  1360. if (edge)
  1361. ret += sprintf(page + ret, ",edge");
  1362. if (pc)
  1363. ret += sprintf(page + ret, ",pc");
  1364. if (any)
  1365. ret += sprintf(page + ret, ",any");
  1366. if (inv)
  1367. ret += sprintf(page + ret, ",inv");
  1368. if (cmask)
  1369. ret += sprintf(page + ret, ",cmask=0x%02llx", cmask);
  1370. ret += sprintf(page + ret, "\n");
  1371. return ret;
  1372. }
  1373. static int __init init_hw_perf_events(void)
  1374. {
  1375. struct x86_pmu_quirk *quirk;
  1376. int err;
  1377. pr_info("Performance Events: ");
  1378. switch (boot_cpu_data.x86_vendor) {
  1379. case X86_VENDOR_INTEL:
  1380. err = intel_pmu_init();
  1381. break;
  1382. case X86_VENDOR_AMD:
  1383. err = amd_pmu_init();
  1384. break;
  1385. default:
  1386. err = -ENOTSUPP;
  1387. }
  1388. if (err != 0) {
  1389. pr_cont("no PMU driver, software events only.\n");
  1390. return 0;
  1391. }
  1392. pmu_check_apic();
  1393. /* sanity check that the hardware exists or is emulated */
  1394. if (!check_hw_exists())
  1395. return 0;
  1396. pr_cont("%s PMU driver.\n", x86_pmu.name);
  1397. x86_pmu.attr_rdpmc = 1; /* enable userspace RDPMC usage by default */
  1398. for (quirk = x86_pmu.quirks; quirk; quirk = quirk->next)
  1399. quirk->func();
  1400. if (!x86_pmu.intel_ctrl)
  1401. x86_pmu.intel_ctrl = (1 << x86_pmu.num_counters) - 1;
  1402. perf_events_lapic_init();
  1403. register_nmi_handler(NMI_LOCAL, perf_event_nmi_handler, 0, "PMI");
  1404. unconstrained = (struct event_constraint)
  1405. __EVENT_CONSTRAINT(0, (1ULL << x86_pmu.num_counters) - 1,
  1406. 0, x86_pmu.num_counters, 0, 0);
  1407. x86_pmu_format_group.attrs = x86_pmu.format_attrs;
  1408. if (x86_pmu.event_attrs)
  1409. x86_pmu_events_group.attrs = x86_pmu.event_attrs;
  1410. if (!x86_pmu.events_sysfs_show)
  1411. x86_pmu_events_group.attrs = &empty_attrs;
  1412. else
  1413. filter_events(x86_pmu_events_group.attrs);
  1414. if (x86_pmu.cpu_events) {
  1415. struct attribute **tmp;
  1416. tmp = merge_attr(x86_pmu_events_group.attrs, x86_pmu.cpu_events);
  1417. if (!WARN_ON(!tmp))
  1418. x86_pmu_events_group.attrs = tmp;
  1419. }
  1420. pr_info("... version: %d\n", x86_pmu.version);
  1421. pr_info("... bit width: %d\n", x86_pmu.cntval_bits);
  1422. pr_info("... generic registers: %d\n", x86_pmu.num_counters);
  1423. pr_info("... value mask: %016Lx\n", x86_pmu.cntval_mask);
  1424. pr_info("... max period: %016Lx\n", x86_pmu.max_period);
  1425. pr_info("... fixed-purpose events: %d\n", x86_pmu.num_counters_fixed);
  1426. pr_info("... event mask: %016Lx\n", x86_pmu.intel_ctrl);
  1427. perf_pmu_register(&pmu, "cpu", PERF_TYPE_RAW);
  1428. perf_cpu_notifier(x86_pmu_notifier);
  1429. return 0;
  1430. }
  1431. early_initcall(init_hw_perf_events);
  1432. static inline void x86_pmu_read(struct perf_event *event)
  1433. {
  1434. x86_perf_event_update(event);
  1435. }
  1436. /*
  1437. * Start group events scheduling transaction
  1438. * Set the flag to make pmu::enable() not perform the
  1439. * schedulability test, it will be performed at commit time
  1440. *
  1441. * We only support PERF_PMU_TXN_ADD transactions. Save the
  1442. * transaction flags but otherwise ignore non-PERF_PMU_TXN_ADD
  1443. * transactions.
  1444. */
  1445. static void x86_pmu_start_txn(struct pmu *pmu, unsigned int txn_flags)
  1446. {
  1447. struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
  1448. WARN_ON_ONCE(cpuc->txn_flags); /* txn already in flight */
  1449. cpuc->txn_flags = txn_flags;
  1450. if (txn_flags & ~PERF_PMU_TXN_ADD)
  1451. return;
  1452. perf_pmu_disable(pmu);
  1453. __this_cpu_write(cpu_hw_events.n_txn, 0);
  1454. }
  1455. /*
  1456. * Stop group events scheduling transaction
  1457. * Clear the flag and pmu::enable() will perform the
  1458. * schedulability test.
  1459. */
  1460. static void x86_pmu_cancel_txn(struct pmu *pmu)
  1461. {
  1462. unsigned int txn_flags;
  1463. struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
  1464. WARN_ON_ONCE(!cpuc->txn_flags); /* no txn in flight */
  1465. txn_flags = cpuc->txn_flags;
  1466. cpuc->txn_flags = 0;
  1467. if (txn_flags & ~PERF_PMU_TXN_ADD)
  1468. return;
  1469. /*
  1470. * Truncate collected array by the number of events added in this
  1471. * transaction. See x86_pmu_add() and x86_pmu_*_txn().
  1472. */
  1473. __this_cpu_sub(cpu_hw_events.n_added, __this_cpu_read(cpu_hw_events.n_txn));
  1474. __this_cpu_sub(cpu_hw_events.n_events, __this_cpu_read(cpu_hw_events.n_txn));
  1475. perf_pmu_enable(pmu);
  1476. }
  1477. /*
  1478. * Commit group events scheduling transaction
  1479. * Perform the group schedulability test as a whole
  1480. * Return 0 if success
  1481. *
  1482. * Does not cancel the transaction on failure; expects the caller to do this.
  1483. */
  1484. static int x86_pmu_commit_txn(struct pmu *pmu)
  1485. {
  1486. struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
  1487. int assign[X86_PMC_IDX_MAX];
  1488. int n, ret;
  1489. WARN_ON_ONCE(!cpuc->txn_flags); /* no txn in flight */
  1490. if (cpuc->txn_flags & ~PERF_PMU_TXN_ADD) {
  1491. cpuc->txn_flags = 0;
  1492. return 0;
  1493. }
  1494. n = cpuc->n_events;
  1495. if (!x86_pmu_initialized())
  1496. return -EAGAIN;
  1497. ret = x86_pmu.schedule_events(cpuc, n, assign);
  1498. if (ret)
  1499. return ret;
  1500. /*
  1501. * copy new assignment, now we know it is possible
  1502. * will be used by hw_perf_enable()
  1503. */
  1504. memcpy(cpuc->assign, assign, n*sizeof(int));
  1505. cpuc->txn_flags = 0;
  1506. perf_pmu_enable(pmu);
  1507. return 0;
  1508. }
  1509. /*
  1510. * a fake_cpuc is used to validate event groups. Due to
  1511. * the extra reg logic, we need to also allocate a fake
  1512. * per_core and per_cpu structure. Otherwise, group events
  1513. * using extra reg may conflict without the kernel being
  1514. * able to catch this when the last event gets added to
  1515. * the group.
  1516. */
  1517. static void free_fake_cpuc(struct cpu_hw_events *cpuc)
  1518. {
  1519. kfree(cpuc->shared_regs);
  1520. kfree(cpuc);
  1521. }
  1522. static struct cpu_hw_events *allocate_fake_cpuc(void)
  1523. {
  1524. struct cpu_hw_events *cpuc;
  1525. int cpu = raw_smp_processor_id();
  1526. cpuc = kzalloc(sizeof(*cpuc), GFP_KERNEL);
  1527. if (!cpuc)
  1528. return ERR_PTR(-ENOMEM);
  1529. /* only needed, if we have extra_regs */
  1530. if (x86_pmu.extra_regs) {
  1531. cpuc->shared_regs = allocate_shared_regs(cpu);
  1532. if (!cpuc->shared_regs)
  1533. goto error;
  1534. }
  1535. cpuc->is_fake = 1;
  1536. return cpuc;
  1537. error:
  1538. free_fake_cpuc(cpuc);
  1539. return ERR_PTR(-ENOMEM);
  1540. }
  1541. /*
  1542. * validate that we can schedule this event
  1543. */
  1544. static int validate_event(struct perf_event *event)
  1545. {
  1546. struct cpu_hw_events *fake_cpuc;
  1547. struct event_constraint *c;
  1548. int ret = 0;
  1549. fake_cpuc = allocate_fake_cpuc();
  1550. if (IS_ERR(fake_cpuc))
  1551. return PTR_ERR(fake_cpuc);
  1552. c = x86_pmu.get_event_constraints(fake_cpuc, -1, event);
  1553. if (!c || !c->weight)
  1554. ret = -EINVAL;
  1555. if (x86_pmu.put_event_constraints)
  1556. x86_pmu.put_event_constraints(fake_cpuc, event);
  1557. free_fake_cpuc(fake_cpuc);
  1558. return ret;
  1559. }
  1560. /*
  1561. * validate a single event group
  1562. *
  1563. * validation include:
  1564. * - check events are compatible which each other
  1565. * - events do not compete for the same counter
  1566. * - number of events <= number of counters
  1567. *
  1568. * validation ensures the group can be loaded onto the
  1569. * PMU if it was the only group available.
  1570. */
  1571. static int validate_group(struct perf_event *event)
  1572. {
  1573. struct perf_event *leader = event->group_leader;
  1574. struct cpu_hw_events *fake_cpuc;
  1575. int ret = -EINVAL, n;
  1576. fake_cpuc = allocate_fake_cpuc();
  1577. if (IS_ERR(fake_cpuc))
  1578. return PTR_ERR(fake_cpuc);
  1579. /*
  1580. * the event is not yet connected with its
  1581. * siblings therefore we must first collect
  1582. * existing siblings, then add the new event
  1583. * before we can simulate the scheduling
  1584. */
  1585. n = collect_events(fake_cpuc, leader, true);
  1586. if (n < 0)
  1587. goto out;
  1588. fake_cpuc->n_events = n;
  1589. n = collect_events(fake_cpuc, event, false);
  1590. if (n < 0)
  1591. goto out;
  1592. fake_cpuc->n_events = n;
  1593. ret = x86_pmu.schedule_events(fake_cpuc, n, NULL);
  1594. out:
  1595. free_fake_cpuc(fake_cpuc);
  1596. return ret;
  1597. }
  1598. static int x86_pmu_event_init(struct perf_event *event)
  1599. {
  1600. struct pmu *tmp;
  1601. int err;
  1602. switch (event->attr.type) {
  1603. case PERF_TYPE_RAW:
  1604. case PERF_TYPE_HARDWARE:
  1605. case PERF_TYPE_HW_CACHE:
  1606. break;
  1607. default:
  1608. return -ENOENT;
  1609. }
  1610. err = __x86_pmu_event_init(event);
  1611. if (!err) {
  1612. /*
  1613. * we temporarily connect event to its pmu
  1614. * such that validate_group() can classify
  1615. * it as an x86 event using is_x86_event()
  1616. */
  1617. tmp = event->pmu;
  1618. event->pmu = &pmu;
  1619. if (event->group_leader != event)
  1620. err = validate_group(event);
  1621. else
  1622. err = validate_event(event);
  1623. event->pmu = tmp;
  1624. }
  1625. if (err) {
  1626. if (event->destroy)
  1627. event->destroy(event);
  1628. }
  1629. if (ACCESS_ONCE(x86_pmu.attr_rdpmc))
  1630. event->hw.flags |= PERF_X86_EVENT_RDPMC_ALLOWED;
  1631. return err;
  1632. }
  1633. static void refresh_pce(void *ignored)
  1634. {
  1635. if (current->active_mm)
  1636. load_mm_cr4(current->active_mm);
  1637. }
  1638. static void x86_pmu_event_mapped(struct perf_event *event)
  1639. {
  1640. if (!(event->hw.flags & PERF_X86_EVENT_RDPMC_ALLOWED))
  1641. return;
  1642. if (atomic_inc_return(&current->mm->context.perf_rdpmc_allowed) == 1)
  1643. on_each_cpu_mask(mm_cpumask(current->mm), refresh_pce, NULL, 1);
  1644. }
  1645. static void x86_pmu_event_unmapped(struct perf_event *event)
  1646. {
  1647. if (!current->mm)
  1648. return;
  1649. if (!(event->hw.flags & PERF_X86_EVENT_RDPMC_ALLOWED))
  1650. return;
  1651. if (atomic_dec_and_test(&current->mm->context.perf_rdpmc_allowed))
  1652. on_each_cpu_mask(mm_cpumask(current->mm), refresh_pce, NULL, 1);
  1653. }
  1654. static int x86_pmu_event_idx(struct perf_event *event)
  1655. {
  1656. int idx = event->hw.idx;
  1657. if (!(event->hw.flags & PERF_X86_EVENT_RDPMC_ALLOWED))
  1658. return 0;
  1659. if (x86_pmu.num_counters_fixed && idx >= INTEL_PMC_IDX_FIXED) {
  1660. idx -= INTEL_PMC_IDX_FIXED;
  1661. idx |= 1 << 30;
  1662. }
  1663. return idx + 1;
  1664. }
  1665. static ssize_t get_attr_rdpmc(struct device *cdev,
  1666. struct device_attribute *attr,
  1667. char *buf)
  1668. {
  1669. return snprintf(buf, 40, "%d\n", x86_pmu.attr_rdpmc);
  1670. }
  1671. static ssize_t set_attr_rdpmc(struct device *cdev,
  1672. struct device_attribute *attr,
  1673. const char *buf, size_t count)
  1674. {
  1675. unsigned long val;
  1676. ssize_t ret;
  1677. ret = kstrtoul(buf, 0, &val);
  1678. if (ret)
  1679. return ret;
  1680. if (val > 2)
  1681. return -EINVAL;
  1682. if (x86_pmu.attr_rdpmc_broken)
  1683. return -ENOTSUPP;
  1684. if ((val == 2) != (x86_pmu.attr_rdpmc == 2)) {
  1685. /*
  1686. * Changing into or out of always available, aka
  1687. * perf-event-bypassing mode. This path is extremely slow,
  1688. * but only root can trigger it, so it's okay.
  1689. */
  1690. if (val == 2)
  1691. static_key_slow_inc(&rdpmc_always_available);
  1692. else
  1693. static_key_slow_dec(&rdpmc_always_available);
  1694. on_each_cpu(refresh_pce, NULL, 1);
  1695. }
  1696. x86_pmu.attr_rdpmc = val;
  1697. return count;
  1698. }
  1699. static DEVICE_ATTR(rdpmc, S_IRUSR | S_IWUSR, get_attr_rdpmc, set_attr_rdpmc);
  1700. static struct attribute *x86_pmu_attrs[] = {
  1701. &dev_attr_rdpmc.attr,
  1702. NULL,
  1703. };
  1704. static struct attribute_group x86_pmu_attr_group = {
  1705. .attrs = x86_pmu_attrs,
  1706. };
  1707. static const struct attribute_group *x86_pmu_attr_groups[] = {
  1708. &x86_pmu_attr_group,
  1709. &x86_pmu_format_group,
  1710. &x86_pmu_events_group,
  1711. NULL,
  1712. };
  1713. static void x86_pmu_sched_task(struct perf_event_context *ctx, bool sched_in)
  1714. {
  1715. if (x86_pmu.sched_task)
  1716. x86_pmu.sched_task(ctx, sched_in);
  1717. }
  1718. void perf_check_microcode(void)
  1719. {
  1720. if (x86_pmu.check_microcode)
  1721. x86_pmu.check_microcode();
  1722. }
  1723. EXPORT_SYMBOL_GPL(perf_check_microcode);
  1724. static struct pmu pmu = {
  1725. .pmu_enable = x86_pmu_enable,
  1726. .pmu_disable = x86_pmu_disable,
  1727. .attr_groups = x86_pmu_attr_groups,
  1728. .event_init = x86_pmu_event_init,
  1729. .event_mapped = x86_pmu_event_mapped,
  1730. .event_unmapped = x86_pmu_event_unmapped,
  1731. .add = x86_pmu_add,
  1732. .del = x86_pmu_del,
  1733. .start = x86_pmu_start,
  1734. .stop = x86_pmu_stop,
  1735. .read = x86_pmu_read,
  1736. .start_txn = x86_pmu_start_txn,
  1737. .cancel_txn = x86_pmu_cancel_txn,
  1738. .commit_txn = x86_pmu_commit_txn,
  1739. .event_idx = x86_pmu_event_idx,
  1740. .sched_task = x86_pmu_sched_task,
  1741. .task_ctx_size = sizeof(struct x86_perf_task_context),
  1742. };
  1743. void arch_perf_update_userpage(struct perf_event *event,
  1744. struct perf_event_mmap_page *userpg, u64 now)
  1745. {
  1746. struct cyc2ns_data *data;
  1747. userpg->cap_user_time = 0;
  1748. userpg->cap_user_time_zero = 0;
  1749. userpg->cap_user_rdpmc =
  1750. !!(event->hw.flags & PERF_X86_EVENT_RDPMC_ALLOWED);
  1751. userpg->pmc_width = x86_pmu.cntval_bits;
  1752. if (!sched_clock_stable())
  1753. return;
  1754. data = cyc2ns_read_begin();
  1755. /*
  1756. * Internal timekeeping for enabled/running/stopped times
  1757. * is always in the local_clock domain.
  1758. */
  1759. userpg->cap_user_time = 1;
  1760. userpg->time_mult = data->cyc2ns_mul;
  1761. userpg->time_shift = data->cyc2ns_shift;
  1762. userpg->time_offset = data->cyc2ns_offset - now;
  1763. /*
  1764. * cap_user_time_zero doesn't make sense when we're using a different
  1765. * time base for the records.
  1766. */
  1767. if (event->clock == &local_clock) {
  1768. userpg->cap_user_time_zero = 1;
  1769. userpg->time_zero = data->cyc2ns_offset;
  1770. }
  1771. cyc2ns_read_end(data);
  1772. }
  1773. /*
  1774. * callchain support
  1775. */
  1776. static int backtrace_stack(void *data, char *name)
  1777. {
  1778. return 0;
  1779. }
  1780. static void backtrace_address(void *data, unsigned long addr, int reliable)
  1781. {
  1782. struct perf_callchain_entry *entry = data;
  1783. perf_callchain_store(entry, addr);
  1784. }
  1785. static const struct stacktrace_ops backtrace_ops = {
  1786. .stack = backtrace_stack,
  1787. .address = backtrace_address,
  1788. .walk_stack = print_context_stack_bp,
  1789. };
  1790. void
  1791. perf_callchain_kernel(struct perf_callchain_entry *entry, struct pt_regs *regs)
  1792. {
  1793. if (perf_guest_cbs && perf_guest_cbs->is_in_guest()) {
  1794. /* TODO: We don't support guest os callchain now */
  1795. return;
  1796. }
  1797. perf_callchain_store(entry, regs->ip);
  1798. dump_trace(NULL, regs, NULL, 0, &backtrace_ops, entry);
  1799. }
  1800. static inline int
  1801. valid_user_frame(const void __user *fp, unsigned long size)
  1802. {
  1803. return (__range_not_ok(fp, size, TASK_SIZE) == 0);
  1804. }
  1805. static unsigned long get_segment_base(unsigned int segment)
  1806. {
  1807. struct desc_struct *desc;
  1808. int idx = segment >> 3;
  1809. if ((segment & SEGMENT_TI_MASK) == SEGMENT_LDT) {
  1810. #ifdef CONFIG_MODIFY_LDT_SYSCALL
  1811. struct ldt_struct *ldt;
  1812. if (idx > LDT_ENTRIES)
  1813. return 0;
  1814. /* IRQs are off, so this synchronizes with smp_store_release */
  1815. ldt = lockless_dereference(current->active_mm->context.ldt);
  1816. if (!ldt || idx > ldt->size)
  1817. return 0;
  1818. desc = &ldt->entries[idx];
  1819. #else
  1820. return 0;
  1821. #endif
  1822. } else {
  1823. if (idx > GDT_ENTRIES)
  1824. return 0;
  1825. desc = raw_cpu_ptr(gdt_page.gdt) + idx;
  1826. }
  1827. return get_desc_base(desc);
  1828. }
  1829. #ifdef CONFIG_IA32_EMULATION
  1830. #include <asm/compat.h>
  1831. static inline int
  1832. perf_callchain_user32(struct pt_regs *regs, struct perf_callchain_entry *entry)
  1833. {
  1834. /* 32-bit process in 64-bit kernel. */
  1835. unsigned long ss_base, cs_base;
  1836. struct stack_frame_ia32 frame;
  1837. const void __user *fp;
  1838. if (!test_thread_flag(TIF_IA32))
  1839. return 0;
  1840. cs_base = get_segment_base(regs->cs);
  1841. ss_base = get_segment_base(regs->ss);
  1842. fp = compat_ptr(ss_base + regs->bp);
  1843. while (entry->nr < PERF_MAX_STACK_DEPTH) {
  1844. unsigned long bytes;
  1845. frame.next_frame = 0;
  1846. frame.return_address = 0;
  1847. bytes = copy_from_user_nmi(&frame, fp, sizeof(frame));
  1848. if (bytes != 0)
  1849. break;
  1850. if (!valid_user_frame(fp, sizeof(frame)))
  1851. break;
  1852. perf_callchain_store(entry, cs_base + frame.return_address);
  1853. fp = compat_ptr(ss_base + frame.next_frame);
  1854. }
  1855. return 1;
  1856. }
  1857. #else
  1858. static inline int
  1859. perf_callchain_user32(struct pt_regs *regs, struct perf_callchain_entry *entry)
  1860. {
  1861. return 0;
  1862. }
  1863. #endif
  1864. void
  1865. perf_callchain_user(struct perf_callchain_entry *entry, struct pt_regs *regs)
  1866. {
  1867. struct stack_frame frame;
  1868. const void __user *fp;
  1869. if (perf_guest_cbs && perf_guest_cbs->is_in_guest()) {
  1870. /* TODO: We don't support guest os callchain now */
  1871. return;
  1872. }
  1873. /*
  1874. * We don't know what to do with VM86 stacks.. ignore them for now.
  1875. */
  1876. if (regs->flags & (X86_VM_MASK | PERF_EFLAGS_VM))
  1877. return;
  1878. fp = (void __user *)regs->bp;
  1879. perf_callchain_store(entry, regs->ip);
  1880. if (!current->mm)
  1881. return;
  1882. if (perf_callchain_user32(regs, entry))
  1883. return;
  1884. while (entry->nr < PERF_MAX_STACK_DEPTH) {
  1885. unsigned long bytes;
  1886. frame.next_frame = NULL;
  1887. frame.return_address = 0;
  1888. bytes = copy_from_user_nmi(&frame, fp, sizeof(frame));
  1889. if (bytes != 0)
  1890. break;
  1891. if (!valid_user_frame(fp, sizeof(frame)))
  1892. break;
  1893. perf_callchain_store(entry, frame.return_address);
  1894. fp = frame.next_frame;
  1895. }
  1896. }
  1897. /*
  1898. * Deal with code segment offsets for the various execution modes:
  1899. *
  1900. * VM86 - the good olde 16 bit days, where the linear address is
  1901. * 20 bits and we use regs->ip + 0x10 * regs->cs.
  1902. *
  1903. * IA32 - Where we need to look at GDT/LDT segment descriptor tables
  1904. * to figure out what the 32bit base address is.
  1905. *
  1906. * X32 - has TIF_X32 set, but is running in x86_64
  1907. *
  1908. * X86_64 - CS,DS,SS,ES are all zero based.
  1909. */
  1910. static unsigned long code_segment_base(struct pt_regs *regs)
  1911. {
  1912. /*
  1913. * For IA32 we look at the GDT/LDT segment base to convert the
  1914. * effective IP to a linear address.
  1915. */
  1916. #ifdef CONFIG_X86_32
  1917. /*
  1918. * If we are in VM86 mode, add the segment offset to convert to a
  1919. * linear address.
  1920. */
  1921. if (regs->flags & X86_VM_MASK)
  1922. return 0x10 * regs->cs;
  1923. if (user_mode(regs) && regs->cs != __USER_CS)
  1924. return get_segment_base(regs->cs);
  1925. #else
  1926. if (user_mode(regs) && !user_64bit_mode(regs) &&
  1927. regs->cs != __USER32_CS)
  1928. return get_segment_base(regs->cs);
  1929. #endif
  1930. return 0;
  1931. }
  1932. unsigned long perf_instruction_pointer(struct pt_regs *regs)
  1933. {
  1934. if (perf_guest_cbs && perf_guest_cbs->is_in_guest())
  1935. return perf_guest_cbs->get_guest_ip();
  1936. return regs->ip + code_segment_base(regs);
  1937. }
  1938. unsigned long perf_misc_flags(struct pt_regs *regs)
  1939. {
  1940. int misc = 0;
  1941. if (perf_guest_cbs && perf_guest_cbs->is_in_guest()) {
  1942. if (perf_guest_cbs->is_user_mode())
  1943. misc |= PERF_RECORD_MISC_GUEST_USER;
  1944. else
  1945. misc |= PERF_RECORD_MISC_GUEST_KERNEL;
  1946. } else {
  1947. if (user_mode(regs))
  1948. misc |= PERF_RECORD_MISC_USER;
  1949. else
  1950. misc |= PERF_RECORD_MISC_KERNEL;
  1951. }
  1952. if (regs->flags & PERF_EFLAGS_EXACT)
  1953. misc |= PERF_RECORD_MISC_EXACT_IP;
  1954. return misc;
  1955. }
  1956. void perf_get_x86_pmu_capability(struct x86_pmu_capability *cap)
  1957. {
  1958. cap->version = x86_pmu.version;
  1959. cap->num_counters_gp = x86_pmu.num_counters;
  1960. cap->num_counters_fixed = x86_pmu.num_counters_fixed;
  1961. cap->bit_width_gp = x86_pmu.cntval_bits;
  1962. cap->bit_width_fixed = x86_pmu.cntval_bits;
  1963. cap->events_mask = (unsigned int)x86_pmu.events_maskl;
  1964. cap->events_mask_len = x86_pmu.events_mask_len;
  1965. }
  1966. EXPORT_SYMBOL_GPL(perf_get_x86_pmu_capability);