]> git.kernelconcepts.de Git - karo-tx-linux.git/blob - arch/powerpc/perf/hv-24x7.c
7e47dcdea62a309616357378928e5f8dbdc3f40f
[karo-tx-linux.git] / arch / powerpc / perf / hv-24x7.c
1 /*
2  * Hypervisor supplied "24x7" performance counter support
3  *
4  * Author: Cody P Schafer <cody@linux.vnet.ibm.com>
5  * Copyright 2014 IBM Corporation.
6  *
7  * This program is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License
9  * as published by the Free Software Foundation; either version
10  * 2 of the License, or (at your option) any later version.
11  */
12
13 #define pr_fmt(fmt) "hv-24x7: " fmt
14
15 #include <linux/perf_event.h>
16 #include <linux/rbtree.h>
17 #include <linux/module.h>
18 #include <linux/slab.h>
19 #include <linux/vmalloc.h>
20
21 #include <asm/firmware.h>
22 #include <asm/hvcall.h>
23 #include <asm/io.h>
24 #include <linux/byteorder/generic.h>
25
26 #include "hv-24x7.h"
27 #include "hv-24x7-catalog.h"
28 #include "hv-common.h"
29
30 static bool domain_is_valid(unsigned domain)
31 {
32         switch (domain) {
33 #define DOMAIN(n, v, x, c)              \
34         case HV_PERF_DOMAIN_##n:        \
35                 /* fall through */
36 #include "hv-24x7-domains.h"
37 #undef DOMAIN
38                 return true;
39         default:
40                 return false;
41         }
42 }
43
44 static bool is_physical_domain(unsigned domain)
45 {
46         switch (domain) {
47 #define DOMAIN(n, v, x, c)              \
48         case HV_PERF_DOMAIN_##n:        \
49                 return c;
50 #include "hv-24x7-domains.h"
51 #undef DOMAIN
52         default:
53                 return false;
54         }
55 }
56
57 static const char *domain_name(unsigned domain)
58 {
59         if (!domain_is_valid(domain))
60                 return NULL;
61
62         switch (domain) {
63         case HV_PERF_DOMAIN_PHYS_CHIP:          return "Physical Chip";
64         case HV_PERF_DOMAIN_PHYS_CORE:          return "Physical Core";
65         case HV_PERF_DOMAIN_VCPU_HOME_CORE:     return "VCPU Home Core";
66         case HV_PERF_DOMAIN_VCPU_HOME_CHIP:     return "VCPU Home Chip";
67         case HV_PERF_DOMAIN_VCPU_HOME_NODE:     return "VCPU Home Node";
68         case HV_PERF_DOMAIN_VCPU_REMOTE_NODE:   return "VCPU Remote Node";
69         }
70
71         WARN_ON_ONCE(domain);
72         return NULL;
73 }
74
75 static bool catalog_entry_domain_is_valid(unsigned domain)
76 {
77         return is_physical_domain(domain);
78 }
79
80 /*
81  * TODO: Merging events:
82  * - Think of the hcall as an interface to a 4d array of counters:
83  *   - x = domains
84  *   - y = indexes in the domain (core, chip, vcpu, node, etc)
85  *   - z = offset into the counter space
86  *   - w = lpars (guest vms, "logical partitions")
87  * - A single request is: x,y,y_last,z,z_last,w,w_last
88  *   - this means we can retrieve a rectangle of counters in y,z for a single x.
89  *
90  * - Things to consider (ignoring w):
91  *   - input  cost_per_request = 16
92  *   - output cost_per_result(ys,zs)  = 8 + 8 * ys + ys * zs
93  *   - limited number of requests per hcall (must fit into 4K bytes)
94  *     - 4k = 16 [buffer header] - 16 [request size] * request_count
95  *     - 255 requests per hcall
96  *   - sometimes it will be more efficient to read extra data and discard
97  */
98
99 /*
100  * Example usage:
101  *  perf stat -e 'hv_24x7/domain=2,offset=8,vcpu=0,lpar=0xffffffff/'
102  */
103
104 /* u3 0-6, one of HV_24X7_PERF_DOMAIN */
105 EVENT_DEFINE_RANGE_FORMAT(domain, config, 0, 3);
106 /* u16 */
107 EVENT_DEFINE_RANGE_FORMAT(core, config, 16, 31);
108 EVENT_DEFINE_RANGE_FORMAT(chip, config, 16, 31);
109 EVENT_DEFINE_RANGE_FORMAT(vcpu, config, 16, 31);
110 /* u32, see "data_offset" */
111 EVENT_DEFINE_RANGE_FORMAT(offset, config, 32, 63);
112 /* u16 */
113 EVENT_DEFINE_RANGE_FORMAT(lpar, config1, 0, 15);
114
115 EVENT_DEFINE_RANGE(reserved1, config,   4, 15);
116 EVENT_DEFINE_RANGE(reserved2, config1, 16, 63);
117 EVENT_DEFINE_RANGE(reserved3, config2,  0, 63);
118
119 static struct attribute *format_attrs[] = {
120         &format_attr_domain.attr,
121         &format_attr_offset.attr,
122         &format_attr_core.attr,
123         &format_attr_chip.attr,
124         &format_attr_vcpu.attr,
125         &format_attr_lpar.attr,
126         NULL,
127 };
128
129 static struct attribute_group format_group = {
130         .name = "format",
131         .attrs = format_attrs,
132 };
133
134 static struct attribute_group event_group = {
135         .name = "events",
136         /* .attrs is set in init */
137 };
138
139 static struct attribute_group event_desc_group = {
140         .name = "event_descs",
141         /* .attrs is set in init */
142 };
143
144 static struct attribute_group event_long_desc_group = {
145         .name = "event_long_descs",
146         /* .attrs is set in init */
147 };
148
149 static struct kmem_cache *hv_page_cache;
150
151 DEFINE_PER_CPU(int, hv_24x7_txn_flags);
152 DEFINE_PER_CPU(int, hv_24x7_txn_err);
153
154 struct hv_24x7_hw {
155         struct perf_event *events[255];
156 };
157
158 DEFINE_PER_CPU(struct hv_24x7_hw, hv_24x7_hw);
159
160 /*
161  * request_buffer and result_buffer are not required to be 4k aligned,
162  * but are not allowed to cross any 4k boundary. Aligning them to 4k is
163  * the simplest way to ensure that.
164  */
165 #define H24x7_DATA_BUFFER_SIZE  4096
166 DEFINE_PER_CPU(char, hv_24x7_reqb[H24x7_DATA_BUFFER_SIZE]) __aligned(4096);
167 DEFINE_PER_CPU(char, hv_24x7_resb[H24x7_DATA_BUFFER_SIZE]) __aligned(4096);
168
169 #define MAX_NUM_REQUESTS        ((H24x7_DATA_BUFFER_SIZE -                     \
170                                         sizeof(struct hv_24x7_request_buffer)) \
171                                         / sizeof(struct hv_24x7_request))
172
173 static char *event_name(struct hv_24x7_event_data *ev, int *len)
174 {
175         *len = be16_to_cpu(ev->event_name_len) - 2;
176         return (char *)ev->remainder;
177 }
178
179 static char *event_desc(struct hv_24x7_event_data *ev, int *len)
180 {
181         unsigned nl = be16_to_cpu(ev->event_name_len);
182         __be16 *desc_len = (__be16 *)(ev->remainder + nl - 2);
183
184         *len = be16_to_cpu(*desc_len) - 2;
185         return (char *)ev->remainder + nl;
186 }
187
188 static char *event_long_desc(struct hv_24x7_event_data *ev, int *len)
189 {
190         unsigned nl = be16_to_cpu(ev->event_name_len);
191         __be16 *desc_len_ = (__be16 *)(ev->remainder + nl - 2);
192         unsigned desc_len = be16_to_cpu(*desc_len_);
193         __be16 *long_desc_len = (__be16 *)(ev->remainder + nl + desc_len - 2);
194
195         *len = be16_to_cpu(*long_desc_len) - 2;
196         return (char *)ev->remainder + nl + desc_len;
197 }
198
199 static bool event_fixed_portion_is_within(struct hv_24x7_event_data *ev,
200                                           void *end)
201 {
202         void *start = ev;
203
204         return (start + offsetof(struct hv_24x7_event_data, remainder)) < end;
205 }
206
207 /*
208  * Things we don't check:
209  *  - padding for desc, name, and long/detailed desc is required to be '\0'
210  *    bytes.
211  *
212  *  Return NULL if we pass end,
213  *  Otherwise return the address of the byte just following the event.
214  */
215 static void *event_end(struct hv_24x7_event_data *ev, void *end)
216 {
217         void *start = ev;
218         __be16 *dl_, *ldl_;
219         unsigned dl, ldl;
220         unsigned nl = be16_to_cpu(ev->event_name_len);
221
222         if (nl < 2) {
223                 pr_debug("%s: name length too short: %d", __func__, nl);
224                 return NULL;
225         }
226
227         if (start + nl > end) {
228                 pr_debug("%s: start=%p + nl=%u > end=%p",
229                                 __func__, start, nl, end);
230                 return NULL;
231         }
232
233         dl_ = (__be16 *)(ev->remainder + nl - 2);
234         if (!IS_ALIGNED((uintptr_t)dl_, 2))
235                 pr_warn("desc len not aligned %p", dl_);
236         dl = be16_to_cpu(*dl_);
237         if (dl < 2) {
238                 pr_debug("%s: desc len too short: %d", __func__, dl);
239                 return NULL;
240         }
241
242         if (start + nl + dl > end) {
243                 pr_debug("%s: (start=%p + nl=%u + dl=%u)=%p > end=%p",
244                                 __func__, start, nl, dl, start + nl + dl, end);
245                 return NULL;
246         }
247
248         ldl_ = (__be16 *)(ev->remainder + nl + dl - 2);
249         if (!IS_ALIGNED((uintptr_t)ldl_, 2))
250                 pr_warn("long desc len not aligned %p", ldl_);
251         ldl = be16_to_cpu(*ldl_);
252         if (ldl < 2) {
253                 pr_debug("%s: long desc len too short (ldl=%u)",
254                                 __func__, ldl);
255                 return NULL;
256         }
257
258         if (start + nl + dl + ldl > end) {
259                 pr_debug("%s: start=%p + nl=%u + dl=%u + ldl=%u > end=%p",
260                                 __func__, start, nl, dl, ldl, end);
261                 return NULL;
262         }
263
264         return start + nl + dl + ldl;
265 }
266
267 static long h_get_24x7_catalog_page_(unsigned long phys_4096,
268                                      unsigned long version, unsigned long index)
269 {
270         pr_devel("h_get_24x7_catalog_page(0x%lx, %lu, %lu)",
271                         phys_4096, version, index);
272
273         WARN_ON(!IS_ALIGNED(phys_4096, 4096));
274
275         return plpar_hcall_norets(H_GET_24X7_CATALOG_PAGE,
276                         phys_4096, version, index);
277 }
278
279 static long h_get_24x7_catalog_page(char page[], u64 version, u32 index)
280 {
281         return h_get_24x7_catalog_page_(virt_to_phys(page),
282                                         version, index);
283 }
284
285 /*
286  * Each event we find in the catalog, will have a sysfs entry. Format the
287  * data for this sysfs entry based on the event's domain.
288  *
289  * Events belonging to the Chip domain can only be monitored in that domain.
290  * i.e the domain for these events is a fixed/knwon value.
291  *
292  * Events belonging to the Core domain can be monitored either in the physical
293  * core or in one of the virtual CPU domains. So the domain value for these
294  * events must be specified by the user (i.e is a required parameter). Format
295  * the Core events with 'domain=?' so the perf-tool can error check required
296  * parameters.
297  *
298  * NOTE: For the Core domain events, rather than making domain a required
299  *       parameter we could default it to PHYS_CORE and allowe users to
300  *       override the domain to one of the VCPU domains.
301  *
302  *       However, this can make the interface a little inconsistent.
303  *
304  *       If we set domain=2 (PHYS_CHIP) and allow user to override this field
305  *       the user may be tempted to also modify the "offset=x" field in which
306  *       can lead to confusing usage. Consider the HPM_PCYC (offset=0x18) and
307  *       HPM_INST (offset=0x20) events. With:
308  *
309  *              perf stat -e hv_24x7/HPM_PCYC,offset=0x20/
310  *
311  *      we end up monitoring HPM_INST, while the command line has HPM_PCYC.
312  *
313  *      By not assigning a default value to the domain for the Core events,
314  *      we can have simple guidelines:
315  *
316  *              - Specifying values for parameters with "=?" is required.
317  *
318  *              - Specifying (i.e overriding) values for other parameters
319  *                is undefined.
320  */
321 static char *event_fmt(struct hv_24x7_event_data *event, unsigned domain)
322 {
323         const char *sindex;
324         const char *lpar;
325         const char *domain_str;
326         char buf[8];
327
328         switch (domain) {
329         case HV_PERF_DOMAIN_PHYS_CHIP:
330                 snprintf(buf, sizeof(buf), "%d", domain);
331                 domain_str = buf;
332                 lpar = "0x0";
333                 sindex = "chip";
334                 break;
335         case HV_PERF_DOMAIN_PHYS_CORE:
336                 domain_str = "?";
337                 lpar = "0x0";
338                 sindex = "core";
339                 break;
340         default:
341                 domain_str = "?";
342                 lpar = "?";
343                 sindex = "vcpu";
344         }
345
346         return kasprintf(GFP_KERNEL,
347                         "domain=%s,offset=0x%x,%s=?,lpar=%s",
348                         domain_str,
349                         be16_to_cpu(event->event_counter_offs) +
350                                 be16_to_cpu(event->event_group_record_offs),
351                         sindex,
352                         lpar);
353 }
354
355 /* Avoid trusting fw to NUL terminate strings */
356 static char *memdup_to_str(char *maybe_str, int max_len, gfp_t gfp)
357 {
358         return kasprintf(gfp, "%.*s", max_len, maybe_str);
359 }
360
361 static ssize_t device_show_string(struct device *dev,
362                 struct device_attribute *attr, char *buf)
363 {
364         struct dev_ext_attribute *d;
365
366         d = container_of(attr, struct dev_ext_attribute, attr);
367
368         return sprintf(buf, "%s\n", (char *)d->var);
369 }
370
371 static struct attribute *device_str_attr_create_(char *name, char *str)
372 {
373         struct dev_ext_attribute *attr = kzalloc(sizeof(*attr), GFP_KERNEL);
374
375         if (!attr)
376                 return NULL;
377
378         sysfs_attr_init(&attr->attr.attr);
379
380         attr->var = str;
381         attr->attr.attr.name = name;
382         attr->attr.attr.mode = 0444;
383         attr->attr.show = device_show_string;
384
385         return &attr->attr.attr;
386 }
387
388 /*
389  * Allocate and initialize strings representing event attributes.
390  *
391  * NOTE: The strings allocated here are never destroyed and continue to
392  *       exist till shutdown. This is to allow us to create as many events
393  *       from the catalog as possible, even if we encounter errors with some.
394  *       In case of changes to error paths in future, these may need to be
395  *       freed by the caller.
396  */
397 static struct attribute *device_str_attr_create(char *name, int name_max,
398                                                 int name_nonce,
399                                                 char *str, size_t str_max)
400 {
401         char *n;
402         char *s = memdup_to_str(str, str_max, GFP_KERNEL);
403         struct attribute *a;
404
405         if (!s)
406                 return NULL;
407
408         if (!name_nonce)
409                 n = kasprintf(GFP_KERNEL, "%.*s", name_max, name);
410         else
411                 n = kasprintf(GFP_KERNEL, "%.*s__%d", name_max, name,
412                                         name_nonce);
413         if (!n)
414                 goto out_s;
415
416         a = device_str_attr_create_(n, s);
417         if (!a)
418                 goto out_n;
419
420         return a;
421 out_n:
422         kfree(n);
423 out_s:
424         kfree(s);
425         return NULL;
426 }
427
428 static struct attribute *event_to_attr(unsigned ix,
429                                        struct hv_24x7_event_data *event,
430                                        unsigned domain,
431                                        int nonce)
432 {
433         int event_name_len;
434         char *ev_name, *a_ev_name, *val;
435         struct attribute *attr;
436
437         if (!domain_is_valid(domain)) {
438                 pr_warn("catalog event %u has invalid domain %u\n",
439                                 ix, domain);
440                 return NULL;
441         }
442
443         val = event_fmt(event, domain);
444         if (!val)
445                 return NULL;
446
447         ev_name = event_name(event, &event_name_len);
448         if (!nonce)
449                 a_ev_name = kasprintf(GFP_KERNEL, "%.*s",
450                                 (int)event_name_len, ev_name);
451         else
452                 a_ev_name = kasprintf(GFP_KERNEL, "%.*s__%d",
453                                 (int)event_name_len, ev_name, nonce);
454
455         if (!a_ev_name)
456                 goto out_val;
457
458         attr = device_str_attr_create_(a_ev_name, val);
459         if (!attr)
460                 goto out_name;
461
462         return attr;
463 out_name:
464         kfree(a_ev_name);
465 out_val:
466         kfree(val);
467         return NULL;
468 }
469
470 static struct attribute *event_to_desc_attr(struct hv_24x7_event_data *event,
471                                             int nonce)
472 {
473         int nl, dl;
474         char *name = event_name(event, &nl);
475         char *desc = event_desc(event, &dl);
476
477         /* If there isn't a description, don't create the sysfs file */
478         if (!dl)
479                 return NULL;
480
481         return device_str_attr_create(name, nl, nonce, desc, dl);
482 }
483
484 static struct attribute *
485 event_to_long_desc_attr(struct hv_24x7_event_data *event, int nonce)
486 {
487         int nl, dl;
488         char *name = event_name(event, &nl);
489         char *desc = event_long_desc(event, &dl);
490
491         /* If there isn't a description, don't create the sysfs file */
492         if (!dl)
493                 return NULL;
494
495         return device_str_attr_create(name, nl, nonce, desc, dl);
496 }
497
498 static int event_data_to_attrs(unsigned ix, struct attribute **attrs,
499                                    struct hv_24x7_event_data *event, int nonce)
500 {
501         *attrs = event_to_attr(ix, event, event->domain, nonce);
502         if (!*attrs)
503                 return -1;
504
505         return 0;
506 }
507
508 /* */
509 struct event_uniq {
510         struct rb_node node;
511         const char *name;
512         int nl;
513         unsigned ct;
514         unsigned domain;
515 };
516
517 static int memord(const void *d1, size_t s1, const void *d2, size_t s2)
518 {
519         if (s1 < s2)
520                 return 1;
521         if (s2 > s1)
522                 return -1;
523
524         return memcmp(d1, d2, s1);
525 }
526
527 static int ev_uniq_ord(const void *v1, size_t s1, unsigned d1, const void *v2,
528                        size_t s2, unsigned d2)
529 {
530         int r = memord(v1, s1, v2, s2);
531
532         if (r)
533                 return r;
534         if (d1 > d2)
535                 return 1;
536         if (d2 > d1)
537                 return -1;
538         return 0;
539 }
540
541 static int event_uniq_add(struct rb_root *root, const char *name, int nl,
542                           unsigned domain)
543 {
544         struct rb_node **new = &(root->rb_node), *parent = NULL;
545         struct event_uniq *data;
546
547         /* Figure out where to put new node */
548         while (*new) {
549                 struct event_uniq *it;
550                 int result;
551
552                 it = container_of(*new, struct event_uniq, node);
553                 result = ev_uniq_ord(name, nl, domain, it->name, it->nl,
554                                         it->domain);
555
556                 parent = *new;
557                 if (result < 0)
558                         new = &((*new)->rb_left);
559                 else if (result > 0)
560                         new = &((*new)->rb_right);
561                 else {
562                         it->ct++;
563                         pr_info("found a duplicate event %.*s, ct=%u\n", nl,
564                                                 name, it->ct);
565                         return it->ct;
566                 }
567         }
568
569         data = kmalloc(sizeof(*data), GFP_KERNEL);
570         if (!data)
571                 return -ENOMEM;
572
573         *data = (struct event_uniq) {
574                 .name = name,
575                 .nl = nl,
576                 .ct = 0,
577                 .domain = domain,
578         };
579
580         /* Add new node and rebalance tree. */
581         rb_link_node(&data->node, parent, new);
582         rb_insert_color(&data->node, root);
583
584         /* data->ct */
585         return 0;
586 }
587
588 static void event_uniq_destroy(struct rb_root *root)
589 {
590         /*
591          * the strings we point to are in the giant block of memory filled by
592          * the catalog, and are freed separately.
593          */
594         struct event_uniq *pos, *n;
595
596         rbtree_postorder_for_each_entry_safe(pos, n, root, node)
597                 kfree(pos);
598 }
599
600
601 /*
602  * ensure the event structure's sizes are self consistent and don't cause us to
603  * read outside of the event
604  *
605  * On success, return the event length in bytes.
606  * Otherwise, return -1 (and print as appropriate).
607  */
608 static ssize_t catalog_event_len_validate(struct hv_24x7_event_data *event,
609                                           size_t event_idx,
610                                           size_t event_data_bytes,
611                                           size_t event_entry_count,
612                                           size_t offset, void *end)
613 {
614         ssize_t ev_len;
615         void *ev_end, *calc_ev_end;
616
617         if (offset >= event_data_bytes)
618                 return -1;
619
620         if (event_idx >= event_entry_count) {
621                 pr_devel("catalog event data has %zu bytes of padding after last event\n",
622                                 event_data_bytes - offset);
623                 return -1;
624         }
625
626         if (!event_fixed_portion_is_within(event, end)) {
627                 pr_warn("event %zu fixed portion is not within range\n",
628                                 event_idx);
629                 return -1;
630         }
631
632         ev_len = be16_to_cpu(event->length);
633
634         if (ev_len % 16)
635                 pr_info("event %zu has length %zu not divisible by 16: event=%pK\n",
636                                 event_idx, ev_len, event);
637
638         ev_end = (__u8 *)event + ev_len;
639         if (ev_end > end) {
640                 pr_warn("event %zu has .length=%zu, ends after buffer end: ev_end=%pK > end=%pK, offset=%zu\n",
641                                 event_idx, ev_len, ev_end, end,
642                                 offset);
643                 return -1;
644         }
645
646         calc_ev_end = event_end(event, end);
647         if (!calc_ev_end) {
648                 pr_warn("event %zu has a calculated length which exceeds buffer length %zu: event=%pK end=%pK, offset=%zu\n",
649                         event_idx, event_data_bytes, event, end,
650                         offset);
651                 return -1;
652         }
653
654         if (calc_ev_end > ev_end) {
655                 pr_warn("event %zu exceeds it's own length: event=%pK, end=%pK, offset=%zu, calc_ev_end=%pK\n",
656                         event_idx, event, ev_end, offset, calc_ev_end);
657                 return -1;
658         }
659
660         return ev_len;
661 }
662
663 #define MAX_4K (SIZE_MAX / 4096)
664
665 static int create_events_from_catalog(struct attribute ***events_,
666                                       struct attribute ***event_descs_,
667                                       struct attribute ***event_long_descs_)
668 {
669         long hret;
670         size_t catalog_len, catalog_page_len, event_entry_count,
671                event_data_len, event_data_offs,
672                event_data_bytes, junk_events, event_idx, event_attr_ct, i,
673                attr_max, event_idx_last, desc_ct, long_desc_ct;
674         ssize_t ct, ev_len;
675         uint64_t catalog_version_num;
676         struct attribute **events, **event_descs, **event_long_descs;
677         struct hv_24x7_catalog_page_0 *page_0 =
678                 kmem_cache_alloc(hv_page_cache, GFP_KERNEL);
679         void *page = page_0;
680         void *event_data, *end;
681         struct hv_24x7_event_data *event;
682         struct rb_root ev_uniq = RB_ROOT;
683         int ret = 0;
684
685         if (!page) {
686                 ret = -ENOMEM;
687                 goto e_out;
688         }
689
690         hret = h_get_24x7_catalog_page(page, 0, 0);
691         if (hret) {
692                 ret = -EIO;
693                 goto e_free;
694         }
695
696         catalog_version_num = be64_to_cpu(page_0->version);
697         catalog_page_len = be32_to_cpu(page_0->length);
698
699         if (MAX_4K < catalog_page_len) {
700                 pr_err("invalid page count: %zu\n", catalog_page_len);
701                 ret = -EIO;
702                 goto e_free;
703         }
704
705         catalog_len = catalog_page_len * 4096;
706
707         event_entry_count = be16_to_cpu(page_0->event_entry_count);
708         event_data_offs   = be16_to_cpu(page_0->event_data_offs);
709         event_data_len    = be16_to_cpu(page_0->event_data_len);
710
711         pr_devel("cv %llu cl %zu eec %zu edo %zu edl %zu\n",
712                         catalog_version_num, catalog_len,
713                         event_entry_count, event_data_offs, event_data_len);
714
715         if ((MAX_4K < event_data_len)
716                         || (MAX_4K < event_data_offs)
717                         || (MAX_4K - event_data_offs < event_data_len)) {
718                 pr_err("invalid event data offs %zu and/or len %zu\n",
719                                 event_data_offs, event_data_len);
720                 ret = -EIO;
721                 goto e_free;
722         }
723
724         if ((event_data_offs + event_data_len) > catalog_page_len) {
725                 pr_err("event data %zu-%zu does not fit inside catalog 0-%zu\n",
726                                 event_data_offs,
727                                 event_data_offs + event_data_len,
728                                 catalog_page_len);
729                 ret = -EIO;
730                 goto e_free;
731         }
732
733         if (SIZE_MAX - 1 < event_entry_count) {
734                 pr_err("event_entry_count %zu is invalid\n", event_entry_count);
735                 ret = -EIO;
736                 goto e_free;
737         }
738
739         event_data_bytes = event_data_len * 4096;
740
741         /*
742          * event data can span several pages, events can cross between these
743          * pages. Use vmalloc to make this easier.
744          */
745         event_data = vmalloc(event_data_bytes);
746         if (!event_data) {
747                 pr_err("could not allocate event data\n");
748                 ret = -ENOMEM;
749                 goto e_free;
750         }
751
752         end = event_data + event_data_bytes;
753
754         /*
755          * using vmalloc_to_phys() like this only works if PAGE_SIZE is
756          * divisible by 4096
757          */
758         BUILD_BUG_ON(PAGE_SIZE % 4096);
759
760         for (i = 0; i < event_data_len; i++) {
761                 hret = h_get_24x7_catalog_page_(
762                                 vmalloc_to_phys(event_data + i * 4096),
763                                 catalog_version_num,
764                                 i + event_data_offs);
765                 if (hret) {
766                         pr_err("Failed to get event data in page %zu: rc=%ld\n",
767                                i + event_data_offs, hret);
768                         ret = -EIO;
769                         goto e_event_data;
770                 }
771         }
772
773         /*
774          * scan the catalog to determine the number of attributes we need, and
775          * verify it at the same time.
776          */
777         for (junk_events = 0, event = event_data, event_idx = 0, attr_max = 0;
778              ;
779              event_idx++, event = (void *)event + ev_len) {
780                 size_t offset = (void *)event - (void *)event_data;
781                 char *name;
782                 int nl;
783
784                 ev_len = catalog_event_len_validate(event, event_idx,
785                                                     event_data_bytes,
786                                                     event_entry_count,
787                                                     offset, end);
788                 if (ev_len < 0)
789                         break;
790
791                 name = event_name(event, &nl);
792
793                 if (event->event_group_record_len == 0) {
794                         pr_devel("invalid event %zu (%.*s): group_record_len == 0, skipping\n",
795                                         event_idx, nl, name);
796                         junk_events++;
797                         continue;
798                 }
799
800                 if (!catalog_entry_domain_is_valid(event->domain)) {
801                         pr_info("event %zu (%.*s) has invalid domain %d\n",
802                                         event_idx, nl, name, event->domain);
803                         junk_events++;
804                         continue;
805                 }
806
807                 attr_max++;
808         }
809
810         event_idx_last = event_idx;
811         if (event_idx_last != event_entry_count)
812                 pr_warn("event buffer ended before listed # of events were parsed (got %zu, wanted %zu, junk %zu)\n",
813                                 event_idx_last, event_entry_count, junk_events);
814
815         events = kmalloc_array(attr_max + 1, sizeof(*events), GFP_KERNEL);
816         if (!events) {
817                 ret = -ENOMEM;
818                 goto e_event_data;
819         }
820
821         event_descs = kmalloc_array(event_idx + 1, sizeof(*event_descs),
822                                 GFP_KERNEL);
823         if (!event_descs) {
824                 ret = -ENOMEM;
825                 goto e_event_attrs;
826         }
827
828         event_long_descs = kmalloc_array(event_idx + 1,
829                         sizeof(*event_long_descs), GFP_KERNEL);
830         if (!event_long_descs) {
831                 ret = -ENOMEM;
832                 goto e_event_descs;
833         }
834
835         /* Iterate over the catalog filling in the attribute vector */
836         for (junk_events = 0, event_attr_ct = 0, desc_ct = 0, long_desc_ct = 0,
837                                 event = event_data, event_idx = 0;
838                         event_idx < event_idx_last;
839                         event_idx++, ev_len = be16_to_cpu(event->length),
840                                 event = (void *)event + ev_len) {
841                 char *name;
842                 int nl;
843                 int nonce;
844                 /*
845                  * these are the only "bad" events that are intermixed and that
846                  * we can ignore without issue. make sure to skip them here
847                  */
848                 if (event->event_group_record_len == 0)
849                         continue;
850                 if (!catalog_entry_domain_is_valid(event->domain))
851                         continue;
852
853                 name  = event_name(event, &nl);
854                 nonce = event_uniq_add(&ev_uniq, name, nl, event->domain);
855                 ct    = event_data_to_attrs(event_idx, events + event_attr_ct,
856                                             event, nonce);
857                 if (ct < 0) {
858                         pr_warn("event %zu (%.*s) creation failure, skipping\n",
859                                 event_idx, nl, name);
860                         junk_events++;
861                 } else {
862                         event_attr_ct++;
863                         event_descs[desc_ct] = event_to_desc_attr(event, nonce);
864                         if (event_descs[desc_ct])
865                                 desc_ct++;
866                         event_long_descs[long_desc_ct] =
867                                         event_to_long_desc_attr(event, nonce);
868                         if (event_long_descs[long_desc_ct])
869                                 long_desc_ct++;
870                 }
871         }
872
873         pr_info("read %zu catalog entries, created %zu event attrs (%zu failures), %zu descs\n",
874                         event_idx, event_attr_ct, junk_events, desc_ct);
875
876         events[event_attr_ct] = NULL;
877         event_descs[desc_ct] = NULL;
878         event_long_descs[long_desc_ct] = NULL;
879
880         event_uniq_destroy(&ev_uniq);
881         vfree(event_data);
882         kmem_cache_free(hv_page_cache, page);
883
884         *events_ = events;
885         *event_descs_ = event_descs;
886         *event_long_descs_ = event_long_descs;
887         return 0;
888
889 e_event_descs:
890         kfree(event_descs);
891 e_event_attrs:
892         kfree(events);
893 e_event_data:
894         vfree(event_data);
895 e_free:
896         kmem_cache_free(hv_page_cache, page);
897 e_out:
898         *events_ = NULL;
899         *event_descs_ = NULL;
900         *event_long_descs_ = NULL;
901         return ret;
902 }
903
904 static ssize_t catalog_read(struct file *filp, struct kobject *kobj,
905                             struct bin_attribute *bin_attr, char *buf,
906                             loff_t offset, size_t count)
907 {
908         long hret;
909         ssize_t ret = 0;
910         size_t catalog_len = 0, catalog_page_len = 0;
911         loff_t page_offset = 0;
912         loff_t offset_in_page;
913         size_t copy_len;
914         uint64_t catalog_version_num = 0;
915         void *page = kmem_cache_alloc(hv_page_cache, GFP_USER);
916         struct hv_24x7_catalog_page_0 *page_0 = page;
917
918         if (!page)
919                 return -ENOMEM;
920
921         hret = h_get_24x7_catalog_page(page, 0, 0);
922         if (hret) {
923                 ret = -EIO;
924                 goto e_free;
925         }
926
927         catalog_version_num = be64_to_cpu(page_0->version);
928         catalog_page_len = be32_to_cpu(page_0->length);
929         catalog_len = catalog_page_len * 4096;
930
931         page_offset = offset / 4096;
932         offset_in_page = offset % 4096;
933
934         if (page_offset >= catalog_page_len)
935                 goto e_free;
936
937         if (page_offset != 0) {
938                 hret = h_get_24x7_catalog_page(page, catalog_version_num,
939                                                page_offset);
940                 if (hret) {
941                         ret = -EIO;
942                         goto e_free;
943                 }
944         }
945
946         copy_len = 4096 - offset_in_page;
947         if (copy_len > count)
948                 copy_len = count;
949
950         memcpy(buf, page+offset_in_page, copy_len);
951         ret = copy_len;
952
953 e_free:
954         if (hret)
955                 pr_err("h_get_24x7_catalog_page(ver=%lld, page=%lld) failed:"
956                        " rc=%ld\n",
957                        catalog_version_num, page_offset, hret);
958         kmem_cache_free(hv_page_cache, page);
959
960         pr_devel("catalog_read: offset=%lld(%lld) count=%zu "
961                         "catalog_len=%zu(%zu) => %zd\n", offset, page_offset,
962                         count, catalog_len, catalog_page_len, ret);
963
964         return ret;
965 }
966
967 static ssize_t domains_show(struct device *dev, struct device_attribute *attr,
968                             char *page)
969 {
970         int d, n, count = 0;
971         const char *str;
972
973         for (d = 0; d < HV_PERF_DOMAIN_MAX; d++) {
974                 str = domain_name(d);
975                 if (!str)
976                         continue;
977
978                 n = sprintf(page, "%d: %s\n", d, str);
979                 if (n < 0)
980                         break;
981
982                 count += n;
983                 page += n;
984         }
985         return count;
986 }
987
988 #define PAGE_0_ATTR(_name, _fmt, _expr)                         \
989 static ssize_t _name##_show(struct device *dev,                 \
990                             struct device_attribute *dev_attr,  \
991                             char *buf)                          \
992 {                                                               \
993         long hret;                                              \
994         ssize_t ret = 0;                                        \
995         void *page = kmem_cache_alloc(hv_page_cache, GFP_USER); \
996         struct hv_24x7_catalog_page_0 *page_0 = page;           \
997         if (!page)                                              \
998                 return -ENOMEM;                                 \
999         hret = h_get_24x7_catalog_page(page, 0, 0);             \
1000         if (hret) {                                             \
1001                 ret = -EIO;                                     \
1002                 goto e_free;                                    \
1003         }                                                       \
1004         ret = sprintf(buf, _fmt, _expr);                        \
1005 e_free:                                                         \
1006         kmem_cache_free(hv_page_cache, page);                   \
1007         return ret;                                             \
1008 }                                                               \
1009 static DEVICE_ATTR_RO(_name)
1010
1011 PAGE_0_ATTR(catalog_version, "%lld\n",
1012                 (unsigned long long)be64_to_cpu(page_0->version));
1013 PAGE_0_ATTR(catalog_len, "%lld\n",
1014                 (unsigned long long)be32_to_cpu(page_0->length) * 4096);
1015 static BIN_ATTR_RO(catalog, 0/* real length varies */);
1016 static DEVICE_ATTR_RO(domains);
1017
1018 static struct bin_attribute *if_bin_attrs[] = {
1019         &bin_attr_catalog,
1020         NULL,
1021 };
1022
1023 static struct attribute *if_attrs[] = {
1024         &dev_attr_catalog_len.attr,
1025         &dev_attr_catalog_version.attr,
1026         &dev_attr_domains.attr,
1027         NULL,
1028 };
1029
1030 static struct attribute_group if_group = {
1031         .name = "interface",
1032         .bin_attrs = if_bin_attrs,
1033         .attrs = if_attrs,
1034 };
1035
1036 static const struct attribute_group *attr_groups[] = {
1037         &format_group,
1038         &event_group,
1039         &event_desc_group,
1040         &event_long_desc_group,
1041         &if_group,
1042         NULL,
1043 };
1044
1045 /*
1046  * Start the process for a new H_GET_24x7_DATA hcall.
1047  */
1048 static void init_24x7_request(struct hv_24x7_request_buffer *request_buffer,
1049                               struct hv_24x7_data_result_buffer *result_buffer)
1050 {
1051
1052         memset(request_buffer, 0, 4096);
1053         memset(result_buffer, 0, 4096);
1054
1055         request_buffer->interface_version = HV_24X7_IF_VERSION_CURRENT;
1056         /* memset above set request_buffer->num_requests to 0 */
1057 }
1058
1059 /*
1060  * Commit (i.e perform) the H_GET_24x7_DATA hcall using the data collected
1061  * by 'init_24x7_request()' and 'add_event_to_24x7_request()'.
1062  */
1063 static int make_24x7_request(struct hv_24x7_request_buffer *request_buffer,
1064                              struct hv_24x7_data_result_buffer *result_buffer)
1065 {
1066         long ret;
1067
1068         /*
1069          * NOTE: Due to variable number of array elements in request and
1070          *       result buffer(s), sizeof() is not reliable. Use the actual
1071          *       allocated buffer size, H24x7_DATA_BUFFER_SIZE.
1072          */
1073         ret = plpar_hcall_norets(H_GET_24X7_DATA,
1074                         virt_to_phys(request_buffer), H24x7_DATA_BUFFER_SIZE,
1075                         virt_to_phys(result_buffer),  H24x7_DATA_BUFFER_SIZE);
1076
1077         if (ret) {
1078                 struct hv_24x7_request *req;
1079
1080                 req = &request_buffer->requests[0];
1081                 pr_notice_ratelimited("hcall failed: [%d %#x %#x %d] => ret 0x%lx (%ld) detail=0x%x failing ix=%x\n",
1082                                       req->performance_domain, req->data_offset,
1083                                       req->starting_ix, req->starting_lpar_ix,
1084                                       ret, ret, result_buffer->detailed_rc,
1085                                       result_buffer->failing_request_ix);
1086                 return -EIO;
1087         }
1088
1089         return 0;
1090 }
1091
1092 /*
1093  * Add the given @event to the next slot in the 24x7 request_buffer.
1094  *
1095  * Note that H_GET_24X7_DATA hcall allows reading several counters'
1096  * values in a single HCALL. We expect the caller to add events to the
1097  * request buffer one by one, make the HCALL and process the results.
1098  */
1099 static int add_event_to_24x7_request(struct perf_event *event,
1100                                 struct hv_24x7_request_buffer *request_buffer)
1101 {
1102         u16 idx;
1103         int i;
1104         struct hv_24x7_request *req;
1105
1106         if (request_buffer->num_requests >= MAX_NUM_REQUESTS) {
1107                 pr_devel("Too many requests for 24x7 HCALL %d\n",
1108                                 request_buffer->num_requests);
1109                 return -EINVAL;
1110         }
1111
1112         switch (event_get_domain(event)) {
1113         case HV_PERF_DOMAIN_PHYS_CHIP:
1114                 idx = event_get_chip(event);
1115                 break;
1116         case HV_PERF_DOMAIN_PHYS_CORE:
1117                 idx = event_get_core(event);
1118                 break;
1119         default:
1120                 idx = event_get_vcpu(event);
1121         }
1122
1123         i = request_buffer->num_requests++;
1124         req = &request_buffer->requests[i];
1125
1126         req->performance_domain = event_get_domain(event);
1127         req->data_size = cpu_to_be16(8);
1128         req->data_offset = cpu_to_be32(event_get_offset(event));
1129         req->starting_lpar_ix = cpu_to_be16(event_get_lpar(event)),
1130         req->max_num_lpars = cpu_to_be16(1);
1131         req->starting_ix = cpu_to_be16(idx);
1132         req->max_ix = cpu_to_be16(1);
1133
1134         return 0;
1135 }
1136
1137 static int single_24x7_request(struct perf_event *event, u64 *count)
1138 {
1139         int ret;
1140         u16 num_elements;
1141         struct hv_24x7_result *result;
1142         struct hv_24x7_request_buffer *request_buffer;
1143         struct hv_24x7_data_result_buffer *result_buffer;
1144
1145         BUILD_BUG_ON(sizeof(*request_buffer) > 4096);
1146         BUILD_BUG_ON(sizeof(*result_buffer) > 4096);
1147
1148         request_buffer = (void *)get_cpu_var(hv_24x7_reqb);
1149         result_buffer = (void *)get_cpu_var(hv_24x7_resb);
1150
1151         init_24x7_request(request_buffer, result_buffer);
1152
1153         ret = add_event_to_24x7_request(event, request_buffer);
1154         if (ret)
1155                 goto out;
1156
1157         ret = make_24x7_request(request_buffer, result_buffer);
1158         if (ret)
1159                 goto out;
1160
1161         result = result_buffer->results;
1162
1163         /* This code assumes that a result has only one element. */
1164         num_elements = be16_to_cpu(result->num_elements_returned);
1165         WARN_ON_ONCE(num_elements != 1);
1166
1167         /* process result from hcall */
1168         *count = be64_to_cpu(result->elements[0].element_data[0]);
1169
1170 out:
1171         put_cpu_var(hv_24x7_reqb);
1172         put_cpu_var(hv_24x7_resb);
1173         return ret;
1174 }
1175
1176
1177 static int h_24x7_event_init(struct perf_event *event)
1178 {
1179         struct hv_perf_caps caps;
1180         unsigned domain;
1181         unsigned long hret;
1182         u64 ct;
1183
1184         /* Not our event */
1185         if (event->attr.type != event->pmu->type)
1186                 return -ENOENT;
1187
1188         /* Unused areas must be 0 */
1189         if (event_get_reserved1(event) ||
1190             event_get_reserved2(event) ||
1191             event_get_reserved3(event)) {
1192                 pr_devel("reserved set when forbidden 0x%llx(0x%llx) 0x%llx(0x%llx) 0x%llx(0x%llx)\n",
1193                                 event->attr.config,
1194                                 event_get_reserved1(event),
1195                                 event->attr.config1,
1196                                 event_get_reserved2(event),
1197                                 event->attr.config2,
1198                                 event_get_reserved3(event));
1199                 return -EINVAL;
1200         }
1201
1202         /* unsupported modes and filters */
1203         if (event->attr.exclude_user   ||
1204             event->attr.exclude_kernel ||
1205             event->attr.exclude_hv     ||
1206             event->attr.exclude_idle   ||
1207             event->attr.exclude_host   ||
1208             event->attr.exclude_guest)
1209                 return -EINVAL;
1210
1211         /* no branch sampling */
1212         if (has_branch_stack(event))
1213                 return -EOPNOTSUPP;
1214
1215         /* offset must be 8 byte aligned */
1216         if (event_get_offset(event) % 8) {
1217                 pr_devel("bad alignment\n");
1218                 return -EINVAL;
1219         }
1220
1221         /* Domains above 6 are invalid */
1222         domain = event_get_domain(event);
1223         if (domain > 6) {
1224                 pr_devel("invalid domain %d\n", domain);
1225                 return -EINVAL;
1226         }
1227
1228         hret = hv_perf_caps_get(&caps);
1229         if (hret) {
1230                 pr_devel("could not get capabilities: rc=%ld\n", hret);
1231                 return -EIO;
1232         }
1233
1234         /* Physical domains & other lpars require extra capabilities */
1235         if (!caps.collect_privileged && (is_physical_domain(domain) ||
1236                 (event_get_lpar(event) != event_get_lpar_max()))) {
1237                 pr_devel("hv permissions disallow: is_physical_domain:%d, lpar=0x%llx\n",
1238                                 is_physical_domain(domain),
1239                                 event_get_lpar(event));
1240                 return -EACCES;
1241         }
1242
1243         /* Get the initial value of the counter for this event */
1244         if (single_24x7_request(event, &ct)) {
1245                 pr_devel("test hcall failed\n");
1246                 return -EIO;
1247         }
1248         (void)local64_xchg(&event->hw.prev_count, ct);
1249
1250         return 0;
1251 }
1252
1253 static u64 h_24x7_get_value(struct perf_event *event)
1254 {
1255         u64 ct;
1256
1257         if (single_24x7_request(event, &ct))
1258                 /* We checked this in event init, shouldn't fail here... */
1259                 return 0;
1260
1261         return ct;
1262 }
1263
1264 static void update_event_count(struct perf_event *event, u64 now)
1265 {
1266         s64 prev;
1267
1268         prev = local64_xchg(&event->hw.prev_count, now);
1269         local64_add(now - prev, &event->count);
1270 }
1271
1272 static void h_24x7_event_read(struct perf_event *event)
1273 {
1274         u64 now;
1275         struct hv_24x7_request_buffer *request_buffer;
1276         struct hv_24x7_hw *h24x7hw;
1277         int txn_flags;
1278
1279         txn_flags = __this_cpu_read(hv_24x7_txn_flags);
1280
1281         /*
1282          * If in a READ transaction, add this counter to the list of
1283          * counters to read during the next HCALL (i.e commit_txn()).
1284          * If not in a READ transaction, go ahead and make the HCALL
1285          * to read this counter by itself.
1286          */
1287
1288         if (txn_flags & PERF_PMU_TXN_READ) {
1289                 int i;
1290                 int ret;
1291
1292                 if (__this_cpu_read(hv_24x7_txn_err))
1293                         return;
1294
1295                 request_buffer = (void *)get_cpu_var(hv_24x7_reqb);
1296
1297                 ret = add_event_to_24x7_request(event, request_buffer);
1298                 if (ret) {
1299                         __this_cpu_write(hv_24x7_txn_err, ret);
1300                 } else {
1301                         /*
1302                          * Associate the event with the HCALL request index,
1303                          * so ->commit_txn() can quickly find/update count.
1304                          */
1305                         i = request_buffer->num_requests - 1;
1306
1307                         h24x7hw = &get_cpu_var(hv_24x7_hw);
1308                         h24x7hw->events[i] = event;
1309                         put_cpu_var(h24x7hw);
1310                         /*
1311                          * Clear the event count so we can compute the _change_
1312                          * in the 24x7 raw counter value at the end of the txn.
1313                          *
1314                          * Note that we could alternatively read the 24x7 value
1315                          * now and save its value in event->hw.prev_count. But
1316                          * that would require issuing a hcall, which would then
1317                          * defeat the purpose of using the txn interface.
1318                          */
1319                         local64_set(&event->count, 0);
1320                 }
1321
1322                 put_cpu_var(hv_24x7_reqb);
1323         } else {
1324                 now = h_24x7_get_value(event);
1325                 update_event_count(event, now);
1326         }
1327 }
1328
1329 static void h_24x7_event_start(struct perf_event *event, int flags)
1330 {
1331         if (flags & PERF_EF_RELOAD)
1332                 local64_set(&event->hw.prev_count, h_24x7_get_value(event));
1333 }
1334
1335 static void h_24x7_event_stop(struct perf_event *event, int flags)
1336 {
1337         h_24x7_event_read(event);
1338 }
1339
1340 static int h_24x7_event_add(struct perf_event *event, int flags)
1341 {
1342         if (flags & PERF_EF_START)
1343                 h_24x7_event_start(event, flags);
1344
1345         return 0;
1346 }
1347
1348 /*
1349  * 24x7 counters only support READ transactions. They are
1350  * always counting and dont need/support ADD transactions.
1351  * Cache the flags, but otherwise ignore transactions that
1352  * are not PERF_PMU_TXN_READ.
1353  */
1354 static void h_24x7_event_start_txn(struct pmu *pmu, unsigned int flags)
1355 {
1356         struct hv_24x7_request_buffer *request_buffer;
1357         struct hv_24x7_data_result_buffer *result_buffer;
1358
1359         /* We should not be called if we are already in a txn */
1360         WARN_ON_ONCE(__this_cpu_read(hv_24x7_txn_flags));
1361
1362         __this_cpu_write(hv_24x7_txn_flags, flags);
1363         if (flags & ~PERF_PMU_TXN_READ)
1364                 return;
1365
1366         request_buffer = (void *)get_cpu_var(hv_24x7_reqb);
1367         result_buffer = (void *)get_cpu_var(hv_24x7_resb);
1368
1369         init_24x7_request(request_buffer, result_buffer);
1370
1371         put_cpu_var(hv_24x7_resb);
1372         put_cpu_var(hv_24x7_reqb);
1373 }
1374
1375 /*
1376  * Clean up transaction state.
1377  *
1378  * NOTE: Ignore state of request and result buffers for now.
1379  *       We will initialize them during the next read/txn.
1380  */
1381 static void reset_txn(void)
1382 {
1383         __this_cpu_write(hv_24x7_txn_flags, 0);
1384         __this_cpu_write(hv_24x7_txn_err, 0);
1385 }
1386
1387 /*
1388  * 24x7 counters only support READ transactions. They are always counting
1389  * and dont need/support ADD transactions. Clear ->txn_flags but otherwise
1390  * ignore transactions that are not of type PERF_PMU_TXN_READ.
1391  *
1392  * For READ transactions, submit all pending 24x7 requests (i.e requests
1393  * that were queued by h_24x7_event_read()), to the hypervisor and update
1394  * the event counts.
1395  */
1396 static int h_24x7_event_commit_txn(struct pmu *pmu)
1397 {
1398         struct hv_24x7_request_buffer *request_buffer;
1399         struct hv_24x7_data_result_buffer *result_buffer;
1400         struct hv_24x7_result *res, *next_res;
1401         u64 count;
1402         int i, ret, txn_flags;
1403         struct hv_24x7_hw *h24x7hw;
1404
1405         txn_flags = __this_cpu_read(hv_24x7_txn_flags);
1406         WARN_ON_ONCE(!txn_flags);
1407
1408         ret = 0;
1409         if (txn_flags & ~PERF_PMU_TXN_READ)
1410                 goto out;
1411
1412         ret = __this_cpu_read(hv_24x7_txn_err);
1413         if (ret)
1414                 goto out;
1415
1416         request_buffer = (void *)get_cpu_var(hv_24x7_reqb);
1417         result_buffer = (void *)get_cpu_var(hv_24x7_resb);
1418
1419         ret = make_24x7_request(request_buffer, result_buffer);
1420         if (ret)
1421                 goto put_reqb;
1422
1423         h24x7hw = &get_cpu_var(hv_24x7_hw);
1424
1425         /* Go through results in the result buffer to update event counts. */
1426         for (i = 0, res = result_buffer->results;
1427              i < result_buffer->num_results; i++, res = next_res) {
1428                 struct perf_event *event = h24x7hw->events[res->result_ix];
1429                 u16 num_elements = be16_to_cpu(res->num_elements_returned);
1430                 u16 data_size = be16_to_cpu(res->result_element_data_size);
1431
1432                 /* This code assumes that a result has only one element. */
1433                 WARN_ON_ONCE(num_elements != 1);
1434
1435                 count = be64_to_cpu(res->elements[0].element_data[0]);
1436                 update_event_count(event, count);
1437
1438                 next_res = (void *) res->elements[0].element_data + data_size;
1439         }
1440
1441         put_cpu_var(hv_24x7_hw);
1442
1443 put_reqb:
1444         put_cpu_var(hv_24x7_resb);
1445         put_cpu_var(hv_24x7_reqb);
1446 out:
1447         reset_txn();
1448         return ret;
1449 }
1450
1451 /*
1452  * 24x7 counters only support READ transactions. They are always counting
1453  * and dont need/support ADD transactions. However, regardless of type
1454  * of transaction, all we need to do is cleanup, so we don't have to check
1455  * the type of transaction.
1456  */
1457 static void h_24x7_event_cancel_txn(struct pmu *pmu)
1458 {
1459         WARN_ON_ONCE(!__this_cpu_read(hv_24x7_txn_flags));
1460         reset_txn();
1461 }
1462
1463 static struct pmu h_24x7_pmu = {
1464         .task_ctx_nr = perf_invalid_context,
1465
1466         .name = "hv_24x7",
1467         .attr_groups = attr_groups,
1468         .event_init  = h_24x7_event_init,
1469         .add         = h_24x7_event_add,
1470         .del         = h_24x7_event_stop,
1471         .start       = h_24x7_event_start,
1472         .stop        = h_24x7_event_stop,
1473         .read        = h_24x7_event_read,
1474         .start_txn   = h_24x7_event_start_txn,
1475         .commit_txn  = h_24x7_event_commit_txn,
1476         .cancel_txn  = h_24x7_event_cancel_txn,
1477 };
1478
1479 static int hv_24x7_init(void)
1480 {
1481         int r;
1482         unsigned long hret;
1483         struct hv_perf_caps caps;
1484
1485         if (!firmware_has_feature(FW_FEATURE_LPAR)) {
1486                 pr_debug("not a virtualized system, not enabling\n");
1487                 return -ENODEV;
1488         }
1489
1490         hret = hv_perf_caps_get(&caps);
1491         if (hret) {
1492                 pr_debug("could not obtain capabilities, not enabling, rc=%ld\n",
1493                                 hret);
1494                 return -ENODEV;
1495         }
1496
1497         hv_page_cache = kmem_cache_create("hv-page-4096", 4096, 4096, 0, NULL);
1498         if (!hv_page_cache)
1499                 return -ENOMEM;
1500
1501         /* sampling not supported */
1502         h_24x7_pmu.capabilities |= PERF_PMU_CAP_NO_INTERRUPT;
1503
1504         r = create_events_from_catalog(&event_group.attrs,
1505                                    &event_desc_group.attrs,
1506                                    &event_long_desc_group.attrs);
1507
1508         if (r)
1509                 return r;
1510
1511         r = perf_pmu_register(&h_24x7_pmu, h_24x7_pmu.name, -1);
1512         if (r)
1513                 return r;
1514
1515         return 0;
1516 }
1517
1518 device_initcall(hv_24x7_init);