perf_event.c 56 KB

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