core.c 60 KB

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