core.c 58 KB

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