core.c 58 KB

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