perf_event.c 54 KB

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