perf_event.c 53 KB

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