linux/kernel/trace/trace_events_hist.c
<<
>>
Prefs
   1// SPDX-License-Identifier: GPL-2.0
   2/*
   3 * trace_events_hist - trace event hist triggers
   4 *
   5 * Copyright (C) 2015 Tom Zanussi <tom.zanussi@linux.intel.com>
   6 */
   7
   8#include <linux/module.h>
   9#include <linux/kallsyms.h>
  10#include <linux/security.h>
  11#include <linux/mutex.h>
  12#include <linux/slab.h>
  13#include <linux/stacktrace.h>
  14#include <linux/rculist.h>
  15#include <linux/tracefs.h>
  16
  17/* for gfp flag names */
  18#include <linux/trace_events.h>
  19#include <trace/events/mmflags.h>
  20
  21#include "tracing_map.h"
  22#include "trace.h"
  23#include "trace_dynevent.h"
  24
  25#define SYNTH_SYSTEM            "synthetic"
  26#define SYNTH_FIELDS_MAX        32
  27
  28#define STR_VAR_LEN_MAX         32 /* must be multiple of sizeof(u64) */
  29
  30#define ERRORS                                                          \
  31        C(NONE,                 "No error"),                            \
  32        C(DUPLICATE_VAR,        "Variable already defined"),            \
  33        C(VAR_NOT_UNIQUE,       "Variable name not unique, need to use fully qualified name (subsys.event.var) for variable"), \
  34        C(TOO_MANY_VARS,        "Too many variables defined"),          \
  35        C(MALFORMED_ASSIGNMENT, "Malformed assignment"),                \
  36        C(NAMED_MISMATCH,       "Named hist trigger doesn't match existing named trigger (includes variables)"), \
  37        C(TRIGGER_EEXIST,       "Hist trigger already exists"),         \
  38        C(TRIGGER_ENOENT_CLEAR, "Can't clear or continue a nonexistent hist trigger"), \
  39        C(SET_CLOCK_FAIL,       "Couldn't set trace_clock"),            \
  40        C(BAD_FIELD_MODIFIER,   "Invalid field modifier"),              \
  41        C(TOO_MANY_SUBEXPR,     "Too many subexpressions (3 max)"),     \
  42        C(TIMESTAMP_MISMATCH,   "Timestamp units in expression don't match"), \
  43        C(TOO_MANY_FIELD_VARS,  "Too many field variables defined"),    \
  44        C(EVENT_FILE_NOT_FOUND, "Event file not found"),                \
  45        C(HIST_NOT_FOUND,       "Matching event histogram not found"),  \
  46        C(HIST_CREATE_FAIL,     "Couldn't create histogram for field"), \
  47        C(SYNTH_VAR_NOT_FOUND,  "Couldn't find synthetic variable"),    \
  48        C(SYNTH_EVENT_NOT_FOUND,"Couldn't find synthetic event"),       \
  49        C(SYNTH_TYPE_MISMATCH,  "Param type doesn't match synthetic event field type"), \
  50        C(SYNTH_COUNT_MISMATCH, "Param count doesn't match synthetic event field count"), \
  51        C(FIELD_VAR_PARSE_FAIL, "Couldn't parse field variable"),       \
  52        C(VAR_CREATE_FIND_FAIL, "Couldn't create or find variable"),    \
  53        C(ONX_NOT_VAR,          "For onmax(x) or onchange(x), x must be a variable"), \
  54        C(ONX_VAR_NOT_FOUND,    "Couldn't find onmax or onchange variable"), \
  55        C(ONX_VAR_CREATE_FAIL,  "Couldn't create onmax or onchange variable"), \
  56        C(FIELD_VAR_CREATE_FAIL,"Couldn't create field variable"),      \
  57        C(TOO_MANY_PARAMS,      "Too many action params"),              \
  58        C(PARAM_NOT_FOUND,      "Couldn't find param"),                 \
  59        C(INVALID_PARAM,        "Invalid action param"),                \
  60        C(ACTION_NOT_FOUND,     "No action found"),                     \
  61        C(NO_SAVE_PARAMS,       "No params found for save()"),          \
  62        C(TOO_MANY_SAVE_ACTIONS,"Can't have more than one save() action per hist"), \
  63        C(ACTION_MISMATCH,      "Handler doesn't support action"),      \
  64        C(NO_CLOSING_PAREN,     "No closing paren found"),              \
  65        C(SUBSYS_NOT_FOUND,     "Missing subsystem"),                   \
  66        C(INVALID_SUBSYS_EVENT, "Invalid subsystem or event name"),     \
  67        C(INVALID_REF_KEY,      "Using variable references in keys not supported"), \
  68        C(VAR_NOT_FOUND,        "Couldn't find variable"),              \
  69        C(FIELD_NOT_FOUND,      "Couldn't find field"),
  70
  71#undef C
  72#define C(a, b)         HIST_ERR_##a
  73
  74enum { ERRORS };
  75
  76#undef C
  77#define C(a, b)         b
  78
  79static const char *err_text[] = { ERRORS };
  80
  81struct hist_field;
  82
  83typedef u64 (*hist_field_fn_t) (struct hist_field *field,
  84                                struct tracing_map_elt *elt,
  85                                struct ring_buffer_event *rbe,
  86                                void *event);
  87
  88#define HIST_FIELD_OPERANDS_MAX 2
  89#define HIST_FIELDS_MAX         (TRACING_MAP_FIELDS_MAX + TRACING_MAP_VARS_MAX)
  90#define HIST_ACTIONS_MAX        8
  91
  92enum field_op_id {
  93        FIELD_OP_NONE,
  94        FIELD_OP_PLUS,
  95        FIELD_OP_MINUS,
  96        FIELD_OP_UNARY_MINUS,
  97};
  98
  99/*
 100 * A hist_var (histogram variable) contains variable information for
 101 * hist_fields having the HIST_FIELD_FL_VAR or HIST_FIELD_FL_VAR_REF
 102 * flag set.  A hist_var has a variable name e.g. ts0, and is
 103 * associated with a given histogram trigger, as specified by
 104 * hist_data.  The hist_var idx is the unique index assigned to the
 105 * variable by the hist trigger's tracing_map.  The idx is what is
 106 * used to set a variable's value and, by a variable reference, to
 107 * retrieve it.
 108 */
 109struct hist_var {
 110        char                            *name;
 111        struct hist_trigger_data        *hist_data;
 112        unsigned int                    idx;
 113};
 114
 115struct hist_field {
 116        struct ftrace_event_field       *field;
 117        unsigned long                   flags;
 118        hist_field_fn_t                 fn;
 119        unsigned int                    ref;
 120        unsigned int                    size;
 121        unsigned int                    offset;
 122        unsigned int                    is_signed;
 123        const char                      *type;
 124        struct hist_field               *operands[HIST_FIELD_OPERANDS_MAX];
 125        struct hist_trigger_data        *hist_data;
 126
 127        /*
 128         * Variable fields contain variable-specific info in var.
 129         */
 130        struct hist_var                 var;
 131        enum field_op_id                operator;
 132        char                            *system;
 133        char                            *event_name;
 134
 135        /*
 136         * The name field is used for EXPR and VAR_REF fields.  VAR
 137         * fields contain the variable name in var.name.
 138         */
 139        char                            *name;
 140
 141        /*
 142         * When a histogram trigger is hit, if it has any references
 143         * to variables, the values of those variables are collected
 144         * into a var_ref_vals array by resolve_var_refs().  The
 145         * current value of each variable is read from the tracing_map
 146         * using the hist field's hist_var.idx and entered into the
 147         * var_ref_idx entry i.e. var_ref_vals[var_ref_idx].
 148         */
 149        unsigned int                    var_ref_idx;
 150        bool                            read_once;
 151};
 152
 153static u64 hist_field_none(struct hist_field *field,
 154                           struct tracing_map_elt *elt,
 155                           struct ring_buffer_event *rbe,
 156                           void *event)
 157{
 158        return 0;
 159}
 160
 161static u64 hist_field_counter(struct hist_field *field,
 162                              struct tracing_map_elt *elt,
 163                              struct ring_buffer_event *rbe,
 164                              void *event)
 165{
 166        return 1;
 167}
 168
 169static u64 hist_field_string(struct hist_field *hist_field,
 170                             struct tracing_map_elt *elt,
 171                             struct ring_buffer_event *rbe,
 172                             void *event)
 173{
 174        char *addr = (char *)(event + hist_field->field->offset);
 175
 176        return (u64)(unsigned long)addr;
 177}
 178
 179static u64 hist_field_dynstring(struct hist_field *hist_field,
 180                                struct tracing_map_elt *elt,
 181                                struct ring_buffer_event *rbe,
 182                                void *event)
 183{
 184        u32 str_item = *(u32 *)(event + hist_field->field->offset);
 185        int str_loc = str_item & 0xffff;
 186        char *addr = (char *)(event + str_loc);
 187
 188        return (u64)(unsigned long)addr;
 189}
 190
 191static u64 hist_field_pstring(struct hist_field *hist_field,
 192                              struct tracing_map_elt *elt,
 193                              struct ring_buffer_event *rbe,
 194                              void *event)
 195{
 196        char **addr = (char **)(event + hist_field->field->offset);
 197
 198        return (u64)(unsigned long)*addr;
 199}
 200
 201static u64 hist_field_log2(struct hist_field *hist_field,
 202                           struct tracing_map_elt *elt,
 203                           struct ring_buffer_event *rbe,
 204                           void *event)
 205{
 206        struct hist_field *operand = hist_field->operands[0];
 207
 208        u64 val = operand->fn(operand, elt, rbe, event);
 209
 210        return (u64) ilog2(roundup_pow_of_two(val));
 211}
 212
 213static u64 hist_field_plus(struct hist_field *hist_field,
 214                           struct tracing_map_elt *elt,
 215                           struct ring_buffer_event *rbe,
 216                           void *event)
 217{
 218        struct hist_field *operand1 = hist_field->operands[0];
 219        struct hist_field *operand2 = hist_field->operands[1];
 220
 221        u64 val1 = operand1->fn(operand1, elt, rbe, event);
 222        u64 val2 = operand2->fn(operand2, elt, rbe, event);
 223
 224        return val1 + val2;
 225}
 226
 227static u64 hist_field_minus(struct hist_field *hist_field,
 228                            struct tracing_map_elt *elt,
 229                            struct ring_buffer_event *rbe,
 230                            void *event)
 231{
 232        struct hist_field *operand1 = hist_field->operands[0];
 233        struct hist_field *operand2 = hist_field->operands[1];
 234
 235        u64 val1 = operand1->fn(operand1, elt, rbe, event);
 236        u64 val2 = operand2->fn(operand2, elt, rbe, event);
 237
 238        return val1 - val2;
 239}
 240
 241static u64 hist_field_unary_minus(struct hist_field *hist_field,
 242                                  struct tracing_map_elt *elt,
 243                                  struct ring_buffer_event *rbe,
 244                                  void *event)
 245{
 246        struct hist_field *operand = hist_field->operands[0];
 247
 248        s64 sval = (s64)operand->fn(operand, elt, rbe, event);
 249        u64 val = (u64)-sval;
 250
 251        return val;
 252}
 253
 254#define DEFINE_HIST_FIELD_FN(type)                                      \
 255        static u64 hist_field_##type(struct hist_field *hist_field,     \
 256                                     struct tracing_map_elt *elt,       \
 257                                     struct ring_buffer_event *rbe,     \
 258                                     void *event)                       \
 259{                                                                       \
 260        type *addr = (type *)(event + hist_field->field->offset);       \
 261                                                                        \
 262        return (u64)(unsigned long)*addr;                               \
 263}
 264
 265DEFINE_HIST_FIELD_FN(s64);
 266DEFINE_HIST_FIELD_FN(u64);
 267DEFINE_HIST_FIELD_FN(s32);
 268DEFINE_HIST_FIELD_FN(u32);
 269DEFINE_HIST_FIELD_FN(s16);
 270DEFINE_HIST_FIELD_FN(u16);
 271DEFINE_HIST_FIELD_FN(s8);
 272DEFINE_HIST_FIELD_FN(u8);
 273
 274#define for_each_hist_field(i, hist_data)       \
 275        for ((i) = 0; (i) < (hist_data)->n_fields; (i)++)
 276
 277#define for_each_hist_val_field(i, hist_data)   \
 278        for ((i) = 0; (i) < (hist_data)->n_vals; (i)++)
 279
 280#define for_each_hist_key_field(i, hist_data)   \
 281        for ((i) = (hist_data)->n_vals; (i) < (hist_data)->n_fields; (i)++)
 282
 283#define HIST_STACKTRACE_DEPTH   16
 284#define HIST_STACKTRACE_SIZE    (HIST_STACKTRACE_DEPTH * sizeof(unsigned long))
 285#define HIST_STACKTRACE_SKIP    5
 286
 287#define HITCOUNT_IDX            0
 288#define HIST_KEY_SIZE_MAX       (MAX_FILTER_STR_VAL + HIST_STACKTRACE_SIZE)
 289
 290enum hist_field_flags {
 291        HIST_FIELD_FL_HITCOUNT          = 1 << 0,
 292        HIST_FIELD_FL_KEY               = 1 << 1,
 293        HIST_FIELD_FL_STRING            = 1 << 2,
 294        HIST_FIELD_FL_HEX               = 1 << 3,
 295        HIST_FIELD_FL_SYM               = 1 << 4,
 296        HIST_FIELD_FL_SYM_OFFSET        = 1 << 5,
 297        HIST_FIELD_FL_EXECNAME          = 1 << 6,
 298        HIST_FIELD_FL_SYSCALL           = 1 << 7,
 299        HIST_FIELD_FL_STACKTRACE        = 1 << 8,
 300        HIST_FIELD_FL_LOG2              = 1 << 9,
 301        HIST_FIELD_FL_TIMESTAMP         = 1 << 10,
 302        HIST_FIELD_FL_TIMESTAMP_USECS   = 1 << 11,
 303        HIST_FIELD_FL_VAR               = 1 << 12,
 304        HIST_FIELD_FL_EXPR              = 1 << 13,
 305        HIST_FIELD_FL_VAR_REF           = 1 << 14,
 306        HIST_FIELD_FL_CPU               = 1 << 15,
 307        HIST_FIELD_FL_ALIAS             = 1 << 16,
 308};
 309
 310struct var_defs {
 311        unsigned int    n_vars;
 312        char            *name[TRACING_MAP_VARS_MAX];
 313        char            *expr[TRACING_MAP_VARS_MAX];
 314};
 315
 316struct hist_trigger_attrs {
 317        char            *keys_str;
 318        char            *vals_str;
 319        char            *sort_key_str;
 320        char            *name;
 321        char            *clock;
 322        bool            pause;
 323        bool            cont;
 324        bool            clear;
 325        bool            ts_in_usecs;
 326        unsigned int    map_bits;
 327
 328        char            *assignment_str[TRACING_MAP_VARS_MAX];
 329        unsigned int    n_assignments;
 330
 331        char            *action_str[HIST_ACTIONS_MAX];
 332        unsigned int    n_actions;
 333
 334        struct var_defs var_defs;
 335};
 336
 337struct field_var {
 338        struct hist_field       *var;
 339        struct hist_field       *val;
 340};
 341
 342struct field_var_hist {
 343        struct hist_trigger_data        *hist_data;
 344        char                            *cmd;
 345};
 346
 347struct hist_trigger_data {
 348        struct hist_field               *fields[HIST_FIELDS_MAX];
 349        unsigned int                    n_vals;
 350        unsigned int                    n_keys;
 351        unsigned int                    n_fields;
 352        unsigned int                    n_vars;
 353        unsigned int                    key_size;
 354        struct tracing_map_sort_key     sort_keys[TRACING_MAP_SORT_KEYS_MAX];
 355        unsigned int                    n_sort_keys;
 356        struct trace_event_file         *event_file;
 357        struct hist_trigger_attrs       *attrs;
 358        struct tracing_map              *map;
 359        bool                            enable_timestamps;
 360        bool                            remove;
 361        struct hist_field               *var_refs[TRACING_MAP_VARS_MAX];
 362        unsigned int                    n_var_refs;
 363
 364        struct action_data              *actions[HIST_ACTIONS_MAX];
 365        unsigned int                    n_actions;
 366
 367        struct field_var                *field_vars[SYNTH_FIELDS_MAX];
 368        unsigned int                    n_field_vars;
 369        unsigned int                    n_field_var_str;
 370        struct field_var_hist           *field_var_hists[SYNTH_FIELDS_MAX];
 371        unsigned int                    n_field_var_hists;
 372
 373        struct field_var                *save_vars[SYNTH_FIELDS_MAX];
 374        unsigned int                    n_save_vars;
 375        unsigned int                    n_save_var_str;
 376};
 377
 378static int synth_event_create(int argc, const char **argv);
 379static int synth_event_show(struct seq_file *m, struct dyn_event *ev);
 380static int synth_event_release(struct dyn_event *ev);
 381static bool synth_event_is_busy(struct dyn_event *ev);
 382static bool synth_event_match(const char *system, const char *event,
 383                        int argc, const char **argv, struct dyn_event *ev);
 384
 385static struct dyn_event_operations synth_event_ops = {
 386        .create = synth_event_create,
 387        .show = synth_event_show,
 388        .is_busy = synth_event_is_busy,
 389        .free = synth_event_release,
 390        .match = synth_event_match,
 391};
 392
 393struct synth_field {
 394        char *type;
 395        char *name;
 396        size_t size;
 397        bool is_signed;
 398        bool is_string;
 399};
 400
 401struct synth_event {
 402        struct dyn_event                        devent;
 403        int                                     ref;
 404        char                                    *name;
 405        struct synth_field                      **fields;
 406        unsigned int                            n_fields;
 407        unsigned int                            n_u64;
 408        struct trace_event_class                class;
 409        struct trace_event_call                 call;
 410        struct tracepoint                       *tp;
 411};
 412
 413static bool is_synth_event(struct dyn_event *ev)
 414{
 415        return ev->ops == &synth_event_ops;
 416}
 417
 418static struct synth_event *to_synth_event(struct dyn_event *ev)
 419{
 420        return container_of(ev, struct synth_event, devent);
 421}
 422
 423static bool synth_event_is_busy(struct dyn_event *ev)
 424{
 425        struct synth_event *event = to_synth_event(ev);
 426
 427        return event->ref != 0;
 428}
 429
 430static bool synth_event_match(const char *system, const char *event,
 431                        int argc, const char **argv, struct dyn_event *ev)
 432{
 433        struct synth_event *sev = to_synth_event(ev);
 434
 435        return strcmp(sev->name, event) == 0 &&
 436                (!system || strcmp(system, SYNTH_SYSTEM) == 0);
 437}
 438
 439struct action_data;
 440
 441typedef void (*action_fn_t) (struct hist_trigger_data *hist_data,
 442                             struct tracing_map_elt *elt, void *rec,
 443                             struct ring_buffer_event *rbe, void *key,
 444                             struct action_data *data, u64 *var_ref_vals);
 445
 446typedef bool (*check_track_val_fn_t) (u64 track_val, u64 var_val);
 447
 448enum handler_id {
 449        HANDLER_ONMATCH = 1,
 450        HANDLER_ONMAX,
 451        HANDLER_ONCHANGE,
 452};
 453
 454enum action_id {
 455        ACTION_SAVE = 1,
 456        ACTION_TRACE,
 457        ACTION_SNAPSHOT,
 458};
 459
 460struct action_data {
 461        enum handler_id         handler;
 462        enum action_id          action;
 463        char                    *action_name;
 464        action_fn_t             fn;
 465
 466        unsigned int            n_params;
 467        char                    *params[SYNTH_FIELDS_MAX];
 468
 469        /*
 470         * When a histogram trigger is hit, the values of any
 471         * references to variables, including variables being passed
 472         * as parameters to synthetic events, are collected into a
 473         * var_ref_vals array.  This var_ref_idx is the index of the
 474         * first param in the array to be passed to the synthetic
 475         * event invocation.
 476         */
 477        unsigned int            var_ref_idx;
 478        struct synth_event      *synth_event;
 479        bool                    use_trace_keyword;
 480        char                    *synth_event_name;
 481
 482        union {
 483                struct {
 484                        char                    *event;
 485                        char                    *event_system;
 486                } match_data;
 487
 488                struct {
 489                        /*
 490                         * var_str contains the $-unstripped variable
 491                         * name referenced by var_ref, and used when
 492                         * printing the action.  Because var_ref
 493                         * creation is deferred to create_actions(),
 494                         * we need a per-action way to save it until
 495                         * then, thus var_str.
 496                         */
 497                        char                    *var_str;
 498
 499                        /*
 500                         * var_ref refers to the variable being
 501                         * tracked e.g onmax($var).
 502                         */
 503                        struct hist_field       *var_ref;
 504
 505                        /*
 506                         * track_var contains the 'invisible' tracking
 507                         * variable created to keep the current
 508                         * e.g. max value.
 509                         */
 510                        struct hist_field       *track_var;
 511
 512                        check_track_val_fn_t    check_val;
 513                        action_fn_t             save_data;
 514                } track_data;
 515        };
 516};
 517
 518struct track_data {
 519        u64                             track_val;
 520        bool                            updated;
 521
 522        unsigned int                    key_len;
 523        void                            *key;
 524        struct tracing_map_elt          elt;
 525
 526        struct action_data              *action_data;
 527        struct hist_trigger_data        *hist_data;
 528};
 529
 530struct hist_elt_data {
 531        char *comm;
 532        u64 *var_ref_vals;
 533        char *field_var_str[SYNTH_FIELDS_MAX];
 534};
 535
 536struct snapshot_context {
 537        struct tracing_map_elt  *elt;
 538        void                    *key;
 539};
 540
 541static void track_data_free(struct track_data *track_data)
 542{
 543        struct hist_elt_data *elt_data;
 544
 545        if (!track_data)
 546                return;
 547
 548        kfree(track_data->key);
 549
 550        elt_data = track_data->elt.private_data;
 551        if (elt_data) {
 552                kfree(elt_data->comm);
 553                kfree(elt_data);
 554        }
 555
 556        kfree(track_data);
 557}
 558
 559static struct track_data *track_data_alloc(unsigned int key_len,
 560                                           struct action_data *action_data,
 561                                           struct hist_trigger_data *hist_data)
 562{
 563        struct track_data *data = kzalloc(sizeof(*data), GFP_KERNEL);
 564        struct hist_elt_data *elt_data;
 565
 566        if (!data)
 567                return ERR_PTR(-ENOMEM);
 568
 569        data->key = kzalloc(key_len, GFP_KERNEL);
 570        if (!data->key) {
 571                track_data_free(data);
 572                return ERR_PTR(-ENOMEM);
 573        }
 574
 575        data->key_len = key_len;
 576        data->action_data = action_data;
 577        data->hist_data = hist_data;
 578
 579        elt_data = kzalloc(sizeof(*elt_data), GFP_KERNEL);
 580        if (!elt_data) {
 581                track_data_free(data);
 582                return ERR_PTR(-ENOMEM);
 583        }
 584        data->elt.private_data = elt_data;
 585
 586        elt_data->comm = kzalloc(TASK_COMM_LEN, GFP_KERNEL);
 587        if (!elt_data->comm) {
 588                track_data_free(data);
 589                return ERR_PTR(-ENOMEM);
 590        }
 591
 592        return data;
 593}
 594
 595static char last_cmd[MAX_FILTER_STR_VAL];
 596static char last_cmd_loc[MAX_FILTER_STR_VAL];
 597
 598static int errpos(char *str)
 599{
 600        return err_pos(last_cmd, str);
 601}
 602
 603static void last_cmd_set(struct trace_event_file *file, char *str)
 604{
 605        const char *system = NULL, *name = NULL;
 606        struct trace_event_call *call;
 607
 608        if (!str)
 609                return;
 610
 611        strncpy(last_cmd, str, MAX_FILTER_STR_VAL - 1);
 612
 613        if (file) {
 614                call = file->event_call;
 615
 616                system = call->class->system;
 617                if (system) {
 618                        name = trace_event_name(call);
 619                        if (!name)
 620                                system = NULL;
 621                }
 622        }
 623
 624        if (system)
 625                snprintf(last_cmd_loc, MAX_FILTER_STR_VAL, "hist:%s:%s", system, name);
 626}
 627
 628static void hist_err(struct trace_array *tr, u8 err_type, u8 err_pos)
 629{
 630        tracing_log_err(tr, last_cmd_loc, last_cmd, err_text,
 631                        err_type, err_pos);
 632}
 633
 634static void hist_err_clear(void)
 635{
 636        last_cmd[0] = '\0';
 637        last_cmd_loc[0] = '\0';
 638}
 639
 640struct synth_trace_event {
 641        struct trace_entry      ent;
 642        u64                     fields[];
 643};
 644
 645static int synth_event_define_fields(struct trace_event_call *call)
 646{
 647        struct synth_trace_event trace;
 648        int offset = offsetof(typeof(trace), fields);
 649        struct synth_event *event = call->data;
 650        unsigned int i, size, n_u64;
 651        char *name, *type;
 652        bool is_signed;
 653        int ret = 0;
 654
 655        for (i = 0, n_u64 = 0; i < event->n_fields; i++) {
 656                size = event->fields[i]->size;
 657                is_signed = event->fields[i]->is_signed;
 658                type = event->fields[i]->type;
 659                name = event->fields[i]->name;
 660                ret = trace_define_field(call, type, name, offset, size,
 661                                         is_signed, FILTER_OTHER);
 662                if (ret)
 663                        break;
 664
 665                if (event->fields[i]->is_string) {
 666                        offset += STR_VAR_LEN_MAX;
 667                        n_u64 += STR_VAR_LEN_MAX / sizeof(u64);
 668                } else {
 669                        offset += sizeof(u64);
 670                        n_u64++;
 671                }
 672        }
 673
 674        event->n_u64 = n_u64;
 675
 676        return ret;
 677}
 678
 679static bool synth_field_signed(char *type)
 680{
 681        if (str_has_prefix(type, "u"))
 682                return false;
 683        if (strcmp(type, "gfp_t") == 0)
 684                return false;
 685
 686        return true;
 687}
 688
 689static int synth_field_is_string(char *type)
 690{
 691        if (strstr(type, "char[") != NULL)
 692                return true;
 693
 694        return false;
 695}
 696
 697static int synth_field_string_size(char *type)
 698{
 699        char buf[4], *end, *start;
 700        unsigned int len;
 701        int size, err;
 702
 703        start = strstr(type, "char[");
 704        if (start == NULL)
 705                return -EINVAL;
 706        start += sizeof("char[") - 1;
 707
 708        end = strchr(type, ']');
 709        if (!end || end < start)
 710                return -EINVAL;
 711
 712        len = end - start;
 713        if (len > 3)
 714                return -EINVAL;
 715
 716        strncpy(buf, start, len);
 717        buf[len] = '\0';
 718
 719        err = kstrtouint(buf, 0, &size);
 720        if (err)
 721                return err;
 722
 723        if (size > STR_VAR_LEN_MAX)
 724                return -EINVAL;
 725
 726        return size;
 727}
 728
 729static int synth_field_size(char *type)
 730{
 731        int size = 0;
 732
 733        if (strcmp(type, "s64") == 0)
 734                size = sizeof(s64);
 735        else if (strcmp(type, "u64") == 0)
 736                size = sizeof(u64);
 737        else if (strcmp(type, "s32") == 0)
 738                size = sizeof(s32);
 739        else if (strcmp(type, "u32") == 0)
 740                size = sizeof(u32);
 741        else if (strcmp(type, "s16") == 0)
 742                size = sizeof(s16);
 743        else if (strcmp(type, "u16") == 0)
 744                size = sizeof(u16);
 745        else if (strcmp(type, "s8") == 0)
 746                size = sizeof(s8);
 747        else if (strcmp(type, "u8") == 0)
 748                size = sizeof(u8);
 749        else if (strcmp(type, "char") == 0)
 750                size = sizeof(char);
 751        else if (strcmp(type, "unsigned char") == 0)
 752                size = sizeof(unsigned char);
 753        else if (strcmp(type, "int") == 0)
 754                size = sizeof(int);
 755        else if (strcmp(type, "unsigned int") == 0)
 756                size = sizeof(unsigned int);
 757        else if (strcmp(type, "long") == 0)
 758                size = sizeof(long);
 759        else if (strcmp(type, "unsigned long") == 0)
 760                size = sizeof(unsigned long);
 761        else if (strcmp(type, "pid_t") == 0)
 762                size = sizeof(pid_t);
 763        else if (strcmp(type, "gfp_t") == 0)
 764                size = sizeof(gfp_t);
 765        else if (synth_field_is_string(type))
 766                size = synth_field_string_size(type);
 767
 768        return size;
 769}
 770
 771static const char *synth_field_fmt(char *type)
 772{
 773        const char *fmt = "%llu";
 774
 775        if (strcmp(type, "s64") == 0)
 776                fmt = "%lld";
 777        else if (strcmp(type, "u64") == 0)
 778                fmt = "%llu";
 779        else if (strcmp(type, "s32") == 0)
 780                fmt = "%d";
 781        else if (strcmp(type, "u32") == 0)
 782                fmt = "%u";
 783        else if (strcmp(type, "s16") == 0)
 784                fmt = "%d";
 785        else if (strcmp(type, "u16") == 0)
 786                fmt = "%u";
 787        else if (strcmp(type, "s8") == 0)
 788                fmt = "%d";
 789        else if (strcmp(type, "u8") == 0)
 790                fmt = "%u";
 791        else if (strcmp(type, "char") == 0)
 792                fmt = "%d";
 793        else if (strcmp(type, "unsigned char") == 0)
 794                fmt = "%u";
 795        else if (strcmp(type, "int") == 0)
 796                fmt = "%d";
 797        else if (strcmp(type, "unsigned int") == 0)
 798                fmt = "%u";
 799        else if (strcmp(type, "long") == 0)
 800                fmt = "%ld";
 801        else if (strcmp(type, "unsigned long") == 0)
 802                fmt = "%lu";
 803        else if (strcmp(type, "pid_t") == 0)
 804                fmt = "%d";
 805        else if (strcmp(type, "gfp_t") == 0)
 806                fmt = "%x";
 807        else if (synth_field_is_string(type))
 808                fmt = "%s";
 809
 810        return fmt;
 811}
 812
 813static enum print_line_t print_synth_event(struct trace_iterator *iter,
 814                                           int flags,
 815                                           struct trace_event *event)
 816{
 817        struct trace_array *tr = iter->tr;
 818        struct trace_seq *s = &iter->seq;
 819        struct synth_trace_event *entry;
 820        struct synth_event *se;
 821        unsigned int i, n_u64;
 822        char print_fmt[32];
 823        const char *fmt;
 824
 825        entry = (struct synth_trace_event *)iter->ent;
 826        se = container_of(event, struct synth_event, call.event);
 827
 828        trace_seq_printf(s, "%s: ", se->name);
 829
 830        for (i = 0, n_u64 = 0; i < se->n_fields; i++) {
 831                if (trace_seq_has_overflowed(s))
 832                        goto end;
 833
 834                fmt = synth_field_fmt(se->fields[i]->type);
 835
 836                /* parameter types */
 837                if (tr->trace_flags & TRACE_ITER_VERBOSE)
 838                        trace_seq_printf(s, "%s ", fmt);
 839
 840                snprintf(print_fmt, sizeof(print_fmt), "%%s=%s%%s", fmt);
 841
 842                /* parameter values */
 843                if (se->fields[i]->is_string) {
 844                        trace_seq_printf(s, print_fmt, se->fields[i]->name,
 845                                         (char *)&entry->fields[n_u64],
 846                                         i == se->n_fields - 1 ? "" : " ");
 847                        n_u64 += STR_VAR_LEN_MAX / sizeof(u64);
 848                } else {
 849                        struct trace_print_flags __flags[] = {
 850                            __def_gfpflag_names, {-1, NULL} };
 851
 852                        trace_seq_printf(s, print_fmt, se->fields[i]->name,
 853                                         entry->fields[n_u64],
 854                                         i == se->n_fields - 1 ? "" : " ");
 855
 856                        if (strcmp(se->fields[i]->type, "gfp_t") == 0) {
 857                                trace_seq_puts(s, " (");
 858                                trace_print_flags_seq(s, "|",
 859                                                      entry->fields[n_u64],
 860                                                      __flags);
 861                                trace_seq_putc(s, ')');
 862                        }
 863                        n_u64++;
 864                }
 865        }
 866end:
 867        trace_seq_putc(s, '\n');
 868
 869        return trace_handle_return(s);
 870}
 871
 872static struct trace_event_functions synth_event_funcs = {
 873        .trace          = print_synth_event
 874};
 875
 876static notrace void trace_event_raw_event_synth(void *__data,
 877                                                u64 *var_ref_vals,
 878                                                unsigned int var_ref_idx)
 879{
 880        struct trace_event_file *trace_file = __data;
 881        struct synth_trace_event *entry;
 882        struct trace_event_buffer fbuffer;
 883        struct ring_buffer *buffer;
 884        struct synth_event *event;
 885        unsigned int i, n_u64;
 886        int fields_size = 0;
 887
 888        event = trace_file->event_call->data;
 889
 890        if (trace_trigger_soft_disabled(trace_file))
 891                return;
 892
 893        fields_size = event->n_u64 * sizeof(u64);
 894
 895        /*
 896         * Avoid ring buffer recursion detection, as this event
 897         * is being performed within another event.
 898         */
 899        buffer = trace_file->tr->trace_buffer.buffer;
 900        ring_buffer_nest_start(buffer);
 901
 902        entry = trace_event_buffer_reserve(&fbuffer, trace_file,
 903                                           sizeof(*entry) + fields_size);
 904        if (!entry)
 905                goto out;
 906
 907        for (i = 0, n_u64 = 0; i < event->n_fields; i++) {
 908                if (event->fields[i]->is_string) {
 909                        char *str_val = (char *)(long)var_ref_vals[var_ref_idx + i];
 910                        char *str_field = (char *)&entry->fields[n_u64];
 911
 912                        strscpy(str_field, str_val, STR_VAR_LEN_MAX);
 913                        n_u64 += STR_VAR_LEN_MAX / sizeof(u64);
 914                } else {
 915                        struct synth_field *field = event->fields[i];
 916                        u64 val = var_ref_vals[var_ref_idx + i];
 917
 918                        switch (field->size) {
 919                        case 1:
 920                                *(u8 *)&entry->fields[n_u64] = (u8)val;
 921                                break;
 922
 923                        case 2:
 924                                *(u16 *)&entry->fields[n_u64] = (u16)val;
 925                                break;
 926
 927                        case 4:
 928                                *(u32 *)&entry->fields[n_u64] = (u32)val;
 929                                break;
 930
 931                        default:
 932                                entry->fields[n_u64] = val;
 933                                break;
 934                        }
 935                        n_u64++;
 936                }
 937        }
 938
 939        trace_event_buffer_commit(&fbuffer);
 940out:
 941        ring_buffer_nest_end(buffer);
 942}
 943
 944static void free_synth_event_print_fmt(struct trace_event_call *call)
 945{
 946        if (call) {
 947                kfree(call->print_fmt);
 948                call->print_fmt = NULL;
 949        }
 950}
 951
 952static int __set_synth_event_print_fmt(struct synth_event *event,
 953                                       char *buf, int len)
 954{
 955        const char *fmt;
 956        int pos = 0;
 957        int i;
 958
 959        /* When len=0, we just calculate the needed length */
 960#define LEN_OR_ZERO (len ? len - pos : 0)
 961
 962        pos += snprintf(buf + pos, LEN_OR_ZERO, "\"");
 963        for (i = 0; i < event->n_fields; i++) {
 964                fmt = synth_field_fmt(event->fields[i]->type);
 965                pos += snprintf(buf + pos, LEN_OR_ZERO, "%s=%s%s",
 966                                event->fields[i]->name, fmt,
 967                                i == event->n_fields - 1 ? "" : ", ");
 968        }
 969        pos += snprintf(buf + pos, LEN_OR_ZERO, "\"");
 970
 971        for (i = 0; i < event->n_fields; i++) {
 972                pos += snprintf(buf + pos, LEN_OR_ZERO,
 973                                ", REC->%s", event->fields[i]->name);
 974        }
 975
 976#undef LEN_OR_ZERO
 977
 978        /* return the length of print_fmt */
 979        return pos;
 980}
 981
 982static int set_synth_event_print_fmt(struct trace_event_call *call)
 983{
 984        struct synth_event *event = call->data;
 985        char *print_fmt;
 986        int len;
 987
 988        /* First: called with 0 length to calculate the needed length */
 989        len = __set_synth_event_print_fmt(event, NULL, 0);
 990
 991        print_fmt = kmalloc(len + 1, GFP_KERNEL);
 992        if (!print_fmt)
 993                return -ENOMEM;
 994
 995        /* Second: actually write the @print_fmt */
 996        __set_synth_event_print_fmt(event, print_fmt, len + 1);
 997        call->print_fmt = print_fmt;
 998
 999        return 0;
1000}
1001
1002static void free_synth_field(struct synth_field *field)
1003{
1004        kfree(field->type);
1005        kfree(field->name);
1006        kfree(field);
1007}
1008
1009static struct synth_field *parse_synth_field(int argc, const char **argv,
1010                                             int *consumed)
1011{
1012        struct synth_field *field;
1013        const char *prefix = NULL, *field_type = argv[0], *field_name, *array;
1014        int len, ret = 0;
1015
1016        if (field_type[0] == ';')
1017                field_type++;
1018
1019        if (!strcmp(field_type, "unsigned")) {
1020                if (argc < 3)
1021                        return ERR_PTR(-EINVAL);
1022                prefix = "unsigned ";
1023                field_type = argv[1];
1024                field_name = argv[2];
1025                *consumed = 3;
1026        } else {
1027                field_name = argv[1];
1028                *consumed = 2;
1029        }
1030
1031        field = kzalloc(sizeof(*field), GFP_KERNEL);
1032        if (!field)
1033                return ERR_PTR(-ENOMEM);
1034
1035        len = strlen(field_name);
1036        array = strchr(field_name, '[');
1037        if (array)
1038                len -= strlen(array);
1039        else if (field_name[len - 1] == ';')
1040                len--;
1041
1042        field->name = kmemdup_nul(field_name, len, GFP_KERNEL);
1043        if (!field->name) {
1044                ret = -ENOMEM;
1045                goto free;
1046        }
1047
1048        if (field_type[0] == ';')
1049                field_type++;
1050        len = strlen(field_type) + 1;
1051        if (array)
1052                len += strlen(array);
1053        if (prefix)
1054                len += strlen(prefix);
1055
1056        field->type = kzalloc(len, GFP_KERNEL);
1057        if (!field->type) {
1058                ret = -ENOMEM;
1059                goto free;
1060        }
1061        if (prefix)
1062                strcat(field->type, prefix);
1063        strcat(field->type, field_type);
1064        if (array) {
1065                strcat(field->type, array);
1066                if (field->type[len - 1] == ';')
1067                        field->type[len - 1] = '\0';
1068        }
1069
1070        field->size = synth_field_size(field->type);
1071        if (!field->size) {
1072                ret = -EINVAL;
1073                goto free;
1074        }
1075
1076        if (synth_field_is_string(field->type))
1077                field->is_string = true;
1078
1079        field->is_signed = synth_field_signed(field->type);
1080
1081 out:
1082        return field;
1083 free:
1084        free_synth_field(field);
1085        field = ERR_PTR(ret);
1086        goto out;
1087}
1088
1089static void free_synth_tracepoint(struct tracepoint *tp)
1090{
1091        if (!tp)
1092                return;
1093
1094        kfree(tp->name);
1095        kfree(tp);
1096}
1097
1098static struct tracepoint *alloc_synth_tracepoint(char *name)
1099{
1100        struct tracepoint *tp;
1101
1102        tp = kzalloc(sizeof(*tp), GFP_KERNEL);
1103        if (!tp)
1104                return ERR_PTR(-ENOMEM);
1105
1106        tp->name = kstrdup(name, GFP_KERNEL);
1107        if (!tp->name) {
1108                kfree(tp);
1109                return ERR_PTR(-ENOMEM);
1110        }
1111
1112        return tp;
1113}
1114
1115typedef void (*synth_probe_func_t) (void *__data, u64 *var_ref_vals,
1116                                    unsigned int var_ref_idx);
1117
1118static inline void trace_synth(struct synth_event *event, u64 *var_ref_vals,
1119                               unsigned int var_ref_idx)
1120{
1121        struct tracepoint *tp = event->tp;
1122
1123        if (unlikely(atomic_read(&tp->key.enabled) > 0)) {
1124                struct tracepoint_func *probe_func_ptr;
1125                synth_probe_func_t probe_func;
1126                void *__data;
1127
1128                if (!(cpu_online(raw_smp_processor_id())))
1129                        return;
1130
1131                probe_func_ptr = rcu_dereference_sched((tp)->funcs);
1132                if (probe_func_ptr) {
1133                        do {
1134                                probe_func = probe_func_ptr->func;
1135                                __data = probe_func_ptr->data;
1136                                probe_func(__data, var_ref_vals, var_ref_idx);
1137                        } while ((++probe_func_ptr)->func);
1138                }
1139        }
1140}
1141
1142static struct synth_event *find_synth_event(const char *name)
1143{
1144        struct dyn_event *pos;
1145        struct synth_event *event;
1146
1147        for_each_dyn_event(pos) {
1148                if (!is_synth_event(pos))
1149                        continue;
1150                event = to_synth_event(pos);
1151                if (strcmp(event->name, name) == 0)
1152                        return event;
1153        }
1154
1155        return NULL;
1156}
1157
1158static int register_synth_event(struct synth_event *event)
1159{
1160        struct trace_event_call *call = &event->call;
1161        int ret = 0;
1162
1163        event->call.class = &event->class;
1164        event->class.system = kstrdup(SYNTH_SYSTEM, GFP_KERNEL);
1165        if (!event->class.system) {
1166                ret = -ENOMEM;
1167                goto out;
1168        }
1169
1170        event->tp = alloc_synth_tracepoint(event->name);
1171        if (IS_ERR(event->tp)) {
1172                ret = PTR_ERR(event->tp);
1173                event->tp = NULL;
1174                goto out;
1175        }
1176
1177        INIT_LIST_HEAD(&call->class->fields);
1178        call->event.funcs = &synth_event_funcs;
1179        call->class->define_fields = synth_event_define_fields;
1180
1181        ret = register_trace_event(&call->event);
1182        if (!ret) {
1183                ret = -ENODEV;
1184                goto out;
1185        }
1186        call->flags = TRACE_EVENT_FL_TRACEPOINT;
1187        call->class->reg = trace_event_reg;
1188        call->class->probe = trace_event_raw_event_synth;
1189        call->data = event;
1190        call->tp = event->tp;
1191
1192        ret = trace_add_event_call(call);
1193        if (ret) {
1194                pr_warn("Failed to register synthetic event: %s\n",
1195                        trace_event_name(call));
1196                goto err;
1197        }
1198
1199        ret = set_synth_event_print_fmt(call);
1200        if (ret < 0) {
1201                trace_remove_event_call(call);
1202                goto err;
1203        }
1204 out:
1205        return ret;
1206 err:
1207        unregister_trace_event(&call->event);
1208        goto out;
1209}
1210
1211static int unregister_synth_event(struct synth_event *event)
1212{
1213        struct trace_event_call *call = &event->call;
1214        int ret;
1215
1216        ret = trace_remove_event_call(call);
1217
1218        return ret;
1219}
1220
1221static void free_synth_event(struct synth_event *event)
1222{
1223        unsigned int i;
1224
1225        if (!event)
1226                return;
1227
1228        for (i = 0; i < event->n_fields; i++)
1229                free_synth_field(event->fields[i]);
1230
1231        kfree(event->fields);
1232        kfree(event->name);
1233        kfree(event->class.system);
1234        free_synth_tracepoint(event->tp);
1235        free_synth_event_print_fmt(&event->call);
1236        kfree(event);
1237}
1238
1239static struct synth_event *alloc_synth_event(const char *name, int n_fields,
1240                                             struct synth_field **fields)
1241{
1242        struct synth_event *event;
1243        unsigned int i;
1244
1245        event = kzalloc(sizeof(*event), GFP_KERNEL);
1246        if (!event) {
1247                event = ERR_PTR(-ENOMEM);
1248                goto out;
1249        }
1250
1251        event->name = kstrdup(name, GFP_KERNEL);
1252        if (!event->name) {
1253                kfree(event);
1254                event = ERR_PTR(-ENOMEM);
1255                goto out;
1256        }
1257
1258        event->fields = kcalloc(n_fields, sizeof(*event->fields), GFP_KERNEL);
1259        if (!event->fields) {
1260                free_synth_event(event);
1261                event = ERR_PTR(-ENOMEM);
1262                goto out;
1263        }
1264
1265        dyn_event_init(&event->devent, &synth_event_ops);
1266
1267        for (i = 0; i < n_fields; i++)
1268                event->fields[i] = fields[i];
1269
1270        event->n_fields = n_fields;
1271 out:
1272        return event;
1273}
1274
1275static void action_trace(struct hist_trigger_data *hist_data,
1276                         struct tracing_map_elt *elt, void *rec,
1277                         struct ring_buffer_event *rbe, void *key,
1278                         struct action_data *data, u64 *var_ref_vals)
1279{
1280        struct synth_event *event = data->synth_event;
1281
1282        trace_synth(event, var_ref_vals, data->var_ref_idx);
1283}
1284
1285struct hist_var_data {
1286        struct list_head list;
1287        struct hist_trigger_data *hist_data;
1288};
1289
1290static int __create_synth_event(int argc, const char *name, const char **argv)
1291{
1292        struct synth_field *field, *fields[SYNTH_FIELDS_MAX];
1293        struct synth_event *event = NULL;
1294        int i, consumed = 0, n_fields = 0, ret = 0;
1295
1296        /*
1297         * Argument syntax:
1298         *  - Add synthetic event: <event_name> field[;field] ...
1299         *  - Remove synthetic event: !<event_name> field[;field] ...
1300         *      where 'field' = type field_name
1301         */
1302
1303        if (name[0] == '\0' || argc < 1)
1304                return -EINVAL;
1305
1306        mutex_lock(&event_mutex);
1307
1308        event = find_synth_event(name);
1309        if (event) {
1310                ret = -EEXIST;
1311                goto out;
1312        }
1313
1314        for (i = 0; i < argc - 1; i++) {
1315                if (strcmp(argv[i], ";") == 0)
1316                        continue;
1317                if (n_fields == SYNTH_FIELDS_MAX) {
1318                        ret = -EINVAL;
1319                        goto err;
1320                }
1321
1322                field = parse_synth_field(argc - i, &argv[i], &consumed);
1323                if (IS_ERR(field)) {
1324                        ret = PTR_ERR(field);
1325                        goto err;
1326                }
1327                fields[n_fields++] = field;
1328                i += consumed - 1;
1329        }
1330
1331        if (i < argc && strcmp(argv[i], ";") != 0) {
1332                ret = -EINVAL;
1333                goto err;
1334        }
1335
1336        event = alloc_synth_event(name, n_fields, fields);
1337        if (IS_ERR(event)) {
1338                ret = PTR_ERR(event);
1339                event = NULL;
1340                goto err;
1341        }
1342        ret = register_synth_event(event);
1343        if (!ret)
1344                dyn_event_add(&event->devent);
1345        else
1346                free_synth_event(event);
1347 out:
1348        mutex_unlock(&event_mutex);
1349
1350        return ret;
1351 err:
1352        for (i = 0; i < n_fields; i++)
1353                free_synth_field(fields[i]);
1354
1355        goto out;
1356}
1357
1358static int create_or_delete_synth_event(int argc, char **argv)
1359{
1360        const char *name = argv[0];
1361        struct synth_event *event = NULL;
1362        int ret;
1363
1364        /* trace_run_command() ensures argc != 0 */
1365        if (name[0] == '!') {
1366                mutex_lock(&event_mutex);
1367                event = find_synth_event(name + 1);
1368                if (event) {
1369                        if (event->ref)
1370                                ret = -EBUSY;
1371                        else {
1372                                ret = unregister_synth_event(event);
1373                                if (!ret) {
1374                                        dyn_event_remove(&event->devent);
1375                                        free_synth_event(event);
1376                                }
1377                        }
1378                } else
1379                        ret = -ENOENT;
1380                mutex_unlock(&event_mutex);
1381                return ret;
1382        }
1383
1384        ret = __create_synth_event(argc - 1, name, (const char **)argv + 1);
1385        return ret == -ECANCELED ? -EINVAL : ret;
1386}
1387
1388static int synth_event_create(int argc, const char **argv)
1389{
1390        const char *name = argv[0];
1391        int len;
1392
1393        if (name[0] != 's' || name[1] != ':')
1394                return -ECANCELED;
1395        name += 2;
1396
1397        /* This interface accepts group name prefix */
1398        if (strchr(name, '/')) {
1399                len = str_has_prefix(name, SYNTH_SYSTEM "/");
1400                if (len == 0)
1401                        return -EINVAL;
1402                name += len;
1403        }
1404        return __create_synth_event(argc - 1, name, argv + 1);
1405}
1406
1407static int synth_event_release(struct dyn_event *ev)
1408{
1409        struct synth_event *event = to_synth_event(ev);
1410        int ret;
1411
1412        if (event->ref)
1413                return -EBUSY;
1414
1415        ret = unregister_synth_event(event);
1416        if (ret)
1417                return ret;
1418
1419        dyn_event_remove(ev);
1420        free_synth_event(event);
1421        return 0;
1422}
1423
1424static int __synth_event_show(struct seq_file *m, struct synth_event *event)
1425{
1426        struct synth_field *field;
1427        unsigned int i;
1428
1429        seq_printf(m, "%s\t", event->name);
1430
1431        for (i = 0; i < event->n_fields; i++) {
1432                field = event->fields[i];
1433
1434                /* parameter values */
1435                seq_printf(m, "%s %s%s", field->type, field->name,
1436                           i == event->n_fields - 1 ? "" : "; ");
1437        }
1438
1439        seq_putc(m, '\n');
1440
1441        return 0;
1442}
1443
1444static int synth_event_show(struct seq_file *m, struct dyn_event *ev)
1445{
1446        struct synth_event *event = to_synth_event(ev);
1447
1448        seq_printf(m, "s:%s/", event->class.system);
1449
1450        return __synth_event_show(m, event);
1451}
1452
1453static int synth_events_seq_show(struct seq_file *m, void *v)
1454{
1455        struct dyn_event *ev = v;
1456
1457        if (!is_synth_event(ev))
1458                return 0;
1459
1460        return __synth_event_show(m, to_synth_event(ev));
1461}
1462
1463static const struct seq_operations synth_events_seq_op = {
1464        .start  = dyn_event_seq_start,
1465        .next   = dyn_event_seq_next,
1466        .stop   = dyn_event_seq_stop,
1467        .show   = synth_events_seq_show,
1468};
1469
1470static int synth_events_open(struct inode *inode, struct file *file)
1471{
1472        int ret;
1473
1474        ret = security_locked_down(LOCKDOWN_TRACEFS);
1475        if (ret)
1476                return ret;
1477
1478        if ((file->f_mode & FMODE_WRITE) && (file->f_flags & O_TRUNC)) {
1479                ret = dyn_events_release_all(&synth_event_ops);
1480                if (ret < 0)
1481                        return ret;
1482        }
1483
1484        return seq_open(file, &synth_events_seq_op);
1485}
1486
1487static ssize_t synth_events_write(struct file *file,
1488                                  const char __user *buffer,
1489                                  size_t count, loff_t *ppos)
1490{
1491        return trace_parse_run_command(file, buffer, count, ppos,
1492                                       create_or_delete_synth_event);
1493}
1494
1495static const struct file_operations synth_events_fops = {
1496        .open           = synth_events_open,
1497        .write          = synth_events_write,
1498        .read           = seq_read,
1499        .llseek         = seq_lseek,
1500        .release        = seq_release,
1501};
1502
1503static u64 hist_field_timestamp(struct hist_field *hist_field,
1504                                struct tracing_map_elt *elt,
1505                                struct ring_buffer_event *rbe,
1506                                void *event)
1507{
1508        struct hist_trigger_data *hist_data = hist_field->hist_data;
1509        struct trace_array *tr = hist_data->event_file->tr;
1510
1511        u64 ts = ring_buffer_event_time_stamp(rbe);
1512
1513        if (hist_data->attrs->ts_in_usecs && trace_clock_in_ns(tr))
1514                ts = ns2usecs(ts);
1515
1516        return ts;
1517}
1518
1519static u64 hist_field_cpu(struct hist_field *hist_field,
1520                          struct tracing_map_elt *elt,
1521                          struct ring_buffer_event *rbe,
1522                          void *event)
1523{
1524        int cpu = smp_processor_id();
1525
1526        return cpu;
1527}
1528
1529/**
1530 * check_field_for_var_ref - Check if a VAR_REF field references a variable
1531 * @hist_field: The VAR_REF field to check
1532 * @var_data: The hist trigger that owns the variable
1533 * @var_idx: The trigger variable identifier
1534 *
1535 * Check the given VAR_REF field to see whether or not it references
1536 * the given variable associated with the given trigger.
1537 *
1538 * Return: The VAR_REF field if it does reference the variable, NULL if not
1539 */
1540static struct hist_field *
1541check_field_for_var_ref(struct hist_field *hist_field,
1542                        struct hist_trigger_data *var_data,
1543                        unsigned int var_idx)
1544{
1545        WARN_ON(!(hist_field && hist_field->flags & HIST_FIELD_FL_VAR_REF));
1546
1547        if (hist_field && hist_field->var.idx == var_idx &&
1548            hist_field->var.hist_data == var_data)
1549                return hist_field;
1550
1551        return NULL;
1552}
1553
1554/**
1555 * find_var_ref - Check if a trigger has a reference to a trigger variable
1556 * @hist_data: The hist trigger that might have a reference to the variable
1557 * @var_data: The hist trigger that owns the variable
1558 * @var_idx: The trigger variable identifier
1559 *
1560 * Check the list of var_refs[] on the first hist trigger to see
1561 * whether any of them are references to the variable on the second
1562 * trigger.
1563 *
1564 * Return: The VAR_REF field referencing the variable if so, NULL if not
1565 */
1566static struct hist_field *find_var_ref(struct hist_trigger_data *hist_data,
1567                                       struct hist_trigger_data *var_data,
1568                                       unsigned int var_idx)
1569{
1570        struct hist_field *hist_field;
1571        unsigned int i;
1572
1573        for (i = 0; i < hist_data->n_var_refs; i++) {
1574                hist_field = hist_data->var_refs[i];
1575                if (check_field_for_var_ref(hist_field, var_data, var_idx))
1576                        return hist_field;
1577        }
1578
1579        return NULL;
1580}
1581
1582/**
1583 * find_any_var_ref - Check if there is a reference to a given trigger variable
1584 * @hist_data: The hist trigger
1585 * @var_idx: The trigger variable identifier
1586 *
1587 * Check to see whether the given variable is currently referenced by
1588 * any other trigger.
1589 *
1590 * The trigger the variable is defined on is explicitly excluded - the
1591 * assumption being that a self-reference doesn't prevent a trigger
1592 * from being removed.
1593 *
1594 * Return: The VAR_REF field referencing the variable if so, NULL if not
1595 */
1596static struct hist_field *find_any_var_ref(struct hist_trigger_data *hist_data,
1597                                           unsigned int var_idx)
1598{
1599        struct trace_array *tr = hist_data->event_file->tr;
1600        struct hist_field *found = NULL;
1601        struct hist_var_data *var_data;
1602
1603        list_for_each_entry(var_data, &tr->hist_vars, list) {
1604                if (var_data->hist_data == hist_data)
1605                        continue;
1606                found = find_var_ref(var_data->hist_data, hist_data, var_idx);
1607                if (found)
1608                        break;
1609        }
1610
1611        return found;
1612}
1613
1614/**
1615 * check_var_refs - Check if there is a reference to any of trigger's variables
1616 * @hist_data: The hist trigger
1617 *
1618 * A trigger can define one or more variables.  If any one of them is
1619 * currently referenced by any other trigger, this function will
1620 * determine that.
1621
1622 * Typically used to determine whether or not a trigger can be removed
1623 * - if there are any references to a trigger's variables, it cannot.
1624 *
1625 * Return: True if there is a reference to any of trigger's variables
1626 */
1627static bool check_var_refs(struct hist_trigger_data *hist_data)
1628{
1629        struct hist_field *field;
1630        bool found = false;
1631        int i;
1632
1633        for_each_hist_field(i, hist_data) {
1634                field = hist_data->fields[i];
1635                if (field && field->flags & HIST_FIELD_FL_VAR) {
1636                        if (find_any_var_ref(hist_data, field->var.idx)) {
1637                                found = true;
1638                                break;
1639                        }
1640                }
1641        }
1642
1643        return found;
1644}
1645
1646static struct hist_var_data *find_hist_vars(struct hist_trigger_data *hist_data)
1647{
1648        struct trace_array *tr = hist_data->event_file->tr;
1649        struct hist_var_data *var_data, *found = NULL;
1650
1651        list_for_each_entry(var_data, &tr->hist_vars, list) {
1652                if (var_data->hist_data == hist_data) {
1653                        found = var_data;
1654                        break;
1655                }
1656        }
1657
1658        return found;
1659}
1660
1661static bool field_has_hist_vars(struct hist_field *hist_field,
1662                                unsigned int level)
1663{
1664        int i;
1665
1666        if (level > 3)
1667                return false;
1668
1669        if (!hist_field)
1670                return false;
1671
1672        if (hist_field->flags & HIST_FIELD_FL_VAR ||
1673            hist_field->flags & HIST_FIELD_FL_VAR_REF)
1674                return true;
1675
1676        for (i = 0; i < HIST_FIELD_OPERANDS_MAX; i++) {
1677                struct hist_field *operand;
1678
1679                operand = hist_field->operands[i];
1680                if (field_has_hist_vars(operand, level + 1))
1681                        return true;
1682        }
1683
1684        return false;
1685}
1686
1687static bool has_hist_vars(struct hist_trigger_data *hist_data)
1688{
1689        struct hist_field *hist_field;
1690        int i;
1691
1692        for_each_hist_field(i, hist_data) {
1693                hist_field = hist_data->fields[i];
1694                if (field_has_hist_vars(hist_field, 0))
1695                        return true;
1696        }
1697
1698        return false;
1699}
1700
1701static int save_hist_vars(struct hist_trigger_data *hist_data)
1702{
1703        struct trace_array *tr = hist_data->event_file->tr;
1704        struct hist_var_data *var_data;
1705
1706        var_data = find_hist_vars(hist_data);
1707        if (var_data)
1708                return 0;
1709
1710        if (tracing_check_open_get_tr(tr))
1711                return -ENODEV;
1712
1713        var_data = kzalloc(sizeof(*var_data), GFP_KERNEL);
1714        if (!var_data) {
1715                trace_array_put(tr);
1716                return -ENOMEM;
1717        }
1718
1719        var_data->hist_data = hist_data;
1720        list_add(&var_data->list, &tr->hist_vars);
1721
1722        return 0;
1723}
1724
1725static void remove_hist_vars(struct hist_trigger_data *hist_data)
1726{
1727        struct trace_array *tr = hist_data->event_file->tr;
1728        struct hist_var_data *var_data;
1729
1730        var_data = find_hist_vars(hist_data);
1731        if (!var_data)
1732                return;
1733
1734        if (WARN_ON(check_var_refs(hist_data)))
1735                return;
1736
1737        list_del(&var_data->list);
1738
1739        kfree(var_data);
1740
1741        trace_array_put(tr);
1742}
1743
1744static struct hist_field *find_var_field(struct hist_trigger_data *hist_data,
1745                                         const char *var_name)
1746{
1747        struct hist_field *hist_field, *found = NULL;
1748        int i;
1749
1750        for_each_hist_field(i, hist_data) {
1751                hist_field = hist_data->fields[i];
1752                if (hist_field && hist_field->flags & HIST_FIELD_FL_VAR &&
1753                    strcmp(hist_field->var.name, var_name) == 0) {
1754                        found = hist_field;
1755                        break;
1756                }
1757        }
1758
1759        return found;
1760}
1761
1762static struct hist_field *find_var(struct hist_trigger_data *hist_data,
1763                                   struct trace_event_file *file,
1764                                   const char *var_name)
1765{
1766        struct hist_trigger_data *test_data;
1767        struct event_trigger_data *test;
1768        struct hist_field *hist_field;
1769
1770        lockdep_assert_held(&event_mutex);
1771
1772        hist_field = find_var_field(hist_data, var_name);
1773        if (hist_field)
1774                return hist_field;
1775
1776        list_for_each_entry(test, &file->triggers, list) {
1777                if (test->cmd_ops->trigger_type == ETT_EVENT_HIST) {
1778                        test_data = test->private_data;
1779                        hist_field = find_var_field(test_data, var_name);
1780                        if (hist_field)
1781                                return hist_field;
1782                }
1783        }
1784
1785        return NULL;
1786}
1787
1788static struct trace_event_file *find_var_file(struct trace_array *tr,
1789                                              char *system,
1790                                              char *event_name,
1791                                              char *var_name)
1792{
1793        struct hist_trigger_data *var_hist_data;
1794        struct hist_var_data *var_data;
1795        struct trace_event_file *file, *found = NULL;
1796
1797        if (system)
1798                return find_event_file(tr, system, event_name);
1799
1800        list_for_each_entry(var_data, &tr->hist_vars, list) {
1801                var_hist_data = var_data->hist_data;
1802                file = var_hist_data->event_file;
1803                if (file == found)
1804                        continue;
1805
1806                if (find_var_field(var_hist_data, var_name)) {
1807                        if (found) {
1808                                hist_err(tr, HIST_ERR_VAR_NOT_UNIQUE, errpos(var_name));
1809                                return NULL;
1810                        }
1811
1812                        found = file;
1813                }
1814        }
1815
1816        return found;
1817}
1818
1819static struct hist_field *find_file_var(struct trace_event_file *file,
1820                                        const char *var_name)
1821{
1822        struct hist_trigger_data *test_data;
1823        struct event_trigger_data *test;
1824        struct hist_field *hist_field;
1825
1826        lockdep_assert_held(&event_mutex);
1827
1828        list_for_each_entry(test, &file->triggers, list) {
1829                if (test->cmd_ops->trigger_type == ETT_EVENT_HIST) {
1830                        test_data = test->private_data;
1831                        hist_field = find_var_field(test_data, var_name);
1832                        if (hist_field)
1833                                return hist_field;
1834                }
1835        }
1836
1837        return NULL;
1838}
1839
1840static struct hist_field *
1841find_match_var(struct hist_trigger_data *hist_data, char *var_name)
1842{
1843        struct trace_array *tr = hist_data->event_file->tr;
1844        struct hist_field *hist_field, *found = NULL;
1845        struct trace_event_file *file;
1846        unsigned int i;
1847
1848        for (i = 0; i < hist_data->n_actions; i++) {
1849                struct action_data *data = hist_data->actions[i];
1850
1851                if (data->handler == HANDLER_ONMATCH) {
1852                        char *system = data->match_data.event_system;
1853                        char *event_name = data->match_data.event;
1854
1855                        file = find_var_file(tr, system, event_name, var_name);
1856                        if (!file)
1857                                continue;
1858                        hist_field = find_file_var(file, var_name);
1859                        if (hist_field) {
1860                                if (found) {
1861                                        hist_err(tr, HIST_ERR_VAR_NOT_UNIQUE,
1862                                                 errpos(var_name));
1863                                        return ERR_PTR(-EINVAL);
1864                                }
1865
1866                                found = hist_field;
1867                        }
1868                }
1869        }
1870        return found;
1871}
1872
1873static struct hist_field *find_event_var(struct hist_trigger_data *hist_data,
1874                                         char *system,
1875                                         char *event_name,
1876                                         char *var_name)
1877{
1878        struct trace_array *tr = hist_data->event_file->tr;
1879        struct hist_field *hist_field = NULL;
1880        struct trace_event_file *file;
1881
1882        if (!system || !event_name) {
1883                hist_field = find_match_var(hist_data, var_name);
1884                if (IS_ERR(hist_field))
1885                        return NULL;
1886                if (hist_field)
1887                        return hist_field;
1888        }
1889
1890        file = find_var_file(tr, system, event_name, var_name);
1891        if (!file)
1892                return NULL;
1893
1894        hist_field = find_file_var(file, var_name);
1895
1896        return hist_field;
1897}
1898
1899static u64 hist_field_var_ref(struct hist_field *hist_field,
1900                              struct tracing_map_elt *elt,
1901                              struct ring_buffer_event *rbe,
1902                              void *event)
1903{
1904        struct hist_elt_data *elt_data;
1905        u64 var_val = 0;
1906
1907        if (WARN_ON_ONCE(!elt))
1908                return var_val;
1909
1910        elt_data = elt->private_data;
1911        var_val = elt_data->var_ref_vals[hist_field->var_ref_idx];
1912
1913        return var_val;
1914}
1915
1916static bool resolve_var_refs(struct hist_trigger_data *hist_data, void *key,
1917                             u64 *var_ref_vals, bool self)
1918{
1919        struct hist_trigger_data *var_data;
1920        struct tracing_map_elt *var_elt;
1921        struct hist_field *hist_field;
1922        unsigned int i, var_idx;
1923        bool resolved = true;
1924        u64 var_val = 0;
1925
1926        for (i = 0; i < hist_data->n_var_refs; i++) {
1927                hist_field = hist_data->var_refs[i];
1928                var_idx = hist_field->var.idx;
1929                var_data = hist_field->var.hist_data;
1930
1931                if (var_data == NULL) {
1932                        resolved = false;
1933                        break;
1934                }
1935
1936                if ((self && var_data != hist_data) ||
1937                    (!self && var_data == hist_data))
1938                        continue;
1939
1940                var_elt = tracing_map_lookup(var_data->map, key);
1941                if (!var_elt) {
1942                        resolved = false;
1943                        break;
1944                }
1945
1946                if (!tracing_map_var_set(var_elt, var_idx)) {
1947                        resolved = false;
1948                        break;
1949                }
1950
1951                if (self || !hist_field->read_once)
1952                        var_val = tracing_map_read_var(var_elt, var_idx);
1953                else
1954                        var_val = tracing_map_read_var_once(var_elt, var_idx);
1955
1956                var_ref_vals[i] = var_val;
1957        }
1958
1959        return resolved;
1960}
1961
1962static const char *hist_field_name(struct hist_field *field,
1963                                   unsigned int level)
1964{
1965        const char *field_name = "";
1966
1967        if (level > 1)
1968                return field_name;
1969
1970        if (field->field)
1971                field_name = field->field->name;
1972        else if (field->flags & HIST_FIELD_FL_LOG2 ||
1973                 field->flags & HIST_FIELD_FL_ALIAS)
1974                field_name = hist_field_name(field->operands[0], ++level);
1975        else if (field->flags & HIST_FIELD_FL_CPU)
1976                field_name = "cpu";
1977        else if (field->flags & HIST_FIELD_FL_EXPR ||
1978                 field->flags & HIST_FIELD_FL_VAR_REF) {
1979                if (field->system) {
1980                        static char full_name[MAX_FILTER_STR_VAL];
1981
1982                        strcat(full_name, field->system);
1983                        strcat(full_name, ".");
1984                        strcat(full_name, field->event_name);
1985                        strcat(full_name, ".");
1986                        strcat(full_name, field->name);
1987                        field_name = full_name;
1988                } else
1989                        field_name = field->name;
1990        } else if (field->flags & HIST_FIELD_FL_TIMESTAMP)
1991                field_name = "common_timestamp";
1992
1993        if (field_name == NULL)
1994                field_name = "";
1995
1996        return field_name;
1997}
1998
1999static hist_field_fn_t select_value_fn(int field_size, int field_is_signed)
2000{
2001        hist_field_fn_t fn = NULL;
2002
2003        switch (field_size) {
2004        case 8:
2005                if (field_is_signed)
2006                        fn = hist_field_s64;
2007                else
2008                        fn = hist_field_u64;
2009                break;
2010        case 4:
2011                if (field_is_signed)
2012                        fn = hist_field_s32;
2013                else
2014                        fn = hist_field_u32;
2015                break;
2016        case 2:
2017                if (field_is_signed)
2018                        fn = hist_field_s16;
2019                else
2020                        fn = hist_field_u16;
2021                break;
2022        case 1:
2023                if (field_is_signed)
2024                        fn = hist_field_s8;
2025                else
2026                        fn = hist_field_u8;
2027                break;
2028        }
2029
2030        return fn;
2031}
2032
2033static int parse_map_size(char *str)
2034{
2035        unsigned long size, map_bits;
2036        int ret;
2037
2038        strsep(&str, "=");
2039        if (!str) {
2040                ret = -EINVAL;
2041                goto out;
2042        }
2043
2044        ret = kstrtoul(str, 0, &size);
2045        if (ret)
2046                goto out;
2047
2048        map_bits = ilog2(roundup_pow_of_two(size));
2049        if (map_bits < TRACING_MAP_BITS_MIN ||
2050            map_bits > TRACING_MAP_BITS_MAX)
2051                ret = -EINVAL;
2052        else
2053                ret = map_bits;
2054 out:
2055        return ret;
2056}
2057
2058static void destroy_hist_trigger_attrs(struct hist_trigger_attrs *attrs)
2059{
2060        unsigned int i;
2061
2062        if (!attrs)
2063                return;
2064
2065        for (i = 0; i < attrs->n_assignments; i++)
2066                kfree(attrs->assignment_str[i]);
2067
2068        for (i = 0; i < attrs->n_actions; i++)
2069                kfree(attrs->action_str[i]);
2070
2071        kfree(attrs->name);
2072        kfree(attrs->sort_key_str);
2073        kfree(attrs->keys_str);
2074        kfree(attrs->vals_str);
2075        kfree(attrs->clock);
2076        kfree(attrs);
2077}
2078
2079static int parse_action(char *str, struct hist_trigger_attrs *attrs)
2080{
2081        int ret = -EINVAL;
2082
2083        if (attrs->n_actions >= HIST_ACTIONS_MAX)
2084                return ret;
2085
2086        if ((str_has_prefix(str, "onmatch(")) ||
2087            (str_has_prefix(str, "onmax(")) ||
2088            (str_has_prefix(str, "onchange("))) {
2089                attrs->action_str[attrs->n_actions] = kstrdup(str, GFP_KERNEL);
2090                if (!attrs->action_str[attrs->n_actions]) {
2091                        ret = -ENOMEM;
2092                        return ret;
2093                }
2094                attrs->n_actions++;
2095                ret = 0;
2096        }
2097        return ret;
2098}
2099
2100static int parse_assignment(struct trace_array *tr,
2101                            char *str, struct hist_trigger_attrs *attrs)
2102{
2103        int ret = 0;
2104
2105        if ((str_has_prefix(str, "key=")) ||
2106            (str_has_prefix(str, "keys="))) {
2107                attrs->keys_str = kstrdup(str, GFP_KERNEL);
2108                if (!attrs->keys_str) {
2109                        ret = -ENOMEM;
2110                        goto out;
2111                }
2112        } else if ((str_has_prefix(str, "val=")) ||
2113                   (str_has_prefix(str, "vals=")) ||
2114                   (str_has_prefix(str, "values="))) {
2115                attrs->vals_str = kstrdup(str, GFP_KERNEL);
2116                if (!attrs->vals_str) {
2117                        ret = -ENOMEM;
2118                        goto out;
2119                }
2120        } else if (str_has_prefix(str, "sort=")) {
2121                attrs->sort_key_str = kstrdup(str, GFP_KERNEL);
2122                if (!attrs->sort_key_str) {
2123                        ret = -ENOMEM;
2124                        goto out;
2125                }
2126        } else if (str_has_prefix(str, "name=")) {
2127                attrs->name = kstrdup(str, GFP_KERNEL);
2128                if (!attrs->name) {
2129                        ret = -ENOMEM;
2130                        goto out;
2131                }
2132        } else if (str_has_prefix(str, "clock=")) {
2133                strsep(&str, "=");
2134                if (!str) {
2135                        ret = -EINVAL;
2136                        goto out;
2137                }
2138
2139                str = strstrip(str);
2140                attrs->clock = kstrdup(str, GFP_KERNEL);
2141                if (!attrs->clock) {
2142                        ret = -ENOMEM;
2143                        goto out;
2144                }
2145        } else if (str_has_prefix(str, "size=")) {
2146                int map_bits = parse_map_size(str);
2147
2148                if (map_bits < 0) {
2149                        ret = map_bits;
2150                        goto out;
2151                }
2152                attrs->map_bits = map_bits;
2153        } else {
2154                char *assignment;
2155
2156                if (attrs->n_assignments == TRACING_MAP_VARS_MAX) {
2157                        hist_err(tr, HIST_ERR_TOO_MANY_VARS, errpos(str));
2158                        ret = -EINVAL;
2159                        goto out;
2160                }
2161
2162                assignment = kstrdup(str, GFP_KERNEL);
2163                if (!assignment) {
2164                        ret = -ENOMEM;
2165                        goto out;
2166                }
2167
2168                attrs->assignment_str[attrs->n_assignments++] = assignment;
2169        }
2170 out:
2171        return ret;
2172}
2173
2174static struct hist_trigger_attrs *
2175parse_hist_trigger_attrs(struct trace_array *tr, char *trigger_str)
2176{
2177        struct hist_trigger_attrs *attrs;
2178        int ret = 0;
2179
2180        attrs = kzalloc(sizeof(*attrs), GFP_KERNEL);
2181        if (!attrs)
2182                return ERR_PTR(-ENOMEM);
2183
2184        while (trigger_str) {
2185                char *str = strsep(&trigger_str, ":");
2186
2187                if (strchr(str, '=')) {
2188                        ret = parse_assignment(tr, str, attrs);
2189                        if (ret)
2190                                goto free;
2191                } else if (strcmp(str, "pause") == 0)
2192                        attrs->pause = true;
2193                else if ((strcmp(str, "cont") == 0) ||
2194                         (strcmp(str, "continue") == 0))
2195                        attrs->cont = true;
2196                else if (strcmp(str, "clear") == 0)
2197                        attrs->clear = true;
2198                else {
2199                        ret = parse_action(str, attrs);
2200                        if (ret)
2201                                goto free;
2202                }
2203        }
2204
2205        if (!attrs->keys_str) {
2206                ret = -EINVAL;
2207                goto free;
2208        }
2209
2210        if (!attrs->clock) {
2211                attrs->clock = kstrdup("global", GFP_KERNEL);
2212                if (!attrs->clock) {
2213                        ret = -ENOMEM;
2214                        goto free;
2215                }
2216        }
2217
2218        return attrs;
2219 free:
2220        destroy_hist_trigger_attrs(attrs);
2221
2222        return ERR_PTR(ret);
2223}
2224
2225static inline void save_comm(char *comm, struct task_struct *task)
2226{
2227        if (!task->pid) {
2228                strcpy(comm, "<idle>");
2229                return;
2230        }
2231
2232        if (WARN_ON_ONCE(task->pid < 0)) {
2233                strcpy(comm, "<XXX>");
2234                return;
2235        }
2236
2237        strncpy(comm, task->comm, TASK_COMM_LEN);
2238}
2239
2240static void hist_elt_data_free(struct hist_elt_data *elt_data)
2241{
2242        unsigned int i;
2243
2244        for (i = 0; i < SYNTH_FIELDS_MAX; i++)
2245                kfree(elt_data->field_var_str[i]);
2246
2247        kfree(elt_data->comm);
2248        kfree(elt_data);
2249}
2250
2251static void hist_trigger_elt_data_free(struct tracing_map_elt *elt)
2252{
2253        struct hist_elt_data *elt_data = elt->private_data;
2254
2255        hist_elt_data_free(elt_data);
2256}
2257
2258static int hist_trigger_elt_data_alloc(struct tracing_map_elt *elt)
2259{
2260        struct hist_trigger_data *hist_data = elt->map->private_data;
2261        unsigned int size = TASK_COMM_LEN;
2262        struct hist_elt_data *elt_data;
2263        struct hist_field *key_field;
2264        unsigned int i, n_str;
2265
2266        elt_data = kzalloc(sizeof(*elt_data), GFP_KERNEL);
2267        if (!elt_data)
2268                return -ENOMEM;
2269
2270        for_each_hist_key_field(i, hist_data) {
2271                key_field = hist_data->fields[i];
2272
2273                if (key_field->flags & HIST_FIELD_FL_EXECNAME) {
2274                        elt_data->comm = kzalloc(size, GFP_KERNEL);
2275                        if (!elt_data->comm) {
2276                                kfree(elt_data);
2277                                return -ENOMEM;
2278                        }
2279                        break;
2280                }
2281        }
2282
2283        n_str = hist_data->n_field_var_str + hist_data->n_save_var_str;
2284
2285        size = STR_VAR_LEN_MAX;
2286
2287        for (i = 0; i < n_str; i++) {
2288                elt_data->field_var_str[i] = kzalloc(size, GFP_KERNEL);
2289                if (!elt_data->field_var_str[i]) {
2290                        hist_elt_data_free(elt_data);
2291                        return -ENOMEM;
2292                }
2293        }
2294
2295        elt->private_data = elt_data;
2296
2297        return 0;
2298}
2299
2300static void hist_trigger_elt_data_init(struct tracing_map_elt *elt)
2301{
2302        struct hist_elt_data *elt_data = elt->private_data;
2303
2304        if (elt_data->comm)
2305                save_comm(elt_data->comm, current);
2306}
2307
2308static const struct tracing_map_ops hist_trigger_elt_data_ops = {
2309        .elt_alloc      = hist_trigger_elt_data_alloc,
2310        .elt_free       = hist_trigger_elt_data_free,
2311        .elt_init       = hist_trigger_elt_data_init,
2312};
2313
2314static const char *get_hist_field_flags(struct hist_field *hist_field)
2315{
2316        const char *flags_str = NULL;
2317
2318        if (hist_field->flags & HIST_FIELD_FL_HEX)
2319                flags_str = "hex";
2320        else if (hist_field->flags & HIST_FIELD_FL_SYM)
2321                flags_str = "sym";
2322        else if (hist_field->flags & HIST_FIELD_FL_SYM_OFFSET)
2323                flags_str = "sym-offset";
2324        else if (hist_field->flags & HIST_FIELD_FL_EXECNAME)
2325                flags_str = "execname";
2326        else if (hist_field->flags & HIST_FIELD_FL_SYSCALL)
2327                flags_str = "syscall";
2328        else if (hist_field->flags & HIST_FIELD_FL_LOG2)
2329                flags_str = "log2";
2330        else if (hist_field->flags & HIST_FIELD_FL_TIMESTAMP_USECS)
2331                flags_str = "usecs";
2332
2333        return flags_str;
2334}
2335
2336static void expr_field_str(struct hist_field *field, char *expr)
2337{
2338        if (field->flags & HIST_FIELD_FL_VAR_REF)
2339                strcat(expr, "$");
2340
2341        strcat(expr, hist_field_name(field, 0));
2342
2343        if (field->flags && !(field->flags & HIST_FIELD_FL_VAR_REF)) {
2344                const char *flags_str = get_hist_field_flags(field);
2345
2346                if (flags_str) {
2347                        strcat(expr, ".");
2348                        strcat(expr, flags_str);
2349                }
2350        }
2351}
2352
2353static char *expr_str(struct hist_field *field, unsigned int level)
2354{
2355        char *expr;
2356
2357        if (level > 1)
2358                return NULL;
2359
2360        expr = kzalloc(MAX_FILTER_STR_VAL, GFP_KERNEL);
2361        if (!expr)
2362                return NULL;
2363
2364        if (!field->operands[0]) {
2365                expr_field_str(field, expr);
2366                return expr;
2367        }
2368
2369        if (field->operator == FIELD_OP_UNARY_MINUS) {
2370                char *subexpr;
2371
2372                strcat(expr, "-(");
2373                subexpr = expr_str(field->operands[0], ++level);
2374                if (!subexpr) {
2375                        kfree(expr);
2376                        return NULL;
2377                }
2378                strcat(expr, subexpr);
2379                strcat(expr, ")");
2380
2381                kfree(subexpr);
2382
2383                return expr;
2384        }
2385
2386        expr_field_str(field->operands[0], expr);
2387
2388        switch (field->operator) {
2389        case FIELD_OP_MINUS:
2390                strcat(expr, "-");
2391                break;
2392        case FIELD_OP_PLUS:
2393                strcat(expr, "+");
2394                break;
2395        default:
2396                kfree(expr);
2397                return NULL;
2398        }
2399
2400        expr_field_str(field->operands[1], expr);
2401
2402        return expr;
2403}
2404
2405static int contains_operator(char *str)
2406{
2407        enum field_op_id field_op = FIELD_OP_NONE;
2408        char *op;
2409
2410        op = strpbrk(str, "+-");
2411        if (!op)
2412                return FIELD_OP_NONE;
2413
2414        switch (*op) {
2415        case '-':
2416                if (*str == '-')
2417                        field_op = FIELD_OP_UNARY_MINUS;
2418                else
2419                        field_op = FIELD_OP_MINUS;
2420                break;
2421        case '+':
2422                field_op = FIELD_OP_PLUS;
2423                break;
2424        default:
2425                break;
2426        }
2427
2428        return field_op;
2429}
2430
2431static void get_hist_field(struct hist_field *hist_field)
2432{
2433        hist_field->ref++;
2434}
2435
2436static void __destroy_hist_field(struct hist_field *hist_field)
2437{
2438        if (--hist_field->ref > 1)
2439                return;
2440
2441        kfree(hist_field->var.name);
2442        kfree(hist_field->name);
2443        kfree(hist_field->type);
2444
2445        kfree(hist_field);
2446}
2447
2448static void destroy_hist_field(struct hist_field *hist_field,
2449                               unsigned int level)
2450{
2451        unsigned int i;
2452
2453        if (level > 3)
2454                return;
2455
2456        if (!hist_field)
2457                return;
2458
2459        if (hist_field->flags & HIST_FIELD_FL_VAR_REF)
2460                return; /* var refs will be destroyed separately */
2461
2462        for (i = 0; i < HIST_FIELD_OPERANDS_MAX; i++)
2463                destroy_hist_field(hist_field->operands[i], level + 1);
2464
2465        __destroy_hist_field(hist_field);
2466}
2467
2468static struct hist_field *create_hist_field(struct hist_trigger_data *hist_data,
2469                                            struct ftrace_event_field *field,
2470                                            unsigned long flags,
2471                                            char *var_name)
2472{
2473        struct hist_field *hist_field;
2474
2475        if (field && is_function_field(field))
2476                return NULL;
2477
2478        hist_field = kzalloc(sizeof(struct hist_field), GFP_KERNEL);
2479        if (!hist_field)
2480                return NULL;
2481
2482        hist_field->ref = 1;
2483
2484        hist_field->hist_data = hist_data;
2485
2486        if (flags & HIST_FIELD_FL_EXPR || flags & HIST_FIELD_FL_ALIAS)
2487                goto out; /* caller will populate */
2488
2489        if (flags & HIST_FIELD_FL_VAR_REF) {
2490                hist_field->fn = hist_field_var_ref;
2491                goto out;
2492        }
2493
2494        if (flags & HIST_FIELD_FL_HITCOUNT) {
2495                hist_field->fn = hist_field_counter;
2496                hist_field->size = sizeof(u64);
2497                hist_field->type = kstrdup("u64", GFP_KERNEL);
2498                if (!hist_field->type)
2499                        goto free;
2500                goto out;
2501        }
2502
2503        if (flags & HIST_FIELD_FL_STACKTRACE) {
2504                hist_field->fn = hist_field_none;
2505                goto out;
2506        }
2507
2508        if (flags & HIST_FIELD_FL_LOG2) {
2509                unsigned long fl = flags & ~HIST_FIELD_FL_LOG2;
2510                hist_field->fn = hist_field_log2;
2511                hist_field->operands[0] = create_hist_field(hist_data, field, fl, NULL);
2512                hist_field->size = hist_field->operands[0]->size;
2513                hist_field->type = kstrdup(hist_field->operands[0]->type, GFP_KERNEL);
2514                if (!hist_field->type)
2515                        goto free;
2516                goto out;
2517        }
2518
2519        if (flags & HIST_FIELD_FL_TIMESTAMP) {
2520                hist_field->fn = hist_field_timestamp;
2521                hist_field->size = sizeof(u64);
2522                hist_field->type = kstrdup("u64", GFP_KERNEL);
2523                if (!hist_field->type)
2524                        goto free;
2525                goto out;
2526        }
2527
2528        if (flags & HIST_FIELD_FL_CPU) {
2529                hist_field->fn = hist_field_cpu;
2530                hist_field->size = sizeof(int);
2531                hist_field->type = kstrdup("unsigned int", GFP_KERNEL);
2532                if (!hist_field->type)
2533                        goto free;
2534                goto out;
2535        }
2536
2537        if (WARN_ON_ONCE(!field))
2538                goto out;
2539
2540        if (is_string_field(field)) {
2541                flags |= HIST_FIELD_FL_STRING;
2542
2543                hist_field->size = MAX_FILTER_STR_VAL;
2544                hist_field->type = kstrdup(field->type, GFP_KERNEL);
2545                if (!hist_field->type)
2546                        goto free;
2547
2548                if (field->filter_type == FILTER_STATIC_STRING)
2549                        hist_field->fn = hist_field_string;
2550                else if (field->filter_type == FILTER_DYN_STRING)
2551                        hist_field->fn = hist_field_dynstring;
2552                else
2553                        hist_field->fn = hist_field_pstring;
2554        } else {
2555                hist_field->size = field->size;
2556                hist_field->is_signed = field->is_signed;
2557                hist_field->type = kstrdup(field->type, GFP_KERNEL);
2558                if (!hist_field->type)
2559                        goto free;
2560
2561                hist_field->fn = select_value_fn(field->size,
2562                                                 field->is_signed);
2563                if (!hist_field->fn) {
2564                        destroy_hist_field(hist_field, 0);
2565                        return NULL;
2566                }
2567        }
2568 out:
2569        hist_field->field = field;
2570        hist_field->flags = flags;
2571
2572        if (var_name) {
2573                hist_field->var.name = kstrdup(var_name, GFP_KERNEL);
2574                if (!hist_field->var.name)
2575                        goto free;
2576        }
2577
2578        return hist_field;
2579 free:
2580        destroy_hist_field(hist_field, 0);
2581        return NULL;
2582}
2583
2584static void destroy_hist_fields(struct hist_trigger_data *hist_data)
2585{
2586        unsigned int i;
2587
2588        for (i = 0; i < HIST_FIELDS_MAX; i++) {
2589                if (hist_data->fields[i]) {
2590                        destroy_hist_field(hist_data->fields[i], 0);
2591                        hist_data->fields[i] = NULL;
2592                }
2593        }
2594
2595        for (i = 0; i < hist_data->n_var_refs; i++) {
2596                WARN_ON(!(hist_data->var_refs[i]->flags & HIST_FIELD_FL_VAR_REF));
2597                __destroy_hist_field(hist_data->var_refs[i]);
2598                hist_data->var_refs[i] = NULL;
2599        }
2600}
2601
2602static int init_var_ref(struct hist_field *ref_field,
2603                        struct hist_field *var_field,
2604                        char *system, char *event_name)
2605{
2606        int err = 0;
2607
2608        ref_field->var.idx = var_field->var.idx;
2609        ref_field->var.hist_data = var_field->hist_data;
2610        ref_field->size = var_field->size;
2611        ref_field->is_signed = var_field->is_signed;
2612        ref_field->flags |= var_field->flags &
2613                (HIST_FIELD_FL_TIMESTAMP | HIST_FIELD_FL_TIMESTAMP_USECS);
2614
2615        if (system) {
2616                ref_field->system = kstrdup(system, GFP_KERNEL);
2617                if (!ref_field->system)
2618                        return -ENOMEM;
2619        }
2620
2621        if (event_name) {
2622                ref_field->event_name = kstrdup(event_name, GFP_KERNEL);
2623                if (!ref_field->event_name) {
2624                        err = -ENOMEM;
2625                        goto free;
2626                }
2627        }
2628
2629        if (var_field->var.name) {
2630                ref_field->name = kstrdup(var_field->var.name, GFP_KERNEL);
2631                if (!ref_field->name) {
2632                        err = -ENOMEM;
2633                        goto free;
2634                }
2635        } else if (var_field->name) {
2636                ref_field->name = kstrdup(var_field->name, GFP_KERNEL);
2637                if (!ref_field->name) {
2638                        err = -ENOMEM;
2639                        goto free;
2640                }
2641        }
2642
2643        ref_field->type = kstrdup(var_field->type, GFP_KERNEL);
2644        if (!ref_field->type) {
2645                err = -ENOMEM;
2646                goto free;
2647        }
2648 out:
2649        return err;
2650 free:
2651        kfree(ref_field->system);
2652        kfree(ref_field->event_name);
2653        kfree(ref_field->name);
2654
2655        goto out;
2656}
2657
2658/**
2659 * create_var_ref - Create a variable reference and attach it to trigger
2660 * @hist_data: The trigger that will be referencing the variable
2661 * @var_field: The VAR field to create a reference to
2662 * @system: The optional system string
2663 * @event_name: The optional event_name string
2664 *
2665 * Given a variable hist_field, create a VAR_REF hist_field that
2666 * represents a reference to it.
2667 *
2668 * This function also adds the reference to the trigger that
2669 * now references the variable.
2670 *
2671 * Return: The VAR_REF field if successful, NULL if not
2672 */
2673static struct hist_field *create_var_ref(struct hist_trigger_data *hist_data,
2674                                         struct hist_field *var_field,
2675                                         char *system, char *event_name)
2676{
2677        unsigned long flags = HIST_FIELD_FL_VAR_REF;
2678        struct hist_field *ref_field;
2679        int i;
2680
2681        /* Check if the variable already exists */
2682        for (i = 0; i < hist_data->n_var_refs; i++) {
2683                ref_field = hist_data->var_refs[i];
2684                if (ref_field->var.idx == var_field->var.idx &&
2685                    ref_field->var.hist_data == var_field->hist_data) {
2686                        get_hist_field(ref_field);
2687                        return ref_field;
2688                }
2689        }
2690
2691        ref_field = create_hist_field(var_field->hist_data, NULL, flags, NULL);
2692        if (ref_field) {
2693                if (init_var_ref(ref_field, var_field, system, event_name)) {
2694                        destroy_hist_field(ref_field, 0);
2695                        return NULL;
2696                }
2697
2698                hist_data->var_refs[hist_data->n_var_refs] = ref_field;
2699                ref_field->var_ref_idx = hist_data->n_var_refs++;
2700        }
2701
2702        return ref_field;
2703}
2704
2705static bool is_var_ref(char *var_name)
2706{
2707        if (!var_name || strlen(var_name) < 2 || var_name[0] != '$')
2708                return false;
2709
2710        return true;
2711}
2712
2713static char *field_name_from_var(struct hist_trigger_data *hist_data,
2714                                 char *var_name)
2715{
2716        char *name, *field;
2717        unsigned int i;
2718
2719        for (i = 0; i < hist_data->attrs->var_defs.n_vars; i++) {
2720                name = hist_data->attrs->var_defs.name[i];
2721
2722                if (strcmp(var_name, name) == 0) {
2723                        field = hist_data->attrs->var_defs.expr[i];
2724                        if (contains_operator(field) || is_var_ref(field))
2725                                continue;
2726                        return field;
2727                }
2728        }
2729
2730        return NULL;
2731}
2732
2733static char *local_field_var_ref(struct hist_trigger_data *hist_data,
2734                                 char *system, char *event_name,
2735                                 char *var_name)
2736{
2737        struct trace_event_call *call;
2738
2739        if (system && event_name) {
2740                call = hist_data->event_file->event_call;
2741
2742                if (strcmp(system, call->class->system) != 0)
2743                        return NULL;
2744
2745                if (strcmp(event_name, trace_event_name(call)) != 0)
2746                        return NULL;
2747        }
2748
2749        if (!!system != !!event_name)
2750                return NULL;
2751
2752        if (!is_var_ref(var_name))
2753                return NULL;
2754
2755        var_name++;
2756
2757        return field_name_from_var(hist_data, var_name);
2758}
2759
2760static struct hist_field *parse_var_ref(struct hist_trigger_data *hist_data,
2761                                        char *system, char *event_name,
2762                                        char *var_name)
2763{
2764        struct hist_field *var_field = NULL, *ref_field = NULL;
2765        struct trace_array *tr = hist_data->event_file->tr;
2766
2767        if (!is_var_ref(var_name))
2768                return NULL;
2769
2770        var_name++;
2771
2772        var_field = find_event_var(hist_data, system, event_name, var_name);
2773        if (var_field)
2774                ref_field = create_var_ref(hist_data, var_field,
2775                                           system, event_name);
2776
2777        if (!ref_field)
2778                hist_err(tr, HIST_ERR_VAR_NOT_FOUND, errpos(var_name));
2779
2780        return ref_field;
2781}
2782
2783static struct ftrace_event_field *
2784parse_field(struct hist_trigger_data *hist_data, struct trace_event_file *file,
2785            char *field_str, unsigned long *flags)
2786{
2787        struct ftrace_event_field *field = NULL;
2788        char *field_name, *modifier, *str;
2789        struct trace_array *tr = file->tr;
2790
2791        modifier = str = kstrdup(field_str, GFP_KERNEL);
2792        if (!modifier)
2793                return ERR_PTR(-ENOMEM);
2794
2795        field_name = strsep(&modifier, ".");
2796        if (modifier) {
2797                if (strcmp(modifier, "hex") == 0)
2798                        *flags |= HIST_FIELD_FL_HEX;
2799                else if (strcmp(modifier, "sym") == 0)
2800                        *flags |= HIST_FIELD_FL_SYM;
2801                else if (strcmp(modifier, "sym-offset") == 0)
2802                        *flags |= HIST_FIELD_FL_SYM_OFFSET;
2803                else if ((strcmp(modifier, "execname") == 0) &&
2804                         (strcmp(field_name, "common_pid") == 0))
2805                        *flags |= HIST_FIELD_FL_EXECNAME;
2806                else if (strcmp(modifier, "syscall") == 0)
2807                        *flags |= HIST_FIELD_FL_SYSCALL;
2808                else if (strcmp(modifier, "log2") == 0)
2809                        *flags |= HIST_FIELD_FL_LOG2;
2810                else if (strcmp(modifier, "usecs") == 0)
2811                        *flags |= HIST_FIELD_FL_TIMESTAMP_USECS;
2812                else {
2813                        hist_err(tr, HIST_ERR_BAD_FIELD_MODIFIER, errpos(modifier));
2814                        field = ERR_PTR(-EINVAL);
2815                        goto out;
2816                }
2817        }
2818
2819        if (strcmp(field_name, "common_timestamp") == 0) {
2820                *flags |= HIST_FIELD_FL_TIMESTAMP;
2821                hist_data->enable_timestamps = true;
2822                if (*flags & HIST_FIELD_FL_TIMESTAMP_USECS)
2823                        hist_data->attrs->ts_in_usecs = true;
2824        } else if (strcmp(field_name, "cpu") == 0)
2825                *flags |= HIST_FIELD_FL_CPU;
2826        else {
2827                field = trace_find_event_field(file->event_call, field_name);
2828                if (!field || !field->size) {
2829                        hist_err(tr, HIST_ERR_FIELD_NOT_FOUND, errpos(field_name));
2830                        field = ERR_PTR(-EINVAL);
2831                        goto out;
2832                }
2833        }
2834 out:
2835        kfree(str);
2836
2837        return field;
2838}
2839
2840static struct hist_field *create_alias(struct hist_trigger_data *hist_data,
2841                                       struct hist_field *var_ref,
2842                                       char *var_name)
2843{
2844        struct hist_field *alias = NULL;
2845        unsigned long flags = HIST_FIELD_FL_ALIAS | HIST_FIELD_FL_VAR;
2846
2847        alias = create_hist_field(hist_data, NULL, flags, var_name);
2848        if (!alias)
2849                return NULL;
2850
2851        alias->fn = var_ref->fn;
2852        alias->operands[0] = var_ref;
2853
2854        if (init_var_ref(alias, var_ref, var_ref->system, var_ref->event_name)) {
2855                destroy_hist_field(alias, 0);
2856                return NULL;
2857        }
2858
2859        alias->var_ref_idx = var_ref->var_ref_idx;
2860
2861        return alias;
2862}
2863
2864static struct hist_field *parse_atom(struct hist_trigger_data *hist_data,
2865                                     struct trace_event_file *file, char *str,
2866                                     unsigned long *flags, char *var_name)
2867{
2868        char *s, *ref_system = NULL, *ref_event = NULL, *ref_var = str;
2869        struct ftrace_event_field *field = NULL;
2870        struct hist_field *hist_field = NULL;
2871        int ret = 0;
2872
2873        s = strchr(str, '.');
2874        if (s) {
2875                s = strchr(++s, '.');
2876                if (s) {
2877                        ref_system = strsep(&str, ".");
2878                        if (!str) {
2879                                ret = -EINVAL;
2880                                goto out;
2881                        }
2882                        ref_event = strsep(&str, ".");
2883                        if (!str) {
2884                                ret = -EINVAL;
2885                                goto out;
2886                        }
2887                        ref_var = str;
2888                }
2889        }
2890
2891        s = local_field_var_ref(hist_data, ref_system, ref_event, ref_var);
2892        if (!s) {
2893                hist_field = parse_var_ref(hist_data, ref_system,
2894                                           ref_event, ref_var);
2895                if (hist_field) {
2896                        if (var_name) {
2897                                hist_field = create_alias(hist_data, hist_field, var_name);
2898                                if (!hist_field) {
2899                                        ret = -ENOMEM;
2900                                        goto out;
2901                                }
2902                        }
2903                        return hist_field;
2904                }
2905        } else
2906                str = s;
2907
2908        field = parse_field(hist_data, file, str, flags);
2909        if (IS_ERR(field)) {
2910                ret = PTR_ERR(field);
2911                goto out;
2912        }
2913
2914        hist_field = create_hist_field(hist_data, field, *flags, var_name);
2915        if (!hist_field) {
2916                ret = -ENOMEM;
2917                goto out;
2918        }
2919
2920        return hist_field;
2921 out:
2922        return ERR_PTR(ret);
2923}
2924
2925static struct hist_field *parse_expr(struct hist_trigger_data *hist_data,
2926                                     struct trace_event_file *file,
2927                                     char *str, unsigned long flags,
2928                                     char *var_name, unsigned int level);
2929
2930static struct hist_field *parse_unary(struct hist_trigger_data *hist_data,
2931                                      struct trace_event_file *file,
2932                                      char *str, unsigned long flags,
2933                                      char *var_name, unsigned int level)
2934{
2935        struct hist_field *operand1, *expr = NULL;
2936        unsigned long operand_flags;
2937        int ret = 0;
2938        char *s;
2939
2940        /* we support only -(xxx) i.e. explicit parens required */
2941
2942        if (level > 3) {
2943                hist_err(file->tr, HIST_ERR_TOO_MANY_SUBEXPR, errpos(str));
2944                ret = -EINVAL;
2945                goto free;
2946        }
2947
2948        str++; /* skip leading '-' */
2949
2950        s = strchr(str, '(');
2951        if (s)
2952                str++;
2953        else {
2954                ret = -EINVAL;
2955                goto free;
2956        }
2957
2958        s = strrchr(str, ')');
2959        if (s)
2960                *s = '\0';
2961        else {
2962                ret = -EINVAL; /* no closing ')' */
2963                goto free;
2964        }
2965
2966        flags |= HIST_FIELD_FL_EXPR;
2967        expr = create_hist_field(hist_data, NULL, flags, var_name);
2968        if (!expr) {
2969                ret = -ENOMEM;
2970                goto free;
2971        }
2972
2973        operand_flags = 0;
2974        operand1 = parse_expr(hist_data, file, str, operand_flags, NULL, ++level);
2975        if (IS_ERR(operand1)) {
2976                ret = PTR_ERR(operand1);
2977                goto free;
2978        }
2979
2980        expr->flags |= operand1->flags &
2981                (HIST_FIELD_FL_TIMESTAMP | HIST_FIELD_FL_TIMESTAMP_USECS);
2982        expr->fn = hist_field_unary_minus;
2983        expr->operands[0] = operand1;
2984        expr->operator = FIELD_OP_UNARY_MINUS;
2985        expr->name = expr_str(expr, 0);
2986        expr->type = kstrdup(operand1->type, GFP_KERNEL);
2987        if (!expr->type) {
2988                ret = -ENOMEM;
2989                goto free;
2990        }
2991
2992        return expr;
2993 free:
2994        destroy_hist_field(expr, 0);
2995        return ERR_PTR(ret);
2996}
2997
2998static int check_expr_operands(struct trace_array *tr,
2999                               struct hist_field *operand1,
3000                               struct hist_field *operand2)
3001{
3002        unsigned long operand1_flags = operand1->flags;
3003        unsigned long operand2_flags = operand2->flags;
3004
3005        if ((operand1_flags & HIST_FIELD_FL_VAR_REF) ||
3006            (operand1_flags & HIST_FIELD_FL_ALIAS)) {
3007                struct hist_field *var;
3008
3009                var = find_var_field(operand1->var.hist_data, operand1->name);
3010                if (!var)
3011                        return -EINVAL;
3012                operand1_flags = var->flags;
3013        }
3014
3015        if ((operand2_flags & HIST_FIELD_FL_VAR_REF) ||
3016            (operand2_flags & HIST_FIELD_FL_ALIAS)) {
3017                struct hist_field *var;
3018
3019                var = find_var_field(operand2->var.hist_data, operand2->name);
3020                if (!var)
3021                        return -EINVAL;
3022                operand2_flags = var->flags;
3023        }
3024
3025        if ((operand1_flags & HIST_FIELD_FL_TIMESTAMP_USECS) !=
3026            (operand2_flags & HIST_FIELD_FL_TIMESTAMP_USECS)) {
3027                hist_err(tr, HIST_ERR_TIMESTAMP_MISMATCH, 0);
3028                return -EINVAL;
3029        }
3030
3031        return 0;
3032}
3033
3034static struct hist_field *parse_expr(struct hist_trigger_data *hist_data,
3035                                     struct trace_event_file *file,
3036                                     char *str, unsigned long flags,
3037                                     char *var_name, unsigned int level)
3038{
3039        struct hist_field *operand1 = NULL, *operand2 = NULL, *expr = NULL;
3040        unsigned long operand_flags;
3041        int field_op, ret = -EINVAL;
3042        char *sep, *operand1_str;
3043
3044        if (level > 3) {
3045                hist_err(file->tr, HIST_ERR_TOO_MANY_SUBEXPR, errpos(str));
3046                return ERR_PTR(-EINVAL);
3047        }
3048
3049        field_op = contains_operator(str);
3050
3051        if (field_op == FIELD_OP_NONE)
3052                return parse_atom(hist_data, file, str, &flags, var_name);
3053
3054        if (field_op == FIELD_OP_UNARY_MINUS)
3055                return parse_unary(hist_data, file, str, flags, var_name, ++level);
3056
3057        switch (field_op) {
3058        case FIELD_OP_MINUS:
3059                sep = "-";
3060                break;
3061        case FIELD_OP_PLUS:
3062                sep = "+";
3063                break;
3064        default:
3065                goto free;
3066        }
3067
3068        operand1_str = strsep(&str, sep);
3069        if (!operand1_str || !str)
3070                goto free;
3071
3072        operand_flags = 0;
3073        operand1 = parse_atom(hist_data, file, operand1_str,
3074                              &operand_flags, NULL);
3075        if (IS_ERR(operand1)) {
3076                ret = PTR_ERR(operand1);
3077                operand1 = NULL;
3078                goto free;
3079        }
3080
3081        /* rest of string could be another expression e.g. b+c in a+b+c */
3082        operand_flags = 0;
3083        operand2 = parse_expr(hist_data, file, str, operand_flags, NULL, ++level);
3084        if (IS_ERR(operand2)) {
3085                ret = PTR_ERR(operand2);
3086                operand2 = NULL;
3087                goto free;
3088        }
3089
3090        ret = check_expr_operands(file->tr, operand1, operand2);
3091        if (ret)
3092                goto free;
3093
3094        flags |= HIST_FIELD_FL_EXPR;
3095
3096        flags |= operand1->flags &
3097                (HIST_FIELD_FL_TIMESTAMP | HIST_FIELD_FL_TIMESTAMP_USECS);
3098
3099        expr = create_hist_field(hist_data, NULL, flags, var_name);
3100        if (!expr) {
3101                ret = -ENOMEM;
3102                goto free;
3103        }
3104
3105        operand1->read_once = true;
3106        operand2->read_once = true;
3107
3108        expr->operands[0] = operand1;
3109        expr->operands[1] = operand2;
3110        expr->operator = field_op;
3111        expr->name = expr_str(expr, 0);
3112        expr->type = kstrdup(operand1->type, GFP_KERNEL);
3113        if (!expr->type) {
3114                ret = -ENOMEM;
3115                goto free;
3116        }
3117
3118        switch (field_op) {
3119        case FIELD_OP_MINUS:
3120                expr->fn = hist_field_minus;
3121                break;
3122        case FIELD_OP_PLUS:
3123                expr->fn = hist_field_plus;
3124                break;
3125        default:
3126                ret = -EINVAL;
3127                goto free;
3128        }
3129
3130        return expr;
3131 free:
3132        destroy_hist_field(operand1, 0);
3133        destroy_hist_field(operand2, 0);
3134        destroy_hist_field(expr, 0);
3135
3136        return ERR_PTR(ret);
3137}
3138
3139static char *find_trigger_filter(struct hist_trigger_data *hist_data,
3140                                 struct trace_event_file *file)
3141{
3142        struct event_trigger_data *test;
3143
3144        lockdep_assert_held(&event_mutex);
3145
3146        list_for_each_entry(test, &file->triggers, list) {
3147                if (test->cmd_ops->trigger_type == ETT_EVENT_HIST) {
3148                        if (test->private_data == hist_data)
3149                                return test->filter_str;
3150                }
3151        }
3152
3153        return NULL;
3154}
3155
3156static struct event_command trigger_hist_cmd;
3157static int event_hist_trigger_func(struct event_command *cmd_ops,
3158                                   struct trace_event_file *file,
3159                                   char *glob, char *cmd, char *param);
3160
3161static bool compatible_keys(struct hist_trigger_data *target_hist_data,
3162                            struct hist_trigger_data *hist_data,
3163                            unsigned int n_keys)
3164{
3165        struct hist_field *target_hist_field, *hist_field;
3166        unsigned int n, i, j;
3167
3168        if (hist_data->n_fields - hist_data->n_vals != n_keys)
3169                return false;
3170
3171        i = hist_data->n_vals;
3172        j = target_hist_data->n_vals;
3173
3174        for (n = 0; n < n_keys; n++) {
3175                hist_field = hist_data->fields[i + n];
3176                target_hist_field = target_hist_data->fields[j + n];
3177
3178                if (strcmp(hist_field->type, target_hist_field->type) != 0)
3179                        return false;
3180                if (hist_field->size != target_hist_field->size)
3181                        return false;
3182                if (hist_field->is_signed != target_hist_field->is_signed)
3183                        return false;
3184        }
3185
3186        return true;
3187}
3188
3189static struct hist_trigger_data *
3190find_compatible_hist(struct hist_trigger_data *target_hist_data,
3191                     struct trace_event_file *file)
3192{
3193        struct hist_trigger_data *hist_data;
3194        struct event_trigger_data *test;
3195        unsigned int n_keys;
3196
3197        lockdep_assert_held(&event_mutex);
3198
3199        n_keys = target_hist_data->n_fields - target_hist_data->n_vals;
3200
3201        list_for_each_entry(test, &file->triggers, list) {
3202                if (test->cmd_ops->trigger_type == ETT_EVENT_HIST) {
3203                        hist_data = test->private_data;
3204
3205                        if (compatible_keys(target_hist_data, hist_data, n_keys))
3206                                return hist_data;
3207                }
3208        }
3209
3210        return NULL;
3211}
3212
3213static struct trace_event_file *event_file(struct trace_array *tr,
3214                                           char *system, char *event_name)
3215{
3216        struct trace_event_file *file;
3217
3218        file = __find_event_file(tr, system, event_name);
3219        if (!file)
3220                return ERR_PTR(-EINVAL);
3221
3222        return file;
3223}
3224
3225static struct hist_field *
3226find_synthetic_field_var(struct hist_trigger_data *target_hist_data,
3227                         char *system, char *event_name, char *field_name)
3228{
3229        struct hist_field *event_var;
3230        char *synthetic_name;
3231
3232        synthetic_name = kzalloc(MAX_FILTER_STR_VAL, GFP_KERNEL);
3233        if (!synthetic_name)
3234                return ERR_PTR(-ENOMEM);
3235
3236        strcpy(synthetic_name, "synthetic_");
3237        strcat(synthetic_name, field_name);
3238
3239        event_var = find_event_var(target_hist_data, system, event_name, synthetic_name);
3240
3241        kfree(synthetic_name);
3242
3243        return event_var;
3244}
3245
3246/**
3247 * create_field_var_hist - Automatically create a histogram and var for a field
3248 * @target_hist_data: The target hist trigger
3249 * @subsys_name: Optional subsystem name
3250 * @event_name: Optional event name
3251 * @field_name: The name of the field (and the resulting variable)
3252 *
3253 * Hist trigger actions fetch data from variables, not directly from
3254 * events.  However, for convenience, users are allowed to directly
3255 * specify an event field in an action, which will be automatically
3256 * converted into a variable on their behalf.
3257
3258 * If a user specifies a field on an event that isn't the event the
3259 * histogram currently being defined (the target event histogram), the
3260 * only way that can be accomplished is if a new hist trigger is
3261 * created and the field variable defined on that.
3262 *
3263 * This function creates a new histogram compatible with the target
3264 * event (meaning a histogram with the same key as the target
3265 * histogram), and creates a variable for the specified field, but
3266 * with 'synthetic_' prepended to the variable name in order to avoid
3267 * collision with normal field variables.
3268 *
3269 * Return: The variable created for the field.
3270 */
3271static struct hist_field *
3272create_field_var_hist(struct hist_trigger_data *target_hist_data,
3273                      char *subsys_name, char *event_name, char *field_name)
3274{
3275        struct trace_array *tr = target_hist_data->event_file->tr;
3276        struct hist_field *event_var = ERR_PTR(-EINVAL);
3277        struct hist_trigger_data *hist_data;
3278        unsigned int i, n, first = true;
3279        struct field_var_hist *var_hist;
3280        struct trace_event_file *file;
3281        struct hist_field *key_field;
3282        char *saved_filter;
3283        char *cmd;
3284        int ret;
3285
3286        if (target_hist_data->n_field_var_hists >= SYNTH_FIELDS_MAX) {
3287                hist_err(tr, HIST_ERR_TOO_MANY_FIELD_VARS, errpos(field_name));
3288                return ERR_PTR(-EINVAL);
3289        }
3290
3291        file = event_file(tr, subsys_name, event_name);
3292
3293        if (IS_ERR(file)) {
3294                hist_err(tr, HIST_ERR_EVENT_FILE_NOT_FOUND, errpos(field_name));
3295                ret = PTR_ERR(file);
3296                return ERR_PTR(ret);
3297        }
3298
3299        /*
3300         * Look for a histogram compatible with target.  We'll use the
3301         * found histogram specification to create a new matching
3302         * histogram with our variable on it.  target_hist_data is not
3303         * yet a registered histogram so we can't use that.
3304         */
3305        hist_data = find_compatible_hist(target_hist_data, file);
3306        if (!hist_data) {
3307                hist_err(tr, HIST_ERR_HIST_NOT_FOUND, errpos(field_name));
3308                return ERR_PTR(-EINVAL);
3309        }
3310
3311        /* See if a synthetic field variable has already been created */
3312        event_var = find_synthetic_field_var(target_hist_data, subsys_name,
3313                                             event_name, field_name);
3314        if (!IS_ERR_OR_NULL(event_var))
3315                return event_var;
3316
3317        var_hist = kzalloc(sizeof(*var_hist), GFP_KERNEL);
3318        if (!var_hist)
3319                return ERR_PTR(-ENOMEM);
3320
3321        cmd = kzalloc(MAX_FILTER_STR_VAL, GFP_KERNEL);
3322        if (!cmd) {
3323                kfree(var_hist);
3324                return ERR_PTR(-ENOMEM);
3325        }
3326
3327        /* Use the same keys as the compatible histogram */
3328        strcat(cmd, "keys=");
3329
3330        for_each_hist_key_field(i, hist_data) {
3331                key_field = hist_data->fields[i];
3332                if (!first)
3333                        strcat(cmd, ",");
3334                strcat(cmd, key_field->field->name);
3335                first = false;
3336        }
3337
3338        /* Create the synthetic field variable specification */
3339        strcat(cmd, ":synthetic_");
3340        strcat(cmd, field_name);
3341        strcat(cmd, "=");
3342        strcat(cmd, field_name);
3343
3344        /* Use the same filter as the compatible histogram */
3345        saved_filter = find_trigger_filter(hist_data, file);
3346        if (saved_filter) {
3347                strcat(cmd, " if ");
3348                strcat(cmd, saved_filter);
3349        }
3350
3351        var_hist->cmd = kstrdup(cmd, GFP_KERNEL);
3352        if (!var_hist->cmd) {
3353                kfree(cmd);
3354                kfree(var_hist);
3355                return ERR_PTR(-ENOMEM);
3356        }
3357
3358        /* Save the compatible histogram information */
3359        var_hist->hist_data = hist_data;
3360
3361        /* Create the new histogram with our variable */
3362        ret = event_hist_trigger_func(&trigger_hist_cmd, file,
3363                                      "", "hist", cmd);
3364        if (ret) {
3365                kfree(cmd);
3366                kfree(var_hist->cmd);
3367                kfree(var_hist);
3368                hist_err(tr, HIST_ERR_HIST_CREATE_FAIL, errpos(field_name));
3369                return ERR_PTR(ret);
3370        }
3371
3372        kfree(cmd);
3373
3374        /* If we can't find the variable, something went wrong */
3375        event_var = find_synthetic_field_var(target_hist_data, subsys_name,
3376                                             event_name, field_name);
3377        if (IS_ERR_OR_NULL(event_var)) {
3378                kfree(var_hist->cmd);
3379                kfree(var_hist);
3380                hist_err(tr, HIST_ERR_SYNTH_VAR_NOT_FOUND, errpos(field_name));
3381                return ERR_PTR(-EINVAL);
3382        }
3383
3384        n = target_hist_data->n_field_var_hists;
3385        target_hist_data->field_var_hists[n] = var_hist;
3386        target_hist_data->n_field_var_hists++;
3387
3388        return event_var;
3389}
3390
3391static struct hist_field *
3392find_target_event_var(struct hist_trigger_data *hist_data,
3393                      char *subsys_name, char *event_name, char *var_name)
3394{
3395        struct trace_event_file *file = hist_data->event_file;
3396        struct hist_field *hist_field = NULL;
3397
3398        if (subsys_name) {
3399                struct trace_event_call *call;
3400
3401                if (!event_name)
3402                        return NULL;
3403
3404                call = file->event_call;
3405
3406                if (strcmp(subsys_name, call->class->system) != 0)
3407                        return NULL;
3408
3409                if (strcmp(event_name, trace_event_name(call)) != 0)
3410                        return NULL;
3411        }
3412
3413        hist_field = find_var_field(hist_data, var_name);
3414
3415        return hist_field;
3416}
3417
3418static inline void __update_field_vars(struct tracing_map_elt *elt,
3419                                       struct ring_buffer_event *rbe,
3420                                       void *rec,
3421                                       struct field_var **field_vars,
3422                                       unsigned int n_field_vars,
3423                                       unsigned int field_var_str_start)
3424{
3425        struct hist_elt_data *elt_data = elt->private_data;
3426        unsigned int i, j, var_idx;
3427        u64 var_val;
3428
3429        for (i = 0, j = field_var_str_start; i < n_field_vars; i++) {
3430                struct field_var *field_var = field_vars[i];
3431                struct hist_field *var = field_var->var;
3432                struct hist_field *val = field_var->val;
3433
3434                var_val = val->fn(val, elt, rbe, rec);
3435                var_idx = var->var.idx;
3436
3437                if (val->flags & HIST_FIELD_FL_STRING) {
3438                        char *str = elt_data->field_var_str[j++];
3439                        char *val_str = (char *)(uintptr_t)var_val;
3440
3441                        strscpy(str, val_str, STR_VAR_LEN_MAX);
3442                        var_val = (u64)(uintptr_t)str;
3443                }
3444                tracing_map_set_var(elt, var_idx, var_val);
3445        }
3446}
3447
3448static void update_field_vars(struct hist_trigger_data *hist_data,
3449                              struct tracing_map_elt *elt,
3450                              struct ring_buffer_event *rbe,
3451                              void *rec)
3452{
3453        __update_field_vars(elt, rbe, rec, hist_data->field_vars,
3454                            hist_data->n_field_vars, 0);
3455}
3456
3457static void save_track_data_vars(struct hist_trigger_data *hist_data,
3458                                 struct tracing_map_elt *elt, void *rec,
3459                                 struct ring_buffer_event *rbe, void *key,
3460                                 struct action_data *data, u64 *var_ref_vals)
3461{
3462        __update_field_vars(elt, rbe, rec, hist_data->save_vars,
3463                            hist_data->n_save_vars, hist_data->n_field_var_str);
3464}
3465
3466static struct hist_field *create_var(struct hist_trigger_data *hist_data,
3467                                     struct trace_event_file *file,
3468                                     char *name, int size, const char *type)
3469{
3470        struct hist_field *var;
3471        int idx;
3472
3473        if (find_var(hist_data, file, name) && !hist_data->remove) {
3474                var = ERR_PTR(-EINVAL);
3475                goto out;
3476        }
3477
3478        var = kzalloc(sizeof(struct hist_field), GFP_KERNEL);
3479        if (!var) {
3480                var = ERR_PTR(-ENOMEM);
3481                goto out;
3482        }
3483
3484        idx = tracing_map_add_var(hist_data->map);
3485        if (idx < 0) {
3486                kfree(var);
3487                var = ERR_PTR(-EINVAL);
3488                goto out;
3489        }
3490
3491        var->flags = HIST_FIELD_FL_VAR;
3492        var->var.idx = idx;
3493        var->var.hist_data = var->hist_data = hist_data;
3494        var->size = size;
3495        var->var.name = kstrdup(name, GFP_KERNEL);
3496        var->type = kstrdup(type, GFP_KERNEL);
3497        if (!var->var.name || !var->type) {
3498                kfree(var->var.name);
3499                kfree(var->type);
3500                kfree(var);
3501                var = ERR_PTR(-ENOMEM);
3502        }
3503 out:
3504        return var;
3505}
3506
3507static struct field_var *create_field_var(struct hist_trigger_data *hist_data,
3508                                          struct trace_event_file *file,
3509                                          char *field_name)
3510{
3511        struct hist_field *val = NULL, *var = NULL;
3512        unsigned long flags = HIST_FIELD_FL_VAR;
3513        struct trace_array *tr = file->tr;
3514        struct field_var *field_var;
3515        int ret = 0;
3516
3517        if (hist_data->n_field_vars >= SYNTH_FIELDS_MAX) {
3518                hist_err(tr, HIST_ERR_TOO_MANY_FIELD_VARS, errpos(field_name));
3519                ret = -EINVAL;
3520                goto err;
3521        }
3522
3523        val = parse_atom(hist_data, file, field_name, &flags, NULL);
3524        if (IS_ERR(val)) {
3525                hist_err(tr, HIST_ERR_FIELD_VAR_PARSE_FAIL, errpos(field_name));
3526                ret = PTR_ERR(val);
3527                goto err;
3528        }
3529
3530        var = create_var(hist_data, file, field_name, val->size, val->type);
3531        if (IS_ERR(var)) {
3532                hist_err(tr, HIST_ERR_VAR_CREATE_FIND_FAIL, errpos(field_name));
3533                kfree(val);
3534                ret = PTR_ERR(var);
3535                goto err;
3536        }
3537
3538        field_var = kzalloc(sizeof(struct field_var), GFP_KERNEL);
3539        if (!field_var) {
3540                kfree(val);
3541                kfree(var);
3542                ret =  -ENOMEM;
3543                goto err;
3544        }
3545
3546        field_var->var = var;
3547        field_var->val = val;
3548 out:
3549        return field_var;
3550 err:
3551        field_var = ERR_PTR(ret);
3552        goto out;
3553}
3554
3555/**
3556 * create_target_field_var - Automatically create a variable for a field
3557 * @target_hist_data: The target hist trigger
3558 * @subsys_name: Optional subsystem name
3559 * @event_name: Optional event name
3560 * @var_name: The name of the field (and the resulting variable)
3561 *
3562 * Hist trigger actions fetch data from variables, not directly from
3563 * events.  However, for convenience, users are allowed to directly
3564 * specify an event field in an action, which will be automatically
3565 * converted into a variable on their behalf.
3566
3567 * This function creates a field variable with the name var_name on
3568 * the hist trigger currently being defined on the target event.  If
3569 * subsys_name and event_name are specified, this function simply
3570 * verifies that they do in fact match the target event subsystem and
3571 * event name.
3572 *
3573 * Return: The variable created for the field.
3574 */
3575static struct field_var *
3576create_target_field_var(struct hist_trigger_data *target_hist_data,
3577                        char *subsys_name, char *event_name, char *var_name)
3578{
3579        struct trace_event_file *file = target_hist_data->event_file;
3580
3581        if (subsys_name) {
3582                struct trace_event_call *call;
3583
3584                if (!event_name)
3585                        return NULL;
3586
3587                call = file->event_call;
3588
3589                if (strcmp(subsys_name, call->class->system) != 0)
3590                        return NULL;
3591
3592                if (strcmp(event_name, trace_event_name(call)) != 0)
3593                        return NULL;
3594        }
3595
3596        return create_field_var(target_hist_data, file, var_name);
3597}
3598
3599static bool check_track_val_max(u64 track_val, u64 var_val)
3600{
3601        if (var_val <= track_val)
3602                return false;
3603
3604        return true;
3605}
3606
3607static bool check_track_val_changed(u64 track_val, u64 var_val)
3608{
3609        if (var_val == track_val)
3610                return false;
3611
3612        return true;
3613}
3614
3615static u64 get_track_val(struct hist_trigger_data *hist_data,
3616                         struct tracing_map_elt *elt,
3617                         struct action_data *data)
3618{
3619        unsigned int track_var_idx = data->track_data.track_var->var.idx;
3620        u64 track_val;
3621
3622        track_val = tracing_map_read_var(elt, track_var_idx);
3623
3624        return track_val;
3625}
3626
3627static void save_track_val(struct hist_trigger_data *hist_data,
3628                           struct tracing_map_elt *elt,
3629                           struct action_data *data, u64 var_val)
3630{
3631        unsigned int track_var_idx = data->track_data.track_var->var.idx;
3632
3633        tracing_map_set_var(elt, track_var_idx, var_val);
3634}
3635
3636static void save_track_data(struct hist_trigger_data *hist_data,
3637                            struct tracing_map_elt *elt, void *rec,
3638                            struct ring_buffer_event *rbe, void *key,
3639                            struct action_data *data, u64 *var_ref_vals)
3640{
3641        if (data->track_data.save_data)
3642                data->track_data.save_data(hist_data, elt, rec, rbe, key, data, var_ref_vals);
3643}
3644
3645static bool check_track_val(struct tracing_map_elt *elt,
3646                            struct action_data *data,
3647                            u64 var_val)
3648{
3649        struct hist_trigger_data *hist_data;
3650        u64 track_val;
3651
3652        hist_data = data->track_data.track_var->hist_data;
3653        track_val = get_track_val(hist_data, elt, data);
3654
3655        return data->track_data.check_val(track_val, var_val);
3656}
3657
3658#ifdef CONFIG_TRACER_SNAPSHOT
3659static bool cond_snapshot_update(struct trace_array *tr, void *cond_data)
3660{
3661        /* called with tr->max_lock held */
3662        struct track_data *track_data = tr->cond_snapshot->cond_data;
3663        struct hist_elt_data *elt_data, *track_elt_data;
3664        struct snapshot_context *context = cond_data;
3665        struct action_data *action;
3666        u64 track_val;
3667
3668        if (!track_data)
3669                return false;
3670
3671        action = track_data->action_data;
3672
3673        track_val = get_track_val(track_data->hist_data, context->elt,
3674                                  track_data->action_data);
3675
3676        if (!action->track_data.check_val(track_data->track_val, track_val))
3677                return false;
3678
3679        track_data->track_val = track_val;
3680        memcpy(track_data->key, context->key, track_data->key_len);
3681
3682        elt_data = context->elt->private_data;
3683        track_elt_data = track_data->elt.private_data;
3684        if (elt_data->comm)
3685                strncpy(track_elt_data->comm, elt_data->comm, TASK_COMM_LEN);
3686
3687        track_data->updated = true;
3688
3689        return true;
3690}
3691
3692static void save_track_data_snapshot(struct hist_trigger_data *hist_data,
3693                                     struct tracing_map_elt *elt, void *rec,
3694                                     struct ring_buffer_event *rbe, void *key,
3695                                     struct action_data *data,
3696                                     u64 *var_ref_vals)
3697{
3698        struct trace_event_file *file = hist_data->event_file;
3699        struct snapshot_context context;
3700
3701        context.elt = elt;
3702        context.key = key;
3703
3704        tracing_snapshot_cond(file->tr, &context);
3705}
3706
3707static void hist_trigger_print_key(struct seq_file *m,
3708                                   struct hist_trigger_data *hist_data,
3709                                   void *key,
3710                                   struct tracing_map_elt *elt);
3711
3712static struct action_data *snapshot_action(struct hist_trigger_data *hist_data)
3713{
3714        unsigned int i;
3715
3716        if (!hist_data->n_actions)
3717                return NULL;
3718
3719        for (i = 0; i < hist_data->n_actions; i++) {
3720                struct action_data *data = hist_data->actions[i];
3721
3722                if (data->action == ACTION_SNAPSHOT)
3723                        return data;
3724        }
3725
3726        return NULL;
3727}
3728
3729static void track_data_snapshot_print(struct seq_file *m,
3730                                      struct hist_trigger_data *hist_data)
3731{
3732        struct trace_event_file *file = hist_data->event_file;
3733        struct track_data *track_data;
3734        struct action_data *action;
3735
3736        track_data = tracing_cond_snapshot_data(file->tr);
3737        if (!track_data)
3738                return;
3739
3740        if (!track_data->updated)
3741                return;
3742
3743        action = snapshot_action(hist_data);
3744        if (!action)
3745                return;
3746
3747        seq_puts(m, "\nSnapshot taken (see tracing/snapshot).  Details:\n");
3748        seq_printf(m, "\ttriggering value { %s(%s) }: %10llu",
3749                   action->handler == HANDLER_ONMAX ? "onmax" : "onchange",
3750                   action->track_data.var_str, track_data->track_val);
3751
3752        seq_puts(m, "\ttriggered by event with key: ");
3753        hist_trigger_print_key(m, hist_data, track_data->key, &track_data->elt);
3754        seq_putc(m, '\n');
3755}
3756#else
3757static bool cond_snapshot_update(struct trace_array *tr, void *cond_data)
3758{
3759        return false;
3760}
3761static void save_track_data_snapshot(struct hist_trigger_data *hist_data,
3762                                     struct tracing_map_elt *elt, void *rec,
3763                                     struct ring_buffer_event *rbe, void *key,
3764                                     struct action_data *data,
3765                                     u64 *var_ref_vals) {}
3766static void track_data_snapshot_print(struct seq_file *m,
3767                                      struct hist_trigger_data *hist_data) {}
3768#endif /* CONFIG_TRACER_SNAPSHOT */
3769
3770static void track_data_print(struct seq_file *m,
3771                             struct hist_trigger_data *hist_data,
3772                             struct tracing_map_elt *elt,
3773                             struct action_data *data)
3774{
3775        u64 track_val = get_track_val(hist_data, elt, data);
3776        unsigned int i, save_var_idx;
3777
3778        if (data->handler == HANDLER_ONMAX)
3779                seq_printf(m, "\n\tmax: %10llu", track_val);
3780        else if (data->handler == HANDLER_ONCHANGE)
3781                seq_printf(m, "\n\tchanged: %10llu", track_val);
3782
3783        if (data->action == ACTION_SNAPSHOT)
3784                return;
3785
3786        for (i = 0; i < hist_data->n_save_vars; i++) {
3787                struct hist_field *save_val = hist_data->save_vars[i]->val;
3788                struct hist_field *save_var = hist_data->save_vars[i]->var;
3789                u64 val;
3790
3791                save_var_idx = save_var->var.idx;
3792
3793                val = tracing_map_read_var(elt, save_var_idx);
3794
3795                if (save_val->flags & HIST_FIELD_FL_STRING) {
3796                        seq_printf(m, "  %s: %-32s", save_var->var.name,
3797                                   (char *)(uintptr_t)(val));
3798                } else
3799                        seq_printf(m, "  %s: %10llu", save_var->var.name, val);
3800        }
3801}
3802
3803static void ontrack_action(struct hist_trigger_data *hist_data,
3804                           struct tracing_map_elt *elt, void *rec,
3805                           struct ring_buffer_event *rbe, void *key,
3806                           struct action_data *data, u64 *var_ref_vals)
3807{
3808        u64 var_val = var_ref_vals[data->track_data.var_ref->var_ref_idx];
3809
3810        if (check_track_val(elt, data, var_val)) {
3811                save_track_val(hist_data, elt, data, var_val);
3812                save_track_data(hist_data, elt, rec, rbe, key, data, var_ref_vals);
3813        }
3814}
3815
3816static void action_data_destroy(struct action_data *data)
3817{
3818        unsigned int i;
3819
3820        lockdep_assert_held(&event_mutex);
3821
3822        kfree(data->action_name);
3823
3824        for (i = 0; i < data->n_params; i++)
3825                kfree(data->params[i]);
3826
3827        if (data->synth_event)
3828                data->synth_event->ref--;
3829
3830        kfree(data->synth_event_name);
3831
3832        kfree(data);
3833}
3834
3835static void track_data_destroy(struct hist_trigger_data *hist_data,
3836                               struct action_data *data)
3837{
3838        struct trace_event_file *file = hist_data->event_file;
3839
3840        destroy_hist_field(data->track_data.track_var, 0);
3841
3842        if (data->action == ACTION_SNAPSHOT) {
3843                struct track_data *track_data;
3844
3845                track_data = tracing_cond_snapshot_data(file->tr);
3846                if (track_data && track_data->hist_data == hist_data) {
3847                        tracing_snapshot_cond_disable(file->tr);
3848                        track_data_free(track_data);
3849                }
3850        }
3851
3852        kfree(data->track_data.var_str);
3853
3854        action_data_destroy(data);
3855}
3856
3857static int action_create(struct hist_trigger_data *hist_data,
3858                         struct action_data *data);
3859
3860static int track_data_create(struct hist_trigger_data *hist_data,
3861                             struct action_data *data)
3862{
3863        struct hist_field *var_field, *ref_field, *track_var = NULL;
3864        struct trace_event_file *file = hist_data->event_file;
3865        struct trace_array *tr = file->tr;
3866        char *track_data_var_str;
3867        int ret = 0;
3868
3869        track_data_var_str = data->track_data.var_str;
3870        if (track_data_var_str[0] != '$') {
3871                hist_err(tr, HIST_ERR_ONX_NOT_VAR, errpos(track_data_var_str));
3872                return -EINVAL;
3873        }
3874        track_data_var_str++;
3875
3876        var_field = find_target_event_var(hist_data, NULL, NULL, track_data_var_str);
3877        if (!var_field) {
3878                hist_err(tr, HIST_ERR_ONX_VAR_NOT_FOUND, errpos(track_data_var_str));
3879                return -EINVAL;
3880        }
3881
3882        ref_field = create_var_ref(hist_data, var_field, NULL, NULL);
3883        if (!ref_field)
3884                return -ENOMEM;
3885
3886        data->track_data.var_ref = ref_field;
3887
3888        if (data->handler == HANDLER_ONMAX)
3889                track_var = create_var(hist_data, file, "__max", sizeof(u64), "u64");
3890        if (IS_ERR(track_var)) {
3891                hist_err(tr, HIST_ERR_ONX_VAR_CREATE_FAIL, 0);
3892                ret = PTR_ERR(track_var);
3893                goto out;
3894        }
3895
3896        if (data->handler == HANDLER_ONCHANGE)
3897                track_var = create_var(hist_data, file, "__change", sizeof(u64), "u64");
3898        if (IS_ERR(track_var)) {
3899                hist_err(tr, HIST_ERR_ONX_VAR_CREATE_FAIL, 0);
3900                ret = PTR_ERR(track_var);
3901                goto out;
3902        }
3903        data->track_data.track_var = track_var;
3904
3905        ret = action_create(hist_data, data);
3906 out:
3907        return ret;
3908}
3909
3910static int parse_action_params(struct trace_array *tr, char *params,
3911                               struct action_data *data)
3912{
3913        char *param, *saved_param;
3914        bool first_param = true;
3915        int ret = 0;
3916
3917        while (params) {
3918                if (data->n_params >= SYNTH_FIELDS_MAX) {
3919                        hist_err(tr, HIST_ERR_TOO_MANY_PARAMS, 0);
3920                        goto out;
3921                }
3922
3923                param = strsep(&params, ",");
3924                if (!param) {
3925                        hist_err(tr, HIST_ERR_PARAM_NOT_FOUND, 0);
3926                        ret = -EINVAL;
3927                        goto out;
3928                }
3929
3930                param = strstrip(param);
3931                if (strlen(param) < 2) {
3932                        hist_err(tr, HIST_ERR_INVALID_PARAM, errpos(param));
3933                        ret = -EINVAL;
3934                        goto out;
3935                }
3936
3937                saved_param = kstrdup(param, GFP_KERNEL);
3938                if (!saved_param) {
3939                        ret = -ENOMEM;
3940                        goto out;
3941                }
3942
3943                if (first_param && data->use_trace_keyword) {
3944                        data->synth_event_name = saved_param;
3945                        first_param = false;
3946                        continue;
3947                }
3948                first_param = false;
3949
3950                data->params[data->n_params++] = saved_param;
3951        }
3952 out:
3953        return ret;
3954}
3955
3956static int action_parse(struct trace_array *tr, char *str, struct action_data *data,
3957                        enum handler_id handler)
3958{
3959        char *action_name;
3960        int ret = 0;
3961
3962        strsep(&str, ".");
3963        if (!str) {
3964                hist_err(tr, HIST_ERR_ACTION_NOT_FOUND, 0);
3965                ret = -EINVAL;
3966                goto out;
3967        }
3968
3969        action_name = strsep(&str, "(");
3970        if (!action_name || !str) {
3971                hist_err(tr, HIST_ERR_ACTION_NOT_FOUND, 0);
3972                ret = -EINVAL;
3973                goto out;
3974        }
3975
3976        if (str_has_prefix(action_name, "save")) {
3977                char *params = strsep(&str, ")");
3978
3979                if (!params) {
3980                        hist_err(tr, HIST_ERR_NO_SAVE_PARAMS, 0);
3981                        ret = -EINVAL;
3982                        goto out;
3983                }
3984
3985                ret = parse_action_params(tr, params, data);
3986                if (ret)
3987                        goto out;
3988
3989                if (handler == HANDLER_ONMAX)
3990                        data->track_data.check_val = check_track_val_max;
3991                else if (handler == HANDLER_ONCHANGE)
3992                        data->track_data.check_val = check_track_val_changed;
3993                else {
3994                        hist_err(tr, HIST_ERR_ACTION_MISMATCH, errpos(action_name));
3995                        ret = -EINVAL;
3996                        goto out;
3997                }
3998
3999                data->track_data.save_data = save_track_data_vars;
4000                data->fn = ontrack_action;
4001                data->action = ACTION_SAVE;
4002        } else if (str_has_prefix(action_name, "snapshot")) {
4003                char *params = strsep(&str, ")");
4004
4005                if (!str) {
4006                        hist_err(tr, HIST_ERR_NO_CLOSING_PAREN, errpos(params));
4007                        ret = -EINVAL;
4008                        goto out;
4009                }
4010
4011                if (handler == HANDLER_ONMAX)
4012                        data->track_data.check_val = check_track_val_max;
4013                else if (handler == HANDLER_ONCHANGE)
4014                        data->track_data.check_val = check_track_val_changed;
4015                else {
4016                        hist_err(tr, HIST_ERR_ACTION_MISMATCH, errpos(action_name));
4017                        ret = -EINVAL;
4018                        goto out;
4019                }
4020
4021                data->track_data.save_data = save_track_data_snapshot;
4022                data->fn = ontrack_action;
4023                data->action = ACTION_SNAPSHOT;
4024        } else {
4025                char *params = strsep(&str, ")");
4026
4027                if (str_has_prefix(action_name, "trace"))
4028                        data->use_trace_keyword = true;
4029
4030                if (params) {
4031                        ret = parse_action_params(tr, params, data);
4032                        if (ret)
4033                                goto out;
4034                }
4035
4036                if (handler == HANDLER_ONMAX)
4037                        data->track_data.check_val = check_track_val_max;
4038                else if (handler == HANDLER_ONCHANGE)
4039                        data->track_data.check_val = check_track_val_changed;
4040
4041                if (handler != HANDLER_ONMATCH) {
4042                        data->track_data.save_data = action_trace;
4043                        data->fn = ontrack_action;
4044                } else
4045                        data->fn = action_trace;
4046
4047                data->action = ACTION_TRACE;
4048        }
4049
4050        data->action_name = kstrdup(action_name, GFP_KERNEL);
4051        if (!data->action_name) {
4052                ret = -ENOMEM;
4053                goto out;
4054        }
4055
4056        data->handler = handler;
4057 out:
4058        return ret;
4059}
4060
4061static struct action_data *track_data_parse(struct hist_trigger_data *hist_data,
4062                                            char *str, enum handler_id handler)
4063{
4064        struct action_data *data;
4065        int ret = -EINVAL;
4066        char *var_str;
4067
4068        data = kzalloc(sizeof(*data), GFP_KERNEL);
4069        if (!data)
4070                return ERR_PTR(-ENOMEM);
4071
4072        var_str = strsep(&str, ")");
4073        if (!var_str || !str) {
4074                ret = -EINVAL;
4075                goto free;
4076        }
4077
4078        data->track_data.var_str = kstrdup(var_str, GFP_KERNEL);
4079        if (!data->track_data.var_str) {
4080                ret = -ENOMEM;
4081                goto free;
4082        }
4083
4084        ret = action_parse(hist_data->event_file->tr, str, data, handler);
4085        if (ret)
4086                goto free;
4087 out:
4088        return data;
4089 free:
4090        track_data_destroy(hist_data, data);
4091        data = ERR_PTR(ret);
4092        goto out;
4093}
4094
4095static void onmatch_destroy(struct action_data *data)
4096{
4097        kfree(data->match_data.event);
4098        kfree(data->match_data.event_system);
4099
4100        action_data_destroy(data);
4101}
4102
4103static void destroy_field_var(struct field_var *field_var)
4104{
4105        if (!field_var)
4106                return;
4107
4108        destroy_hist_field(field_var->var, 0);
4109        destroy_hist_field(field_var->val, 0);
4110
4111        kfree(field_var);
4112}
4113
4114static void destroy_field_vars(struct hist_trigger_data *hist_data)
4115{
4116        unsigned int i;
4117
4118        for (i = 0; i < hist_data->n_field_vars; i++)
4119                destroy_field_var(hist_data->field_vars[i]);
4120}
4121
4122static void save_field_var(struct hist_trigger_data *hist_data,
4123                           struct field_var *field_var)
4124{
4125        hist_data->field_vars[hist_data->n_field_vars++] = field_var;
4126
4127        if (field_var->val->flags & HIST_FIELD_FL_STRING)
4128                hist_data->n_field_var_str++;
4129}
4130
4131
4132static int check_synth_field(struct synth_event *event,
4133                             struct hist_field *hist_field,
4134                             unsigned int field_pos)
4135{
4136        struct synth_field *field;
4137
4138        if (field_pos >= event->n_fields)
4139                return -EINVAL;
4140
4141        field = event->fields[field_pos];
4142
4143        if (strcmp(field->type, hist_field->type) != 0)
4144                return -EINVAL;
4145
4146        return 0;
4147}
4148
4149static struct hist_field *
4150trace_action_find_var(struct hist_trigger_data *hist_data,
4151                      struct action_data *data,
4152                      char *system, char *event, char *var)
4153{
4154        struct trace_array *tr = hist_data->event_file->tr;
4155        struct hist_field *hist_field;
4156
4157        var++; /* skip '$' */
4158
4159        hist_field = find_target_event_var(hist_data, system, event, var);
4160        if (!hist_field) {
4161                if (!system && data->handler == HANDLER_ONMATCH) {
4162                        system = data->match_data.event_system;
4163                        event = data->match_data.event;
4164                }
4165
4166                hist_field = find_event_var(hist_data, system, event, var);
4167        }
4168
4169        if (!hist_field)
4170                hist_err(tr, HIST_ERR_PARAM_NOT_FOUND, errpos(var));
4171
4172        return hist_field;
4173}
4174
4175static struct hist_field *
4176trace_action_create_field_var(struct hist_trigger_data *hist_data,
4177                              struct action_data *data, char *system,
4178                              char *event, char *var)
4179{
4180        struct hist_field *hist_field = NULL;
4181        struct field_var *field_var;
4182
4183        /*
4184         * First try to create a field var on the target event (the
4185         * currently being defined).  This will create a variable for
4186         * unqualified fields on the target event, or if qualified,
4187         * target fields that have qualified names matching the target.
4188         */
4189        field_var = create_target_field_var(hist_data, system, event, var);
4190
4191        if (field_var && !IS_ERR(field_var)) {
4192                save_field_var(hist_data, field_var);
4193                hist_field = field_var->var;
4194        } else {
4195                field_var = NULL;
4196                /*
4197                 * If no explicit system.event is specfied, default to
4198                 * looking for fields on the onmatch(system.event.xxx)
4199                 * event.
4200                 */
4201                if (!system && data->handler == HANDLER_ONMATCH) {
4202                        system = data->match_data.event_system;
4203                        event = data->match_data.event;
4204                }
4205
4206                /*
4207                 * At this point, we're looking at a field on another
4208                 * event.  Because we can't modify a hist trigger on
4209                 * another event to add a variable for a field, we need
4210                 * to create a new trigger on that event and create the
4211                 * variable at the same time.
4212                 */
4213                hist_field = create_field_var_hist(hist_data, system, event, var);
4214                if (IS_ERR(hist_field))
4215                        goto free;
4216        }
4217 out:
4218        return hist_field;
4219 free:
4220        destroy_field_var(field_var);
4221        hist_field = NULL;
4222        goto out;
4223}
4224
4225static int trace_action_create(struct hist_trigger_data *hist_data,
4226                               struct action_data *data)
4227{
4228        struct trace_array *tr = hist_data->event_file->tr;
4229        char *event_name, *param, *system = NULL;
4230        struct hist_field *hist_field, *var_ref;
4231        unsigned int i, var_ref_idx;
4232        unsigned int field_pos = 0;
4233        struct synth_event *event;
4234        char *synth_event_name;
4235        int ret = 0;
4236
4237        lockdep_assert_held(&event_mutex);
4238
4239        if (data->use_trace_keyword)
4240                synth_event_name = data->synth_event_name;
4241        else
4242                synth_event_name = data->action_name;
4243
4244        event = find_synth_event(synth_event_name);
4245        if (!event) {
4246                hist_err(tr, HIST_ERR_SYNTH_EVENT_NOT_FOUND, errpos(synth_event_name));
4247                return -EINVAL;
4248        }
4249
4250        event->ref++;
4251
4252        var_ref_idx = hist_data->n_var_refs;
4253
4254        for (i = 0; i < data->n_params; i++) {
4255                char *p;
4256
4257                p = param = kstrdup(data->params[i], GFP_KERNEL);
4258                if (!param) {
4259                        ret = -ENOMEM;
4260                        goto err;
4261                }
4262
4263                system = strsep(&param, ".");
4264                if (!param) {
4265                        param = (char *)system;
4266                        system = event_name = NULL;
4267                } else {
4268                        event_name = strsep(&param, ".");
4269                        if (!param) {
4270                                kfree(p);
4271                                ret = -EINVAL;
4272                                goto err;
4273                        }
4274                }
4275
4276                if (param[0] == '$')
4277                        hist_field = trace_action_find_var(hist_data, data,
4278                                                           system, event_name,
4279                                                           param);
4280                else
4281                        hist_field = trace_action_create_field_var(hist_data,
4282                                                                   data,
4283                                                                   system,
4284                                                                   event_name,
4285                                                                   param);
4286
4287                if (!hist_field) {
4288                        kfree(p);
4289                        ret = -EINVAL;
4290                        goto err;
4291                }
4292
4293                if (check_synth_field(event, hist_field, field_pos) == 0) {
4294                        var_ref = create_var_ref(hist_data, hist_field,
4295                                                 system, event_name);
4296                        if (!var_ref) {
4297                                kfree(p);
4298                                ret = -ENOMEM;
4299                                goto err;
4300                        }
4301
4302                        field_pos++;
4303                        kfree(p);
4304                        continue;
4305                }
4306
4307                hist_err(tr, HIST_ERR_SYNTH_TYPE_MISMATCH, errpos(param));
4308                kfree(p);
4309                ret = -EINVAL;
4310                goto err;
4311        }
4312
4313        if (field_pos != event->n_fields) {
4314                hist_err(tr, HIST_ERR_SYNTH_COUNT_MISMATCH, errpos(event->name));
4315                ret = -EINVAL;
4316                goto err;
4317        }
4318
4319        data->synth_event = event;
4320        data->var_ref_idx = var_ref_idx;
4321 out:
4322        return ret;
4323 err:
4324        event->ref--;
4325
4326        goto out;
4327}
4328
4329static int action_create(struct hist_trigger_data *hist_data,
4330                         struct action_data *data)
4331{
4332        struct trace_event_file *file = hist_data->event_file;
4333        struct trace_array *tr = file->tr;
4334        struct track_data *track_data;
4335        struct field_var *field_var;
4336        unsigned int i;
4337        char *param;
4338        int ret = 0;
4339
4340        if (data->action == ACTION_TRACE)
4341                return trace_action_create(hist_data, data);
4342
4343        if (data->action == ACTION_SNAPSHOT) {
4344                track_data = track_data_alloc(hist_data->key_size, data, hist_data);
4345                if (IS_ERR(track_data)) {
4346                        ret = PTR_ERR(track_data);
4347                        goto out;
4348                }
4349
4350                ret = tracing_snapshot_cond_enable(file->tr, track_data,
4351                                                   cond_snapshot_update);
4352                if (ret)
4353                        track_data_free(track_data);
4354
4355                goto out;
4356        }
4357
4358        if (data->action == ACTION_SAVE) {
4359                if (hist_data->n_save_vars) {
4360                        ret = -EEXIST;
4361                        hist_err(tr, HIST_ERR_TOO_MANY_SAVE_ACTIONS, 0);
4362                        goto out;
4363                }
4364
4365                for (i = 0; i < data->n_params; i++) {
4366                        param = kstrdup(data->params[i], GFP_KERNEL);
4367                        if (!param) {
4368                                ret = -ENOMEM;
4369                                goto out;
4370                        }
4371
4372                        field_var = create_target_field_var(hist_data, NULL, NULL, param);
4373                        if (IS_ERR(field_var)) {
4374                                hist_err(tr, HIST_ERR_FIELD_VAR_CREATE_FAIL,
4375                                         errpos(param));
4376                                ret = PTR_ERR(field_var);
4377                                kfree(param);
4378                                goto out;
4379                        }
4380
4381                        hist_data->save_vars[hist_data->n_save_vars++] = field_var;
4382                        if (field_var->val->flags & HIST_FIELD_FL_STRING)
4383                                hist_data->n_save_var_str++;
4384                        kfree(param);
4385                }
4386        }
4387 out:
4388        return ret;
4389}
4390
4391static int onmatch_create(struct hist_trigger_data *hist_data,
4392                          struct action_data *data)
4393{
4394        return action_create(hist_data, data);
4395}
4396
4397static struct action_data *onmatch_parse(struct trace_array *tr, char *str)
4398{
4399        char *match_event, *match_event_system;
4400        struct action_data *data;
4401        int ret = -EINVAL;
4402
4403        data = kzalloc(sizeof(*data), GFP_KERNEL);
4404        if (!data)
4405                return ERR_PTR(-ENOMEM);
4406
4407        match_event = strsep(&str, ")");
4408        if (!match_event || !str) {
4409                hist_err(tr, HIST_ERR_NO_CLOSING_PAREN, errpos(match_event));
4410                goto free;
4411        }
4412
4413        match_event_system = strsep(&match_event, ".");
4414        if (!match_event) {
4415                hist_err(tr, HIST_ERR_SUBSYS_NOT_FOUND, errpos(match_event_system));
4416                goto free;
4417        }
4418
4419        if (IS_ERR(event_file(tr, match_event_system, match_event))) {
4420                hist_err(tr, HIST_ERR_INVALID_SUBSYS_EVENT, errpos(match_event));
4421                goto free;
4422        }
4423
4424        data->match_data.event = kstrdup(match_event, GFP_KERNEL);
4425        if (!data->match_data.event) {
4426                ret = -ENOMEM;
4427                goto free;
4428        }
4429
4430        data->match_data.event_system = kstrdup(match_event_system, GFP_KERNEL);
4431        if (!data->match_data.event_system) {
4432                ret = -ENOMEM;
4433                goto free;
4434        }
4435
4436        ret = action_parse(tr, str, data, HANDLER_ONMATCH);
4437        if (ret)
4438                goto free;
4439 out:
4440        return data;
4441 free:
4442        onmatch_destroy(data);
4443        data = ERR_PTR(ret);
4444        goto out;
4445}
4446
4447static int create_hitcount_val(struct hist_trigger_data *hist_data)
4448{
4449        hist_data->fields[HITCOUNT_IDX] =
4450                create_hist_field(hist_data, NULL, HIST_FIELD_FL_HITCOUNT, NULL);
4451        if (!hist_data->fields[HITCOUNT_IDX])
4452                return -ENOMEM;
4453
4454        hist_data->n_vals++;
4455        hist_data->n_fields++;
4456
4457        if (WARN_ON(hist_data->n_vals > TRACING_MAP_VALS_MAX))
4458                return -EINVAL;
4459
4460        return 0;
4461}
4462
4463static int __create_val_field(struct hist_trigger_data *hist_data,
4464                              unsigned int val_idx,
4465                              struct trace_event_file *file,
4466                              char *var_name, char *field_str,
4467                              unsigned long flags)
4468{
4469        struct hist_field *hist_field;
4470        int ret = 0;
4471
4472        hist_field = parse_expr(hist_data, file, field_str, flags, var_name, 0);
4473        if (IS_ERR(hist_field)) {
4474                ret = PTR_ERR(hist_field);
4475                goto out;
4476        }
4477
4478        hist_data->fields[val_idx] = hist_field;
4479
4480        ++hist_data->n_vals;
4481        ++hist_data->n_fields;
4482
4483        if (WARN_ON(hist_data->n_vals > TRACING_MAP_VALS_MAX + TRACING_MAP_VARS_MAX))
4484                ret = -EINVAL;
4485 out:
4486        return ret;
4487}
4488
4489static int create_val_field(struct hist_trigger_data *hist_data,
4490                            unsigned int val_idx,
4491                            struct trace_event_file *file,
4492                            char *field_str)
4493{
4494        if (WARN_ON(val_idx >= TRACING_MAP_VALS_MAX))
4495                return -EINVAL;
4496
4497        return __create_val_field(hist_data, val_idx, file, NULL, field_str, 0);
4498}
4499
4500static int create_var_field(struct hist_trigger_data *hist_data,
4501                            unsigned int val_idx,
4502                            struct trace_event_file *file,
4503                            char *var_name, char *expr_str)
4504{
4505        struct trace_array *tr = hist_data->event_file->tr;
4506        unsigned long flags = 0;
4507
4508        if (WARN_ON(val_idx >= TRACING_MAP_VALS_MAX + TRACING_MAP_VARS_MAX))
4509                return -EINVAL;
4510
4511        if (find_var(hist_data, file, var_name) && !hist_data->remove) {
4512                hist_err(tr, HIST_ERR_DUPLICATE_VAR, errpos(var_name));
4513                return -EINVAL;
4514        }
4515
4516        flags |= HIST_FIELD_FL_VAR;
4517        hist_data->n_vars++;
4518        if (WARN_ON(hist_data->n_vars > TRACING_MAP_VARS_MAX))
4519                return -EINVAL;
4520
4521        return __create_val_field(hist_data, val_idx, file, var_name, expr_str, flags);
4522}
4523
4524static int create_val_fields(struct hist_trigger_data *hist_data,
4525                             struct trace_event_file *file)
4526{
4527        char *fields_str, *field_str;
4528        unsigned int i, j = 1;
4529        int ret;
4530
4531        ret = create_hitcount_val(hist_data);
4532        if (ret)
4533                goto out;
4534
4535        fields_str = hist_data->attrs->vals_str;
4536        if (!fields_str)
4537                goto out;
4538
4539        strsep(&fields_str, "=");
4540        if (!fields_str)
4541                goto out;
4542
4543        for (i = 0, j = 1; i < TRACING_MAP_VALS_MAX &&
4544                     j < TRACING_MAP_VALS_MAX; i++) {
4545                field_str = strsep(&fields_str, ",");
4546                if (!field_str)
4547                        break;
4548
4549                if (strcmp(field_str, "hitcount") == 0)
4550                        continue;
4551
4552                ret = create_val_field(hist_data, j++, file, field_str);
4553                if (ret)
4554                        goto out;
4555        }
4556
4557        if (fields_str && (strcmp(fields_str, "hitcount") != 0))
4558                ret = -EINVAL;
4559 out:
4560        return ret;
4561}
4562
4563static int create_key_field(struct hist_trigger_data *hist_data,
4564                            unsigned int key_idx,
4565                            unsigned int key_offset,
4566                            struct trace_event_file *file,
4567                            char *field_str)
4568{
4569        struct trace_array *tr = hist_data->event_file->tr;
4570        struct hist_field *hist_field = NULL;
4571        unsigned long flags = 0;
4572        unsigned int key_size;
4573        int ret = 0;
4574
4575        if (WARN_ON(key_idx >= HIST_FIELDS_MAX))
4576                return -EINVAL;
4577
4578        flags |= HIST_FIELD_FL_KEY;
4579
4580        if (strcmp(field_str, "stacktrace") == 0) {
4581                flags |= HIST_FIELD_FL_STACKTRACE;
4582                key_size = sizeof(unsigned long) * HIST_STACKTRACE_DEPTH;
4583                hist_field = create_hist_field(hist_data, NULL, flags, NULL);
4584        } else {
4585                hist_field = parse_expr(hist_data, file, field_str, flags,
4586                                        NULL, 0);
4587                if (IS_ERR(hist_field)) {
4588                        ret = PTR_ERR(hist_field);
4589                        goto out;
4590                }
4591
4592                if (field_has_hist_vars(hist_field, 0)) {
4593                        hist_err(tr, HIST_ERR_INVALID_REF_KEY, errpos(field_str));
4594                        destroy_hist_field(hist_field, 0);
4595                        ret = -EINVAL;
4596                        goto out;
4597                }
4598
4599                key_size = hist_field->size;
4600        }
4601
4602        hist_data->fields[key_idx] = hist_field;
4603
4604        key_size = ALIGN(key_size, sizeof(u64));
4605        hist_data->fields[key_idx]->size = key_size;
4606        hist_data->fields[key_idx]->offset = key_offset;
4607
4608        hist_data->key_size += key_size;
4609
4610        if (hist_data->key_size > HIST_KEY_SIZE_MAX) {
4611                ret = -EINVAL;
4612                goto out;
4613        }
4614
4615        hist_data->n_keys++;
4616        hist_data->n_fields++;
4617
4618        if (WARN_ON(hist_data->n_keys > TRACING_MAP_KEYS_MAX))
4619                return -EINVAL;
4620
4621        ret = key_size;
4622 out:
4623        return ret;
4624}
4625
4626static int create_key_fields(struct hist_trigger_data *hist_data,
4627                             struct trace_event_file *file)
4628{
4629        unsigned int i, key_offset = 0, n_vals = hist_data->n_vals;
4630        char *fields_str, *field_str;
4631        int ret = -EINVAL;
4632
4633        fields_str = hist_data->attrs->keys_str;
4634        if (!fields_str)
4635                goto out;
4636
4637        strsep(&fields_str, "=");
4638        if (!fields_str)
4639                goto out;
4640
4641        for (i = n_vals; i < n_vals + TRACING_MAP_KEYS_MAX; i++) {
4642                field_str = strsep(&fields_str, ",");
4643                if (!field_str)
4644                        break;
4645                ret = create_key_field(hist_data, i, key_offset,
4646                                       file, field_str);
4647                if (ret < 0)
4648                        goto out;
4649                key_offset += ret;
4650        }
4651        if (fields_str) {
4652                ret = -EINVAL;
4653                goto out;
4654        }
4655        ret = 0;
4656 out:
4657        return ret;
4658}
4659
4660static int create_var_fields(struct hist_trigger_data *hist_data,
4661                             struct trace_event_file *file)
4662{
4663        unsigned int i, j = hist_data->n_vals;
4664        int ret = 0;
4665
4666        unsigned int n_vars = hist_data->attrs->var_defs.n_vars;
4667
4668        for (i = 0; i < n_vars; i++) {
4669                char *var_name = hist_data->attrs->var_defs.name[i];
4670                char *expr = hist_data->attrs->var_defs.expr[i];
4671
4672                ret = create_var_field(hist_data, j++, file, var_name, expr);
4673                if (ret)
4674                        goto out;
4675        }
4676 out:
4677        return ret;
4678}
4679
4680static void free_var_defs(struct hist_trigger_data *hist_data)
4681{
4682        unsigned int i;
4683
4684        for (i = 0; i < hist_data->attrs->var_defs.n_vars; i++) {
4685                kfree(hist_data->attrs->var_defs.name[i]);
4686                kfree(hist_data->attrs->var_defs.expr[i]);
4687        }
4688
4689        hist_data->attrs->var_defs.n_vars = 0;
4690}
4691
4692static int parse_var_defs(struct hist_trigger_data *hist_data)
4693{
4694        struct trace_array *tr = hist_data->event_file->tr;
4695        char *s, *str, *var_name, *field_str;
4696        unsigned int i, j, n_vars = 0;
4697        int ret = 0;
4698
4699        for (i = 0; i < hist_data->attrs->n_assignments; i++) {
4700                str = hist_data->attrs->assignment_str[i];
4701                for (j = 0; j < TRACING_MAP_VARS_MAX; j++) {
4702                        field_str = strsep(&str, ",");
4703                        if (!field_str)
4704                                break;
4705
4706                        var_name = strsep(&field_str, "=");
4707                        if (!var_name || !field_str) {
4708                                hist_err(tr, HIST_ERR_MALFORMED_ASSIGNMENT,
4709                                         errpos(var_name));
4710                                ret = -EINVAL;
4711                                goto free;
4712                        }
4713
4714                        if (n_vars == TRACING_MAP_VARS_MAX) {
4715                                hist_err(tr, HIST_ERR_TOO_MANY_VARS, errpos(var_name));
4716                                ret = -EINVAL;
4717                                goto free;
4718                        }
4719
4720                        s = kstrdup(var_name, GFP_KERNEL);
4721                        if (!s) {
4722                                ret = -ENOMEM;
4723                                goto free;
4724                        }
4725                        hist_data->attrs->var_defs.name[n_vars] = s;
4726
4727                        s = kstrdup(field_str, GFP_KERNEL);
4728                        if (!s) {
4729                                kfree(hist_data->attrs->var_defs.name[n_vars]);
4730                                ret = -ENOMEM;
4731                                goto free;
4732                        }
4733                        hist_data->attrs->var_defs.expr[n_vars++] = s;
4734
4735                        hist_data->attrs->var_defs.n_vars = n_vars;
4736                }
4737        }
4738
4739        return ret;
4740 free:
4741        free_var_defs(hist_data);
4742
4743        return ret;
4744}
4745
4746static int create_hist_fields(struct hist_trigger_data *hist_data,
4747                              struct trace_event_file *file)
4748{
4749        int ret;
4750
4751        ret = parse_var_defs(hist_data);
4752        if (ret)
4753                goto out;
4754
4755        ret = create_val_fields(hist_data, file);
4756        if (ret)
4757                goto out;
4758
4759        ret = create_var_fields(hist_data, file);
4760        if (ret)
4761                goto out;
4762
4763        ret = create_key_fields(hist_data, file);
4764        if (ret)
4765                goto out;
4766 out:
4767        free_var_defs(hist_data);
4768
4769        return ret;
4770}
4771
4772static int is_descending(const char *str)
4773{
4774        if (!str)
4775                return 0;
4776
4777        if (strcmp(str, "descending") == 0)
4778                return 1;
4779
4780        if (strcmp(str, "ascending") == 0)
4781                return 0;
4782
4783        return -EINVAL;
4784}
4785
4786static int create_sort_keys(struct hist_trigger_data *hist_data)
4787{
4788        char *fields_str = hist_data->attrs->sort_key_str;
4789        struct tracing_map_sort_key *sort_key;
4790        int descending, ret = 0;
4791        unsigned int i, j, k;
4792
4793        hist_data->n_sort_keys = 1; /* we always have at least one, hitcount */
4794
4795        if (!fields_str)
4796                goto out;
4797
4798        strsep(&fields_str, "=");
4799        if (!fields_str) {
4800                ret = -EINVAL;
4801                goto out;
4802        }
4803
4804        for (i = 0; i < TRACING_MAP_SORT_KEYS_MAX; i++) {
4805                struct hist_field *hist_field;
4806                char *field_str, *field_name;
4807                const char *test_name;
4808
4809                sort_key = &hist_data->sort_keys[i];
4810
4811                field_str = strsep(&fields_str, ",");
4812                if (!field_str) {
4813                        if (i == 0)
4814                                ret = -EINVAL;
4815                        break;
4816                }
4817
4818                if ((i == TRACING_MAP_SORT_KEYS_MAX - 1) && fields_str) {
4819                        ret = -EINVAL;
4820                        break;
4821                }
4822
4823                field_name = strsep(&field_str, ".");
4824                if (!field_name) {
4825                        ret = -EINVAL;
4826                        break;
4827                }
4828
4829                if (strcmp(field_name, "hitcount") == 0) {
4830                        descending = is_descending(field_str);
4831                        if (descending < 0) {
4832                                ret = descending;
4833                                break;
4834                        }
4835                        sort_key->descending = descending;
4836                        continue;
4837                }
4838
4839                for (j = 1, k = 1; j < hist_data->n_fields; j++) {
4840                        unsigned int idx;
4841
4842                        hist_field = hist_data->fields[j];
4843                        if (hist_field->flags & HIST_FIELD_FL_VAR)
4844                                continue;
4845
4846                        idx = k++;
4847
4848                        test_name = hist_field_name(hist_field, 0);
4849
4850                        if (strcmp(field_name, test_name) == 0) {
4851                                sort_key->field_idx = idx;
4852                                descending = is_descending(field_str);
4853                                if (descending < 0) {
4854                                        ret = descending;
4855                                        goto out;
4856                                }
4857                                sort_key->descending = descending;
4858                                break;
4859                        }
4860                }
4861                if (j == hist_data->n_fields) {
4862                        ret = -EINVAL;
4863                        break;
4864                }
4865        }
4866
4867        hist_data->n_sort_keys = i;
4868 out:
4869        return ret;
4870}
4871
4872static void destroy_actions(struct hist_trigger_data *hist_data)
4873{
4874        unsigned int i;
4875
4876        for (i = 0; i < hist_data->n_actions; i++) {
4877                struct action_data *data = hist_data->actions[i];
4878
4879                if (data->handler == HANDLER_ONMATCH)
4880                        onmatch_destroy(data);
4881                else if (data->handler == HANDLER_ONMAX ||
4882                         data->handler == HANDLER_ONCHANGE)
4883                        track_data_destroy(hist_data, data);
4884                else
4885                        kfree(data);
4886        }
4887}
4888
4889static int parse_actions(struct hist_trigger_data *hist_data)
4890{
4891        struct trace_array *tr = hist_data->event_file->tr;
4892        struct action_data *data;
4893        unsigned int i;
4894        int ret = 0;
4895        char *str;
4896        int len;
4897
4898        for (i = 0; i < hist_data->attrs->n_actions; i++) {
4899                str = hist_data->attrs->action_str[i];
4900
4901                if ((len = str_has_prefix(str, "onmatch("))) {
4902                        char *action_str = str + len;
4903
4904                        data = onmatch_parse(tr, action_str);
4905                        if (IS_ERR(data)) {
4906                                ret = PTR_ERR(data);
4907                                break;
4908                        }
4909                } else if ((len = str_has_prefix(str, "onmax("))) {
4910                        char *action_str = str + len;
4911
4912                        data = track_data_parse(hist_data, action_str,
4913                                                HANDLER_ONMAX);
4914                        if (IS_ERR(data)) {
4915                                ret = PTR_ERR(data);
4916                                break;
4917                        }
4918                } else if ((len = str_has_prefix(str, "onchange("))) {
4919                        char *action_str = str + len;
4920
4921                        data = track_data_parse(hist_data, action_str,
4922                                                HANDLER_ONCHANGE);
4923                        if (IS_ERR(data)) {
4924                                ret = PTR_ERR(data);
4925                                break;
4926                        }
4927                } else {
4928                        ret = -EINVAL;
4929                        break;
4930                }
4931
4932                hist_data->actions[hist_data->n_actions++] = data;
4933        }
4934
4935        return ret;
4936}
4937
4938static int create_actions(struct hist_trigger_data *hist_data)
4939{
4940        struct action_data *data;
4941        unsigned int i;
4942        int ret = 0;
4943
4944        for (i = 0; i < hist_data->attrs->n_actions; i++) {
4945                data = hist_data->actions[i];
4946
4947                if (data->handler == HANDLER_ONMATCH) {
4948                        ret = onmatch_create(hist_data, data);
4949                        if (ret)
4950                                break;
4951                } else if (data->handler == HANDLER_ONMAX ||
4952                           data->handler == HANDLER_ONCHANGE) {
4953                        ret = track_data_create(hist_data, data);
4954                        if (ret)
4955                                break;
4956                } else {
4957                        ret = -EINVAL;
4958                        break;
4959                }
4960        }
4961
4962        return ret;
4963}
4964
4965static void print_actions(struct seq_file *m,
4966                          struct hist_trigger_data *hist_data,
4967                          struct tracing_map_elt *elt)
4968{
4969        unsigned int i;
4970
4971        for (i = 0; i < hist_data->n_actions; i++) {
4972                struct action_data *data = hist_data->actions[i];
4973
4974                if (data->action == ACTION_SNAPSHOT)
4975                        continue;
4976
4977                if (data->handler == HANDLER_ONMAX ||
4978                    data->handler == HANDLER_ONCHANGE)
4979                        track_data_print(m, hist_data, elt, data);
4980        }
4981}
4982
4983static void print_action_spec(struct seq_file *m,
4984                              struct hist_trigger_data *hist_data,
4985                              struct action_data *data)
4986{
4987        unsigned int i;
4988
4989        if (data->action == ACTION_SAVE) {
4990                for (i = 0; i < hist_data->n_save_vars; i++) {
4991                        seq_printf(m, "%s", hist_data->save_vars[i]->var->var.name);
4992                        if (i < hist_data->n_save_vars - 1)
4993                                seq_puts(m, ",");
4994                }
4995        } else if (data->action == ACTION_TRACE) {
4996                if (data->use_trace_keyword)
4997                        seq_printf(m, "%s", data->synth_event_name);
4998                for (i = 0; i < data->n_params; i++) {
4999                        if (i || data->use_trace_keyword)
5000                                seq_puts(m, ",");
5001                        seq_printf(m, "%s", data->params[i]);
5002                }
5003        }
5004}
5005
5006static void print_track_data_spec(struct seq_file *m,
5007                                  struct hist_trigger_data *hist_data,
5008                                  struct action_data *data)
5009{
5010        if (data->handler == HANDLER_ONMAX)
5011                seq_puts(m, ":onmax(");
5012        else if (data->handler == HANDLER_ONCHANGE)
5013                seq_puts(m, ":onchange(");
5014        seq_printf(m, "%s", data->track_data.var_str);
5015        seq_printf(m, ").%s(", data->action_name);
5016
5017        print_action_spec(m, hist_data, data);
5018
5019        seq_puts(m, ")");
5020}
5021
5022static void print_onmatch_spec(struct seq_file *m,
5023                               struct hist_trigger_data *hist_data,
5024                               struct action_data *data)
5025{
5026        seq_printf(m, ":onmatch(%s.%s).", data->match_data.event_system,
5027                   data->match_data.event);
5028
5029        seq_printf(m, "%s(", data->action_name);
5030
5031        print_action_spec(m, hist_data, data);
5032
5033        seq_puts(m, ")");
5034}
5035
5036static bool actions_match(struct hist_trigger_data *hist_data,
5037                          struct hist_trigger_data *hist_data_test)
5038{
5039        unsigned int i, j;
5040
5041        if (hist_data->n_actions != hist_data_test->n_actions)
5042                return false;
5043
5044        for (i = 0; i < hist_data->n_actions; i++) {
5045                struct action_data *data = hist_data->actions[i];
5046                struct action_data *data_test = hist_data_test->actions[i];
5047                char *action_name, *action_name_test;
5048
5049                if (data->handler != data_test->handler)
5050                        return false;
5051                if (data->action != data_test->action)
5052                        return false;
5053
5054                if (data->n_params != data_test->n_params)
5055                        return false;
5056
5057                for (j = 0; j < data->n_params; j++) {
5058                        if (strcmp(data->params[j], data_test->params[j]) != 0)
5059                                return false;
5060                }
5061
5062                if (data->use_trace_keyword)
5063                        action_name = data->synth_event_name;
5064                else
5065                        action_name = data->action_name;
5066
5067                if (data_test->use_trace_keyword)
5068                        action_name_test = data_test->synth_event_name;
5069                else
5070                        action_name_test = data_test->action_name;
5071
5072                if (strcmp(action_name, action_name_test) != 0)
5073                        return false;
5074
5075                if (data->handler == HANDLER_ONMATCH) {
5076                        if (strcmp(data->match_data.event_system,
5077                                   data_test->match_data.event_system) != 0)
5078                                return false;
5079                        if (strcmp(data->match_data.event,
5080                                   data_test->match_data.event) != 0)
5081                                return false;
5082                } else if (data->handler == HANDLER_ONMAX ||
5083                           data->handler == HANDLER_ONCHANGE) {
5084                        if (strcmp(data->track_data.var_str,
5085                                   data_test->track_data.var_str) != 0)
5086                                return false;
5087                }
5088        }
5089
5090        return true;
5091}
5092
5093
5094static void print_actions_spec(struct seq_file *m,
5095                               struct hist_trigger_data *hist_data)
5096{
5097        unsigned int i;
5098
5099        for (i = 0; i < hist_data->n_actions; i++) {
5100                struct action_data *data = hist_data->actions[i];
5101
5102                if (data->handler == HANDLER_ONMATCH)
5103                        print_onmatch_spec(m, hist_data, data);
5104                else if (data->handler == HANDLER_ONMAX ||
5105                         data->handler == HANDLER_ONCHANGE)
5106                        print_track_data_spec(m, hist_data, data);
5107        }
5108}
5109
5110static void destroy_field_var_hists(struct hist_trigger_data *hist_data)
5111{
5112        unsigned int i;
5113
5114        for (i = 0; i < hist_data->n_field_var_hists; i++) {
5115                kfree(hist_data->field_var_hists[i]->cmd);
5116                kfree(hist_data->field_var_hists[i]);
5117        }
5118}
5119
5120static void destroy_hist_data(struct hist_trigger_data *hist_data)
5121{
5122        if (!hist_data)
5123                return;
5124
5125        destroy_hist_trigger_attrs(hist_data->attrs);
5126        destroy_hist_fields(hist_data);
5127        tracing_map_destroy(hist_data->map);
5128
5129        destroy_actions(hist_data);
5130        destroy_field_vars(hist_data);
5131        destroy_field_var_hists(hist_data);
5132
5133        kfree(hist_data);
5134}
5135
5136static int create_tracing_map_fields(struct hist_trigger_data *hist_data)
5137{
5138        struct tracing_map *map = hist_data->map;
5139        struct ftrace_event_field *field;
5140        struct hist_field *hist_field;
5141        int i, idx = 0;
5142
5143        for_each_hist_field(i, hist_data) {
5144                hist_field = hist_data->fields[i];
5145                if (hist_field->flags & HIST_FIELD_FL_KEY) {
5146                        tracing_map_cmp_fn_t cmp_fn;
5147
5148                        field = hist_field->field;
5149
5150                        if (hist_field->flags & HIST_FIELD_FL_STACKTRACE)
5151                                cmp_fn = tracing_map_cmp_none;
5152                        else if (!field)
5153                                cmp_fn = tracing_map_cmp_num(hist_field->size,
5154                                                             hist_field->is_signed);
5155                        else if (is_string_field(field))
5156                                cmp_fn = tracing_map_cmp_string;
5157                        else
5158                                cmp_fn = tracing_map_cmp_num(field->size,
5159                                                             field->is_signed);
5160                        idx = tracing_map_add_key_field(map,
5161                                                        hist_field->offset,
5162                                                        cmp_fn);
5163                } else if (!(hist_field->flags & HIST_FIELD_FL_VAR))
5164                        idx = tracing_map_add_sum_field(map);
5165
5166                if (idx < 0)
5167                        return idx;
5168
5169                if (hist_field->flags & HIST_FIELD_FL_VAR) {
5170                        idx = tracing_map_add_var(map);
5171                        if (idx < 0)
5172                                return idx;
5173                        hist_field->var.idx = idx;
5174                        hist_field->var.hist_data = hist_data;
5175                }
5176        }
5177
5178        return 0;
5179}
5180
5181static struct hist_trigger_data *
5182create_hist_data(unsigned int map_bits,
5183                 struct hist_trigger_attrs *attrs,
5184                 struct trace_event_file *file,
5185                 bool remove)
5186{
5187        const struct tracing_map_ops *map_ops = NULL;
5188        struct hist_trigger_data *hist_data;
5189        int ret = 0;
5190
5191        hist_data = kzalloc(sizeof(*hist_data), GFP_KERNEL);
5192        if (!hist_data)
5193                return ERR_PTR(-ENOMEM);
5194
5195        hist_data->attrs = attrs;
5196        hist_data->remove = remove;
5197        hist_data->event_file = file;
5198
5199        ret = parse_actions(hist_data);
5200        if (ret)
5201                goto free;
5202
5203        ret = create_hist_fields(hist_data, file);
5204        if (ret)
5205                goto free;
5206
5207        ret = create_sort_keys(hist_data);
5208        if (ret)
5209                goto free;
5210
5211        map_ops = &hist_trigger_elt_data_ops;
5212
5213        hist_data->map = tracing_map_create(map_bits, hist_data->key_size,
5214                                            map_ops, hist_data);
5215        if (IS_ERR(hist_data->map)) {
5216                ret = PTR_ERR(hist_data->map);
5217                hist_data->map = NULL;
5218                goto free;
5219        }
5220
5221        ret = create_tracing_map_fields(hist_data);
5222        if (ret)
5223                goto free;
5224 out:
5225        return hist_data;
5226 free:
5227        hist_data->attrs = NULL;
5228
5229        destroy_hist_data(hist_data);
5230
5231        hist_data = ERR_PTR(ret);
5232
5233        goto out;
5234}
5235
5236static void hist_trigger_elt_update(struct hist_trigger_data *hist_data,
5237                                    struct tracing_map_elt *elt, void *rec,
5238                                    struct ring_buffer_event *rbe,
5239                                    u64 *var_ref_vals)
5240{
5241        struct hist_elt_data *elt_data;
5242        struct hist_field *hist_field;
5243        unsigned int i, var_idx;
5244        u64 hist_val;
5245
5246        elt_data = elt->private_data;
5247        elt_data->var_ref_vals = var_ref_vals;
5248
5249        for_each_hist_val_field(i, hist_data) {
5250                hist_field = hist_data->fields[i];
5251                hist_val = hist_field->fn(hist_field, elt, rbe, rec);
5252                if (hist_field->flags & HIST_FIELD_FL_VAR) {
5253                        var_idx = hist_field->var.idx;
5254                        tracing_map_set_var(elt, var_idx, hist_val);
5255                        continue;
5256                }
5257                tracing_map_update_sum(elt, i, hist_val);
5258        }
5259
5260        for_each_hist_key_field(i, hist_data) {
5261                hist_field = hist_data->fields[i];
5262                if (hist_field->flags & HIST_FIELD_FL_VAR) {
5263                        hist_val = hist_field->fn(hist_field, elt, rbe, rec);
5264                        var_idx = hist_field->var.idx;
5265                        tracing_map_set_var(elt, var_idx, hist_val);
5266                }
5267        }
5268
5269        update_field_vars(hist_data, elt, rbe, rec);
5270}
5271
5272static inline void add_to_key(char *compound_key, void *key,
5273                              struct hist_field *key_field, void *rec)
5274{
5275        size_t size = key_field->size;
5276
5277        if (key_field->flags & HIST_FIELD_FL_STRING) {
5278                struct ftrace_event_field *field;
5279
5280                field = key_field->field;
5281                if (field->filter_type == FILTER_DYN_STRING)
5282                        size = *(u32 *)(rec + field->offset) >> 16;
5283                else if (field->filter_type == FILTER_PTR_STRING)
5284                        size = strlen(key);
5285                else if (field->filter_type == FILTER_STATIC_STRING)
5286                        size = field->size;
5287
5288                /* ensure NULL-termination */
5289                if (size > key_field->size - 1)
5290                        size = key_field->size - 1;
5291
5292                strncpy(compound_key + key_field->offset, (char *)key, size);
5293        } else
5294                memcpy(compound_key + key_field->offset, key, size);
5295}
5296
5297static void
5298hist_trigger_actions(struct hist_trigger_data *hist_data,
5299                     struct tracing_map_elt *elt, void *rec,
5300                     struct ring_buffer_event *rbe, void *key,
5301                     u64 *var_ref_vals)
5302{
5303        struct action_data *data;
5304        unsigned int i;
5305
5306        for (i = 0; i < hist_data->n_actions; i++) {
5307                data = hist_data->actions[i];
5308                data->fn(hist_data, elt, rec, rbe, key, data, var_ref_vals);
5309        }
5310}
5311
5312static void event_hist_trigger(struct event_trigger_data *data, void *rec,
5313                               struct ring_buffer_event *rbe)
5314{
5315        struct hist_trigger_data *hist_data = data->private_data;
5316        bool use_compound_key = (hist_data->n_keys > 1);
5317        unsigned long entries[HIST_STACKTRACE_DEPTH];
5318        u64 var_ref_vals[TRACING_MAP_VARS_MAX];
5319        char compound_key[HIST_KEY_SIZE_MAX];
5320        struct tracing_map_elt *elt = NULL;
5321        struct hist_field *key_field;
5322        u64 field_contents;
5323        void *key = NULL;
5324        unsigned int i;
5325
5326        memset(compound_key, 0, hist_data->key_size);
5327
5328        for_each_hist_key_field(i, hist_data) {
5329                key_field = hist_data->fields[i];
5330
5331                if (key_field->flags & HIST_FIELD_FL_STACKTRACE) {
5332                        memset(entries, 0, HIST_STACKTRACE_SIZE);
5333                        stack_trace_save(entries, HIST_STACKTRACE_DEPTH,
5334                                         HIST_STACKTRACE_SKIP);
5335                        key = entries;
5336                } else {
5337                        field_contents = key_field->fn(key_field, elt, rbe, rec);
5338                        if (key_field->flags & HIST_FIELD_FL_STRING) {
5339                                key = (void *)(unsigned long)field_contents;
5340                                use_compound_key = true;
5341                        } else
5342                                key = (void *)&field_contents;
5343                }
5344
5345                if (use_compound_key)
5346                        add_to_key(compound_key, key, key_field, rec);
5347        }
5348
5349        if (use_compound_key)
5350                key = compound_key;
5351
5352        if (hist_data->n_var_refs &&
5353            !resolve_var_refs(hist_data, key, var_ref_vals, false))
5354                return;
5355
5356        elt = tracing_map_insert(hist_data->map, key);
5357        if (!elt)
5358                return;
5359
5360        hist_trigger_elt_update(hist_data, elt, rec, rbe, var_ref_vals);
5361
5362        if (resolve_var_refs(hist_data, key, var_ref_vals, true))
5363                hist_trigger_actions(hist_data, elt, rec, rbe, key, var_ref_vals);
5364}
5365
5366static void hist_trigger_stacktrace_print(struct seq_file *m,
5367                                          unsigned long *stacktrace_entries,
5368                                          unsigned int max_entries)
5369{
5370        char str[KSYM_SYMBOL_LEN];
5371        unsigned int spaces = 8;
5372        unsigned int i;
5373
5374        for (i = 0; i < max_entries; i++) {
5375                if (!stacktrace_entries[i])
5376                        return;
5377
5378                seq_printf(m, "%*c", 1 + spaces, ' ');
5379                sprint_symbol(str, stacktrace_entries[i]);
5380                seq_printf(m, "%s\n", str);
5381        }
5382}
5383
5384static void hist_trigger_print_key(struct seq_file *m,
5385                                   struct hist_trigger_data *hist_data,
5386                                   void *key,
5387                                   struct tracing_map_elt *elt)
5388{
5389        struct hist_field *key_field;
5390        char str[KSYM_SYMBOL_LEN];
5391        bool multiline = false;
5392        const char *field_name;
5393        unsigned int i;
5394        u64 uval;
5395
5396        seq_puts(m, "{ ");
5397
5398        for_each_hist_key_field(i, hist_data) {
5399                key_field = hist_data->fields[i];
5400
5401                if (i > hist_data->n_vals)
5402                        seq_puts(m, ", ");
5403
5404                field_name = hist_field_name(key_field, 0);
5405
5406                if (key_field->flags & HIST_FIELD_FL_HEX) {
5407                        uval = *(u64 *)(key + key_field->offset);
5408                        seq_printf(m, "%s: %llx", field_name, uval);
5409                } else if (key_field->flags & HIST_FIELD_FL_SYM) {
5410                        uval = *(u64 *)(key + key_field->offset);
5411                        sprint_symbol_no_offset(str, uval);
5412                        seq_printf(m, "%s: [%llx] %-45s", field_name,
5413                                   uval, str);
5414                } else if (key_field->flags & HIST_FIELD_FL_SYM_OFFSET) {
5415                        uval = *(u64 *)(key + key_field->offset);
5416                        sprint_symbol(str, uval);
5417                        seq_printf(m, "%s: [%llx] %-55s", field_name,
5418                                   uval, str);
5419                } else if (key_field->flags & HIST_FIELD_FL_EXECNAME) {
5420                        struct hist_elt_data *elt_data = elt->private_data;
5421                        char *comm;
5422
5423                        if (WARN_ON_ONCE(!elt_data))
5424                                return;
5425
5426                        comm = elt_data->comm;
5427
5428                        uval = *(u64 *)(key + key_field->offset);
5429                        seq_printf(m, "%s: %-16s[%10llu]", field_name,
5430                                   comm, uval);
5431                } else if (key_field->flags & HIST_FIELD_FL_SYSCALL) {
5432                        const char *syscall_name;
5433
5434                        uval = *(u64 *)(key + key_field->offset);
5435                        syscall_name = get_syscall_name(uval);
5436                        if (!syscall_name)
5437                                syscall_name = "unknown_syscall";
5438
5439                        seq_printf(m, "%s: %-30s[%3llu]", field_name,
5440                                   syscall_name, uval);
5441                } else if (key_field->flags & HIST_FIELD_FL_STACKTRACE) {
5442                        seq_puts(m, "stacktrace:\n");
5443                        hist_trigger_stacktrace_print(m,
5444                                                      key + key_field->offset,
5445                                                      HIST_STACKTRACE_DEPTH);
5446                        multiline = true;
5447                } else if (key_field->flags & HIST_FIELD_FL_LOG2) {
5448                        seq_printf(m, "%s: ~ 2^%-2llu", field_name,
5449                                   *(u64 *)(key + key_field->offset));
5450                } else if (key_field->flags & HIST_FIELD_FL_STRING) {
5451                        seq_printf(m, "%s: %-50s", field_name,
5452                                   (char *)(key + key_field->offset));
5453                } else {
5454                        uval = *(u64 *)(key + key_field->offset);
5455                        seq_printf(m, "%s: %10llu", field_name, uval);
5456                }
5457        }
5458
5459        if (!multiline)
5460                seq_puts(m, " ");
5461
5462        seq_puts(m, "}");
5463}
5464
5465static void hist_trigger_entry_print(struct seq_file *m,
5466                                     struct hist_trigger_data *hist_data,
5467                                     void *key,
5468                                     struct tracing_map_elt *elt)
5469{
5470        const char *field_name;
5471        unsigned int i;
5472
5473        hist_trigger_print_key(m, hist_data, key, elt);
5474
5475        seq_printf(m, " hitcount: %10llu",
5476                   tracing_map_read_sum(elt, HITCOUNT_IDX));
5477
5478        for (i = 1; i < hist_data->n_vals; i++) {
5479                field_name = hist_field_name(hist_data->fields[i], 0);
5480
5481                if (hist_data->fields[i]->flags & HIST_FIELD_FL_VAR ||
5482                    hist_data->fields[i]->flags & HIST_FIELD_FL_EXPR)
5483                        continue;
5484
5485                if (hist_data->fields[i]->flags & HIST_FIELD_FL_HEX) {
5486                        seq_printf(m, "  %s: %10llx", field_name,
5487                                   tracing_map_read_sum(elt, i));
5488                } else {
5489                        seq_printf(m, "  %s: %10llu", field_name,
5490                                   tracing_map_read_sum(elt, i));
5491                }
5492        }
5493
5494        print_actions(m, hist_data, elt);
5495
5496        seq_puts(m, "\n");
5497}
5498
5499static int print_entries(struct seq_file *m,
5500                         struct hist_trigger_data *hist_data)
5501{
5502        struct tracing_map_sort_entry **sort_entries = NULL;
5503        struct tracing_map *map = hist_data->map;
5504        int i, n_entries;
5505
5506        n_entries = tracing_map_sort_entries(map, hist_data->sort_keys,
5507                                             hist_data->n_sort_keys,
5508                                             &sort_entries);
5509        if (n_entries < 0)
5510                return n_entries;
5511
5512        for (i = 0; i < n_entries; i++)
5513                hist_trigger_entry_print(m, hist_data,
5514                                         sort_entries[i]->key,
5515                                         sort_entries[i]->elt);
5516
5517        tracing_map_destroy_sort_entries(sort_entries, n_entries);
5518
5519        return n_entries;
5520}
5521
5522static void hist_trigger_show(struct seq_file *m,
5523                              struct event_trigger_data *data, int n)
5524{
5525        struct hist_trigger_data *hist_data;
5526        int n_entries;
5527
5528        if (n > 0)
5529                seq_puts(m, "\n\n");
5530
5531        seq_puts(m, "# event histogram\n#\n# trigger info: ");
5532        data->ops->print(m, data->ops, data);
5533        seq_puts(m, "#\n\n");
5534
5535        hist_data = data->private_data;
5536        n_entries = print_entries(m, hist_data);
5537        if (n_entries < 0)
5538                n_entries = 0;
5539
5540        track_data_snapshot_print(m, hist_data);
5541
5542        seq_printf(m, "\nTotals:\n    Hits: %llu\n    Entries: %u\n    Dropped: %llu\n",
5543                   (u64)atomic64_read(&hist_data->map->hits),
5544                   n_entries, (u64)atomic64_read(&hist_data->map->drops));
5545}
5546
5547static int hist_show(struct seq_file *m, void *v)
5548{
5549        struct event_trigger_data *data;
5550        struct trace_event_file *event_file;
5551        int n = 0, ret = 0;
5552
5553        mutex_lock(&event_mutex);
5554
5555        event_file = event_file_data(m->private);
5556        if (unlikely(!event_file)) {
5557                ret = -ENODEV;
5558                goto out_unlock;
5559        }
5560
5561        list_for_each_entry(data, &event_file->triggers, list) {
5562                if (data->cmd_ops->trigger_type == ETT_EVENT_HIST)
5563                        hist_trigger_show(m, data, n++);
5564        }
5565
5566 out_unlock:
5567        mutex_unlock(&event_mutex);
5568
5569        return ret;
5570}
5571
5572static int event_hist_open(struct inode *inode, struct file *file)
5573{
5574        int ret;
5575
5576        ret = security_locked_down(LOCKDOWN_TRACEFS);
5577        if (ret)
5578                return ret;
5579
5580        return single_open(file, hist_show, file);
5581}
5582
5583const struct file_operations event_hist_fops = {
5584        .open = event_hist_open,
5585        .read = seq_read,
5586        .llseek = seq_lseek,
5587        .release = single_release,
5588};
5589
5590static void hist_field_print(struct seq_file *m, struct hist_field *hist_field)
5591{
5592        const char *field_name = hist_field_name(hist_field, 0);
5593
5594        if (hist_field->var.name)
5595                seq_printf(m, "%s=", hist_field->var.name);
5596
5597        if (hist_field->flags & HIST_FIELD_FL_CPU)
5598                seq_puts(m, "cpu");
5599        else if (field_name) {
5600                if (hist_field->flags & HIST_FIELD_FL_VAR_REF ||
5601                    hist_field->flags & HIST_FIELD_FL_ALIAS)
5602                        seq_putc(m, '$');
5603                seq_printf(m, "%s", field_name);
5604        } else if (hist_field->flags & HIST_FIELD_FL_TIMESTAMP)
5605                seq_puts(m, "common_timestamp");
5606
5607        if (hist_field->flags) {
5608                if (!(hist_field->flags & HIST_FIELD_FL_VAR_REF) &&
5609                    !(hist_field->flags & HIST_FIELD_FL_EXPR)) {
5610                        const char *flags = get_hist_field_flags(hist_field);
5611
5612                        if (flags)
5613                                seq_printf(m, ".%s", flags);
5614                }
5615        }
5616}
5617
5618static int event_hist_trigger_print(struct seq_file *m,
5619                                    struct event_trigger_ops *ops,
5620                                    struct event_trigger_data *data)
5621{
5622        struct hist_trigger_data *hist_data = data->private_data;
5623        struct hist_field *field;
5624        bool have_var = false;
5625        unsigned int i;
5626
5627        seq_puts(m, "hist:");
5628
5629        if (data->name)
5630                seq_printf(m, "%s:", data->name);
5631
5632        seq_puts(m, "keys=");
5633
5634        for_each_hist_key_field(i, hist_data) {
5635                field = hist_data->fields[i];
5636
5637                if (i > hist_data->n_vals)
5638                        seq_puts(m, ",");
5639
5640                if (field->flags & HIST_FIELD_FL_STACKTRACE)
5641                        seq_puts(m, "stacktrace");
5642                else
5643                        hist_field_print(m, field);
5644        }
5645
5646        seq_puts(m, ":vals=");
5647
5648        for_each_hist_val_field(i, hist_data) {
5649                field = hist_data->fields[i];
5650                if (field->flags & HIST_FIELD_FL_VAR) {
5651                        have_var = true;
5652                        continue;
5653                }
5654
5655                if (i == HITCOUNT_IDX)
5656                        seq_puts(m, "hitcount");
5657                else {
5658                        seq_puts(m, ",");
5659                        hist_field_print(m, field);
5660                }
5661        }
5662
5663        if (have_var) {
5664                unsigned int n = 0;
5665
5666                seq_puts(m, ":");
5667
5668                for_each_hist_val_field(i, hist_data) {
5669                        field = hist_data->fields[i];
5670
5671                        if (field->flags & HIST_FIELD_FL_VAR) {
5672                                if (n++)
5673                                        seq_puts(m, ",");
5674                                hist_field_print(m, field);
5675                        }
5676                }
5677        }
5678
5679        seq_puts(m, ":sort=");
5680
5681        for (i = 0; i < hist_data->n_sort_keys; i++) {
5682                struct tracing_map_sort_key *sort_key;
5683                unsigned int idx, first_key_idx;
5684
5685                /* skip VAR vals */
5686                first_key_idx = hist_data->n_vals - hist_data->n_vars;
5687
5688                sort_key = &hist_data->sort_keys[i];
5689                idx = sort_key->field_idx;
5690
5691                if (WARN_ON(idx >= HIST_FIELDS_MAX))
5692                        return -EINVAL;
5693
5694                if (i > 0)
5695                        seq_puts(m, ",");
5696
5697                if (idx == HITCOUNT_IDX)
5698                        seq_puts(m, "hitcount");
5699                else {
5700                        if (idx >= first_key_idx)
5701                                idx += hist_data->n_vars;
5702                        hist_field_print(m, hist_data->fields[idx]);
5703                }
5704
5705                if (sort_key->descending)
5706                        seq_puts(m, ".descending");
5707        }
5708        seq_printf(m, ":size=%u", (1 << hist_data->map->map_bits));
5709        if (hist_data->enable_timestamps)
5710                seq_printf(m, ":clock=%s", hist_data->attrs->clock);
5711
5712        print_actions_spec(m, hist_data);
5713
5714        if (data->filter_str)
5715                seq_printf(m, " if %s", data->filter_str);
5716
5717        if (data->paused)
5718                seq_puts(m, " [paused]");
5719        else
5720                seq_puts(m, " [active]");
5721
5722        seq_putc(m, '\n');
5723
5724        return 0;
5725}
5726
5727static int event_hist_trigger_init(struct event_trigger_ops *ops,
5728                                   struct event_trigger_data *data)
5729{
5730        struct hist_trigger_data *hist_data = data->private_data;
5731
5732        if (!data->ref && hist_data->attrs->name)
5733                save_named_trigger(hist_data->attrs->name, data);
5734
5735        data->ref++;
5736
5737        return 0;
5738}
5739
5740static void unregister_field_var_hists(struct hist_trigger_data *hist_data)
5741{
5742        struct trace_event_file *file;
5743        unsigned int i;
5744        char *cmd;
5745        int ret;
5746
5747        for (i = 0; i < hist_data->n_field_var_hists; i++) {
5748                file = hist_data->field_var_hists[i]->hist_data->event_file;
5749                cmd = hist_data->field_var_hists[i]->cmd;
5750                ret = event_hist_trigger_func(&trigger_hist_cmd, file,
5751                                              "!hist", "hist", cmd);
5752        }
5753}
5754
5755static void event_hist_trigger_free(struct event_trigger_ops *ops,
5756                                    struct event_trigger_data *data)
5757{
5758        struct hist_trigger_data *hist_data = data->private_data;
5759
5760        if (WARN_ON_ONCE(data->ref <= 0))
5761                return;
5762
5763        data->ref--;
5764        if (!data->ref) {
5765                if (data->name)
5766                        del_named_trigger(data);
5767
5768                trigger_data_free(data);
5769
5770                remove_hist_vars(hist_data);
5771
5772                unregister_field_var_hists(hist_data);
5773
5774                destroy_hist_data(hist_data);
5775        }
5776}
5777
5778static struct event_trigger_ops event_hist_trigger_ops = {
5779        .func                   = event_hist_trigger,
5780        .print                  = event_hist_trigger_print,
5781        .init                   = event_hist_trigger_init,
5782        .free                   = event_hist_trigger_free,
5783};
5784
5785static int event_hist_trigger_named_init(struct event_trigger_ops *ops,
5786                                         struct event_trigger_data *data)
5787{
5788        data->ref++;
5789
5790        save_named_trigger(data->named_data->name, data);
5791
5792        event_hist_trigger_init(ops, data->named_data);
5793
5794        return 0;
5795}
5796
5797static void event_hist_trigger_named_free(struct event_trigger_ops *ops,
5798                                          struct event_trigger_data *data)
5799{
5800        if (WARN_ON_ONCE(data->ref <= 0))
5801                return;
5802
5803        event_hist_trigger_free(ops, data->named_data);
5804
5805        data->ref--;
5806        if (!data->ref) {
5807                del_named_trigger(data);
5808                trigger_data_free(data);
5809        }
5810}
5811
5812static struct event_trigger_ops event_hist_trigger_named_ops = {
5813        .func                   = event_hist_trigger,
5814        .print                  = event_hist_trigger_print,
5815        .init                   = event_hist_trigger_named_init,
5816        .free                   = event_hist_trigger_named_free,
5817};
5818
5819static struct event_trigger_ops *event_hist_get_trigger_ops(char *cmd,
5820                                                            char *param)
5821{
5822        return &event_hist_trigger_ops;
5823}
5824
5825static void hist_clear(struct event_trigger_data *data)
5826{
5827        struct hist_trigger_data *hist_data = data->private_data;
5828
5829        if (data->name)
5830                pause_named_trigger(data);
5831
5832        tracepoint_synchronize_unregister();
5833
5834        tracing_map_clear(hist_data->map);
5835
5836        if (data->name)
5837                unpause_named_trigger(data);
5838}
5839
5840static bool compatible_field(struct ftrace_event_field *field,
5841                             struct ftrace_event_field *test_field)
5842{
5843        if (field == test_field)
5844                return true;
5845        if (field == NULL || test_field == NULL)
5846                return false;
5847        if (strcmp(field->name, test_field->name) != 0)
5848                return false;
5849        if (strcmp(field->type, test_field->type) != 0)
5850                return false;
5851        if (field->size != test_field->size)
5852                return false;
5853        if (field->is_signed != test_field->is_signed)
5854                return false;
5855
5856        return true;
5857}
5858
5859static bool hist_trigger_match(struct event_trigger_data *data,
5860                               struct event_trigger_data *data_test,
5861                               struct event_trigger_data *named_data,
5862                               bool ignore_filter)
5863{
5864        struct tracing_map_sort_key *sort_key, *sort_key_test;
5865        struct hist_trigger_data *hist_data, *hist_data_test;
5866        struct hist_field *key_field, *key_field_test;
5867        unsigned int i;
5868
5869        if (named_data && (named_data != data_test) &&
5870            (named_data != data_test->named_data))
5871                return false;
5872
5873        if (!named_data && is_named_trigger(data_test))
5874                return false;
5875
5876        hist_data = data->private_data;
5877        hist_data_test = data_test->private_data;
5878
5879        if (hist_data->n_vals != hist_data_test->n_vals ||
5880            hist_data->n_fields != hist_data_test->n_fields ||
5881            hist_data->n_sort_keys != hist_data_test->n_sort_keys)
5882                return false;
5883
5884        if (!ignore_filter) {
5885                if ((data->filter_str && !data_test->filter_str) ||
5886                   (!data->filter_str && data_test->filter_str))
5887                        return false;
5888        }
5889
5890        for_each_hist_field(i, hist_data) {
5891                key_field = hist_data->fields[i];
5892                key_field_test = hist_data_test->fields[i];
5893
5894                if (key_field->flags != key_field_test->flags)
5895                        return false;
5896                if (!compatible_field(key_field->field, key_field_test->field))
5897                        return false;
5898                if (key_field->offset != key_field_test->offset)
5899                        return false;
5900                if (key_field->size != key_field_test->size)
5901                        return false;
5902                if (key_field->is_signed != key_field_test->is_signed)
5903                        return false;
5904                if (!!key_field->var.name != !!key_field_test->var.name)
5905                        return false;
5906                if (key_field->var.name &&
5907                    strcmp(key_field->var.name, key_field_test->var.name) != 0)
5908                        return false;
5909        }
5910
5911        for (i = 0; i < hist_data->n_sort_keys; i++) {
5912                sort_key = &hist_data->sort_keys[i];
5913                sort_key_test = &hist_data_test->sort_keys[i];
5914
5915                if (sort_key->field_idx != sort_key_test->field_idx ||
5916                    sort_key->descending != sort_key_test->descending)
5917                        return false;
5918        }
5919
5920        if (!ignore_filter && data->filter_str &&
5921            (strcmp(data->filter_str, data_test->filter_str) != 0))
5922                return false;
5923
5924        if (!actions_match(hist_data, hist_data_test))
5925                return false;
5926
5927        return true;
5928}
5929
5930static int hist_register_trigger(char *glob, struct event_trigger_ops *ops,
5931                                 struct event_trigger_data *data,
5932                                 struct trace_event_file *file)
5933{
5934        struct hist_trigger_data *hist_data = data->private_data;
5935        struct event_trigger_data *test, *named_data = NULL;
5936        struct trace_array *tr = file->tr;
5937        int ret = 0;
5938
5939        if (hist_data->attrs->name) {
5940                named_data = find_named_trigger(hist_data->attrs->name);
5941                if (named_data) {
5942                        if (!hist_trigger_match(data, named_data, named_data,
5943                                                true)) {
5944                                hist_err(tr, HIST_ERR_NAMED_MISMATCH, errpos(hist_data->attrs->name));
5945                                ret = -EINVAL;
5946                                goto out;
5947                        }
5948                }
5949        }
5950
5951        if (hist_data->attrs->name && !named_data)
5952                goto new;
5953
5954        lockdep_assert_held(&event_mutex);
5955
5956        list_for_each_entry(test, &file->triggers, list) {
5957                if (test->cmd_ops->trigger_type == ETT_EVENT_HIST) {
5958                        if (!hist_trigger_match(data, test, named_data, false))
5959                                continue;
5960                        if (hist_data->attrs->pause)
5961                                test->paused = true;
5962                        else if (hist_data->attrs->cont)
5963                                test->paused = false;
5964                        else if (hist_data->attrs->clear)
5965                                hist_clear(test);
5966                        else {
5967                                hist_err(tr, HIST_ERR_TRIGGER_EEXIST, 0);
5968                                ret = -EEXIST;
5969                        }
5970                        goto out;
5971                }
5972        }
5973 new:
5974        if (hist_data->attrs->cont || hist_data->attrs->clear) {
5975                hist_err(tr, HIST_ERR_TRIGGER_ENOENT_CLEAR, 0);
5976                ret = -ENOENT;
5977                goto out;
5978        }
5979
5980        if (hist_data->attrs->pause)
5981                data->paused = true;
5982
5983        if (named_data) {
5984                data->private_data = named_data->private_data;
5985                set_named_trigger_data(data, named_data);
5986                data->ops = &event_hist_trigger_named_ops;
5987        }
5988
5989        if (data->ops->init) {
5990                ret = data->ops->init(data->ops, data);
5991                if (ret < 0)
5992                        goto out;
5993        }
5994
5995        if (hist_data->enable_timestamps) {
5996                char *clock = hist_data->attrs->clock;
5997
5998                ret = tracing_set_clock(file->tr, hist_data->attrs->clock);
5999                if (ret) {
6000                        hist_err(tr, HIST_ERR_SET_CLOCK_FAIL, errpos(clock));
6001                        goto out;
6002                }
6003
6004                tracing_set_time_stamp_abs(file->tr, true);
6005        }
6006
6007        if (named_data)
6008                destroy_hist_data(hist_data);
6009
6010        ret++;
6011 out:
6012        return ret;
6013}
6014
6015static int hist_trigger_enable(struct event_trigger_data *data,
6016                               struct trace_event_file *file)
6017{
6018        int ret = 0;
6019
6020        list_add_tail_rcu(&data->list, &file->triggers);
6021
6022        update_cond_flag(file);
6023
6024        if (trace_event_trigger_enable_disable(file, 1) < 0) {
6025                list_del_rcu(&data->list);
6026                update_cond_flag(file);
6027                ret--;
6028        }
6029
6030        return ret;
6031}
6032
6033static bool have_hist_trigger_match(struct event_trigger_data *data,
6034                                    struct trace_event_file *file)
6035{
6036        struct hist_trigger_data *hist_data = data->private_data;
6037        struct event_trigger_data *test, *named_data = NULL;
6038        bool match = false;
6039
6040        lockdep_assert_held(&event_mutex);
6041
6042        if (hist_data->attrs->name)
6043                named_data = find_named_trigger(hist_data->attrs->name);
6044
6045        list_for_each_entry(test, &file->triggers, list) {
6046                if (test->cmd_ops->trigger_type == ETT_EVENT_HIST) {
6047                        if (hist_trigger_match(data, test, named_data, false)) {
6048                                match = true;
6049                                break;
6050                        }
6051                }
6052        }
6053
6054        return match;
6055}
6056
6057static bool hist_trigger_check_refs(struct event_trigger_data *data,
6058                                    struct trace_event_file *file)
6059{
6060        struct hist_trigger_data *hist_data = data->private_data;
6061        struct event_trigger_data *test, *named_data = NULL;
6062
6063        lockdep_assert_held(&event_mutex);
6064
6065        if (hist_data->attrs->name)
6066                named_data = find_named_trigger(hist_data->attrs->name);
6067
6068        list_for_each_entry(test, &file->triggers, list) {
6069                if (test->cmd_ops->trigger_type == ETT_EVENT_HIST) {
6070                        if (!hist_trigger_match(data, test, named_data, false))
6071                                continue;
6072                        hist_data = test->private_data;
6073                        if (check_var_refs(hist_data))
6074                                return true;
6075                        break;
6076                }
6077        }
6078
6079        return false;
6080}
6081
6082static void hist_unregister_trigger(char *glob, struct event_trigger_ops *ops,
6083                                    struct event_trigger_data *data,
6084                                    struct trace_event_file *file)
6085{
6086        struct hist_trigger_data *hist_data = data->private_data;
6087        struct event_trigger_data *test, *named_data = NULL;
6088        bool unregistered = false;
6089
6090        lockdep_assert_held(&event_mutex);
6091
6092        if (hist_data->attrs->name)
6093                named_data = find_named_trigger(hist_data->attrs->name);
6094
6095        list_for_each_entry(test, &file->triggers, list) {
6096                if (test->cmd_ops->trigger_type == ETT_EVENT_HIST) {
6097                        if (!hist_trigger_match(data, test, named_data, false))
6098                                continue;
6099                        unregistered = true;
6100                        list_del_rcu(&test->list);
6101                        trace_event_trigger_enable_disable(file, 0);
6102                        update_cond_flag(file);
6103                        break;
6104                }
6105        }
6106
6107        if (unregistered && test->ops->free)
6108                test->ops->free(test->ops, test);
6109
6110        if (hist_data->enable_timestamps) {
6111                if (!hist_data->remove || unregistered)
6112                        tracing_set_time_stamp_abs(file->tr, false);
6113        }
6114}
6115
6116static bool hist_file_check_refs(struct trace_event_file *file)
6117{
6118        struct hist_trigger_data *hist_data;
6119        struct event_trigger_data *test;
6120
6121        lockdep_assert_held(&event_mutex);
6122
6123        list_for_each_entry(test, &file->triggers, list) {
6124                if (test->cmd_ops->trigger_type == ETT_EVENT_HIST) {
6125                        hist_data = test->private_data;
6126                        if (check_var_refs(hist_data))
6127                                return true;
6128                }
6129        }
6130
6131        return false;
6132}
6133
6134static void hist_unreg_all(struct trace_event_file *file)
6135{
6136        struct event_trigger_data *test, *n;
6137        struct hist_trigger_data *hist_data;
6138        struct synth_event *se;
6139        const char *se_name;
6140
6141        lockdep_assert_held(&event_mutex);
6142
6143        if (hist_file_check_refs(file))
6144                return;
6145
6146        list_for_each_entry_safe(test, n, &file->triggers, list) {
6147                if (test->cmd_ops->trigger_type == ETT_EVENT_HIST) {
6148                        hist_data = test->private_data;
6149                        list_del_rcu(&test->list);
6150                        trace_event_trigger_enable_disable(file, 0);
6151
6152                        se_name = trace_event_name(file->event_call);
6153                        se = find_synth_event(se_name);
6154                        if (se)
6155                                se->ref--;
6156
6157                        update_cond_flag(file);
6158                        if (hist_data->enable_timestamps)
6159                                tracing_set_time_stamp_abs(file->tr, false);
6160                        if (test->ops->free)
6161                                test->ops->free(test->ops, test);
6162                }
6163        }
6164}
6165
6166static int event_hist_trigger_func(struct event_command *cmd_ops,
6167                                   struct trace_event_file *file,
6168                                   char *glob, char *cmd, char *param)
6169{
6170        unsigned int hist_trigger_bits = TRACING_MAP_BITS_DEFAULT;
6171        struct event_trigger_data *trigger_data;
6172        struct hist_trigger_attrs *attrs;
6173        struct event_trigger_ops *trigger_ops;
6174        struct hist_trigger_data *hist_data;
6175        struct synth_event *se;
6176        const char *se_name;
6177        bool remove = false;
6178        char *trigger, *p;
6179        int ret = 0;
6180
6181        lockdep_assert_held(&event_mutex);
6182
6183        if (glob && strlen(glob)) {
6184                hist_err_clear();
6185                last_cmd_set(file, param);
6186        }
6187
6188        if (!param)
6189                return -EINVAL;
6190
6191        if (glob[0] == '!')
6192                remove = true;
6193
6194        /*
6195         * separate the trigger from the filter (k:v [if filter])
6196         * allowing for whitespace in the trigger
6197         */
6198        p = trigger = param;
6199        do {
6200                p = strstr(p, "if");
6201                if (!p)
6202                        break;
6203                if (p == param)
6204                        return -EINVAL;
6205                if (*(p - 1) != ' ' && *(p - 1) != '\t') {
6206                        p++;
6207                        continue;
6208                }
6209                if (p >= param + strlen(param) - (sizeof("if") - 1) - 1)
6210                        return -EINVAL;
6211                if (*(p + sizeof("if") - 1) != ' ' && *(p + sizeof("if") - 1) != '\t') {
6212                        p++;
6213                        continue;
6214                }
6215                break;
6216        } while (p);
6217
6218        if (!p)
6219                param = NULL;
6220        else {
6221                *(p - 1) = '\0';
6222                param = strstrip(p);
6223                trigger = strstrip(trigger);
6224        }
6225
6226        attrs = parse_hist_trigger_attrs(file->tr, trigger);
6227        if (IS_ERR(attrs))
6228                return PTR_ERR(attrs);
6229
6230        if (attrs->map_bits)
6231                hist_trigger_bits = attrs->map_bits;
6232
6233        hist_data = create_hist_data(hist_trigger_bits, attrs, file, remove);
6234        if (IS_ERR(hist_data)) {
6235                destroy_hist_trigger_attrs(attrs);
6236                return PTR_ERR(hist_data);
6237        }
6238
6239        trigger_ops = cmd_ops->get_trigger_ops(cmd, trigger);
6240
6241        trigger_data = kzalloc(sizeof(*trigger_data), GFP_KERNEL);
6242        if (!trigger_data) {
6243                ret = -ENOMEM;
6244                goto out_free;
6245        }
6246
6247        trigger_data->count = -1;
6248        trigger_data->ops = trigger_ops;
6249        trigger_data->cmd_ops = cmd_ops;
6250
6251        INIT_LIST_HEAD(&trigger_data->list);
6252        RCU_INIT_POINTER(trigger_data->filter, NULL);
6253
6254        trigger_data->private_data = hist_data;
6255
6256        /* if param is non-empty, it's supposed to be a filter */
6257        if (param && cmd_ops->set_filter) {
6258                ret = cmd_ops->set_filter(param, trigger_data, file);
6259                if (ret < 0)
6260                        goto out_free;
6261        }
6262
6263        if (remove) {
6264                if (!have_hist_trigger_match(trigger_data, file))
6265                        goto out_free;
6266
6267                if (hist_trigger_check_refs(trigger_data, file)) {
6268                        ret = -EBUSY;
6269                        goto out_free;
6270                }
6271
6272                cmd_ops->unreg(glob+1, trigger_ops, trigger_data, file);
6273                se_name = trace_event_name(file->event_call);
6274                se = find_synth_event(se_name);
6275                if (se)
6276                        se->ref--;
6277                ret = 0;
6278                goto out_free;
6279        }
6280
6281        ret = cmd_ops->reg(glob, trigger_ops, trigger_data, file);
6282        /*
6283         * The above returns on success the # of triggers registered,
6284         * but if it didn't register any it returns zero.  Consider no
6285         * triggers registered a failure too.
6286         */
6287        if (!ret) {
6288                if (!(attrs->pause || attrs->cont || attrs->clear))
6289                        ret = -ENOENT;
6290                goto out_free;
6291        } else if (ret < 0)
6292                goto out_free;
6293
6294        if (get_named_trigger_data(trigger_data))
6295                goto enable;
6296
6297        if (has_hist_vars(hist_data))
6298                save_hist_vars(hist_data);
6299
6300        ret = create_actions(hist_data);
6301        if (ret)
6302                goto out_unreg;
6303
6304        ret = tracing_map_init(hist_data->map);
6305        if (ret)
6306                goto out_unreg;
6307enable:
6308        ret = hist_trigger_enable(trigger_data, file);
6309        if (ret)
6310                goto out_unreg;
6311
6312        se_name = trace_event_name(file->event_call);
6313        se = find_synth_event(se_name);
6314        if (se)
6315                se->ref++;
6316        /* Just return zero, not the number of registered triggers */
6317        ret = 0;
6318 out:
6319        if (ret == 0)
6320                hist_err_clear();
6321
6322        return ret;
6323 out_unreg:
6324        cmd_ops->unreg(glob+1, trigger_ops, trigger_data, file);
6325 out_free:
6326        if (cmd_ops->set_filter)
6327                cmd_ops->set_filter(NULL, trigger_data, NULL);
6328
6329        remove_hist_vars(hist_data);
6330
6331        kfree(trigger_data);
6332
6333        destroy_hist_data(hist_data);
6334        goto out;
6335}
6336
6337static struct event_command trigger_hist_cmd = {
6338        .name                   = "hist",
6339        .trigger_type           = ETT_EVENT_HIST,
6340        .flags                  = EVENT_CMD_FL_NEEDS_REC,
6341        .func                   = event_hist_trigger_func,
6342        .reg                    = hist_register_trigger,
6343        .unreg                  = hist_unregister_trigger,
6344        .unreg_all              = hist_unreg_all,
6345        .get_trigger_ops        = event_hist_get_trigger_ops,
6346        .set_filter             = set_trigger_filter,
6347};
6348
6349__init int register_trigger_hist_cmd(void)
6350{
6351        int ret;
6352
6353        ret = register_event_command(&trigger_hist_cmd);
6354        WARN_ON(ret < 0);
6355
6356        return ret;
6357}
6358
6359static void
6360hist_enable_trigger(struct event_trigger_data *data, void *rec,
6361                    struct ring_buffer_event *event)
6362{
6363        struct enable_trigger_data *enable_data = data->private_data;
6364        struct event_trigger_data *test;
6365
6366        list_for_each_entry_rcu(test, &enable_data->file->triggers, list,
6367                                lockdep_is_held(&event_mutex)) {
6368                if (test->cmd_ops->trigger_type == ETT_EVENT_HIST) {
6369                        if (enable_data->enable)
6370                                test->paused = false;
6371                        else
6372                                test->paused = true;
6373                }
6374        }
6375}
6376
6377static void
6378hist_enable_count_trigger(struct event_trigger_data *data, void *rec,
6379                          struct ring_buffer_event *event)
6380{
6381        if (!data->count)
6382                return;
6383
6384        if (data->count != -1)
6385                (data->count)--;
6386
6387        hist_enable_trigger(data, rec, event);
6388}
6389
6390static struct event_trigger_ops hist_enable_trigger_ops = {
6391        .func                   = hist_enable_trigger,
6392        .print                  = event_enable_trigger_print,
6393        .init                   = event_trigger_init,
6394        .free                   = event_enable_trigger_free,
6395};
6396
6397static struct event_trigger_ops hist_enable_count_trigger_ops = {
6398        .func                   = hist_enable_count_trigger,
6399        .print                  = event_enable_trigger_print,
6400        .init                   = event_trigger_init,
6401        .free                   = event_enable_trigger_free,
6402};
6403
6404static struct event_trigger_ops hist_disable_trigger_ops = {
6405        .func                   = hist_enable_trigger,
6406        .print                  = event_enable_trigger_print,
6407        .init                   = event_trigger_init,
6408        .free                   = event_enable_trigger_free,
6409};
6410
6411static struct event_trigger_ops hist_disable_count_trigger_ops = {
6412        .func                   = hist_enable_count_trigger,
6413        .print                  = event_enable_trigger_print,
6414        .init                   = event_trigger_init,
6415        .free                   = event_enable_trigger_free,
6416};
6417
6418static struct event_trigger_ops *
6419hist_enable_get_trigger_ops(char *cmd, char *param)
6420{
6421        struct event_trigger_ops *ops;
6422        bool enable;
6423
6424        enable = (strcmp(cmd, ENABLE_HIST_STR) == 0);
6425
6426        if (enable)
6427                ops = param ? &hist_enable_count_trigger_ops :
6428                        &hist_enable_trigger_ops;
6429        else
6430                ops = param ? &hist_disable_count_trigger_ops :
6431                        &hist_disable_trigger_ops;
6432
6433        return ops;
6434}
6435
6436static void hist_enable_unreg_all(struct trace_event_file *file)
6437{
6438        struct event_trigger_data *test, *n;
6439
6440        list_for_each_entry_safe(test, n, &file->triggers, list) {
6441                if (test->cmd_ops->trigger_type == ETT_HIST_ENABLE) {
6442                        list_del_rcu(&test->list);
6443                        update_cond_flag(file);
6444                        trace_event_trigger_enable_disable(file, 0);
6445                        if (test->ops->free)
6446                                test->ops->free(test->ops, test);
6447                }
6448        }
6449}
6450
6451static struct event_command trigger_hist_enable_cmd = {
6452        .name                   = ENABLE_HIST_STR,
6453        .trigger_type           = ETT_HIST_ENABLE,
6454        .func                   = event_enable_trigger_func,
6455        .reg                    = event_enable_register_trigger,
6456        .unreg                  = event_enable_unregister_trigger,
6457        .unreg_all              = hist_enable_unreg_all,
6458        .get_trigger_ops        = hist_enable_get_trigger_ops,
6459        .set_filter             = set_trigger_filter,
6460};
6461
6462static struct event_command trigger_hist_disable_cmd = {
6463        .name                   = DISABLE_HIST_STR,
6464        .trigger_type           = ETT_HIST_ENABLE,
6465        .func                   = event_enable_trigger_func,
6466        .reg                    = event_enable_register_trigger,
6467        .unreg                  = event_enable_unregister_trigger,
6468        .unreg_all              = hist_enable_unreg_all,
6469        .get_trigger_ops        = hist_enable_get_trigger_ops,
6470        .set_filter             = set_trigger_filter,
6471};
6472
6473static __init void unregister_trigger_hist_enable_disable_cmds(void)
6474{
6475        unregister_event_command(&trigger_hist_enable_cmd);
6476        unregister_event_command(&trigger_hist_disable_cmd);
6477}
6478
6479__init int register_trigger_hist_enable_disable_cmds(void)
6480{
6481        int ret;
6482
6483        ret = register_event_command(&trigger_hist_enable_cmd);
6484        if (WARN_ON(ret < 0))
6485                return ret;
6486        ret = register_event_command(&trigger_hist_disable_cmd);
6487        if (WARN_ON(ret < 0))
6488                unregister_trigger_hist_enable_disable_cmds();
6489
6490        return ret;
6491}
6492
6493static __init int trace_events_hist_init(void)
6494{
6495        struct dentry *entry = NULL;
6496        struct dentry *d_tracer;
6497        int err = 0;
6498
6499        err = dyn_event_register(&synth_event_ops);
6500        if (err) {
6501                pr_warn("Could not register synth_event_ops\n");
6502                return err;
6503        }
6504
6505        d_tracer = tracing_init_dentry();
6506        if (IS_ERR(d_tracer)) {
6507                err = PTR_ERR(d_tracer);
6508                goto err;
6509        }
6510
6511        entry = tracefs_create_file("synthetic_events", 0644, d_tracer,
6512                                    NULL, &synth_events_fops);
6513        if (!entry) {
6514                err = -ENODEV;
6515                goto err;
6516        }
6517
6518        return err;
6519 err:
6520        pr_warn("Could not create tracefs 'synthetic_events' entry\n");
6521
6522        return err;
6523}
6524
6525fs_initcall(trace_events_hist_init);
6526