core.c 58 KB

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