core.c 58 KB

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