core.c 59 KB

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