perf_event.c 54 KB

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