core.c 60 KB

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