core.c 59 KB

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